From 12c37655d62ae93fcda77afe610e494936d46eb4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 13:20:14 -0600 Subject: [PATCH 01/26] feat(credential-groups): people status chips, send reminder, integrations header cleanup - People: one status badge per person (Revoked > Email failed > Needs reconnect > Connected > Expired > Invited); needs-reconnect connections shown distinctly instead of being filtered out - Row menu: Resend -> Send reminder, hidden once the enrollment is completed - Remove uncalled props (searchConnection, panel, filters, setupFallback, requestDisabled, enabled, visibleProviders) and the 'Revoke all account access' variant - Integrations: drop the persistent help text; 'Update configurations' becomes a header overflow 'Re-apply app configuration' with a confirm modal; provider -> integration in catalog and toast/remove copy - Invitation email: org groups read '{Org}', not '{Org} workspace' (explicit ownerKind) - README: current tab and action names --- .../credential-group-invitation-email.tsx | 15 +- .../emails/credential-groups/render.ts | 1 + .../organization-account-invite-modal.tsx | 13 +- .../organization-account-people.tsx | 307 +++++++++--------- .../organization-account-provider-catalog.tsx | 16 +- .../organization-account-providers.test.tsx | 17 +- .../organization-account-providers.tsx | 85 +++-- .../organization-person-connections.tsx | 30 +- apps/sim/lib/credential-groups/README.md | 8 +- apps/sim/lib/credential-groups/enrollments.ts | 1 + 10 files changed, 274 insertions(+), 219 deletions(-) diff --git a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx index 0c00470109f..ab41f97c527 100644 --- a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx +++ b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx @@ -6,7 +6,10 @@ interface CredentialGroupInvitationEmailProps { recipientEmail: string /** Absent when a workflow issued the invitation: there is no person to name. */ inviterName?: string + /** The organization or workspace name, per {@link ownerKind}. */ workspaceName: string + /** Whether the Credential Group belongs to an organization or a single workspace. */ + ownerKind: 'organization' | 'workspace' credentialGroupName: string invitationLink: string searchProviderName?: string @@ -16,6 +19,7 @@ export function CredentialGroupInvitationEmail({ recipientEmail, inviterName, workspaceName, + ownerKind, credentialGroupName, invitationLink, searchProviderName, @@ -47,8 +51,15 @@ export function CredentialGroupInvitationEmail({ ) : ( <> - to connect accounts for {credentialGroupName} in the{' '} - {workspaceName} workspace on Sim. + to connect accounts for {credentialGroupName} in{' '} + {ownerKind === 'workspace' ? ( + <> + the {workspaceName} workspace + + ) : ( + {workspaceName} + )}{' '} + on Sim. )} diff --git a/apps/sim/components/emails/credential-groups/render.ts b/apps/sim/components/emails/credential-groups/render.ts index b4f13f238bd..f9473e2ab0b 100644 --- a/apps/sim/components/emails/credential-groups/render.ts +++ b/apps/sim/components/emails/credential-groups/render.ts @@ -5,6 +5,7 @@ export async function renderCredentialGroupInvitationEmail(params: { recipientEmail: string inviterName?: string workspaceName: string + ownerKind: 'organization' | 'workspace' credentialGroupName: string invitationLink: string searchProviderName?: string diff --git a/apps/sim/ee/credential-groups/components/organization-account-invite-modal.tsx b/apps/sim/ee/credential-groups/components/organization-account-invite-modal.tsx index 2fe1e467083..e14e264b5f6 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-invite-modal.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-invite-modal.tsx @@ -16,7 +16,6 @@ import { useInviteOrganizationAccountPeople } from '@/hooks/queries/organization interface OrganizationAccountInviteModalProps { organizationId: string - searchConnection?: { optionId: string; providerName: string } onClose: () => void } @@ -27,7 +26,6 @@ function validateEmail(email: string): string | null { export function OrganizationAccountInviteModal({ organizationId, - searchConnection, onClose, }: OrganizationAccountInviteModalProps) { const invite = useInviteOrganizationAccountPeople() @@ -57,7 +55,6 @@ export function OrganizationAccountInviteModal({ const result = await invite.mutateAsync({ organizationId, emails, - ...(searchConnection ? { optionId: searchConnection.optionId } : {}), }) const failures = result.results.filter((item) => !item.success) if (failures.length === 0) { @@ -85,17 +82,11 @@ export function OrganizationAccountInviteModal({ handleOpenChange(false)}> - {searchConnection - ? `Request ${searchConnection.providerName} connections` - : 'Request account connections'} + Request account connections connection.status === 'needs_reauth')) { + return 'needs_reconnect' } - enabled?: boolean - requestDisabled?: boolean - filters?: ReactNode - setupFallback?: ReactNode + if (connections.some((connection) => connection.status === 'active')) return 'connected' + if (person.expired && person.status === 'invited') return 'expired' + return 'invited' } -export function OrganizationAccountPeople({ - organizationId, - searchConnection, - panel, - enabled = true, - setupFallback, - filters, - requestDisabled = false, -}: OrganizationAccountPeopleProps) { + +export function OrganizationAccountPeople({ organizationId }: OrganizationAccountPeopleProps) { const resend = useResendOrganizationAccountInvitation() const revoke = useRevokeOrganizationAccountEnrollment() const [peopleSearch, setPeopleSearch] = useOrganizationAccountPeopleSearch() const search = useDebounce(peopleSearch.trim(), SEARCH_DEBOUNCE_MS) - const people = useOrganizationAccountPeople(organizationId, search, { - enabled, - ...(searchConnection ? { optionId: searchConnection.optionId } : {}), - }) + const people = useOrganizationAccountPeople(organizationId, search) const [inviteOpen, setInviteOpen] = useState(false) const [revokingPerson, setRevokingPerson] = useState<{ id: string; email: string } | null>(null) const error = resend.error ?? revoke.error const pending = resend.isPending || revoke.isPending const enrollments = people.data?.pages.flatMap((page) => page.enrollments) ?? [] - const awaitingSetup = setupFallback !== undefined return ( setInviteOpen(true), }, - ...(panel?.actions ?? []), ]} > - {filters} - {awaitingSetup ? ( - setupFallback - ) : ( + {people.isPending && ( + Loading people… + )} + {people.error && !people.isFetchNextPageError && ( + void people.refetch()} + variant='inline' + /> + )} + {error && ( +

+ {error.message} +

+ )} + {!people.isPending && (!people.error || people.isFetchNextPageError) && ( <> - {people.isPending && ( - Loading people… - )} - {people.error && !people.isFetchNextPageError && ( - void people.refetch()} - variant='inline' - /> - )} - {error && ( -

- {error.message} -

- )} - {!people.isPending && (!people.error || people.isFetchNextPageError) && ( - <> - {enrollments.length === 0 ? ( - - {search ? 'No people match your search' : 'No people invited yet'} - - ) : ( -
- {enrollments.map((person) => ( - } - iconVariant='custom' - title={person.email} - description={} - trailing={ - - resend.mutate( - { - organizationId, - enrollmentId: person.id, - ...(searchConnection - ? { optionId: searchConnection.optionId } - : {}), - }, - { onSuccess: () => toast.success('Invitation sent') } - ), - }, - { - label: searchConnection ? 'Revoke all account access' : 'Revoke', - destructive: true, - disabled: pending || person.status === 'revoked', - onSelect: () => { - revoke.reset() - setRevokingPerson({ id: person.id, email: person.email }) - }, + {enrollments.length === 0 ? ( + + {search ? 'No people match your search' : 'No people invited yet'} + + ) : ( +
+ {enrollments.map((person) => { + const status = PERSON_STATUS_BADGES[getPersonStatus(person)] + const revoked = person.status === 'revoked' + return ( + } + iconVariant='custom' + title={person.email} + description={} + badge={ + + {status.label} + + } + trailing={ + + resend.mutate( + { organizationId, enrollmentId: person.id }, + { onSuccess: () => toast.success('Reminder sent') } + ), + }, + ]), + { + label: 'Revoke', + destructive: true, + disabled: pending || revoked, + onSelect: () => { + revoke.reset() + setRevokingPerson({ id: person.id, email: person.email }) }, - ]} - /> - } - /> - ))} -
- )} - {people.hasNextPage && !people.isFetchNextPageError && ( - void people.fetchNextPage()} - > - {people.isFetchingNextPage ? 'Loading...' : 'Load more'} - - )} - - )} - {people.isFetchNextPageError && ( - void people.fetchNextPage()} - variant='inline' - /> - )} - {inviteOpen && ( - setInviteOpen(false)} - /> - )} - {revokingPerson && ( - { - if (!open && !revoke.isPending) setRevokingPerson(null) - }} - title={`Revoke ${revokingPerson.email}`} - text='This removes all accounts contributed by this person from organization workflows and Search. It does not remove their organization membership.' - defaultAction='none' - confirm={{ - label: searchConnection ? 'Revoke all account access' : 'Revoke', - pendingLabel: 'Revoking…', - pending: revoke.isPending, - variant: 'destructive', - onClick: () => - revoke.mutate( - { organizationId, enrollmentId: revokingPerson.id }, - { - onSuccess: () => { - setRevokingPerson(null) - toast.success('Access revoked') - }, + }, + ]} + /> } - ), - }} - > - {revoke.error?.message} - + /> + ) + })} +
+ )} + {people.hasNextPage && !people.isFetchNextPageError && ( + void people.fetchNextPage()}> + {people.isFetchingNextPage ? 'Loading...' : 'Load more'} + )} )} + {people.isFetchNextPageError && ( + void people.fetchNextPage()} + variant='inline' + /> + )} + {inviteOpen && ( + setInviteOpen(false)} + /> + )} + {revokingPerson && ( + { + if (!open && !revoke.isPending) setRevokingPerson(null) + }} + title={`Revoke ${revokingPerson.email}`} + text='This removes all accounts contributed by this person from organization workflows and Search. It does not remove their organization membership.' + defaultAction='none' + confirm={{ + label: 'Revoke', + pendingLabel: 'Revoking…', + pending: revoke.isPending, + variant: 'destructive', + onClick: () => + revoke.mutate( + { organizationId, enrollmentId: revokingPerson.id }, + { + onSuccess: () => { + setRevokingPerson(null) + toast.success('Access revoked') + }, + } + ), + }} + > + {revoke.error?.message} + + )}
) } diff --git a/apps/sim/ee/credential-groups/components/organization-account-provider-catalog.tsx b/apps/sim/ee/credential-groups/components/organization-account-provider-catalog.tsx index fa4a65d86b0..5d068876edb 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-provider-catalog.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-provider-catalog.tsx @@ -83,31 +83,31 @@ export function OrganizationAccountProviderCatalog({ return ( { if (!open && !pending) onClose() }} > - Add provider + Add integration setSearch(event.target.value)} /> - +
{providers.map(({ name, icon: Icon, choice }) => ( @@ -138,7 +138,9 @@ export function OrganizationAccountProviderCatalog({ ))} {!providers.length && ( - {query ? 'No matching providers.' : 'All available providers have been added.'} + {query + ? 'No matching integrations.' + : 'All available integrations have been added.'} )}
diff --git a/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx b/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx index e0e4464675c..cff794b4f16 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx @@ -174,7 +174,20 @@ describe('organization provider configuration UI', () => { requiredScopes: ['search:read'], } await render([], [github, gmail, slack]) - await clickButton('Update configurations') + const menu = document.querySelector( + 'button[aria-label="Integration actions"]' + ) + expect(menu).not.toBeNull() + await act(async () => + menu?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) + ) + const reapply = [...document.querySelectorAll('[role="menuitem"]')].find( + (node) => node.textContent?.trim() === 'Re-apply app configuration' + ) + expect(reapply).toBeDefined() + await act(async () => reapply?.click()) + expect(mocks.update).not.toHaveBeenCalled() + await clickButton('Re-apply') expect(mocks.update).toHaveBeenCalledExactlyOnceWith( { organizationId: 'org-1', @@ -207,7 +220,7 @@ describe('organization provider configuration UI', () => { ) expect(mocks.add).not.toHaveBeenCalled() expect(mocks.remove).not.toHaveBeenCalled() - expect(toast.success).toHaveBeenCalledWith('Provider configurations updated') + expect(toast.success).toHaveBeenCalledWith('App configuration re-applied') }) it('loads existing settings for Configure and preserves a saved secret left blank', async () => { diff --git a/apps/sim/ee/credential-groups/components/organization-account-providers.tsx b/apps/sim/ee/credential-groups/components/organization-account-providers.tsx index 3bfaad18340..9d2827648eb 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-providers.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-providers.tsx @@ -3,6 +3,7 @@ import { useState } from 'react' import { Chip, + ChipConfirmModal, ChipModal, ChipModalBody, ChipModalError, @@ -55,7 +56,6 @@ interface OrganizationAccountProvidersProps { group: NonNullable availableProviders: CredentialGroupProvider[] availableMcpConnectors?: readonly ManagedMcpConnectorId[] - visibleProviders?: readonly CredentialGroupProvider[] } export function OrganizationAccountProviders({ @@ -63,7 +63,6 @@ export function OrganizationAccountProviders({ group, availableProviders, availableMcpConnectors, - visibleProviders, }: OrganizationAccountProvidersProps) { const [searchTerm, setSearchParam] = useQueryState(credentialGroupProviderSearchParam.key, { ...credentialGroupProviderSearchParam.parser, @@ -74,18 +73,21 @@ export function OrganizationAccountProviders({ const [removing, setRemoving] = useState(null) const [slackOpen, setSlackOpen] = useState(false) const [databricksOpen, setDatabricksOpen] = useState(false) + const [reapplyOpen, setReapplyOpen] = useState(false) const update = useUpdateOrganizationAccounts() const addMcp = useAddOrganizationAccountMcpProvider() const removeMcp = useRemoveOrganizationAccountMcpProvider() const pending = update.isPending || addMcp.isPending || removeMcp.isPending const options = getOrganizationAccountUpdateOptions(group) - const updateConfigurations = () => { + const reapplyConfiguration = () => { if (pending) return update.mutate( { organizationId, groupId: group.id, update: { options } }, { - onSuccess: () => toast.success('Provider configurations updated'), - onError: (error) => toast.error(error.message), + onSuccess: () => { + setReapplyOpen(false) + toast.success('App configuration re-applied') + }, } ) } @@ -132,7 +134,7 @@ export function OrganizationAccountProviders({ if (!removing || pending) return const onSuccess = () => { setRemoving(null) - toast.success('Provider removed') + toast.success('Integration removed') } if (removing.kind === 'mcp') { removeMcp.mutate({ organizationId, connectorId: removing.connectorId }, { onSuccess }) @@ -148,18 +150,16 @@ export function OrganizationAccountProviders({ } } const rows = [ - ...group.options - .filter((option) => !visibleProviders || visibleProviders.includes(option.provider)) - .map((option) => { - const service = getCredentialGroupProviderService(option.provider) - return { - id: option.id, - name: service.name, - icon: service.icon, - configure: option.provider === 'slack' ? () => setSlackOpen(true) : undefined, - choice: { kind: 'oauth', provider: option.provider } as const, - } - }), + ...group.options.map((option) => { + const service = getCredentialGroupProviderService(option.provider) + return { + id: option.id, + name: service.name, + icon: service.icon, + configure: option.provider === 'slack' ? () => setSlackOpen(true) : undefined, + choice: { kind: 'oauth', provider: option.provider } as const, + } + }), ...group.mcpServers .filter((server) => server.managedConnectorId !== 'databricks' || server.enabled) .map((server) => ({ @@ -190,12 +190,7 @@ export function OrganizationAccountProviders({ - {options.length > 0 && ( - - Update configurations - - )} +
} disabled={pending} @@ -208,15 +203,24 @@ export function OrganizationAccountProviders({ > Add integration + {options.length > 0 && ( + { + update.reset() + setReapplyOpen(true) + }, + }, + ]} + /> + )}
} > - {options.length > 0 && ( -

- Apply the current app configuration. Accounts whose app configuration changed will need - to reconnect. -

- )}
{visibleRows.map(({ id, name, icon: Icon, configure, choice }) => ( )} + {reapplyOpen && ( + { + if (!open && !update.isPending) setReapplyOpen(false) + }} + title='Re-apply app configuration' + text='Apply the current app configuration to every integration. Accounts whose app configuration changed will need to reconnect.' + confirm={{ + label: 'Re-apply', + pendingLabel: 'Re-applying…', + pending: update.isPending, + variant: 'primary', + onClick: reapplyConfiguration, + }} + > + {update.error ? getErrorMessage(update.error) : null} + + )} {removing && (

- Remove this provider and its connected accounts from the organization? + Remove this integration and its connected accounts from the organization?

{error ? getErrorMessage(error) : null}
diff --git a/apps/sim/ee/credential-groups/components/organization-person-connections.tsx b/apps/sim/ee/credential-groups/components/organization-person-connections.tsx index d3575fe1a7a..1ee65beeff9 100644 --- a/apps/sim/ee/credential-groups/components/organization-person-connections.tsx +++ b/apps/sim/ee/credential-groups/components/organization-person-connections.tsx @@ -21,7 +21,7 @@ export function OrganizationPersonConnections({ person }: OrganizationPersonConn const connectionsRef = useRef(null) const connections = person.connections - .filter((connection) => connection.status === 'active') + .filter((connection) => connection.status !== 'revoked') .map((connection) => { const display = connection.provider === 'gitlab' @@ -40,17 +40,19 @@ export function OrganizationPersonConnections({ person }: OrganizationPersonConn name: service?.name ?? display?.detailTitle ?? 'GitLab', icon: service?.icon ?? display?.icon ?? undefined, count: connection.count, + needsReconnect: connection.status === 'needs_reauth', } }) const accounts = [ ...connections, ...person.mcpConnections - .filter((connection) => connection.status === 'active') + .filter((connection) => connection.status !== 'revoked') .map((connection) => ({ - key: `mcp:${connection.mcpServerId}`, + key: `mcp:${connection.mcpServerId}:${connection.status}`, name: connection.name, count: connection.count, icon: undefined, + needsReconnect: connection.status === 'needs_reauth', })), ] @@ -70,11 +72,23 @@ export function OrganizationPersonConnections({ person }: OrganizationPersonConn )} {...scrollFadeAttributes(edges)} > - {accounts.map(({ key, name, icon, count }) => ( - - 1 ? `${name} (${count})` : name} /> - - ))} + {accounts.map(({ key, name, icon, count, needsReconnect }) => { + const label = count > 1 ? `${name} (${count})` : name + return ( + + + + ) + })} ) } diff --git a/apps/sim/lib/credential-groups/README.md b/apps/sim/lib/credential-groups/README.md index a0a5b19e9d1..8fb7aa3766e 100644 --- a/apps/sim/lib/credential-groups/README.md +++ b/apps/sim/lib/credential-groups/README.md @@ -1,10 +1,10 @@ # Organization connected accounts -An organization has at most one account pool. Owners and admins manage it in **Organization settings → Credential Groups**, with Providers, People, and Workspace access tabs. The initial workspace allowlist is empty. Personal account settings show the signed-in person’s own contributions, including contributions to organizations they have not joined. +An organization has at most one account pool. Owners and admins manage it in **Organization settings → Credential Groups**, with Integrations, People, and Access tabs. The initial workspace allowlist is empty. Personal account settings show the signed-in person’s own contributions, including contributions to organizations they have not joined. Credential Groups remains available whenever its organization feature is enabled, independently of Search. Search administrators use **Settings → Sources**; members use **Integrations**. The live Sources page has no credential-pool setup or People tabs. These surfaces reuse current grants without changing credential-group API access or stored workspace policies. -**Credential Groups → People → Request connections** retains manual email invitations, Resend, and Revoke actions. If no org credential group exists, People directs the admin to provider setup first. Search source creation does not replace required provider app configuration. +**Credential Groups → People → Request connections** sends manual email invitations. Each person shows one status (Invited, Expired, Email failed, Connected, Needs reconnect, or Revoked) and has **Send reminder** (until their enrollment is completed) and **Revoke** in their actions menu. If no org credential group exists, the page offers **Set up Credential Groups** first. Search source creation does not replace required provider app configuration. ## Permissions @@ -29,9 +29,9 @@ MCP `credentialId` identifies the person’s connection (`mcp-cg-…`) and is us Credential trigger mode supports `credential_added`, `credential_reconnected`, and `form_submitted`. Events go to opted-in, currently deployed Credential triggers in allowed workspaces. Legacy Credential Group blocks are hidden and fail with an explicit replacement instruction; they are not automatically rebound. -## Providers +## Integrations -The Providers tab lists only added providers. **Add provider** opens a searchable catalog with the remaining providers. Required configuration is completed before adding a provider; **Configure** reopens Slack or Databricks settings directly. Providers without required setup are added directly. Providers have **Remove** in their actions menu. Individual account connections remain in People. Connected accounts does not display indexing status, load Search sources, or open indexing setup. +The Integrations tab lists only added integrations. **Add integration** opens a searchable catalog with the remaining ones. Required configuration is completed before adding an integration; **Configure** reopens Slack or Databricks settings directly. Integrations without required setup are added directly. Each has **Remove** in its actions menu. The header actions menu has **Re-apply app configuration**, which rewrites every integration's current app configuration after a confirmation; accounts whose app configuration changed must reconnect. Individual account connections remain in People. Connected accounts does not display indexing status, load Search sources, or open indexing setup. - Fireflies and Granola: an admin adds the provider; Sim supplies the fixed hosted MCP endpoint and dynamic client registration. Each person completes their own OAuth authorization. - Databricks: **Add** collects and validates the organization's tenant MCP URL and registered OAuth client before creating an enabled provider in one transaction. Cancelling leaves nothing added. Organization owners and admins create it through `POST /api/organizations/[id]/connected-accounts/mcp-providers` and read or edit settings through `GET` / `PUT /api/organizations/[id]/connected-accounts/databricks`; no workspace configuration is used. Unfinished entries from the earlier flow appear in the Add catalog until their configuration is saved. The form never reads stored client secrets, and leaving the secret blank when editing preserves it. Endpoint/client identity changes invalidate affected grants and pending attempts, requiring people to reconnect. diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 7c12d0feb7e..76339cd94fc 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -628,6 +628,7 @@ async function sendInvitation( recipientEmail: email, inviterName, workspaceName: context.workspaceName, + ownerKind: context.organizationId ? 'organization' : 'workspace', credentialGroupName: context.groupName, invitationLink: focusedLink.toString(), ...(options.searchConnection From 2c72a59dff1d2305611ef520bf9353e1661d610e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 13:26:30 -0600 Subject: [PATCH 02/26] feat(credential-groups): Slack return allowlist, specific enrollment link errors, connect sign-in - lib/credential-groups/return-url: closed allowlist (slack.com/app_redirect, *.slack.com, slack://app|open|channel) matched on the raw string before parsing - OAuth attempt state carries a validated returnUrl and a 'connect' returnTo; the callback reads the destination only from stored state; enroll and completion pages render a 'Return to Slack' link (never an automatic redirect) - explainCredentialGroupEnrollmentLink: expired / revoked / paused / delivery failed / wrong account outcomes for a signed-in person; others see only a masked address - login: credential-group callbacks get 'Sign in to connect your accounts' with social first --- apps/sim/app/(auth)/login/login-form.tsx | 41 ++-- .../enroll/[token]/oauth/[optionId]/route.ts | 16 +- .../credential-groups/enrollment-redirect.ts | 4 +- .../api/credential-groups/oauth-callback.ts | 18 +- .../app/credential-groups/complete/page.tsx | 25 ++- .../enroll/[token]/page.test.tsx | 3 + .../credential-groups/enroll/[token]/page.tsx | 146 ++++++++++++-- .../lib/api/contracts/credential-groups.ts | 5 +- .../enrollment-link-outcome.integration.ts | 187 ++++++++++++++++++ .../application/enrollment-link-outcome.ts | 66 +++++++ .../application/public-enrollment.ts | 8 +- apps/sim/lib/credential-groups/enrollments.ts | 54 +++++ apps/sim/lib/credential-groups/oauth-state.ts | 31 ++- apps/sim/lib/credential-groups/oauth.ts | 5 +- .../lib/credential-groups/return-url.test.ts | 60 ++++++ apps/sim/lib/credential-groups/return-url.ts | 53 +++++ 16 files changed, 673 insertions(+), 49 deletions(-) create mode 100644 apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts create mode 100644 apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts create mode 100644 apps/sim/lib/credential-groups/return-url.test.ts create mode 100644 apps/sim/lib/credential-groups/return-url.ts diff --git a/apps/sim/app/(auth)/login/login-form.tsx b/apps/sim/app/(auth)/login/login-form.tsx index 5ac641a1ca1..73e8f800589 100644 --- a/apps/sim/app/(auth)/login/login-form.tsx +++ b/apps/sim/app/(auth)/login/login-form.tsx @@ -105,6 +105,8 @@ export default function LoginPage({ logger.warn('Invalid callback URL detected and blocked:', { url: callbackUrlParam }) } const callbackUrl = isValidCallbackUrl ? callbackUrlParam! : DEFAULT_POST_AUTH_ROUTE + /** Invitees connecting accounts mostly arrive from a link; Google and Microsoft come first. */ + const connectFlow = isValidCallbackUrl && callbackUrl.startsWith('/credential-groups/') const [forgotPasswordOpen, setForgotPasswordOpen] = useState(false) const [forgotPasswordEmail, setForgotPasswordEmail] = useState('') @@ -359,6 +361,18 @@ export default function LoginPage({ const passwordFieldErrors = showValidationError && passwordErrors.length > 0 ? passwordErrors : [] const canSubmit = email.trim().length > 0 && password.length > 0 + const socialButtons = ( + + ) + if (!emailPasswordEnabled && !ssoEnabled && !hasSocial) return (
- + {connectFlow ? ( + + ) : ( + + )} + + {connectFlow && showBottomSection && socialButtons} + {connectFlow && emailPasswordEnabled && showBottomSection && ( + + )} {showTopSSO && ( @@ -492,19 +515,9 @@ export default function LoginPage({ )} - {showDivider && } - - {showBottomSection && ( - - )} + {!connectFlow && showDivider && } + + {!connectFlow && showBottomSection && socialButtons}
diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts index aa5582d7263..51715c3c988 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts @@ -12,6 +12,7 @@ import { enforceCredentialGroupEnrollmentOAuthRateLimit, enforcePublicCredentialGroupOAuthStartIpRateLimit, } from '@/lib/credential-groups/rate-limit' +import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { createCredentialGroupEnrollmentRedirect } from '@/app/api/credential-groups/enrollment-redirect' export const dynamic = 'force-dynamic' @@ -29,8 +30,12 @@ export const GET = withRouteHandler( const parsed = await parseRequest(startCredentialGroupOAuthContract, request, context) if (!parsed.success) return limited ?? parsed.response const { token, optionId } = parsed.data.params - const { returnTo } = parsed.data.query - const focus: Record = returnTo ? { optionId, returnTo } : {} + const { returnTo, return: rawReturnUrl } = parsed.data.query + const returnUrl = rawReturnUrl ? parseCredentialGroupReturnUrl(rawReturnUrl)?.href : undefined + const focus: Record = { + ...(returnTo ? { optionId, returnTo } : {}), + ...(returnUrl ? { return: returnUrl } : {}), + } if (limited) { return createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth: 'rate_limited' }) } @@ -49,7 +54,12 @@ export const GET = withRouteHandler( try { const { authorizationUrl } = await startPublicCredentialGroupOAuth.execute({ principal, - input: { invitationToken: token, optionId, ...(returnTo ? { returnTo } : {}) }, + input: { + invitationToken: token, + optionId, + ...(returnTo ? { returnTo } : {}), + ...(returnUrl ? { returnUrl } : {}), + }, request, }) const response = NextResponse.redirect(authorizationUrl) diff --git a/apps/sim/app/api/credential-groups/enrollment-redirect.ts b/apps/sim/app/api/credential-groups/enrollment-redirect.ts index 7868fb0a087..11a3afe45c4 100644 --- a/apps/sim/app/api/credential-groups/enrollment-redirect.ts +++ b/apps/sim/app/api/credential-groups/enrollment-redirect.ts @@ -24,12 +24,14 @@ export function createCredentialGroupEnrollmentRedirect( export function createCredentialGroupCompletionRedirect( oauth?: CredentialGroupOAuthFailure, completionId?: string, - organizationId?: string + organizationId?: string, + returnUrl?: string ): NextResponse { const query = new URLSearchParams() if (oauth) query.set('oauth', oauth) if (completionId) query.set('completionId', completionId) if (organizationId) query.set('organizationId', organizationId) + if (returnUrl) query.set('return', returnUrl) return new NextResponse(null, { status: 303, headers: { diff --git a/apps/sim/app/api/credential-groups/oauth-callback.ts b/apps/sim/app/api/credential-groups/oauth-callback.ts index ff5eacf7a5a..a991c887674 100644 --- a/apps/sim/app/api/credential-groups/oauth-callback.ts +++ b/apps/sim/app/api/credential-groups/oauth-callback.ts @@ -67,9 +67,11 @@ export async function handleCredentialGroupOAuthCallback({ if (!attempt || attempt.provider !== provider) { return createCredentialGroupCompletionRedirect(limited ? 'rate_limited' : 'expired') } - const focus: Record = attempt.returnTo - ? { optionId: attempt.optionId, returnTo: attempt.returnTo } - : {} + /** The return destination comes only from server-held attempt state, never the callback query. */ + const focus: Record = { + ...(attempt.returnTo ? { optionId: attempt.optionId, returnTo: attempt.returnTo } : {}), + ...(attempt.returnUrl ? { return: attempt.returnUrl } : {}), + } const setupRedirect = (oauth?: CredentialGroupOAuthFailure) => new NextResponse(null, { status: 303, @@ -90,7 +92,12 @@ export async function handleCredentialGroupOAuthCallback({ installationSetup ? setupRedirect(oauth) : attempt.completionRedirect - ? createCredentialGroupCompletionRedirect(oauth, attempt.completionId, returnOrganizationId) + ? createCredentialGroupCompletionRedirect( + oauth, + attempt.completionId, + returnOrganizationId, + attempt.returnUrl + ) : createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { ...focus, oauth }) if (limited) { return failureRedirect('rate_limited') @@ -122,7 +129,8 @@ export async function handleCredentialGroupOAuthCallback({ ? createCredentialGroupCompletionRedirect( undefined, attempt.completionId, - returnOrganizationId + returnOrganizationId, + attempt.returnUrl ) : createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { ...focus, diff --git a/apps/sim/app/credential-groups/complete/page.tsx b/apps/sim/app/credential-groups/complete/page.tsx index 773882918e0..37a9b6c45e2 100644 --- a/apps/sim/app/credential-groups/complete/page.tsx +++ b/apps/sim/app/credential-groups/complete/page.tsx @@ -5,6 +5,7 @@ import { CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES, isCredentialGroupOAuthFailure, } from '@/lib/credential-groups/oauth-completion' +import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { APP_ENTRY_PATH, organizationRoutes } from '@/lib/navigation/paths' import { AuthHeader, AuthShell } from '@/app/(auth)/components' import { CredentialGroupCompletionHandoff } from '@/app/credential-groups/complete/completion-handoff' @@ -21,15 +22,19 @@ export default async function CredentialGroupCompletePage({ oauth?: string | string[] completionId?: string | string[] organizationId?: string | string[] + return?: string | string[] }> }) { - const { oauth, completionId, organizationId } = await searchParams + const { oauth, completionId, organizationId, return: rawReturnUrl } = await searchParams const failure = oauth === undefined ? undefined : isCredentialGroupOAuthFailure(oauth) ? oauth : 'failed' const returnHref = typeof organizationId === 'string' && organizationId.length > 0 && organizationId.length <= 128 ? organizationRoutes(encodeURIComponent(organizationId)).integrations : undefined + /** Rendered only as a link the person clicks: no automatic hop to an external scheme. */ + const slackReturnHref = + typeof rawReturnUrl === 'string' ? parseCredentialGroupReturnUrl(rawReturnUrl)?.href : undefined const error = failure ? CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure] : undefined return ( @@ -46,15 +51,25 @@ export default async function CredentialGroupCompletePage({ error ?? (returnHref ? 'Returning to Integrations.' - : 'Your accounts are ready to use — you can close this tab.') + : slackReturnHref + ? 'Your account is ready to use.' + : 'Your accounts are ready to use — you can close this tab.') } /> - {(error || returnHref) && ( + {slackReturnHref ? (
- - {returnHref ? 'Return to Integrations' : 'Open Sim'} + + Return to Slack
+ ) : ( + (error || returnHref) && ( +
+ + {returnHref ? 'Return to Integrations' : 'Open Sim'} + +
+ ) )}
) diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.test.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.test.tsx index 058bc67a24a..fbb3aa0b58a 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.test.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.test.tsx @@ -15,6 +15,9 @@ vi.mock('next/headers', () => ({ headers: async () => new Headers() })) vi.mock('@/lib/credential-groups/application/enrollment-auth', () => ({ authenticateCredentialGroupEnrollment: mocks.authenticate, })) +vi.mock('@/lib/credential-groups/application/enrollment-link-outcome', () => ({ + explainCredentialGroupEnrollmentLink: async () => ({ kind: 'unknown' }), +})) vi.mock('@/lib/credential-groups/application/public-enrollment', () => ({ readPublicCredentialGroupEnrollment: { execute: mocks.read }, })) diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index 130cdbf3e74..2bde9272ecf 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -13,6 +13,10 @@ import { asOrchestrationError } from '@/lib/core/orchestration/types' import type { ResourceOwner } from '@/lib/core/resource-scope' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' import { authenticateCredentialGroupEnrollment } from '@/lib/credential-groups/application/enrollment-auth' +import { + type CredentialGroupEnrollmentLinkOutcome, + explainCredentialGroupEnrollmentLink, +} from '@/lib/credential-groups/application/enrollment-link-outcome' import { readPublicCredentialGroupEnrollment } from '@/lib/credential-groups/application/public-enrollment' import { CredentialGroupEnrollmentError } from '@/lib/credential-groups/enrollments' import { getManagedMcpConnectorIcon } from '@/lib/credential-groups/managed-mcp-connector-icons' @@ -20,11 +24,13 @@ import { CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES } from '@/lib/credential-groups import { CredentialGroupProviderConfigurationError } from '@/lib/credential-groups/provider-adapter' import { getCredentialGroupProviderService } from '@/lib/credential-groups/providers' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' +import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { APP_ENTRY_PATH, organizationRoutes } from '@/lib/navigation/paths' import { AuthHeader, AuthShell as LogoShell, SupportFooter } from '@/app/(auth)/components' import { OAuthConnectLink } from '@/app/credential-groups/enroll/[token]/oauth-reconnect-link' import { CredentialGroupOAuthToast } from '@/app/credential-groups/enroll/[token]/oauth-toast' import { SourceCompletion } from '@/app/desktop/connect/source-completion' +import { SwitchAccount } from '@/app/desktop/connect/switch-account' export const metadata: Metadata = { title: 'Connect accounts', @@ -52,6 +58,7 @@ function PageShell({ children }: PageShellProps) { interface UnavailableInvitationProps { token?: string + title?: string rateLimited?: boolean message?: string recoveryHref?: string @@ -60,6 +67,7 @@ interface UnavailableInvitationProps { function UnavailableInvitation({ token, + title, rateLimited = false, message, recoveryHref = APP_ENTRY_PATH, @@ -70,7 +78,7 @@ function UnavailableInvitation({ {token && }
+): string { + const asker = outcome.inviterName ?? (outcome.organizationName || 'an admin') + return outcome.reason === 'expired' + ? `This link expired. Ask ${asker} for a new one.` + : `This link is no longer active. Ask ${asker} for a new one.` +} + +/** Tells a signed-in person why their link did not open; unknown links stay generic. */ +function EnrollmentLinkProblem({ + token, + outcome, + signedInEmail, + callbackUrl, + fallbackMessage, +}: EnrollmentLinkProblemProps) { + const organizationName = + 'organizationName' in outcome && outcome.organizationName + ? outcome.organizationName + : 'Your organization' + switch (outcome.kind) { + case 'wrong_account': + return ( + + +
+ +
+ +
+
+
+ ) + case 'revoked': + return ( + + ) + case 'paused': + return ( + + ) + case 'needs_new_link': + return ( + + ) + case 'unavailable': + return + case 'unknown': + return + } +} + interface UnavailableSearchConnectionProps { token: string returnHref: string @@ -142,11 +226,16 @@ export default async function CredentialGroupEnrollmentPage({ if (!token || token.length > 128) return const resolvedSearchParams = await searchParams + const rawReturnUrl = getSearchParam(resolvedSearchParams, 'return') + const slackReturnUrl = rawReturnUrl + ? parseCredentialGroupReturnUrl(rawReturnUrl)?.href + : undefined const callback = new URLSearchParams() for (const key of ['returnTo', 'optionId']) { const value = getSearchParam(resolvedSearchParams, key) if (value) callback.set(key, value) } + if (slackReturnUrl) callback.set('return', slackReturnUrl) const callbackUrl = `/credential-groups/enroll/${encodeURIComponent(token)}${callback.size ? `?${callback}` : ''}` const session = await getSession() if (!session?.user) { @@ -161,11 +250,30 @@ export default async function CredentialGroupEnrollmentPage({ recoveryLabel='Verify email' /> ) + const signedInUser = { id: session.user.id, email: session.user.email } + const explainLinkProblem = async (fallbackMessage?: string) => ( + + ) const principal = await authenticateCredentialGroupEnrollment(token) - if (!principal) return - const returnToSearch = resolvedSearchParams.returnTo === 'search' - const returnToAccounts = resolvedSearchParams.returnTo === 'accounts' - const focused = returnToSearch || returnToAccounts + if (!principal) return explainLinkProblem() + const returnTo = getSearchParam(resolvedSearchParams, 'returnTo') + const returnToSearch = returnTo === 'search' + const focusedReturnTo = + returnTo === 'search' || returnTo === 'accounts' || returnTo === 'connect' + ? returnTo + : undefined + const focused = focusedReturnTo !== undefined const requestedOptionId = resolvedSearchParams.optionId const focusedOptionId = typeof requestedOptionId === 'string' && requestedOptionId.length <= 128 @@ -181,19 +289,26 @@ export default async function CredentialGroupEnrollmentPage({ return { enrollment: null } throw error }) - if (!enrollmentResult) return + if (!enrollmentResult) return explainLinkProblem() if ('enrollmentError' in enrollmentResult) - return + return explainLinkProblem(enrollmentResult.enrollmentError) const { enrollment } = enrollmentResult const canReturnToSearch = returnToSearch && ('canSearch' in enrollmentResult ? enrollmentResult.canSearch : !principal.organizationId) - const returnHref = canReturnToSearch ? sourceReturnPath(principal) : APP_ENTRY_PATH - const returnLabel = canReturnToSearch - ? principal.organizationId - ? 'Return to Search' - : 'Open knowledge bases' - : 'Open Sim' + const returnHref = + slackReturnUrl ?? (canReturnToSearch ? sourceReturnPath(principal) : APP_ENTRY_PATH) + const returnLabel = slackReturnUrl + ? 'Return to Slack' + : canReturnToSearch + ? principal.organizationId + ? 'Return to Search' + : 'Open knowledge bases' + : 'Open Sim' + const oauthStartQuery = new URLSearchParams() + if (focusedReturnTo) oauthStartQuery.set('returnTo', focusedReturnTo) + if (slackReturnUrl) oauthStartQuery.set('return', slackReturnUrl) + const oauthStartSuffix = oauthStartQuery.size ? `?${oauthStartQuery}` : '' if (!enrollment) return ( account.status === 'connected' ) ? undefined : ( 0} variant={focused ? 'primary' : undefined} /> @@ -357,8 +472,9 @@ export default async function CredentialGroupEnrollmentPage({
+ {slackReturnUrl && Return to Slack} {enrollment.status === 'completed' ? 'Submitted' : 'Submit'} diff --git a/apps/sim/lib/api/contracts/credential-groups.ts b/apps/sim/lib/api/contracts/credential-groups.ts index 70be7c77dcd..288ce4aa440 100644 --- a/apps/sim/lib/api/contracts/credential-groups.ts +++ b/apps/sim/lib/api/contracts/credential-groups.ts @@ -16,6 +16,7 @@ import { CREDENTIAL_GROUP_PROVIDER_IDS, CREDENTIAL_GROUP_STANDARD_OAUTH_PROVIDER_IDS, } from '@/lib/credential-groups/providers' +import { CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH } from '@/lib/credential-groups/return-url' export const credentialGroupProviderSchema = z.enum(CREDENTIAL_GROUP_PROVIDER_IDS) export const credentialGroupStatusSchema = z.enum(['active', 'disabled']) @@ -571,7 +572,9 @@ export const slackCredentialGroupConfigurationCallbackContract = defineRouteCont }) export const startCredentialGroupOAuthQuerySchema = z.object({ - returnTo: z.enum(['search', 'accounts']).optional(), + returnTo: z.enum(['search', 'accounts', 'connect']).optional(), + /** A Slack destination; the server keeps it only when it passes the return allowlist. */ + return: z.string().max(CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH).optional(), }) export type StartCredentialGroupOAuthQuery = z.output diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts new file mode 100644 index 00000000000..d1b327b9f8b --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts @@ -0,0 +1,187 @@ +/** + * What a signed-in person is told when an invitation link does not open, against real Postgres so + * the token lookup, the joins that name the organization and inviter, and the identity check run + * on stored rows. Failure modes: an unknown token, a forwarded link opened by someone else (who + * must learn nothing but a masked address, whatever state the enrollment is in), a revoked + * enrollment, a disabled group, a failed delivery, and an expired link. + */ +import { db } from '@sim/db' +import { credentialGroup, credentialGroupEnrollment, organization, user } from '@sim/db/schema' +import { sha256Hex } from '@sim/security/hash' +import { generateId } from '@sim/utils/id' +import { inArray } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { explainCredentialGroupEnrollmentLink } from '@/lib/credential-groups/application/enrollment-link-outcome' + +vi.mock('@/lib/credential-groups/scoped-availability', () => ({ + isScopedCredentialGroupsAvailable: async () => true, +})) + +const inviterId = generateId() +const inviteeId = generateId() +const strangerId = generateId() +const inviteeEmail = `invitee-${inviteeId}@example.test` +const strangerEmail = `stranger-${strangerId}@example.test` +const invitee = { id: inviteeId, email: inviteeEmail } +const stranger = { id: strangerId, email: strangerEmail } +const DAY_MS = 24 * 60 * 60 * 1000 + +const organizationIds: string[] = [] + +/** + * Each enrollment gets its own organization and group: an organization holds one group, and a + * group one enrollment per email and user. + */ +async function seedEnrollment( + values: Partial & { email: string }, + groupStatus: 'active' | 'disabled' = 'active' +): Promise { + const token = generateId() + const organizationId = generateId() + const groupId = generateId() + organizationIds.push(organizationId) + await db.insert(organization).values({ + id: organizationId, + name: 'Acme Corp', + slug: organizationId, + createdAt: new Date(), + }) + await db.insert(credentialGroup).values({ + id: groupId, + organizationId, + publicId: generateId(), + name: 'Accounts', + options: [], + status: groupStatus, + }) + await db.insert(credentialGroupEnrollment).values({ + id: generateId(), + credentialGroupId: groupId, + status: 'invited', + invitationTokenHash: sha256Hex(token), + invitationExpiresAt: new Date(Date.now() + DAY_MS), + invitedAt: new Date(), + createdBy: inviterId, + ...values, + }) + return token +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + [ + { id: inviterId, name: 'Ada Admin', email: `inviter-${inviterId}@example.test` }, + { id: inviteeId, name: 'Invitee', email: inviteeEmail }, + { id: strangerId, name: 'Stranger', email: strangerEmail }, + ].map((row) => ({ ...row, emailVerified: true, createdAt: now, updatedAt: now })) + ) +}) + +afterAll(async () => { + await db.delete(credentialGroup).where(inArray(credentialGroup.organizationId, organizationIds)) + await db.delete(organization).where(inArray(organization.id, organizationIds)) + await db.delete(user).where(inArray(user.id, [inviterId, inviteeId, strangerId])) +}) + +describe('explainCredentialGroupEnrollmentLink', () => { + it('keeps an unknown token generic', async () => { + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: generateId(), user: invitee }) + ).resolves.toEqual({ kind: 'unknown' }) + }) + + it('tells the invitee an expired unbound link needs reissuing by its inviter', async () => { + const token = await seedEnrollment({ + email: inviteeEmail, + invitationExpiresAt: new Date(Date.now() - DAY_MS), + }) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) + ).resolves.toEqual({ + kind: 'needs_new_link', + reason: 'expired', + organizationName: 'Acme Corp', + inviterName: 'Ada Admin', + }) + }) + + it('matches the invited email case-insensitively for an unbound link', async () => { + const token = await seedEnrollment({ + email: inviteeEmail, + status: 'revoked', + revokedAt: new Date(), + }) + await expect( + explainCredentialGroupEnrollmentLink({ + invitationToken: token, + user: { id: inviteeId, email: inviteeEmail.toUpperCase() }, + }) + ).resolves.toEqual({ kind: 'revoked', organizationName: 'Acme Corp' }) + }) + + it('tells the bound person a revoked enrollment is no longer needed', async () => { + const token = await seedEnrollment({ + email: inviteeEmail, + userId: inviteeId, + status: 'completed', + revokedAt: new Date(), + }) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) + ).resolves.toEqual({ kind: 'revoked', organizationName: 'Acme Corp' }) + }) + + it('names the paused group to its invitee', async () => { + const token = await seedEnrollment({ email: inviteeEmail }, 'disabled') + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) + ).resolves.toEqual({ kind: 'paused', organizationName: 'Acme Corp' }) + }) + + it('tells the matching person a link whose delivery failed needs reissuing', async () => { + const token = await seedEnrollment({ email: inviteeEmail, status: 'delivery_failed' }) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) + ).resolves.toEqual({ + kind: 'needs_new_link', + reason: 'delivery_failed', + organizationName: 'Acme Corp', + inviterName: 'Ada Admin', + }) + }) + + it.each([ + ['a live link', {}, 'active'], + ['an expired link', { invitationExpiresAt: new Date(Date.now() - DAY_MS) }, 'active'], + ['a revoked link', { status: 'revoked' as const, revokedAt: new Date() }, 'active'], + ['a failed delivery', { status: 'delivery_failed' as const }, 'active'], + ['a paused group', {}, 'disabled'], + ] as const)( + 'shows someone else holding %s only a masked address', + async (_label, values, groupStatus) => { + const token = await seedEnrollment({ email: inviteeEmail, ...values }, groupStatus) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: stranger }) + ).resolves.toEqual({ kind: 'wrong_account', maskedEmail: 'i***@example.test' }) + } + ) + + it('treats a link bound to another user as the wrong account even for the same email', async () => { + const token = await seedEnrollment({ + email: strangerEmail, + userId: inviteeId, + status: 'in_progress', + }) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: stranger }) + ).resolves.toEqual({ kind: 'wrong_account', maskedEmail: 's***@example.test' }) + }) + + it('stays generic for a live link that already belongs to the person', async () => { + const token = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) + ).resolves.toEqual({ kind: 'unavailable' }) + }) +}) diff --git a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts new file mode 100644 index 00000000000..e6e50fb7055 --- /dev/null +++ b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts @@ -0,0 +1,66 @@ +import { normalizeEmail } from '@sim/utils/string' +import { findCredentialGroupEnrollmentLinkRecord } from '@/lib/credential-groups/enrollments' + +/** + * Why an invitation link did not open for a signed-in, verified person. Enrollment details are + * only described to the person the enrollment belongs to; anyone else holding the link learns + * just a masked form of the address it was sent to. + */ +export type CredentialGroupEnrollmentLinkOutcome = + | { kind: 'unknown' } + | { kind: 'wrong_account'; maskedEmail: string } + | { kind: 'revoked'; organizationName: string } + | { kind: 'paused'; organizationName: string } + | { + kind: 'needs_new_link' + reason: 'expired' | 'delivery_failed' + organizationName: string + inviterName: string | null + } + | { kind: 'unavailable' } + +interface ExplainCredentialGroupEnrollmentLinkParams { + invitationToken: string + user: { id: string; email: string } +} + +/** Masks an address as `b***@example.com` so a forwarded link never reveals who it was for. */ +function maskEnrollmentEmail(email: string): string { + const at = email.lastIndexOf('@') + if (at < 1) return '***' + return `${email[0]}***${email.slice(at)}` +} + +/** Explains a link that failed to open, for the page that shows the person what to do next. */ +export async function explainCredentialGroupEnrollmentLink({ + invitationToken, + user, +}: ExplainCredentialGroupEnrollmentLinkParams): Promise { + const record = await findCredentialGroupEnrollmentLinkRecord(invitationToken) + if (!record) return { kind: 'unknown' } + + const belongsToUser = record.userId + ? record.userId === user.id + : normalizeEmail(user.email) === record.email + if (!belongsToUser) + return { kind: 'wrong_account', maskedEmail: maskEnrollmentEmail(record.email) } + + const { organizationName } = record + if (record.revoked) return { kind: 'revoked', organizationName } + if (!record.groupActive) return { kind: 'paused', organizationName } + if (record.status === 'delivery_failed') + return { + kind: 'needs_new_link', + reason: 'delivery_failed', + organizationName, + inviterName: record.inviterName, + } + if (record.expiresAt.getTime() <= Date.now()) + return { + kind: 'needs_new_link', + reason: 'expired', + organizationName, + inviterName: record.inviterName, + } + return { kind: 'unavailable' } +} diff --git a/apps/sim/lib/credential-groups/application/public-enrollment.ts b/apps/sim/lib/credential-groups/application/public-enrollment.ts index 594ab5910c1..01564379a0d 100644 --- a/apps/sim/lib/credential-groups/application/public-enrollment.ts +++ b/apps/sim/lib/credential-groups/application/public-enrollment.ts @@ -31,6 +31,7 @@ import { } from '@/lib/credential-groups/oauth' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' import { CredentialGroupInvitationUnavailableError } from '@/lib/credential-groups/provider-adapter' +import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { fireCredentialGroupTrigger } from '@/lib/credential-groups/trigger' import { isKnowledgeMemberAccessAvailable } from '@/lib/knowledge/access/availability' import { getOrganizationSettingsAccess } from '@/lib/organizations/settings-access' @@ -180,7 +181,9 @@ export const completePublicCredentialGroupEnrollment = interface PublicCredentialGroupOAuthInput { invitationToken: string optionId: string - returnTo?: 'search' | 'accounts' + returnTo?: 'search' | 'accounts' | 'connect' + /** Raw `return` query value; kept only when it is an allowed Slack destination. */ + returnUrl?: string } interface PublicCredentialGroupOAuthContext extends PublicCredentialGroupEnrollmentIdentity { @@ -211,6 +214,9 @@ export const startPublicCredentialGroupOAuth = defineAuthorizedCredentialGroupEn return { authorizationUrl: await startCredentialGroupOAuth(context.oauth, input.invitationToken, { returnTo: input.returnTo, + returnUrl: input.returnUrl + ? parseCredentialGroupReturnUrl(input.returnUrl)?.href + : undefined, }), } }, diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 7c12d0feb7e..e4d93c72a3e 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -1494,3 +1494,57 @@ function credentialGroupOAuthContextFromRow( options: row.options, } } + +export interface CredentialGroupEnrollmentLinkRecord { + email: string + userId: string | null + status: CredentialGroupEnrollmentStatus + expiresAt: Date + revoked: boolean + groupActive: boolean + organizationName: string + inviterName: string | null +} + +/** + * Reads the enrollment an invitation token names in any state, so the person holding it can be + * told why it stopped working. Grants no authority: live-link callers use + * {@link authenticatePublicCredentialGroupEnrollment}. + */ +export async function findCredentialGroupEnrollmentLinkRecord( + token: string +): Promise { + if (!token.trim() || token.length > 128) return null + const [row] = await db + .select({ + email: credentialGroupEnrollment.email, + userId: credentialGroupEnrollment.userId, + status: credentialGroupEnrollment.status, + expiresAt: credentialGroupEnrollment.invitationExpiresAt, + revokedAt: credentialGroupEnrollment.revokedAt, + groupStatus: credentialGroup.status, + workspaceId: credentialGroup.workspaceId, + organizationId: credentialGroup.organizationId, + organizationName: organization.name, + workspaceName: workspace.name, + inviterName: user.name, + }) + .from(credentialGroupEnrollment) + .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) + .leftJoin(workspace, eq(workspace.id, credentialGroup.workspaceId)) + .leftJoin(organization, eq(organization.id, credentialGroup.organizationId)) + .leftJoin(user, eq(user.id, credentialGroupEnrollment.createdBy)) + .where(eq(credentialGroupEnrollment.invitationTokenHash, hashInvitationToken(token))) + .limit(1) + if (!row || !(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(row)))) return null + return { + email: row.email, + userId: row.userId, + status: row.status, + expiresAt: row.expiresAt, + revoked: row.status === 'revoked' || row.revokedAt !== null, + groupActive: row.groupStatus === 'active', + organizationName: row.organizationName ?? row.workspaceName ?? '', + inviterName: row.inviterName, + } +} diff --git a/apps/sim/lib/credential-groups/oauth-state.ts b/apps/sim/lib/credential-groups/oauth-state.ts index 3aaa95094d6..cf626556b4d 100644 --- a/apps/sim/lib/credential-groups/oauth-state.ts +++ b/apps/sim/lib/credential-groups/oauth-state.ts @@ -13,6 +13,15 @@ import { type CredentialGroupProvider, isCredentialGroupProvider, } from '@/lib/credential-groups/providers' +import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' + +/** Where a managed-enrollment OAuth attempt lands once the provider sends the person back. */ +export type CredentialGroupOAuthReturnTo = + | 'search' + | 'accounts' + | 'connect' + | 'integrations' + | 'github-installation' const OAUTH_ATTEMPT_TTL_MS = 10 * 60 * 1000 const OAUTH_ATTEMPT_VERSION = 5 as const @@ -44,7 +53,8 @@ interface StoredCredentialGroupOAuthAttempt { completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: 'search' | 'accounts' | 'integrations' | 'github-installation' + returnTo?: CredentialGroupOAuthReturnTo + returnUrl?: string nonceHash: string encryptedCodeVerifier?: string encryptedInvitationToken: string @@ -69,7 +79,8 @@ export interface CredentialGroupOAuthAttempt { completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: 'search' | 'accounts' | 'integrations' | 'github-installation' + returnTo?: CredentialGroupOAuthReturnTo + returnUrl?: string codeVerifier?: string invitationToken: string createdAt: number @@ -91,7 +102,8 @@ interface CreateCredentialGroupOAuthAttemptParams { completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: 'search' | 'accounts' | 'integrations' | 'github-installation' + returnTo?: CredentialGroupOAuthReturnTo + returnUrl?: string codeVerifier?: string invitationToken: string } @@ -140,11 +152,15 @@ function isStoredAttempt(value: unknown): value is StoredCredentialGroupOAuthAtt (candidate.returnTo === undefined || candidate.returnTo === 'search' || candidate.returnTo === 'accounts' || + candidate.returnTo === 'connect' || candidate.returnTo === 'integrations' || (candidate.returnTo === 'github-installation' && candidate.provider === 'github-repositories' && typeof candidate.organizationId === 'string' && typeof candidate.completionId === 'string')) && + (candidate.returnUrl === undefined || + (typeof candidate.returnUrl === 'string' && + parseCredentialGroupReturnUrl(candidate.returnUrl) !== null)) && typeof candidate.nonceHash === 'string' && (candidate.encryptedCodeVerifier === undefined || typeof candidate.encryptedCodeVerifier === 'string') && @@ -170,6 +186,13 @@ export async function createCredentialGroupOAuthAttempt( throw new Error('GitHub installation OAuth requires an organization-bound setup attempt') } if (params.connectionIntent) credentialGroupConnectionIntentSchema.parse(params.connectionIntent) + const returnUrl = + params.returnUrl === undefined + ? undefined + : parseCredentialGroupReturnUrl(params.returnUrl)?.href + if (params.returnUrl !== undefined && !returnUrl) { + throw new Error('Credential group OAuth return URL is not an allowed destination') + } const redis = getRedisClient() const state = `${OAUTH_ATTEMPT_STATE_PREFIX}${generateId()}` const nonce = generateId() @@ -194,6 +217,7 @@ export async function createCredentialGroupOAuthAttempt( ...(params.connectionIntent ? { connectionIntent: params.connectionIntent } : {}), ...(params.completionId ? { completionId: params.completionId } : {}), ...(params.returnTo ? { returnTo: params.returnTo } : {}), + ...(returnUrl ? { returnUrl } : {}), nonceHash: sha256Hex(nonce), ...(encryptedCodeVerifier ? { encryptedCodeVerifier: encryptedCodeVerifier.encrypted } : {}), encryptedInvitationToken: encryptedInvitationToken.encrypted, @@ -251,6 +275,7 @@ export async function consumeCredentialGroupOAuthAttempt( ...(parsed.connectionIntent ? { connectionIntent: parsed.connectionIntent } : {}), ...(parsed.completionId ? { completionId: parsed.completionId } : {}), ...(parsed.returnTo ? { returnTo: parsed.returnTo } : {}), + ...(parsed.returnUrl ? { returnUrl: parsed.returnUrl } : {}), ...(codeVerifier ? { codeVerifier: codeVerifier.decrypted } : {}), invitationToken: invitationToken.decrypted, createdAt: parsed.createdAt, diff --git a/apps/sim/lib/credential-groups/oauth.ts b/apps/sim/lib/credential-groups/oauth.ts index f8773adffd7..270b2c6bb1b 100644 --- a/apps/sim/lib/credential-groups/oauth.ts +++ b/apps/sim/lib/credential-groups/oauth.ts @@ -21,6 +21,7 @@ import { CREDENTIAL_GROUP_ACCOUNTS_PER_PROVIDER_LIMIT } from '@/lib/credential-g import type { CredentialGroupConnectionIntent } from '@/lib/credential-groups/oauth-intent' import { type CredentialGroupOAuthAttempt, + type CredentialGroupOAuthReturnTo, createCredentialGroupOAuthAttempt, } from '@/lib/credential-groups/oauth-state' import type { @@ -121,7 +122,8 @@ export async function startCredentialGroupOAuth( completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: 'search' | 'accounts' | 'integrations' | 'github-installation' + returnTo?: CredentialGroupOAuthReturnTo + returnUrl?: string } = {} ): Promise { if (!context.credentialOwnerId) throw new CredentialGroupInvitationUnavailableError() @@ -145,6 +147,7 @@ export async function startCredentialGroupOAuth( completionId: options.completionId, connectionIntent: options.connectionIntent, returnTo: options.returnTo, + returnUrl: options.returnUrl, invitationToken, }) return await prepared.buildAuthorizationUrl({ state, nonce }) diff --git a/apps/sim/lib/credential-groups/return-url.test.ts b/apps/sim/lib/credential-groups/return-url.test.ts new file mode 100644 index 00000000000..1e39defe4d6 --- /dev/null +++ b/apps/sim/lib/credential-groups/return-url.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest' +import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' + +describe('parseCredentialGroupReturnUrl', () => { + it.each([ + 'https://slack.com/app_redirect?app=A123&team=T123', + 'https://slack.com/app_redirect?channel=C123&team=T123', + 'https://acme.slack.com/archives/C123/p1700000000000100', + 'https://acme.enterprise.slack.com/', + 'https://app.slack.com/client/T123/D456#thread', + 'slack://app?team=T123&id=A123', + 'slack://open?team=T123', + 'slack://channel?team=T123&id=C123', + ])('accepts the Slack destination %s', (raw) => { + expect(parseCredentialGroupReturnUrl(raw)?.href).toBe(raw) + }) + + it.each([ + ['another host', 'https://example.com/app_redirect?app=A1'], + ['a lookalike suffix', 'https://slack.com.evil.com/app_redirect'], + ['a lookalike prefix', 'https://evilslack.com/'], + ['a lookalike subdomain suffix', 'https://acme.slack.com.evil.com/'], + ['userinfo before the host', 'https://slack.com@evil.com/'], + ['userinfo naming Slack', 'https://user@acme.slack.com/'], + ['userinfo with a password', 'https://a:b@acme.slack.com/'], + ['an explicit port', 'https://slack.com:8443/app_redirect'], + ['the default port spelled out', 'https://acme.slack.com:443/'], + ['plain http', 'http://slack.com/app_redirect?app=A1'], + ['a javascript URL', 'javascript:alert(1)//slack.com'], + ['a data URL', 'data:text/html,'], + ['a protocol-relative URL', '//slack.com/app_redirect'], + ['a relative path', '/app_redirect'], + ['an uppercase scheme', 'HTTPS://slack.com/app_redirect'], + ['a leading space', ' https://slack.com/app_redirect'], + ['a trailing newline', 'https://slack.com/app_redirect\n'], + ['an embedded tab', 'https://sla\tck.com/app_redirect'], + ['a NUL byte', 'https://slack.com/app_redirect\u0000'], + ['a backslash authority', 'https://evil.com\\@slack.com/'], + ['backslashes for slashes', 'https:\\\\slack.com/app_redirect'], + ['a percent-encoded dot in the host', 'https://slack%2ecom/app_redirect'], + ['a percent-encoded host suffix', 'https://evil.com%2f.slack.com/'], + ['a non-ASCII homoglyph host', 'https://slаck.com/app_redirect'], + ['a punycode host', 'https://xn--slck-7cd.com/app_redirect'], + ['a trailing-dot host', 'https://slack.com./app_redirect'], + ['an empty subdomain label', 'https://.slack.com/'], + ['another slack.com path', 'https://slack.com/oauth/v2/authorize?client_id=1'], + ['an app_redirect prefix path', 'https://slack.com/app_redirect/../signin'], + ['an IP host', 'https://127.0.0.1/'], + ['an unlisted slack scheme action', 'slack://user?team=T123&id=U123'], + ['a slack scheme with a path', 'slack://app/../../etc?team=T1'], + ['a slack scheme with userinfo', 'slack://evil@app?team=T1'], + ['a slack scheme with a port', 'slack://app:1?team=T1'], + ['a slack scheme lookalike action', 'slack://application?team=T1'], + ['a slack-like scheme', 'slacks://app?team=T1'], + ['an overlong URL', `https://slack.com/app_redirect?app=${'A'.repeat(2048)}`], + ['an empty string', ''], + ])('rejects %s', (_label, raw) => { + expect(parseCredentialGroupReturnUrl(raw)).toBeNull() + }) +}) diff --git a/apps/sim/lib/credential-groups/return-url.ts b/apps/sim/lib/credential-groups/return-url.ts new file mode 100644 index 00000000000..b5562697a3f --- /dev/null +++ b/apps/sim/lib/credential-groups/return-url.ts @@ -0,0 +1,53 @@ +/** + * The closed allowlist of places a connect flow may send someone back to once their account is + * connected. Only Slack is allowed: `https://slack.com/app_redirect`, any `https://*.slack.com` + * page, and the `slack://app|open|channel` deep links. + * + * The raw string is matched before it is parsed, so parser normalization (percent-decoding, + * backslash folding, default-port stripping, IDNA) can never turn a rejected spelling into an + * accepted host. The result is only ever rendered as a link the person clicks, never followed by + * an automatic redirect. + */ + +export const CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH = 2048 + +/** Printable ASCII only: no whitespace, control characters, or non-ASCII lookalikes. */ +const PRINTABLE_ASCII = /^[\x21-\x7e]+$/ +const SLACK_WEB_URL = + /^https:\/\/((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*slack\.com)(?[/?#][^\\]*)?$/ +const SLACK_APP_URL = /^slack:\/\/(app|open|channel)(\?[^#\\]*)?$/ + +/** Returns the parsed URL when `raw` is an allowed Slack destination, else `null`. */ +export function parseCredentialGroupReturnUrl(raw: string): URL | null { + if (raw.length === 0 || raw.length > CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH) return null + if (!PRINTABLE_ASCII.test(raw) || raw.includes('\\')) return null + + if (raw.startsWith('slack://')) { + const match = SLACK_APP_URL.exec(raw) + if (!match) return null + const url = URL.canParse(raw) ? new URL(raw) : null + return url && url.protocol === 'slack:' && url.host === match[1] && url.href === raw + ? url + : null + } + + const match = SLACK_WEB_URL.exec(raw) + if (!match) return null + const host = match[1] + if (host === 'slack.com' && !/^\/app_redirect(?:\?|$)/.test(match.groups?.rest ?? '')) { + return null + } + if (!URL.canParse(raw)) return null + const url = new URL(raw) + if ( + url.protocol !== 'https:' || + url.username || + url.password || + url.port || + url.hostname !== host || + (host === 'slack.com' && url.pathname !== '/app_redirect') + ) { + return null + } + return url +} From 22cd8947bf9e1073498e293f3244fa983a40189f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 13:26:46 -0600 Subject: [PATCH 03/26] feat(credential-groups): enrollment links stop rotating invitations Invitation bearer tokens move to a new credential_group_enrollment_link table (migration 0489, expand-only, backfilled one 'email' link per existing enrollment). Issuing a link (admin invite, resend, self or viewer enroll) inserts a link and never invalidates another, so an emailed link keeps working after the person connects themselves, and an OAuth attempt started before a resend still completes. - Every token check (public resolve, bind, completion, OAuth and MCP grant persistence) goes through liveEnrollmentLinkCondition: an unrevoked link, unexpired only while the enrollment has no bound user. A hash with no link row falls back to the legacy column the released app still writes during the deploy window. - invitation_token_hash stays NOT NULL and mirrors the newest link so a rollback keeps working; invitation_expires_at keeps the latest expiry. - Self/viewer enroll no longer resets createdBy, invitedAt, sentAt or status on an existing enrollment; admin invite and resend keep their behavior, and resend's sentAt write is guarded by its own link. - Disconnect and revoke revoke every link; a reinvitation after revocation issues a fresh link without reviving the old ones. - delivery_failed no longer blocks a session-verified or bound person holding a live link (completion, MCP grants, personal tokens). --- .../enrollment-links.integration.ts | 359 + .../application/enrollment-auth.ts | 2 +- .../personal-organization-accounts.ts | 11 +- .../lib/credential-groups/enrollments.test.ts | 19 +- apps/sim/lib/credential-groups/enrollments.ts | 196 +- apps/sim/lib/credential-groups/oauth.ts | 3 +- apps/sim/lib/credentials/managed-mcp.test.ts | 3 +- apps/sim/lib/credentials/managed-mcp.ts | 11 +- .../lib/credentials/personal-tokens.test.ts | 1 + apps/sim/lib/credentials/personal-tokens.ts | 12 +- ...0489_credential_group_enrollment_links.sql | 39 + .../db/migrations/meta/0489_snapshot.json | 34833 ++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/schema.ts | 46 + .../credential-groups-enrollments.mock.ts | 15 +- .../src/mocks/schema-tables.generated.ts | 11 + 16 files changed, 35481 insertions(+), 87 deletions(-) create mode 100644 apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts create mode 100644 packages/db/migrations/0489_credential_group_enrollment_links.sql create mode 100644 packages/db/migrations/meta/0489_snapshot.json diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts new file mode 100644 index 00000000000..239298c9f96 --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts @@ -0,0 +1,359 @@ +/** + * Enrollment links against real Postgres: issuing a link never invalidates another, expiry binds + * only an unbound enrollment, and disconnect or revocation kills every link. Only the email + * transport and the provider code exchange are faked; the emailed link is read from what would + * have been sent. + */ +import { db } from '@sim/db' +import { + credential, + credentialGroup, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + member, + organization, + user, +} from '@sim/db/schema' +import { sha256Hex } from '@sim/security/hash' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { generateId } from '@sim/utils/id' +import { eq } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { disconnectPersonalOrganizationAccount } from '@/lib/credential-groups/application/personal-organization-accounts' +import { + authenticatePublicCredentialGroupEnrollment, + bindCredentialGroupEnrollmentUser, + completeAuthorizedCredentialGroupEnrollment, + getCredentialGroupOAuthContextForEnrollment, + inviteCredentialGroupEnrollment, + resendCredentialGroupEnrollment, + revokeCredentialGroupEnrollment, +} from '@/lib/credential-groups/enrollments' +import { completeCredentialGroupOAuth } from '@/lib/credential-groups/oauth' +import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' +import type { CredentialGroupProvider } from '@/lib/credential-groups/providers' +import { createViewerCredentialGroupEnrollment } from '@/lib/credential-groups/self-enrollment' +import { ensureWorkspaceAccountsGroup } from '@/lib/credential-groups/service' + +const POLICY = { authorizationAppId: 'fixture-app', requiredScopes: ['read'], scopeVersion: 1 } + +/** The last invitation link each recipient was emailed. */ +const emailedLinks = new Map() + +vi.mock('@/lib/credential-groups/scoped-availability', () => ({ + isScopedCredentialGroupsAvailable: async () => true, +})) + +vi.mock('@/components/emails/credential-groups/render', () => ({ + renderCredentialGroupInvitationEmail: async (input: { invitationLink: string }) => + input.invitationLink, +})) + +vi.mock('@/lib/messaging/email/mailer', () => ({ + sendEmail: async (input: { to: string; html: string }) => { + emailedLinks.set(input.to, input.html) + return { success: true, message: 'sent' } + }, +})) + +vi.mock('@/lib/credential-groups/provider-registry', async (importOriginal) => { + const { getCredentialGroupProviderId } = await import('@/lib/credential-groups/providers') + return { + ...(await importOriginal()), + getCredentialGroupProviderAdapter: (provider: CredentialGroupProvider) => { + const policy = { ...POLICY, provider, providerId: getCredentialGroupProviderId(provider) } + return { + provider, + requiresRefreshToken: false, + getPolicy: async () => policy, + exchangeAndVerify: async ({ code }: { code: string }) => ({ + providerId: policy.providerId, + providerSubjectId: code, + providerTenantId: null, + displayName: code, + metadata: { email: code }, + accessToken: `token-for-${code}`, + grantedScopes: POLICY.requiredScopes, + accessTokenExpiresAt: null, + refreshTokenExpiresAt: null, + }), + } + }, + } +}) + +const organizationId = generateId() +const adminId = generateId() +const scope = { kind: 'organization' as const, organizationId } +const DRIVE = { + id: 'option-google-drive', + provider: 'google-drive' as const, + label: 'Google Drive', + authorizationAppId: POLICY.authorizationAppId, + requiredScopes: POLICY.requiredScopes, + scopeVersion: POLICY.scopeVersion, + required: false, + status: 'active' as const, +} +let groupId = '' +const userIds: string[] = [adminId] + +async function createPerson(): Promise<{ userId: string; email: string }> { + const userId = generateId() + const email = `${userId}@links.test` + await db.insert(user).values({ + id: userId, + name: 'Link fixture', + email, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }) + userIds.push(userId) + return { userId, email } +} + +function tokenOf(link: string | undefined): string { + const token = link ? new URL(link).pathname.split('/').at(-1) : undefined + if (!token) throw new Error('Invitation link has no token') + return token +} + +async function adminInvite(email: string): Promise<{ enrollmentId: string; token: string }> { + const enrollment = await inviteCredentialGroupEnrollment(scope, groupId, adminId, 'Admin', email) + return { enrollmentId: enrollment.id, token: tokenOf(emailedLinks.get(email)) } +} + +async function selfEnroll(userId: string): Promise<{ enrollmentId: string; token: string }> { + const { enrollment, invitationLink } = await createViewerCredentialGroupEnrollment({ + organizationId, + credentialGroupId: groupId, + userId, + }) + return { enrollmentId: enrollment.id, token: tokenOf(invitationLink) } +} + +async function resend(enrollmentId: string, email: string): Promise { + await resendCredentialGroupEnrollment(scope, groupId, enrollmentId, adminId, 'Admin') + return tokenOf(emailedLinks.get(email)) +} + +async function resolves(token: string): Promise { + return (await authenticatePublicCredentialGroupEnrollment(token)) !== null +} + +/** Ages every link of an enrollment, and the legacy column, past its expiry. */ +async function expire(enrollmentId: string) { + const past = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000) + await db + .update(credentialGroupEnrollmentLink) + .set({ expiresAt: past }) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId)) + await db + .update(credentialGroupEnrollment) + .set({ invitationExpiresAt: past }) + .where(eq(credentialGroupEnrollment.id, enrollmentId)) +} + +/** Starts an OAuth attempt with `token`, the way the enroll route records it. */ +function attemptFor( + person: { userId: string; email: string }, + enrollmentId: string, + token: string +): CredentialGroupOAuthAttempt { + return { + userId: person.userId, + state: generateId(), + provider: DRIVE.provider, + nonceHash: 'nonce', + organizationId, + email: person.email, + enrollmentId, + credentialGroupId: groupId, + optionId: DRIVE.id, + authorizationAppId: POLICY.authorizationAppId, + scopeVersion: POLICY.scopeVersion, + requiredScopes: POLICY.requiredScopes, + redirectUri: 'https://sim.test/callback', + invitationToken: token, + createdAt: Date.now(), + } +} + +async function finishAttempt( + person: { userId: string; email: string }, + attempt: CredentialGroupOAuthAttempt +) { + const context = await getCredentialGroupOAuthContextForEnrollment( + { + organizationId, + credentialGroupId: groupId, + enrollmentId: attempt.enrollmentId, + email: person.email, + userId: person.userId, + }, + DRIVE.id + ) + if (!context) throw new Error('Enrollment is not live') + return completeCredentialGroupOAuth(context, attempt, `${person.userId}@drive.test`) +} + +beforeAll(async () => { + await db.insert(user).values({ + id: adminId, + name: 'Admin', + email: `${adminId}@links.test`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }) + await db.insert(organization).values({ id: organizationId, name: 'Links', slug: organizationId }) + await db + .insert(member) + .values({ id: generateId(), organizationId, userId: adminId, role: 'owner' }) + const group = await ensureWorkspaceAccountsGroup(scope, adminId) + groupId = group.id + await db + .update(credentialGroup) + .set({ options: [DRIVE] }) + .where(eq(credentialGroup.id, groupId)) +}) + +afterAll(async () => { + await db.delete(credential).where(eq(credential.organizationId, organizationId)) + await db.delete(organization).where(eq(organization.id, organizationId)) + for (const id of userIds) await db.delete(user).where(eq(user.id, id)) +}) + +describe('credential group enrollment links', () => { + it('keeps an emailed link working after the person connects themselves', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + const [before] = await db + .select() + .from(credentialGroupEnrollment) + .where(eq(credentialGroupEnrollment.id, emailed.enrollmentId)) + + const self = await selfEnroll(person.userId) + + expect(self.enrollmentId).toBe(emailed.enrollmentId) + expect(await resolves(emailed.token)).toBe(true) + expect(await resolves(self.token)).toBe(true) + const [after] = await db + .select() + .from(credentialGroupEnrollment) + .where(eq(credentialGroupEnrollment.id, emailed.enrollmentId)) + expect(after).toMatchObject({ + createdBy: adminId, + invitedAt: before?.invitedAt, + sentAt: before?.sentAt, + }) + }) + + it('completes an OAuth attempt started before the admin resent the invitation', async () => { + const person = await createPerson() + const self = await selfEnroll(person.userId) + const attempt = attemptFor(person, self.enrollmentId, self.token) + + const resent = await resend(self.enrollmentId, person.email) + + await expect(finishAttempt(person, attempt)).resolves.toMatchObject({ created: true }) + expect(await resolves(self.token)).toBe(true) + expect(await resolves(resent)).toBe(true) + }) + + it('lets a bound, completed person reuse an expired link', async () => { + const person = await createPerson() + const self = await selfEnroll(person.userId) + const identity = await authenticatePublicCredentialGroupEnrollment(self.token) + if (!identity) throw new Error('Fresh link did not resolve') + await expect(completeAuthorizedCredentialGroupEnrollment(identity)).resolves.toMatchObject({ + completed: true, + }) + + await expire(self.enrollmentId) + + const later = await authenticatePublicCredentialGroupEnrollment(self.token) + expect(later).toMatchObject({ enrollmentId: self.enrollmentId, userId: person.userId }) + if (!later) throw new Error('Expired link of a bound person did not resolve') + await expect(bindCredentialGroupEnrollmentUser(later, person.userId)).resolves.toBeUndefined() + }) + + it('rejects an expired link while the enrollment is unbound', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + expect(await resolves(emailed.token)).toBe(true) + + await expire(emailed.enrollmentId) + + expect(await resolves(emailed.token)).toBe(false) + }) + + it('kills every link when the person disconnects an account', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + const self = await selfEnroll(person.userId) + const { credentialId } = await finishAttempt( + person, + attemptFor(person, self.enrollmentId, self.token) + ) + + await disconnectPersonalOrganizationAccount.execute({ + principal: createSessionPrincipal({ userId: person.userId }), + input: { credentialId }, + }) + + expect(await resolves(emailed.token)).toBe(false) + expect(await resolves(self.token)).toBe(false) + }) + + it('kills every link on revocation, and a later reinvitation does not revive them', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + const self = await selfEnroll(person.userId) + + await revokeCredentialGroupEnrollment(scope, groupId, emailed.enrollmentId) + expect(await resolves(emailed.token)).toBe(false) + expect(await resolves(self.token)).toBe(false) + + const reinvited = await adminInvite(person.email) + expect(reinvited.enrollmentId).toBe(emailed.enrollmentId) + expect(await resolves(reinvited.token)).toBe(true) + expect(await resolves(emailed.token)).toBe(false) + expect(await resolves(self.token)).toBe(false) + }) + + it('resolves an invitation the pre-link app wrote during a deploy', async () => { + const person = await createPerson() + const token = generateId() + const enrollmentId = generateId() + await db.insert(credentialGroupEnrollment).values({ + id: enrollmentId, + credentialGroupId: groupId, + email: person.email, + status: 'invited', + invitationTokenHash: sha256Hex(token), + invitationExpiresAt: new Date(Date.now() + 60_000), + invitedAt: new Date(), + createdBy: adminId, + }) + + expect(await resolves(token)).toBe(true) + await expire(enrollmentId) + expect(await resolves(token)).toBe(false) + }) + + it('keeps both links when a resend races the person connecting themselves', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + + const [resent, self] = await Promise.all([ + resend(emailed.enrollmentId, person.email), + selfEnroll(person.userId), + ]) + + expect(await resolves(emailed.token)).toBe(true) + expect(await resolves(resent)).toBe(true) + expect(await resolves(self.token)).toBe(true) + }) +}) diff --git a/apps/sim/lib/credential-groups/application/enrollment-auth.ts b/apps/sim/lib/credential-groups/application/enrollment-auth.ts index b39ac84ea1e..9b7fed6f1b0 100644 --- a/apps/sim/lib/credential-groups/application/enrollment-auth.ts +++ b/apps/sim/lib/credential-groups/application/enrollment-auth.ts @@ -27,7 +27,7 @@ export async function authenticateCredentialGroupEnrollment( }) } -/** A consumed one-time attempt retains only its original enrollment authority, never a rotated invitation. */ +/** A consumed one-time attempt keeps only the authority of the link it started from, while that link stays live. */ export async function credentialGroupOAuthAttemptPrincipal( attempt: Pick< CredentialGroupOAuthAttempt, diff --git a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts index a46adaac2ec..8c07f833577 100644 --- a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts +++ b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts @@ -16,7 +16,10 @@ import { runWithOutboundOrganization } from '@/lib/core/network/context.server' import { OrchestrationError } from '@/lib/core/orchestration/types' import { sameResourceScopeCondition } from '@/lib/core/resource-scope.server' import { createCredentialGroupOAuthStartUrl } from '@/lib/credential-groups/enrollment-links' -import { lockCredentialGroupEnrollmentLifecycle } from '@/lib/credential-groups/enrollments' +import { + lockCredentialGroupEnrollmentLifecycle, + revokeCredentialGroupEnrollmentLinks, +} from '@/lib/credential-groups/enrollments' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import { createViewerCredentialGroupEnrollment } from '@/lib/credential-groups/self-enrollment' import { @@ -216,13 +219,15 @@ export const disconnectPersonalOrganizationAccount = defineAuthorizedCredentialU const [current] = await ownAccounts(principal.userId, input, tx) if (!current || current.enrollmentId !== account.enrollmentId) throw new OrchestrationError('not_found', 'Connected account not found') + const now = new Date() await tx .update(credential) - .set({ managedOauthStatus: 'revoked', revokedAt: new Date(), updatedAt: new Date() }) + .set({ managedOauthStatus: 'revoked', revokedAt: now, updatedAt: now }) .where(eq(credential.id, current.credentialId)) + await revokeCredentialGroupEnrollmentLinks(tx, current.enrollmentId, now) await tx .update(credentialGroupEnrollment) - .set({ invitationTokenHash: sha256Hex(generateId()), updatedAt: new Date() }) + .set({ invitationTokenHash: sha256Hex(generateId()), updatedAt: now }) .where(eq(credentialGroupEnrollment.id, current.enrollmentId)) }) return { diff --git a/apps/sim/lib/credential-groups/enrollments.test.ts b/apps/sim/lib/credential-groups/enrollments.test.ts index be3077a0df5..947f7fea68b 100644 --- a/apps/sim/lib/credential-groups/enrollments.test.ts +++ b/apps/sim/lib/credential-groups/enrollments.test.ts @@ -375,7 +375,9 @@ describe('verified self enrollment', () => { it('permits a token enrollment in an empty canonical group without sending email', async () => { dbChainMockFns.limit.mockResolvedValueOnce([group]).mockResolvedValueOnce([]) - dbChainMockFns.returning.mockResolvedValueOnce([ENROLLMENT]) + dbChainMockFns.returning + .mockResolvedValueOnce([ENROLLMENT]) + .mockResolvedValueOnce([{ id: 'link-1' }]) const result = await createCredentialGroupSelfEnrollmentLink( 'workspace-1', 'group-1', @@ -456,6 +458,7 @@ describe('resendCredentialGroupEnrollment', () => { .mockResolvedValueOnce([ENROLLMENT]) dbChainMockFns.returning .mockResolvedValueOnce([ENROLLMENT]) + .mockResolvedValueOnce([{ id: 'link-1' }]) .mockResolvedValueOnce([{ ...ENROLLMENT, sentAt: new Date() }]) vi.mocked(sendEmail).mockResolvedValueOnce({ success: true, message: 'sent' }) @@ -621,7 +624,7 @@ describe('enrollment context for session-authorized or consumed-attempt OAuth', beforeEach(() => { resetDbChainMock() }) - it('resolves pinned identity after invitation rotation or expiry without looking up the old bearer', async () => { + it('resolves pinned identity without looking up an invitation bearer', async () => { queueTableRows(schemaMock.credentialGroupEnrollment, [row]) expect(await getCredentialGroupOAuthContextForEnrollment(identity, 'option-1')).toMatchObject({ enrollmentId: identity.enrollmentId, @@ -637,22 +640,10 @@ describe('enrollment context for session-authorized or consumed-attempt OAuth', schemaMock.credentialGroupEnrollment.invitationTokenHash, expect.anything() ) - queueTableRows(schemaMock.credentialGroupEnrollment, [row]) - expect( - await getAuthorizedCredentialGroupOAuthContext( - { ...identity, invitationTokenHash: 'old-hash' }, - 'option-1' - ) - ).toBeNull() - expect(eq).toHaveBeenCalledWith( - schemaMock.credentialGroupEnrollment.invitationTokenHash, - 'old-hash' - ) }) it.each([ { groupStatus: 'disabled' }, { enrollment: { ...row.enrollment, status: 'revoked' } }, - { enrollment: { ...row.enrollment, status: 'delivery_failed' } }, { enrollment: { ...row.enrollment, revokedAt: NOW } }, { options: [] }, { options: [{ id: 'option-1', provider: 'gmail', status: 'disabled' }] }, diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 7c12d0feb7e..5a2cf81d036 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -4,6 +4,7 @@ import { credential, credentialGroup, credentialGroupEnrollment, + credentialGroupEnrollmentLink, mcpServers, organization, user, @@ -13,7 +14,21 @@ import { sha256Hex } from '@sim/security/hash' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { normalizeEmail, truncate } from '@sim/utils/string' -import { and, asc, count, desc, eq, inArray, isNull, lt, or, type SQL, sql } from 'drizzle-orm' +import { + and, + asc, + count, + desc, + eq, + gt, + inArray, + isNotNull, + isNull, + lt, + or, + type SQL, + sql, +} from 'drizzle-orm' import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' import { getCredentialGroupInvitationSubject } from '@/components/emails/subjects' import { searchFilter } from '@/lib/api/list-query' @@ -83,16 +98,27 @@ interface InvitationContext { /** What issuing an invitation does to an enrollment an admin revoked. */ export type RevokedEnrollmentPolicy = 'reactivate' | 'reject' +type EnrollmentLinkPurpose = (typeof credentialGroupEnrollmentLink.$inferInsert)['purpose'] + interface SendInvitationOptions { expectedEnrollmentId?: string revokedEnrollment: RevokedEnrollmentPolicy searchConnection?: { optionId: string; providerName: string } } +interface IssueInvitationOptions extends SendInvitationOptions { + /** + * `email` is an administrator's (re)invitation and restarts the invitation lifecycle; + * `self` only adds a link, leaving an existing enrollment's issuer, timestamps and status as + * they are. + */ + purpose: Extract +} + interface IssuedInvitation { enrollment: EnrollmentRow invitationLink: string - tokenHash: string + linkId: string } export interface PublicCredentialGroupEnrollment { @@ -255,6 +281,43 @@ function hashInvitationToken(token: string): string { return sha256Hex(token) } +/** + * Matches the enrollment row that `tokenHash` is a live link into: an unrevoked link, unexpired + * unless the enrollment is already bound to a user (from then on the signed-in user is the + * authority, not the link's age). A hash with no link row falls back to the enrollment's legacy + * column, which the pre-link app still writes during a deploy or rollback. + */ +export function liveEnrollmentLinkCondition(tokenHash: string, now = new Date()): SQL { + const link = credentialGroupEnrollmentLink + const bound = isNotNull(credentialGroupEnrollment.userId) + return sql`(exists (select 1 from ${link} where ${and( + eq(link.enrollmentId, credentialGroupEnrollment.id), + eq(link.tokenHash, tokenHash), + isNull(link.revokedAt), + or(bound, gt(link.expiresAt, now)) + )}) or (${and( + eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), + or(bound, gt(credentialGroupEnrollment.invitationExpiresAt, now)) + )} and not exists (select 1 from ${link} where ${eq(link.tokenHash, tokenHash)})))` +} + +/** Revokes every link into an enrollment; callers hold its lifecycle lock. */ +export async function revokeCredentialGroupEnrollmentLinks( + tx: DbTransaction, + enrollmentId: string, + now = new Date() +): Promise { + await tx + .update(credentialGroupEnrollmentLink) + .set({ revokedAt: now }) + .where( + and( + eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId), + isNull(credentialGroupEnrollmentLink.revokedAt) + ) + ) +} + function metadataString(metadata: object | null, key: string): string | null { const value = metadata ? (metadata as Record)[key] : undefined return typeof value === 'string' && value.length > 0 ? value : null @@ -285,12 +348,7 @@ async function loadLiveEnrollmentRow(scope: SQL | undefined) { .limit(1) if (!row || row.groupStatus !== 'active') return null - if ( - row.enrollment.status === 'revoked' || - row.enrollment.status === 'delivery_failed' || - row.enrollment.revokedAt - ) - return null + if (row.enrollment.status === 'revoked' || row.enrollment.revokedAt) return null const ownerScope = resourceScopeFromOwner(row) if (!(await isScopedCredentialGroupsAvailable(ownerScope))) return null @@ -306,24 +364,24 @@ async function resolvePublicEnrollmentRowByIdentity( enrollmentId?: string } ) { - const row = await loadLiveEnrollmentRow( + return loadLiveEnrollmentRow( and( - eq(credentialGroupEnrollment.invitationTokenHash, identity.invitationTokenHash), + liveEnrollmentLinkCondition(identity.invitationTokenHash), identity.enrollmentId ? eq(credentialGroupEnrollment.id, identity.enrollmentId) : undefined ) ) - return row && row.enrollment.invitationExpiresAt.getTime() > Date.now() ? row : null } function identityForPublicEnrollmentRow( - row: NonNullable>> + row: NonNullable>>, + invitationTokenHash: string ): PublicCredentialGroupEnrollmentIdentity { return { enrollmentId: row.enrollment.id, credentialGroupId: row.groupId, ...resourceScopeFields(resourceScopeFromOwner(row)), email: row.enrollment.email, - invitationTokenHash: row.enrollment.invitationTokenHash, + invitationTokenHash, ...(row.enrollment.userId ? { userId: row.enrollment.userId } : {}), } } @@ -332,10 +390,9 @@ function identityForPublicEnrollmentRow( export async function authenticatePublicCredentialGroupEnrollment( token: string ): Promise { - const row = await resolvePublicEnrollmentRowByIdentity({ - invitationTokenHash: hashInvitationToken(token), - }) - return row ? identityForPublicEnrollmentRow(row) : null + const invitationTokenHash = hashInvitationToken(token) + const row = await resolvePublicEnrollmentRowByIdentity({ invitationTokenHash }) + return row ? identityForPublicEnrollmentRow(row, invitationTokenHash) : null } async function resolveAuthorizedPublicEnrollmentRow( @@ -381,7 +438,7 @@ export async function bindCredentialGroupEnrollmentUser( and( eq(credentialGroupEnrollment.id, identity.enrollmentId), eq(credentialGroupEnrollment.credentialGroupId, identity.credentialGroupId), - eq(credentialGroupEnrollment.invitationTokenHash, identity.invitationTokenHash), + liveEnrollmentLinkCondition(identity.invitationTokenHash), eq(credentialGroupEnrollment.email, identity.email), resourceScopeCondition(credentialGroup, resourceScopeFromOwner(identity)), eq(credentialGroup.status, 'active') @@ -389,12 +446,7 @@ export async function bindCredentialGroupEnrollmentUser( ) .limit(1) .for('update', { of: credentialGroupEnrollment }) - if ( - !row || - row.enrollment.invitationExpiresAt.getTime() <= Date.now() || - row.enrollment.revokedAt || - ['revoked', 'delivery_failed'].includes(row.enrollment.status) - ) { + if (!row || row.enrollment.revokedAt || row.enrollment.status === 'revoked') { throw new CredentialGroupEnrollmentError('Invitation is invalid or expired', 404) } if ( @@ -520,14 +572,14 @@ async function issueInvitation( */ userId: string | undefined, email: string, - options: SendInvitationOptions + options: IssueInvitationOptions ): Promise { const now = new Date() const token = generateId() const tokenHash = hashInvitationToken(token) const expiresAt = new Date(now.getTime() + INVITATION_TTL_MS) - const enrollment = await db.transaction(async (tx) => { + const issued = await db.transaction(async (tx) => { await lockCredentialGroupInvitationTarget(tx, context.groupId, email) const [existing] = await tx .select() @@ -566,22 +618,28 @@ async function issueInvitation( const preservesProgress = current?.status === 'in_progress' || current?.status === 'completed' const nextStatus = preservesProgress ? current.status : ('invited' as const) - const mutableValues = { - status: nextStatus, + const linkValues = { invitationTokenHash: tokenHash, - invitationExpiresAt: expiresAt, + invitationExpiresAt: + current && current.invitationExpiresAt > expiresAt + ? current.invitationExpiresAt + : expiresAt, + updatedAt: now, + } + const invitationValues = { + ...linkValues, + status: nextStatus, invitedAt: now, sentAt: null, completedAt: preservesProgress ? current.completedAt : null, revokedAt: null, lastDeliveryError: null, createdBy: userId ?? null, - updatedAt: now, } const [next] = current ? await tx .update(credentialGroupEnrollment) - .set(mutableValues) + .set(options.purpose === 'email' ? invitationValues : linkValues) .where(eq(credentialGroupEnrollment.id, current.id)) .returning() : await tx @@ -590,21 +648,42 @@ async function issueInvitation( id: generateId(), credentialGroupId: context.groupId, email, - ...mutableValues, + ...invitationValues, createdAt: now, }) .returning() if (!next) throw new Error('Credential group enrollment write returned no row') - return next + const [link] = await tx + .insert(credentialGroupEnrollmentLink) + .values({ + id: generateId(), + enrollmentId: next.id, + tokenHash, + purpose: options.purpose, + expiresAt, + createdAt: now, + }) + .returning({ id: credentialGroupEnrollmentLink.id }) + if (!link) throw new Error('Credential group enrollment link insert returned no row') + return { enrollment: next, linkId: link.id } }) return { - enrollment, + ...issued, invitationLink: `${getBaseUrl()}/credential-groups/enroll/${token}`, - tokenHash, } } +/** True while the link an invitation was sent with is unrevoked. */ +function enrollmentLinkStillLive(linkId: string): SQL { + const link = credentialGroupEnrollmentLink + return sql`exists (select 1 from ${link} where ${and( + eq(link.id, linkId), + eq(link.enrollmentId, credentialGroupEnrollment.id), + isNull(link.revokedAt) + )})` +} + async function sendInvitation( context: InvitationContext, /** See {@link issueInvitation}: the issuer is attribution, never the authority. */ @@ -617,8 +696,8 @@ async function sendInvitation( const { enrollment: issued, invitationLink, - tokenHash, - } = await issueInvitation(context, userId, email, options) + linkId, + } = await issueInvitation(context, userId, email, { ...options, purpose: 'email' }) const focusedLink = new URL(invitationLink) if (options.searchConnection) { focusedLink.searchParams.set('optionId', options.searchConnection.optionId) @@ -653,7 +732,7 @@ async function sendInvitation( .where( and( eq(credentialGroupEnrollment.id, issued.id), - eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), + enrollmentLinkStillLive(linkId), eq(credentialGroupEnrollment.status, issued.status) ) ) @@ -673,7 +752,7 @@ async function sendInvitation( .where( and( eq(credentialGroupEnrollment.id, issued.id), - eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), + enrollmentLinkStillLive(linkId), eq(credentialGroupEnrollment.status, issued.status) ) ) @@ -969,6 +1048,7 @@ export async function createCredentialGroupSelfEnrollmentLink( const context = await getInvitationContext(scope, groupId, false) const issued = await issueInvitation(context, undefined, normalizeEmail(email), { revokedEnrollment: 'reject', + purpose: 'self', }) return { enrollment: toCredentialGroupEnrollment(issued.enrollment), @@ -1094,6 +1174,7 @@ export async function revokeCredentialGroupEnrollment( ) ) .returning({ id: credential.id, type: credential.type }) + await revokeCredentialGroupEnrollmentLinks(tx, enrollmentId, now) const [updated] = await tx .update(credentialGroupEnrollment) .set({ status: 'revoked', revokedAt: now, updatedAt: now }) @@ -1279,13 +1360,12 @@ async function buildPublicCredentialGroupEnrollment( /** Finalizes an enrollment after the recipient finishes their optional account selections. */ export async function completeCredentialGroupEnrollment(token: string): Promise { - const row = await resolvePublicEnrollmentRowByIdentity({ - invitationTokenHash: hashInvitationToken(token), - }) + const invitationTokenHash = hashInvitationToken(token) + const row = await resolvePublicEnrollmentRowByIdentity({ invitationTokenHash }) if (!row) return null const result = await completeResolvedCredentialGroupEnrollment( row, - identityForPublicEnrollmentRow(row) + identityForPublicEnrollmentRow(row, invitationTokenHash) ) return result?.completed ?? null } @@ -1306,23 +1386,16 @@ async function completeResolvedCredentialGroupEnrollment( await lockCredentialGroupEnrollmentLifecycle(tx, row.enrollment.id) const now = new Date() const [current] = await tx - .select({ - status: credentialGroupEnrollment.status, - invitationTokenHash: credentialGroupEnrollment.invitationTokenHash, - invitationExpiresAt: credentialGroupEnrollment.invitationExpiresAt, - }) + .select({ status: credentialGroupEnrollment.status }) .from(credentialGroupEnrollment) - .where(eq(credentialGroupEnrollment.id, row.enrollment.id)) + .where( + and( + eq(credentialGroupEnrollment.id, row.enrollment.id), + liveEnrollmentLinkCondition(identity.invitationTokenHash, now) + ) + ) .limit(1) - if ( - !current || - current.status === 'revoked' || - current.status === 'delivery_failed' || - current.invitationTokenHash !== identity.invitationTokenHash || - current.invitationExpiresAt.getTime() <= now.getTime() - ) { - return null - } + if (!current || current.status === 'revoked') return null const [group] = await tx .select({ @@ -1351,7 +1424,12 @@ async function completeResolvedCredentialGroupEnrollment( .where( and( eq(credentialGroupEnrollment.id, row.enrollment.id), - inArray(credentialGroupEnrollment.status, ['invited', 'in_progress', 'completed']) + inArray(credentialGroupEnrollment.status, [ + 'invited', + 'delivery_failed', + 'in_progress', + 'completed', + ]) ) ) .returning({ id: credentialGroupEnrollment.id }) diff --git a/apps/sim/lib/credential-groups/oauth.ts b/apps/sim/lib/credential-groups/oauth.ts index f8773adffd7..7149cf38605 100644 --- a/apps/sim/lib/credential-groups/oauth.ts +++ b/apps/sim/lib/credential-groups/oauth.ts @@ -15,6 +15,7 @@ import { resourceScopeCondition } from '@/lib/core/resource-scope.server' import { resolveAccountWrite } from '@/lib/credential-groups/account-rules' import { type CredentialGroupOAuthContext, + liveEnrollmentLinkCondition, lockCredentialGroupEnrollmentLifecycle, } from '@/lib/credential-groups/enrollments' import { CREDENTIAL_GROUP_ACCOUNTS_PER_PROVIDER_LIMIT } from '@/lib/credential-groups/limits' @@ -182,7 +183,7 @@ async function persistGrant( eq(credentialGroupEnrollment.credentialGroupId, context.credentialGroupId), eq(credentialGroupEnrollment.email, context.email), eq(credentialGroupEnrollment.userId, context.credentialOwnerId), - eq(credentialGroupEnrollment.invitationTokenHash, invitationTokenHash) + liveEnrollmentLinkCondition(invitationTokenHash) ) ) .limit(1) diff --git a/apps/sim/lib/credentials/managed-mcp.test.ts b/apps/sim/lib/credentials/managed-mcp.test.ts index 4b7290d8a85..6e44d29afa0 100644 --- a/apps/sim/lib/credentials/managed-mcp.test.ts +++ b/apps/sim/lib/credentials/managed-mcp.test.ts @@ -88,8 +88,7 @@ describe('managed MCP grant persistence', () => { connectionId: expect.stringMatching(/^mcp-cg-/), }) expect(eq).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.userId, 'person-1') - expect(eq).toHaveBeenCalledWith( - schemaMock.credentialGroupEnrollment.invitationTokenHash, + expect(credentialGroupsEnrollmentsMockFns.mockLiveEnrollmentLinkCondition).toHaveBeenCalledWith( input.invitationTokenHash ) expect(eq).toHaveBeenCalledWith(schemaMock.mcpServers.oauthConfigVersion, 2) diff --git a/apps/sim/lib/credentials/managed-mcp.ts b/apps/sim/lib/credentials/managed-mcp.ts index 9ee170a3fc6..f6293b3d993 100644 --- a/apps/sim/lib/credentials/managed-mcp.ts +++ b/apps/sim/lib/credentials/managed-mcp.ts @@ -22,7 +22,10 @@ import { import { decryptSecret, encryptSecret } from '@/lib/core/security/encryption' import { resolveAccountWrite } from '@/lib/credential-groups/account-rules' import type { OrganizationCredentialType } from '@/lib/credential-groups/credential-types' -import { lockCredentialGroupEnrollmentLifecycle } from '@/lib/credential-groups/enrollments' +import { + liveEnrollmentLinkCondition, + lockCredentialGroupEnrollmentLifecycle, +} from '@/lib/credential-groups/enrollments' import { getManagedMcpConnector, managedMcpAccountLimit, @@ -371,7 +374,7 @@ export async function persistManagedMcpCredential(params: { eq(credentialGroupEnrollment.credentialGroupId, params.credentialGroupId), eq(credentialGroupEnrollment.email, params.email), eq(credentialGroupEnrollment.userId, params.userId), - eq(credentialGroupEnrollment.invitationTokenHash, params.invitationTokenHash), + liveEnrollmentLinkCondition(params.invitationTokenHash), resourceScopeCondition(credentialGroup, scope), resourceScopeCondition(mcpServers, scope), eq(mcpServers.oauthConfigVersion, params.oauthConfigVersion), @@ -387,7 +390,9 @@ export async function persistManagedMcpCredential(params: { !source.managedConnectorId || source.groupStatus !== 'active' || source.enrollmentRevokedAt || - !['invited', 'in_progress', 'completed'].includes(source.enrollmentStatus) || + !['invited', 'delivery_failed', 'in_progress', 'completed'].includes( + source.enrollmentStatus + ) || source.linkedCredentialGroupId !== source.credentialGroupId ) { throw new ManagedMcpCredentialError('Managed MCP connection is no longer available', 404) diff --git a/apps/sim/lib/credentials/personal-tokens.test.ts b/apps/sim/lib/credentials/personal-tokens.test.ts index faaf7485557..2c3a26fd94d 100644 --- a/apps/sim/lib/credentials/personal-tokens.test.ts +++ b/apps/sim/lib/credentials/personal-tokens.test.ts @@ -84,6 +84,7 @@ function expectLiveBinding() { expect(eq).toHaveBeenCalledWith(schemaMock.user.id, schemaMock.credentialGroupEnrollment.userId) expect(inArray).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.status, [ 'invited', + 'delivery_failed', 'in_progress', 'completed', ]) diff --git a/apps/sim/lib/credentials/personal-tokens.ts b/apps/sim/lib/credentials/personal-tokens.ts index 63b8fd4281c..7afd365fc28 100644 --- a/apps/sim/lib/credentials/personal-tokens.ts +++ b/apps/sim/lib/credentials/personal-tokens.ts @@ -94,6 +94,14 @@ export async function getPersonalTokenCredentials( ) } +/** An enrollment whose invitation email bounced still binds its verified, signed-in owner. */ +const PERSONAL_TOKEN_ENROLLMENT_STATUSES = [ + 'invited', + 'delivery_failed', + 'in_progress', + 'completed', +] as const + function liveEnrollmentConditions(workspaceId: string, userId: string) { return [ or( @@ -110,7 +118,7 @@ function liveEnrollmentConditions(workspaceId: string, userId: string) { isNull(credentialGroup.organizationId), sql`exists (select 1 from ${member} where ${member.organizationId} = ${credentialGroup.organizationId} and ${member.userId} = ${userId})` ), - inArray(credentialGroupEnrollment.status, ['invited', 'in_progress', 'completed']), + inArray(credentialGroupEnrollment.status, PERSONAL_TOKEN_ENROLLMENT_STATUSES), isNull(credentialGroupEnrollment.revokedAt), ] } @@ -155,7 +163,7 @@ export async function requirePersonalTokenEnrollment( eq(credentialGroup.status, 'active'), eq(user.id, input.userId), eq(user.emailVerified, true), - inArray(credentialGroupEnrollment.status, ['invited', 'in_progress', 'completed']), + inArray(credentialGroupEnrollment.status, PERSONAL_TOKEN_ENROLLMENT_STATUSES), isNull(credentialGroupEnrollment.revokedAt), sql`exists (select 1 from ${member} where ${member.organizationId} = ${scope.organizationId} and ${member.userId} = ${input.userId})`, ]) diff --git a/packages/db/migrations/0489_credential_group_enrollment_links.sql b/packages/db/migrations/0489_credential_group_enrollment_links.sql new file mode 100644 index 00000000000..c6bdc690a0d --- /dev/null +++ b/packages/db/migrations/0489_credential_group_enrollment_links.sql @@ -0,0 +1,39 @@ +-- Expand: invitation bearer links move to their own table so issuing one never invalidates +-- another. credential_group_enrollment.invitation_token_hash stays NOT NULL and the app keeps +-- writing it (mirroring the newest link), so the released app and a rollback keep resolving +-- invitations through it. Every statement is idempotent: a replay after an earlier migration's +-- embedded COMMIT re-runs this file in autocommit. +DO $$ BEGIN + CREATE TYPE "public"."credential_group_enrollment_link_purpose" AS ENUM('email', 'self', 'connect'); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$;--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "credential_group_enrollment_link" ( + "id" text PRIMARY KEY NOT NULL, + "enrollment_id" text NOT NULL, + "token_hash" text NOT NULL, + "purpose" "credential_group_enrollment_link_purpose" NOT NULL, + "option_id" text, + "expires_at" timestamp NOT NULL, + "revoked_at" timestamp, + "created_at" timestamp DEFAULT now() NOT NULL, + CONSTRAINT "credential_group_enrollment_link_enrollment_id_credential_group_enrollment_id_fk" FOREIGN KEY ("enrollment_id") REFERENCES "public"."credential_group_enrollment"("id") ON DELETE cascade ON UPDATE no action, + CONSTRAINT "credential_group_enrollment_link_token_hash_length_check" CHECK (length("credential_group_enrollment_link"."token_hash") = 64) +); +--> statement-breakpoint +CREATE UNIQUE INDEX IF NOT EXISTS "credential_group_enrollment_link_token_hash_unique" ON "credential_group_enrollment_link" USING btree ("token_hash");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "credential_group_enrollment_link_enrollment_id_idx" ON "credential_group_enrollment_link" USING btree ("enrollment_id");--> statement-breakpoint +-- Backfill: each existing enrollment's current invitation becomes its first link. One row per +-- enrollment (a small table), and ON CONFLICT on the unique token hash makes a replay a no-op. +-- Rows the released app writes after this runs carry no link and resolve through the legacy +-- branch of liveEnrollmentLinkCondition until they are reissued. +INSERT INTO "credential_group_enrollment_link" ("id", "enrollment_id", "token_hash", "purpose", "expires_at", "revoked_at", "created_at") +SELECT + gen_random_uuid()::text, + e."id", + e."invitation_token_hash", + 'email', + e."invitation_expires_at", + COALESCE(e."revoked_at", CASE WHEN e."status" = 'revoked' THEN now() END), + e."invited_at" +FROM "credential_group_enrollment" e +ON CONFLICT ("token_hash") DO NOTHING; diff --git a/packages/db/migrations/meta/0489_snapshot.json b/packages/db/migrations/meta/0489_snapshot.json new file mode 100644 index 00000000000..fc6f9f3f9bd --- /dev/null +++ b/packages/db/migrations/meta/0489_snapshot.json @@ -0,0 +1,34833 @@ +{ + "id": "c545d68d-eef3-405a-89ea-36781560bffd", + "prevId": "71fe2561-72db-41f3-a89e-d44b1520cbce", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config": { + "name": "oauth_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_at": { + "name": "refresh_revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_code": { + "name": "refresh_revoked_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_token_hash": { + "name": "refresh_revoked_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "account_user_id_idx": { + "name": "account_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_account_on_account_id_provider_id": { + "name": "idx_account_on_account_id_provider_id", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_blocked": { + "name": "activity_rollup_blocked", + "schema": "", + "columns": { + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": true, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "retry_at": { + "name": "retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_dirty": { + "name": "activity_rollup_dirty", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "due_at": { + "name": "due_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "activity_rollup_dirty_due_at_idx": { + "name": "activity_rollup_dirty_due_at_idx", + "columns": [ + { + "expression": "due_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "activity_rollup_dirty_workspace_id_bucket_start_pk": { + "name": "activity_rollup_dirty_workspace_id_bucket_start_pk", + "columns": ["workspace_id", "bucket_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_inflight": { + "name": "activity_rollup_inflight", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "next_check_at": { + "name": "next_check_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "activity_rollup_inflight_next_check_at_idx": { + "name": "activity_rollup_inflight_next_check_at_idx", + "columns": [ + { + "expression": "next_check_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "activity_rollup_inflight_workspace_id_bucket_start_pk": { + "name": "activity_rollup_inflight_workspace_id_bucket_start_pk", + "columns": ["workspace_id", "bucket_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_state": { + "name": "activity_rollup_state", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "coverage_start": { + "name": "coverage_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "fresh_through": { + "name": "fresh_through", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "backfill_completed_at": { + "name": "backfill_completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_end_scan": { + "name": "last_end_scan", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "lease_owner": { + "name": "lease_owner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "housekeeping_at": { + "name": "housekeeping_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "maintained_at": { + "name": "maintained_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "failed_passes": { + "name": "failed_passes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "corrections_at": { + "name": "corrections_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_memory_turn": { + "name": "agent_memory_turn", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_order": { + "name": "execution_order", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "encrypted_state": { + "name": "encrypted_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "agent_memory_turn_invocation_unique": { + "name": "agent_memory_turn_invocation_unique", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "node_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_memory_turn_workflow_idx": { + "name": "agent_memory_turn_workflow_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "agent_memory_turn_memory_id_memory_id_fk": { + "name": "agent_memory_turn_memory_id_memory_id_fk", + "tableFrom": "agent_memory_turn", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "agent_memory_turn_workflow_id_workflow_id_fk": { + "name": "agent_memory_turn_workflow_id_workflow_id_fk", + "tableFrom": "agent_memory_turn", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.api_key": { + "name": "api_key", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key_hash": { + "name": "key_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'personal'" + }, + "access": { + "name": "access", + "type": "api_key_access", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'write'" + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "api_key_workspace_type_idx": { + "name": "api_key_workspace_type_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "api_key_user_type_idx": { + "name": "api_key_user_type_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "api_key_key_hash_idx": { + "name": "api_key_key_hash_idx", + "columns": [ + { + "expression": "key_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "api_key_user_id_user_id_fk": { + "name": "api_key_user_id_user_id_fk", + "tableFrom": "api_key", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "api_key_workspace_id_workspace_id_fk": { + "name": "api_key_workspace_id_workspace_id_fk", + "tableFrom": "api_key", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "api_key_created_by_user_id_fk": { + "name": "api_key_created_by_user_id_fk", + "tableFrom": "api_key", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "api_key_key_unique": { + "name": "api_key_key_unique", + "nullsNotDistinct": false, + "columns": ["key"] + } + }, + "policies": {}, + "checkConstraints": { + "workspace_type_check": { + "name": "workspace_type_check", + "value": "(type = 'workspace' AND workspace_id IS NOT NULL) OR (type = 'personal' AND workspace_id IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.assistant_tool_permission": { + "name": "assistant_tool_permission", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "read_policy": { + "name": "read_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'allow'" + }, + "write_policy": { + "name": "write_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'ask'" + }, + "overrides": { + "name": "overrides", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "assistant_tool_permission_credential_idx": { + "name": "assistant_tool_permission_credential_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "assistant_tool_permission_user_idx": { + "name": "assistant_tool_permission_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assistant_tool_permission_organization_id_organization_id_fk": { + "name": "assistant_tool_permission_organization_id_organization_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_tool_permission_user_id_user_id_fk": { + "name": "assistant_tool_permission_user_id_user_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_tool_permission_credential_id_credential_id_fk": { + "name": "assistant_tool_permission_credential_id_credential_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "assistant_tool_permission_organization_id_user_id_credential_id_pk": { + "name": "assistant_tool_permission_organization_id_user_id_credential_id_pk", + "columns": ["organization_id", "user_id", "credential_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "assistant_tool_permission_policy_check": { + "name": "assistant_tool_permission_policy_check", + "value": "\"assistant_tool_permission\".\"read_policy\" IN ('allow', 'ask', 'block') AND \"assistant_tool_permission\".\"write_policy\" IN ('allow', 'ask', 'block')" + }, + "assistant_tool_permission_revision_check": { + "name": "assistant_tool_permission_revision_check", + "value": "\"assistant_tool_permission\".\"revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.async_jobs": { + "name": "async_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_at": { + "name": "run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 3 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "async_jobs_status_started_at_idx": { + "name": "async_jobs_status_started_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_status_completed_at_idx": { + "name": "async_jobs_status_completed_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "completed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_pending_run_at_idx": { + "name": "async_jobs_schedule_pending_run_at_idx", + "columns": [ + { + "expression": "run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_processing_started_at_idx": { + "name": "async_jobs_schedule_processing_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" = 'processing'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_unreconciled_terminal_idx": { + "name": "async_jobs_schedule_unreconciled_terminal_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" IN ('completed', 'failed', 'cancelled') AND COALESCE(\"async_jobs\".\"metadata\" ->> 'scheduleReconciled', 'false') <> 'true'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.audit_log": { + "name": "audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_email": { + "name": "actor_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_name": { + "name": "resource_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "audit_log_workspace_created_idx": { + "name": "audit_log_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_workspace_created_at_id_idx": { + "name": "audit_log_workspace_created_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_actor_created_idx": { + "name": "audit_log_actor_created_idx", + "columns": [ + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_org_level_created_at_id_idx": { + "name": "audit_log_org_level_created_at_id_idx", + "columns": [ + { + "expression": "(\"metadata\"->>'organizationId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"audit_log\".\"workspace_id\" IS NULL AND (\"audit_log\".\"metadata\"->>'organizationId') IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "audit_log_resource_idx": { + "name": "audit_log_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_action_idx": { + "name": "audit_log_action_idx", + "columns": [ + { + "expression": "action", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "audit_log_workspace_id_workspace_id_fk": { + "name": "audit_log_workspace_id_workspace_id_fk", + "tableFrom": "audit_log", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "audit_log_actor_id_user_id_fk": { + "name": "audit_log_actor_id_user_id_fk", + "tableFrom": "audit_log", + "tableTo": "user", + "columnsFrom": ["actor_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_license": { + "name": "aws_marketplace_license", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "license_arn": { + "name": "license_arn", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "product_code": { + "name": "product_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "customer_aws_account_id": { + "name": "customer_aws_account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agreement_id": { + "name": "agreement_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agreement_seen_at": { + "name": "agreement_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "renewed_agreement_id": { + "name": "renewed_agreement_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "aws_marketplace_license_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_verified_at": { + "name": "last_verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "last_verification_attempt_at": { + "name": "last_verification_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "license_event_received_at": { + "name": "license_event_received_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "claim_token_hash": { + "name": "claim_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_expires_at": { + "name": "claim_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "linked_by_user_id": { + "name": "linked_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_linked_at": { + "name": "organization_linked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "contact_email": { + "name": "contact_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "company_name": { + "name": "company_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "aws_marketplace_license_arn_unique": { + "name": "aws_marketplace_license_arn_unique", + "columns": [ + { + "expression": "license_arn", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_claim_token_hash_unique": { + "name": "aws_marketplace_license_claim_token_hash_unique", + "columns": [ + { + "expression": "claim_token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_agreement_id_idx": { + "name": "aws_marketplace_license_agreement_id_idx", + "columns": [ + { + "expression": "agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_renewed_agreement_id_idx": { + "name": "aws_marketplace_license_renewed_agreement_id_idx", + "columns": [ + { + "expression": "renewed_agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_account_product_idx": { + "name": "aws_marketplace_license_account_product_idx", + "columns": [ + { + "expression": "customer_aws_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "product_code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_last_attempt_idx": { + "name": "aws_marketplace_license_last_attempt_idx", + "columns": [ + { + "expression": "last_verification_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_organization_id_idx": { + "name": "aws_marketplace_license_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_linked_by_user_id_idx": { + "name": "aws_marketplace_license_linked_by_user_id_idx", + "columns": [ + { + "expression": "linked_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "aws_marketplace_license_organization_id_organization_id_fk": { + "name": "aws_marketplace_license_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_license", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "aws_marketplace_license_linked_by_user_id_user_id_fk": { + "name": "aws_marketplace_license_linked_by_user_id_user_id_fk", + "tableFrom": "aws_marketplace_license", + "tableTo": "user", + "columnsFrom": ["linked_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_usage_report": { + "name": "aws_marketplace_usage_report", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "license_id": { + "name": "license_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hour_start": { + "name": "hour_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "aws_marketplace_usage_report_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "metering_record_id": { + "name": "metering_record_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reported_at": { + "name": "reported_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "aws_marketplace_usage_report_license_dimension_hour_unique": { + "name": "aws_marketplace_usage_report_license_dimension_hour_unique", + "columns": [ + { + "expression": "license_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dimension", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "hour_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_usage_report_status_hour_idx": { + "name": "aws_marketplace_usage_report_status_hour_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "hour_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_usage_report_organization_id_idx": { + "name": "aws_marketplace_usage_report_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "aws_marketplace_usage_report_organization_id_organization_id_fk": { + "name": "aws_marketplace_usage_report_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_usage_report", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "aws_marketplace_usage_report_license_id_aws_marketplace_license_id_fk": { + "name": "aws_marketplace_usage_report_license_id_aws_marketplace_license_id_fk", + "tableFrom": "aws_marketplace_usage_report", + "tableTo": "aws_marketplace_license", + "columnsFrom": ["license_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_usage_tally": { + "name": "aws_marketplace_usage_tally", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "period_start": { + "name": "period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "counted_from": { + "name": "counted_from", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "cost_usd": { + "name": "cost_usd", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "units": { + "name": "units", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "aws_marketplace_usage_tally_organization_id_organization_id_fk": { + "name": "aws_marketplace_usage_tally_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_usage_tally", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "aws_marketplace_usage_tally_organization_id_dimension_period_start_pk": { + "name": "aws_marketplace_usage_tally_organization_id_dimension_period_start_pk", + "columns": ["organization_id", "dimension", "period_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.background_work_status": { + "name": "background_work_status", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "background_work_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "background_work_status_value", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "background_work_status_workspace_status_idx": { + "name": "background_work_status_workspace_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_workflow_status_idx": { + "name": "background_work_status_workflow_status_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_meta_child_ws_idx": { + "name": "background_work_status_meta_child_ws_idx", + "columns": [ + { + "expression": "(\"metadata\" ->> 'childWorkspaceId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_meta_other_ws_idx": { + "name": "background_work_status_meta_other_ws_idx", + "columns": [ + { + "expression": "(\"metadata\" ->> 'otherWorkspaceId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "background_work_status_workspace_id_workspace_id_fk": { + "name": "background_work_status_workspace_id_workspace_id_fk", + "tableFrom": "background_work_status", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "background_work_status_workflow_id_workflow_id_fk": { + "name": "background_work_status_workflow_id_workflow_id_fk", + "tableFrom": "background_work_status", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.changelog_change": { + "name": "changelog_change", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "release_id": { + "name": "release_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "changelog_change_release_position_unique": { + "name": "changelog_change_release_position_unique", + "columns": [ + { + "expression": "release_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "changelog_change_release_id_changelog_release_id_fk": { + "name": "changelog_change_release_id_changelog_release_id_fk", + "tableFrom": "changelog_change", + "tableTo": "changelog_release", + "columnsFrom": ["release_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "changelog_change_workflow_id_workflow_id_fk": { + "name": "changelog_change_workflow_id_workflow_id_fk", + "tableFrom": "changelog_change", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_change_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "changelog_change_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "changelog_change", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_change_chat_id_copilot_chats_id_fk": { + "name": "changelog_change_chat_id_copilot_chats_id_fk", + "tableFrom": "changelog_change", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.changelog_release": { + "name": "changelog_release", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version_major": { + "name": "version_major", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version_minor": { + "name": "version_minor", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version_patch": { + "name": "version_patch", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "bump_reason": { + "name": "bump_reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body_file_id": { + "name": "body_file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "published_at": { + "name": "published_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "changelog_release_workspace_version_unique": { + "name": "changelog_release_workspace_version_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_major", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_minor", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_patch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "changelog_release_body_file_unique": { + "name": "changelog_release_body_file_unique", + "columns": [ + { + "expression": "body_file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "changelog_release_workspace_published_idx": { + "name": "changelog_release_workspace_published_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "published_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "changelog_release_workspace_id_workspace_id_fk": { + "name": "changelog_release_workspace_id_workspace_id_fk", + "tableFrom": "changelog_release", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "changelog_release_body_file_id_workspace_files_id_fk": { + "name": "changelog_release_body_file_id_workspace_files_id_fk", + "tableFrom": "changelog_release", + "tableTo": "workspace_files", + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "changelog_release_created_by_user_id_fk": { + "name": "changelog_release_created_by_user_id_fk", + "tableFrom": "changelog_release", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_release_updated_by_user_id_fk": { + "name": "changelog_release_updated_by_user_id_fk", + "tableFrom": "changelog_release", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "changelog_release_version_check": { + "name": "changelog_release_version_check", + "value": "\"changelog_release\".\"version_major\" >= 0 AND \"changelog_release\".\"version_minor\" >= 0 AND \"changelog_release\".\"version_patch\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.chat": { + "name": "chat", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "customizations": { + "name": "customizations", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_emails": { + "name": "allowed_emails", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "output_configs": { + "name": "output_configs", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "include_thinking": { + "name": "include_thinking", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "include_tool_calls": { + "name": "include_tool_calls", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "identifier_idx": { + "name": "identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"chat\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_archived_at_partial_idx": { + "name": "chat_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_chat_on_workflow_id_archived_at": { + "name": "idx_chat_on_workflow_id_archived_at", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_user_id_idx": { + "name": "chat_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_workflow_id_workflow_id_fk": { + "name": "chat_workflow_id_workflow_id_fk", + "tableFrom": "chat", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_user_id_user_id_fk": { + "name": "chat_user_id_user_id_fk", + "tableFrom": "chat", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.client_credential_token": { + "name": "client_credential_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "encrypted_value": { + "name": "encrypted_value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token_digest": { + "name": "access_token_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "client_credential_token_expires_at_idx": { + "name": "client_credential_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"client_credential_token\".\"access_token_digest\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "client_credential_token_access_token_digest_idx": { + "name": "client_credential_token_access_token_digest_idx", + "columns": [ + { + "expression": "access_token_digest", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"client_credential_token\".\"access_token_digest\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_async_tool_calls": { + "name": "copilot_async_tool_calls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "checkpoint_id": { + "name": "checkpoint_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "tool_call_id": { + "name": "tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "args": { + "name": "args", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "executable_name": { + "name": "executable_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_workspace_id": { + "name": "target_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_args": { + "name": "approved_args", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "assistant_action": { + "name": "assistant_action", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "execution_retryable": { + "name": "execution_retryable", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "status": { + "name": "status", + "type": "copilot_async_tool_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "result": { + "name": "result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_decision": { + "name": "permission_decision", + "type": "copilot_tool_permission_decision", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "permission_decided_at": { + "name": "permission_decided_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_requested_at": { + "name": "permission_requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "pickup_deadline_at": { + "name": "pickup_deadline_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "persist_seq": { + "name": "persist_seq", + "type": "bigint", + "primaryKey": false, + "notNull": false, + "default": "nextval('copilot_async_tool_calls_persist_seq')" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "claimed_by": { + "name": "claimed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "browser_download_started_at": { + "name": "browser_download_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_started_at": { + "name": "execution_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_settled_at": { + "name": "execution_settled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_owner_token": { + "name": "execution_owner_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_lease_expires_at": { + "name": "execution_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execution_revoked_at": { + "name": "execution_revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execution_attempts": { + "name": "execution_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "execution_deadline_at": { + "name": "execution_deadline_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "client_workflow_execution_id": { + "name": "client_workflow_execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sandbox_processes": { + "name": "sandbox_processes", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_async_tool_calls_checkpoint_id_idx": { + "name": "copilot_async_tool_calls_checkpoint_id_idx", + "columns": [ + { + "expression": "checkpoint_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_status_idx": { + "name": "copilot_async_tool_calls_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_run_status_idx": { + "name": "copilot_async_tool_calls_run_status_idx", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_tool_call_id_unique": { + "name": "copilot_async_tool_calls_tool_call_id_unique", + "columns": [ + { + "expression": "tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_async_tool_calls_run_id_copilot_runs_id_fk": { + "name": "copilot_async_tool_calls_run_id_copilot_runs_id_fk", + "tableFrom": "copilot_async_tool_calls", + "tableTo": "copilot_runs", + "columnsFrom": ["run_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_async_tool_calls_checkpoint_id_copilot_run_checkpoints_id_fk": { + "name": "copilot_async_tool_calls_checkpoint_id_copilot_run_checkpoints_id_fk", + "tableFrom": "copilot_async_tool_calls", + "tableTo": "copilot_run_checkpoints", + "columnsFrom": ["checkpoint_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_chats": { + "name": "copilot_chats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "memory_space_id": { + "name": "memory_space_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "chat_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'copilot'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude-3-7-sonnet-latest'" + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_conversation_key": { + "name": "external_conversation_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_conversation_metadata": { + "name": "external_conversation_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "preview_yaml": { + "name": "preview_yaml", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "resources": { + "name": "resources", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "auto_allowed_tools": { + "name": "auto_allowed_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "pinned": { + "name": "pinned", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_chats_organization_id_idx": { + "name": "copilot_chats_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_external_conversation_unique": { + "name": "copilot_chats_external_conversation_unique", + "columns": [ + { + "expression": "external_conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"copilot_chats\".\"external_conversation_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_org_created_idx": { + "name": "copilot_chats_user_org_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_workflow_id_idx": { + "name": "copilot_chats_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workflow_idx": { + "name": "copilot_chats_user_workflow_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workspace_idx": { + "name": "copilot_chats_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_created_at_idx": { + "name": "copilot_chats_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_updated_at_idx": { + "name": "copilot_chats_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_workspace_created_at_id_idx": { + "name": "copilot_chats_workspace_created_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workspace_deleted_partial_idx": { + "name": "copilot_chats_user_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_chats\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_chats_user_id_user_id_fk": { + "name": "copilot_chats_user_id_user_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_workflow_id_workflow_id_fk": { + "name": "copilot_chats_workflow_id_workflow_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_workspace_id_workspace_id_fk": { + "name": "copilot_chats_workspace_id_workspace_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_organization_id_organization_id_fk": { + "name": "copilot_chats_organization_id_organization_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "copilot_chats_owner_check": { + "name": "copilot_chats_owner_check", + "value": "num_nonnulls(\"copilot_chats\".\"workspace_id\", \"copilot_chats\".\"organization_id\") <= 1" + }, + "copilot_chats_organization_workflow_check": { + "name": "copilot_chats_organization_workflow_check", + "value": "\"copilot_chats\".\"organization_id\" IS NULL OR \"copilot_chats\".\"workflow_id\" IS NULL" + } + }, + "isRLSEnabled": false + }, + "public.copilot_feedback": { + "name": "copilot_feedback", + "schema": "", + "columns": { + "feedback_id": { + "name": "feedback_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_query": { + "name": "user_query", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent_response": { + "name": "agent_response", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_positive": { + "name": "is_positive", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "feedback": { + "name": "feedback", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_yaml": { + "name": "workflow_yaml", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_feedback_user_id_idx": { + "name": "copilot_feedback_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_chat_id_idx": { + "name": "copilot_feedback_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_user_chat_idx": { + "name": "copilot_feedback_user_chat_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_is_positive_idx": { + "name": "copilot_feedback_is_positive_idx", + "columns": [ + { + "expression": "is_positive", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_created_at_idx": { + "name": "copilot_feedback_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_feedback_user_id_user_id_fk": { + "name": "copilot_feedback_user_id_user_id_fk", + "tableFrom": "copilot_feedback", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_feedback_chat_id_copilot_chats_id_fk": { + "name": "copilot_feedback_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_feedback", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_messages": { + "name": "copilot_messages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "display_content": { + "name": "display_content", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_messages_chat_message_unique": { + "name": "copilot_messages_chat_message_unique", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_created_at_idx": { + "name": "copilot_messages_chat_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_seq_idx": { + "name": "copilot_messages_chat_seq_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_stream_idx": { + "name": "copilot_messages_chat_stream_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "stream_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"stream_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_user_seq_idx": { + "name": "copilot_messages_chat_user_seq_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_user_created_at_idx": { + "name": "copilot_messages_chat_user_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user' AND \"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_user_created_at_idx": { + "name": "copilot_messages_user_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user' AND \"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_messages_chat_id_copilot_chats_id_fk": { + "name": "copilot_messages_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_messages", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_organization_request_stops": { + "name": "copilot_organization_request_stops", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stopped_at": { + "name": "stopped_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "copilot_organization_request_stops_user_id_user_id_fk": { + "name": "copilot_organization_request_stops_user_id_user_id_fk", + "tableFrom": "copilot_organization_request_stops", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_organization_request_stops_organization_id_organization_id_fk": { + "name": "copilot_organization_request_stops_organization_id_organization_id_fk", + "tableFrom": "copilot_organization_request_stops", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "copilot_organization_request_stops_user_id_organization_id_stream_id_pk": { + "name": "copilot_organization_request_stops_user_id_organization_id_stream_id_pk", + "columns": ["user_id", "organization_id", "stream_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_request_stops": { + "name": "copilot_request_stops", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stopped_at": { + "name": "stopped_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "copilot_request_stops_user_id_user_id_fk": { + "name": "copilot_request_stops_user_id_user_id_fk", + "tableFrom": "copilot_request_stops", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_request_stops_workspace_id_workspace_id_fk": { + "name": "copilot_request_stops_workspace_id_workspace_id_fk", + "tableFrom": "copilot_request_stops", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "copilot_request_stops_user_id_workspace_id_stream_id_pk": { + "name": "copilot_request_stops_user_id_workspace_id_stream_id_pk", + "columns": ["user_id", "workspace_id", "stream_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_run_checkpoints": { + "name": "copilot_run_checkpoints", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "pending_tool_call_id": { + "name": "pending_tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "conversation_snapshot": { + "name": "conversation_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "agent_state": { + "name": "agent_state", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "provider_request": { + "name": "provider_request", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_run_checkpoints_pending_tool_call_id_idx": { + "name": "copilot_run_checkpoints_pending_tool_call_id_idx", + "columns": [ + { + "expression": "pending_tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_run_checkpoints_run_pending_tool_unique": { + "name": "copilot_run_checkpoints_run_pending_tool_unique", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "pending_tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_run_checkpoints_run_id_copilot_runs_id_fk": { + "name": "copilot_run_checkpoints_run_id_copilot_runs_id_fk", + "tableFrom": "copilot_run_checkpoints", + "tableTo": "copilot_runs", + "columnsFrom": ["run_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_runs": { + "name": "copilot_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_execution_version": { + "name": "tool_execution_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tool_admission_closed_at": { + "name": "tool_admission_closed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "parent_run_id": { + "name": "parent_run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agent": { + "name": "agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "copilot_run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "request_context": { + "name": "request_context", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "desktop_device_id": { + "name": "desktop_device_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "copilot_runs_parent_run_id_idx": { + "name": "copilot_runs_parent_run_id_idx", + "columns": [ + { + "expression": "parent_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_chat_started_at_idx": { + "name": "copilot_runs_chat_started_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_user_id_idx": { + "name": "copilot_runs_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_workflow_id_idx": { + "name": "copilot_runs_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_status_idx": { + "name": "copilot_runs_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_chat_execution_idx": { + "name": "copilot_runs_chat_execution_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_execution_started_at_idx": { + "name": "copilot_runs_execution_started_at_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_workspace_completed_at_id_idx": { + "name": "copilot_runs_workspace_completed_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"completed_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_stream_id_unique": { + "name": "copilot_runs_stream_id_unique", + "columns": [ + { + "expression": "stream_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_desktop_device_started_at_idx": { + "name": "copilot_runs_desktop_device_started_at_idx", + "columns": [ + { + "expression": "desktop_device_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_runs\".\"desktop_device_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_runs_chat_id_copilot_chats_id_fk": { + "name": "copilot_runs_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_user_id_user_id_fk": { + "name": "copilot_runs_user_id_user_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_workflow_id_workflow_id_fk": { + "name": "copilot_runs_workflow_id_workflow_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_workspace_id_workspace_id_fk": { + "name": "copilot_runs_workspace_id_workspace_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_organization_id_organization_id_fk": { + "name": "copilot_runs_organization_id_organization_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_desktop_device_id_desktop_devices_id_fk": { + "name": "copilot_runs_desktop_device_id_desktop_devices_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "desktop_devices", + "columnsFrom": ["desktop_device_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_service_usage": { + "name": "copilot_service_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tool_call_id": { + "name": "tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "service": { + "name": "service", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cost_usd": { + "name": "cost_usd", + "type": "numeric(12, 8)", + "primaryKey": false, + "notNull": false + }, + "worker_origin": { + "name": "worker_origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "delivered_at": { + "name": "delivered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "copilot_service_usage_pending_idx": { + "name": "copilot_service_usage_pending_idx", + "columns": [ + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "delivered_at IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.credential": { + "name": "credential", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "slack_app_id": { + "name": "slack_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "credential_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "unredacted": { + "name": "unredacted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_key": { + "name": "env_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_owner_user_id": { + "name": "env_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_service_account_key": { + "name": "encrypted_service_account_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_personal_token": { + "name": "encrypted_personal_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "authorization_app_id": { + "name": "authorization_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_enrollment_id": { + "name": "credential_group_enrollment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_option_id": { + "name": "credential_group_option_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_server_id": { + "name": "mcp_server_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_oauth_config_version": { + "name": "mcp_oauth_config_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "managed_oauth_scope_version": { + "name": "managed_oauth_scope_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "provider_subject_id": { + "name": "provider_subject_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_tenant_id": { + "name": "provider_tenant_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "managed_oauth_status": { + "name": "managed_oauth_status", + "type": "managed_oauth_credential_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "granted_scopes": { + "name": "granted_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "provider_metadata": { + "name": "provider_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "encrypted_oauth_token_set": { + "name": "encrypted_oauth_token_set", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_tools": { + "name": "mcp_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "mcp_tools_refreshed_at": { + "name": "mcp_tools_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_refreshed_at": { + "name": "last_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_organization_id_idx": { + "name": "credential_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_organization_account_unique": { + "name": "credential_organization_account_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"account_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_org_personal_token_unique": { + "name": "credential_org_personal_token_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'personal_token'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_id_idx": { + "name": "credential_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_type_idx": { + "name": "credential_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_provider_id_idx": { + "name": "credential_provider_id_idx", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_account_id_idx": { + "name": "credential_account_id_idx", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_env_owner_user_id_idx": { + "name": "credential_env_owner_user_id_idx", + "columns": [ + { + "expression": "env_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_idx": { + "name": "credential_group_enrollment_idx", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_mcp_server_idx": { + "name": "credential_mcp_server_idx", + "columns": [ + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_option_identity_unique": { + "name": "credential_group_option_identity_unique", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "credential_group_option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_tenant_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'managed_oauth'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_managed_mcp_enrollment_server_identity_unique": { + "name": "credential_managed_mcp_enrollment_server_identity_unique", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_subject_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_tenant_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'managed_mcp'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_account_unique": { + "name": "credential_workspace_account_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "account_id IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_env_unique": { + "name": "credential_workspace_env_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "type = 'env_workspace'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_personal_env_unique": { + "name": "credential_workspace_personal_env_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "type = 'env_personal'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_workspace_id_workspace_id_fk": { + "name": "credential_workspace_id_workspace_id_fk", + "tableFrom": "credential", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_organization_id_organization_id_fk": { + "name": "credential_organization_id_organization_id_fk", + "tableFrom": "credential", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_slack_app_id_slack_app_id_fk": { + "name": "credential_slack_app_id_slack_app_id_fk", + "tableFrom": "credential", + "tableTo": "slack_app", + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "credential_account_id_account_id_fk": { + "name": "credential_account_id_account_id_fk", + "tableFrom": "credential", + "tableTo": "account", + "columnsFrom": ["account_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_env_owner_user_id_user_id_fk": { + "name": "credential_env_owner_user_id_user_id_fk", + "tableFrom": "credential", + "tableTo": "user", + "columnsFrom": ["env_owner_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_credential_group_enrollment_id_credential_group_enrollment_id_fk": { + "name": "credential_credential_group_enrollment_id_credential_group_enrollment_id_fk", + "tableFrom": "credential", + "tableTo": "credential_group_enrollment", + "columnsFrom": ["credential_group_enrollment_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_mcp_server_id_mcp_servers_id_fk": { + "name": "credential_mcp_server_id_mcp_servers_id_fk", + "tableFrom": "credential", + "tableTo": "mcp_servers", + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_created_by_user_id_fk": { + "name": "credential_created_by_user_id_fk", + "tableFrom": "credential", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_owner_check": { + "name": "credential_owner_check", + "value": "num_nonnulls(\"credential\".\"workspace_id\", \"credential\".\"organization_id\") = 1" + }, + "credential_organization_type_check": { + "name": "credential_organization_type_check", + "value": "\"credential\".\"organization_id\" IS NULL OR \"credential\".\"type\" IN ('oauth', 'managed_oauth', 'managed_mcp', 'service_account', 'personal_token')" + }, + "credential_personal_token_source_check": { + "name": "credential_personal_token_source_check", + "value": "(type::text <> 'personal_token') OR (\n created_by IS NOT NULL\n AND provider_id IS NOT NULL\n AND provider_id = 'gitlab'\n AND provider_subject_id IS NOT NULL\n AND provider_tenant_id IS NOT NULL\n AND encrypted_personal_token IS NOT NULL\n AND granted_scopes IS NOT NULL\n AND cardinality(granted_scopes) > 0\n AND account_id IS NULL\n AND env_key IS NULL\n AND env_owner_user_id IS NULL\n AND authorization_app_id IS NULL\n AND encrypted_oauth_token_set IS NULL\n AND encrypted_service_account_key IS NULL\n AND unredacted = false\n )" + }, + "credential_oauth_source_check": { + "name": "credential_oauth_source_check", + "value": "(type <> 'oauth') OR (account_id IS NOT NULL AND provider_id IS NOT NULL)" + }, + "credential_managed_oauth_source_check": { + "name": "credential_managed_oauth_source_check", + "value": "(type::text <> 'managed_oauth') OR (\n account_id IS NULL\n AND provider_id IS NOT NULL\n AND authorization_app_id IS NOT NULL\n AND provider_subject_id IS NOT NULL\n AND managed_oauth_status IS NOT NULL\n AND granted_scopes IS NOT NULL\n AND encrypted_oauth_token_set IS NOT NULL\n AND granted_at IS NOT NULL\n )" + }, + "credential_managed_oauth_group_binding_check": { + "name": "credential_managed_oauth_group_binding_check", + "value": "(type::text <> 'managed_oauth') OR (\n credential_group_enrollment_id IS NOT NULL\n AND credential_group_option_id IS NOT NULL\n AND managed_oauth_scope_version IS NOT NULL\n AND managed_oauth_scope_version > 0\n )" + }, + "credential_managed_mcp_source_check": { + "name": "credential_managed_mcp_source_check", + "value": "(type::text <> 'managed_mcp') OR (\n id LIKE 'mcp-cg-%'\n AND account_id IS NULL\n AND provider_id IS NULL\n AND authorization_app_id IS NULL\n AND credential_group_enrollment_id IS NOT NULL\n AND credential_group_option_id IS NULL\n AND mcp_server_id IS NOT NULL\n AND managed_oauth_status IS NOT NULL\n AND (managed_oauth_status <> 'active' OR (\n encrypted_oauth_token_set IS NOT NULL\n AND mcp_tools IS NOT NULL\n ))\n AND granted_at IS NOT NULL\n AND managed_oauth_scope_version IS NULL\n AND granted_scopes IS NULL\n AND provider_metadata IS NULL\n AND created_by IS NULL\n AND env_key IS NULL\n AND env_owner_user_id IS NULL\n AND encrypted_service_account_key IS NULL\n AND unredacted = false\n )" + }, + "credential_creator_source_check": { + "name": "credential_creator_source_check", + "value": "(type::text = 'managed_mcp') OR created_by IS NOT NULL" + }, + "credential_workspace_env_source_check": { + "name": "credential_workspace_env_source_check", + "value": "(type <> 'env_workspace') OR (env_key IS NOT NULL AND env_owner_user_id IS NULL)" + }, + "credential_personal_env_source_check": { + "name": "credential_personal_env_source_check", + "value": "(type <> 'env_personal') OR (env_key IS NOT NULL AND env_owner_user_id IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.credential_group": { + "name": "credential_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "public_id": { + "name": "public_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "encrypted_provider_configuration": { + "name": "encrypted_provider_configuration", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "credential_group_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_organization_unique": { + "name": "credential_group_organization_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_public_id_unique": { + "name": "credential_group_public_id_unique", + "columns": [ + { + "expression": "public_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_workspace_unique": { + "name": "credential_group_workspace_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_workspace_id_workspace_id_fk": { + "name": "credential_group_workspace_id_workspace_id_fk", + "tableFrom": "credential_group", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_organization_id_organization_id_fk": { + "name": "credential_group_organization_id_organization_id_fk", + "tableFrom": "credential_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_created_by_user_id_fk": { + "name": "credential_group_created_by_user_id_fk", + "tableFrom": "credential_group", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_owner_check": { + "name": "credential_group_owner_check", + "value": "num_nonnulls(\"credential_group\".\"workspace_id\", \"credential_group\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.credential_group_enrollment": { + "name": "credential_group_enrollment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "credential_group_enrollment_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'invited'" + }, + "invitation_token_hash": { + "name": "invitation_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invitation_expires_at": { + "name": "invitation_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "invited_at": { + "name": "invited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_delivery_error": { + "name": "last_delivery_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_enrollment_group_user_unique": { + "name": "credential_group_enrollment_group_user_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential_group_enrollment\".\"user_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_user_id_idx": { + "name": "credential_group_enrollment_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_email_unique": { + "name": "credential_group_enrollment_group_email_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_invitation_token_hash_unique": { + "name": "credential_group_enrollment_invitation_token_hash_unique", + "columns": [ + { + "expression": "invitation_token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_status_idx": { + "name": "credential_group_enrollment_group_status_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_invited_at_id_idx": { + "name": "credential_group_enrollment_group_invited_at_id_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "invited_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_enrollment_credential_group_id_credential_group_id_fk": { + "name": "credential_group_enrollment_credential_group_id_credential_group_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_enrollment_user_id_user_id_fk": { + "name": "credential_group_enrollment_user_id_user_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_enrollment_created_by_user_id_fk": { + "name": "credential_group_enrollment_created_by_user_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_enrollment_normalized_email_check": { + "name": "credential_group_enrollment_normalized_email_check", + "value": "\"credential_group_enrollment\".\"email\" = lower(btrim(\"credential_group_enrollment\".\"email\")) AND length(\"credential_group_enrollment\".\"email\") BETWEEN 3 AND 320" + }, + "credential_group_enrollment_invitation_token_hash_length_check": { + "name": "credential_group_enrollment_invitation_token_hash_length_check", + "value": "length(\"credential_group_enrollment\".\"invitation_token_hash\") = 64" + } + }, + "isRLSEnabled": false + }, + "public.credential_group_enrollment_link": { + "name": "credential_group_enrollment_link", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "enrollment_id": { + "name": "enrollment_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "credential_group_enrollment_link_purpose", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "option_id": { + "name": "option_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_enrollment_link_token_hash_unique": { + "name": "credential_group_enrollment_link_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_link_enrollment_id_idx": { + "name": "credential_group_enrollment_link_enrollment_id_idx", + "columns": [ + { + "expression": "enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_enrollment_link_enrollment_id_credential_group_enrollment_id_fk": { + "name": "credential_group_enrollment_link_enrollment_id_credential_group_enrollment_id_fk", + "tableFrom": "credential_group_enrollment_link", + "tableTo": "credential_group_enrollment", + "columnsFrom": ["enrollment_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_enrollment_link_token_hash_length_check": { + "name": "credential_group_enrollment_link_token_hash_length_check", + "value": "length(\"credential_group_enrollment_link\".\"token_hash\") = 64" + } + }, + "isRLSEnabled": false + }, + "public.credential_member": { + "name": "credential_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "credential_member_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "status": { + "name": "status", + "type": "credential_member_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "joined_at": { + "name": "joined_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_member_user_id_idx": { + "name": "credential_member_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_role_idx": { + "name": "credential_member_role_idx", + "columns": [ + { + "expression": "role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_status_idx": { + "name": "credential_member_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_unique": { + "name": "credential_member_unique", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_member_credential_id_credential_id_fk": { + "name": "credential_member_credential_id_credential_id_fk", + "tableFrom": "credential_member", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_member_user_id_user_id_fk": { + "name": "credential_member_user_id_user_id_fk", + "tableFrom": "credential_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_member_invited_by_user_id_fk": { + "name": "credential_member_invited_by_user_id_fk", + "tableFrom": "credential_member", + "tableTo": "user", + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_block": { + "name": "custom_block", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "icon_url": { + "name": "icon_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inputs": { + "name": "inputs", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "outputs": { + "name": "outputs", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "trace_child_runs": { + "name": "trace_child_runs", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "custom_block_workflow_id_idx": { + "name": "custom_block_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "custom_block_organization_type_unique": { + "name": "custom_block_organization_type_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "custom_block_organization_id_organization_id_fk": { + "name": "custom_block_organization_id_organization_id_fk", + "tableFrom": "custom_block", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_block_workflow_id_workflow_id_fk": { + "name": "custom_block_workflow_id_workflow_id_fk", + "tableFrom": "custom_block", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_block_created_by_user_id_fk": { + "name": "custom_block_created_by_user_id_fk", + "tableFrom": "custom_block", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_tools": { + "name": "custom_tools", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schema": { + "name": "schema", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "custom_tools_workspace_title_unique": { + "name": "custom_tools_workspace_title_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "custom_tools_workspace_id_workspace_id_fk": { + "name": "custom_tools_workspace_id_workspace_id_fk", + "tableFrom": "custom_tools", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_tools_user_id_user_id_fk": { + "name": "custom_tools_user_id_user_id_fk", + "tableFrom": "custom_tools", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.dashboard": { + "name": "dashboard", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "dashboard_workspace_id_unique": { + "name": "dashboard_workspace_id_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "dashboard_workspace_id_workspace_id_fk": { + "name": "dashboard_workspace_id_workspace_id_fk", + "tableFrom": "dashboard", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "dashboard_created_by_user_id_fk": { + "name": "dashboard_created_by_user_id_fk", + "tableFrom": "dashboard", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "dashboard_updated_by_user_id_fk": { + "name": "dashboard_updated_by_user_id_fk", + "tableFrom": "dashboard", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.data_drain_runs": { + "name": "data_drain_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "drain_id": { + "name": "drain_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "data_drain_run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "data_drain_run_trigger", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "rows_exported": { + "name": "rows_exported", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "bytes_written": { + "name": "bytes_written", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cursor_before": { + "name": "cursor_before", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cursor_after": { + "name": "cursor_after", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locators": { + "name": "locators", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": { + "data_drain_runs_drain_started_idx": { + "name": "data_drain_runs_drain_started_idx", + "columns": [ + { + "expression": "drain_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "data_drain_runs_drain_id_data_drains_id_fk": { + "name": "data_drain_runs_drain_id_data_drains_id_fk", + "tableFrom": "data_drain_runs", + "tableTo": "data_drains", + "columnsFrom": ["drain_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.data_drains": { + "name": "data_drains", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "data_drain_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "destination_type": { + "name": "destination_type", + "type": "data_drain_destination", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "destination_config": { + "name": "destination_config", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "destination_credentials": { + "name": "destination_credentials", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schedule_cadence": { + "name": "schedule_cadence", + "type": "data_drain_cadence", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_success_at": { + "name": "last_success_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "data_drains_due_idx": { + "name": "data_drains_due_idx", + "columns": [ + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "data_drains_org_name_unique": { + "name": "data_drains_org_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "data_drains_organization_id_organization_id_fk": { + "name": "data_drains_organization_id_organization_id_fk", + "tableFrom": "data_drains", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "data_drains_created_by_user_id_fk": { + "name": "data_drains_created_by_user_id_fk", + "tableFrom": "data_drains", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deleted_account_identity": { + "name": "deleted_account_identity", + "schema": "", + "columns": { + "identity_hash": { + "name": "identity_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "deleted_account_identity_expires_at_idx": { + "name": "deleted_account_identity_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.desktop_devices": { + "name": "desktop_devices", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_version": { + "name": "app_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "capabilities": { + "name": "capabilities", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "desktop_devices_user_id_idx": { + "name": "desktop_devices_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "desktop_devices_session_id_idx": { + "name": "desktop_devices_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "desktop_devices_user_id_user_id_fk": { + "name": "desktop_devices_user_id_user_id_fk", + "tableFrom": "desktop_devices", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "desktop_devices_session_id_session_id_fk": { + "name": "desktop_devices_session_id_session_id_fk", + "tableFrom": "desktop_devices", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.docs_embeddings": { + "name": "docs_embeddings", + "schema": "", + "columns": { + "chunk_id": { + "name": "chunk_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chunk_text": { + "name": "chunk_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_document": { + "name": "source_document", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_link": { + "name": "source_link", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "header_text": { + "name": "header_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "header_level": { + "name": "header_level", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": true + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "chunk_text_tsv": { + "name": "chunk_text_tsv", + "type": "tsvector", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "to_tsvector('english', \"docs_embeddings\".\"chunk_text\")", + "type": "stored" + } + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "docs_emb_source_document_idx": { + "name": "docs_emb_source_document_idx", + "columns": [ + { + "expression": "source_document", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_header_level_idx": { + "name": "docs_emb_header_level_idx", + "columns": [ + { + "expression": "header_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_source_header_idx": { + "name": "docs_emb_source_header_idx", + "columns": [ + { + "expression": "source_document", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "header_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_model_idx": { + "name": "docs_emb_model_idx", + "columns": [ + { + "expression": "embedding_model", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_created_at_idx": { + "name": "docs_emb_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_embedding_vector_hnsw_idx": { + "name": "docs_embedding_vector_hnsw_idx", + "columns": [ + { + "expression": "embedding", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "vector_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "docs_emb_metadata_gin_idx": { + "name": "docs_emb_metadata_gin_idx", + "columns": [ + { + "expression": "metadata", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "docs_emb_chunk_text_fts_idx": { + "name": "docs_emb_chunk_text_fts_idx", + "columns": [ + { + "expression": "chunk_text_tsv", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "docs_embedding_not_null_check": { + "name": "docs_embedding_not_null_check", + "value": "\"embedding\" IS NOT NULL" + }, + "docs_header_level_check": { + "name": "docs_header_level_check", + "value": "\"header_level\" >= 1 AND \"header_level\" <= 6" + } + }, + "isRLSEnabled": false + }, + "public.document": { + "name": "document", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_url": { + "name": "file_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file_size": { + "name": "file_size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "file_sha256": { + "name": "file_sha256", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "character_count": { + "name": "character_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "processing_status": { + "name": "processing_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "processing_attempts": { + "name": "processing_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "processing_queued_at": { + "name": "processing_queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_queue_token": { + "name": "processing_queue_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_started_at": { + "name": "processing_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_deferred_until": { + "name": "processing_deferred_until", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_completed_at": { + "name": "processing_completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_error": { + "name": "processing_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_recovery_after": { + "name": "processing_recovery_after", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "user_excluded": { + "name": "user_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "tag1": { + "name": "tag1", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag2": { + "name": "tag2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag3": { + "name": "tag3", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag4": { + "name": "tag4", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag5": { + "name": "tag5", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag6": { + "name": "tag6", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag7": { + "name": "tag7", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "number1": { + "name": "number1", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number2": { + "name": "number2", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number3": { + "name": "number3", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number4": { + "name": "number4", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number5": { + "name": "number5", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "date1": { + "name": "date1", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "date2": { + "name": "date2", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "boolean1": { + "name": "boolean1", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean2": { + "name": "boolean2", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean3": { + "name": "boolean3", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_url": { + "name": "source_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "acl": { + "name": "acl", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{ws}'::text[]" + }, + "acl_requirements": { + "name": "acl_requirements", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "acl_verified_at": { + "name": "acl_verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_modified_at": { + "name": "source_modified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_seen_at": { + "name": "source_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "doc_uploaded_by_idx": { + "name": "doc_uploaded_by_idx", + "columns": [ + { + "expression": "uploaded_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"uploaded_by\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_kb_source_modified_idx": { + "name": "doc_kb_source_modified_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_modified_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_acl_gin_idx": { + "name": "doc_acl_gin_idx", + "columns": [ + { + "expression": "acl", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "array_ops" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "gin", + "with": {} + }, + "doc_filename_idx": { + "name": "doc_filename_idx", + "columns": [ + { + "expression": "filename", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_processing_status_idx": { + "name": "doc_processing_status_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "processing_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_processing_recovery_idx": { + "name": "doc_connector_processing_recovery_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"processing_status\" IN ('pending', 'processing', 'failed') AND \"document\".\"connector_id\" IS NOT NULL AND \"document\".\"content_hash\" IS NOT NULL AND \"document\".\"storage_key\" IS NOT NULL AND \"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_connector_processing_status_idx": { + "name": "doc_connector_processing_status_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "processing_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"processing_status\" IN ('pending', 'processing', 'failed') AND \"document\".\"connector_id\" IS NOT NULL AND \"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_external_id_idx": { + "name": "doc_connector_external_id_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_source_lookup_idx": { + "name": "doc_connector_source_lookup_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_reconciliation_v2_idx": { + "name": "doc_connector_reconciliation_v2_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_active_kb_token_count_idx": { + "name": "doc_active_kb_token_count_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "token_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_storage_key_idx": { + "name": "doc_storage_key_idx", + "columns": [ + { + "expression": "storage_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"storage_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_archived_at_partial_idx": { + "name": "doc_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_deleted_at_partial_idx": { + "name": "doc_deleted_at_partial_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_tombstone_idx": { + "name": "doc_connector_tombstone_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"archived_at\" IS NULL AND (\"document\".\"deleted_at\" IS NOT NULL OR \"document\".\"content_hash\" IS NULL)", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_live_idx": { + "name": "doc_connector_live_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag1_lower_idx": { + "name": "doc_kb_tag1_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag1\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag2_lower_idx": { + "name": "doc_kb_tag2_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag2\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag3_lower_idx": { + "name": "doc_kb_tag3_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag3\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag4_lower_idx": { + "name": "doc_kb_tag4_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag4\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag5_lower_idx": { + "name": "doc_kb_tag5_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag5\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag6_lower_idx": { + "name": "doc_kb_tag6_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag6\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag7_lower_idx": { + "name": "doc_kb_tag7_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag7\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number1_idx": { + "name": "doc_number1_idx", + "columns": [ + { + "expression": "number1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number2_idx": { + "name": "doc_number2_idx", + "columns": [ + { + "expression": "number2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number3_idx": { + "name": "doc_number3_idx", + "columns": [ + { + "expression": "number3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number4_idx": { + "name": "doc_number4_idx", + "columns": [ + { + "expression": "number4", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number5_idx": { + "name": "doc_number5_idx", + "columns": [ + { + "expression": "number5", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_date1_idx": { + "name": "doc_date1_idx", + "columns": [ + { + "expression": "date1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_date2_idx": { + "name": "doc_date2_idx", + "columns": [ + { + "expression": "date2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_boolean1_idx": { + "name": "doc_boolean1_idx", + "columns": [ + { + "expression": "boolean1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_boolean2_idx": { + "name": "doc_boolean2_idx", + "columns": [ + { + "expression": "boolean2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_boolean3_idx": { + "name": "doc_boolean3_idx", + "columns": [ + { + "expression": "boolean3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "document_knowledge_base_id_knowledge_base_id_fk": { + "name": "document_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "document", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "document_connector_id_knowledge_connector_id_fk": { + "name": "document_connector_id_knowledge_connector_id_fk", + "tableFrom": "document", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "document_uploaded_by_user_id_fk": { + "name": "document_uploaded_by_user_id_fk", + "tableFrom": "document", + "tableTo": "user", + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "doc_acl_token_shape_check": { + "name": "doc_acl_token_shape_check", + "value": "array_position(\"document\".\"acl\", NULL) IS NULL AND (cardinality(\"document\".\"acl\") = 0 OR (cardinality(\"document\".\"acl\") = array_length(string_to_array(array_to_string(\"document\".\"acl\", E'\\n'), E'\\n'), 1) AND array_to_string(\"document\".\"acl\", E'\\n') ~ '^((ws|pub|link|u:[^\\nA-Z]+@[^\\nA-Z]+|[gs]:[^\\n:]+:[^\\n:]+:[^\\n]+)(\\n(ws|pub|link|u:[^\\nA-Z]+@[^\\nA-Z]+|[gs]:[^\\n:]+:[^\\n:]+:[^\\n]+))*)$'))" + } + }, + "isRLSEnabled": false + }, + "public.document_secret_provenance": { + "name": "document_secret_provenance", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "document_secret_provenance_document_id_document_id_fk": { + "name": "document_secret_provenance_document_id_document_id_fk", + "tableFrom": "document_secret_provenance", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "document_secret_provenance_status_check": { + "name": "document_secret_provenance_status_check", + "value": "\"document_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.embedding": { + "name": "embedding", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chunk_index": { + "name": "chunk_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "chunk_hash": { + "name": "chunk_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "content_length": { + "name": "content_length", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "embedding_384": { + "name": "embedding_384", + "type": "vector(384)", + "primaryKey": false, + "notNull": false + }, + "embedding_768": { + "name": "embedding_768", + "type": "vector(768)", + "primaryKey": false, + "notNull": false + }, + "embedding_1024": { + "name": "embedding_1024", + "type": "vector(1024)", + "primaryKey": false, + "notNull": false + }, + "embedding_3072": { + "name": "embedding_3072", + "type": "vector(3072)", + "primaryKey": false, + "notNull": false + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "start_offset": { + "name": "start_offset", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "end_offset": { + "name": "end_offset", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "tag1": { + "name": "tag1", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag2": { + "name": "tag2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag3": { + "name": "tag3", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag4": { + "name": "tag4", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag5": { + "name": "tag5", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag6": { + "name": "tag6", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag7": { + "name": "tag7", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "number1": { + "name": "number1", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number2": { + "name": "number2", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number3": { + "name": "number3", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number4": { + "name": "number4", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number5": { + "name": "number5", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "date1": { + "name": "date1", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "date2": { + "name": "date2", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "boolean1": { + "name": "boolean1", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean2": { + "name": "boolean2", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean3": { + "name": "boolean3", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "content_tsv": { + "name": "content_tsv", + "type": "tsvector", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "to_tsvector('english', \"embedding\".\"content\")", + "type": "stored" + } + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "emb_doc_chunk_idx": { + "name": "emb_doc_chunk_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chunk_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_model_idx": { + "name": "emb_kb_model_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "embedding_model", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_enabled_idx": { + "name": "emb_kb_enabled_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_doc_enabled_idx": { + "name": "emb_doc_enabled_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag1_lower_idx": { + "name": "emb_kb_tag1_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag1\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag2_lower_idx": { + "name": "emb_kb_tag2_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag2\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag3_lower_idx": { + "name": "emb_kb_tag3_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag3\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag4_lower_idx": { + "name": "emb_kb_tag4_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag4\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag5_lower_idx": { + "name": "emb_kb_tag5_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag5\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag6_lower_idx": { + "name": "emb_kb_tag6_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag6\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag7_lower_idx": { + "name": "emb_kb_tag7_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag7\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number1_idx": { + "name": "emb_number1_idx", + "columns": [ + { + "expression": "number1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number2_idx": { + "name": "emb_number2_idx", + "columns": [ + { + "expression": "number2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number3_idx": { + "name": "emb_number3_idx", + "columns": [ + { + "expression": "number3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number4_idx": { + "name": "emb_number4_idx", + "columns": [ + { + "expression": "number4", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number5_idx": { + "name": "emb_number5_idx", + "columns": [ + { + "expression": "number5", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_date1_idx": { + "name": "emb_date1_idx", + "columns": [ + { + "expression": "date1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "emb_date2_idx": { + "name": "emb_date2_idx", + "columns": [ + { + "expression": "date2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "emb_boolean1_idx": { + "name": "emb_boolean1_idx", + "columns": [ + { + "expression": "boolean1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_boolean2_idx": { + "name": "emb_boolean2_idx", + "columns": [ + { + "expression": "boolean2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_boolean3_idx": { + "name": "emb_boolean3_idx", + "columns": [ + { + "expression": "boolean3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_content_fts_idx": { + "name": "emb_content_fts_idx", + "columns": [ + { + "expression": "content_tsv", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": { + "fastupdate": "off" + } + } + }, + "foreignKeys": { + "embedding_knowledge_base_id_knowledge_base_id_fk": { + "name": "embedding_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "embedding", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "embedding_document_id_document_id_fk": { + "name": "embedding_document_id_document_id_fk", + "tableFrom": "embedding", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_width_check": { + "name": "embedding_width_check", + "value": "num_nonnulls(\"embedding\", \"embedding_384\", \"embedding_768\", \"embedding_1024\", \"embedding_3072\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.embedding_search": { + "name": "embedding_search", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "acl": { + "name": "acl", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "binary": { + "name": "binary", + "type": "bit(1536)", + "primaryKey": false, + "notNull": false + }, + "binary_384": { + "name": "binary_384", + "type": "bit(384)", + "primaryKey": false, + "notNull": false + }, + "binary_768": { + "name": "binary_768", + "type": "bit(768)", + "primaryKey": false, + "notNull": false + }, + "binary_1024": { + "name": "binary_1024", + "type": "bit(1024)", + "primaryKey": false, + "notNull": false + }, + "binary_3072": { + "name": "binary_3072", + "type": "bit(3072)", + "primaryKey": false, + "notNull": false + }, + "vector": { + "name": "vector", + "type": "halfvec(1536)", + "primaryKey": false, + "notNull": false + }, + "vector_384": { + "name": "vector_384", + "type": "halfvec(384)", + "primaryKey": false, + "notNull": false + }, + "vector_512": { + "name": "vector_512", + "type": "halfvec(512)", + "primaryKey": false, + "notNull": false + }, + "vector_768": { + "name": "vector_768", + "type": "halfvec(768)", + "primaryKey": false, + "notNull": false + }, + "vector_1024": { + "name": "vector_1024", + "type": "halfvec(1024)", + "primaryKey": false, + "notNull": false + }, + "vector_3072": { + "name": "vector_3072", + "type": "halfvec(3072)", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "embedding_search_kb_idx": { + "name": "embedding_search_kb_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "embedding_search_document_lookup_idx": { + "name": "embedding_search_document_lookup_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"embedding_search\".\"enabled\"", + "concurrently": true, + "method": "btree", + "with": {} + }, + "embedding_search_cosine_hnsw_idx": { + "name": "embedding_search_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_512_cosine_hnsw_idx": { + "name": "embedding_search_512_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_512", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_384_cosine_hnsw_idx": { + "name": "embedding_search_384_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_384", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_768_cosine_hnsw_idx": { + "name": "embedding_search_768_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_768", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_1024_cosine_hnsw_idx": { + "name": "embedding_search_1024_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_1024", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_3072_cosine_hnsw_idx": { + "name": "embedding_search_3072_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_3072", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + } + }, + "foreignKeys": { + "embedding_search_id_embedding_id_fk": { + "name": "embedding_search_id_embedding_id_fk", + "tableFrom": "embedding_search", + "tableTo": "embedding", + "columnsFrom": ["id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_search_width_check": { + "name": "embedding_search_width_check", + "value": "num_nonnulls(\"binary\", \"binary_384\", \"binary_768\", \"binary_1024\", \"binary_3072\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.embedding_secret_provenance": { + "name": "embedding_secret_provenance", + "schema": "", + "columns": { + "embedding_id": { + "name": "embedding_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "embedding_secret_provenance_embedding_id_embedding_id_fk": { + "name": "embedding_secret_provenance_embedding_id_embedding_id_fk", + "tableFrom": "embedding_secret_provenance", + "tableTo": "embedding", + "columnsFrom": ["embedding_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_secret_provenance_status_check": { + "name": "embedding_secret_provenance_status_check", + "value": "\"embedding_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.enterprise_seat_true_up": { + "name": "enterprise_seat_true_up", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "subscription_id": { + "name": "subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "window_start": { + "name": "window_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "window_end": { + "name": "window_end", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "peak_extra_seats": { + "name": "peak_extra_seats", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "seat_price_cents": { + "name": "seat_price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "amount_cents": { + "name": "amount_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "billed_at": { + "name": "billed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "enterprise_seat_true_up_subscription_window_unique": { + "name": "enterprise_seat_true_up_subscription_window_unique", + "columns": [ + { + "expression": "subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "window_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "enterprise_seat_true_up_organization_id_idx": { + "name": "enterprise_seat_true_up_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "enterprise_seat_true_up_unbilled_idx": { + "name": "enterprise_seat_true_up_unbilled_idx", + "columns": [ + { + "expression": "window_end", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "billed_at IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "enterprise_seat_true_up_subscription_id_subscription_id_fk": { + "name": "enterprise_seat_true_up_subscription_id_subscription_id_fk", + "tableFrom": "enterprise_seat_true_up", + "tableTo": "subscription", + "columnsFrom": ["subscription_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "enterprise_seat_true_up_organization_id_organization_id_fk": { + "name": "enterprise_seat_true_up_organization_id_organization_id_fk", + "tableFrom": "enterprise_seat_true_up", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.environment": { + "name": "environment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "environment_user_id_user_id_fk": { + "name": "environment_user_id_user_id_fk", + "tableFrom": "environment", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "environment_user_id_unique": { + "name": "environment_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_value_dependencies": { + "name": "execution_large_value_dependencies", + "schema": "", + "columns": { + "parent_key": { + "name": "parent_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_key": { + "name": "child_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "execution_large_value_dependencies_workspace_parent_key_idx": { + "name": "execution_large_value_dependencies_workspace_parent_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_value_dependencies_workspace_child_key_idx": { + "name": "execution_large_value_dependencies_workspace_child_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_value_dependencies_workspace_id_workspace_id_fk": { + "name": "execution_large_value_dependencies_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_value_dependencies", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "execution_large_value_dependencies_parent_key_child_key_pk": { + "name": "execution_large_value_dependencies_parent_key_child_key_pk", + "columns": ["parent_key", "child_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_value_references": { + "name": "execution_large_value_references", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "execution_large_value_reference_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "execution_large_value_references_workspace_execution_source_idx": { + "name": "execution_large_value_references_workspace_execution_source_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_value_references_workflow_id_idx": { + "name": "execution_large_value_references_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_value_references_workspace_id_workspace_id_fk": { + "name": "execution_large_value_references_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_value_references", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_large_value_references_workflow_id_workflow_id_fk": { + "name": "execution_large_value_references_workflow_id_workflow_id_fk", + "tableFrom": "execution_large_value_references", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "execution_large_value_references_key_execution_id_source_pk": { + "name": "execution_large_value_references_key_execution_id_source_pk", + "columns": ["key", "execution_id", "source"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_values": { + "name": "execution_large_values", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_execution_id": { + "name": "owner_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "execution_large_values_owner_execution_id_idx": { + "name": "execution_large_values_owner_execution_id_idx", + "columns": [ + { + "expression": "owner_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_cleanup_idx": { + "name": "execution_large_values_cleanup_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"execution_large_values\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_tombstone_cleanup_idx": { + "name": "execution_large_values_tombstone_cleanup_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"execution_large_values\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_workflow_id_idx": { + "name": "execution_large_values_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_workspace_id_idx": { + "name": "execution_large_values_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_values_workspace_id_workspace_id_fk": { + "name": "execution_large_values_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_values", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_large_values_workflow_id_workflow_id_fk": { + "name": "execution_large_values_workflow_id_workflow_id_fk", + "tableFrom": "execution_large_values", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.file_search_dependency": { + "name": "file_search_dependency", + "schema": "", + "columns": { + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "file_search_dependency_file_idx": { + "name": "file_search_dependency_file_idx", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "file_search_dependency_owner_idx": { + "name": "file_search_dependency_owner_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "file_search_dependency_build_id_workspace_file_search_build_id_fk": { + "name": "file_search_dependency_build_id_workspace_file_search_build_id_fk", + "tableFrom": "file_search_dependency", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "file_search_dependency_build_id_file_id_pk": { + "name": "file_search_dependency_build_id_file_id_pk", + "columns": ["build_id", "file_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.file_search_dispatch_queue": { + "name": "file_search_dispatch_queue", + "schema": "", + "columns": { + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enqueued_at": { + "name": "enqueued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_dispatched_at": { + "name": "last_dispatched_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "file_search_dispatch_schedule_idx": { + "name": "file_search_dispatch_schedule_idx", + "columns": [ + { + "expression": "last_dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "first" + }, + { + "expression": "enqueued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "file_search_dispatch_queue_entity_type_entity_id_pk": { + "name": "file_search_dispatch_queue_entity_type_entity_id_pk", + "columns": ["entity_type", "entity_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_dispatch_owner_check": { + "name": "file_search_dispatch_owner_check", + "value": "\"file_search_dispatch_queue\".\"entity_type\" IN ('workspace', 'project') AND length(\"file_search_dispatch_queue\".\"entity_id\") > 0" + } + }, + "isRLSEnabled": false + }, + "public.folder": { + "name": "folder", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_type": { + "name": "resource_type", + "type": "folder_resource_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parent_id": { + "name": "parent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "folder_project_id_idx": { + "name": "folder_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "folder_project_resource_parent_name_active_unique": { + "name": "folder_project_resource_parent_name_active_unique", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"parent_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"folder\".\"deleted_at\" IS NULL AND \"folder\".\"project_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "folder_user_idx": { + "name": "folder_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_resource_parent_idx": { + "name": "folder_workspace_resource_parent_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_parent_sort_idx": { + "name": "folder_parent_sort_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_deleted_at_idx": { + "name": "folder_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_deleted_partial_idx": { + "name": "folder_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"folder\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_resource_parent_name_active_unique": { + "name": "folder_workspace_resource_parent_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"parent_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"folder\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "folder_project_id_project_id_fk": { + "name": "folder_project_id_project_id_fk", + "tableFrom": "folder", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "folder_user_id_user_id_fk": { + "name": "folder_user_id_user_id_fk", + "tableFrom": "folder", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "folder_workspace_id_workspace_id_fk": { + "name": "folder_workspace_id_workspace_id_fk", + "tableFrom": "folder", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "folder_parent_id_folder_id_fk": { + "name": "folder_parent_id_folder_id_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "folder_workspace_parent_owner_fk": { + "name": "folder_workspace_parent_owner_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id", "workspace_id", "resource_type"], + "columnsTo": ["id", "workspace_id", "resource_type"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "folder_project_parent_owner_fk": { + "name": "folder_project_parent_owner_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id", "project_id", "resource_type"], + "columnsTo": ["id", "project_id", "resource_type"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "folder_workspace_owner_type_unique": { + "name": "folder_workspace_owner_type_unique", + "nullsNotDistinct": false, + "columns": ["id", "workspace_id", "resource_type"] + }, + "folder_project_owner_type_unique": { + "name": "folder_project_owner_type_unique", + "nullsNotDistinct": false, + "columns": ["id", "project_id", "resource_type"] + } + }, + "policies": {}, + "checkConstraints": { + "folder_owner_check": { + "name": "folder_owner_check", + "value": "num_nonnulls(\"folder\".\"workspace_id\", \"folder\".\"project_id\") = 1 AND (\"folder\".\"project_id\" IS NULL OR \"folder\".\"resource_type\" = 'file')" + } + }, + "isRLSEnabled": false + }, + "public.idempotency_key": { + "name": "idempotency_key", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "result": { + "name": "result", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idempotency_key_created_at_idx": { + "name": "idempotency_key_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitation": { + "name": "invitation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "invitation_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'organization'" + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "inviter_id": { + "name": "inviter_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "membership_intent": { + "name": "membership_intent", + "type": "invitation_membership_intent", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'internal'" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "invitation_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "invitation_email_idx": { + "name": "invitation_email_idx", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_organization_id_idx": { + "name": "invitation_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_status_idx": { + "name": "invitation_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_pending_email_org_unique": { + "name": "invitation_pending_email_org_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"invitation\".\"status\" = 'pending' AND \"invitation\".\"organization_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitation_inviter_id_user_id_fk": { + "name": "invitation_inviter_id_user_id_fk", + "tableFrom": "invitation", + "tableTo": "user", + "columnsFrom": ["inviter_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_organization_id_organization_id_fk": { + "name": "invitation_organization_id_organization_id_fk", + "tableFrom": "invitation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "invitation_token_unique": { + "name": "invitation_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitation_workspace_grant": { + "name": "invitation_workspace_grant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "invitation_id": { + "name": "invitation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "invitation_workspace_grant_unique": { + "name": "invitation_workspace_grant_unique", + "columns": [ + { + "expression": "invitation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_workspace_grant_workspace_id_idx": { + "name": "invitation_workspace_grant_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitation_workspace_grant_invitation_id_invitation_id_fk": { + "name": "invitation_workspace_grant_invitation_id_invitation_id_fk", + "tableFrom": "invitation_workspace_grant", + "tableTo": "invitation", + "columnsFrom": ["invitation_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_workspace_grant_workspace_id_workspace_id_fk": { + "name": "invitation_workspace_grant_workspace_id_workspace_id_fk", + "tableFrom": "invitation_workspace_grant", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.job_execution_logs": { + "name": "job_execution_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "schedule_id": { + "name": "schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_duration_ms": { + "name": "total_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "execution_data": { + "name": "execution_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "cost": { + "name": "cost", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "occurrence_at": { + "name": "occurrence_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_request_id": { + "name": "billing_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "job_execution_logs_schedule_occurrence_unique": { + "name": "job_execution_logs_schedule_occurrence_unique", + "columns": [ + { + "expression": "schedule_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "occurrence_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_billing_request_unique": { + "name": "job_execution_logs_billing_request_unique", + "columns": [ + { + "expression": "billing_request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"job_execution_logs\".\"billing_request_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_open_idx": { + "name": "job_execution_logs_open_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"job_execution_logs\".\"status\" IN ('queued', 'running')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_workspace_started_at_idx": { + "name": "job_execution_logs_workspace_started_at_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_workspace_ended_at_id_idx": { + "name": "job_execution_logs_workspace_ended_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"ended_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_execution_id_unique": { + "name": "job_execution_logs_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_trigger_idx": { + "name": "job_execution_logs_trigger_idx", + "columns": [ + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "job_execution_logs_schedule_id_workflow_schedule_id_fk": { + "name": "job_execution_logs_schedule_id_workflow_schedule_id_fk", + "tableFrom": "job_execution_logs", + "tableTo": "workflow_schedule", + "columnsFrom": ["schedule_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "job_execution_logs_workspace_id_workspace_id_fk": { + "name": "job_execution_logs_workspace_id_workspace_id_fk", + "tableFrom": "job_execution_logs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_base": { + "name": "knowledge_base", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_search_index": { + "name": "is_search_index", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "embedding_dimension": { + "name": "embedding_dimension", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1536 + }, + "chunking_config": { + "name": "chunking_config", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{\"maxSize\": 1024, \"minSize\": 1, \"overlap\": 200}'" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kb_organization_id_idx": { + "name": "kb_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_organization_search_index_unique": { + "name": "kb_organization_search_index_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"is_search_index\" = true AND \"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_organization_name_active_unique": { + "name": "kb_organization_name_active_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_id_idx": { + "name": "kb_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_user_workspace_idx": { + "name": "kb_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_folder_id_idx": { + "name": "kb_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_deleted_at_idx": { + "name": "kb_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_deleted_partial_idx": { + "name": "kb_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_base\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_name_active_unique": { + "name": "kb_workspace_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_search_index_unique": { + "name": "kb_workspace_search_index_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"is_search_index\" = true AND \"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_user_id_user_id_fk": { + "name": "knowledge_base_user_id_user_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_workspace_id_workspace_id_fk": { + "name": "knowledge_base_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_organization_id_organization_id_fk": { + "name": "knowledge_base_organization_id_organization_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_folder_id_folder_id_fk": { + "name": "knowledge_base_folder_id_folder_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kb_owner_check": { + "name": "kb_owner_check", + "value": "num_nonnulls(\"knowledge_base\".\"workspace_id\", \"knowledge_base\".\"organization_id\") = 1" + }, + "kb_organization_search_index_check": { + "name": "kb_organization_search_index_check", + "value": "\"knowledge_base\".\"organization_id\" IS NULL OR \"knowledge_base\".\"is_search_index\"" + }, + "kb_organization_folder_check": { + "name": "kb_organization_folder_check", + "value": "\"knowledge_base\".\"organization_id\" IS NULL OR \"knowledge_base\".\"folder_id\" IS NULL" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_base_import": { + "name": "knowledge_base_import", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_key": { + "name": "source_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "documents_total": { + "name": "documents_total", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "documents_imported": { + "name": "documents_imported", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "documents_failed": { + "name": "documents_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "vectors_reused": { + "name": "vectors_reused", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "failures": { + "name": "failures", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "knowledge_base_import_watchdog_idx": { + "name": "knowledge_base_import_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "knowledge_base_import_knowledge_base_id_idx": { + "name": "knowledge_base_import_knowledge_base_id_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_import_workspace_id_workspace_id_fk": { + "name": "knowledge_base_import_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_base_import", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_import_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_base_import_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_base_import", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_base_tag_definitions": { + "name": "knowledge_base_tag_definitions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tag_slot": { + "name": "tag_slot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "field_type": { + "name": "field_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kb_tag_definitions_kb_slot_idx": { + "name": "kb_tag_definitions_kb_slot_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tag_slot", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_tag_definitions_kb_display_name_idx": { + "name": "kb_tag_definitions_kb_display_name_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_tag_definitions_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_base_tag_definitions_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_base_tag_definitions", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector": { + "name": "knowledge_connector", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_config": { + "name": "source_config", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "sync_mode": { + "name": "sync_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'full'" + }, + "sync_interval_minutes": { + "name": "sync_interval_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1440 + }, + "access_mode": { + "name": "access_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'workspace'" + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_option_id": { + "name": "credential_group_option_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_status": { + "name": "member_sync_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'idle'" + }, + "member_sync_lock_token": { + "name": "member_sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_lock_lease_at": { + "name": "member_sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "next_member_sync_at": { + "name": "next_member_sync_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": false + }, + "last_member_sync_at": { + "name": "last_member_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_member_sync_error": { + "name": "last_member_sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_consecutive_failures": { + "name": "member_sync_consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "access_rewrite_pending": { + "name": "access_rewrite_pending", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image_removal_pending": { + "name": "image_removal_pending", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "member_tombstone_cursor": { + "name": "member_tombstone_cursor", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "member_resurrection_cursor": { + "name": "member_resurrection_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "last_sync_at": { + "name": "last_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_sync_error": { + "name": "last_sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_sync_doc_count": { + "name": "last_sync_doc_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "listing_checkpoint": { + "name": "listing_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "directory_checkpoint": { + "name": "directory_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "next_sync_at": { + "name": "next_sync_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": false + }, + "next_directory_sync_at": { + "name": "next_directory_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "sync_lock_token": { + "name": "sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_lock_lease_at": { + "name": "sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "detached_at": { + "name": "detached_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "detach_reserved_bytes": { + "name": "detach_reserved_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "kc_knowledge_base_id_idx": { + "name": "kc_knowledge_base_id_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_status_next_sync_idx": { + "name": "kc_status_next_sync_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_archived_at_partial_idx": { + "name": "kc_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_deleted_at_partial_idx": { + "name": "kc_deleted_at_partial_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_member_sync_due_idx": { + "name": "kc_member_sync_due_idx", + "columns": [ + { + "expression": "member_sync_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_member_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"access_mode\" = 'members' AND \"knowledge_connector\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_directory_sync_due_idx": { + "name": "kc_directory_sync_due_idx", + "columns": [ + { + "expression": "next_directory_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"access_mode\" = 'admin' AND \"knowledge_connector\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_connector_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_connector", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_credential_group_id_credential_group_id_fk": { + "name": "knowledge_connector_credential_group_id_credential_group_id_fk", + "tableFrom": "knowledge_connector", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kc_access_mode_check": { + "name": "kc_access_mode_check", + "value": "\"knowledge_connector\".\"access_mode\" IN ('workspace', 'members', 'admin')" + }, + "kc_member_sync_status_check": { + "name": "kc_member_sync_status_check", + "value": "\"knowledge_connector\".\"member_sync_status\" IN ('idle', 'pending', 'running', 'error', 'disabled')" + }, + "kc_sync_lock_exclusive_check": { + "name": "kc_sync_lock_exclusive_check", + "value": "NOT (\"knowledge_connector\".\"sync_lock_token\" IS NOT NULL AND \"knowledge_connector\".\"member_sync_lock_token\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_member": { + "name": "knowledge_connector_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_started_at": { + "name": "last_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_complete_listing_at": { + "name": "last_complete_listing_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_listed_count": { + "name": "last_listed_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_synced_through": { + "name": "member_synced_through", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope_renewed_at": { + "name": "scope_renewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope_renewal_cursor": { + "name": "scope_renewal_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope_renewal_started_at": { + "name": "scope_renewal_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "change_cursor": { + "name": "change_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "listing_checkpoint": { + "name": "listing_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kcm_organization_id_idx": { + "name": "kcm_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_connector_credential_unique": { + "name": "kcm_connector_credential_unique", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_connector_queue_idx": { + "name": "kcm_connector_queue_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "first" + }, + { + "expression": "last_started_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_credential_idx": { + "name": "kcm_credential_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_member_workspace_id_workspace_id_fk": { + "name": "knowledge_connector_member_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_organization_id_organization_id_fk": { + "name": "knowledge_connector_member_organization_id_organization_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_member_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_credential_id_credential_id_fk": { + "name": "knowledge_connector_member_credential_id_credential_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcm_owner_check": { + "name": "kcm_owner_check", + "value": "num_nonnulls(\"knowledge_connector_member\".\"workspace_id\", \"knowledge_connector_member\".\"organization_id\") = 1" + }, + "kcm_status_check": { + "name": "kcm_status_check", + "value": "\"knowledge_connector_member\".\"status\" IN ('active', 'suspended', 'disabled')" + }, + "kcm_subject_token_shape_check": { + "name": "kcm_subject_token_shape_check", + "value": "\"knowledge_connector_member\".\"subject_token\" ~ '^s:[^:]+:[^:]+:.+$'" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_member_sync_log": { + "name": "knowledge_connector_member_sync_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "members_claimed": { + "name": "members_claimed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_completed": { + "name": "members_completed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_incomplete": { + "name": "members_incomplete", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_failed": { + "name": "members_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_failed": { + "name": "docs_failed", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "processing_dispatch_failed": { + "name": "processing_dispatch_failed", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "docs_listed": { + "name": "docs_listed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_added": { + "name": "docs_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_updated": { + "name": "docs_updated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_unchanged": { + "name": "docs_unchanged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_hydrated_once": { + "name": "docs_hydrated_once", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_added": { + "name": "observations_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_renewed": { + "name": "observations_renewed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_removed": { + "name": "observations_removed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_tombstoned": { + "name": "docs_tombstoned", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_resurrected": { + "name": "docs_resurrected", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_purged": { + "name": "docs_purged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "credentials_audited": { + "name": "credentials_audited", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "database_failure_class": { + "name": "database_failure_class", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcmsl_connector_started_at_idx": { + "name": "kcmsl_connector_started_at_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcmsl_started_at_partial_idx": { + "name": "kcmsl_started_at_partial_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_member_sync_log\".\"status\" = 'started'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_member_sync_log_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_member_sync_log_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_member_sync_log", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcmsl_status_check": { + "name": "kcmsl_status_check", + "value": "\"knowledge_connector_member_sync_log\".\"status\" IN ('started', 'partial', 'completed', 'failed')" + }, + "kcmsl_database_failure_class_check": { + "name": "kcmsl_database_failure_class_check", + "value": "\"knowledge_connector_member_sync_log\".\"database_failure_class\" IN ('capacity', 'conflict', 'connection')" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_partition": { + "name": "knowledge_connector_partition", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "partition_key": { + "name": "partition_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation_id": { + "name": "generation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context": { + "name": "context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "retry_at": { + "name": "retry_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "permission_cursor": { + "name": "permission_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_attempts": { + "name": "permission_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "permission_retry_at": { + "name": "permission_retry_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "permission_last_served_at": { + "name": "permission_last_served_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_started_at": { + "name": "permission_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_failure": { + "name": "permission_failure", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcp_content_due_idx": { + "name": "kcp_content_due_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "retry_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_served_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcp_permission_due_idx": { + "name": "kcp_permission_due_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_retry_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_last_served_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_partition_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_partition_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_partition", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcp_pk": { + "name": "kcp_pk", + "columns": ["connector_id", "partition_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcp_partition_key_check": { + "name": "kcp_partition_key_check", + "value": "octet_length(\"knowledge_connector_partition\".\"partition_key\") BETWEEN 1 AND 1024" + }, + "kcp_context_check": { + "name": "kcp_context_check", + "value": "jsonb_typeof(\"knowledge_connector_partition\".\"context\") = 'object' AND octet_length(\"knowledge_connector_partition\".\"context\"::text) <= 16384" + }, + "kcp_status_check": { + "name": "kcp_status_check", + "value": "\"knowledge_connector_partition\".\"status\" IN ('pending', 'complete', 'blocked')" + }, + "kcp_cursor_check": { + "name": "kcp_cursor_check", + "value": "(\"knowledge_connector_partition\".\"cursor\" IS NULL OR octet_length(\"knowledge_connector_partition\".\"cursor\") <= 393216) AND (\"knowledge_connector_partition\".\"permission_cursor\" IS NULL OR octet_length(\"knowledge_connector_partition\".\"permission_cursor\") <= 393216)" + }, + "kcp_attempts_check": { + "name": "kcp_attempts_check", + "value": "\"knowledge_connector_partition\".\"attempts\" >= 0 AND \"knowledge_connector_partition\".\"permission_attempts\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_grant": { + "name": "knowledge_connector_permission_grant", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_key": { + "name": "group_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpg_subject_idx": { + "name": "kcpg_subject_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "kcpg_snapshot_fk": { + "name": "kcpg_snapshot_fk", + "tableFrom": "knowledge_connector_permission_grant", + "tableTo": "knowledge_connector_permission_snapshot", + "columnsFrom": ["connector_id"], + "columnsTo": ["connector_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpg_pk": { + "name": "kcpg_pk", + "columns": ["connector_id", "group_key", "subject_token"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcpg_group_check": { + "name": "kcpg_group_check", + "value": "length(\"knowledge_connector_permission_grant\".\"group_key\") BETWEEN 1 AND 255" + }, + "kcpg_subject_check": { + "name": "kcpg_subject_check", + "value": "\"knowledge_connector_permission_grant\".\"subject_token\" ~ '^u:[^[:space:]A-Z]+@[^[:space:]A-Z]+$'" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import": { + "name": "knowledge_connector_permission_import", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_binding": { + "name": "credential_binding", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expected_revision": { + "name": "expected_revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "manifest": { + "name": "manifest", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "part_digests": { + "name": "part_digests", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "user_rows": { + "name": "user_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "project_rows": { + "name": "project_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "completed_revision": { + "name": "completed_revision", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpi_connector_idx": { + "name": "kcpi_connector_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcpi_expires_idx": { + "name": "kcpi_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_permission_import_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_permission_import", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcpi_revision_check": { + "name": "kcpi_revision_check", + "value": "\"knowledge_connector_permission_import\".\"expected_revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import_grant": { + "name": "knowledge_connector_permission_import_grant", + "schema": "", + "columns": { + "import_id": { + "name": "import_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_path": { + "name": "project_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_key": { + "name": "group_key", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcpig_subject_idx": { + "name": "kcpig_subject_idx", + "columns": [ + { + "expression": "import_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_grant_import_id_knowledge_connector_permission_import_id_fk": { + "name": "knowledge_connector_permission_import_grant_import_id_knowledge_connector_permission_import_id_fk", + "tableFrom": "knowledge_connector_permission_import_grant", + "tableTo": "knowledge_connector_permission_import", + "columnsFrom": ["import_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpig_pk": { + "name": "kcpig_pk", + "columns": ["import_id", "project_path", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import_identity": { + "name": "knowledge_connector_permission_import_identity", + "schema": "", + "columns": { + "import_id": { + "name": "import_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpii_subject_import_idx": { + "name": "kcpii_subject_import_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "import_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_identity_import_id_knowledge_connector_permission_import_id_fk": { + "name": "knowledge_connector_permission_import_identity_import_id_knowledge_connector_permission_import_id_fk", + "tableFrom": "knowledge_connector_permission_import_identity", + "tableTo": "knowledge_connector_permission_import", + "columnsFrom": ["import_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpii_pk": { + "name": "kcpii_pk", + "columns": ["import_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_snapshot": { + "name": "knowledge_connector_permission_snapshot", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "kcps_connector_fk": { + "name": "kcps_connector_fk", + "tableFrom": "knowledge_connector_permission_snapshot", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcps_revision_check": { + "name": "kcps_revision_check", + "value": "\"knowledge_connector_permission_snapshot\".\"revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_sync_log": { + "name": "knowledge_connector_sync_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "docs_added": { + "name": "docs_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_updated": { + "name": "docs_updated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_deleted": { + "name": "docs_deleted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_unchanged": { + "name": "docs_unchanged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_skipped": { + "name": "docs_skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_failed": { + "name": "docs_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "listed_count": { + "name": "listed_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "database_failure_class": { + "name": "database_failure_class", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcsl_connector_started_at_idx": { + "name": "kcsl_connector_started_at_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcsl_started_at_partial_idx": { + "name": "kcsl_started_at_partial_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_sync_log\".\"status\" = 'started'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcsl_terminal_started_at_idx": { + "name": "kcsl_terminal_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_sync_log\".\"status\" IN ('completed', 'failed')", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_sync_log_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_sync_log_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_sync_log", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcsl_database_failure_class_check": { + "name": "kcsl_database_failure_class_check", + "value": "\"knowledge_connector_sync_log\".\"database_failure_class\" IN ('capacity', 'conflict', 'connection')" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_document_observation": { + "name": "knowledge_document_observation", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kdo_member_idx": { + "name": "kdo_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_document_observation_document_id_document_id_fk": { + "name": "knowledge_document_observation_document_id_document_id_fk", + "tableFrom": "knowledge_document_observation", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_document_observation_member_id_knowledge_connector_member_id_fk": { + "name": "knowledge_document_observation_member_id_knowledge_connector_member_id_fk", + "tableFrom": "knowledge_document_observation", + "tableTo": "knowledge_connector_member", + "columnsFrom": ["member_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "knowledge_document_observation_document_id_member_id_pk": { + "name": "knowledge_document_observation_document_id_member_id_pk", + "columns": ["document_id", "member_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_external_directory": { + "name": "knowledge_external_directory", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sync_lock_token": { + "name": "sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_lock_lease_at": { + "name": "sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_started_at": { + "name": "last_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_complete_sync_at": { + "name": "last_complete_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "ked_workspace_identity_unique": { + "name": "ked_workspace_identity_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "ked_organization_identity_unique": { + "name": "ked_organization_identity_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_external_directory_workspace_id_workspace_id_fk": { + "name": "knowledge_external_directory_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_external_directory", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_external_directory_organization_id_organization_id_fk": { + "name": "knowledge_external_directory_organization_id_organization_id_fk", + "tableFrom": "knowledge_external_directory", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ked_owner_check": { + "name": "ked_owner_check", + "value": "num_nonnulls(\"knowledge_external_directory\".\"workspace_id\", \"knowledge_external_directory\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_external_group": { + "name": "knowledge_external_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_group_id": { + "name": "external_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "keg_organization_identity_unique": { + "name": "keg_organization_identity_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_organization_synced_idx": { + "name": "keg_organization_synced_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_synced_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_identity_unique": { + "name": "keg_identity_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_workspace_synced_idx": { + "name": "keg_workspace_synced_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_synced_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_external_group_organization_id_organization_id_fk": { + "name": "knowledge_external_group_organization_id_organization_id_fk", + "tableFrom": "knowledge_external_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "keg_workspace_fk": { + "name": "keg_workspace_fk", + "tableFrom": "knowledge_external_group", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "keg_owner_check": { + "name": "keg_owner_check", + "value": "num_nonnulls(\"knowledge_external_group\".\"workspace_id\", \"knowledge_external_group\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_external_group_member": { + "name": "knowledge_external_group_member", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kegm_subject_token_idx": { + "name": "kegm_subject_token_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "kegm_group_fk": { + "name": "kegm_group_fk", + "tableFrom": "knowledge_external_group_member", + "tableTo": "knowledge_external_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "knowledge_external_group_member_group_id_subject_token_pk": { + "name": "knowledge_external_group_member_group_id_subject_token_pk", + "columns": ["group_id", "subject_token"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_projection_dirty": { + "name": "knowledge_projection_dirty", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "content": { + "name": "content", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "marked_at": { + "name": "marked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "knowledge_projection_dirty_marked_at_idx": { + "name": "knowledge_projection_dirty_marked_at_idx", + "columns": [ + { + "expression": "marked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_projection_dirty_document_id_document_id_fk": { + "name": "knowledge_projection_dirty_document_id_document_id_fk", + "tableFrom": "knowledge_projection_dirty", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mcp_server_oauth": { + "name": "mcp_server_oauth", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "mcp_server_id": { + "name": "mcp_server_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_information": { + "name": "client_information", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tokens": { + "name": "tokens", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_verifier": { + "name": "code_verifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state_created_at": { + "name": "state_created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_refreshed_at": { + "name": "last_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mcp_server_oauth_server_unique": { + "name": "mcp_server_oauth_server_unique", + "columns": [ + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_server_oauth_state_idx": { + "name": "mcp_server_oauth_state_idx", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mcp_server_oauth_mcp_server_id_mcp_servers_id_fk": { + "name": "mcp_server_oauth_mcp_server_id_mcp_servers_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "mcp_servers", + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_server_oauth_user_id_user_id_fk": { + "name": "mcp_server_oauth_user_id_user_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "mcp_server_oauth_workspace_id_workspace_id_fk": { + "name": "mcp_server_oauth_workspace_id_workspace_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_server_oauth_organization_id_organization_id_fk": { + "name": "mcp_server_oauth_organization_id_organization_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_server_oauth_owner_check": { + "name": "mcp_server_oauth_owner_check", + "value": "num_nonnulls(\"mcp_server_oauth\".\"workspace_id\", \"mcp_server_oauth\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.mcp_servers": { + "name": "mcp_servers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "managed_connector_id": { + "name": "managed_connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config_version": { + "name": "oauth_config_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "transport": { + "name": "transport", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'headers'" + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_client_secret": { + "name": "oauth_client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "headers": { + "name": "headers", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "timeout": { + "name": "timeout", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 30000 + }, + "retries": { + "name": "retries", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 3 + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "last_connected": { + "name": "last_connected", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "connection_status": { + "name": "connection_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'disconnected'" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status_config": { + "name": "status_config", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "tool_count": { + "name": "tool_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_tools_refresh": { + "name": "last_tools_refresh", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_requests": { + "name": "total_requests", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mcp_servers_organization_id_idx": { + "name": "mcp_servers_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_workspace_enabled_idx": { + "name": "mcp_servers_workspace_enabled_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_credential_group_idx": { + "name": "mcp_servers_credential_group_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_credential_group_managed_connector_unique": { + "name": "mcp_servers_credential_group_managed_connector_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "managed_connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"mcp_servers\".\"credential_group_id\" IS NOT NULL AND \"mcp_servers\".\"managed_connector_id\" IS NOT NULL AND \"mcp_servers\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_workspace_deleted_partial_idx": { + "name": "mcp_servers_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"mcp_servers\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mcp_servers_workspace_id_workspace_id_fk": { + "name": "mcp_servers_workspace_id_workspace_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_servers_organization_id_organization_id_fk": { + "name": "mcp_servers_organization_id_organization_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_servers_credential_group_id_credential_group_id_fk": { + "name": "mcp_servers_credential_group_id_credential_group_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "mcp_servers_created_by_user_id_fk": { + "name": "mcp_servers_created_by_user_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_servers_owner_check": { + "name": "mcp_servers_owner_check", + "value": "num_nonnulls(\"mcp_servers\".\"workspace_id\", \"mcp_servers\".\"organization_id\") = 1" + }, + "mcp_servers_organization_managed_check": { + "name": "mcp_servers_organization_managed_check", + "value": "\"mcp_servers\".\"organization_id\" IS NULL OR \"mcp_servers\".\"credential_group_id\" IS NOT NULL" + }, + "mcp_servers_credential_group_managed_connector_check": { + "name": "mcp_servers_credential_group_managed_connector_check", + "value": "\"mcp_servers\".\"credential_group_id\" IS NULL OR \"mcp_servers\".\"managed_connector_id\" IS NOT NULL" + }, + "mcp_servers_managed_connector_oauth_check": { + "name": "mcp_servers_managed_connector_oauth_check", + "value": "\"mcp_servers\".\"managed_connector_id\" IS NULL OR \"mcp_servers\".\"auth_type\" = 'oauth'" + } + }, + "isRLSEnabled": false + }, + "public.member": { + "name": "member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "member_user_id_unique": { + "name": "member_user_id_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_organization_id_idx": { + "name": "member_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "member_user_id_user_id_fk": { + "name": "member_user_id_user_id_fk", + "tableFrom": "member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_organization_id_organization_id_fk": { + "name": "member_organization_id_organization_id_fk", + "tableFrom": "member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.member_profile": { + "name": "member_profile", + "schema": "", + "columns": { + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "manager_member_id": { + "name": "manager_member_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "member_profile_manager_member_id_idx": { + "name": "member_profile_manager_member_id_idx", + "columns": [ + { + "expression": "manager_member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_profile_updated_by_idx": { + "name": "member_profile_updated_by_idx", + "columns": [ + { + "expression": "updated_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "member_profile_member_id_member_id_fk": { + "name": "member_profile_member_id_member_id_fk", + "tableFrom": "member_profile", + "tableTo": "member", + "columnsFrom": ["member_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_profile_manager_member_id_member_id_fk": { + "name": "member_profile_manager_member_id_member_id_fk", + "tableFrom": "member_profile", + "tableTo": "member", + "columnsFrom": ["manager_member_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "member_profile_updated_by_user_id_fk": { + "name": "member_profile_updated_by_user_id_fk", + "tableFrom": "member_profile", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "member_profile_not_own_manager": { + "name": "member_profile_not_own_manager", + "value": "\"member_profile\".\"manager_member_id\" <> \"member_profile\".\"member_id\"" + } + }, + "isRLSEnabled": false + }, + "public.memory": { + "name": "memory", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "storage_version": { + "name": "storage_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "encrypted_context_summary": { + "name": "encrypted_context_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "memory_key_idx": { + "name": "memory_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_workspace_key_idx": { + "name": "memory_workspace_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_workspace_deleted_partial_idx": { + "name": "memory_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"memory\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_workspace_id_workspace_id_fk": { + "name": "memory_workspace_id_workspace_id_fk", + "tableFrom": "memory", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_artifact": { + "name": "memory_artifact", + "schema": "", + "columns": { + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "memory_artifact_key_idx": { + "name": "memory_artifact_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_artifact_memory_id_memory_id_fk": { + "name": "memory_artifact_memory_id_memory_id_fk", + "tableFrom": "memory_artifact", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "memory_artifact_key_execution_large_values_key_fk": { + "name": "memory_artifact_key_execution_large_values_key_fk", + "tableFrom": "memory_artifact", + "tableTo": "execution_large_values", + "columnsFrom": ["key"], + "columnsTo": ["key"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "memory_artifact_memory_id_key_pk": { + "name": "memory_artifact_memory_id_key_pk", + "columns": ["memory_id", "key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_item": { + "name": "memory_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sequence": { + "name": "sequence", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "memory_item_sequence_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "append_key": { + "name": "append_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "turn_id": { + "name": "turn_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provenance_status": { + "name": "provenance_status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provenance_entries": { + "name": "provenance_entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "memory_item_append_unique": { + "name": "memory_item_append_unique", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "append_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_item_sequence_idx": { + "name": "memory_item_sequence_idx", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sequence", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_item_memory_id_memory_id_fk": { + "name": "memory_item_memory_id_memory_id_fk", + "tableFrom": "memory_item", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "memory_item_kind_check": { + "name": "memory_item_kind_check", + "value": "\"memory_item\".\"kind\" IN ('message', 'exchange')" + }, + "memory_item_provenance_status_check": { + "name": "memory_item_provenance_status_check", + "value": "\"memory_item\".\"provenance_status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.memory_secret_provenance": { + "name": "memory_secret_provenance", + "schema": "", + "columns": { + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "memory_secret_provenance_memory_id_memory_id_fk": { + "name": "memory_secret_provenance_memory_id_memory_id_fk", + "tableFrom": "memory_secret_provenance", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "memory_secret_provenance_status_check": { + "name": "memory_secret_provenance_status_check", + "value": "\"memory_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.mothership_benchmark_runs": { + "name": "mothership_benchmark_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "benchmark_id": { + "name": "benchmark_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "evaluation_key": { + "name": "evaluation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reviews": { + "name": "reviews", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "correct": { + "name": "correct", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "automatic_correct": { + "name": "automatic_correct", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "total": { + "name": "total", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "artifacts": { + "name": "artifacts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_benchmark_runs_benchmark_created_idx": { + "name": "mothership_benchmark_runs_benchmark_created_idx", + "columns": [ + { + "expression": "benchmark_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_benchmark_runs_benchmark_id_mothership_benchmarks_id_fk": { + "name": "mothership_benchmark_runs_benchmark_id_mothership_benchmarks_id_fk", + "tableFrom": "mothership_benchmark_runs", + "tableTo": "mothership_benchmarks", + "columnsFrom": ["benchmark_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mothership_benchmark_runs_score_check": { + "name": "mothership_benchmark_runs_score_check", + "value": "\"mothership_benchmark_runs\".\"total\" > 0 AND \"mothership_benchmark_runs\".\"correct\" >= 0 AND \"mothership_benchmark_runs\".\"correct\" <= \"mothership_benchmark_runs\".\"total\"" + }, + "mothership_benchmark_runs_version_check": { + "name": "mothership_benchmark_runs_version_check", + "value": "\"mothership_benchmark_runs\".\"version\" > 0" + }, + "mothership_benchmark_runs_automatic_score_check": { + "name": "mothership_benchmark_runs_automatic_score_check", + "value": "\"mothership_benchmark_runs\".\"automatic_correct\" >= 0 AND \"mothership_benchmark_runs\".\"automatic_correct\" <= \"mothership_benchmark_runs\".\"total\"" + } + }, + "isRLSEnabled": false + }, + "public.mothership_benchmarks": { + "name": "mothership_benchmarks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_as_user_id": { + "name": "run_as_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "artifacts": { + "name": "artifacts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "running_stage": { + "name": "running_stage", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attempt_id": { + "name": "attempt_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "planner_chat_id": { + "name": "planner_chat_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_benchmarks_owner_created_idx": { + "name": "mothership_benchmarks_owner_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mothership_benchmarks_workspace_idx": { + "name": "mothership_benchmarks_workspace_idx", + "columns": [ + { + "expression": "source_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_benchmarks_organization_id_organization_id_fk": { + "name": "mothership_benchmarks_organization_id_organization_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_user_id_user_id_fk": { + "name": "mothership_benchmarks_user_id_user_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_run_as_user_id_user_id_fk": { + "name": "mothership_benchmarks_run_as_user_id_user_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "user", + "columnsFrom": ["run_as_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_source_workspace_id_workspace_id_fk": { + "name": "mothership_benchmarks_source_workspace_id_workspace_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "workspace", + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mothership_benchmarks_version_check": { + "name": "mothership_benchmarks_version_check", + "value": "\"mothership_benchmarks\".\"version\" > 0" + }, + "mothership_benchmarks_attempt_check": { + "name": "mothership_benchmarks_attempt_check", + "value": "(\"mothership_benchmarks\".\"running_stage\" IS NULL AND \"mothership_benchmarks\".\"attempt_id\" IS NULL AND \"mothership_benchmarks\".\"lease_expires_at\" IS NULL) OR (\"mothership_benchmarks\".\"running_stage\" IS NOT NULL AND \"mothership_benchmarks\".\"running_stage\" IN ('distill', 'redact', 'plan', 'reconstruct', 'grade') AND \"mothership_benchmarks\".\"attempt_id\" IS NOT NULL AND \"mothership_benchmarks\".\"lease_expires_at\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.mothership_inbox_allowed_sender": { + "name": "mothership_inbox_allowed_sender", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "added_by": { + "name": "added_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "inbox_sender_ws_email_idx": { + "name": "inbox_sender_ws_email_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_inbox_allowed_sender_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_allowed_sender_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_allowed_sender", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_inbox_allowed_sender_added_by_user_id_fk": { + "name": "mothership_inbox_allowed_sender_added_by_user_id_fk", + "tableFrom": "mothership_inbox_allowed_sender", + "tableTo": "user", + "columnsFrom": ["added_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_inbox_task": { + "name": "mothership_inbox_task", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_email": { + "name": "from_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sender_authenticated": { + "name": "sender_authenticated", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "from_name": { + "name": "from_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body_preview": { + "name": "body_preview", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_text": { + "name": "body_text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_html": { + "name": "body_html", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_message_id": { + "name": "email_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "in_reply_to": { + "name": "in_reply_to", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "response_message_id": { + "name": "response_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agentmail_message_id": { + "name": "agentmail_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'received'" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "trigger_job_id": { + "name": "trigger_job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "result_summary": { + "name": "result_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rejection_reason": { + "name": "rejection_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "has_attachments": { + "name": "has_attachments", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "cc_recipients": { + "name": "cc_recipients", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "processing_started_at": { + "name": "processing_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "inbox_task_ws_created_at_idx": { + "name": "inbox_task_ws_created_at_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_ws_status_idx": { + "name": "inbox_task_ws_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_response_msg_id_idx": { + "name": "inbox_task_response_msg_id_idx", + "columns": [ + { + "expression": "response_message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_email_msg_id_idx": { + "name": "inbox_task_email_msg_id_idx", + "columns": [ + { + "expression": "email_message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_inbox_task_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_task_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_task", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_inbox_task_chat_id_copilot_chats_id_fk": { + "name": "mothership_inbox_task_chat_id_copilot_chats_id_fk", + "tableFrom": "mothership_inbox_task", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_inbox_webhook": { + "name": "mothership_inbox_webhook", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "webhook_id": { + "name": "webhook_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_inbox_webhook_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_webhook_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_webhook", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "mothership_inbox_webhook_workspace_id_unique": { + "name": "mothership_inbox_webhook_workspace_id_unique", + "nullsNotDistinct": false, + "columns": ["workspace_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_memory_selections": { + "name": "mothership_memory_selections", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "space_id": { + "name": "space_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_memory_selections_user_id_user_id_fk": { + "name": "mothership_memory_selections_user_id_user_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_selections_organization_id_organization_id_fk": { + "name": "mothership_memory_selections_organization_id_organization_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_selections_space_id_mothership_memory_spaces_id_fk": { + "name": "mothership_memory_selections_space_id_mothership_memory_spaces_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "mothership_memory_spaces", + "columnsFrom": ["space_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "mothership_memory_selections_user_id_organization_id_pk": { + "name": "mothership_memory_selections_user_id_organization_id_pk", + "columns": ["user_id", "organization_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_memory_spaces": { + "name": "mothership_memory_spaces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_memory_spaces_owner_idx": { + "name": "mothership_memory_spaces_owner_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_memory_spaces_user_id_user_id_fk": { + "name": "mothership_memory_spaces_user_id_user_id_fk", + "tableFrom": "mothership_memory_spaces", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_spaces_organization_id_organization_id_fk": { + "name": "mothership_memory_spaces_organization_id_organization_id_fk", + "tableFrom": "mothership_memory_spaces", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_resource_effects": { + "name": "mothership_resource_effects", + "schema": "", + "columns": { + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "effect_id": { + "name": "effect_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_resource_effects_chat_id_copilot_chats_id_fk": { + "name": "mothership_resource_effects_chat_id_copilot_chats_id_fk", + "tableFrom": "mothership_resource_effects", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "mothership_resource_effects_chat_id_effect_id_pk": { + "name": "mothership_resource_effects_chat_id_effect_id_pk", + "columns": ["chat_id", "effect_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_access_token": { + "name": "oauth_access_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_id": { + "name": "refresh_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "oauth_access_token_client_id_idx": { + "name": "oauth_access_token_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_session_id_idx": { + "name": "oauth_access_token_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_refresh_id_idx": { + "name": "oauth_access_token_refresh_id_idx", + "columns": [ + { + "expression": "refresh_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_user_client_idx": { + "name": "oauth_access_token_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_expires_at_idx": { + "name": "oauth_access_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_access_token_client_id_oauth_client_client_id_fk": { + "name": "oauth_access_token_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_token_session_id_session_id_fk": { + "name": "oauth_access_token_session_id_session_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_access_token_user_id_user_id_fk": { + "name": "oauth_access_token_user_id_user_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_token_refresh_id_oauth_refresh_token_id_fk": { + "name": "oauth_access_token_refresh_id_oauth_refresh_token_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "oauth_refresh_token", + "columnsFrom": ["refresh_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_access_token_token_unique": { + "name": "oauth_access_token_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": { + "oauth_access_token_search_resource_check": { + "name": "oauth_access_token_search_resource_check", + "value": "NOT ('search:read' = ANY(\"oauth_access_token\".\"scopes\")) OR \"oauth_access_token\".\"resource\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.oauth_client": { + "name": "oauth_client", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_secret": { + "name": "client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "disabled": { + "name": "disabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "skip_consent": { + "name": "skip_consent", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "enable_end_session": { + "name": "enable_end_session", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "subject_type": { + "name": "subject_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "uri": { + "name": "uri", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "contacts": { + "name": "contacts", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "tos": { + "name": "tos", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_id": { + "name": "software_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_version": { + "name": "software_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_statement": { + "name": "software_statement", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "post_logout_redirect_uris": { + "name": "post_logout_redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "token_endpoint_auth_method": { + "name": "token_endpoint_auth_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "grant_types": { + "name": "grant_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "response_types": { + "name": "response_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "require_pkce": { + "name": "require_pkce", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "oauth_client_user_id_idx": { + "name": "oauth_client_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_client_user_id_user_id_fk": { + "name": "oauth_client_user_id_user_id_fk", + "tableFrom": "oauth_client", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_client_client_id_unique": { + "name": "oauth_client_client_id_unique", + "nullsNotDistinct": false, + "columns": ["client_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_consent": { + "name": "oauth_consent", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_consent_client_id_idx": { + "name": "oauth_consent_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_consent_client_id_oauth_client_client_id_fk": { + "name": "oauth_consent_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_consent", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_consent_user_id_user_id_fk": { + "name": "oauth_consent_user_id_user_id_fk", + "tableFrom": "oauth_consent", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_consent_user_client_reference_unique": { + "name": "oauth_consent_user_client_reference_unique", + "nullsNotDistinct": true, + "columns": ["user_id", "client_id", "reference_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_refresh_token": { + "name": "oauth_refresh_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "revoked": { + "name": "revoked", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "auth_time": { + "name": "auth_time", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "family_id": { + "name": "family_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_refresh_token_client_id_idx": { + "name": "oauth_refresh_token_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_session_id_idx": { + "name": "oauth_refresh_token_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_user_client_idx": { + "name": "oauth_refresh_token_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_expires_at_idx": { + "name": "oauth_refresh_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_refresh_token_client_id_oauth_client_client_id_fk": { + "name": "oauth_refresh_token_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_refresh_token_session_id_session_id_fk": { + "name": "oauth_refresh_token_session_id_session_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_refresh_token_user_id_user_id_fk": { + "name": "oauth_refresh_token_user_id_user_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_refresh_token_family_id_oauth_token_family_id_fk": { + "name": "oauth_refresh_token_family_id_oauth_token_family_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "oauth_token_family", + "columnsFrom": ["family_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_refresh_token_token_unique": { + "name": "oauth_refresh_token_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + }, + "oauth_refresh_token_family_generation_unique": { + "name": "oauth_refresh_token_family_generation_unique", + "nullsNotDistinct": false, + "columns": ["family_id", "generation"] + } + }, + "policies": {}, + "checkConstraints": { + "oauth_refresh_token_generation_check": { + "name": "oauth_refresh_token_generation_check", + "value": "\"oauth_refresh_token\".\"generation\" BETWEEN 0 AND 1000" + }, + "oauth_refresh_token_search_resource_check": { + "name": "oauth_refresh_token_search_resource_check", + "value": "NOT ('search:read' = ANY(\"oauth_refresh_token\".\"scopes\")) OR \"oauth_refresh_token\".\"resource\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.oauth_token_family": { + "name": "oauth_token_family", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "consent_id": { + "name": "consent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "current_generation": { + "name": "current_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_token_family_client_id_idx": { + "name": "oauth_token_family_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_session_id_idx": { + "name": "oauth_token_family_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_user_client_idx": { + "name": "oauth_token_family_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_consent_id_idx": { + "name": "oauth_token_family_consent_id_idx", + "columns": [ + { + "expression": "consent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_expires_at_idx": { + "name": "oauth_token_family_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_token_family_client_id_oauth_client_client_id_fk": { + "name": "oauth_token_family_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_token_family_session_id_session_id_fk": { + "name": "oauth_token_family_session_id_session_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_token_family_user_id_user_id_fk": { + "name": "oauth_token_family_user_id_user_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_token_family_consent_id_oauth_consent_id_fk": { + "name": "oauth_token_family_consent_id_oauth_consent_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "oauth_consent", + "columnsFrom": ["consent_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "oauth_token_family_generation_check": { + "name": "oauth_token_family_generation_check", + "value": "\"oauth_token_family\".\"current_generation\" BETWEEN 0 AND 1000" + } + }, + "isRLSEnabled": false + }, + "public.organization": { + "name": "organization", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "session_policy_settings": { + "name": "session_policy_settings", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "security_policy_version": { + "name": "security_policy_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "require_sso": { + "name": "require_sso", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "data_retention_settings": { + "name": "data_retention_settings", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "org_usage_limit": { + "name": "org_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "self_serve_usage_limit": { + "name": "self_serve_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit_notifications": { + "name": "limit_notifications", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "credit_balance": { + "name": "credit_balance", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_access_request_settings": { + "name": "organization_access_request_settings", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "allow_requests": { + "name": "allow_requests", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "organization_access_request_settings_organization_id_organization_id_fk": { + "name": "organization_access_request_settings_organization_id_organization_id_fk", + "tableFrom": "organization_access_request_settings", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_access_request_settings_updated_by_user_id_fk": { + "name": "organization_access_request_settings_updated_by_user_id_fk", + "tableFrom": "organization_access_request_settings", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_byok_keys": { + "name": "organization_byok_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_byok_organization_provider_idx": { + "name": "organization_byok_organization_provider_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_byok_keys_organization_id_organization_id_fk": { + "name": "organization_byok_keys_organization_id_organization_id_fk", + "tableFrom": "organization_byok_keys", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_byok_keys_created_by_user_id_fk": { + "name": "organization_byok_keys_created_by_user_id_fk", + "tableFrom": "organization_byok_keys", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_member_activity_daily": { + "name": "organization_member_activity_daily", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_count": { + "name": "event_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "first_at": { + "name": "first_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_at": { + "name": "last_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "organization_member_activity_daily_day_idx": { + "name": "organization_member_activity_daily_day_idx", + "columns": [ + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_member_activity_daily_user_idx": { + "name": "organization_member_activity_daily_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_member_activity_daily_organization_id_organization_id_fk": { + "name": "organization_member_activity_daily_organization_id_organization_id_fk", + "tableFrom": "organization_member_activity_daily", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_activity_daily_user_id_user_id_fk": { + "name": "organization_member_activity_daily_user_id_user_id_fk", + "tableFrom": "organization_member_activity_daily", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_member_activity_daily_pk": { + "name": "organization_member_activity_daily_pk", + "columns": ["organization_id", "day", "surface", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_member_activity_daily_surface_check": { + "name": "organization_member_activity_daily_surface_check", + "value": "\"organization_member_activity_daily\".\"surface\" IN ('assistant', 'agent', 'search', 'search_mcp', 'slack', 'workflows')" + }, + "organization_member_activity_daily_count_check": { + "name": "organization_member_activity_daily_count_check", + "value": "\"organization_member_activity_daily\".\"event_count\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.organization_member_usage_limit": { + "name": "organization_member_usage_limit", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "usage_limit": { + "name": "usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "set_by": { + "name": "set_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "org_member_usage_limit_org_user_unique": { + "name": "org_member_usage_limit_org_user_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "org_member_usage_limit_organization_id_idx": { + "name": "org_member_usage_limit_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_member_usage_limit_organization_id_organization_id_fk": { + "name": "organization_member_usage_limit_organization_id_organization_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_usage_limit_user_id_user_id_fk": { + "name": "organization_member_usage_limit_user_id_user_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_usage_limit_set_by_user_id_fk": { + "name": "organization_member_usage_limit_set_by_user_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "user", + "columnsFrom": ["set_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_history": { + "name": "organization_search_history", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sources": { + "name": "sources", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "queries": { + "name": "queries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": { + "organization_search_history_user_idx": { + "name": "organization_search_history_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_search_history_organization_id_organization_id_fk": { + "name": "organization_search_history_organization_id_organization_id_fk", + "tableFrom": "organization_search_history", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_search_history_user_id_user_id_fk": { + "name": "organization_search_history_user_id_user_id_fk", + "tableFrom": "organization_search_history", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_history_organization_id_user_id_pk": { + "name": "organization_search_history_organization_id_user_id_pk", + "columns": ["organization_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_integration": { + "name": "organization_search_integration", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "approved": { + "name": "approved", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "organization_search_integration_organization_id_organization_id_fk": { + "name": "organization_search_integration_organization_id_organization_id_fk", + "tableFrom": "organization_search_integration", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_integration_organization_id_connector_type_pk": { + "name": "organization_search_integration_organization_id_connector_type_pk", + "columns": ["organization_id", "connector_type"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_integration_daily": { + "name": "organization_search_integration_daily", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "searches_ok": { + "name": "searches_ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_partial": { + "name": "searches_partial", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_reconnect": { + "name": "searches_reconnect", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_rate_limited": { + "name": "searches_rate_limited", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_unavailable": { + "name": "searches_unavailable", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_timeout": { + "name": "searches_timeout", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "opens": { + "name": "opens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "organization_search_integration_daily_day_idx": { + "name": "organization_search_integration_daily_day_idx", + "columns": [ + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_integration_daily_user_idx": { + "name": "organization_search_integration_daily_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_search_integration_daily_organization_id_organization_id_fk": { + "name": "organization_search_integration_daily_organization_id_organization_id_fk", + "tableFrom": "organization_search_integration_daily", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_search_integration_daily_user_id_user_id_fk": { + "name": "organization_search_integration_daily_user_id_user_id_fk", + "tableFrom": "organization_search_integration_daily", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_integration_daily_pk": { + "name": "organization_search_integration_daily_pk", + "columns": ["organization_id", "day", "surface", "connector_type", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_search_integration_daily_surface_check": { + "name": "organization_search_integration_daily_surface_check", + "value": "\"organization_search_integration_daily\".\"surface\" IN ('assistant', 'agent', 'search', 'search_mcp', 'slack', 'workflows')" + }, + "organization_search_integration_daily_connector_type_check": { + "name": "organization_search_integration_daily_connector_type_check", + "value": "\"organization_search_integration_daily\".\"connector_type\" ~ '^[a-z][a-z0-9_]{0,63}$'" + }, + "organization_search_integration_daily_counts_check": { + "name": "organization_search_integration_daily_counts_check", + "value": "LEAST(\"organization_search_integration_daily\".\"searches_ok\", \"organization_search_integration_daily\".\"searches_partial\", \"organization_search_integration_daily\".\"searches_reconnect\", \"organization_search_integration_daily\".\"searches_rate_limited\", \"organization_search_integration_daily\".\"searches_unavailable\", \"organization_search_integration_daily\".\"searches_timeout\", \"organization_search_integration_daily\".\"opens\") >= 0" + }, + "organization_search_integration_daily_total_check": { + "name": "organization_search_integration_daily_total_check", + "value": "\"organization_search_integration_daily\".\"searches_ok\" + \"organization_search_integration_daily\".\"searches_partial\" + \"organization_search_integration_daily\".\"searches_reconnect\" + \"organization_search_integration_daily\".\"searches_rate_limited\" + \"organization_search_integration_daily\".\"searches_unavailable\" + \"organization_search_integration_daily\".\"searches_timeout\" + \"organization_search_integration_daily\".\"opens\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.organization_search_mcp_invocation": { + "name": "organization_search_mcp_invocation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_name": { + "name": "client_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_search_mcp_invocation_org_created_idx": { + "name": "organization_search_mcp_invocation_org_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_mcp_invocation_user_idx": { + "name": "organization_search_mcp_invocation_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_mcp_invocation_created_idx": { + "name": "organization_search_mcp_invocation_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "org_search_mcp_invocation_org_fk": { + "name": "org_search_mcp_invocation_org_fk", + "tableFrom": "organization_search_mcp_invocation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "org_search_mcp_invocation_user_fk": { + "name": "org_search_mcp_invocation_user_fk", + "tableFrom": "organization_search_mcp_invocation", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_search_mcp_invocation_tool_check": { + "name": "organization_search_mcp_invocation_tool_check", + "value": "\"organization_search_mcp_invocation\".\"tool_name\" IN ('search', 'read_document', 'chat', 'search_people', 'search_experts', 'list_my_activity', 'list_my_chat_history')" + }, + "organization_search_mcp_invocation_outcome_check": { + "name": "organization_search_mcp_invocation_outcome_check", + "value": "\"organization_search_mcp_invocation\".\"outcome\" IN ('success', 'error', 'cancelled', 'rate_limited')" + }, + "organization_search_mcp_invocation_duration_check": { + "name": "organization_search_mcp_invocation_duration_check", + "value": "\"organization_search_mcp_invocation\".\"duration_ms\" >= 0" + }, + "organization_search_mcp_invocation_client_name_check": { + "name": "organization_search_mcp_invocation_client_name_check", + "value": "length(\"organization_search_mcp_invocation\".\"client_name\") <= 256" + }, + "organization_search_mcp_invocation_auth_check": { + "name": "organization_search_mcp_invocation_auth_check", + "value": "(\"organization_search_mcp_invocation\".\"auth_kind\" = 'oauth_access_token' AND \"organization_search_mcp_invocation\".\"oauth_client_id\" IS NOT NULL)\n OR (\"organization_search_mcp_invocation\".\"auth_kind\" IN ('personal_api_key', 'workspace_api_key') AND \"organization_search_mcp_invocation\".\"oauth_client_id\" IS NULL AND \"organization_search_mcp_invocation\".\"client_name\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.organization_secret": { + "name": "organization_secret", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_value": { + "name": "encrypted_value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_secret_shared_unique": { + "name": "organization_secret_shared_unique", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organization_secret\".\"owner_user_id\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_secret_member_unique": { + "name": "organization_secret_member_unique", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organization_secret\".\"owner_user_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_secret_owner_idx": { + "name": "organization_secret_owner_idx", + "columns": [ + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_secret_source_id_organization_secret_source_id_fk": { + "name": "organization_secret_source_id_organization_secret_source_id_fk", + "tableFrom": "organization_secret", + "tableTo": "organization_secret_source", + "columnsFrom": ["source_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_secret_owner_user_id_user_id_fk": { + "name": "organization_secret_owner_user_id_user_id_fk", + "tableFrom": "organization_secret", + "tableTo": "user", + "columnsFrom": ["owner_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_secret_source": { + "name": "organization_secret_source", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_secret_source_org_unique": { + "name": "organization_secret_source_org_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_secret_source_organization_id_organization_id_fk": { + "name": "organization_secret_source_organization_id_organization_id_fk", + "tableFrom": "organization_secret_source", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_secret_source_mode_check": { + "name": "organization_secret_source_mode_check", + "value": "\"organization_secret_source\".\"mode\" IN ('organization', 'member')" + } + }, + "isRLSEnabled": false + }, + "public.outbox_event": { + "name": "outbox_event", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "available_at": { + "name": "available_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "locked_at": { + "name": "locked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "outbox_event_status_available_idx": { + "name": "outbox_event_status_available_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_pending_type_available_idx": { + "name": "outbox_event_pending_type_available_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"outbox_event\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_locked_at_idx": { + "name": "outbox_event_locked_at_idx", + "columns": [ + { + "expression": "locked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_type_created_idx": { + "name": "outbox_event_type_created_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.paused_executions": { + "name": "paused_executions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_snapshot": { + "name": "execution_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "pause_points": { + "name": "pause_points", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "total_pause_count": { + "name": "total_pause_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "resumed_count": { + "name": "resumed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "automatic_resume_retry_count": { + "name": "automatic_resume_retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'paused'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "paused_at": { + "name": "paused_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "next_resume_at": { + "name": "next_resume_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "paused_executions_workflow_id_idx": { + "name": "paused_executions_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_status_idx": { + "name": "paused_executions_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_execution_id_unique": { + "name": "paused_executions_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_next_resume_at_idx": { + "name": "paused_executions_next_resume_at_idx", + "columns": [ + { + "expression": "next_resume_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'paused' AND next_resume_at IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "paused_executions_workflow_id_workflow_id_fk": { + "name": "paused_executions_workflow_id_workflow_id_fk", + "tableFrom": "paused_executions", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pending_credential_draft": { + "name": "pending_credential_draft", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config": { + "name": "oauth_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "pending_draft_organization_id_idx": { + "name": "pending_draft_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pending_draft_user_provider_org": { + "name": "pending_draft_user_provider_org", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pending_draft_user_provider_ws": { + "name": "pending_draft_user_provider_ws", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "pending_credential_draft_user_id_user_id_fk": { + "name": "pending_credential_draft_user_id_user_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_workspace_id_workspace_id_fk": { + "name": "pending_credential_draft_workspace_id_workspace_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_organization_id_organization_id_fk": { + "name": "pending_credential_draft_organization_id_organization_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_credential_id_credential_id_fk": { + "name": "pending_credential_draft_credential_id_credential_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "pending_draft_owner_check": { + "name": "pending_draft_owner_check", + "value": "num_nonnulls(\"pending_credential_draft\".\"workspace_id\", \"pending_credential_draft\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.people_directory_entry": { + "name": "people_directory_entry", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manager_external_id": { + "name": "manager_external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "people_directory_entry_source_id_idx": { + "name": "people_directory_entry_source_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_entry_email_idx": { + "name": "people_directory_entry_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_entry_manager_idx": { + "name": "people_directory_entry_manager_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "manager_external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_entry_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_entry_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_entry", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_issue": { + "name": "people_directory_issue", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fields": { + "name": "fields", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "resolution": { + "name": "resolution", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference": { + "name": "reference", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kept_previous": { + "name": "kept_previous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "since": { + "name": "since", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "people_directory_issue_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_issue_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_issue", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_issue_organization_id_external_id_kind_pk": { + "name": "people_directory_issue_organization_id_external_id_kind_pk", + "columns": ["organization_id", "external_id", "kind"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_page": { + "name": "people_directory_page", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "page_hash": { + "name": "page_hash", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "people_directory_page_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_page_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_page", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_page_organization_id_run_id_page_hash_pk": { + "name": "people_directory_page_organization_id_run_id_page_hash_pk", + "columns": ["organization_id", "run_id", "page_hash"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_scim_change": { + "name": "people_directory_scim_change", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "changed_at": { + "name": "changed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "people_directory_scim_change_due_idx": { + "name": "people_directory_scim_change_due_idx", + "columns": [ + { + "expression": "changed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_scim_change_organization_id_organization_id_fk": { + "name": "people_directory_scim_change_organization_id_organization_id_fk", + "tableFrom": "people_directory_scim_change", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_stage": { + "name": "people_directory_stage", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "proposed_id": { + "name": "proposed_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "employee_number": { + "name": "employee_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue": { + "name": "issue", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue_fields": { + "name": "issue_fields", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manager_external_id": { + "name": "manager_external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reports_cursor": { + "name": "reports_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reports_complete": { + "name": "reports_complete", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "people_directory_stage_run_email_idx": { + "name": "people_directory_stage_run_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_stage_pending_idx": { + "name": "people_directory_stage_pending_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "NOT \"people_directory_stage\".\"reports_complete\"", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_stage_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_stage_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_stage", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_stage_organization_id_run_id_external_id_pk": { + "name": "people_directory_stage_organization_id_run_id_external_id_pk", + "columns": ["organization_id", "run_id", "external_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "people_directory_stage_email_check": { + "name": "people_directory_stage_email_check", + "value": "\"people_directory_stage\".\"email\" IS NOT NULL OR \"people_directory_stage\".\"issue\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.people_directory_sync": { + "name": "people_directory_sync", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_target": { + "name": "source_target", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_credential": { + "name": "encrypted_credential", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "configured_by": { + "name": "configured_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_token": { + "name": "lease_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "run_started_at": { + "name": "run_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "users_read": { + "name": "users_read", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "unmatched_managers": { + "name": "unmatched_managers", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "retry_count": { + "name": "retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_sync_at": { + "name": "next_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_attempt_at": { + "name": "last_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_success_at": { + "name": "last_success_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_directory_sync_due_idx": { + "name": "people_directory_sync_due_idx", + "columns": [ + { + "expression": "next_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_sync_organization_id_organization_id_fk": { + "name": "people_directory_sync_organization_id_organization_id_fk", + "tableFrom": "people_directory_sync", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "people_directory_sync_configured_by_user_id_fk": { + "name": "people_directory_sync_configured_by_user_id_fk", + "tableFrom": "people_directory_sync", + "tableTo": "user", + "columnsFrom": ["configured_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_slack_identity": { + "name": "people_slack_identity", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_team_id": { + "name": "slack_team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_user_id": { + "name": "slack_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_slack_identity_email_idx": { + "name": "people_slack_identity_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_slack_identity_organization_id_organization_id_fk": { + "name": "people_slack_identity_organization_id_organization_id_fk", + "tableFrom": "people_slack_identity", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_slack_identity_organization_id_slack_team_id_email_pk": { + "name": "people_slack_identity_organization_id_slack_team_id_email_pk", + "columns": ["organization_id", "slack_team_id", "email"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_slack_sync": { + "name": "people_slack_sync", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "next_refresh_at": { + "name": "next_refresh_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "lease_token": { + "name": "lease_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refreshed_at": { + "name": "refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_slack_sync_due_idx": { + "name": "people_slack_sync_due_idx", + "columns": [ + { + "expression": "next_refresh_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_slack_sync_organization_id_organization_id_fk": { + "name": "people_slack_sync_organization_id_organization_id_fk", + "tableFrom": "people_slack_sync", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_access_request": { + "name": "permission_access_request", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requester_id": { + "name": "requester_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope_key": { + "name": "scope_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_key": { + "name": "target_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target": { + "name": "target", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "target_label": { + "name": "target_label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "membership_id": { + "name": "membership_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "group_name": { + "name": "group_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decision": { + "name": "decision", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "decided_at": { + "name": "decided_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "permission_access_request_pending_unique": { + "name": "permission_access_request_pending_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requester_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"permission_access_request\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_access_request_org_queue_idx": { + "name": "permission_access_request_org_queue_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_access_request_requester_idx": { + "name": "permission_access_request_requester_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requester_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_access_request_organization_id_organization_id_fk": { + "name": "permission_access_request_organization_id_organization_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_access_request_requester_id_user_id_fk": { + "name": "permission_access_request_requester_id_user_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "user", + "columnsFrom": ["requester_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_access_request_decided_by_user_id_fk": { + "name": "permission_access_request_decided_by_user_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "user", + "columnsFrom": ["decided_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "permission_access_request_status_check": { + "name": "permission_access_request_status_check", + "value": "\"permission_access_request\".\"status\" in ('pending', 'fulfilled', 'declined', 'cancelled', 'closed')" + } + }, + "isRLSEnabled": false + }, + "public.permission_group": { + "name": "permission_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "membership_mode": { + "name": "membership_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'inherit'" + } + }, + "indexes": { + "permission_group_created_by_idx": { + "name": "permission_group_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_organization_name_unique": { + "name": "permission_group_organization_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_organization_default_unique": { + "name": "permission_group_organization_default_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "is_default = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_organization_id_organization_id_fk": { + "name": "permission_group_organization_id_organization_id_fk", + "tableFrom": "permission_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_created_by_user_id_fk": { + "name": "permission_group_created_by_user_id_fk", + "tableFrom": "permission_group", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_group_member": { + "name": "permission_group_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permission_group_member_group_user_unique": { + "name": "permission_group_member_group_user_unique", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_member_organization_user_idx": { + "name": "permission_group_member_organization_user_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_member_permission_group_id_permission_group_id_fk": { + "name": "permission_group_member_permission_group_id_permission_group_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_organization_id_organization_id_fk": { + "name": "permission_group_member_organization_id_organization_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_user_id_user_id_fk": { + "name": "permission_group_member_user_id_user_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_assigned_by_user_id_fk": { + "name": "permission_group_member_assigned_by_user_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "user", + "columnsFrom": ["assigned_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_group_workspace": { + "name": "permission_group_workspace", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permission_group_workspace_workspace_id_idx": { + "name": "permission_group_workspace_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_workspace_group_workspace_unique": { + "name": "permission_group_workspace_group_workspace_unique", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_workspace_permission_group_id_permission_group_id_fk": { + "name": "permission_group_workspace_permission_group_id_permission_group_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_workspace_workspace_id_workspace_id_fk": { + "name": "permission_group_workspace_workspace_id_workspace_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_workspace_organization_id_organization_id_fk": { + "name": "permission_group_workspace_organization_id_organization_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permissions": { + "name": "permissions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permissions_entity_idx": { + "name": "permissions_entity_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permissions_user_entity_permission_idx": { + "name": "permissions_user_entity_permission_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permissions_unique_constraint": { + "name": "permissions_unique_constraint", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permissions_user_id_user_id_fk": { + "name": "permissions_user_id_user_id_fk", + "tableFrom": "permissions", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pinned_item": { + "name": "pinned_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pinned_at": { + "name": "pinned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "pinned_item_user_workspace_idx": { + "name": "pinned_item_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pinned_item_resource_idx": { + "name": "pinned_item_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pinned_item_user_resource_unique": { + "name": "pinned_item_user_resource_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "pinned_item_user_id_user_id_fk": { + "name": "pinned_item_user_id_user_id_fk", + "tableFrom": "pinned_item", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pinned_item_workspace_id_workspace_id_fk": { + "name": "pinned_item_workspace_id_workspace_id_fk", + "tableFrom": "pinned_item", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project": { + "name": "project", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_scope_key": { + "name": "organization_scope_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END", + "type": "stored" + } + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "project_organization_archive_id_idx": { + "name": "project_organization_archive_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "project_owner_archive_id_idx": { + "name": "project_owner_archive_id_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_organization_id_organization_id_fk": { + "name": "project_organization_id_organization_id_fk", + "tableFrom": "project", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "project_owner_id_user_id_fk": { + "name": "project_owner_id_user_id_fk", + "tableFrom": "project", + "tableTo": "user", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "project_id_organization_scope_unique": { + "name": "project_id_organization_scope_unique", + "nullsNotDistinct": false, + "columns": ["id", "organization_scope_key"] + } + }, + "policies": {}, + "checkConstraints": { + "project_name_length": { + "name": "project_name_length", + "value": "char_length(btrim(\"project\".\"name\")) BETWEEN 1 AND 100" + } + }, + "isRLSEnabled": false + }, + "public.public_share": { + "name": "public_share", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_emails": { + "name": "allowed_emails", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "public_share_entity_id_idx": { + "name": "public_share_entity_id_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_token_unique": { + "name": "public_share_token_unique", + "columns": [ + { + "expression": "token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_resource_unique": { + "name": "public_share_resource_unique", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_resource_id_idx": { + "name": "public_share_resource_id_idx", + "columns": [ + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_workspace_id_idx": { + "name": "public_share_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "public_share_workspace_id_workspace_id_fk": { + "name": "public_share_workspace_id_workspace_id_fk", + "tableFrom": "public_share", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "public_share_created_by_user_id_fk": { + "name": "public_share_created_by_user_id_fk", + "tableFrom": "public_share", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "public_share_entity_binding_check": { + "name": "public_share_entity_binding_check", + "value": "\n (\"public_share\".\"entity_type\" IS NULL AND \"public_share\".\"entity_id\" IS NULL AND \"public_share\".\"workspace_id\" IS NOT NULL)\n OR (\"public_share\".\"entity_type\" IS NOT NULL AND \"public_share\".\"entity_id\" IS NOT NULL AND char_length(\"public_share\".\"entity_id\") > 0\n AND ((\"public_share\".\"entity_type\" = 'workspace' AND \"public_share\".\"workspace_id\" IS NOT NULL AND \"public_share\".\"entity_id\" = \"public_share\".\"workspace_id\")\n OR (\"public_share\".\"entity_type\" = 'project' AND \"public_share\".\"workspace_id\" IS NULL AND \"public_share\".\"resource_type\" = 'file')))\n " + } + }, + "isRLSEnabled": false + }, + "public.resource_policy": { + "name": "resource_policy", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "document": { + "name": "document", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "resource_policy_organization_id_idx": { + "name": "resource_policy_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resource_policy_resource_unique": { + "name": "resource_policy_resource_unique", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resource_policy_workspace_id_idx": { + "name": "resource_policy_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resource_policy_workspace_id_workspace_id_fk": { + "name": "resource_policy_workspace_id_workspace_id_fk", + "tableFrom": "resource_policy", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "resource_policy_organization_id_organization_id_fk": { + "name": "resource_policy_organization_id_organization_id_fk", + "tableFrom": "resource_policy", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "resource_policy_created_by_user_id_fk": { + "name": "resource_policy_created_by_user_id_fk", + "tableFrom": "resource_policy", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "resource_policy_updated_by_user_id_fk": { + "name": "resource_policy_updated_by_user_id_fk", + "tableFrom": "resource_policy", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "resource_policy_owner_check": { + "name": "resource_policy_owner_check", + "value": "num_nonnulls(\"resource_policy\".\"workspace_id\", \"resource_policy\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.resume_queue": { + "name": "resume_queue", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "paused_execution_id": { + "name": "paused_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_execution_id": { + "name": "parent_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "new_execution_id": { + "name": "new_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context_id": { + "name": "context_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resume_input": { + "name": "resume_input", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "queued_at": { + "name": "queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "resume_queue_parent_status_idx": { + "name": "resume_queue_parent_status_idx", + "columns": [ + { + "expression": "parent_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resume_queue_new_execution_idx": { + "name": "resume_queue_new_execution_idx", + "columns": [ + { + "expression": "new_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resume_queue_paused_execution_id_paused_executions_id_fk": { + "name": "resume_queue_paused_execution_id_paused_executions_id_fk", + "tableFrom": "resume_queue", + "tableTo": "paused_executions", + "columnsFrom": ["paused_execution_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sandbox_image": { + "name": "sandbox_image", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "spec_hash": { + "name": "spec_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "spec": { + "name": "spec", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "sandbox_image_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "image_ref": { + "name": "image_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_image_id": { + "name": "provider_image_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "materialization_generation": { + "name": "materialization_generation", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_detail": { + "name": "error_detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sandbox_image_provider_spec_unique": { + "name": "sandbox_image_provider_spec_unique", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "spec_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sandbox_image_status_idx": { + "name": "sandbox_image_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sandbox_image_last_used_idx": { + "name": "sandbox_image_last_used_idx", + "columns": [ + { + "expression": "last_used_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_connection": { + "name": "scim_connection", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "settings": { + "name": "settings", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_request_at": { + "name": "last_request_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "reconcile_lock_token": { + "name": "reconcile_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reconcile_lease_at": { + "name": "reconcile_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "reconciled_at": { + "name": "reconciled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_connection_organization_unique": { + "name": "scim_connection_organization_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_connection_reconcile_due_idx": { + "name": "scim_connection_reconcile_due_idx", + "columns": [ + { + "expression": "reconciled_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_connection_organization_id_organization_id_fk": { + "name": "scim_connection_organization_id_organization_id_fk", + "tableFrom": "scim_connection", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_connection_created_by_user_id_fk": { + "name": "scim_connection_created_by_user_id_fk", + "tableFrom": "scim_connection", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_credential": { + "name": "scim_credential", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_by": { + "name": "revoked_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_credential_token_hash_unique": { + "name": "scim_credential_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_credential_connection_idx": { + "name": "scim_credential_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_credential_connection_id_scim_connection_id_fk": { + "name": "scim_credential_connection_id_scim_connection_id_fk", + "tableFrom": "scim_credential", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_credential_revoked_by_user_id_fk": { + "name": "scim_credential_revoked_by_user_id_fk", + "tableFrom": "scim_credential", + "tableTo": "user", + "columnsFrom": ["revoked_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "scim_credential_created_by_user_id_fk": { + "name": "scim_credential_created_by_user_id_fk", + "tableFrom": "scim_credential", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_group": { + "name": "scim_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name_key": { + "name": "display_name_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_connection_display_name_unique": { + "name": "scim_group_connection_display_name_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_connection_external_id_unique": { + "name": "scim_group_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "external_id is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_connection_order_idx": { + "name": "scim_group_connection_order_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_connection_id_scim_connection_id_fk": { + "name": "scim_group_connection_id_scim_connection_id_fk", + "tableFrom": "scim_group", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_group_mapping": { + "name": "scim_group_mapping", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_kind": { + "name": "target_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_mapping_permission_group_idx": { + "name": "scim_group_mapping_permission_group_idx", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_mapping_workspace_idx": { + "name": "scim_group_mapping_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_mapping_group_target_unique": { + "name": "scim_group_mapping_group_target_unique", + "columns": [ + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"permission_group_id\", \"workspace_id\", \"role\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_mapping_group_id_scim_group_id_fk": { + "name": "scim_group_mapping_group_id_scim_group_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "scim_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_permission_group_id_permission_group_id_fk": { + "name": "scim_group_mapping_permission_group_id_permission_group_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_workspace_id_workspace_id_fk": { + "name": "scim_group_mapping_workspace_id_workspace_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_created_by_user_id_fk": { + "name": "scim_group_mapping_created_by_user_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "scim_group_mapping_target_shape": { + "name": "scim_group_mapping_target_shape", + "value": "(\n (\"scim_group_mapping\".\"target_kind\" = 'permission_group' AND \"scim_group_mapping\".\"permission_group_id\" IS NOT NULL AND \"scim_group_mapping\".\"workspace_id\" IS NULL AND \"scim_group_mapping\".\"permission_type\" IS NULL AND \"scim_group_mapping\".\"role\" IS NULL)\n OR (\"scim_group_mapping\".\"target_kind\" = 'workspace' AND \"scim_group_mapping\".\"workspace_id\" IS NOT NULL AND \"scim_group_mapping\".\"permission_type\" IS NOT NULL AND \"scim_group_mapping\".\"permission_group_id\" IS NULL AND \"scim_group_mapping\".\"role\" IS NULL)\n OR (\"scim_group_mapping\".\"target_kind\" = 'org_role' AND \"scim_group_mapping\".\"role\" IS NOT NULL AND \"scim_group_mapping\".\"permission_group_id\" IS NULL AND \"scim_group_mapping\".\"workspace_id\" IS NULL AND \"scim_group_mapping\".\"permission_type\" IS NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.scim_group_member": { + "name": "scim_group_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scim_user_id": { + "name": "scim_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_member_group_user_unique": { + "name": "scim_group_member_group_user_unique", + "columns": [ + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_member_scim_user_idx": { + "name": "scim_group_member_scim_user_idx", + "columns": [ + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_member_group_id_scim_group_id_fk": { + "name": "scim_group_member_group_id_scim_group_id_fk", + "tableFrom": "scim_group_member", + "tableTo": "scim_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_member_scim_user_id_scim_user_id_fk": { + "name": "scim_group_member_scim_user_id_scim_user_id_fk", + "tableFrom": "scim_group_member", + "tableTo": "scim_user", + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_projection_grant": { + "name": "scim_projection_grant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scim_user_id": { + "name": "scim_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_kind": { + "name": "target_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "baseline_permission": { + "name": "baseline_permission", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'directory'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_projection_grant_user_target_unique": { + "name": "scim_projection_grant_user_target_unique", + "columns": [ + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_projection_grant_connection_idx": { + "name": "scim_projection_grant_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_projection_grant_connection_id_scim_connection_id_fk": { + "name": "scim_projection_grant_connection_id_scim_connection_id_fk", + "tableFrom": "scim_projection_grant", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_projection_grant_scim_user_id_scim_user_id_fk": { + "name": "scim_projection_grant_scim_user_id_scim_user_id_fk", + "tableFrom": "scim_projection_grant", + "tableTo": "scim_user", + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_request_log": { + "name": "scim_request_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scim_type": { + "name": "scim_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_request_log_connection_created_idx": { + "name": "scim_request_log_connection_created_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_request_log_connection_id_scim_connection_id_fk": { + "name": "scim_request_log_connection_id_scim_connection_id_fk", + "tableFrom": "scim_request_log", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_user": { + "name": "scim_user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_name": { + "name": "user_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "attributes": { + "name": "attributes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_user_connection_user_unique": { + "name": "scim_user_connection_user_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_user_name_unique": { + "name": "scim_user_connection_user_name_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_external_id_unique": { + "name": "scim_user_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "external_id is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_order_idx": { + "name": "scim_user_connection_order_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_user_idx": { + "name": "scim_user_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_user_connection_id_scim_connection_id_fk": { + "name": "scim_user_connection_id_scim_connection_id_fk", + "tableFrom": "scim_user", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_user_user_id_user_id_fk": { + "name": "scim_user_user_id_user_id_fk", + "tableFrom": "scim_user", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_user_tombstone": { + "name": "scim_user_tombstone", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_user_tombstone_connection_external_id_unique": { + "name": "scim_user_tombstone_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_tombstone_user_idx": { + "name": "scim_user_tombstone_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_user_tombstone_connection_id_scim_connection_id_fk": { + "name": "scim_user_tombstone_connection_id_scim_connection_id_fk", + "tableFrom": "scim_user_tombstone", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_user_tombstone_user_id_user_id_fk": { + "name": "scim_user_tombstone_user_id_user_id_fk", + "tableFrom": "scim_user_tombstone", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.secret_usage": { + "name": "secret_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_name": { + "name": "secret_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_scope": { + "name": "secret_scope", + "type": "secret_usage_scope", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "secret_owner_user_id": { + "name": "secret_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "source": { + "name": "source", + "type": "secret_usage_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "usage_date": { + "name": "usage_date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "use_count": { + "name": "use_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "last_execution_id": { + "name": "last_execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_trigger": { + "name": "last_trigger", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "secret_usage_bucket_unique": { + "name": "secret_usage_bucket_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_date", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "secret_usage_secret_recent_idx": { + "name": "secret_usage_secret_recent_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_used_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "secret_usage_workspace_id_workspace_id_fk": { + "name": "secret_usage_workspace_id_workspace_id_fk", + "tableFrom": "secret_usage", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "active_organization_id": { + "name": "active_organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "session_user_id_idx": { + "name": "session_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "session_active_organization_id_organization_id_fk": { + "name": "session_active_organization_id_organization_id_fk", + "tableFrom": "session", + "tableTo": "organization", + "columnsFrom": ["active_organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "theme": { + "name": "theme", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "auto_connect": { + "name": "auto_connect", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "telemetry_enabled": { + "name": "telemetry_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "email_preferences": { + "name": "email_preferences", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "billing_usage_notifications_enabled": { + "name": "billing_usage_notifications_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "super_user_mode_enabled": { + "name": "super_user_mode_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "mothership_environment": { + "name": "mothership_environment", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "error_notifications_enabled": { + "name": "error_notifications_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "snap_to_grid_size": { + "name": "snap_to_grid_size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "show_action_bar": { + "name": "show_action_bar", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "auto_focus_on_click": { + "name": "auto_focus_on_click", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "copilot_auto_allowed_tools": { + "name": "copilot_auto_allowed_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "last_active_workspace_id": { + "name": "last_active_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "settings_user_id_user_id_fk": { + "name": "settings_user_id_user_id_fk", + "tableFrom": "settings", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "settings_user_id_unique": { + "name": "settings_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sim_link": { + "name": "sim_link", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_name": { + "name": "normalized_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_url": { + "name": "default_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "unlisted": { + "name": "unlisted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "restrict_edit": { + "name": "restrict_edit", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "visit_count": { + "name": "visit_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_visited_at": { + "name": "last_visited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sim_link_organization_name_unique": { + "name": "sim_link_organization_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sim_link_created_by_idx": { + "name": "sim_link_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sim_link_organization_id_organization_id_fk": { + "name": "sim_link_organization_id_organization_id_fk", + "tableFrom": "sim_link", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sim_link_created_by_user_id_fk": { + "name": "sim_link_created_by_user_id_fk", + "tableFrom": "sim_link", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sim_trigger_state": { + "name": "sim_trigger_state", + "schema": "", + "columns": { + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope_key": { + "name": "scope_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "last_fired_at": { + "name": "last_fired_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "sim_trigger_state_workflow_id_workflow_id_fk": { + "name": "sim_trigger_state_workflow_id_workflow_id_fk", + "tableFrom": "sim_trigger_state", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "sim_trigger_state_workflow_id_block_id_scope_key_pk": { + "name": "sim_trigger_state_workflow_id_block_id_scope_key_pk", + "columns": ["workflow_id", "block_id", "scope_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill": { + "name": "skill", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_workspace_name_unique": { + "name": "skill_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_workspace_id_workspace_id_fk": { + "name": "skill_workspace_id_workspace_id_fk", + "tableFrom": "skill", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_user_id_user_id_fk": { + "name": "skill_user_id_user_id_fk", + "tableFrom": "skill", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill_member": { + "name": "skill_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_member_user_id_idx": { + "name": "skill_member_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skill_member_unique": { + "name": "skill_member_unique", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_member_skill_id_skill_id_fk": { + "name": "skill_member_skill_id_skill_id_fk", + "tableFrom": "skill_member", + "tableTo": "skill", + "columnsFrom": ["skill_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_member_user_id_user_id_fk": { + "name": "skill_member_user_id_user_id_fk", + "tableFrom": "skill_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_member_invited_by_user_id_fk": { + "name": "skill_member_invited_by_user_id_fk", + "tableFrom": "skill_member", + "tableTo": "user", + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_app": { + "name": "slack_app", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_client_secret": { + "name": "encrypted_client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_signing_secret": { + "name": "encrypted_signing_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "slack_app_organization_id_organization_id_fk": { + "name": "slack_app_organization_id_organization_id_fk", + "tableFrom": "slack_app", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "slack_app_owner_check": { + "name": "slack_app_owner_check", + "value": "(\"slack_app\".\"kind\" = 'custom' AND \"slack_app\".\"organization_id\" IS NOT NULL) OR (\"slack_app\".\"kind\" = 'shared' AND \"slack_app\".\"organization_id\" IS NULL)" + }, + "slack_app_custom_credentials_check": { + "name": "slack_app_custom_credentials_check", + "value": "\"slack_app\".\"kind\" = 'shared' OR (\"slack_app\".\"client_id\" IS NOT NULL AND \"slack_app\".\"encrypted_client_secret\" IS NOT NULL AND \"slack_app\".\"encrypted_signing_secret\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.slack_search_installation": { + "name": "slack_search_installation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_id": { + "name": "app_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_app_id": { + "name": "slack_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team_name": { + "name": "team_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bot_user_id": { + "name": "bot_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enterprise_id": { + "name": "enterprise_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "credential_version": { + "name": "credential_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_outcome": { + "name": "last_outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_event_at": { + "name": "last_event_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "slack_search_installation_organization_idx": { + "name": "slack_search_installation_organization_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_credential_unique": { + "name": "slack_search_installation_credential_unique", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_app_team_unique": { + "name": "slack_search_installation_app_team_unique", + "columns": [ + { + "expression": "app_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_active_team_unique": { + "name": "slack_search_installation_active_team_unique", + "columns": [ + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"slack_search_installation\".\"enabled\" = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_search_installation_organization_id_organization_id_fk": { + "name": "slack_search_installation_organization_id_organization_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_search_installation_credential_id_credential_id_fk": { + "name": "slack_search_installation_credential_id_credential_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_search_installation_slack_app_id_slack_app_id_fk": { + "name": "slack_search_installation_slack_app_id_slack_app_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "slack_app", + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_search_turn": { + "name": "slack_search_turn", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "slack_search_turn_ordinal_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "conversation_key": { + "name": "conversation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "lease_id": { + "name": "lease_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "slack_search_turn_event_unique": { + "name": "slack_search_turn_event_unique", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_pending_idx": { + "name": "slack_search_turn_pending_idx", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_thread_idx": { + "name": "slack_search_turn_thread_idx", + "columns": [ + { + "expression": "conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_active_thread_unique": { + "name": "slack_search_turn_active_thread_unique", + "columns": [ + { + "expression": "conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"slack_search_turn\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_search_turn_installation_id_slack_search_installation_id_fk": { + "name": "slack_search_turn_installation_id_slack_search_installation_id_fk", + "tableFrom": "slack_search_turn", + "tableTo": "slack_search_installation", + "columnsFrom": ["installation_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sso_domain": { + "name": "sso_domain", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "verification_token": { + "name": "verification_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "verified_at": { + "name": "verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "primary_provider_id": { + "name": "primary_provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sso_domain_domain_idx": { + "name": "sso_domain_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_domain_org_domain_unique": { + "name": "sso_domain_org_domain_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_domain_verified_unique": { + "name": "sso_domain_verified_unique", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "status = 'verified'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sso_domain_organization_id_organization_id_fk": { + "name": "sso_domain_organization_id_organization_id_fk", + "tableFrom": "sso_domain", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sso_domain_created_by_user_id_fk": { + "name": "sso_domain_created_by_user_id_fk", + "tableFrom": "sso_domain", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sso_provider": { + "name": "sso_provider", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oidc_config": { + "name": "oidc_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "saml_config": { + "name": "saml_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "domain_verified": { + "name": "domain_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "jit_provisioning_enabled": { + "name": "jit_provisioning_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + } + }, + "indexes": { + "sso_provider_provider_id_unique": { + "name": "sso_provider_provider_id_unique", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_domain_idx": { + "name": "sso_provider_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_user_id_idx": { + "name": "sso_provider_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_organization_id_idx": { + "name": "sso_provider_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sso_provider_user_id_user_id_fk": { + "name": "sso_provider_user_id_user_id_fk", + "tableFrom": "sso_provider", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sso_provider_organization_id_organization_id_fk": { + "name": "sso_provider_organization_id_organization_id_fk", + "tableFrom": "sso_provider", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.subscription": { + "name": "subscription", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "period_start": { + "name": "period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "period_end": { + "name": "period_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "cancel_at": { + "name": "cancel_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "canceled_at": { + "name": "canceled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "seats": { + "name": "seats", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "trial_start": { + "name": "trial_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trial_end": { + "name": "trial_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "billing_interval": { + "name": "billing_interval", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_schedule_id": { + "name": "stripe_schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "last_closed_period_start": { + "name": "last_closed_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "allowance_period_start": { + "name": "allowance_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "allowance_seats": { + "name": "allowance_seats", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "allowance_seat_months": { + "name": "allowance_seat_months", + "type": "numeric", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "subscription_reference_status_idx": { + "name": "subscription_reference_status_idx", + "columns": [ + { + "expression": "reference_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "subscription_cycle_close_lagging_idx": { + "name": "subscription_cycle_close_lagging_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"subscription\".\"status\" in ('active', 'past_due') and \"subscription\".\"period_start\" is not null and (\"subscription\".\"last_closed_period_start\" is null or \"subscription\".\"last_closed_period_start\" < \"subscription\".\"period_start\")", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "check_enterprise_metadata": { + "name": "check_enterprise_metadata", + "value": "plan != 'enterprise' OR metadata IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.table_jobs": { + "name": "table_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "rows_processed": { + "name": "rows_processed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "table_jobs_one_active_per_table": { + "name": "table_jobs_one_active_per_table", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"table_jobs\".\"status\" = 'running' AND \"table_jobs\".\"type\" <> 'export'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_jobs_watchdog_idx": { + "name": "table_jobs_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_jobs_table_started_idx": { + "name": "table_jobs_table_started_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_jobs_table_id_user_table_definitions_id_fk": { + "name": "table_jobs_table_id_user_table_definitions_id_fk", + "tableFrom": "table_jobs", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_jobs_workspace_id_workspace_id_fk": { + "name": "table_jobs_workspace_id_workspace_id_fk", + "tableFrom": "table_jobs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_row_executions": { + "name": "table_row_executions", + "schema": "", + "columns": { + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "row_id": { + "name": "row_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "running_block_ids": { + "name": "running_block_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "block_errors": { + "name": "block_errors", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "capability_governed_user_id": { + "name": "capability_governed_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enrichment_details": { + "name": "enrichment_details", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "table_row_executions_table_status_idx": { + "name": "table_row_executions_table_status_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_row_executions\".\"status\" IN ('queued', 'running', 'pending')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_row_executions_execution_id_idx": { + "name": "table_row_executions_execution_id_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_row_executions\".\"execution_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_row_executions_table_group_idx": { + "name": "table_row_executions_table_group_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_row_executions_table_id_user_table_definitions_id_fk": { + "name": "table_row_executions_table_id_user_table_definitions_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_row_executions_row_id_user_table_rows_id_fk": { + "name": "table_row_executions_row_id_user_table_rows_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user_table_rows", + "columnsFrom": ["row_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_row_executions_capability_governed_user_id_user_id_fk": { + "name": "table_row_executions_capability_governed_user_id_user_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user", + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "table_row_executions_row_id_group_id_pk": { + "name": "table_row_executions_row_id_group_id_pk", + "columns": ["row_id", "group_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_run_dispatches": { + "name": "table_run_dispatches", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "cursor": { + "name": "cursor", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit": { + "name": "limit", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "processed_count": { + "name": "processed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_manual_run": { + "name": "is_manual_run", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "triggered_by_user_id": { + "name": "triggered_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capability_governed_user_id": { + "name": "capability_governed_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_at": { + "name": "requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "heartbeat_at": { + "name": "heartbeat_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "table_run_dispatches_active_idx": { + "name": "table_run_dispatches_active_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_run_dispatches_watchdog_idx": { + "name": "table_run_dispatches_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requested_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_run_dispatches_governed_active_idx": { + "name": "table_run_dispatches_governed_active_idx", + "columns": [ + { + "expression": "capability_governed_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_run_dispatches\".\"status\" IN ('pending', 'dispatching')", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_run_dispatches_table_id_user_table_definitions_id_fk": { + "name": "table_run_dispatches_table_id_user_table_definitions_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_run_dispatches_workspace_id_workspace_id_fk": { + "name": "table_run_dispatches_workspace_id_workspace_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_run_dispatches_triggered_by_user_id_user_id_fk": { + "name": "table_run_dispatches_triggered_by_user_id_user_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user", + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "table_run_dispatches_capability_governed_user_id_user_id_fk": { + "name": "table_run_dispatches_capability_governed_user_id_user_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user", + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_views": { + "name": "table_views", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "table_views_table_created_idx": { + "name": "table_views_table_created_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_views_workspace_created_idx": { + "name": "table_views_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_views_table_default_unique": { + "name": "table_views_table_default_unique", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "is_default = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_views_table_id_user_table_definitions_id_fk": { + "name": "table_views_table_id_user_table_definitions_id_fk", + "tableFrom": "table_views", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_views_workspace_id_workspace_id_fk": { + "name": "table_views_workspace_id_workspace_id_fk", + "tableFrom": "table_views", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_views_created_by_user_id_fk": { + "name": "table_views_created_by_user_id_fk", + "tableFrom": "table_views", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.trial_card": { + "name": "trial_card", + "schema": "", + "columns": { + "fingerprint": { + "name": "fingerprint", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "trial_card_user_id_idx": { + "name": "trial_card_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "trial_card_user_id_user_id_fk": { + "name": "trial_card_user_id_user_id_fk", + "tableFrom": "trial_card", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.upload_session": { + "name": "upload_session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "purpose": { + "name": "purpose", + "type": "upload_session_purpose", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "upload_session_method", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "storage_context": { + "name": "storage_context", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "final_key": { + "name": "final_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_provider": { + "name": "storage_provider", + "type": "upload_session_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "provider_upload_id": { + "name": "provider_upload_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_object_version": { + "name": "provider_object_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_size": { + "name": "file_size", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "part_size": { + "name": "part_size", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "part_count": { + "name": "part_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "upload_session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'uploading'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "processing_lease_id": { + "name": "processing_lease_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_lease_expires_at": { + "name": "processing_lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_file_id": { + "name": "completed_file_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "upload_session_token_hash_unique": { + "name": "upload_session_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "upload_session_final_key_unique": { + "name": "upload_session_final_key_unique", + "columns": [ + { + "expression": "final_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "upload_session_status_expires_at_idx": { + "name": "upload_session_status_expires_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.usage_log": { + "name": "usage_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category": { + "name": "category", + "type": "usage_log_category", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "usage_log_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "cost": { + "name": "cost", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "event_key": { + "name": "event_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_entity_type": { + "name": "billing_entity_type", + "type": "billing_entity_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "billing_entity_id": { + "name": "billing_entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_period_start": { + "name": "billing_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "billing_period_end": { + "name": "billing_period_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "usage_log_user_created_at_idx": { + "name": "usage_log_user_created_at_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_source_idx": { + "name": "usage_log_source_idx", + "columns": [ + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_workflow_id_idx": { + "name": "usage_log_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_event_key_unique": { + "name": "usage_log_event_key_unique", + "columns": [ + { + "expression": "event_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"usage_log\".\"event_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_billing_entity_period_cost_idx": { + "name": "usage_log_billing_entity_period_cost_idx", + "columns": [ + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_period_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_period_end", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"usage_log\".\"billing_entity_type\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_billing_entity_created_at_cost_idx": { + "name": "usage_log_billing_entity_created_at_cost_idx", + "columns": [ + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"usage_log\".\"billing_entity_type\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_workspace_created_at_cost_idx": { + "name": "usage_log_workspace_created_at_cost_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_execution_id_idx": { + "name": "usage_log_execution_id_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "usage_log_user_id_user_id_fk": { + "name": "usage_log_user_id_user_id_fk", + "tableFrom": "usage_log", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "usage_log_workspace_id_workspace_id_fk": { + "name": "usage_log_workspace_id_workspace_id_fk", + "tableFrom": "usage_log", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "usage_log_workflow_id_workflow_id_fk": { + "name": "usage_log_workflow_id_workflow_id_fk", + "tableFrom": "usage_log", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "usage_log_billing_scope_all_or_none": { + "name": "usage_log_billing_scope_all_or_none", + "value": "(\n (\"usage_log\".\"billing_entity_type\" IS NULL AND \"usage_log\".\"billing_entity_id\" IS NULL AND \"usage_log\".\"billing_period_start\" IS NULL AND \"usage_log\".\"billing_period_end\" IS NULL)\n OR\n (\"usage_log\".\"billing_entity_type\" IS NOT NULL AND \"usage_log\".\"billing_entity_id\" IS NOT NULL AND \"usage_log\".\"billing_period_start\" IS NOT NULL AND \"usage_log\".\"billing_period_end\" IS NOT NULL AND \"usage_log\".\"billing_period_start\" < \"usage_log\".\"billing_period_end\")\n )" + } + }, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_email": { + "name": "normalized_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'user'" + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "suspension_source": { + "name": "suspension_source", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_email_lower_idx": { + "name": "user_email_lower_idx", + "columns": [ + { + "expression": "lower(btrim(\"email\"))", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_gmail_mailbox_idx": { + "name": "user_gmail_mailbox_idx", + "columns": [ + { + "expression": "(CASE WHEN split_part(lower(btrim(\"email\")), '@', 2) IN ('gmail.com', 'googlemail.com') THEN replace(split_part(split_part(lower(btrim(\"email\")), '@', 1), '+', 1), '.', '') || '@gmail.com' END)", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "(CASE WHEN split_part(lower(btrim(\"user\".\"email\")), '@', 2) IN ('gmail.com', 'googlemail.com') THEN replace(split_part(split_part(lower(btrim(\"user\".\"email\")), '@', 1), '+', 1), '.', '') || '@gmail.com' END) IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": ["email"] + }, + "user_normalized_email_unique": { + "name": "user_normalized_email_unique", + "nullsNotDistinct": false, + "columns": ["normalized_email"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_stats": { + "name": "user_stats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "current_usage_limit": { + "name": "current_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'5'" + }, + "usage_limit_updated_at": { + "name": "usage_limit_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "last_period_cost": { + "name": "last_period_cost", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'0'" + }, + "billed_overage_this_period": { + "name": "billed_overage_this_period", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "credit_balance": { + "name": "credit_balance", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "last_period_copilot_cost": { + "name": "last_period_copilot_cost", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'0'" + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "free_tier_eligible": { + "name": "free_tier_eligible", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "billing_blocked": { + "name": "billing_blocked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "billing_blocked_reason": { + "name": "billing_blocked_reason", + "type": "billing_blocked_reason", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "limit_notifications": { + "name": "limit_notifications", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + } + }, + "indexes": {}, + "foreignKeys": { + "user_stats_user_id_user_id_fk": { + "name": "user_stats_user_id_user_id_fk", + "tableFrom": "user_stats", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_stats_user_id_unique": { + "name": "user_stats_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_definitions": { + "name": "user_table_definitions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "schema": { + "name": "schema", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "max_rows": { + "name": "max_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10000 + }, + "row_count": { + "name": "row_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "rows_version": { + "name": "rows_version", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "schema_locked": { + "name": "schema_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "insert_locked": { + "name": "insert_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "update_locked": { + "name": "update_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "delete_locked": { + "name": "delete_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "user_table_def_workspace_id_idx": { + "name": "user_table_def_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_folder_id_idx": { + "name": "user_table_def_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_created_by_idx": { + "name": "user_table_def_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "user_table_def_workspace_name_unique": { + "name": "user_table_def_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"user_table_definitions\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_archived_at_idx": { + "name": "user_table_def_archived_at_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_workspace_archived_partial_idx": { + "name": "user_table_def_workspace_archived_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"user_table_definitions\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_definitions_workspace_id_workspace_id_fk": { + "name": "user_table_definitions_workspace_id_workspace_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_definitions_folder_id_folder_id_fk": { + "name": "user_table_definitions_folder_id_folder_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "user_table_definitions_created_by_user_id_fk": { + "name": "user_table_definitions_created_by_user_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_row_changes": { + "name": "user_table_row_changes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "user_table_row_changes_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "row_delta": { + "name": "row_delta", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "user_table_row_changes_table_id_idx": { + "name": "user_table_row_changes_table_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_row_changes_table_id_user_table_definitions_id_fk": { + "name": "user_table_row_changes_table_id_user_table_definitions_id_fk", + "tableFrom": "user_table_row_changes", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_row_secret_provenance": { + "name": "user_table_row_secret_provenance", + "schema": "", + "columns": { + "row_id": { + "name": "row_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_table_row_secret_provenance_row_id_user_table_rows_id_fk": { + "name": "user_table_row_secret_provenance_row_id_user_table_rows_id_fk", + "tableFrom": "user_table_row_secret_provenance", + "tableTo": "user_table_rows", + "columnsFrom": ["row_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_table_row_secret_provenance_status_check": { + "name": "user_table_row_secret_provenance_status_check", + "value": "\"user_table_row_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.user_table_rows": { + "name": "user_table_rows", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_table_rows_created_by_idx": { + "name": "user_table_rows_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"user_table_rows\".\"created_by\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "user_table_rows_tenant_data_gin_idx": { + "name": "user_table_rows_tenant_data_gin_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"data\" jsonb_path_ops", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "user_table_rows_workspace_table_idx": { + "name": "user_table_rows_workspace_table_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_position_idx": { + "name": "user_table_rows_table_position_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_order_key_idx": { + "name": "user_table_rows_table_order_key_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_created_id_idx": { + "name": "user_table_rows_table_created_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_id_id_idx": { + "name": "user_table_rows_table_id_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_rows_table_id_user_table_definitions_id_fk": { + "name": "user_table_rows_table_id_user_table_definitions_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_rows_workspace_id_workspace_id_fk": { + "name": "user_table_rows_workspace_id_workspace_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_rows_created_by_user_id_fk": { + "name": "user_table_rows_created_by_user_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "verification_expires_at_idx": { + "name": "verification_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.webhook": { + "name": "webhook", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_status": { + "name": "registration_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_generation": { + "name": "registration_generation", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "config_fingerprint": { + "name": "config_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "prepared_at": { + "name": "prepared_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "routing_key": { + "name": "routing_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_config": { + "name": "provider_config", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "path_deployment_unique": { + "name": "path_deployment_unique", + "columns": [ + { + "expression": "path", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_workflow_deployment_idx": { + "name": "webhook_workflow_deployment_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_routing_key_active_idx": { + "name": "webhook_routing_key_active_idx", + "columns": [ + { + "expression": "routing_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"webhook\".\"archived_at\" IS NULL AND \"webhook\".\"routing_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_archived_at_partial_idx": { + "name": "webhook_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"webhook\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_webhook_on_provider_is_active_workflow_id_deploym_bdeed5468": { + "name": "idx_webhook_on_provider_is_active_workflow_id_deploym_bdeed5468", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_webhook_on_workflow_id_block_id_updated_at_desc": { + "name": "idx_webhook_on_workflow_id_block_id_updated_at_desc", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_active_registration_unique": { + "name": "webhook_active_registration_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"registration_status\" = 'active' AND \"webhook\".\"block_id\" IS NOT NULL AND \"webhook\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_candidate_registration_unique": { + "name": "webhook_candidate_registration_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"registration_status\" = 'candidate' AND \"webhook\".\"block_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_registration_status_generation_idx": { + "name": "webhook_registration_status_generation_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "registration_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "registration_generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "webhook_workflow_id_workflow_id_fk": { + "name": "webhook_workflow_id_workflow_id_fk", + "tableFrom": "webhook", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "webhook_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "webhook_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "webhook", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "webhook_registration_status_check": { + "name": "webhook_registration_status_check", + "value": "\"webhook\".\"registration_status\" IS NULL OR \"webhook\".\"registration_status\" IN ('active', 'candidate', 'retired', 'orphaned')" + }, + "webhook_registration_generation_check": { + "name": "webhook_registration_generation_check", + "value": "\"webhook\".\"registration_generation\" IS NULL OR \"webhook\".\"registration_generation\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.webhook_path_claim": { + "name": "webhook_path_claim", + "schema": "", + "columns": { + "path": { + "name": "path", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "webhook_path_claim_workflow_idx": { + "name": "webhook_path_claim_workflow_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "webhook_path_claim_workflow_id_workflow_id_fk": { + "name": "webhook_path_claim_workflow_id_workflow_id_fk", + "tableFrom": "webhook_path_claim", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "webhook_path_claim_generation_check": { + "name": "webhook_path_claim_generation_check", + "value": "\"webhook_path_claim\".\"generation\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.workflow": { + "name": "workflow", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_synced": { + "name": "last_synced", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "is_deployed": { + "name": "is_deployed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deployed_at": { + "name": "deployed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "is_public_api": { + "name": "is_public_api", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "fork_sync_excluded": { + "name": "fork_sync_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_workspace_id_idx": { + "name": "workflow_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_user_workspace_idx": { + "name": "workflow_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_workspace_folder_name_active_unique": { + "name": "workflow_workspace_folder_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_folder_sort_idx": { + "name": "workflow_folder_sort_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_active_workspace_sort_idx": { + "name": "workflow_active_workspace_sort_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_archived_at_idx": { + "name": "workflow_archived_at_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_workspace_archived_partial_idx": { + "name": "workflow_workspace_archived_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_user_id_user_id_fk": { + "name": "workflow_user_id_user_id_fk", + "tableFrom": "workflow", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_workspace_id_workspace_id_fk": { + "name": "workflow_workspace_id_workspace_id_fk", + "tableFrom": "workflow", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_folder_id_folder_id_fk": { + "name": "workflow_folder_id_folder_id_fk", + "tableFrom": "workflow", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_activity_hourly": { + "name": "workflow_activity_hourly", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "runs": { + "name": "runs", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "completed": { + "name": "completed", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cancelled": { + "name": "cancelled", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "in_flight": { + "name": "in_flight", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "duration_sum_ms": { + "name": "duration_sum_ms", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "duration_count": { + "name": "duration_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "computed_at": { + "name": "computed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_activity_hourly_read_idx": { + "name": "workflow_activity_hourly_read_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "bucket_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "runs", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "completed", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "failed", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cancelled", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "in_flight", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "duration_sum_ms", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "duration_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_activity_hourly_bucket_start_idx": { + "name": "workflow_activity_hourly_bucket_start_idx", + "columns": [ + { + "expression": "bucket_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "workflow_activity_hourly_pk": { + "name": "workflow_activity_hourly_pk", + "columns": ["workspace_id", "bucket_start", "workflow_id", "trigger"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_blocks": { + "name": "workflow_blocks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position_x": { + "name": "position_x", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "position_y": { + "name": "position_y", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "horizontal_handles": { + "name": "horizontal_handles", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "is_wide": { + "name": "is_wide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "advanced_mode": { + "name": "advanced_mode", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "trigger_mode": { + "name": "trigger_mode", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "error_enabled": { + "name": "error_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "retry": { + "name": "retry", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "height": { + "name": "height", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "sub_blocks": { + "name": "sub_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "outputs": { + "name": "outputs", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_blocks_workflow_id_idx": { + "name": "workflow_blocks_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_blocks_type_idx": { + "name": "workflow_blocks_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_blocks_workflow_id_workflow_id_fk": { + "name": "workflow_blocks_workflow_id_workflow_id_fk", + "tableFrom": "workflow_blocks", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_checkpoints": { + "name": "workflow_checkpoints", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_state": { + "name": "workflow_state", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_checkpoints_chat_id_idx": { + "name": "workflow_checkpoints_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_message_id_idx": { + "name": "workflow_checkpoints_message_id_idx", + "columns": [ + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_user_workflow_idx": { + "name": "workflow_checkpoints_user_workflow_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_workflow_chat_idx": { + "name": "workflow_checkpoints_workflow_chat_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_created_at_idx": { + "name": "workflow_checkpoints_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_chat_created_at_idx": { + "name": "workflow_checkpoints_chat_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_checkpoints_user_id_user_id_fk": { + "name": "workflow_checkpoints_user_id_user_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_checkpoints_workflow_id_workflow_id_fk": { + "name": "workflow_checkpoints_workflow_id_workflow_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_checkpoints_chat_id_copilot_chats_id_fk": { + "name": "workflow_checkpoints_chat_id_copilot_chats_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_deployment_operation": { + "name": "workflow_deployment_operation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "previous_active_version_id": { + "name": "previous_active_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "protocol_version": { + "name": "protocol_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'preparing'" + }, + "component_readiness": { + "name": "component_readiness", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_deployment_operation_workflow_generation_unique": { + "name": "workflow_deployment_operation_workflow_generation_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_idempotency_unique": { + "name": "workflow_deployment_operation_workflow_idempotency_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_deployment_operation\".\"idempotency_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_in_flight_unique": { + "name": "workflow_deployment_operation_workflow_in_flight_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_deployment_operation\".\"status\" IN ('preparing', 'activating')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_status_idx": { + "name": "workflow_deployment_operation_workflow_status_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_deployment_version_idx": { + "name": "workflow_deployment_operation_deployment_version_idx", + "columns": [ + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_version_generation_idx": { + "name": "workflow_deployment_operation_workflow_version_generation_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_deployment_operation_workflow_id_workflow_id_fk": { + "name": "workflow_deployment_operation_workflow_id_workflow_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_deployment_operation_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_deployment_operation_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_deployment_operation_previous_active_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_deployment_operation_previous_active_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["previous_active_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workflow_deployment_operation_action_check": { + "name": "workflow_deployment_operation_action_check", + "value": "\"workflow_deployment_operation\".\"action\" IN ('deploy', 'activate')" + }, + "workflow_deployment_operation_status_check": { + "name": "workflow_deployment_operation_status_check", + "value": "\"workflow_deployment_operation\".\"status\" IN ('preparing', 'activating', 'active', 'failed', 'superseded')" + }, + "workflow_deployment_operation_generation_check": { + "name": "workflow_deployment_operation_generation_check", + "value": "\"workflow_deployment_operation\".\"generation\" > 0" + }, + "workflow_deployment_operation_protocol_version_check": { + "name": "workflow_deployment_operation_protocol_version_check", + "value": "\"workflow_deployment_operation\".\"protocol_version\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.workflow_deployment_version": { + "name": "workflow_deployment_version", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_deployment_version_workflow_version_unique": { + "name": "workflow_deployment_version_workflow_version_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_version_workflow_active_idx": { + "name": "workflow_deployment_version_workflow_active_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_version_created_at_idx": { + "name": "workflow_deployment_version_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_deployment_version_workflow_id_workflow_id_fk": { + "name": "workflow_deployment_version_workflow_id_workflow_id_fk", + "tableFrom": "workflow_deployment_version", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_edges": { + "name": "workflow_edges", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_block_id": { + "name": "source_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_block_id": { + "name": "target_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_handle": { + "name": "source_handle", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_handle": { + "name": "target_handle", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_edges_workflow_source_idx": { + "name": "workflow_edges_workflow_source_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_workflow_target_idx": { + "name": "workflow_edges_workflow_target_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_source_block_fk_idx": { + "name": "workflow_edges_source_block_fk_idx", + "columns": [ + { + "expression": "source_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_target_block_fk_idx": { + "name": "workflow_edges_target_block_fk_idx", + "columns": [ + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_edges_workflow_id_workflow_id_fk": { + "name": "workflow_edges_workflow_id_workflow_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_edges_source_block_id_workflow_blocks_id_fk": { + "name": "workflow_edges_source_block_id_workflow_blocks_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow_blocks", + "columnsFrom": ["source_block_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_edges_target_block_id_workflow_blocks_id_fk": { + "name": "workflow_edges_target_block_id_workflow_blocks_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow_blocks", + "columnsFrom": ["target_block_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_execution_logs": { + "name": "workflow_execution_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state_snapshot_id": { + "name": "state_snapshot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "execution_deadline_at": { + "name": "execution_deadline_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_duration_ms": { + "name": "total_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "execution_data": { + "name": "execution_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "cost_total": { + "name": "cost_total", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "models_used": { + "name": "models_used", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_execution_logs_state_snapshot_id_idx": { + "name": "workflow_execution_logs_state_snapshot_id_idx", + "columns": [ + { + "expression": "state_snapshot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_deployment_version_id_idx": { + "name": "workflow_execution_logs_deployment_version_id_idx", + "columns": [ + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_trigger_idx": { + "name": "workflow_execution_logs_trigger_idx", + "columns": [ + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_level_idx": { + "name": "workflow_execution_logs_level_idx", + "columns": [ + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_started_at_idx": { + "name": "workflow_execution_logs_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_execution_id_unique": { + "name": "workflow_execution_logs_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workflow_started_at_idx": { + "name": "workflow_execution_logs_workflow_started_at_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_activity_level_idx": { + "name": "workflow_execution_logs_workspace_activity_level_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "total_duration_ms", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_started_at_id_desc_idx": { + "name": "workflow_execution_logs_workspace_started_at_id_desc_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC NULLS LAST", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "\"id\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_cost_total_idx": { + "name": "workflow_execution_logs_workspace_cost_total_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost_total", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_models_used_idx": { + "name": "workflow_execution_logs_models_used_idx", + "columns": [ + { + "expression": "models_used", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "workflow_execution_logs_workspace_ended_at_id_idx": { + "name": "workflow_execution_logs_workspace_ended_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"ended_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_running_started_at_idx": { + "name": "workflow_execution_logs_running_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_running_deadline_idx": { + "name": "workflow_execution_logs_running_deadline_idx", + "columns": [ + { + "expression": "execution_deadline_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'running' AND \"workflow_execution_logs\".\"execution_deadline_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_redacting_started_at_idx": { + "name": "workflow_execution_logs_redacting_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'redacting'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_redacting_deadline_idx": { + "name": "workflow_execution_logs_redacting_deadline_idx", + "columns": [ + { + "expression": "execution_deadline_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'redacting' AND \"workflow_execution_logs\".\"execution_deadline_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_completed_ended_at_idx": { + "name": "workflow_execution_logs_completed_ended_at_idx", + "columns": [ + { + "expression": "ended_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'completed' AND \"workflow_execution_logs\".\"level\" = 'info' AND \"workflow_execution_logs\".\"ended_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_late_end_idx": { + "name": "workflow_execution_logs_late_end_idx", + "columns": [ + { + "expression": "ended_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"ended_at\" >= \"workflow_execution_logs\".\"started_at\" + interval '2 hours'", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_execution_logs_workflow_id_workflow_id_fk": { + "name": "workflow_execution_logs_workflow_id_workflow_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workflow_execution_logs_workspace_id_workspace_id_fk": { + "name": "workflow_execution_logs_workspace_id_workspace_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_execution_logs_state_snapshot_id_workflow_execution_snapshots_id_fk": { + "name": "workflow_execution_logs_state_snapshot_id_workflow_execution_snapshots_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow_execution_snapshots", + "columnsFrom": ["state_snapshot_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workflow_execution_logs_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_execution_logs_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_execution_snapshots": { + "name": "workflow_execution_snapshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state_hash": { + "name": "state_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state_data": { + "name": "state_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_snapshots_hash_idx": { + "name": "workflow_snapshots_hash_idx", + "columns": [ + { + "expression": "state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_snapshots_workflow_hash_idx": { + "name": "workflow_snapshots_workflow_hash_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_snapshots_created_at_idx": { + "name": "workflow_snapshots_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_execution_snapshots_workflow_id_workflow_id_fk": { + "name": "workflow_execution_snapshots_workflow_id_workflow_id_fk", + "tableFrom": "workflow_execution_snapshots", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_mcp_server": { + "name": "workflow_mcp_server", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_public": { + "name": "is_public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_mcp_server_workspace_id_idx": { + "name": "workflow_mcp_server_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_created_by_idx": { + "name": "workflow_mcp_server_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_deleted_at_idx": { + "name": "workflow_mcp_server_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_workspace_deleted_partial_idx": { + "name": "workflow_mcp_server_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_mcp_server\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_mcp_server_workspace_id_workspace_id_fk": { + "name": "workflow_mcp_server_workspace_id_workspace_id_fk", + "tableFrom": "workflow_mcp_server", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_mcp_server_created_by_user_id_fk": { + "name": "workflow_mcp_server_created_by_user_id_fk", + "tableFrom": "workflow_mcp_server", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_mcp_tool": { + "name": "workflow_mcp_tool", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "server_id": { + "name": "server_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_description": { + "name": "tool_description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parameter_schema": { + "name": "parameter_schema", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "parameter_description_overrides": { + "name": "parameter_description_overrides", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'::json" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_mcp_tool_server_id_idx": { + "name": "workflow_mcp_tool_server_id_idx", + "columns": [ + { + "expression": "server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_workflow_id_idx": { + "name": "workflow_mcp_tool_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_server_workflow_unique": { + "name": "workflow_mcp_tool_server_workflow_unique", + "columns": [ + { + "expression": "server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_mcp_tool\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_archived_at_partial_idx": { + "name": "workflow_mcp_tool_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_mcp_tool\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_mcp_tool_server_id_workflow_mcp_server_id_fk": { + "name": "workflow_mcp_tool_server_id_workflow_mcp_server_id_fk", + "tableFrom": "workflow_mcp_tool", + "tableTo": "workflow_mcp_server", + "columnsFrom": ["server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_mcp_tool_workflow_id_workflow_id_fk": { + "name": "workflow_mcp_tool_workflow_id_workflow_id_fk", + "tableFrom": "workflow_mcp_tool", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_schedule": { + "name": "workflow_schedule", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_operation_id": { + "name": "deployment_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cron_expression": { + "name": "cron_expression", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_ran_at": { + "name": "last_ran_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_queued_at": { + "name": "last_queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trigger_type": { + "name": "trigger_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'UTC'" + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "infra_retry_count": { + "name": "infra_retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "disabled_reason": { + "name": "disabled_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'workflow'" + }, + "job_title": { + "name": "job_title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'persistent'" + }, + "success_condition": { + "name": "success_condition", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "max_runs": { + "name": "max_runs", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "source_chat_id": { + "name": "source_chat_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_task_name": { + "name": "source_task_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_user_id": { + "name": "source_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_scope": { + "name": "secret_scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'all'" + }, + "mounted_secrets": { + "name": "mounted_secrets", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "job_history": { + "name": "job_history", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "contexts": { + "name": "contexts", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "excluded_dates": { + "name": "excluded_dates", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_budget_usd": { + "name": "run_budget_usd", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_schedule_workflow_block_deployment_unique": { + "name": "workflow_schedule_workflow_block_deployment_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_workflow_deployment_idx": { + "name": "workflow_schedule_workflow_deployment_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_archived_at_partial_idx": { + "name": "workflow_schedule_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_workflow_schedule_on_source_workspace_id_source_t_c07f3bba6": { + "name": "idx_workflow_schedule_on_source_workspace_id_source_t_c07f3bba6", + "columns": [ + { + "expression": "source_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_due_workflow_idx": { + "name": "workflow_schedule_due_workflow_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL AND \"workflow_schedule\".\"status\" NOT IN ('disabled', 'completed') AND (\"workflow_schedule\".\"source_type\" = 'workflow' OR \"workflow_schedule\".\"source_type\" IS NULL)", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_due_job_idx": { + "name": "workflow_schedule_due_job_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL AND \"workflow_schedule\".\"status\" NOT IN ('disabled', 'completed') AND \"workflow_schedule\".\"source_type\" = 'job'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_schedule_workflow_id_workflow_id_fk": { + "name": "workflow_schedule_workflow_id_workflow_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_schedule_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_deployment_operation_id_workflow_deployment_operation_id_fk": { + "name": "workflow_schedule_deployment_operation_id_workflow_deployment_operation_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow_deployment_operation", + "columnsFrom": ["deployment_operation_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workflow_schedule_source_user_id_user_id_fk": { + "name": "workflow_schedule_source_user_id_user_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "user", + "columnsFrom": ["source_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_source_workspace_id_workspace_id_fk": { + "name": "workflow_schedule_source_workspace_id_workspace_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workspace", + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_source_meta": { + "name": "workflow_source_meta", + "schema": "", + "columns": { + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "meta": { + "name": "meta", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workflow_source_meta_workflow_id_workflow_id_fk": { + "name": "workflow_source_meta_workflow_id_workflow_id_fk", + "tableFrom": "workflow_source_meta", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_subflows": { + "name": "workflow_subflows", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_subflows_workflow_type_idx": { + "name": "workflow_subflows_workflow_type_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_subflows_workflow_id_workflow_id_fk": { + "name": "workflow_subflows_workflow_id_workflow_id_fk", + "tableFrom": "workflow_subflows", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_test": { + "name": "workflow_test", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_file_id": { + "name": "body_file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cases": { + "name": "cases", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_test_workspace_name_unique": { + "name": "workflow_test_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_test\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_test_body_file_unique": { + "name": "workflow_test_body_file_unique", + "columns": [ + { + "expression": "body_file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_test_workspace_id_workspace_id_fk": { + "name": "workflow_test_workspace_id_workspace_id_fk", + "tableFrom": "workflow_test", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_body_file_id_workspace_files_id_fk": { + "name": "workflow_test_body_file_id_workspace_files_id_fk", + "tableFrom": "workflow_test", + "tableTo": "workspace_files", + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workflow_test_created_by_user_id_user_id_fk": { + "name": "workflow_test_created_by_user_id_user_id_fk", + "tableFrom": "workflow_test", + "tableTo": "user", + "columnsFrom": ["created_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_test_run": { + "name": "workflow_test_run", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "test_id": { + "name": "test_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "passed": { + "name": "passed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "skipped": { + "name": "skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "report": { + "name": "report", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ran_against": { + "name": "ran_against", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "progress": { + "name": "progress", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "triggered_by_actor": { + "name": "triggered_by_actor", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "triggered_by_user_id": { + "name": "triggered_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_test_run_test_version_started_idx": { + "name": "workflow_test_run_test_version_started_idx", + "columns": [ + { + "expression": "test_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_test_run_test_id_workflow_test_id_fk": { + "name": "workflow_test_run_test_id_workflow_test_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "workflow_test", + "columnsFrom": ["test_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_run_workspace_id_workspace_id_fk": { + "name": "workflow_test_run_workspace_id_workspace_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_run_triggered_by_user_id_user_id_fk": { + "name": "workflow_test_run_triggered_by_user_id_user_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "user", + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workflow_test_run_version_check": { + "name": "workflow_test_run_version_check", + "value": "\"workflow_test_run\".\"version\" IN ('draft', 'deployed')" + }, + "workflow_test_run_status_check": { + "name": "workflow_test_run_status_check", + "value": "\"workflow_test_run\".\"status\" IN ('running', 'passed', 'failed', 'error')" + }, + "workflow_test_run_completed_check": { + "name": "workflow_test_run_completed_check", + "value": "(\"workflow_test_run\".\"status\" = 'running') = (\"workflow_test_run\".\"completed_at\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workload_identity_pending_subject": { + "name": "workload_identity_pending_subject", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "workload_identity_pending_subject_subject_unique": { + "name": "workload_identity_pending_subject_subject_unique", + "columns": [ + { + "expression": "subject", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workload_identity_pending_subject_issuer_idx": { + "name": "workload_identity_pending_subject_issuer_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workload_identity_pending_subject_user_id_idx": { + "name": "workload_identity_pending_subject_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workload_identity_pending_subject_workspace_id_workspace_id_fk": { + "name": "workload_identity_pending_subject_workspace_id_workspace_id_fk", + "tableFrom": "workload_identity_pending_subject", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workload_identity_pending_subject_user_id_user_id_fk": { + "name": "workload_identity_pending_subject_user_id_user_id_fk", + "tableFrom": "workload_identity_pending_subject", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace": { + "name": "workspace", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'#33C482'" + }, + "logo_url": { + "name": "logo_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_scope_key": { + "name": "organization_scope_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END", + "type": "stored" + } + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_mode": { + "name": "workspace_mode", + "type": "workspace_mode", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'grandfathered_shared'" + }, + "billed_account_user_id": { + "name": "billed_account_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "allow_personal_api_keys": { + "name": "allow_personal_api_keys", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "inbox_enabled": { + "name": "inbox_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "inbox_address": { + "name": "inbox_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbox_provider_id": { + "name": "inbox_provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbox_secret_scope": { + "name": "inbox_secret_scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'all'" + }, + "inbox_mounted_secrets": { + "name": "inbox_mounted_secrets", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "organization_assigned_at": { + "name": "organization_assigned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "forked_from_workspace_id": { + "name": "forked_from_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fork_sync_new_workflows_excluded": { + "name": "fork_sync_new_workflows_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_owner_id_idx": { + "name": "workspace_owner_id_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_organization_id_idx": { + "name": "workspace_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_billed_account_user_id_idx": { + "name": "workspace_billed_account_user_id_idx", + "columns": [ + { + "expression": "billed_account_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_project_id_id_idx": { + "name": "workspace_project_id_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_mode_idx": { + "name": "workspace_mode_idx", + "columns": [ + { + "expression": "workspace_mode", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_forked_from_workspace_id_idx": { + "name": "workspace_forked_from_workspace_id_idx", + "columns": [ + { + "expression": "forked_from_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_inbox_provider_id_idx": { + "name": "workspace_inbox_provider_id_idx", + "columns": [ + { + "expression": "inbox_provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace\".\"inbox_provider_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_owner_id_user_id_fk": { + "name": "workspace_owner_id_user_id_fk", + "tableFrom": "workspace", + "tableTo": "user", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_organization_id_organization_id_fk": { + "name": "workspace_organization_id_organization_id_fk", + "tableFrom": "workspace", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_project_id_project_id_fk": { + "name": "workspace_project_id_project_id_fk", + "tableFrom": "workspace", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "workspace_billed_account_user_id_user_id_fk": { + "name": "workspace_billed_account_user_id_user_id_fk", + "tableFrom": "workspace", + "tableTo": "user", + "columnsFrom": ["billed_account_user_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workspace_forked_from_workspace_id_workspace_id_fk": { + "name": "workspace_forked_from_workspace_id_workspace_id_fk", + "tableFrom": "workspace", + "tableTo": "workspace", + "columnsFrom": ["forked_from_workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_project_organization_fk": { + "name": "workspace_project_organization_fk", + "tableFrom": "workspace", + "tableTo": "project", + "columnsFrom": ["project_id", "organization_scope_key"], + "columnsTo": ["id", "organization_scope_key"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workspace_fork_project_fk": { + "name": "workspace_fork_project_fk", + "tableFrom": "workspace", + "tableTo": "workspace", + "columnsFrom": ["forked_from_workspace_id", "project_id"], + "columnsTo": ["id", "project_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "workspace_id_project_unique": { + "name": "workspace_id_project_unique", + "nullsNotDistinct": false, + "columns": ["id", "project_id"] + } + }, + "policies": {}, + "checkConstraints": { + "workspace_storage_used_bytes_non_negative": { + "name": "workspace_storage_used_bytes_non_negative", + "value": "\"workspace\".\"storage_used_bytes\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.workspace_byok_keys": { + "name": "workspace_byok_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_byok_workspace_provider_idx": { + "name": "workspace_byok_workspace_provider_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_byok_keys_workspace_id_workspace_id_fk": { + "name": "workspace_byok_keys_workspace_id_workspace_id_fk", + "tableFrom": "workspace_byok_keys", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_byok_keys_created_by_user_id_fk": { + "name": "workspace_byok_keys_created_by_user_id_fk", + "tableFrom": "workspace_byok_keys", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_environment": { + "name": "workspace_environment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_environment_workspace_unique": { + "name": "workspace_environment_workspace_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_environment_workspace_id_workspace_id_fk": { + "name": "workspace_environment_workspace_id_workspace_id_fk", + "tableFrom": "workspace_environment", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file": { + "name": "workspace_file", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_file_workspace_id_idx": { + "name": "workspace_file_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_deleted_at_idx": { + "name": "workspace_file_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_workspace_deleted_partial_idx": { + "name": "workspace_file_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_uploaded_by_idx": { + "name": "workspace_file_uploaded_by_idx", + "columns": [ + { + "expression": "uploaded_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_workspace_id_workspace_id_fk": { + "name": "workspace_file_workspace_id_workspace_id_fk", + "tableFrom": "workspace_file", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_uploaded_by_user_id_fk": { + "name": "workspace_file_uploaded_by_user_id_fk", + "tableFrom": "workspace_file", + "tableTo": "user", + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "workspace_file_key_unique": { + "name": "workspace_file_key_unique", + "nullsNotDistinct": false, + "columns": ["key"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_collab_state": { + "name": "workspace_file_collab_state", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "doc_state": { + "name": "doc_state", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_file_collab_state_file_id_workspace_files_id_fk": { + "name": "workspace_file_collab_state_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_collab_state", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_search_backfill": { + "name": "workspace_file_search_backfill", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "after_workspace_id": { + "name": "after_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_entity_type": { + "name": "after_entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_entity_id": { + "name": "after_entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_file_id": { + "name": "after_file_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_search_build": { + "name": "workspace_file_search_build", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "artifact_key": { + "name": "artifact_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_file_search_build_file_idx": { + "name": "workspace_file_search_build_file_idx", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_build_cleanup_idx": { + "name": "workspace_file_search_build_cleanup_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_build\".\"expires_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_build_owner_check": { + "name": "file_search_build_owner_check", + "value": "(\"workspace_file_search_build\".\"entity_type\" IS NULL AND \"workspace_file_search_build\".\"entity_id\" IS NULL AND \"workspace_file_search_build\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_build\".\"entity_type\" = 'workspace' AND \"workspace_file_search_build\".\"entity_id\" = \"workspace_file_search_build\".\"workspace_id\") OR (\"workspace_file_search_build\".\"entity_type\" = 'project' AND length(\"workspace_file_search_build\".\"entity_id\") > 0 AND \"workspace_file_search_build\".\"workspace_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_search_chunk": { + "name": "workspace_file_search_chunk", + "schema": "", + "columns": { + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "line_start": { + "name": "line_start", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "fragment": { + "name": "fragment", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "overlap": { + "name": "overlap", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "file_search_chunk_owner_content_idx": { + "name": "file_search_chunk_owner_content_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "content", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_chunk\".\"entity_type\" = 'project'", + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "workspace_file_search_chunk_line_idx": { + "name": "workspace_file_search_chunk_line_idx", + "columns": [ + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "line_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ordinal", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_chunk_content_idx": { + "name": "workspace_file_search_chunk_content_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "content", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + } + }, + "foreignKeys": { + "workspace_file_search_chunk_build_id_workspace_file_search_build_id_fk": { + "name": "workspace_file_search_chunk_build_id_workspace_file_search_build_id_fk", + "tableFrom": "workspace_file_search_chunk", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_file_search_chunk_pk": { + "name": "workspace_file_search_chunk_pk", + "columns": ["build_id", "ordinal"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_chunk_owner_check": { + "name": "file_search_chunk_owner_check", + "value": "(\"workspace_file_search_chunk\".\"entity_type\" IS NULL AND \"workspace_file_search_chunk\".\"entity_id\" IS NULL AND \"workspace_file_search_chunk\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_chunk\".\"entity_type\" = 'workspace' AND \"workspace_file_search_chunk\".\"entity_id\" = \"workspace_file_search_chunk\".\"workspace_id\") OR (\"workspace_file_search_chunk\".\"entity_type\" = 'project' AND length(\"workspace_file_search_chunk\".\"entity_id\") > 0 AND \"workspace_file_search_chunk\".\"workspace_id\" IS NULL)" + }, + "workspace_file_search_chunk_content_size": { + "name": "workspace_file_search_chunk_content_size", + "value": "octet_length(\"workspace_file_search_chunk\".\"content\") <= 8192" + }, + "workspace_file_search_chunk_position": { + "name": "workspace_file_search_chunk_position", + "value": "\"workspace_file_search_chunk\".\"ordinal\" >= 0 AND \"workspace_file_search_chunk\".\"line_start\" > 0 AND \"workspace_file_search_chunk\".\"overlap\" BETWEEN 0 AND 2" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_search_revision": { + "name": "workspace_file_search_revision", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "workspace_file_search_index_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "line_count": { + "name": "line_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "indexed_bytes": { + "name": "indexed_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "dispatched_at": { + "name": "dispatched_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "handoff_expires_at": { + "name": "handoff_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "build_started_at": { + "name": "build_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "abandoned_builds": { + "name": "abandoned_builds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_build_artifact_key": { + "name": "last_build_artifact_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "file_search_revision_owner_pending_idx": { + "name": "file_search_revision_owner_pending_idx", + "columns": [ + { + "expression": "coalesce(\"entity_type\", 'workspace')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"entity_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_content_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "file_search_revision_owner_status_idx": { + "name": "file_search_revision_owner_status_idx", + "columns": [ + { + "expression": "coalesce(\"entity_type\", 'workspace')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"entity_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_workspace_status_idx": { + "name": "workspace_file_search_revision_workspace_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_build_idx": { + "name": "workspace_file_search_revision_build_idx", + "columns": [ + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_pending_idx": { + "name": "workspace_file_search_revision_pending_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_content_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_active_idx": { + "name": "workspace_file_search_revision_active_idx", + "columns": [ + { + "expression": "dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_search_revision_file_id_workspace_files_id_fk": { + "name": "workspace_file_search_revision_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_search_revision", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_search_revision_build_id_workspace_file_search_build_id_fk": { + "name": "workspace_file_search_revision_build_id_workspace_file_search_build_id_fk", + "tableFrom": "workspace_file_search_revision", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_revision_owner_check": { + "name": "file_search_revision_owner_check", + "value": "(\"workspace_file_search_revision\".\"entity_type\" IS NULL AND \"workspace_file_search_revision\".\"entity_id\" IS NULL AND \"workspace_file_search_revision\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_revision\".\"entity_type\" = 'workspace' AND \"workspace_file_search_revision\".\"entity_id\" = \"workspace_file_search_revision\".\"workspace_id\") OR (\"workspace_file_search_revision\".\"entity_type\" = 'project' AND length(\"workspace_file_search_revision\".\"entity_id\") > 0 AND \"workspace_file_search_revision\".\"workspace_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_secret_provenance": { + "name": "workspace_file_secret_provenance", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_file_secret_provenance_file_id_workspace_files_id_fk": { + "name": "workspace_file_secret_provenance_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_secret_provenance", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_file_secret_provenance_status_check": { + "name": "workspace_file_secret_provenance_status_check", + "value": "\"workspace_file_secret_provenance\".\"status\" IN ('exact', 'unknown', 'unrecorded')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_version": { + "name": "workspace_file_version", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "superseded_at": { + "name": "superseded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "workspace_file_version_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "author_user_ids": { + "name": "author_user_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "restored_from_version": { + "name": "restored_from_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_status": { + "name": "secret_provenance_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_entries": { + "name": "secret_provenance_entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_file_version_file_version_unique": { + "name": "workspace_file_version_file_version_unique", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_key_unique": { + "name": "workspace_file_version_key_unique", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_workspace_id_idx": { + "name": "workspace_file_version_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_workspace_superseded_idx": { + "name": "workspace_file_version_workspace_superseded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "superseded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_version\".\"superseded_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_version_file_id_workspace_files_id_fk": { + "name": "workspace_file_version_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_version", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_version_workspace_id_workspace_id_fk": { + "name": "workspace_file_version_workspace_id_workspace_id_fk", + "tableFrom": "workspace_file_version", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_file_version_provenance_status_check": { + "name": "workspace_file_version_provenance_status_check", + "value": "\"workspace_file_version\".\"secret_provenance_status\" IS NULL OR \"workspace_file_version\".\"secret_provenance_status\" IN ('exact', 'unknown', 'unrecorded')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_files": { + "name": "workspace_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "context": { + "name": "context", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "original_name": { + "name": "original_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "date_trunc('milliseconds', now())" + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_files_project_id_idx": { + "name": "workspace_files_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_project_folder_name_active_unique": { + "name": "workspace_files_project_folder_name_active_unique", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"project_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_key_active_unique": { + "name": "workspace_files_key_active_unique", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_folder_name_active_unique": { + "name": "workspace_files_workspace_folder_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_search_owner_keyset_idx": { + "name": "workspace_files_search_owner_keyset_idx", + "columns": [ + { + "expression": "(CASE WHEN \"project_id\" IS NOT NULL THEN 'project' ELSE 'workspace' END)", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"project_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND ((\"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL) OR (\"workspace_files\".\"context\" = 'project' AND \"workspace_files\".\"project_id\" IS NOT NULL))", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_keyset_idx": { + "name": "workspace_files_workspace_active_keyset_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_uploaded_idx": { + "name": "workspace_files_workspace_active_uploaded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_updated_idx": { + "name": "workspace_files_workspace_active_updated_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_folder_uploaded_idx": { + "name": "workspace_files_workspace_folder_uploaded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_name_trgm_idx": { + "name": "workspace_files_workspace_name_trgm_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "workspace_files_workspace_display_name_idx": { + "name": "workspace_files_workspace_display_name_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "regexp_replace(regexp_replace(regexp_replace(normalize(\"original_name\", NFC), '^[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+|[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+$', '', 'g'), '[\\x01-\\x1f\\x7f]', '', 'g'), '[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+', ' ', 'g')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_chat_display_name_unique": { + "name": "workspace_files_chat_display_name_unique", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"context\" = 'mothership' AND \"workspace_files\".\"chat_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_organization_id_idx": { + "name": "workspace_files_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_key_idx": { + "name": "workspace_files_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_user_id_idx": { + "name": "workspace_files_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_id_idx": { + "name": "workspace_files_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_folder_id_idx": { + "name": "workspace_files_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_context_idx": { + "name": "workspace_files_context_idx", + "columns": [ + { + "expression": "context", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_chat_id_idx": { + "name": "workspace_files_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_deleted_at_idx": { + "name": "workspace_files_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_deleted_partial_idx": { + "name": "workspace_files_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_files_project_id_project_id_fk": { + "name": "workspace_files_project_id_project_id_fk", + "tableFrom": "workspace_files", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "workspace_files_user_id_user_id_fk": { + "name": "workspace_files_user_id_user_id_fk", + "tableFrom": "workspace_files", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_workspace_id_workspace_id_fk": { + "name": "workspace_files_workspace_id_workspace_id_fk", + "tableFrom": "workspace_files", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_organization_id_organization_id_fk": { + "name": "workspace_files_organization_id_organization_id_fk", + "tableFrom": "workspace_files", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_folder_id_folder_id_fk": { + "name": "workspace_files_folder_id_folder_id_fk", + "tableFrom": "workspace_files", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_files_chat_id_copilot_chats_id_fk": { + "name": "workspace_files_chat_id_copilot_chats_id_fk", + "tableFrom": "workspace_files", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_files_owner_check": { + "name": "workspace_files_owner_check", + "value": "num_nonnulls(\"workspace_files\".\"workspace_id\", \"workspace_files\".\"project_id\", \"workspace_files\".\"organization_id\") <= 1" + }, + "workspace_files_workspace_binding_check": { + "name": "workspace_files_workspace_binding_check", + "value": "\"workspace_files\".\"context\" NOT IN ('workspace', 'chat', 'mothership', 'execution', 'workspace-logos') OR \"workspace_files\".\"workspace_id\" IS NOT NULL" + }, + "workspace_files_project_binding_check": { + "name": "workspace_files_project_binding_check", + "value": "(\"workspace_files\".\"project_id\" IS NOT NULL) = (\"workspace_files\".\"context\" = 'project') AND (\"workspace_files\".\"project_id\" IS NULL OR \"workspace_files\".\"chat_id\" IS NULL)" + }, + "workspace_files_organization_binding_check": { + "name": "workspace_files_organization_binding_check", + "value": "\"workspace_files\".\"organization_id\" IS NULL OR (\"workspace_files\".\"workspace_id\" IS NULL AND \"workspace_files\".\"context\" = 'knowledge-base' AND \"workspace_files\".\"folder_id\" IS NULL AND \"workspace_files\".\"chat_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_fork_block_map": { + "name": "workspace_fork_block_map", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_workflow_id": { + "name": "parent_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_block_id": { + "name": "parent_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_workflow_id": { + "name": "child_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_block_id": { + "name": "child_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_block_map_child_ws_parent_unique": { + "name": "workspace_fork_block_map_child_ws_parent_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_child_unique": { + "name": "workspace_fork_block_map_child_ws_child_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_parent_wf_idx": { + "name": "workspace_fork_block_map_child_ws_parent_wf_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_child_wf_idx": { + "name": "workspace_fork_block_map_child_ws_child_wf_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_block_map_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_block_map_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_block_map", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_dependent_value": { + "name": "workspace_fork_dependent_value", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workflow_id": { + "name": "target_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_block_id": { + "name": "target_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sub_block_key": { + "name": "sub_block_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_dependent_value_field_unique": { + "name": "workspace_fork_dependent_value_field_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sub_block_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_dependent_value_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_dependent_value_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_dependent_value", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_promote_run": { + "name": "workspace_fork_promote_run", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workspace_id": { + "name": "target_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "direction": { + "name": "direction", + "type": "workspace_fork_promote_direction", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "snapshot": { + "name": "snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_promote_run_child_ws_target_unique": { + "name": "workspace_fork_promote_run_child_ws_target_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_promote_run_target_ws_idx": { + "name": "workspace_fork_promote_run_target_ws_idx", + "columns": [ + { + "expression": "target_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_promote_run_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_promote_run_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_promote_run", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_promote_run_created_by_user_id_fk": { + "name": "workspace_fork_promote_run_created_by_user_id_fk", + "tableFrom": "workspace_fork_promote_run", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_resource_map": { + "name": "workspace_fork_resource_map", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "workspace_fork_resource_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "parent_resource_id": { + "name": "parent_resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_resource_id": { + "name": "child_resource_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_resource_map_child_type_parent_unique": { + "name": "workspace_fork_resource_map_child_type_parent_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_resource_map_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_resource_map_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_resource_map", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_resource_map_created_by_user_id_fk": { + "name": "workspace_fork_resource_map_created_by_user_id_fk", + "tableFrom": "workspace_fork_resource_map", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_workflow_sync": { + "name": "workspace_fork_workflow_sync", + "schema": "", + "columns": { + "deployment_operation_id": { + "name": "deployment_operation_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_workflow_id": { + "name": "source_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workflow_id": { + "name": "target_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_deployment_version_id": { + "name": "source_deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sequence": { + "name": "sequence", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "workspace_fork_workflow_sync_sequence_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "promote_run_id": { + "name": "promote_run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "activated_at": { + "name": "activated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "rollback_operation_id": { + "name": "rollback_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rolled_back_at": { + "name": "rolled_back_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_fork_workflow_sync_baseline_idx": { + "name": "workspace_fork_workflow_sync_baseline_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sequence", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_fork_workflow_sync\".\"activated_at\" IS NOT NULL AND \"workspace_fork_workflow_sync\".\"rolled_back_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_run_idx": { + "name": "workspace_fork_workflow_sync_run_idx", + "columns": [ + { + "expression": "promote_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_rollback_idx": { + "name": "workspace_fork_workflow_sync_rollback_idx", + "columns": [ + { + "expression": "rollback_operation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_fork_workflow_sync\".\"rollback_operation_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_source_idx": { + "name": "workspace_fork_workflow_sync_source_idx", + "columns": [ + { + "expression": "source_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_target_idx": { + "name": "workspace_fork_workflow_sync_target_idx", + "columns": [ + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_child_workspace_idx": { + "name": "workspace_fork_workflow_sync_child_workspace_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_workflow_sync_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_workflow_sync_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_workflow_sync_source_workflow_id_workflow_id_fk": { + "name": "workspace_fork_workflow_sync_source_workflow_id_workflow_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workflow", + "columnsFrom": ["source_workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_workflow_sync_target_workflow_id_workflow_id_fk": { + "name": "workspace_fork_workflow_sync_target_workflow_id_workflow_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workflow", + "columnsFrom": ["target_workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_operation_receipt": { + "name": "workspace_operation_receipt", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "report": { + "name": "report", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_operation_receipt_request_unique": { + "name": "workspace_operation_receipt_request_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_operation_receipt_workspace_created_idx": { + "name": "workspace_operation_receipt_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_operation_receipt_workspace_id_workspace_id_fk": { + "name": "workspace_operation_receipt_workspace_id_workspace_id_fk", + "tableFrom": "workspace_operation_receipt", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_resource_key": { + "name": "workspace_resource_key", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "workspace_resource_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_resource_key_ws_kind_key_unique": { + "name": "workspace_resource_key_ws_kind_key_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_resource_key_ws_kind_resource_unique": { + "name": "workspace_resource_key_ws_kind_resource_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_resource_key_workspace_id_workspace_id_fk": { + "name": "workspace_resource_key_workspace_id_workspace_id_fk", + "tableFrom": "workspace_resource_key", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_resource_key_created_by_user_id_fk": { + "name": "workspace_resource_key_created_by_user_id_fk", + "tableFrom": "workspace_resource_key", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_resource_key_key_format": { + "name": "workspace_resource_key_key_format", + "value": "\"workspace_resource_key\".\"key\" ~ '^[a-z][a-z0-9_-]{0,63}$'" + }, + "workspace_resource_key_origin_check": { + "name": "workspace_resource_key_origin_check", + "value": "\"workspace_resource_key\".\"origin\" IN ('allocated', 'adopted', 'created')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_sandbox": { + "name": "workspace_sandbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "language": { + "name": "language", + "type": "sandbox_language", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "dependencies": { + "name": "dependencies", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "cli_tools": { + "name": "cli_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "system_packages": { + "name": "system_packages", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "spec_hash": { + "name": "spec_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_sandbox_workspace_name_unique": { + "name": "workspace_sandbox_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_sandbox_spec_hash_idx": { + "name": "workspace_sandbox_spec_hash_idx", + "columns": [ + { + "expression": "spec_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_sandbox_workspace_id_workspace_id_fk": { + "name": "workspace_sandbox_workspace_id_workspace_id_fk", + "tableFrom": "workspace_sandbox", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_sandbox_created_by_user_id_fk": { + "name": "workspace_sandbox_created_by_user_id_fk", + "tableFrom": "workspace_sandbox", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_source_apply_lease": { + "name": "workspace_source_apply_lease", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "acquired_at": { + "name": "acquired_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_source_apply_lease_workspace_id_workspace_id_fk": { + "name": "workspace_source_apply_lease_workspace_id_workspace_id_fk", + "tableFrom": "workspace_source_apply_lease", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_source_staged_blob": { + "name": "workspace_source_staged_blob", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "consumed_at": { + "name": "consumed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_source_staged_blob_scope_hash_unique": { + "name": "workspace_source_staged_blob_scope_hash_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sha256", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_source_staged_blob_expires_at_idx": { + "name": "workspace_source_staged_blob_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_source_staged_blob_workspace_id_workspace_id_fk": { + "name": "workspace_source_staged_blob_workspace_id_workspace_id_fk", + "tableFrom": "workspace_source_staged_blob", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_visit": { + "name": "workspace_visit", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visited_at": { + "name": "visited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_visit_workspace_idx": { + "name": "workspace_visit_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_visit_user_id_user_id_fk": { + "name": "workspace_visit_user_id_user_id_fk", + "tableFrom": "workspace_visit", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_visit_workspace_id_workspace_id_fk": { + "name": "workspace_visit_workspace_id_workspace_id_fk", + "tableFrom": "workspace_visit", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_visit_user_id_workspace_id_pk": { + "name": "workspace_visit_user_id_workspace_id_pk", + "columns": ["user_id", "workspace_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.api_key_access": { + "name": "api_key_access", + "schema": "public", + "values": ["read", "write"] + }, + "public.aws_marketplace_license_status": { + "name": "aws_marketplace_license_status", + "schema": "public", + "values": ["pending", "active", "inactive"] + }, + "public.aws_marketplace_usage_report_status": { + "name": "aws_marketplace_usage_report_status", + "schema": "public", + "values": ["pending", "reported", "rejected"] + }, + "public.background_work_kind": { + "name": "background_work_kind", + "schema": "public", + "values": ["deployment_side_effects", "fork_content_copy", "fork_sync", "fork_rollback"] + }, + "public.background_work_status_value": { + "name": "background_work_status_value", + "schema": "public", + "values": ["pending", "processing", "completed", "completed_with_warnings", "failed"] + }, + "public.billing_blocked_reason": { + "name": "billing_blocked_reason", + "schema": "public", + "values": ["payment_failed", "dispute"] + }, + "public.billing_entity_type": { + "name": "billing_entity_type", + "schema": "public", + "values": ["user", "organization"] + }, + "public.chat_type": { + "name": "chat_type", + "schema": "public", + "values": ["mothership", "copilot"] + }, + "public.copilot_async_tool_status": { + "name": "copilot_async_tool_status", + "schema": "public", + "values": ["pending", "running", "completed", "failed", "cancelled", "delivered"] + }, + "public.copilot_run_status": { + "name": "copilot_run_status", + "schema": "public", + "values": ["active", "paused_waiting_for_tool", "resuming", "complete", "error", "cancelled"] + }, + "public.copilot_tool_permission_decision": { + "name": "copilot_tool_permission_decision", + "schema": "public", + "values": ["allow", "allow_chat", "always_allow", "skip"] + }, + "public.credential_group_enrollment_link_purpose": { + "name": "credential_group_enrollment_link_purpose", + "schema": "public", + "values": ["email", "self", "connect"] + }, + "public.credential_group_enrollment_status": { + "name": "credential_group_enrollment_status", + "schema": "public", + "values": ["invited", "delivery_failed", "in_progress", "completed", "revoked"] + }, + "public.credential_group_status": { + "name": "credential_group_status", + "schema": "public", + "values": ["active", "disabled"] + }, + "public.credential_member_role": { + "name": "credential_member_role", + "schema": "public", + "values": ["admin", "member"] + }, + "public.credential_member_status": { + "name": "credential_member_status", + "schema": "public", + "values": ["active", "pending", "revoked"] + }, + "public.credential_type": { + "name": "credential_type", + "schema": "public", + "values": [ + "oauth", + "managed_oauth", + "managed_mcp", + "env_workspace", + "env_personal", + "service_account", + "personal_token" + ] + }, + "public.data_drain_cadence": { + "name": "data_drain_cadence", + "schema": "public", + "values": ["every_15_minutes", "hourly", "daily"] + }, + "public.data_drain_destination": { + "name": "data_drain_destination", + "schema": "public", + "values": [ + "s3", + "gcs", + "azure_blob", + "sentinel", + "datadog", + "splunk", + "bigquery", + "snowflake", + "webhook" + ] + }, + "public.data_drain_run_status": { + "name": "data_drain_run_status", + "schema": "public", + "values": ["running", "success", "failed"] + }, + "public.data_drain_run_trigger": { + "name": "data_drain_run_trigger", + "schema": "public", + "values": ["cron", "manual"] + }, + "public.data_drain_source": { + "name": "data_drain_source", + "schema": "public", + "values": ["workflow_logs", "job_logs", "audit_logs", "copilot_chats", "copilot_runs"] + }, + "public.execution_large_value_reference_source": { + "name": "execution_large_value_reference_source", + "schema": "public", + "values": ["execution_log", "paused_snapshot"] + }, + "public.folder_resource_type": { + "name": "folder_resource_type", + "schema": "public", + "values": ["workflow", "file", "knowledge_base", "table"] + }, + "public.invitation_kind": { + "name": "invitation_kind", + "schema": "public", + "values": ["organization", "workspace"] + }, + "public.invitation_membership_intent": { + "name": "invitation_membership_intent", + "schema": "public", + "values": ["internal", "external"] + }, + "public.invitation_status": { + "name": "invitation_status", + "schema": "public", + "values": ["pending", "accepted", "rejected", "cancelled", "expired"] + }, + "public.managed_oauth_credential_status": { + "name": "managed_oauth_credential_status", + "schema": "public", + "values": ["active", "needs_reauth", "revoked"] + }, + "public.permission_type": { + "name": "permission_type", + "schema": "public", + "values": ["admin", "write", "read"] + }, + "public.sandbox_image_status": { + "name": "sandbox_image_status", + "schema": "public", + "values": ["pending", "building", "ready", "failed"] + }, + "public.sandbox_language": { + "name": "sandbox_language", + "schema": "public", + "values": ["javascript", "python"] + }, + "public.secret_usage_scope": { + "name": "secret_usage_scope", + "schema": "public", + "values": ["workspace", "personal"] + }, + "public.secret_usage_source": { + "name": "secret_usage_source", + "schema": "public", + "values": ["workflow", "copilot", "mcp"] + }, + "public.upload_session_method": { + "name": "upload_session_method", + "schema": "public", + "values": ["put", "multipart"] + }, + "public.upload_session_provider": { + "name": "upload_session_provider", + "schema": "public", + "values": ["local", "s3", "blob", "gcs"] + }, + "public.upload_session_purpose": { + "name": "upload_session_purpose", + "schema": "public", + "values": [ + "workspace_file", + "project_file", + "table_import", + "knowledge_import", + "knowledge_document", + "profile_picture", + "workspace_logo", + "organization_logo", + "mothership_attachment", + "execution_attachment" + ] + }, + "public.upload_session_status": { + "name": "upload_session_status", + "schema": "public", + "values": [ + "uploading", + "completing", + "finalizing", + "completed", + "aborting", + "aborted", + "failed", + "expired" + ] + }, + "public.usage_log_category": { + "name": "usage_log_category", + "schema": "public", + "values": ["model", "fixed", "tool", "model_unbilled"] + }, + "public.usage_log_source": { + "name": "usage_log_source", + "schema": "public", + "values": [ + "workflow", + "wand", + "copilot", + "workspace-chat", + "mcp_copilot", + "mothership_block", + "knowledge-base", + "voice-input", + "enrichment", + "voice-output", + "api-tool", + "workflow-test" + ] + }, + "public.workspace_file_search_index_status": { + "name": "workspace_file_search_index_status", + "schema": "public", + "values": ["pending", "ready", "skipped", "failed"] + }, + "public.workspace_file_version_source": { + "name": "workspace_file_version_source", + "schema": "public", + "values": ["upload", "user", "api", "copilot", "workflow", "collab", "revert", "unknown"] + }, + "public.workspace_fork_promote_direction": { + "name": "workspace_fork_promote_direction", + "schema": "public", + "values": ["push", "pull"] + }, + "public.workspace_fork_resource_type": { + "name": "workspace_fork_resource_type", + "schema": "public", + "values": [ + "workflow", + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "knowledge_document", + "file", + "file_folder", + "mcp_server", + "workflow_mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ] + }, + "public.workspace_mode": { + "name": "workspace_mode", + "schema": "public", + "values": ["personal", "organization", "grandfathered_shared"] + }, + "public.workspace_resource_kind": { + "name": "workspace_resource_kind", + "schema": "public", + "values": [ + "credential", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ] + } + }, + "schemas": {}, + "sequences": { + "public.copilot_async_tool_calls_persist_seq": { + "name": "copilot_async_tool_calls_persist_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 1f746538122..30ef4130d2b 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -3417,6 +3417,13 @@ "when": 1796283260143, "tag": "0488_people_manager_matching", "breakpoints": true + }, + { + "idx": 489, + "version": "7", + "when": 1796325337826, + "tag": "0489_credential_group_enrollment_links", + "breakpoints": true } ] } diff --git a/packages/db/schema.ts b/packages/db/schema.ts index 9ed28fef08a..f6dc0be418f 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7413,7 +7413,15 @@ export const credentialGroupEnrollment = pgTable( /** Bound once after the invitee signs in with the verified invitation email. */ userId: text('user_id').references(() => user.id, { onDelete: 'cascade' }), status: credentialGroupEnrollmentStatusEnum('status').notNull().default('invited'), + /** + * Mirrors the newest `credential_group_enrollment_link` so a rollback to the pre-link app + * still resolves invitations. contract-pending(after the enrollment-link expand is fully + * deployed and no rollback target predates it): retire this column with its unique index, + * length check, and the legacy branch of `liveEnrollmentLinkCondition` — once deployed, every + * invitation resolves through the link table. + */ invitationTokenHash: text('invitation_token_hash').notNull(), + /** Latest expiry among the enrollment's links; reporting only. */ invitationExpiresAt: timestamp('invitation_expires_at').notNull(), invitedAt: timestamp('invited_at').notNull(), sentAt: timestamp('sent_at'), @@ -7456,6 +7464,44 @@ export const credentialGroupEnrollment = pgTable( }) ) +export const credentialGroupEnrollmentLinkPurposeEnum = pgEnum( + 'credential_group_enrollment_link_purpose', + ['email', 'self', 'connect'] +) + +/** + * One bearer link into an enrollment. Issuing a link never invalidates another; expiry binds + * only while the enrollment has no user, and disconnect or revocation revokes every link. + */ +export const credentialGroupEnrollmentLink = pgTable( + 'credential_group_enrollment_link', + { + id: text('id').primaryKey(), + enrollmentId: text('enrollment_id') + .notNull() + .references(() => credentialGroupEnrollment.id, { onDelete: 'cascade' }), + tokenHash: text('token_hash').notNull(), + purpose: credentialGroupEnrollmentLinkPurposeEnum('purpose').notNull(), + /** Set when the link focuses a single account option. */ + optionId: text('option_id'), + expiresAt: timestamp('expires_at').notNull(), + revokedAt: timestamp('revoked_at'), + createdAt: timestamp('created_at').notNull().defaultNow(), + }, + (table) => ({ + tokenHashUnique: uniqueIndex('credential_group_enrollment_link_token_hash_unique').on( + table.tokenHash + ), + enrollmentIdx: index('credential_group_enrollment_link_enrollment_id_idx').on( + table.enrollmentId + ), + tokenHashLength: check( + 'credential_group_enrollment_link_token_hash_length_check', + sql`length(${table.tokenHash}) = 64` + ), + }) +) + /** Personal Assistant preferences never confer access to another account or override organization policy. */ export const assistantToolPermission = pgTable( 'assistant_tool_permission', diff --git a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts index 3ba0506dae8..a591031c6d2 100644 --- a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts +++ b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts @@ -17,8 +17,10 @@ export class MockCredentialGroupEnrollmentError extends Error { /** * Controllable mock functions for `@/lib/credential-groups/enrollments`. * - * Every function is a bare `vi.fn()` except `mockLockCredentialGroupEnrollmentLifecycle`, which - * resolves `undefined` (an uncontended advisory lock). + * Every function is a bare `vi.fn()` except `mockLockCredentialGroupEnrollmentLifecycle` and + * `mockRevokeCredentialGroupEnrollmentLinks`, which resolve `undefined`, and + * `mockLiveEnrollmentLinkCondition`, which returns a `{ type: 'liveEnrollmentLink', tokenHash }` + * condition node a test can find in a WHERE tree. * * @example * ```ts @@ -32,6 +34,13 @@ export const credentialGroupsEnrollmentsMockFns = { mockLockCredentialGroupEnrollmentLifecycle: vi.fn( async (_executor: unknown, _enrollmentId: string): Promise => {} ), + mockLiveEnrollmentLinkCondition: vi.fn((tokenHash: string) => ({ + type: 'liveEnrollmentLink', + tokenHash, + })), + mockRevokeCredentialGroupEnrollmentLinks: vi.fn( + async (_executor: unknown, _enrollmentId: string, _now?: Date): Promise => {} + ), mockAuthenticatePublicCredentialGroupEnrollment: vi.fn(), mockBindCredentialGroupEnrollmentUser: vi.fn(), mockListCredentialGroupEnrollments: vi.fn(), @@ -65,6 +74,8 @@ const fns = credentialGroupsEnrollmentsMockFns export const credentialGroupsEnrollmentsMock = { CredentialGroupEnrollmentError: MockCredentialGroupEnrollmentError, lockCredentialGroupEnrollmentLifecycle: fns.mockLockCredentialGroupEnrollmentLifecycle, + liveEnrollmentLinkCondition: fns.mockLiveEnrollmentLinkCondition, + revokeCredentialGroupEnrollmentLinks: fns.mockRevokeCredentialGroupEnrollmentLinks, authenticatePublicCredentialGroupEnrollment: fns.mockAuthenticatePublicCredentialGroupEnrollment, bindCredentialGroupEnrollmentUser: fns.mockBindCredentialGroupEnrollmentUser, listCredentialGroupEnrollments: fns.mockListCredentialGroupEnrollments, diff --git a/packages/testing/src/mocks/schema-tables.generated.ts b/packages/testing/src/mocks/schema-tables.generated.ts index 3992fff9994..8b39829be2f 100644 --- a/packages/testing/src/mocks/schema-tables.generated.ts +++ b/packages/testing/src/mocks/schema-tables.generated.ts @@ -1878,6 +1878,16 @@ export const GENERATED_SCHEMA_TABLES = { 'createdAt', 'updatedAt', ], + credentialGroupEnrollmentLink: [ + 'id', + 'enrollmentId', + 'tokenHash', + 'purpose', + 'optionId', + 'expiresAt', + 'revokedAt', + 'createdAt', + ], assistantToolPermission: [ 'organizationId', 'userId', @@ -2566,6 +2576,7 @@ export const GENERATED_SCHEMA_ENUMS = { 'completed', 'revoked', ], + credentialGroupEnrollmentLinkPurposeEnum: ['email', 'self', 'connect'], credentialMemberRoleEnum: ['admin', 'member'], credentialMemberStatusEnum: ['active', 'pending', 'revoked'], dataDrainSourceEnum: ['workflow_logs', 'job_logs', 'audit_logs', 'copilot_chats', 'copilot_runs'], From b71d562e37e92e93a65a23168b271f14b77c0378 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 13:32:33 -0600 Subject: [PATCH 04/26] feat(credential-groups): workflow connection status and requests - Credential block: get_connection_status (collapsed connected / not_connected / needs_reconnect + credentialId + stable connectUrl) and request_connection (constant { requested, connectUrl } result). - Shared connect URL builder lib/credential-groups/connect-url.ts. - Org admin policy for workflow connection requests, stored as a WorkflowConnectionRequests statement in the organization account access policy (v2 documents without it still parse; absent = off). Access updates preserve it. Read/update org operations, route, contract, React Query hook, and an Access tab section. - requestOrganizationAccountConnection: policy-gated (enabled, workspace, email domain, provider), daily cap under a group lock, per-email invitation lock, creates only absent enrollments (never reactivates revoked or re-attributes an admin invite), optional email with the connect link, audited with the workflow as actor. - Expand-only migration: nullable credential_group_enrollment.requested_by_workflow_id. - Real-Postgres integration tests for status mapping and request guards; codec tests. --- .../docs/workflows/blocks/credential.mdx | 20 + .../workflow-requests/route.ts | 40 + apps/sim/blocks/blocks/credential.ts | 70 +- apps/sim/blocks/sdk-names.generated.ts | 2 +- apps/sim/blocks/sdk-names/credential.json | 2 + .../credential-group-invitation-email.tsx | 22 +- .../emails/credential-groups/render.ts | 1 + .../organization-account-workspace-access.tsx | 2 + .../organization-connection-requests.tsx | 283 + .../executor/handlers/credential/handler.ts | 24 + .../hooks/queries/organization-accounts.ts | 30 + .../utils/organization-accounts-keys.ts | 3 + .../api/contracts/organization-accounts.ts | 71 + ...orkflow-connection-requests.integration.ts | 505 + .../application/authorization.ts | 7 + .../application/connection-requests.ts | 250 + .../application/operations.ts | 22 + .../application/organization-access.ts | 18 +- .../organization-connection-requests.ts | 187 + .../workspace-access-policy.test.ts | 82 +- .../application/workspace-access-policy.ts | 149 +- apps/sim/lib/credential-groups/connect-url.ts | 31 + .../connection-request-policy.ts | 66 + .../credential-groups/connection-requests.ts | 253 + apps/sim/lib/credential-groups/enrollments.ts | 2 +- apps/sim/lib/resource-policies/registry.ts | 8 +- .../db/credential-group-resource-policies.ts | 62 + ...489_credential_group_workflow_requests.sql | 1 + .../db/migrations/meta/0489_snapshot.json | 34725 ++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/schema.ts | 2 + .../src/mocks/schema-tables.generated.ts | 1 + 32 files changed, 36908 insertions(+), 40 deletions(-) create mode 100644 apps/sim/app/api/organizations/[id]/connected-accounts/workflow-requests/route.ts create mode 100644 apps/sim/ee/credential-groups/components/organization-connection-requests.tsx create mode 100644 apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts create mode 100644 apps/sim/lib/credential-groups/application/connection-requests.ts create mode 100644 apps/sim/lib/credential-groups/application/organization-connection-requests.ts create mode 100644 apps/sim/lib/credential-groups/connect-url.ts create mode 100644 apps/sim/lib/credential-groups/connection-request-policy.ts create mode 100644 apps/sim/lib/credential-groups/connection-requests.ts create mode 100644 packages/db/migrations/0489_credential_group_workflow_requests.sql create mode 100644 packages/db/migrations/meta/0489_snapshot.json diff --git a/apps/docs/content/docs/workflows/blocks/credential.mdx b/apps/docs/content/docs/workflows/blocks/credential.mdx index 5a38df40a32..c29cbf4b3dc 100644 --- a/apps/docs/content/docs/workflows/blocks/credential.mdx +++ b/apps/docs/content/docs/workflows/blocks/credential.mdx @@ -28,6 +28,8 @@ A credential ID is a reference, not a token. The downstream block resolves and a | **List Credentials** | Return workspace OAuth credential references, optionally filtered by providers. | | **Find Organization Account** | Find exactly one active OAuth contribution by invitation email and provider. | | **List Organization Accounts** | Page through active OAuth contributions, optionally filtered by email and providers. | +| **Get Connection Status** | Report whether a person has connected a provider, with a link they can open to connect it. | +| **Request Connection** | Ask a person to connect a provider, when an organization admin allows workflow requests. | | **Find Organization MCP Connection** | Find exactly one active managed MCP connection by invitation email and MCP provider. | | **List Organization MCP Connections** | Page through active managed MCP connections, optionally filtered by email and provider. | @@ -51,6 +53,8 @@ Authorized workflows in an allowed workspace can discover active contributions f | --- | --- | --- | | Find Organization Account | **Email**, **Provider** | — | | List Organization Accounts | — | **Email**, **Providers**, **Limit**, **Cursor** | +| Get Connection Status | **Email**, **Provider** | — | +| Request Connection | **Email**, **Provider** | — | | Find Organization MCP Connection | **Email**, **MCP provider** | — | | List Organization MCP Connections | — | **Email**, **MCP provider**, **Limit**, **Cursor** | @@ -86,6 +90,22 @@ Pass `` to compatible credential fields. A deleted cred For example, name the block **Account**, choose Find Organization Account, set Email to `alex@example.com`, and select Gmail. Use `` in a Gmail block to act with that contribution. +### Connection status and requests [#connection-requests] + +**Get Connection Status** returns: + +| Output | Meaning | +| --- | --- | +| `status` | `connected`, `not_connected`, or `needs_reconnect` | +| `connected` | Whether a usable account exists | +| `credentialId` | The account Find Organization Account would return, or `null` unless connected | +| `provider` | The provider the status refers to | +| `connectUrl` | A link the person opens to sign in to Sim and connect this provider | + +The status never says whether the person was invited, removed, or never asked. `connectUrl` carries no secret: the page checks that the signed-in person is the one with that email before anything is connected, so it is safe to post, for example as a Slack button. + +**Request Connection** returns `requested` and `connectUrl`. It works only when an admin turns on **Let workflows request connections** on the connected accounts **Access** tab, for the workflow's workspace, the person's email domain, and the provider. A request outside those settings, or past the daily limit, fails with an error. Otherwise the result is the same whether the person was already asked, already connected, or removed; a removed person is never re-invited. When the admin chose to also email the person, Sim sends the link once a day at most. + ### Managed MCP | Field | Meaning | diff --git a/apps/sim/app/api/organizations/[id]/connected-accounts/workflow-requests/route.ts b/apps/sim/app/api/organizations/[id]/connected-accounts/workflow-requests/route.ts new file mode 100644 index 00000000000..706d47f079d --- /dev/null +++ b/apps/sim/app/api/organizations/[id]/connected-accounts/workflow-requests/route.ts @@ -0,0 +1,40 @@ +import { + getOrganizationConnectionRequestPolicyContract, + updateOrganizationConnectionRequestPolicyContract, +} from '@/lib/api/contracts/organization-accounts' +import { + defineInternalJsonRoute, + internalOrchestrationErrorPolicy, + internalRateLimits, + internalSessionAuth, +} from '@/lib/api/server/routes' +import { + getOrganizationConnectionRequestPolicy, + organizationConnectionRequestOperations, + updateOrganizationConnectionRequestPolicy, +} from '@/lib/credential-groups/application/organization-connection-requests' + +export const GET = defineInternalJsonRoute({ + contract: getOrganizationConnectionRequestPolicyContract, + auth: internalSessionAuth, + operation: organizationConnectionRequestOperations.read, + rateLimit: internalRateLimits.none({ + reason: 'Bounded administrator connection request settings read', + }), + errorPolicy: internalOrchestrationErrorPolicy, + mapInput: ({ params }) => ({ organizationId: params.id }), + useCase: getOrganizationConnectionRequestPolicy, +}) + +export const PUT = defineInternalJsonRoute({ + contract: updateOrganizationConnectionRequestPolicyContract, + auth: internalSessionAuth, + operation: organizationConnectionRequestOperations.update, + rateLimit: internalRateLimits.none({ + reason: 'Administrator policy revision protects bounded connection request updates', + }), + errorPolicy: internalOrchestrationErrorPolicy, + mapInput: ({ params, body }) => ({ organizationId: params.id, ...body }), + useCase: updateOrganizationConnectionRequestPolicy, + present: ({ revision, policy }) => ({ revision, policy }), +}) diff --git a/apps/sim/blocks/blocks/credential.ts b/apps/sim/blocks/blocks/credential.ts index 290377dece8..3023486fa34 100644 --- a/apps/sim/blocks/blocks/credential.ts +++ b/apps/sim/blocks/blocks/credential.ts @@ -3,8 +3,10 @@ import { CREDENTIAL_GROUP_EVENT_TRIGGER_ID } from '@/lib/credential-groups/trigg import type { BlockConfig } from '@/blocks/types' import { getTrigger } from '@/triggers' +const CONNECTION_OPERATIONS = ['get_connection_status', 'request_connection'] const ORGANIZATION_OPERATIONS = [ 'find_organization_account', + ...CONNECTION_OPERATIONS, 'list_organization_accounts', 'find_organization_mcp_connection', 'list_organization_mcp_connections', @@ -19,9 +21,10 @@ const MCP_OPERATIONS = ['find_organization_mcp_connection', 'list_organization_m export const CredentialBlock: BlockConfig = { type: 'credential', name: 'Credential', - description: 'Select credentials or find organization accounts and MCP connections', + description: + 'Select credentials, find organization accounts and MCP connections, or ask people to connect', longDescription: - 'Select workspace OAuth credentials or find and list organization accounts in an allowlisted workspace. List Organization Accounts discovers connected accounts by provider without requiring an email. An optional exact enrollment email narrows the list. Only active accounts for integrations allowed in the executing workspace are returned; disconnected accounts are excluded. Results are paginated using hasMore and nextCursor. Manage invitations in organization settings.', + 'Select workspace OAuth credentials or find and list organization accounts in an allowlisted workspace. List Organization Accounts discovers connected accounts by provider without requiring an email. An optional exact enrollment email narrows the list. Only active accounts for integrations allowed in the executing workspace are returned; disconnected accounts are excluded. Results are paginated using hasMore and nextCursor. Get Connection Status reports whether a person has connected an integration and returns a link they can open to connect it. Request Connection asks them to connect, when an organization admin allows workflow connection requests. Manage invitations in organization settings.', bestPractices: ` - Use "Select Credential" to define an OAuth credential once and reference in multiple downstream blocks instead of repeating credential IDs. - Use "List Credentials" with a ForEach loop to iterate over all OAuth accounts (e.g. all Gmail accounts). @@ -29,6 +32,8 @@ export const CredentialBlock: BlockConfig = { - Use "List Organization Accounts" with Providers selected and Email blank to discover all accessible accounts for those integrations. - Organization lists return one page at a time. While hasMore is true, pass nextCursor as Cursor with the same filters to get every matching account. - "Find Organization Account" requires an exact enrollment email and provider, and returns that person's first connected account for the provider, or fails if there is none. Use "List Organization Accounts" to reach their other accounts. + - Use "Get Connection Status" before acting for a person: when connected is false, show them connectUrl (for example as a Slack button). The status is only connected, not_connected, or needs_reconnect. + - Use "Request Connection" to also notify the person, when organization settings allow workflow connection requests for that email domain and integration. It returns the same result whatever the person's state. - Outputs contain account identities and credential references, never secret values. - To switch credentials across environments, replace the single Credential block rather than updating every downstream block. `, @@ -47,6 +52,16 @@ export const CredentialBlock: BlockConfig = { { text: 'from', field: 'organizationProviders' }, { text: 'for', field: 'email' }, ], + get_connection_status: [ + 'Get connection status', + { text: 'for', field: 'email' }, + { text: 'in', field: 'organizationProvider' }, + ], + request_connection: [ + 'Request connection', + { text: 'from', field: 'email' }, + { text: 'for', field: 'organizationProvider' }, + ], find_organization_mcp_connection: [ 'Find organization MCP connection', { text: 'for', field: 'email' }, @@ -69,6 +84,8 @@ export const CredentialBlock: BlockConfig = { { label: 'List Credentials', id: 'list' }, { label: 'Find Organization Account', id: 'find_organization_account' }, { label: 'List Organization Accounts', id: 'list_organization_accounts' }, + { label: 'Get Connection Status', id: 'get_connection_status' }, + { label: 'Request Connection', id: 'request_connection' }, { label: 'Find Organization MCP Connection', id: 'find_organization_mcp_connection' }, { label: 'List Organization MCP Connections', id: 'list_organization_mcp_connections' }, ], @@ -107,7 +124,10 @@ export const CredentialBlock: BlockConfig = { title: 'Provider', type: 'dropdown', selectorKey: 'workspace.credentialGroupProviders', - condition: { field: 'operation', value: 'find_organization_account' }, + condition: { + field: 'operation', + value: ['find_organization_account', ...CONNECTION_OPERATIONS], + }, required: true, }, { @@ -136,7 +156,11 @@ export const CredentialBlock: BlockConfig = { condition: { field: 'operation', value: ORGANIZATION_OPERATIONS }, required: { field: 'operation', - value: ['find_organization_account', 'find_organization_mcp_connection'], + value: [ + 'find_organization_account', + 'find_organization_mcp_connection', + ...CONNECTION_OPERATIONS, + ], }, }, { @@ -163,7 +187,8 @@ export const CredentialBlock: BlockConfig = { operation: { type: 'string', description: 'Credential operation' }, email: { type: 'string', - description: 'Exact enrollment email; optional for lists, required for find operations', + description: + 'Exact enrollment email; optional for lists, required for find and connection operations', }, organizationProvider: { type: 'string', @@ -189,12 +214,43 @@ export const CredentialBlock: BlockConfig = { outputs: { credentialId: { type: 'string', - description: "Credential ID — pipe into other blocks' credential fields", + description: + "Credential ID — pipe into other blocks' credential fields. Null from Get Connection Status unless connected.", condition: { field: 'operation', - value: [...OAUTH_FIND_OPERATIONS, 'find_organization_mcp_connection'], + value: [ + ...OAUTH_FIND_OPERATIONS, + 'find_organization_mcp_connection', + 'get_connection_status', + ], }, }, + status: { + type: 'string', + description: 'connected, not_connected, or needs_reconnect', + condition: { field: 'operation', value: 'get_connection_status' }, + }, + connected: { + type: 'boolean', + description: 'Whether the person has a usable account for the provider', + condition: { field: 'operation', value: 'get_connection_status' }, + }, + provider: { + type: 'string', + description: 'Provider ID the status refers to', + condition: { field: 'operation', value: 'get_connection_status' }, + }, + connectUrl: { + type: 'string', + description: + 'Link the person opens to sign in and connect this provider. Safe to share; it carries no secret.', + condition: { field: 'operation', value: CONNECTION_OPERATIONS }, + }, + requested: { + type: 'boolean', + description: 'Always true once the request is accepted, whatever the person has done before', + condition: { field: 'operation', value: 'request_connection' }, + }, displayName: { type: 'string', description: 'Human-readable name of the credential', diff --git a/apps/sim/blocks/sdk-names.generated.ts b/apps/sim/blocks/sdk-names.generated.ts index 00f37184f18..ffe359bd241 100644 --- a/apps/sim/blocks/sdk-names.generated.ts +++ b/apps/sim/blocks/sdk-names.generated.ts @@ -84,7 +84,7 @@ const BLOCKS: Record = { context_dev: '{"namespace":"contextDev","methods":{"classify_naics":"classifyNaics","classify_sic":"classifySic","crawl":"crawlWebsite","extract":"extractStructuredData","extract_product":"extractProduct","extract_products":"extractProducts","get_brand":"getBrandByDomain","get_brand_by_email":"getBrandByEmail","get_brand_by_name":"getBrandByName","get_brand_by_ticker":"getBrandByTicker","identify_transaction":"identifyTransaction","map":"mapSitemap","scrape_fonts":"scrapeFonts","scrape_html":"scrapeHtml","scrape_images":"scrapeImages","scrape_markdown":"scrapeMarkdown","scrape_styleguide":"scrapeStyleguide","screenshot":"screenshot","search":"webSearch"}}', convex: '{"namespace":"legacy.convex","methods":{"action":"runAction","document_deltas":"documentDeltas","list_documents":"listDocuments","list_tables":"listTables","mutation":"runMutation","query":"runQuery","run_function":"runFunction"}}', convex_v2: '{"namespace":"convex","methods":{"action":"runAction","document_deltas":"documentDeltas","list_documents":"listDocuments","list_tables":"listTables","mutation":"runMutation","query":"runQuery","run_function":"runFunction"},"paramAliases":{"action":{"oauthCredential":"credential"}}}', - credential: '{"namespace":"credential","methods":{"find_organization_account":"findOrganizationAccount","find_organization_mcp_connection":"findOrganizationMcpConnection","list":"listCredentials","list_organization_accounts":"listOrganizationAccounts","list_organization_mcp_connections":"listOrganizationMcpConnections","select":"selectCredential"},"triggers":{"credential_group_event":"groupEvent"}}', + credential: '{"namespace":"credential","methods":{"find_organization_account":"findOrganizationAccount","find_organization_mcp_connection":"findOrganizationMcpConnection","get_connection_status":"getConnectionStatus","list":"listCredentials","list_organization_accounts":"listOrganizationAccounts","list_organization_mcp_connections":"listOrganizationMcpConnections","request_connection":"requestConnection","select":"selectCredential"},"triggers":{"credential_group_event":"groupEvent"}}', credential_group: '{"namespace":"legacy.credentialGroup","methods":{"get_invite_link":"getInviteLink","list_credentials":"listCredentials","list_mcp_connections":"listMcpConnections","list_people":"listPeople","send_invite":"sendInvite"},"triggers":{"credential_group_event":"event"}}', crowdstrike: '{"namespace":"legacy.crowdstrike","methods":{"crowdstrike_create_indicators":"createIndicators","crowdstrike_delete_indicators":"deleteIndicators","crowdstrike_delete_rtr_session":"deleteRtrSession","crowdstrike_execute_rtr_command":"executeRtrCommand","crowdstrike_get_alert_details":"getAlertDetails","crowdstrike_get_case_details":"getCaseDetails","crowdstrike_get_host_group_details":"getHostGroupDetails","crowdstrike_get_indicator_details":"getIndicatorDetails","crowdstrike_get_rtr_command_status":"getRtrCommandStatus","crowdstrike_get_sensor_aggregates":"getSensorAggregates","crowdstrike_get_sensor_details":"getSensorDetails","crowdstrike_get_vulnerability_details":"getVulnerabilityDetails","crowdstrike_init_rtr_session":"initRtrSession","crowdstrike_perform_host_action":"performHostAction","crowdstrike_perform_host_group_action":"performHostGroupAction","crowdstrike_query_alerts":"queryAlerts","crowdstrike_query_cases":"queryCases","crowdstrike_query_host_groups":"queryHostGroups","crowdstrike_query_indicators":"queryIndicators","crowdstrike_query_sensors":"querySensors","crowdstrike_query_vulnerabilities":"queryVulnerabilities","crowdstrike_update_alerts":"updateAlerts","crowdstrike_update_indicators":"updateIndicators"}}', crowdstrike_v2: '{"namespace":"crowdstrike","methods":{"crowdstrike_create_indicators":"createIndicators","crowdstrike_delete_indicators":"deleteIndicators","crowdstrike_delete_rtr_session":"deleteRtrSession","crowdstrike_execute_rtr_command":"executeRtrCommand","crowdstrike_get_alert_details":"getAlertDetails","crowdstrike_get_case_details":"getCaseDetails","crowdstrike_get_host_group_details":"getHostGroupDetails","crowdstrike_get_indicator_details":"getIndicatorDetails","crowdstrike_get_rtr_command_status":"getRtrCommandStatus","crowdstrike_get_sensor_aggregates":"getSensorAggregates","crowdstrike_get_sensor_details":"getSensorDetails","crowdstrike_get_vulnerability_details":"getVulnerabilityDetails","crowdstrike_init_rtr_session":"initRtrSession","crowdstrike_perform_host_action":"performHostAction","crowdstrike_perform_host_group_action":"performHostGroupAction","crowdstrike_query_alerts":"queryAlerts","crowdstrike_query_cases":"queryCases","crowdstrike_query_host_groups":"queryHostGroups","crowdstrike_query_indicators":"queryIndicators","crowdstrike_query_sensors":"querySensors","crowdstrike_query_vulnerabilities":"queryVulnerabilities","crowdstrike_update_alerts":"updateAlerts","crowdstrike_update_indicators":"updateIndicators"},"paramAliases":{"action":{"oauthCredential":"credential"}}}', diff --git a/apps/sim/blocks/sdk-names/credential.json b/apps/sim/blocks/sdk-names/credential.json index 653907273d9..a9cb7fe5426 100644 --- a/apps/sim/blocks/sdk-names/credential.json +++ b/apps/sim/blocks/sdk-names/credential.json @@ -3,9 +3,11 @@ "methods": { "find_organization_account": "findOrganizationAccount", "find_organization_mcp_connection": "findOrganizationMcpConnection", + "get_connection_status": "getConnectionStatus", "list": "listCredentials", "list_organization_accounts": "listOrganizationAccounts", "list_organization_mcp_connections": "listOrganizationMcpConnections", + "request_connection": "requestConnection", "select": "selectCredential" }, "triggers": { diff --git a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx index 0c00470109f..948ec786d1a 100644 --- a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx +++ b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx @@ -10,6 +10,11 @@ interface CredentialGroupInvitationEmailProps { credentialGroupName: string invitationLink: string searchProviderName?: string + /** + * Set when a workflow asked for one integration. The link is then the stable connect + * page, which signs the person in instead of expiring, so the footer says so. + */ + requestedProviderName?: string } export function CredentialGroupInvitationEmail({ @@ -19,7 +24,9 @@ export function CredentialGroupInvitationEmail({ credentialGroupName, invitationLink, searchProviderName, + requestedProviderName, }: CredentialGroupInvitationEmailProps) { + const providerName = searchProviderName ?? requestedProviderName return ( {workspaceName}. + ) : requestedProviderName ? ( + <> + to connect your {requestedProviderName} account for {workspaceName} on + Sim. + ) : ( <> to connect accounts for {credentialGroupName} in the{' '} @@ -60,16 +72,18 @@ export function CredentialGroupInvitationEmail({ - {searchProviderName ? `Connect ${searchProviderName}` : 'Connect Accounts'} + {providerName ? `Connect ${providerName}` : 'Connect Accounts'}
- This private link expires in 7 days. Sim will send you to each provider to sign in and will - never ask for your provider password. If you did not expect this invitation, you can ignore - it. + {requestedProviderName + ? `Sign in to Sim as ${recipientEmail} to continue. ` + : 'This private link expires in 7 days. '} + Sim will send you to each provider to sign in and will never ask for your provider password. + If you did not expect this invitation, you can ignore it. ) diff --git a/apps/sim/components/emails/credential-groups/render.ts b/apps/sim/components/emails/credential-groups/render.ts index b4f13f238bd..561e5b84c7c 100644 --- a/apps/sim/components/emails/credential-groups/render.ts +++ b/apps/sim/components/emails/credential-groups/render.ts @@ -8,6 +8,7 @@ export async function renderCredentialGroupInvitationEmail(params: { credentialGroupName: string invitationLink: string searchProviderName?: string + requestedProviderName?: string }): Promise { return await render(CredentialGroupInvitationEmail(params)) } diff --git a/apps/sim/ee/credential-groups/components/organization-account-workspace-access.tsx b/apps/sim/ee/credential-groups/components/organization-account-workspace-access.tsx index 396a3c8a593..95edd2b9513 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-workspace-access.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-workspace-access.tsx @@ -17,6 +17,7 @@ import { SettingsResourceRow, } from '@/app/workspace/[workspaceId]/settings/components/settings-resource-row' import { SettingsSection } from '@/app/workspace/[workspaceId]/settings/components/settings-section/settings-section' +import { OrganizationConnectionRequests } from '@/ee/credential-groups/components/organization-connection-requests' import { OrganizationWorkspaceGrantModal } from '@/ee/credential-groups/components/organization-workspace-grant-modal' import { credentialGroupWorkspaceSearchParam } from '@/ee/credential-groups/search-params' import { @@ -195,6 +196,7 @@ function WorkspaceAccessForm({ organizationId, access, searchTerm }: WorkspaceAc
)} + {editor && ( +const ALL_WORKSPACES = 'all' +const TOGGLE_LABEL = 'Let workflows request connections' + +interface OrganizationConnectionRequestsProps { + organizationId: string +} + +/** Off until an admin saves a policy; the switch then pauses or resumes it without losing it. */ +export function OrganizationConnectionRequests({ + organizationId, +}: OrganizationConnectionRequestsProps) { + const state = useOrganizationConnectionRequestPolicy(organizationId) + const update = useUpdateOrganizationConnectionRequestPolicy() + const [editing, setEditing] = useState(false) + + if (state.error) + return ( + + void state.refetch()} + variant='inline' + /> + + ) + if (!state.data) return null + const { policy, revision } = state.data + + const save = async (next: Policy) => { + try { + await update.mutateAsync({ organizationId, revision, policy: next }) + setEditing(false) + toast.success('Workflow requests updated') + } catch (error) { + toast.error(getErrorMessage(error, 'Could not update workflow requests')) + } + } + + return ( + + + {policy && ( + { + update.reset() + setEditing(true) + }} + > + Edit + + )} + { + if (policy) void save({ ...policy, enabled: checked }) + else if (checked) { + update.reset() + setEditing(true) + } + }} + /> +
+ } + /> + {editing && ( + setEditing(false)} + onSave={(next) => void save(next)} + /> + )} + + ) +} + +interface ConnectionRequestPolicyModalProps { + state: OrganizationConnectionRequestPolicyState + disabled: boolean + error?: string + onClose: () => void + onSave: (policy: Policy) => void +} + +function ConnectionRequestPolicyModal({ + state, + disabled, + error, + onClose, + onSave, +}: ConnectionRequestPolicyModalProps) { + const initial = state.policy + const [workspaces, setWorkspaces] = useState( + initial?.workspaces ?? { mode: 'all' } + ) + const [domains, setDomains] = useState(initial?.emailDomains.join(', ') ?? '') + const [providers, setProviders] = useState(initial?.providers ?? []) + const [dailyLimit, setDailyLimit] = useState( + String(initial?.dailyLimit ?? CONNECTION_REQUEST_DAILY_LIMIT_DEFAULT) + ) + const [sendEmail, setSendEmail] = useState(initial?.sendEmail ?? true) + + const emailDomains = domains + .split(',') + .map((domain) => domain.trim().toLowerCase().replace(/^@/, '')) + .filter(Boolean) + const limit = Number(dailyLimit) + const limitValid = + Number.isInteger(limit) && limit >= 1 && limit <= CONNECTION_REQUEST_DAILY_LIMIT_MAX + const workspacesValid = workspaces.mode === 'all' || workspaces.workspaceIds.length > 0 + const valid = emailDomains.length > 0 && providers.length > 0 && limitValid && workspacesValid + + return ( + !open && !disabled && onClose()} + > + + Workflow requests + + + + {(aria) => ( + ({ + value: workspace.id, + label: workspace.name, + })), + ]} + value={workspaces.mode === 'all' ? [ALL_WORKSPACES] : workspaces.workspaceIds} + onChange={(values) => { + if (workspaces.mode !== 'all' && values.includes(ALL_WORKSPACES)) { + setWorkspaces({ mode: 'all' }) + return + } + setWorkspaces({ + mode: 'selected', + workspaceIds: values.filter((value) => value !== ALL_WORKSPACES), + }) + }} + allLabel='Select workspaces' + aria-label='Workspaces' + showAllOption={false} + searchable + searchPlaceholder='Search workspaces' + disabled={disabled} + fullWidth + matchTriggerWidth + align='start' + {...aria} + /> + )} + + + + {(aria) => ( + ({ + value: provider.id, + label: provider.label, + }))} + value={providers} + onChange={setProviders} + allLabel='Select integrations' + aria-label='Integrations' + showAllOption={false} + searchable + searchPlaceholder='Search integrations' + disabled={disabled} + fullWidth + matchTriggerWidth + align='start' + {...aria} + /> + )} + + + + {(aria) => ( + + )} + + {error} + + + onSave({ + enabled: initial?.enabled ?? true, + workspaces, + emailDomains, + providers, + dailyLimit: limit, + sendEmail, + }), + }} + /> + + ) +} diff --git a/apps/sim/executor/handlers/credential/handler.ts b/apps/sim/executor/handlers/credential/handler.ts index 4bbe708f0c7..77b52ceea86 100644 --- a/apps/sim/executor/handlers/credential/handler.ts +++ b/apps/sim/executor/handlers/credential/handler.ts @@ -1,5 +1,9 @@ import { omit } from '@sim/utils/object' import { CREDENTIAL_GROUP_DELEGATION_AUDIENCE } from '@/lib/credential-groups/application/authorization' +import { + getOrganizationAccountConnectionStatus, + requestOrganizationAccountConnection, +} from '@/lib/credential-groups/application/connection-requests' import { listCredentialGroupCredentials } from '@/lib/credential-groups/application/list-credentials' import { listCredentialGroupMcpConnections } from '@/lib/credential-groups/application/list-mcp-connections' import { MAX_CREDENTIAL_GROUP_CREDENTIAL_PAGE_SIZE } from '@/lib/credential-groups/credentials' @@ -125,6 +129,26 @@ export class CredentialBlockHandler implements BlockHandler { ) return omit(first, ['accountEmail']) } + case 'get_connection_status': + return getOrganizationAccountConnectionStatus.execute({ + principal, + input: { + workspaceId: ctx.workspaceId, + email: requireString(inputs.email, 'Email'), + providerId: requireString(inputs.organizationProvider, 'Provider'), + }, + }) + case 'request_connection': { + const { requested, connectUrl } = await requestOrganizationAccountConnection.execute({ + principal, + input: { + workspaceId: ctx.workspaceId, + email: requireString(inputs.email, 'Email'), + providerId: requireString(inputs.organizationProvider, 'Provider'), + }, + }) + return { requested, connectUrl } + } case 'find_organization_mcp_connection': case 'list_organization_mcp_connections': { const find = operation === 'find_organization_mcp_connection' diff --git a/apps/sim/hooks/queries/organization-accounts.ts b/apps/sim/hooks/queries/organization-accounts.ts index a94b62779cb..d01be12887d 100644 --- a/apps/sim/hooks/queries/organization-accounts.ts +++ b/apps/sim/hooks/queries/organization-accounts.ts @@ -24,6 +24,7 @@ import { ensureOrganizationAccountsContract, getOrganizationAccountsContract, getOrganizationAccountWorkspaceAccessContract, + getOrganizationConnectionRequestPolicyContract, getOrganizationDatabricksSetupContract, getWorkspaceOrganizationAccountsContract, type InviteOrganizationAccountPeopleBody, @@ -41,8 +42,10 @@ import { startOrganizationAccountConnectionContract, type UpdateOrganizationAccountsBody, type UpdateOrganizationAccountWorkspaceAccessBody, + type UpdateOrganizationConnectionRequestPolicyBody, updateOrganizationAccountsContract, updateOrganizationAccountWorkspaceAccessContract, + updateOrganizationConnectionRequestPolicyContract, } from '@/lib/api/contracts/organization-accounts' import { connectCredentialGroupInPopup } from '@/lib/credential-groups/oauth-popup' import { isDesktopApp } from '@/lib/desktop' @@ -345,6 +348,33 @@ export function useUpdateOrganizationAccountWorkspaceAccess() { ]), }) } +export function useOrganizationConnectionRequestPolicy(organizationId: string) { + return useQuery({ + queryKey: organizationAccountsKeys.connectionRequests(organizationId), + enabled: Boolean(organizationId), + staleTime: ORGANIZATION_ACCOUNTS_STALE_TIME, + queryFn: ({ signal }) => + requestJson(getOrganizationConnectionRequestPolicyContract, { + params: { id: organizationId }, + signal, + }), + }) +} +export function useUpdateOrganizationConnectionRequestPolicy() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: ({ + organizationId, + ...body + }: { organizationId: string } & UpdateOrganizationConnectionRequestPolicyBody) => + requestJson(updateOrganizationConnectionRequestPolicyContract, { + params: { id: organizationId }, + body, + }), + onSettled: (_data, _error, { organizationId }) => + queryClient.invalidateQueries({ queryKey: organizationAccountsKeys.access(organizationId) }), + }) +} export function useOrganizationAccountPeople( organizationId: string, search?: OrganizationAccountPeopleQuery['search'], diff --git a/apps/sim/hooks/queries/utils/organization-accounts-keys.ts b/apps/sim/hooks/queries/utils/organization-accounts-keys.ts index 50d24f293a5..8e45b675d1d 100644 --- a/apps/sim/hooks/queries/utils/organization-accounts-keys.ts +++ b/apps/sim/hooks/queries/utils/organization-accounts-keys.ts @@ -12,6 +12,9 @@ export const organizationAccountsKeys = { workspace: (workspaceId?: string) => [...organizationAccountsKeys.workspaces(), workspaceId ?? ''] as const, access: (id?: string) => [...organizationAccountsKeys.detail(id), 'access'] as const, + /** Under `access`: both edit one policy revision, so invalidating Access refreshes this too. */ + connectionRequests: (id?: string) => + [...organizationAccountsKeys.access(id), 'connection-requests'] as const, people: (id?: string) => [...organizationAccountsKeys.detail(id), 'people'] as const, peopleList: (id: string, search?: string, optionId?: string) => [ diff --git a/apps/sim/lib/api/contracts/organization-accounts.ts b/apps/sim/lib/api/contracts/organization-accounts.ts index 39c0426b337..79f5cc6bbb9 100644 --- a/apps/sim/lib/api/contracts/organization-accounts.ts +++ b/apps/sim/lib/api/contracts/organization-accounts.ts @@ -16,6 +16,12 @@ import { } from '@/lib/api/contracts/credential-groups' import { organizationIdSchema, workspaceIdSchema } from '@/lib/api/contracts/primitives' import { defineRouteContract } from '@/lib/api/contracts/types' +import { + CONNECTION_REQUEST_DAILY_LIMIT_MAX, + CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT, + CONNECTION_REQUEST_PROVIDER_LIMIT, + connectionRequestPolicySchema, +} from '@/lib/credential-groups/connection-request-policy' import { ORGANIZATION_CREDENTIAL_TYPES } from '@/lib/credential-groups/credential-types' import { ACCOUNT_SITE_LIMIT, @@ -210,6 +216,71 @@ export type UpdateOrganizationAccountWorkspaceAccessBody = z.input< NonNullable > +export const getOrganizationConnectionRequestPolicyContract = defineRouteContract({ + method: 'GET', + path: '/api/organizations/[id]/connected-accounts/workflow-requests', + params: organizationAccountsParamsSchema, + response: { + mode: 'json', + schema: z.object({ + revision: z.number().int().positive(), + policy: connectionRequestPolicySchema.nullable(), + workspaces: z + .array(z.object({ id: workspaceIdSchema, name: z.string().max(256) })) + .max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT), + providers: z + .array(z.object({ id: z.string().min(1).max(64), label: z.string().max(256) })) + .max(CONNECTION_REQUEST_PROVIDER_LIMIT), + }), + }, +}) + +/** Lists may arrive unsorted or mixed-case; the use case normalizes them before validating. */ +const updateOrganizationConnectionRequestPolicyBodySchema = z + .object({ + revision: z.number().int().positive(), + policy: z + .object({ + enabled: z.boolean(), + workspaces: z.discriminatedUnion('mode', [ + z.object({ mode: z.literal('all') }).strict(), + z + .object({ + mode: z.literal('selected'), + workspaceIds: z.array(workspaceIdSchema).max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT), + }) + .strict(), + ]), + emailDomains: z.array(z.string().max(253)).max(CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT), + providers: z.array(z.string().max(64)).max(CONNECTION_REQUEST_PROVIDER_LIMIT), + dailyLimit: z.number().int().min(1).max(CONNECTION_REQUEST_DAILY_LIMIT_MAX), + sendEmail: z.boolean(), + }) + .strict() + .nullable(), + }) + .strict() + +export const updateOrganizationConnectionRequestPolicyContract = defineRouteContract({ + method: 'PUT', + path: '/api/organizations/[id]/connected-accounts/workflow-requests', + params: organizationAccountsParamsSchema, + body: updateOrganizationConnectionRequestPolicyBodySchema, + response: { + mode: 'json', + schema: z.object({ + revision: z.number().int().positive(), + policy: connectionRequestPolicySchema.nullable(), + }), + }, +}) +export type OrganizationConnectionRequestPolicyState = z.output< + typeof getOrganizationConnectionRequestPolicyContract.response.schema +> +export type UpdateOrganizationConnectionRequestPolicyBody = z.input< + NonNullable +> + export const listOrganizationAccountPeopleQuerySchema = z.object({ limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).max(512).optional(), diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts new file mode 100644 index 00000000000..cf36b483a2f --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -0,0 +1,505 @@ +/** + * Workflow-facing connection status and connection requests against real PostgreSQL, real + * workspace authorization, and the real resource policy. Only the provider token exchange is + * faked, so a connected account is minted by the same grant persistence production uses. + * + * Failure modes: a workflow learning more than connected / not_connected / needs_reconnect; a + * workspace outside the Access allowlist reading status; another organization's accounts leaking + * in; a request without (or outside) the admin policy succeeding; a request reactivating a + * revoked person or re-attributing an admin invitation; concurrent requests creating two rows; + * the daily cap being exceeded; per-person outcomes being distinguishable from the result. + */ +import type { WorkflowExecutionDelegatedPrincipal } from '@sim/auth/principal' +import { db } from '@sim/db' +import { + credential, + credentialGroup, + credentialGroupEnrollment, + member, + organization, + resourcePolicy, + user, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { sha256Hex } from '@sim/security/hash' +import { generateId } from '@sim/utils/id' +import { and, eq, inArray, isNotNull } from 'drizzle-orm' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { CREDENTIAL_GROUP_DELEGATION_AUDIENCE } from '@/lib/credential-groups/application/authorization' +import { + getOrganizationAccountConnectionStatus, + requestOrganizationAccountConnection, +} from '@/lib/credential-groups/application/connection-requests' +import { buildOrganizationAccountAccessPolicy } from '@/lib/credential-groups/application/workspace-access-policy' +import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' +import type { CredentialGroupOAuthContext } from '@/lib/credential-groups/enrollments' +import { completeCredentialGroupOAuth } from '@/lib/credential-groups/oauth' +import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' +import type { CredentialGroupProvider } from '@/lib/credential-groups/providers' +import { getCredentialGroupProviderId } from '@/lib/credential-groups/providers' + +const POLICY = { authorizationAppId: 'fixture-app', requiredScopes: ['read'], scopeVersion: 1 } + +vi.mock('@/lib/credential-groups/scoped-availability', () => ({ + isScopedCredentialGroupsAvailable: async () => true, +})) + +vi.mock('@/lib/credential-groups/provider-registry', async (importOriginal) => { + const { getCredentialGroupProviderId: providerIdOf } = await import( + '@/lib/credential-groups/providers' + ) + return { + ...(await importOriginal()), + getCredentialGroupProviderAdapter: (provider: CredentialGroupProvider) => { + const policy = { ...POLICY, provider, providerId: providerIdOf(provider) } + return { + provider, + requiresRefreshToken: false, + getPolicy: async () => policy, + exchangeAndVerify: async ({ code }: { code: string }) => ({ + providerId: policy.providerId, + providerSubjectId: code, + providerTenantId: null, + displayName: code, + metadata: { email: code }, + accessToken: `token-for-${code}`, + grantedScopes: POLICY.requiredScopes, + accessTokenExpiresAt: null, + refreshTokenExpiresAt: null, + }), + } + }, + } +}) + +const DRIVE = { + id: 'option-drive', + provider: 'google-drive' as const, + label: 'Google Drive', + ...POLICY, + required: false, + status: 'active' as const, +} +const DRIVE_ID = getCredentialGroupProviderId('google-drive') + +interface OrgFixture { + organizationId: string + groupId: string + publicId: string + workspaceId: string + outsideWorkspaceId: string + policyId: string +} + +const ownerId = generateId() +const workflowId = generateId() +const domain = `${generateId().slice(0, 12).toLowerCase()}.test` +const people = new Map() +let orgA: OrgFixture +let orgB: OrgFixture + +const address = (label: string) => `${label}@${domain}` + +async function createOrg(): Promise { + const fixture = { + organizationId: generateId(), + groupId: generateId(), + publicId: generateId(), + workspaceId: generateId(), + outsideWorkspaceId: generateId(), + policyId: generateId(), + } + await db.insert(organization).values({ + id: fixture.organizationId, + name: 'Connection requests fixture', + slug: fixture.organizationId, + createdAt: new Date(), + }) + await insertWorkspaceFixture( + db, + [fixture.workspaceId, fixture.outsideWorkspaceId].map((id) => ({ + id, + name: 'Fixture workspace', + ownerId, + billedAccountUserId: ownerId, + organizationId: fixture.organizationId, + })) + ) + await db.insert(credentialGroup).values({ + id: fixture.groupId, + organizationId: fixture.organizationId, + publicId: fixture.publicId, + name: 'Connected accounts', + options: [DRIVE], + }) + await db.insert(resourcePolicy).values({ + id: fixture.policyId, + organizationId: fixture.organizationId, + resourceType: 'credential_group', + resourceId: fixture.groupId, + document: buildOrganizationAccountAccessPolicy(fixture.groupId, [ + { workspaceId: fixture.workspaceId, access: { mode: 'all' } }, + ]), + }) + return fixture +} + +async function setRequestPolicy(fixture: OrgFixture, requests: ConnectionRequestPolicy | null) { + await db + .update(resourcePolicy) + .set({ + document: buildOrganizationAccountAccessPolicy( + fixture.groupId, + [{ workspaceId: fixture.workspaceId, access: { mode: 'all' } }], + requests + ), + }) + .where(eq(resourcePolicy.id, fixture.policyId)) +} + +const OPEN_POLICY: ConnectionRequestPolicy = { + enabled: true, + workspaces: { mode: 'all' }, + emailDomains: [domain], + providers: [DRIVE_ID], + dailyLimit: 50, + sendEmail: false, +} + +/** An actorless deployed run: no subject, so no role check stands between it and the policy. */ +function deployedRun(workspaceId: string): WorkflowExecutionDelegatedPrincipal { + const issuedAt = new Date(Date.now() - 1000) + return { + kind: 'delegated', + serviceId: 'executor', + workspaceId, + delegationId: generateId(), + audience: CREDENTIAL_GROUP_DELEGATION_AUDIENCE, + issuedAt, + expiresAt: new Date(issuedAt.getTime() + 60_000), + delegationContext: { + kind: 'workflow_execution', + workflowId, + principal: { kind: 'system', serviceId: 'schedule', workspaceId, workflowId }, + currentWorkflow: { workflowId, mode: 'deployment', deploymentVersionId: generateId() }, + }, + } +} + +const status = (fixture: OrgFixture, email: string, workspaceId = fixture.workspaceId) => + getOrganizationAccountConnectionStatus.execute({ + principal: deployedRun(workspaceId), + input: { workspaceId, email, providerId: DRIVE_ID }, + }) + +const request = ( + fixture: OrgFixture, + email: string, + workspaceId = fixture.workspaceId, + providerId = DRIVE_ID +) => + requestOrganizationAccountConnection.execute({ + principal: deployedRun(workspaceId), + input: { workspaceId, email, providerId }, + }) + +async function refusal(result: Promise) { + const error = await result.then( + () => null, + (caught: unknown) => caught + ) + expect(error).toBeInstanceOf(OrchestrationError) + return error as OrchestrationError +} + +async function enroll( + fixture: OrgFixture, + email: string, + values: Partial = {} +) { + const id = generateId() + await db.insert(credentialGroupEnrollment).values({ + id, + credentialGroupId: fixture.groupId, + email, + status: 'invited', + invitationTokenHash: sha256Hex(generateId()), + invitationExpiresAt: new Date(Date.now() + 3_600_000), + invitedAt: new Date(), + createdBy: ownerId, + ...values, + }) + return id +} + +/** Binds a person and connects a Drive account through the real grant persistence. */ +async function connectPerson(fixture: OrgFixture, email: string) { + const userId = generateId() + people.set(email, userId) + await db.insert(user).values({ + id: userId, + name: email, + email, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }) + await db.insert(member).values({ + id: generateId(), + organizationId: fixture.organizationId, + userId, + role: 'member', + createdAt: new Date(), + }) + const invitationToken = generateId() + const enrollmentId = await enroll(fixture, email, { + userId, + status: 'completed', + invitationTokenHash: sha256Hex(invitationToken), + }) + const context: CredentialGroupOAuthContext = { + enrollmentId, + credentialGroupId: fixture.groupId, + credentialGroupName: 'Connected accounts', + organizationId: fixture.organizationId, + workspaceName: 'Fixture', + workspaceOwnerId: null, + credentialOwnerId: userId, + email, + enrollmentStatus: 'completed', + option: DRIVE, + options: [DRIVE], + } + const attempt: CredentialGroupOAuthAttempt = { + userId, + state: generateId(), + provider: 'google-drive', + nonceHash: 'nonce', + organizationId: fixture.organizationId, + email, + enrollmentId, + credentialGroupId: fixture.groupId, + optionId: DRIVE.id, + authorizationAppId: POLICY.authorizationAppId, + scopeVersion: POLICY.scopeVersion, + requiredScopes: POLICY.requiredScopes, + redirectUri: 'https://sim.test/callback', + invitationToken, + createdAt: Date.now(), + connectionIntent: { kind: 'create' }, + } + const { credentialId } = await completeCredentialGroupOAuth(context, attempt, `${email}-drive`) + return { enrollmentId, credentialId } +} + +const enrollmentsFor = (fixture: OrgFixture, email: string) => + db + .select() + .from(credentialGroupEnrollment) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, fixture.groupId), + eq(credentialGroupEnrollment.email, email) + ) + ) + +beforeAll(async () => { + await db.insert(user).values({ + id: ownerId, + name: 'Owner', + email: `owner-${ownerId}@${domain}`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }) + orgA = await createOrg() + orgB = await createOrg() +}) + +afterAll(async () => { + const organizations = [orgA, orgB].flatMap((fixture) => (fixture ? [fixture.organizationId] : [])) + await deleteWorkspaceFixture(db, inArray(workspace.organizationId, organizations)) + await db.delete(organization).where(inArray(organization.id, organizations)) + await db.delete(user).where(inArray(user.id, [ownerId, ...people.values()])) +}) + +describe('get_connection_status', () => { + const connectUrl = () => + `http://localhost:3000/credential-groups/${orgA.publicId}/connect?provider=${DRIVE_ID}` + + it('reports a connected person with the credential Find Organization Account returns', async () => { + const { credentialId } = await connectPerson(orgA, address('connected')) + expect(await status(orgA, address('connected'))).toEqual({ + status: 'connected', + connected: true, + credentialId, + provider: DRIVE_ID, + connectUrl: connectUrl(), + }) + }) + + it('reports needs_reconnect, without a credential, when the account needs reauthorization', async () => { + const { credentialId } = await connectPerson(orgA, address('stale')) + await db + .update(credential) + .set({ managedOauthStatus: 'needs_reauth' }) + .where(eq(credential.id, credentialId)) + expect(await status(orgA, address('stale'))).toEqual({ + status: 'needs_reconnect', + connected: false, + credentialId: null, + provider: DRIVE_ID, + connectUrl: connectUrl(), + }) + }) + + it('collapses invited, failed, revoked, expired and unknown people into one identical answer', async () => { + await enroll(orgA, address('invited')) + await enroll(orgA, address('failed'), { status: 'delivery_failed' }) + await enroll(orgA, address('expired'), { invitationExpiresAt: new Date(Date.now() - 1000) }) + const revoked = await connectPerson(orgA, address('revoked')) + await db + .update(credentialGroupEnrollment) + .set({ status: 'revoked', revokedAt: new Date() }) + .where(eq(credentialGroupEnrollment.id, revoked.enrollmentId)) + + const answers = await Promise.all( + ['invited', 'failed', 'expired', 'revoked', 'nobody'].map((label) => + status(orgA, address(label)) + ) + ) + for (const answer of answers) + expect(answer).toEqual({ + status: 'not_connected', + connected: false, + credentialId: null, + provider: DRIVE_ID, + connectUrl: connectUrl(), + }) + }) + + it('refuses a workspace that is not on the Access allowlist', async () => { + const error = await refusal(status(orgA, address('connected'), orgA.outsideWorkspaceId)) + expect(error.code).toBe('forbidden') + }) + + it("never reports another organization's connected account", async () => { + await connectPerson(orgB, address('other-org')) + expect(await status(orgB, address('other-org'))).toMatchObject({ status: 'connected' }) + expect(await status(orgA, address('other-org'))).toMatchObject({ + status: 'not_connected', + credentialId: null, + }) + }) +}) + +describe('request_connection', () => { + beforeEach(async () => { + await setRequestPolicy(orgA, OPEN_POLICY) + }) + + it('is refused while no policy was saved, or the saved policy is off', async () => { + await setRequestPolicy(orgA, null) + expect((await refusal(request(orgA, address('absent')))).code).toBe('forbidden') + await setRequestPolicy(orgA, { ...OPEN_POLICY, enabled: false }) + expect((await refusal(request(orgA, address('absent')))).code).toBe('forbidden') + expect(await enrollmentsFor(orgA, address('absent'))).toEqual([]) + }) + + it('is refused for a domain, integration or workspace outside the policy', async () => { + expect((await refusal(request(orgA, `someone@other-${domain}`))).message).toContain( + 'not allowed' + ) + await setRequestPolicy(orgA, { ...OPEN_POLICY, providers: ['github-repositories'] }) + expect((await refusal(request(orgA, address('wrong-provider')))).code).toBe('forbidden') + await setRequestPolicy(orgA, { + ...OPEN_POLICY, + workspaces: { mode: 'selected', workspaceIds: [orgA.outsideWorkspaceId] }, + }) + expect((await refusal(request(orgA, address('wrong-workspace')))).code).toBe('forbidden') + expect( + await db + .select({ id: credentialGroupEnrollment.id }) + .from(credentialGroupEnrollment) + .where( + inArray(credentialGroupEnrollment.email, [ + `someone@other-${domain}`, + address('wrong-provider'), + address('wrong-workspace'), + ]) + ) + ).toEqual([]) + }) + + it('creates one unattributed invited enrollment that names the requesting workflow', async () => { + const result = await request(orgA, address('new')) + expect({ requested: result.requested, connectUrl: result.connectUrl }).toEqual({ + requested: true, + connectUrl: `http://localhost:3000/credential-groups/${orgA.publicId}/connect?provider=${DRIVE_ID}`, + }) + expect(await enrollmentsFor(orgA, address('new'))).toEqual([ + expect.objectContaining({ + status: 'invited', + createdBy: null, + userId: null, + requestedByWorkflowId: workflowId, + }), + ]) + }) + + it('never reactivates a revoked person and answers exactly as for anyone else', async () => { + const revokedId = await enroll(orgA, address('revoked-request'), { + status: 'revoked', + revokedAt: new Date(), + }) + const [before] = await enrollmentsFor(orgA, address('revoked-request')) + const revoked = await request(orgA, address('revoked-request')) + const fresh = await request(orgA, address('fresh-request')) + expect({ requested: revoked.requested, connectUrl: revoked.connectUrl }).toEqual({ + requested: fresh.requested, + connectUrl: fresh.connectUrl, + }) + const [after] = await enrollmentsFor(orgA, address('revoked-request')) + expect(after).toEqual(before) + expect(after?.id).toBe(revokedId) + }) + + it('leaves an admin invitation attributed to the admin', async () => { + await enroll(orgA, address('admin-invited')) + const [before] = await enrollmentsFor(orgA, address('admin-invited')) + await request(orgA, address('admin-invited')) + const [after] = await enrollmentsFor(orgA, address('admin-invited')) + expect(after).toEqual(before) + expect(after).toMatchObject({ createdBy: ownerId, requestedByWorkflowId: null }) + }) + + it('creates a single enrollment when the same person is requested concurrently', async () => { + const results = await Promise.allSettled( + Array.from({ length: 5 }, () => request(orgA, address('concurrent'))) + ) + expect(results.every((result) => result.status === 'fulfilled')).toBe(true) + expect(await enrollmentsFor(orgA, address('concurrent'))).toHaveLength(1) + }) + + it('stops creating requests at the daily limit, even under concurrency', async () => { + await setRequestPolicy(orgB, { ...OPEN_POLICY, dailyLimit: 2 }) + const results = await Promise.allSettled( + ['cap-1', 'cap-2', 'cap-3', 'cap-4'].map((label) => request(orgB, address(label))) + ) + expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(2) + const created = await db + .select({ id: credentialGroupEnrollment.id }) + .from(credentialGroupEnrollment) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, orgB.groupId), + isNotNull(credentialGroupEnrollment.requestedByWorkflowId) + ) + ) + .then((rows) => rows.length) + expect(created).toBe(2) + expect((await refusal(request(orgB, address('cap-5')))).code).toBe('conflict') + }) +}) diff --git a/apps/sim/lib/credential-groups/application/authorization.ts b/apps/sim/lib/credential-groups/application/authorization.ts index 2d6b92d3379..2cf5260e06c 100644 --- a/apps/sim/lib/credential-groups/application/authorization.ts +++ b/apps/sim/lib/credential-groups/application/authorization.ts @@ -91,6 +91,13 @@ function requireConsistentWorkflowSubject( return subject } +/** The workflow whose run holds this executor delegation, for attribution only. */ +export function requireCredentialGroupCurrentWorkflow( + principal: Principal +): WorkflowExecutionAuthority { + return requireCurrentWorkflow(principal) +} + /** * Asserts the delegation still names the subject its run was minted for, without * requiring that subject to be a Sim user. diff --git a/apps/sim/lib/credential-groups/application/connection-requests.ts b/apps/sim/lib/credential-groups/application/connection-requests.ts new file mode 100644 index 00000000000..7b9e25aa6ea --- /dev/null +++ b/apps/sim/lib/credential-groups/application/connection-requests.ts @@ -0,0 +1,250 @@ +import { AuditAction, AuditResourceType } from '@sim/audit' +import { isValidEmailSyntax, normalizeEmail } from '@sim/utils/string' +import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { + credentialGroupDelegationPolicy, + requireCredentialGroupCurrentWorkflow, + requireCredentialGroupWorkflowActor, +} from '@/lib/credential-groups/application/authorization' +import { credentialGroupOperations } from '@/lib/credential-groups/application/operations' +import { + type OrganizationAccountsWorkspaceContext, + requireOrganizationAccountsWorkspaceAccess, + resolveOrganizationAccountsWorkspaceContext, +} from '@/lib/credential-groups/application/organization-workspace-access' +import { + type OrganizationAccountAccessPolicy, + organizationAccountPolicyAllowsWorkspace, + readWorkflowConnectionRequestPolicy, +} from '@/lib/credential-groups/application/workspace-access-policy' +import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' +import { + ConnectionRequestDailyLimitError, + loadConnectionRequestGroup, + loadOrganizationAccountConnectionStatus, + type OrganizationAccountConnectionStatus, + recordCredentialGroupConnectionRequest, + sendConnectionRequestEmail, +} from '@/lib/credential-groups/connection-requests' +import { + getCredentialGroupProviderId, + isCredentialGroupProvider, +} from '@/lib/credential-groups/providers' + +export interface OrganizationAccountConnectionInput { + workspaceId: string + email: string + /** Credential provider ID, as Find Organization Account takes it. */ + providerId: string +} + +export interface OrganizationAccountConnectionStatusResult { + status: OrganizationAccountConnectionStatus + connected: boolean + credentialId: string | null + provider: string + connectUrl: string +} + +/** Identical for every person, so a workflow cannot tell invited, revoked, or connected apart. */ +interface OrganizationAccountConnectionRequestResult { + requested: true + connectUrl: string +} + +function requireEmail(value: string): string { + const email = normalizeEmail(value) + if (!isValidEmailSyntax(email)) + throw new OrchestrationError('validation', 'Email must be a valid address') + return email +} + +/** + * Resolves the group options collecting this provider that the executing workspace may use, + * with the same errors List Organization Accounts gives for an inactive or disallowed provider. + */ +function requireAllowedProviderOptions( + context: OrganizationAccountsWorkspaceContext, + policy: OrganizationAccountAccessPolicy, + providerId: string +) { + if (context.status !== 'active') + throw new OrchestrationError('conflict', 'Credential group is disabled') + const options = context.options.flatMap((option) => + option.status === 'active' && + isCredentialGroupProvider(option.provider) && + getCredentialGroupProviderId(option.provider) === providerId + ? [{ ...option, provider: option.provider }] + : [] + ) + const [first] = options + if (!first) + throw new OrchestrationError( + 'validation', + `Credential provider is not active in this group: ${providerId}` + ) + const allowed = options.filter((option) => + organizationAccountPolicyAllowsWorkspace( + policy, + context.workspaceId, + `oauth:${option.provider}` + ) + ) + if (!allowed.length) + throw new OrchestrationError( + 'forbidden', + 'This workspace is not allowed to use the requested credential provider' + ) + return { options: allowed, label: first.label } +} + +function requireWorkspacePolicy(context: OrganizationAccountsWorkspaceContext) { + const policy = context.workspaceAccessPolicy + if (!policy) throw new Error('Connection lookups require workspace policy authorization') + return policy +} + +export const getOrganizationAccountConnectionStatus = defineAuthorizedWorkspaceUseCase({ + operation: credentialGroupOperations.getConnectionStatus, + resolveContext: ({ input }: { input: OrganizationAccountConnectionInput }) => + resolveOrganizationAccountsWorkspaceContext(input.workspaceId), + authorizationOptions: { delegation: credentialGroupDelegationPolicy }, + async authorizeResource({ principal, context }) { + requireCredentialGroupWorkflowActor(principal) + context.workspaceAccessPolicy = await requireOrganizationAccountsWorkspaceAccess(context) + }, + execute: async ({ input, context }): Promise => { + const email = requireEmail(input.email) + const { options } = requireAllowedProviderOptions( + context, + requireWorkspacePolicy(context), + input.providerId + ) + const [{ status, credentialId }, group] = await Promise.all([ + loadOrganizationAccountConnectionStatus({ + organizationId: context.organizationId, + credentialGroupId: context.credentialGroupId, + credentialGroupOptionIds: options.map((option) => option.id), + email, + providerId: input.providerId, + }), + loadConnectionRequestGroup(context.credentialGroupId), + ]) + return { + status, + connected: status === 'connected', + credentialId, + provider: input.providerId, + connectUrl: buildCredentialGroupConnectUrl({ + publicId: group.publicId, + provider: input.providerId, + }), + } + }, +}) + +interface RecordedRequest extends OrganizationAccountConnectionRequestResult { + enrollmentId: string + created: boolean + workflowId: string + providerId: string +} + +/** + * Asks a person to connect one integration on a workflow's behalf. Authority is the + * organization admin's connection request policy, checked here rather than through the + * operation's role: an actorless deployed run has no role to check. Policy refusals are the + * workflow author's configuration problem and say so; per-person outcomes all look the same. + */ +export const requestOrganizationAccountConnection = defineAuthorizedWorkspaceUseCase({ + operation: credentialGroupOperations.requestConnection, + resolveContext: ({ input }: { input: OrganizationAccountConnectionInput }) => + resolveOrganizationAccountsWorkspaceContext(input.workspaceId), + authorizationOptions: { delegation: credentialGroupDelegationPolicy }, + async authorizeResource({ principal, context }) { + requireCredentialGroupWorkflowActor(principal) + context.workspaceAccessPolicy = await requireOrganizationAccountsWorkspaceAccess(context) + }, + execute: async ({ principal, input, context }): Promise => { + const { workflowId } = requireCredentialGroupCurrentWorkflow(principal) + const email = requireEmail(input.email) + const accessPolicy = requireWorkspacePolicy(context) + const requests = readWorkflowConnectionRequestPolicy(accessPolicy) + if (!requests?.enabled) + throw new OrchestrationError( + 'forbidden', + 'Workflow connection requests are turned off for this organization' + ) + if ( + requests.workspaces.mode === 'selected' && + !requests.workspaces.workspaceIds.includes(context.workspaceId) + ) + throw new OrchestrationError( + 'forbidden', + 'This workspace is not allowed to request connections' + ) + const domain = email.slice(email.lastIndexOf('@') + 1) + if (!requests.emailDomains.includes(domain)) + throw new OrchestrationError( + 'forbidden', + `Connection requests are not allowed for ${domain} addresses` + ) + if (!requests.providers.includes(input.providerId)) + throw new OrchestrationError( + 'forbidden', + `Connection requests are not allowed for ${input.providerId}` + ) + const { label } = requireAllowedProviderOptions(context, accessPolicy, input.providerId) + + const group = await loadConnectionRequestGroup(context.credentialGroupId) + const connectUrl = buildCredentialGroupConnectUrl({ + publicId: group.publicId, + provider: input.providerId, + }) + let recorded + try { + recorded = await recordCredentialGroupConnectionRequest({ + credentialGroupId: context.credentialGroupId, + email, + workflowId, + dailyLimit: requests.dailyLimit, + sendEmail: requests.sendEmail, + }) + } catch (error) { + if (error instanceof ConnectionRequestDailyLimitError) + throw new OrchestrationError('conflict', error.message) + throw error + } + if (recorded.notify) + await sendConnectionRequestEmail({ + enrollmentId: recorded.enrollmentId, + email, + organizationName: group.organizationName, + credentialGroupName: group.groupName, + providerName: label, + connectUrl, + }) + return { + requested: true, + connectUrl, + enrollmentId: recorded.enrollmentId, + created: recorded.created, + workflowId, + providerId: input.providerId, + } + }, + projectAudit: ({ context, result }) => ({ + action: AuditAction.CREDENTIAL_GROUP_UPDATED, + resourceType: AuditResourceType.CREDENTIAL_GROUP, + resourceId: context.credentialGroupId, + resourceName: context.name, + description: 'A workflow requested an account connection', + metadata: { + workflowId: result.workflowId, + providerId: result.providerId, + enrollmentId: result.enrollmentId, + created: result.created, + }, + }), +}) diff --git a/apps/sim/lib/credential-groups/application/operations.ts b/apps/sim/lib/credential-groups/application/operations.ts index a6db72f9f9e..615a5b532d8 100644 --- a/apps/sim/lib/credential-groups/application/operations.ts +++ b/apps/sim/lib/credential-groups/application/operations.ts @@ -113,6 +113,28 @@ export const credentialGroupOperations = { principalKinds: ['delegated'], delegatedServices: ['executor'], }), + // permission-group-exempt: read by the executor for one person's collapsed connection status; the Access allowlist is the gate + getConnectionStatus: defineWorkspaceOperation({ + id: 'credential_groups.connections.status', + minimumRole: 'read', + workspaceApiKey: 'deny', + capability: 'none', + principalKinds: ['delegated'], + delegatedServices: ['executor'], + }), + /** + * The role here is a floor, not the authority: an actorless deployed run skips role + * checks, so the organization's connection request policy decides inside the use case. + */ + // permission-group-exempt: authority is the organization admin's connection request policy, and no group key names it + requestConnection: defineWorkspaceOperation({ + id: 'credential_groups.connections.request', + minimumRole: 'read', + workspaceApiKey: 'deny', + capability: 'none', + principalKinds: ['delegated'], + delegatedServices: ['executor'], + }), // permission-group-exempt: read by the executor to resolve an enrolled person's MCP connection; use is enforced by the Credential Group policy listMcpConnections: defineWorkspaceOperation({ id: 'credential_groups.mcp_connections.list', diff --git a/apps/sim/lib/credential-groups/application/organization-access.ts b/apps/sim/lib/credential-groups/application/organization-access.ts index f05d749ee24..c16516f49af 100644 --- a/apps/sim/lib/credential-groups/application/organization-access.ts +++ b/apps/sim/lib/credential-groups/application/organization-access.ts @@ -10,6 +10,7 @@ import { buildOrganizationAccountAccessPolicy, listOrganizationAccountWorkspaceGrants, organizationAccountAccessPolicyCodec, + readWorkflowConnectionRequestPolicy, } from '@/lib/credential-groups/application/workspace-access-policy' import { getOrganizationCredentialTypeCatalog } from '@/lib/credential-groups/credential-types' import { loadScopedAccountsCredentialListContext } from '@/lib/credential-groups/credentials' @@ -125,7 +126,22 @@ export const updateOrganizationAccountWorkspaceAccess = defineOrganizationAccoun 'Every allowed workspace must be active and belong to this organization' ) } - const document = buildOrganizationAccountAccessPolicy(group.credentialGroupId, parsed.data) + const current = await requireResourcePolicy({ + organizationId: context.organizationId, + resourceType: 'credential_group', + resourceId: group.credentialGroupId, + codec: organizationAccountAccessPolicyCodec, + }) + if (current.revision !== input.revision) + throw new OrchestrationError( + 'conflict', + 'Workspace access changed. Reload before saving again.' + ) + const document = buildOrganizationAccountAccessPolicy( + group.credentialGroupId, + parsed.data, + readWorkflowConnectionRequestPolicy(current.document) + ) /** Indented JSON conservatively includes the whitespace PostgreSQL adds to jsonb text. */ if ( Buffer.byteLength(JSON.stringify(document, null, 1), 'utf8') > diff --git a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts new file mode 100644 index 00000000000..4a02eaa3167 --- /dev/null +++ b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts @@ -0,0 +1,187 @@ +import { db } from '@sim/db' +import { workspace } from '@sim/db/schema' +import { and, asc, eq, inArray, isNull } from 'drizzle-orm' +import type { OrganizationMembershipContext } from '@/lib/core/application/organization-authorization' +import { defineOrganizationOperation } from '@/lib/core/application/organization-operation' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { defineOrganizationAccountsUseCase } from '@/lib/credential-groups/application/organization-accounts' +import { + listOrganizationAccountWorkspaceIds, + organizationAccountAccessPolicyCodec, + readWorkflowConnectionRequestPolicy, + withWorkflowConnectionRequestPolicy, +} from '@/lib/credential-groups/application/workspace-access-policy' +import { + type ConnectionRequestPolicy, + connectionRequestPolicySchema, + normalizeConnectionRequestList, +} from '@/lib/credential-groups/connection-request-policy' +import { loadScopedAccountsCredentialListContext } from '@/lib/credential-groups/credentials' +import { + getCredentialGroupProviderId, + isCredentialGroupProvider, +} from '@/lib/credential-groups/providers' +import { + ResourcePolicyRevisionConflictError, + requireResourcePolicy, + writeResourcePolicy, +} from '@/lib/resource-policies/repository' + +export const organizationConnectionRequestOperations = { + read: defineOrganizationOperation({ + id: 'organization_accounts.connection_requests.read', + contentDelivery: 'none', + minimumRole: 'admin', + principalKinds: ['session', 'organization_delegated'], + delegationAudience: 'sim:settings', + delegatedServices: ['copilot'], + capability: 'integrations.manage', + }), + update: defineOrganizationOperation({ + id: 'organization_accounts.connection_requests.update', + contentDelivery: 'none', + minimumRole: 'admin', + principalKinds: ['session', 'organization_delegated'], + delegationAudience: 'sim:settings', + delegatedServices: ['copilot'], + capability: 'integrations.manage', + }), +} as const + +async function loadConnectionRequestState(organizationId: string) { + const group = await loadScopedAccountsCredentialListContext({ + kind: 'organization', + organizationId, + }) + if (!group) + throw new OrchestrationError('not_found', 'Organization connected accounts are not configured') + const policy = await requireResourcePolicy({ + organizationId, + resourceType: 'credential_group', + resourceId: group.credentialGroupId, + codec: organizationAccountAccessPolicyCodec, + }) + const accessWorkspaceIds = listOrganizationAccountWorkspaceIds(policy.document) + const workspaces = accessWorkspaceIds.length + ? await db + .select({ id: workspace.id, name: workspace.name }) + .from(workspace) + .where( + and( + eq(workspace.organizationId, organizationId), + inArray(workspace.id, accessWorkspaceIds), + isNull(workspace.archivedAt) + ) + ) + .orderBy(asc(workspace.name), asc(workspace.id)) + : [] + const providers = group.options.flatMap((option) => + option.status === 'active' && isCredentialGroupProvider(option.provider) + ? [{ id: getCredentialGroupProviderId(option.provider), label: option.label }] + : [] + ) + return { group, policy, workspaces, providers } +} + +export const getOrganizationConnectionRequestPolicy = defineOrganizationAccountsUseCase({ + operation: organizationConnectionRequestOperations.read, + async execute({ context }) { + const { policy, workspaces, providers } = await loadConnectionRequestState( + context.organizationId + ) + return { + revision: policy.revision, + policy: readWorkflowConnectionRequestPolicy(policy.document), + workspaces, + providers, + } + }, +}) + +export const updateOrganizationConnectionRequestPolicy = defineOrganizationAccountsUseCase({ + operation: organizationConnectionRequestOperations.update, + async execute({ + input, + context, + }: { + input: { organizationId: string; revision: number; policy: ConnectionRequestPolicy | null } + context: OrganizationMembershipContext + }) { + const parsed = input.policy + ? connectionRequestPolicySchema.safeParse({ + ...input.policy, + emailDomains: normalizeConnectionRequestList(input.policy.emailDomains), + providers: normalizeConnectionRequestList(input.policy.providers), + workspaces: + input.policy.workspaces.mode === 'all' + ? input.policy.workspaces + : { + mode: 'selected', + workspaceIds: [...new Set(input.policy.workspaces.workspaceIds)].sort(), + }, + }) + : null + if (parsed && !parsed.success) + throw new OrchestrationError( + 'validation', + parsed.error.issues[0]?.message ?? 'Connection request settings are invalid' + ) + const next = parsed?.data ?? null + const { group, policy, workspaces, providers } = await loadConnectionRequestState( + context.organizationId + ) + if (policy.revision !== input.revision) + throw new OrchestrationError( + 'conflict', + 'Connection request settings changed. Reload before saving again.' + ) + if (next) { + const allowedProviders = new Set(providers.map((provider) => provider.id)) + if (next.providers.some((provider) => !allowedProviders.has(provider))) + throw new OrchestrationError( + 'validation', + 'Every integration must be an active integration in this organization' + ) + const allowedWorkspaces = new Set(workspaces.map((entry) => entry.id)) + if ( + next.workspaces.mode === 'selected' && + next.workspaces.workspaceIds.some((workspaceId) => !allowedWorkspaces.has(workspaceId)) + ) + throw new OrchestrationError( + 'validation', + 'Every workspace must already be allowed on the Access tab' + ) + } + try { + const written = await writeResourcePolicy({ + organizationId: context.organizationId, + resourceType: 'credential_group', + resourceId: group.credentialGroupId, + codec: organizationAccountAccessPolicyCodec, + expectedRevision: input.revision, + document: withWorkflowConnectionRequestPolicy(policy.document, next), + actorUserId: context.userId, + }) + return { + credentialGroupId: group.credentialGroupId, + name: group.name, + revision: written.revision, + policy: readWorkflowConnectionRequestPolicy(written.document), + } + } catch (error) { + if (error instanceof ResourcePolicyRevisionConflictError) + throw new OrchestrationError( + 'conflict', + 'Connection request settings changed. Reload before saving again.' + ) + throw error + } + }, + projectAudit: (result) => ({ + resourceId: result.credentialGroupId, + resourceName: result.name, + description: result.policy?.enabled + ? 'Allowed workflows to request account connections' + : 'Turned off workflow connection requests', + }), +}) diff --git a/apps/sim/lib/credential-groups/application/workspace-access-policy.test.ts b/apps/sim/lib/credential-groups/application/workspace-access-policy.test.ts index 7af6872999c..52f2033f54c 100644 --- a/apps/sim/lib/credential-groups/application/workspace-access-policy.test.ts +++ b/apps/sim/lib/credential-groups/application/workspace-access-policy.test.ts @@ -1,3 +1,4 @@ +import { validateOrganizationAccountPolicyDocument } from '@sim/db/credential-group-resource-policies' import { describe, expect, it } from 'vitest' import { buildOrganizationAccountAccessPolicy, @@ -5,7 +6,10 @@ import { listOrganizationAccountWorkspaceIds, organizationAccountAccessPolicyCodec, organizationAccountPolicyAllowsWorkspace, + readWorkflowConnectionRequestPolicy, + withWorkflowConnectionRequestPolicy, } from '@/lib/credential-groups/application/workspace-access-policy' +import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' import { organizationAccountWorkspaceGrantsSchema } from '@/lib/credential-groups/workspace-grants' describe('organization account workspace policy', () => { @@ -153,7 +157,9 @@ describe('integration-specific organization grants', () => { ...policy, statements: [ { - ...policy.statements.find((statement) => statement.condition), + ...policy.statements.find( + (statement) => 'condition' in statement && statement.condition + ), condition: { StringEquals: { 'credential_group:CredentialType': types } }, }, ], @@ -165,8 +171,12 @@ describe('integration-specific organization grants', () => { }) it('rejects ambiguous overlapping or duplicate statements', () => { - const selected = policy.statements.find((statement) => statement.condition)! - const unrestricted = policy.statements.find((statement) => !statement.condition)! + const selected = policy.statements.find( + (statement) => 'condition' in statement && statement.condition + )! + const unrestricted = policy.statements.find( + (statement) => !('condition' in statement && statement.condition) + )! for (const statements of [ [selected, selected], [selected, { ...unrestricted, principals: selected.principals }], @@ -181,3 +191,69 @@ describe('integration-specific organization grants', () => { } }) }) + +describe('workflow connection request statement', () => { + const expected = { type: 'credential_group' as const, id: 'group-1' } + const requests: ConnectionRequestPolicy = { + enabled: true, + workspaces: { mode: 'selected', workspaceIds: ['workspace-requests'] }, + emailDomains: ['example.com'], + providers: ['google-drive'], + dailyLimit: 50, + sendEmail: true, + } + const grants = [{ workspaceId: 'workspace-1', access: { mode: 'all' as const } }] + + it('parses a version 2 document saved before requests existed, with requests off', () => { + const stored = { + version: 2, + resource: { type: 'credential_group', id: 'group-1' }, + statements: [ + { + sid: 'WorkspaceCredentialAccess', + effect: 'allow', + actions: ['credential_groups.credentials.use'], + principals: [{ type: 'workspace', workspaceId: 'workspace-1' }], + }, + ], + } + const document = organizationAccountAccessPolicyCodec.parse(stored, expected) + expect(readWorkflowConnectionRequestPolicy(document)).toBeNull() + expect(listOrganizationAccountWorkspaceGrants(document)).toEqual(grants) + }) + + it('round-trips the policy without granting its workspaces credential use', () => { + const document = organizationAccountAccessPolicyCodec.parse( + buildOrganizationAccountAccessPolicy('group-1', grants, requests), + expected + ) + expect(readWorkflowConnectionRequestPolicy(document)).toEqual(requests) + expect(listOrganizationAccountWorkspaceGrants(document)).toEqual(grants) + expect(listOrganizationAccountWorkspaceIds(document)).toEqual(['workspace-1']) + expect(organizationAccountPolicyAllowsWorkspace(document, 'workspace-requests')).toBe(false) + expect(organizationAccountPolicyAllowsWorkspace(document, 'workspace-1')).toBe(true) + expect( + readWorkflowConnectionRequestPolicy(withWorkflowConnectionRequestPolicy(document, null)) + ).toBeNull() + }) + + it('is accepted by the database policy validator', () => { + for (const workspaces of [requests.workspaces, { mode: 'all' as const }]) + expect(() => + validateOrganizationAccountPolicyDocument( + buildOrganizationAccountAccessPolicy('group-1', grants, { ...requests, workspaces }), + 'group-1' + ) + ).not.toThrow() + }) + + it('rejects wildcard domains, an empty domain list, and an out-of-range daily limit', () => { + for (const invalid of [ + { ...requests, emailDomains: ['*.example.com'] }, + { ...requests, emailDomains: [] }, + { ...requests, dailyLimit: 1001 }, + { ...requests, dailyLimit: 0 }, + ]) + expect(() => buildOrganizationAccountAccessPolicy('group-1', grants, invalid)).toThrow() + }) +}) diff --git a/apps/sim/lib/credential-groups/application/workspace-access-policy.ts b/apps/sim/lib/credential-groups/application/workspace-access-policy.ts index bc037f9277c..447dede82db 100644 --- a/apps/sim/lib/credential-groups/application/workspace-access-policy.ts +++ b/apps/sim/lib/credential-groups/application/workspace-access-policy.ts @@ -1,4 +1,8 @@ import { z } from 'zod' +import { + type ConnectionRequestPolicy, + connectionRequestSettingsSchema, +} from '@/lib/credential-groups/connection-request-policy' import { ORGANIZATION_CREDENTIAL_TYPES, type OrganizationCredentialType, @@ -12,7 +16,10 @@ import { import { CREDENTIAL_TYPE_CONDITION_KEY } from '@/lib/resource-policies/conditions/credential-type' import { evaluateResourcePolicy } from '@/lib/resource-policies/evaluator' import { workspaceResourcePolicyPrincipalSchema } from '@/lib/resource-policies/principals/workspace' -import { CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION } from '@/lib/resource-policies/registry' +import { + CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION, + CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION, +} from '@/lib/resource-policies/registry' import type { ResourcePolicyCodec } from '@/lib/resource-policies/types' const workspaceAccessStatementSchema = z @@ -55,6 +62,43 @@ const workspaceAccessStatementSchema = z } }) +const WORKFLOW_CONNECTION_REQUEST_SID = 'WorkflowConnectionRequests' + +/** + * Whether, and within which limits, workflows may ask a person to connect an account. + * No principals means every workspace the Access statements allow; the request is + * still refused for a workspace those statements do not allow. + */ +const workflowConnectionRequestStatementSchema = z + .object({ + sid: z.literal(WORKFLOW_CONNECTION_REQUEST_SID), + effect: z.literal('allow'), + actions: z.tuple([z.literal(CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION)]), + principals: z + .array(workspaceResourcePolicyPrincipalSchema) + .max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT) + .refine( + (principals) => + principals.every( + (principal, index) => + index === 0 || principals[index - 1].workspaceId < principal.workspaceId + ), + 'Workspace principals must be sorted and unique' + ), + settings: connectionRequestSettingsSchema, + }) + .strict() + +type WorkspaceAccessStatement = z.output +type WorkflowConnectionRequestStatement = z.output + +function isWorkspaceAccessStatement( + statement: WorkspaceAccessStatement | WorkflowConnectionRequestStatement +): statement is WorkspaceAccessStatement { + return statement.sid !== WORKFLOW_CONNECTION_REQUEST_SID +} + +/** Version 2 documents written before connection requests existed parse unchanged. */ export const organizationAccountAccessPolicySchema = z .object({ version: z.literal(2), @@ -62,14 +106,15 @@ export const organizationAccountAccessPolicySchema = z .object({ type: z.literal('credential_group'), id: z.string().min(1).max(128) }) .strict(), statements: z - .array(workspaceAccessStatementSchema) - .max(ORGANIZATION_CREDENTIAL_TYPES.length + 1), + .array(z.union([workspaceAccessStatementSchema, workflowConnectionRequestStatementSchema])) + .max(ORGANIZATION_CREDENTIAL_TYPES.length + 2), }) .strict() - .superRefine(({ statements }, context) => { - const statementIds = new Set(statements.map((statement) => statement.sid)) - if (statementIds.size !== statements.length) + .superRefine(({ statements: allStatements }, context) => { + const statementIds = new Set(allStatements.map((statement) => statement.sid)) + if (statementIds.size !== allStatements.length) context.addIssue({ code: 'custom', message: 'Workspace statements must be unique' }) + const statements = allStatements.filter(isWorkspaceAccessStatement) const unrestricted = new Set( statements .filter((statement) => !statement.condition) @@ -105,9 +150,14 @@ export const organizationAccountAccessPolicyCodec: ResourcePolicyCodec< }, } +/** + * Builds the Access statements from grants. Pass the current document's connection + * request statement through `requests` so saving Access never drops it. + */ export function buildOrganizationAccountAccessPolicy( credentialGroupId: string, - grants: OrganizationAccountWorkspaceGrant[] + grants: OrganizationAccountWorkspaceGrant[], + requests: ConnectionRequestPolicy | null = null ): OrganizationAccountAccessPolicy { const parsed = organizationAccountWorkspaceGrantsSchema.parse(grants) const byType = new Map() @@ -122,25 +172,80 @@ export function buildOrganizationAccountAccessPolicy( return organizationAccountAccessPolicySchema.parse({ version: 2, resource: { type: 'credential_group', id: credentialGroupId }, - statements: [...byType] - .sort(([left], [right]) => left.localeCompare(right)) - .map(([type, workspaceIds]) => ({ - sid: type === 'all' ? 'WorkspaceCredentialAccess' : `WorkspaceCredentialAccess:${type}`, - effect: 'allow', - actions: [CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION], - principals: workspaceIds.sort().map((workspaceId) => ({ type: 'workspace', workspaceId })), - ...(type === 'all' - ? {} - : { condition: { StringEquals: { [CREDENTIAL_TYPE_CONDITION_KEY]: type } } }), - })), + statements: [ + ...[...byType] + .sort(([left], [right]) => left.localeCompare(right)) + .map(([type, workspaceIds]) => ({ + sid: type === 'all' ? 'WorkspaceCredentialAccess' : `WorkspaceCredentialAccess:${type}`, + effect: 'allow', + actions: [CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION], + principals: workspaceIds + .sort() + .map((workspaceId) => ({ type: 'workspace', workspaceId })), + ...(type === 'all' + ? {} + : { condition: { StringEquals: { [CREDENTIAL_TYPE_CONDITION_KEY]: type } } }), + })), + ...(requests ? [toWorkflowConnectionRequestStatement(requests)] : []), + ], }) } +function toWorkflowConnectionRequestStatement({ + workspaces, + ...settings +}: ConnectionRequestPolicy): WorkflowConnectionRequestStatement { + return { + sid: WORKFLOW_CONNECTION_REQUEST_SID, + effect: 'allow', + actions: [CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION], + principals: + workspaces.mode === 'all' + ? [] + : workspaces.workspaceIds.map((workspaceId) => ({ type: 'workspace', workspaceId })), + settings, + } +} + +/** Replaces (or, with `null`, removes) the connection request statement, keeping Access as is. */ +export function withWorkflowConnectionRequestPolicy( + document: OrganizationAccountAccessPolicy, + requests: ConnectionRequestPolicy | null +): OrganizationAccountAccessPolicy { + return organizationAccountAccessPolicySchema.parse({ + ...document, + statements: [ + ...document.statements.filter(isWorkspaceAccessStatement), + ...(requests ? [toWorkflowConnectionRequestStatement(requests)] : []), + ], + }) +} + +/** The admin's connection request policy, or `null` when none was ever saved (requests are off). */ +export function readWorkflowConnectionRequestPolicy( + document: OrganizationAccountAccessPolicy +): ConnectionRequestPolicy | null { + const statement = document.statements.find( + (candidate): candidate is WorkflowConnectionRequestStatement => + !isWorkspaceAccessStatement(candidate) + ) + if (!statement) return null + return { + ...statement.settings, + workspaces: statement.principals.length + ? { + mode: 'selected', + workspaceIds: statement.principals.map((principal) => principal.workspaceId), + } + : { mode: 'all' }, + } +} + export function listOrganizationAccountWorkspaceGrants( document: OrganizationAccountAccessPolicy ): OrganizationAccountWorkspaceGrant[] { const grants = new Map() - for (const statement of document.statements) { + for (const statement of document.statements.filter(isWorkspaceAccessStatement)) { const type = statement.condition?.StringEquals[CREDENTIAL_TYPE_CONDITION_KEY] for (const { workspaceId } of statement.principals) { if (!type) { @@ -167,9 +272,9 @@ export function listOrganizationAccountWorkspaceIds( ): string[] { return [ ...new Set( - document.statements.flatMap((statement) => - statement.principals.map((principal) => principal.workspaceId) - ) + document.statements + .filter(isWorkspaceAccessStatement) + .flatMap((statement) => statement.principals.map((principal) => principal.workspaceId)) ), ].sort() } diff --git a/apps/sim/lib/credential-groups/connect-url.ts b/apps/sim/lib/credential-groups/connect-url.ts new file mode 100644 index 00000000000..2ebb6ce0c31 --- /dev/null +++ b/apps/sim/lib/credential-groups/connect-url.ts @@ -0,0 +1,31 @@ +import { getBaseUrl } from '@/lib/core/utils/urls' + +/** Destinations the connect page may offer a button back to once the account is connected. */ +export type CredentialGroupConnectReturnKey = 'slack' + +/** + * The stable link that asks a person to connect one integration in an organization's + * Credential Group. It carries no secret: the page verifies the signed-in person against + * their own enrollment before minting anything, so the link is safe to show a workflow + * or to copy from the People tab. + */ +export function buildCredentialGroupConnectUrl({ + publicId, + provider, + returnKey, +}: { + publicId: string + /** Credential provider ID of the group option to connect (for example `google-email`). */ + provider: string + returnKey?: CredentialGroupConnectReturnKey +}): string { + if (!publicId.trim()) throw new Error('Credential group public ID is required') + if (!provider.trim()) throw new Error('Credential provider is required') + const url = new URL( + `/credential-groups/${encodeURIComponent(publicId)}/connect`, + `${getBaseUrl()}/` + ) + url.searchParams.set('provider', provider) + if (returnKey) url.searchParams.set('return', returnKey) + return url.toString() +} diff --git a/apps/sim/lib/credential-groups/connection-request-policy.ts b/apps/sim/lib/credential-groups/connection-request-policy.ts new file mode 100644 index 00000000000..bf16c82449c --- /dev/null +++ b/apps/sim/lib/credential-groups/connection-request-policy.ts @@ -0,0 +1,66 @@ +import { z } from 'zod' +import { ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT } from '@/lib/credential-groups/limits' + +export const CONNECTION_REQUEST_DAILY_LIMIT_MAX = 1000 +export const CONNECTION_REQUEST_DAILY_LIMIT_DEFAULT = 50 +export const CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT = 50 +export const CONNECTION_REQUEST_PROVIDER_LIMIT = 100 + +const EMAIL_DOMAIN_PATTERN = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/ +const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/ + +function sortedUnique(values: readonly string[]): boolean { + return values.every((value, index) => index === 0 || values[index - 1] < value) +} + +/** A bare, lowercase domain such as `example.com`; wildcards and addresses are refused. */ +const connectionRequestEmailDomainSchema = z + .string() + .regex(EMAIL_DOMAIN_PATTERN, 'Enter a domain such as example.com') + +export const connectionRequestSettingsSchema = z + .object({ + enabled: z.boolean(), + emailDomains: z + .array(connectionRequestEmailDomainSchema) + .min(1, 'Add at least one email domain') + .max(CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT) + .refine(sortedUnique, 'Email domains must be sorted and unique'), + providers: z + .array(z.string().regex(PROVIDER_ID_PATTERN)) + .min(1, 'Select at least one integration') + .max(CONNECTION_REQUEST_PROVIDER_LIMIT) + .refine(sortedUnique, 'Integrations must be sorted and unique'), + dailyLimit: z.number().int().min(1).max(CONNECTION_REQUEST_DAILY_LIMIT_MAX), + sendEmail: z.boolean(), + }) + .strict() + +const connectionRequestWorkspacesSchema = z.discriminatedUnion('mode', [ + z.object({ mode: z.literal('all') }).strict(), + z + .object({ + mode: z.literal('selected'), + workspaceIds: z + .array(z.string().min(1).max(128)) + .min(1, 'Select at least one workspace') + .max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT) + .refine(sortedUnique, 'Workspaces must be sorted and unique'), + }) + .strict(), +]) + +/** + * What an organization admin allows workflows to ask for. "All" workspaces means every + * workspace already allowed on the Access tab; a request never widens that allowlist. + */ +export const connectionRequestPolicySchema = connectionRequestSettingsSchema + .extend({ workspaces: connectionRequestWorkspacesSchema }) + .strict() + +export type ConnectionRequestPolicy = z.output + +/** Lowercases, trims, sorts, and de-duplicates admin input before it is validated. */ +export function normalizeConnectionRequestList(values: readonly string[]): string[] { + return [...new Set(values.map((value) => value.trim().toLowerCase()).filter(Boolean))].sort() +} diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts new file mode 100644 index 00000000000..206cc1c898c --- /dev/null +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -0,0 +1,253 @@ +import { db } from '@sim/db' +import { + credential, + credentialGroup, + credentialGroupEnrollment, + organization, +} from '@sim/db/schema' +import { createLogger } from '@sim/logger' +import { sha256Hex } from '@sim/security/hash' +import { getErrorMessage } from '@sim/utils/errors' +import { generateId } from '@sim/utils/id' +import { truncate } from '@sim/utils/string' +import { and, count, eq, gt, inArray, isNotNull } from 'drizzle-orm' +import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' +import { getCredentialGroupInvitationSubject } from '@/components/emails/subjects' +import { resourceScopeFromOwner } from '@/lib/core/resource-scope' +import { resourceScopeCondition } from '@/lib/core/resource-scope.server' +import { + LIVE_ENROLLMENT_STATUSES, + listCredentialGroupCredentialReferences, +} from '@/lib/credential-groups/credentials' +import { lockCredentialGroupInvitationTarget } from '@/lib/credential-groups/enrollments' +import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' +import { sendEmail } from '@/lib/messaging/email/mailer' +import { getFromEmailAddress } from '@/lib/messaging/email/utils' + +const logger = createLogger('CredentialGroupConnectionRequests') + +const DAY_MS = 24 * 60 * 60 * 1000 +/** Matches the admin invitation lifetime, so an unbound requested enrollment ages out alike. */ +const REQUESTED_ENROLLMENT_TTL_MS = 7 * DAY_MS + +/** What a workflow may learn about one person and integration. Nothing finer is exposed. */ +export type OrganizationAccountConnectionStatus = 'connected' | 'not_connected' | 'needs_reconnect' + +export class ConnectionRequestDailyLimitError extends Error { + constructor() { + super('This organization reached its daily limit for workflow connection requests') + this.name = 'ConnectionRequestDailyLimitError' + } +} + +/** + * Collapses a person's enrollment and credentials for one integration into a workflow-safe + * status. `connected` uses the same live-account query as Find Organization Account, so the + * returned credential is the one that operation would return. `needs_reconnect` means a live + * enrollment holds an account the provider stopped honoring. Everything else, including an + * invitation, a revocation, a failed delivery, or no enrollment at all, is `not_connected`. + */ +export async function loadOrganizationAccountConnectionStatus(input: { + organizationId: string + credentialGroupId: string + credentialGroupOptionIds: string[] + email: string + providerId: string +}): Promise<{ status: OrganizationAccountConnectionStatus; credentialId: string | null }> { + if (input.credentialGroupOptionIds.length === 0) + return { status: 'not_connected', credentialId: null } + const { credentials } = await listCredentialGroupCredentialReferences({ + organizationId: input.organizationId, + credentialGroupId: input.credentialGroupId, + credentialGroupOptionIds: input.credentialGroupOptionIds, + email: input.email, + credentialProviderIds: [input.providerId], + limit: 1, + }) + const [connected] = credentials + if (connected) return { status: 'connected', credentialId: connected.credentialId } + + const [stale] = await db + .select({ id: credential.id }) + .from(credential) + .innerJoin( + credentialGroupEnrollment, + eq(credentialGroupEnrollment.id, credential.credentialGroupEnrollmentId) + ) + .where( + and( + resourceScopeCondition( + credential, + resourceScopeFromOwner({ organizationId: input.organizationId }) + ), + eq(credential.type, 'managed_oauth'), + eq(credential.managedOauthStatus, 'needs_reauth'), + eq(credential.providerId, input.providerId), + inArray(credential.credentialGroupOptionId, input.credentialGroupOptionIds), + eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId), + eq(credentialGroupEnrollment.email, input.email), + isNotNull(credentialGroupEnrollment.userId), + eq(credential.createdBy, credentialGroupEnrollment.userId), + inArray(credentialGroupEnrollment.status, [...LIVE_ENROLLMENT_STATUSES]) + ) + ) + .limit(1) + return stale + ? { status: 'needs_reconnect', credentialId: null } + : { status: 'not_connected', credentialId: null } +} + +/** The group's public identity and display names, for the connect link and its email. */ +export async function loadConnectionRequestGroup(credentialGroupId: string) { + const [row] = await db + .select({ + publicId: credentialGroup.publicId, + groupName: credentialGroup.name, + organizationName: organization.name, + }) + .from(credentialGroup) + .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) + .where(eq(credentialGroup.id, credentialGroupId)) + .limit(1) + if (!row) throw new Error('Credential group not found') + return row +} + +export interface RecordedConnectionRequest { + enrollmentId: string + /** Whether this request created the enrollment. */ + created: boolean + /** Whether the person should be emailed now: a new request, or a reminder past the cooldown. */ + notify: boolean +} + +/** + * Records one workflow's request that a person connect an account. Runs in one transaction: + * the group lock serializes the daily cap, and the per-email invitation lock is the one admin + * invitations take, so a request never races an invite for the same address. + * + * Only an absent enrollment is created. An existing one is never changed in status or + * attribution: a revoked person stays revoked, an admin's invitation stays the admin's, and a + * connected person stays connected. The only write to an existing row is claiming the reminder + * slot on an unbound, still-invited enrollment a workflow created, at most once a day. + */ +export async function recordCredentialGroupConnectionRequest(input: { + credentialGroupId: string + email: string + workflowId: string + dailyLimit: number + sendEmail: boolean +}): Promise { + return db.transaction(async (tx) => { + const now = new Date() + await acquireAdvisoryXactLock( + tx, + 'credential_group_connection_request', + `credential-group-connection-request:${input.credentialGroupId}` + ) + const [recent] = await tx + .select({ total: count() }) + .from(credentialGroupEnrollment) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId), + isNotNull(credentialGroupEnrollment.requestedByWorkflowId), + gt(credentialGroupEnrollment.createdAt, new Date(now.getTime() - DAY_MS)) + ) + ) + /** Checked before the address is looked up, so hitting the cap says nothing about the person. */ + if ((recent?.total ?? 0) >= input.dailyLimit) throw new ConnectionRequestDailyLimitError() + + await lockCredentialGroupInvitationTarget(tx, input.credentialGroupId, input.email) + const [existing] = await tx + .select({ + id: credentialGroupEnrollment.id, + status: credentialGroupEnrollment.status, + userId: credentialGroupEnrollment.userId, + sentAt: credentialGroupEnrollment.sentAt, + requestedByWorkflowId: credentialGroupEnrollment.requestedByWorkflowId, + }) + .from(credentialGroupEnrollment) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId), + eq(credentialGroupEnrollment.email, input.email) + ) + ) + .limit(1) + + if (existing) { + const remind = + input.sendEmail && + existing.requestedByWorkflowId !== null && + existing.status === 'invited' && + existing.userId === null && + (!existing.sentAt || existing.sentAt.getTime() <= now.getTime() - DAY_MS) + if (remind) { + await tx + .update(credentialGroupEnrollment) + .set({ sentAt: now, updatedAt: now }) + .where(eq(credentialGroupEnrollment.id, existing.id)) + } + return { enrollmentId: existing.id, created: false, notify: remind } + } + + const enrollmentId = generateId() + await tx.insert(credentialGroupEnrollment).values({ + id: enrollmentId, + credentialGroupId: input.credentialGroupId, + email: input.email, + status: 'invited', + /** No invitation link is issued: the person signs in on the connect page instead. */ + invitationTokenHash: sha256Hex(generateId()), + invitationExpiresAt: new Date(now.getTime() + REQUESTED_ENROLLMENT_TTL_MS), + invitedAt: now, + sentAt: input.sendEmail ? now : null, + createdBy: null, + requestedByWorkflowId: input.workflowId, + createdAt: now, + updatedAt: now, + }) + return { enrollmentId, created: true, notify: input.sendEmail } + }) +} + +/** + * Emails the person the stable connect link. A failed delivery is recorded for admins on the + * enrollment and never surfaces to the workflow, whose result must not depend on the person. + */ +export async function sendConnectionRequestEmail(input: { + enrollmentId: string + email: string + organizationName: string + credentialGroupName: string + providerName: string + connectUrl: string +}): Promise { + let failure: string + try { + const html = await renderCredentialGroupInvitationEmail({ + recipientEmail: input.email, + workspaceName: input.organizationName, + credentialGroupName: input.credentialGroupName, + invitationLink: input.connectUrl, + requestedProviderName: input.providerName, + }) + const result = await sendEmail({ + to: input.email, + subject: getCredentialGroupInvitationSubject(undefined, input.organizationName), + html, + from: getFromEmailAddress(), + emailType: 'transactional', + }) + if (result.success) return + failure = result.message + } catch (error) { + failure = getErrorMessage(error, 'Failed to send connection request email') + } + logger.warn('Connection request email failed', { enrollmentId: input.enrollmentId }) + await db + .update(credentialGroupEnrollment) + .set({ lastDeliveryError: truncate(failure, 500), updatedAt: new Date() }) + .where(eq(credentialGroupEnrollment.id, input.enrollmentId)) +} diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 7c12d0feb7e..72833271433 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -188,7 +188,7 @@ export async function lockCredentialGroupEnrollmentLifecycle( } /** Serializes invitation issuance before an enrollment row is known or locked. */ -async function lockCredentialGroupInvitationTarget( +export async function lockCredentialGroupInvitationTarget( executor: DbTransaction, groupId: string, email: string diff --git a/apps/sim/lib/resource-policies/registry.ts b/apps/sim/lib/resource-policies/registry.ts index 32c42363bdc..c15c3c31f29 100644 --- a/apps/sim/lib/resource-policies/registry.ts +++ b/apps/sim/lib/resource-policies/registry.ts @@ -3,7 +3,13 @@ import type { ResourcePolicyPrincipalType } from '@/lib/resource-policies/princi export const RESOURCE_POLICY_RESOURCE_TYPES = ['credential_group'] as const export const CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION = 'credential_groups.credentials.use' as const -export const RESOURCE_POLICY_ACTIONS = [CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION] as const +/** Lets a workflow ask a person to connect an account; the statement carries the admin's limits. */ +export const CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION = + 'credential_groups.connections.request' as const +export const RESOURCE_POLICY_ACTIONS = [ + CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION, + CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION, +] as const export type ResourcePolicyResourceType = (typeof RESOURCE_POLICY_RESOURCE_TYPES)[number] export type ResourcePolicyAction = (typeof RESOURCE_POLICY_ACTIONS)[number] diff --git a/packages/db/credential-group-resource-policies.ts b/packages/db/credential-group-resource-policies.ts index c21292ed4fb..7bac34d0516 100644 --- a/packages/db/credential-group-resource-policies.ts +++ b/packages/db/credential-group-resource-policies.ts @@ -10,6 +10,8 @@ const WORKFLOW_ACCESS_SID = 'WorkflowCredentialAccess' /** Statements the knowledge module writes for connectors crawling through an option. */ const KNOWLEDGE_CONNECTOR_ACCESS_SID_PREFIX = 'KnowledgeConnectorCredentialAccess:' const CREDENTIAL_USE_ACTION = 'credential_groups.credentials.use' +const CONNECTION_REQUEST_SID = 'WorkflowConnectionRequests' +const CONNECTION_REQUEST_ACTION = 'credential_groups.connections.request' const ACTOR_OWNS_CREDENTIAL_CONDITION_KEY = 'credential_group:ActorOwnsCredential' const DEPLOYMENT_MODE_CONDITION_KEY = 'execution:WorkflowMode' @@ -377,6 +379,13 @@ export function validateOrganizationAccountPolicyDocument( const selectedWorkspaces = new Set() for (const value of document.statements) { const statement = requireRecord(value, 'Organization account workspace statement') + if (statement.sid === CONNECTION_REQUEST_SID) { + if (seenStatements.has(CONNECTION_REQUEST_SID)) + throw new Error('Organization account policy repeats its connection request statement') + seenStatements.add(CONNECTION_REQUEST_SID) + validateConnectionRequestStatement(statement) + continue + } requireExactKeys( statement, [ @@ -442,6 +451,59 @@ export function validateOrganizationAccountPolicyDocument( throw new Error('Organization account policy supports at most 1000 workspaces') } +/** The workflow connection request statement; the application owns its settings' finer rules. */ +function validateConnectionRequestStatement(statement: Record): void { + requireExactKeys( + statement, + ['sid', 'effect', 'actions', 'principals', 'settings'], + 'Organization account connection request statement' + ) + if ( + statement.effect !== 'allow' || + !Array.isArray(statement.actions) || + statement.actions.length !== 1 || + statement.actions[0] !== CONNECTION_REQUEST_ACTION || + !Array.isArray(statement.principals) || + statement.principals.length > 1000 + ) + throw new Error('Organization account connection request statement is invalid') + let previous = '' + for (const value of statement.principals) { + const principal = requireRecord(value, 'Organization account connection request principal') + requireExactKeys( + principal, + ['type', 'workspaceId'], + 'Organization account connection request principal' + ) + const id = requireCanonicalId(principal.workspaceId, 'Organization account workspace ID') + if (principal.type !== 'workspace' || id <= previous) + throw new Error('Organization account workspace principals must be unique and sorted') + previous = id + } + const settings = requireRecord(statement.settings, 'Organization account connection request') + requireExactKeys( + settings, + ['enabled', 'emailDomains', 'providers', 'dailyLimit', 'sendEmail'], + 'Organization account connection request' + ) + const { dailyLimit } = settings + if ( + typeof settings.enabled !== 'boolean' || + typeof settings.sendEmail !== 'boolean' || + typeof dailyLimit !== 'number' || + !Number.isInteger(dailyLimit) || + dailyLimit < 1 || + dailyLimit > 1000 || + !Array.isArray(settings.emailDomains) || + settings.emailDomains.length < 1 || + !settings.emailDomains.every((domain) => typeof domain === 'string') || + !Array.isArray(settings.providers) || + settings.providers.length < 1 || + !settings.providers.every((provider) => typeof provider === 'string') + ) + throw new Error('Organization account connection request settings are invalid') +} + function assertPage( rows: T[], afterId: string, diff --git a/packages/db/migrations/0489_credential_group_workflow_requests.sql b/packages/db/migrations/0489_credential_group_workflow_requests.sql new file mode 100644 index 00000000000..dcf0dadb513 --- /dev/null +++ b/packages/db/migrations/0489_credential_group_workflow_requests.sql @@ -0,0 +1 @@ +ALTER TABLE "credential_group_enrollment" ADD COLUMN "requested_by_workflow_id" text; \ No newline at end of file diff --git a/packages/db/migrations/meta/0489_snapshot.json b/packages/db/migrations/meta/0489_snapshot.json new file mode 100644 index 00000000000..5ddc62ca26a --- /dev/null +++ b/packages/db/migrations/meta/0489_snapshot.json @@ -0,0 +1,34725 @@ +{ + "id": "bcdab562-c001-4b25-abf0-955e2efbc4b6", + "prevId": "71fe2561-72db-41f3-a89e-d44b1520cbce", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config": { + "name": "oauth_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_at": { + "name": "refresh_revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_code": { + "name": "refresh_revoked_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_token_hash": { + "name": "refresh_revoked_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "account_user_id_idx": { + "name": "account_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_account_on_account_id_provider_id": { + "name": "idx_account_on_account_id_provider_id", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_blocked": { + "name": "activity_rollup_blocked", + "schema": "", + "columns": { + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": true, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "retry_at": { + "name": "retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_dirty": { + "name": "activity_rollup_dirty", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "due_at": { + "name": "due_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "activity_rollup_dirty_due_at_idx": { + "name": "activity_rollup_dirty_due_at_idx", + "columns": [ + { + "expression": "due_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "activity_rollup_dirty_workspace_id_bucket_start_pk": { + "name": "activity_rollup_dirty_workspace_id_bucket_start_pk", + "columns": ["workspace_id", "bucket_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_inflight": { + "name": "activity_rollup_inflight", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "next_check_at": { + "name": "next_check_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "activity_rollup_inflight_next_check_at_idx": { + "name": "activity_rollup_inflight_next_check_at_idx", + "columns": [ + { + "expression": "next_check_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "activity_rollup_inflight_workspace_id_bucket_start_pk": { + "name": "activity_rollup_inflight_workspace_id_bucket_start_pk", + "columns": ["workspace_id", "bucket_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_state": { + "name": "activity_rollup_state", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "coverage_start": { + "name": "coverage_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "fresh_through": { + "name": "fresh_through", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "backfill_completed_at": { + "name": "backfill_completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_end_scan": { + "name": "last_end_scan", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "lease_owner": { + "name": "lease_owner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "housekeeping_at": { + "name": "housekeeping_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "maintained_at": { + "name": "maintained_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "failed_passes": { + "name": "failed_passes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "corrections_at": { + "name": "corrections_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_memory_turn": { + "name": "agent_memory_turn", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_order": { + "name": "execution_order", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "encrypted_state": { + "name": "encrypted_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "agent_memory_turn_invocation_unique": { + "name": "agent_memory_turn_invocation_unique", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "node_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_memory_turn_workflow_idx": { + "name": "agent_memory_turn_workflow_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "agent_memory_turn_memory_id_memory_id_fk": { + "name": "agent_memory_turn_memory_id_memory_id_fk", + "tableFrom": "agent_memory_turn", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "agent_memory_turn_workflow_id_workflow_id_fk": { + "name": "agent_memory_turn_workflow_id_workflow_id_fk", + "tableFrom": "agent_memory_turn", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.api_key": { + "name": "api_key", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key_hash": { + "name": "key_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'personal'" + }, + "access": { + "name": "access", + "type": "api_key_access", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'write'" + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "api_key_workspace_type_idx": { + "name": "api_key_workspace_type_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "api_key_user_type_idx": { + "name": "api_key_user_type_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "api_key_key_hash_idx": { + "name": "api_key_key_hash_idx", + "columns": [ + { + "expression": "key_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "api_key_user_id_user_id_fk": { + "name": "api_key_user_id_user_id_fk", + "tableFrom": "api_key", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "api_key_workspace_id_workspace_id_fk": { + "name": "api_key_workspace_id_workspace_id_fk", + "tableFrom": "api_key", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "api_key_created_by_user_id_fk": { + "name": "api_key_created_by_user_id_fk", + "tableFrom": "api_key", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "api_key_key_unique": { + "name": "api_key_key_unique", + "nullsNotDistinct": false, + "columns": ["key"] + } + }, + "policies": {}, + "checkConstraints": { + "workspace_type_check": { + "name": "workspace_type_check", + "value": "(type = 'workspace' AND workspace_id IS NOT NULL) OR (type = 'personal' AND workspace_id IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.assistant_tool_permission": { + "name": "assistant_tool_permission", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "read_policy": { + "name": "read_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'allow'" + }, + "write_policy": { + "name": "write_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'ask'" + }, + "overrides": { + "name": "overrides", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "assistant_tool_permission_credential_idx": { + "name": "assistant_tool_permission_credential_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "assistant_tool_permission_user_idx": { + "name": "assistant_tool_permission_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assistant_tool_permission_organization_id_organization_id_fk": { + "name": "assistant_tool_permission_organization_id_organization_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_tool_permission_user_id_user_id_fk": { + "name": "assistant_tool_permission_user_id_user_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_tool_permission_credential_id_credential_id_fk": { + "name": "assistant_tool_permission_credential_id_credential_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "assistant_tool_permission_organization_id_user_id_credential_id_pk": { + "name": "assistant_tool_permission_organization_id_user_id_credential_id_pk", + "columns": ["organization_id", "user_id", "credential_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "assistant_tool_permission_policy_check": { + "name": "assistant_tool_permission_policy_check", + "value": "\"assistant_tool_permission\".\"read_policy\" IN ('allow', 'ask', 'block') AND \"assistant_tool_permission\".\"write_policy\" IN ('allow', 'ask', 'block')" + }, + "assistant_tool_permission_revision_check": { + "name": "assistant_tool_permission_revision_check", + "value": "\"assistant_tool_permission\".\"revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.async_jobs": { + "name": "async_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_at": { + "name": "run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 3 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "async_jobs_status_started_at_idx": { + "name": "async_jobs_status_started_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_status_completed_at_idx": { + "name": "async_jobs_status_completed_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "completed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_pending_run_at_idx": { + "name": "async_jobs_schedule_pending_run_at_idx", + "columns": [ + { + "expression": "run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_processing_started_at_idx": { + "name": "async_jobs_schedule_processing_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" = 'processing'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_unreconciled_terminal_idx": { + "name": "async_jobs_schedule_unreconciled_terminal_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" IN ('completed', 'failed', 'cancelled') AND COALESCE(\"async_jobs\".\"metadata\" ->> 'scheduleReconciled', 'false') <> 'true'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.audit_log": { + "name": "audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_email": { + "name": "actor_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_name": { + "name": "resource_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "audit_log_workspace_created_idx": { + "name": "audit_log_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_workspace_created_at_id_idx": { + "name": "audit_log_workspace_created_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_actor_created_idx": { + "name": "audit_log_actor_created_idx", + "columns": [ + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_org_level_created_at_id_idx": { + "name": "audit_log_org_level_created_at_id_idx", + "columns": [ + { + "expression": "(\"metadata\"->>'organizationId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"audit_log\".\"workspace_id\" IS NULL AND (\"audit_log\".\"metadata\"->>'organizationId') IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "audit_log_resource_idx": { + "name": "audit_log_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_action_idx": { + "name": "audit_log_action_idx", + "columns": [ + { + "expression": "action", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "audit_log_workspace_id_workspace_id_fk": { + "name": "audit_log_workspace_id_workspace_id_fk", + "tableFrom": "audit_log", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "audit_log_actor_id_user_id_fk": { + "name": "audit_log_actor_id_user_id_fk", + "tableFrom": "audit_log", + "tableTo": "user", + "columnsFrom": ["actor_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_license": { + "name": "aws_marketplace_license", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "license_arn": { + "name": "license_arn", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "product_code": { + "name": "product_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "customer_aws_account_id": { + "name": "customer_aws_account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agreement_id": { + "name": "agreement_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agreement_seen_at": { + "name": "agreement_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "renewed_agreement_id": { + "name": "renewed_agreement_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "aws_marketplace_license_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_verified_at": { + "name": "last_verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "last_verification_attempt_at": { + "name": "last_verification_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "license_event_received_at": { + "name": "license_event_received_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "claim_token_hash": { + "name": "claim_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_expires_at": { + "name": "claim_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "linked_by_user_id": { + "name": "linked_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_linked_at": { + "name": "organization_linked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "contact_email": { + "name": "contact_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "company_name": { + "name": "company_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "aws_marketplace_license_arn_unique": { + "name": "aws_marketplace_license_arn_unique", + "columns": [ + { + "expression": "license_arn", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_claim_token_hash_unique": { + "name": "aws_marketplace_license_claim_token_hash_unique", + "columns": [ + { + "expression": "claim_token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_agreement_id_idx": { + "name": "aws_marketplace_license_agreement_id_idx", + "columns": [ + { + "expression": "agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_renewed_agreement_id_idx": { + "name": "aws_marketplace_license_renewed_agreement_id_idx", + "columns": [ + { + "expression": "renewed_agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_account_product_idx": { + "name": "aws_marketplace_license_account_product_idx", + "columns": [ + { + "expression": "customer_aws_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "product_code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_last_attempt_idx": { + "name": "aws_marketplace_license_last_attempt_idx", + "columns": [ + { + "expression": "last_verification_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_organization_id_idx": { + "name": "aws_marketplace_license_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_linked_by_user_id_idx": { + "name": "aws_marketplace_license_linked_by_user_id_idx", + "columns": [ + { + "expression": "linked_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "aws_marketplace_license_organization_id_organization_id_fk": { + "name": "aws_marketplace_license_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_license", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "aws_marketplace_license_linked_by_user_id_user_id_fk": { + "name": "aws_marketplace_license_linked_by_user_id_user_id_fk", + "tableFrom": "aws_marketplace_license", + "tableTo": "user", + "columnsFrom": ["linked_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_usage_report": { + "name": "aws_marketplace_usage_report", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "license_id": { + "name": "license_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hour_start": { + "name": "hour_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "aws_marketplace_usage_report_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "metering_record_id": { + "name": "metering_record_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reported_at": { + "name": "reported_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "aws_marketplace_usage_report_license_dimension_hour_unique": { + "name": "aws_marketplace_usage_report_license_dimension_hour_unique", + "columns": [ + { + "expression": "license_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dimension", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "hour_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_usage_report_status_hour_idx": { + "name": "aws_marketplace_usage_report_status_hour_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "hour_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_usage_report_organization_id_idx": { + "name": "aws_marketplace_usage_report_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "aws_marketplace_usage_report_organization_id_organization_id_fk": { + "name": "aws_marketplace_usage_report_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_usage_report", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "aws_marketplace_usage_report_license_id_aws_marketplace_license_id_fk": { + "name": "aws_marketplace_usage_report_license_id_aws_marketplace_license_id_fk", + "tableFrom": "aws_marketplace_usage_report", + "tableTo": "aws_marketplace_license", + "columnsFrom": ["license_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_usage_tally": { + "name": "aws_marketplace_usage_tally", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "period_start": { + "name": "period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "counted_from": { + "name": "counted_from", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "cost_usd": { + "name": "cost_usd", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "units": { + "name": "units", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "aws_marketplace_usage_tally_organization_id_organization_id_fk": { + "name": "aws_marketplace_usage_tally_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_usage_tally", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "aws_marketplace_usage_tally_organization_id_dimension_period_start_pk": { + "name": "aws_marketplace_usage_tally_organization_id_dimension_period_start_pk", + "columns": ["organization_id", "dimension", "period_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.background_work_status": { + "name": "background_work_status", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "background_work_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "background_work_status_value", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "background_work_status_workspace_status_idx": { + "name": "background_work_status_workspace_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_workflow_status_idx": { + "name": "background_work_status_workflow_status_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_meta_child_ws_idx": { + "name": "background_work_status_meta_child_ws_idx", + "columns": [ + { + "expression": "(\"metadata\" ->> 'childWorkspaceId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_meta_other_ws_idx": { + "name": "background_work_status_meta_other_ws_idx", + "columns": [ + { + "expression": "(\"metadata\" ->> 'otherWorkspaceId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "background_work_status_workspace_id_workspace_id_fk": { + "name": "background_work_status_workspace_id_workspace_id_fk", + "tableFrom": "background_work_status", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "background_work_status_workflow_id_workflow_id_fk": { + "name": "background_work_status_workflow_id_workflow_id_fk", + "tableFrom": "background_work_status", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.changelog_change": { + "name": "changelog_change", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "release_id": { + "name": "release_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "changelog_change_release_position_unique": { + "name": "changelog_change_release_position_unique", + "columns": [ + { + "expression": "release_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "changelog_change_release_id_changelog_release_id_fk": { + "name": "changelog_change_release_id_changelog_release_id_fk", + "tableFrom": "changelog_change", + "tableTo": "changelog_release", + "columnsFrom": ["release_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "changelog_change_workflow_id_workflow_id_fk": { + "name": "changelog_change_workflow_id_workflow_id_fk", + "tableFrom": "changelog_change", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_change_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "changelog_change_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "changelog_change", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_change_chat_id_copilot_chats_id_fk": { + "name": "changelog_change_chat_id_copilot_chats_id_fk", + "tableFrom": "changelog_change", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.changelog_release": { + "name": "changelog_release", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version_major": { + "name": "version_major", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version_minor": { + "name": "version_minor", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version_patch": { + "name": "version_patch", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "bump_reason": { + "name": "bump_reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body_file_id": { + "name": "body_file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "published_at": { + "name": "published_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "changelog_release_workspace_version_unique": { + "name": "changelog_release_workspace_version_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_major", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_minor", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_patch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "changelog_release_body_file_unique": { + "name": "changelog_release_body_file_unique", + "columns": [ + { + "expression": "body_file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "changelog_release_workspace_published_idx": { + "name": "changelog_release_workspace_published_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "published_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "changelog_release_workspace_id_workspace_id_fk": { + "name": "changelog_release_workspace_id_workspace_id_fk", + "tableFrom": "changelog_release", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "changelog_release_body_file_id_workspace_files_id_fk": { + "name": "changelog_release_body_file_id_workspace_files_id_fk", + "tableFrom": "changelog_release", + "tableTo": "workspace_files", + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "changelog_release_created_by_user_id_fk": { + "name": "changelog_release_created_by_user_id_fk", + "tableFrom": "changelog_release", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_release_updated_by_user_id_fk": { + "name": "changelog_release_updated_by_user_id_fk", + "tableFrom": "changelog_release", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "changelog_release_version_check": { + "name": "changelog_release_version_check", + "value": "\"changelog_release\".\"version_major\" >= 0 AND \"changelog_release\".\"version_minor\" >= 0 AND \"changelog_release\".\"version_patch\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.chat": { + "name": "chat", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "customizations": { + "name": "customizations", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_emails": { + "name": "allowed_emails", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "output_configs": { + "name": "output_configs", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "include_thinking": { + "name": "include_thinking", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "include_tool_calls": { + "name": "include_tool_calls", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "identifier_idx": { + "name": "identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"chat\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_archived_at_partial_idx": { + "name": "chat_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_chat_on_workflow_id_archived_at": { + "name": "idx_chat_on_workflow_id_archived_at", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_user_id_idx": { + "name": "chat_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_workflow_id_workflow_id_fk": { + "name": "chat_workflow_id_workflow_id_fk", + "tableFrom": "chat", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_user_id_user_id_fk": { + "name": "chat_user_id_user_id_fk", + "tableFrom": "chat", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.client_credential_token": { + "name": "client_credential_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "encrypted_value": { + "name": "encrypted_value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token_digest": { + "name": "access_token_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "client_credential_token_expires_at_idx": { + "name": "client_credential_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"client_credential_token\".\"access_token_digest\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "client_credential_token_access_token_digest_idx": { + "name": "client_credential_token_access_token_digest_idx", + "columns": [ + { + "expression": "access_token_digest", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"client_credential_token\".\"access_token_digest\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_async_tool_calls": { + "name": "copilot_async_tool_calls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "checkpoint_id": { + "name": "checkpoint_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "tool_call_id": { + "name": "tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "args": { + "name": "args", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "executable_name": { + "name": "executable_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_workspace_id": { + "name": "target_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_args": { + "name": "approved_args", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "assistant_action": { + "name": "assistant_action", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "execution_retryable": { + "name": "execution_retryable", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "status": { + "name": "status", + "type": "copilot_async_tool_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "result": { + "name": "result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_decision": { + "name": "permission_decision", + "type": "copilot_tool_permission_decision", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "permission_decided_at": { + "name": "permission_decided_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_requested_at": { + "name": "permission_requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "pickup_deadline_at": { + "name": "pickup_deadline_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "persist_seq": { + "name": "persist_seq", + "type": "bigint", + "primaryKey": false, + "notNull": false, + "default": "nextval('copilot_async_tool_calls_persist_seq')" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "claimed_by": { + "name": "claimed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "browser_download_started_at": { + "name": "browser_download_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_started_at": { + "name": "execution_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_settled_at": { + "name": "execution_settled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_owner_token": { + "name": "execution_owner_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_lease_expires_at": { + "name": "execution_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execution_revoked_at": { + "name": "execution_revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execution_attempts": { + "name": "execution_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "execution_deadline_at": { + "name": "execution_deadline_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "client_workflow_execution_id": { + "name": "client_workflow_execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sandbox_processes": { + "name": "sandbox_processes", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_async_tool_calls_checkpoint_id_idx": { + "name": "copilot_async_tool_calls_checkpoint_id_idx", + "columns": [ + { + "expression": "checkpoint_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_status_idx": { + "name": "copilot_async_tool_calls_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_run_status_idx": { + "name": "copilot_async_tool_calls_run_status_idx", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_tool_call_id_unique": { + "name": "copilot_async_tool_calls_tool_call_id_unique", + "columns": [ + { + "expression": "tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_async_tool_calls_run_id_copilot_runs_id_fk": { + "name": "copilot_async_tool_calls_run_id_copilot_runs_id_fk", + "tableFrom": "copilot_async_tool_calls", + "tableTo": "copilot_runs", + "columnsFrom": ["run_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_async_tool_calls_checkpoint_id_copilot_run_checkpoints_id_fk": { + "name": "copilot_async_tool_calls_checkpoint_id_copilot_run_checkpoints_id_fk", + "tableFrom": "copilot_async_tool_calls", + "tableTo": "copilot_run_checkpoints", + "columnsFrom": ["checkpoint_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_chats": { + "name": "copilot_chats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "memory_space_id": { + "name": "memory_space_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "chat_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'copilot'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude-3-7-sonnet-latest'" + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_conversation_key": { + "name": "external_conversation_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_conversation_metadata": { + "name": "external_conversation_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "preview_yaml": { + "name": "preview_yaml", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "resources": { + "name": "resources", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "auto_allowed_tools": { + "name": "auto_allowed_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "pinned": { + "name": "pinned", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_chats_organization_id_idx": { + "name": "copilot_chats_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_external_conversation_unique": { + "name": "copilot_chats_external_conversation_unique", + "columns": [ + { + "expression": "external_conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"copilot_chats\".\"external_conversation_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_org_created_idx": { + "name": "copilot_chats_user_org_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_workflow_id_idx": { + "name": "copilot_chats_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workflow_idx": { + "name": "copilot_chats_user_workflow_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workspace_idx": { + "name": "copilot_chats_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_created_at_idx": { + "name": "copilot_chats_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_updated_at_idx": { + "name": "copilot_chats_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_workspace_created_at_id_idx": { + "name": "copilot_chats_workspace_created_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workspace_deleted_partial_idx": { + "name": "copilot_chats_user_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_chats\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_chats_user_id_user_id_fk": { + "name": "copilot_chats_user_id_user_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_workflow_id_workflow_id_fk": { + "name": "copilot_chats_workflow_id_workflow_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_workspace_id_workspace_id_fk": { + "name": "copilot_chats_workspace_id_workspace_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_organization_id_organization_id_fk": { + "name": "copilot_chats_organization_id_organization_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "copilot_chats_owner_check": { + "name": "copilot_chats_owner_check", + "value": "num_nonnulls(\"copilot_chats\".\"workspace_id\", \"copilot_chats\".\"organization_id\") <= 1" + }, + "copilot_chats_organization_workflow_check": { + "name": "copilot_chats_organization_workflow_check", + "value": "\"copilot_chats\".\"organization_id\" IS NULL OR \"copilot_chats\".\"workflow_id\" IS NULL" + } + }, + "isRLSEnabled": false + }, + "public.copilot_feedback": { + "name": "copilot_feedback", + "schema": "", + "columns": { + "feedback_id": { + "name": "feedback_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_query": { + "name": "user_query", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent_response": { + "name": "agent_response", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_positive": { + "name": "is_positive", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "feedback": { + "name": "feedback", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_yaml": { + "name": "workflow_yaml", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_feedback_user_id_idx": { + "name": "copilot_feedback_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_chat_id_idx": { + "name": "copilot_feedback_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_user_chat_idx": { + "name": "copilot_feedback_user_chat_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_is_positive_idx": { + "name": "copilot_feedback_is_positive_idx", + "columns": [ + { + "expression": "is_positive", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_created_at_idx": { + "name": "copilot_feedback_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_feedback_user_id_user_id_fk": { + "name": "copilot_feedback_user_id_user_id_fk", + "tableFrom": "copilot_feedback", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_feedback_chat_id_copilot_chats_id_fk": { + "name": "copilot_feedback_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_feedback", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_messages": { + "name": "copilot_messages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "display_content": { + "name": "display_content", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_messages_chat_message_unique": { + "name": "copilot_messages_chat_message_unique", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_created_at_idx": { + "name": "copilot_messages_chat_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_seq_idx": { + "name": "copilot_messages_chat_seq_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_stream_idx": { + "name": "copilot_messages_chat_stream_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "stream_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"stream_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_user_seq_idx": { + "name": "copilot_messages_chat_user_seq_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_user_created_at_idx": { + "name": "copilot_messages_chat_user_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user' AND \"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_user_created_at_idx": { + "name": "copilot_messages_user_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user' AND \"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_messages_chat_id_copilot_chats_id_fk": { + "name": "copilot_messages_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_messages", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_organization_request_stops": { + "name": "copilot_organization_request_stops", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stopped_at": { + "name": "stopped_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "copilot_organization_request_stops_user_id_user_id_fk": { + "name": "copilot_organization_request_stops_user_id_user_id_fk", + "tableFrom": "copilot_organization_request_stops", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_organization_request_stops_organization_id_organization_id_fk": { + "name": "copilot_organization_request_stops_organization_id_organization_id_fk", + "tableFrom": "copilot_organization_request_stops", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "copilot_organization_request_stops_user_id_organization_id_stream_id_pk": { + "name": "copilot_organization_request_stops_user_id_organization_id_stream_id_pk", + "columns": ["user_id", "organization_id", "stream_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_request_stops": { + "name": "copilot_request_stops", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stopped_at": { + "name": "stopped_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "copilot_request_stops_user_id_user_id_fk": { + "name": "copilot_request_stops_user_id_user_id_fk", + "tableFrom": "copilot_request_stops", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_request_stops_workspace_id_workspace_id_fk": { + "name": "copilot_request_stops_workspace_id_workspace_id_fk", + "tableFrom": "copilot_request_stops", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "copilot_request_stops_user_id_workspace_id_stream_id_pk": { + "name": "copilot_request_stops_user_id_workspace_id_stream_id_pk", + "columns": ["user_id", "workspace_id", "stream_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_run_checkpoints": { + "name": "copilot_run_checkpoints", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "pending_tool_call_id": { + "name": "pending_tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "conversation_snapshot": { + "name": "conversation_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "agent_state": { + "name": "agent_state", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "provider_request": { + "name": "provider_request", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_run_checkpoints_pending_tool_call_id_idx": { + "name": "copilot_run_checkpoints_pending_tool_call_id_idx", + "columns": [ + { + "expression": "pending_tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_run_checkpoints_run_pending_tool_unique": { + "name": "copilot_run_checkpoints_run_pending_tool_unique", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "pending_tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_run_checkpoints_run_id_copilot_runs_id_fk": { + "name": "copilot_run_checkpoints_run_id_copilot_runs_id_fk", + "tableFrom": "copilot_run_checkpoints", + "tableTo": "copilot_runs", + "columnsFrom": ["run_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_runs": { + "name": "copilot_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_execution_version": { + "name": "tool_execution_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tool_admission_closed_at": { + "name": "tool_admission_closed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "parent_run_id": { + "name": "parent_run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agent": { + "name": "agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "copilot_run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "request_context": { + "name": "request_context", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "desktop_device_id": { + "name": "desktop_device_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "copilot_runs_parent_run_id_idx": { + "name": "copilot_runs_parent_run_id_idx", + "columns": [ + { + "expression": "parent_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_chat_started_at_idx": { + "name": "copilot_runs_chat_started_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_user_id_idx": { + "name": "copilot_runs_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_workflow_id_idx": { + "name": "copilot_runs_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_status_idx": { + "name": "copilot_runs_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_chat_execution_idx": { + "name": "copilot_runs_chat_execution_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_execution_started_at_idx": { + "name": "copilot_runs_execution_started_at_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_workspace_completed_at_id_idx": { + "name": "copilot_runs_workspace_completed_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"completed_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_stream_id_unique": { + "name": "copilot_runs_stream_id_unique", + "columns": [ + { + "expression": "stream_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_desktop_device_started_at_idx": { + "name": "copilot_runs_desktop_device_started_at_idx", + "columns": [ + { + "expression": "desktop_device_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_runs\".\"desktop_device_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_runs_chat_id_copilot_chats_id_fk": { + "name": "copilot_runs_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_user_id_user_id_fk": { + "name": "copilot_runs_user_id_user_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_workflow_id_workflow_id_fk": { + "name": "copilot_runs_workflow_id_workflow_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_workspace_id_workspace_id_fk": { + "name": "copilot_runs_workspace_id_workspace_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_organization_id_organization_id_fk": { + "name": "copilot_runs_organization_id_organization_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_desktop_device_id_desktop_devices_id_fk": { + "name": "copilot_runs_desktop_device_id_desktop_devices_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "desktop_devices", + "columnsFrom": ["desktop_device_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_service_usage": { + "name": "copilot_service_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tool_call_id": { + "name": "tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "service": { + "name": "service", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cost_usd": { + "name": "cost_usd", + "type": "numeric(12, 8)", + "primaryKey": false, + "notNull": false + }, + "worker_origin": { + "name": "worker_origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "delivered_at": { + "name": "delivered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "copilot_service_usage_pending_idx": { + "name": "copilot_service_usage_pending_idx", + "columns": [ + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "delivered_at IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.credential": { + "name": "credential", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "slack_app_id": { + "name": "slack_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "credential_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "unredacted": { + "name": "unredacted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_key": { + "name": "env_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_owner_user_id": { + "name": "env_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_service_account_key": { + "name": "encrypted_service_account_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_personal_token": { + "name": "encrypted_personal_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "authorization_app_id": { + "name": "authorization_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_enrollment_id": { + "name": "credential_group_enrollment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_option_id": { + "name": "credential_group_option_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_server_id": { + "name": "mcp_server_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_oauth_config_version": { + "name": "mcp_oauth_config_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "managed_oauth_scope_version": { + "name": "managed_oauth_scope_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "provider_subject_id": { + "name": "provider_subject_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_tenant_id": { + "name": "provider_tenant_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "managed_oauth_status": { + "name": "managed_oauth_status", + "type": "managed_oauth_credential_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "granted_scopes": { + "name": "granted_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "provider_metadata": { + "name": "provider_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "encrypted_oauth_token_set": { + "name": "encrypted_oauth_token_set", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_tools": { + "name": "mcp_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "mcp_tools_refreshed_at": { + "name": "mcp_tools_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_refreshed_at": { + "name": "last_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_organization_id_idx": { + "name": "credential_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_organization_account_unique": { + "name": "credential_organization_account_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"account_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_org_personal_token_unique": { + "name": "credential_org_personal_token_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'personal_token'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_id_idx": { + "name": "credential_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_type_idx": { + "name": "credential_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_provider_id_idx": { + "name": "credential_provider_id_idx", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_account_id_idx": { + "name": "credential_account_id_idx", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_env_owner_user_id_idx": { + "name": "credential_env_owner_user_id_idx", + "columns": [ + { + "expression": "env_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_idx": { + "name": "credential_group_enrollment_idx", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_mcp_server_idx": { + "name": "credential_mcp_server_idx", + "columns": [ + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_option_identity_unique": { + "name": "credential_group_option_identity_unique", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "credential_group_option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_tenant_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'managed_oauth'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_managed_mcp_enrollment_server_identity_unique": { + "name": "credential_managed_mcp_enrollment_server_identity_unique", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_subject_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_tenant_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'managed_mcp'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_account_unique": { + "name": "credential_workspace_account_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "account_id IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_env_unique": { + "name": "credential_workspace_env_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "type = 'env_workspace'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_personal_env_unique": { + "name": "credential_workspace_personal_env_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "type = 'env_personal'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_workspace_id_workspace_id_fk": { + "name": "credential_workspace_id_workspace_id_fk", + "tableFrom": "credential", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_organization_id_organization_id_fk": { + "name": "credential_organization_id_organization_id_fk", + "tableFrom": "credential", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_slack_app_id_slack_app_id_fk": { + "name": "credential_slack_app_id_slack_app_id_fk", + "tableFrom": "credential", + "tableTo": "slack_app", + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "credential_account_id_account_id_fk": { + "name": "credential_account_id_account_id_fk", + "tableFrom": "credential", + "tableTo": "account", + "columnsFrom": ["account_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_env_owner_user_id_user_id_fk": { + "name": "credential_env_owner_user_id_user_id_fk", + "tableFrom": "credential", + "tableTo": "user", + "columnsFrom": ["env_owner_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_credential_group_enrollment_id_credential_group_enrollment_id_fk": { + "name": "credential_credential_group_enrollment_id_credential_group_enrollment_id_fk", + "tableFrom": "credential", + "tableTo": "credential_group_enrollment", + "columnsFrom": ["credential_group_enrollment_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_mcp_server_id_mcp_servers_id_fk": { + "name": "credential_mcp_server_id_mcp_servers_id_fk", + "tableFrom": "credential", + "tableTo": "mcp_servers", + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_created_by_user_id_fk": { + "name": "credential_created_by_user_id_fk", + "tableFrom": "credential", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_owner_check": { + "name": "credential_owner_check", + "value": "num_nonnulls(\"credential\".\"workspace_id\", \"credential\".\"organization_id\") = 1" + }, + "credential_organization_type_check": { + "name": "credential_organization_type_check", + "value": "\"credential\".\"organization_id\" IS NULL OR \"credential\".\"type\" IN ('oauth', 'managed_oauth', 'managed_mcp', 'service_account', 'personal_token')" + }, + "credential_personal_token_source_check": { + "name": "credential_personal_token_source_check", + "value": "(type::text <> 'personal_token') OR (\n created_by IS NOT NULL\n AND provider_id IS NOT NULL\n AND provider_id = 'gitlab'\n AND provider_subject_id IS NOT NULL\n AND provider_tenant_id IS NOT NULL\n AND encrypted_personal_token IS NOT NULL\n AND granted_scopes IS NOT NULL\n AND cardinality(granted_scopes) > 0\n AND account_id IS NULL\n AND env_key IS NULL\n AND env_owner_user_id IS NULL\n AND authorization_app_id IS NULL\n AND encrypted_oauth_token_set IS NULL\n AND encrypted_service_account_key IS NULL\n AND unredacted = false\n )" + }, + "credential_oauth_source_check": { + "name": "credential_oauth_source_check", + "value": "(type <> 'oauth') OR (account_id IS NOT NULL AND provider_id IS NOT NULL)" + }, + "credential_managed_oauth_source_check": { + "name": "credential_managed_oauth_source_check", + "value": "(type::text <> 'managed_oauth') OR (\n account_id IS NULL\n AND provider_id IS NOT NULL\n AND authorization_app_id IS NOT NULL\n AND provider_subject_id IS NOT NULL\n AND managed_oauth_status IS NOT NULL\n AND granted_scopes IS NOT NULL\n AND encrypted_oauth_token_set IS NOT NULL\n AND granted_at IS NOT NULL\n )" + }, + "credential_managed_oauth_group_binding_check": { + "name": "credential_managed_oauth_group_binding_check", + "value": "(type::text <> 'managed_oauth') OR (\n credential_group_enrollment_id IS NOT NULL\n AND credential_group_option_id IS NOT NULL\n AND managed_oauth_scope_version IS NOT NULL\n AND managed_oauth_scope_version > 0\n )" + }, + "credential_managed_mcp_source_check": { + "name": "credential_managed_mcp_source_check", + "value": "(type::text <> 'managed_mcp') OR (\n id LIKE 'mcp-cg-%'\n AND account_id IS NULL\n AND provider_id IS NULL\n AND authorization_app_id IS NULL\n AND credential_group_enrollment_id IS NOT NULL\n AND credential_group_option_id IS NULL\n AND mcp_server_id IS NOT NULL\n AND managed_oauth_status IS NOT NULL\n AND (managed_oauth_status <> 'active' OR (\n encrypted_oauth_token_set IS NOT NULL\n AND mcp_tools IS NOT NULL\n ))\n AND granted_at IS NOT NULL\n AND managed_oauth_scope_version IS NULL\n AND granted_scopes IS NULL\n AND provider_metadata IS NULL\n AND created_by IS NULL\n AND env_key IS NULL\n AND env_owner_user_id IS NULL\n AND encrypted_service_account_key IS NULL\n AND unredacted = false\n )" + }, + "credential_creator_source_check": { + "name": "credential_creator_source_check", + "value": "(type::text = 'managed_mcp') OR created_by IS NOT NULL" + }, + "credential_workspace_env_source_check": { + "name": "credential_workspace_env_source_check", + "value": "(type <> 'env_workspace') OR (env_key IS NOT NULL AND env_owner_user_id IS NULL)" + }, + "credential_personal_env_source_check": { + "name": "credential_personal_env_source_check", + "value": "(type <> 'env_personal') OR (env_key IS NOT NULL AND env_owner_user_id IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.credential_group": { + "name": "credential_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "public_id": { + "name": "public_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "encrypted_provider_configuration": { + "name": "encrypted_provider_configuration", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "credential_group_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_organization_unique": { + "name": "credential_group_organization_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_public_id_unique": { + "name": "credential_group_public_id_unique", + "columns": [ + { + "expression": "public_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_workspace_unique": { + "name": "credential_group_workspace_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_workspace_id_workspace_id_fk": { + "name": "credential_group_workspace_id_workspace_id_fk", + "tableFrom": "credential_group", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_organization_id_organization_id_fk": { + "name": "credential_group_organization_id_organization_id_fk", + "tableFrom": "credential_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_created_by_user_id_fk": { + "name": "credential_group_created_by_user_id_fk", + "tableFrom": "credential_group", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_owner_check": { + "name": "credential_group_owner_check", + "value": "num_nonnulls(\"credential_group\".\"workspace_id\", \"credential_group\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.credential_group_enrollment": { + "name": "credential_group_enrollment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "credential_group_enrollment_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'invited'" + }, + "invitation_token_hash": { + "name": "invitation_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invitation_expires_at": { + "name": "invitation_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "invited_at": { + "name": "invited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_delivery_error": { + "name": "last_delivery_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_by_workflow_id": { + "name": "requested_by_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_enrollment_group_user_unique": { + "name": "credential_group_enrollment_group_user_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential_group_enrollment\".\"user_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_user_id_idx": { + "name": "credential_group_enrollment_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_email_unique": { + "name": "credential_group_enrollment_group_email_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_invitation_token_hash_unique": { + "name": "credential_group_enrollment_invitation_token_hash_unique", + "columns": [ + { + "expression": "invitation_token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_status_idx": { + "name": "credential_group_enrollment_group_status_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_invited_at_id_idx": { + "name": "credential_group_enrollment_group_invited_at_id_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "invited_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_enrollment_credential_group_id_credential_group_id_fk": { + "name": "credential_group_enrollment_credential_group_id_credential_group_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_enrollment_user_id_user_id_fk": { + "name": "credential_group_enrollment_user_id_user_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_enrollment_created_by_user_id_fk": { + "name": "credential_group_enrollment_created_by_user_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_enrollment_normalized_email_check": { + "name": "credential_group_enrollment_normalized_email_check", + "value": "\"credential_group_enrollment\".\"email\" = lower(btrim(\"credential_group_enrollment\".\"email\")) AND length(\"credential_group_enrollment\".\"email\") BETWEEN 3 AND 320" + }, + "credential_group_enrollment_invitation_token_hash_length_check": { + "name": "credential_group_enrollment_invitation_token_hash_length_check", + "value": "length(\"credential_group_enrollment\".\"invitation_token_hash\") = 64" + } + }, + "isRLSEnabled": false + }, + "public.credential_member": { + "name": "credential_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "credential_member_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "status": { + "name": "status", + "type": "credential_member_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "joined_at": { + "name": "joined_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_member_user_id_idx": { + "name": "credential_member_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_role_idx": { + "name": "credential_member_role_idx", + "columns": [ + { + "expression": "role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_status_idx": { + "name": "credential_member_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_unique": { + "name": "credential_member_unique", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_member_credential_id_credential_id_fk": { + "name": "credential_member_credential_id_credential_id_fk", + "tableFrom": "credential_member", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_member_user_id_user_id_fk": { + "name": "credential_member_user_id_user_id_fk", + "tableFrom": "credential_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_member_invited_by_user_id_fk": { + "name": "credential_member_invited_by_user_id_fk", + "tableFrom": "credential_member", + "tableTo": "user", + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_block": { + "name": "custom_block", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "icon_url": { + "name": "icon_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inputs": { + "name": "inputs", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "outputs": { + "name": "outputs", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "trace_child_runs": { + "name": "trace_child_runs", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "custom_block_workflow_id_idx": { + "name": "custom_block_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "custom_block_organization_type_unique": { + "name": "custom_block_organization_type_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "custom_block_organization_id_organization_id_fk": { + "name": "custom_block_organization_id_organization_id_fk", + "tableFrom": "custom_block", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_block_workflow_id_workflow_id_fk": { + "name": "custom_block_workflow_id_workflow_id_fk", + "tableFrom": "custom_block", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_block_created_by_user_id_fk": { + "name": "custom_block_created_by_user_id_fk", + "tableFrom": "custom_block", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_tools": { + "name": "custom_tools", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schema": { + "name": "schema", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "custom_tools_workspace_title_unique": { + "name": "custom_tools_workspace_title_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "custom_tools_workspace_id_workspace_id_fk": { + "name": "custom_tools_workspace_id_workspace_id_fk", + "tableFrom": "custom_tools", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_tools_user_id_user_id_fk": { + "name": "custom_tools_user_id_user_id_fk", + "tableFrom": "custom_tools", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.dashboard": { + "name": "dashboard", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "dashboard_workspace_id_unique": { + "name": "dashboard_workspace_id_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "dashboard_workspace_id_workspace_id_fk": { + "name": "dashboard_workspace_id_workspace_id_fk", + "tableFrom": "dashboard", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "dashboard_created_by_user_id_fk": { + "name": "dashboard_created_by_user_id_fk", + "tableFrom": "dashboard", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "dashboard_updated_by_user_id_fk": { + "name": "dashboard_updated_by_user_id_fk", + "tableFrom": "dashboard", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.data_drain_runs": { + "name": "data_drain_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "drain_id": { + "name": "drain_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "data_drain_run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "data_drain_run_trigger", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "rows_exported": { + "name": "rows_exported", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "bytes_written": { + "name": "bytes_written", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cursor_before": { + "name": "cursor_before", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cursor_after": { + "name": "cursor_after", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locators": { + "name": "locators", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": { + "data_drain_runs_drain_started_idx": { + "name": "data_drain_runs_drain_started_idx", + "columns": [ + { + "expression": "drain_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "data_drain_runs_drain_id_data_drains_id_fk": { + "name": "data_drain_runs_drain_id_data_drains_id_fk", + "tableFrom": "data_drain_runs", + "tableTo": "data_drains", + "columnsFrom": ["drain_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.data_drains": { + "name": "data_drains", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "data_drain_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "destination_type": { + "name": "destination_type", + "type": "data_drain_destination", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "destination_config": { + "name": "destination_config", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "destination_credentials": { + "name": "destination_credentials", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schedule_cadence": { + "name": "schedule_cadence", + "type": "data_drain_cadence", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_success_at": { + "name": "last_success_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "data_drains_due_idx": { + "name": "data_drains_due_idx", + "columns": [ + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "data_drains_org_name_unique": { + "name": "data_drains_org_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "data_drains_organization_id_organization_id_fk": { + "name": "data_drains_organization_id_organization_id_fk", + "tableFrom": "data_drains", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "data_drains_created_by_user_id_fk": { + "name": "data_drains_created_by_user_id_fk", + "tableFrom": "data_drains", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deleted_account_identity": { + "name": "deleted_account_identity", + "schema": "", + "columns": { + "identity_hash": { + "name": "identity_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "deleted_account_identity_expires_at_idx": { + "name": "deleted_account_identity_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.desktop_devices": { + "name": "desktop_devices", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_version": { + "name": "app_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "capabilities": { + "name": "capabilities", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "desktop_devices_user_id_idx": { + "name": "desktop_devices_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "desktop_devices_session_id_idx": { + "name": "desktop_devices_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "desktop_devices_user_id_user_id_fk": { + "name": "desktop_devices_user_id_user_id_fk", + "tableFrom": "desktop_devices", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "desktop_devices_session_id_session_id_fk": { + "name": "desktop_devices_session_id_session_id_fk", + "tableFrom": "desktop_devices", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.docs_embeddings": { + "name": "docs_embeddings", + "schema": "", + "columns": { + "chunk_id": { + "name": "chunk_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chunk_text": { + "name": "chunk_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_document": { + "name": "source_document", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_link": { + "name": "source_link", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "header_text": { + "name": "header_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "header_level": { + "name": "header_level", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": true + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "chunk_text_tsv": { + "name": "chunk_text_tsv", + "type": "tsvector", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "to_tsvector('english', \"docs_embeddings\".\"chunk_text\")", + "type": "stored" + } + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "docs_emb_source_document_idx": { + "name": "docs_emb_source_document_idx", + "columns": [ + { + "expression": "source_document", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_header_level_idx": { + "name": "docs_emb_header_level_idx", + "columns": [ + { + "expression": "header_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_source_header_idx": { + "name": "docs_emb_source_header_idx", + "columns": [ + { + "expression": "source_document", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "header_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_model_idx": { + "name": "docs_emb_model_idx", + "columns": [ + { + "expression": "embedding_model", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_created_at_idx": { + "name": "docs_emb_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_embedding_vector_hnsw_idx": { + "name": "docs_embedding_vector_hnsw_idx", + "columns": [ + { + "expression": "embedding", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "vector_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "docs_emb_metadata_gin_idx": { + "name": "docs_emb_metadata_gin_idx", + "columns": [ + { + "expression": "metadata", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "docs_emb_chunk_text_fts_idx": { + "name": "docs_emb_chunk_text_fts_idx", + "columns": [ + { + "expression": "chunk_text_tsv", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "docs_embedding_not_null_check": { + "name": "docs_embedding_not_null_check", + "value": "\"embedding\" IS NOT NULL" + }, + "docs_header_level_check": { + "name": "docs_header_level_check", + "value": "\"header_level\" >= 1 AND \"header_level\" <= 6" + } + }, + "isRLSEnabled": false + }, + "public.document": { + "name": "document", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_url": { + "name": "file_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file_size": { + "name": "file_size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "file_sha256": { + "name": "file_sha256", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "character_count": { + "name": "character_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "processing_status": { + "name": "processing_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "processing_attempts": { + "name": "processing_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "processing_queued_at": { + "name": "processing_queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_queue_token": { + "name": "processing_queue_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_started_at": { + "name": "processing_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_deferred_until": { + "name": "processing_deferred_until", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_completed_at": { + "name": "processing_completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_error": { + "name": "processing_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_recovery_after": { + "name": "processing_recovery_after", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "user_excluded": { + "name": "user_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "tag1": { + "name": "tag1", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag2": { + "name": "tag2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag3": { + "name": "tag3", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag4": { + "name": "tag4", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag5": { + "name": "tag5", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag6": { + "name": "tag6", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag7": { + "name": "tag7", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "number1": { + "name": "number1", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number2": { + "name": "number2", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number3": { + "name": "number3", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number4": { + "name": "number4", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number5": { + "name": "number5", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "date1": { + "name": "date1", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "date2": { + "name": "date2", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "boolean1": { + "name": "boolean1", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean2": { + "name": "boolean2", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean3": { + "name": "boolean3", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_url": { + "name": "source_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "acl": { + "name": "acl", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{ws}'::text[]" + }, + "acl_requirements": { + "name": "acl_requirements", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "acl_verified_at": { + "name": "acl_verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_modified_at": { + "name": "source_modified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_seen_at": { + "name": "source_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "doc_uploaded_by_idx": { + "name": "doc_uploaded_by_idx", + "columns": [ + { + "expression": "uploaded_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"uploaded_by\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_kb_source_modified_idx": { + "name": "doc_kb_source_modified_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_modified_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_acl_gin_idx": { + "name": "doc_acl_gin_idx", + "columns": [ + { + "expression": "acl", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "array_ops" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "gin", + "with": {} + }, + "doc_filename_idx": { + "name": "doc_filename_idx", + "columns": [ + { + "expression": "filename", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_processing_status_idx": { + "name": "doc_processing_status_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "processing_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_processing_recovery_idx": { + "name": "doc_connector_processing_recovery_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"processing_status\" IN ('pending', 'processing', 'failed') AND \"document\".\"connector_id\" IS NOT NULL AND \"document\".\"content_hash\" IS NOT NULL AND \"document\".\"storage_key\" IS NOT NULL AND \"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_connector_processing_status_idx": { + "name": "doc_connector_processing_status_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "processing_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"processing_status\" IN ('pending', 'processing', 'failed') AND \"document\".\"connector_id\" IS NOT NULL AND \"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_external_id_idx": { + "name": "doc_connector_external_id_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_source_lookup_idx": { + "name": "doc_connector_source_lookup_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_reconciliation_v2_idx": { + "name": "doc_connector_reconciliation_v2_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_active_kb_token_count_idx": { + "name": "doc_active_kb_token_count_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "token_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_storage_key_idx": { + "name": "doc_storage_key_idx", + "columns": [ + { + "expression": "storage_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"storage_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_archived_at_partial_idx": { + "name": "doc_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_deleted_at_partial_idx": { + "name": "doc_deleted_at_partial_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_tombstone_idx": { + "name": "doc_connector_tombstone_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"archived_at\" IS NULL AND (\"document\".\"deleted_at\" IS NOT NULL OR \"document\".\"content_hash\" IS NULL)", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_live_idx": { + "name": "doc_connector_live_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag1_lower_idx": { + "name": "doc_kb_tag1_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag1\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag2_lower_idx": { + "name": "doc_kb_tag2_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag2\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag3_lower_idx": { + "name": "doc_kb_tag3_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag3\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag4_lower_idx": { + "name": "doc_kb_tag4_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag4\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag5_lower_idx": { + "name": "doc_kb_tag5_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag5\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag6_lower_idx": { + "name": "doc_kb_tag6_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag6\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag7_lower_idx": { + "name": "doc_kb_tag7_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag7\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number1_idx": { + "name": "doc_number1_idx", + "columns": [ + { + "expression": "number1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number2_idx": { + "name": "doc_number2_idx", + "columns": [ + { + "expression": "number2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number3_idx": { + "name": "doc_number3_idx", + "columns": [ + { + "expression": "number3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number4_idx": { + "name": "doc_number4_idx", + "columns": [ + { + "expression": "number4", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number5_idx": { + "name": "doc_number5_idx", + "columns": [ + { + "expression": "number5", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_date1_idx": { + "name": "doc_date1_idx", + "columns": [ + { + "expression": "date1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_date2_idx": { + "name": "doc_date2_idx", + "columns": [ + { + "expression": "date2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_boolean1_idx": { + "name": "doc_boolean1_idx", + "columns": [ + { + "expression": "boolean1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_boolean2_idx": { + "name": "doc_boolean2_idx", + "columns": [ + { + "expression": "boolean2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_boolean3_idx": { + "name": "doc_boolean3_idx", + "columns": [ + { + "expression": "boolean3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "document_knowledge_base_id_knowledge_base_id_fk": { + "name": "document_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "document", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "document_connector_id_knowledge_connector_id_fk": { + "name": "document_connector_id_knowledge_connector_id_fk", + "tableFrom": "document", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "document_uploaded_by_user_id_fk": { + "name": "document_uploaded_by_user_id_fk", + "tableFrom": "document", + "tableTo": "user", + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "doc_acl_token_shape_check": { + "name": "doc_acl_token_shape_check", + "value": "array_position(\"document\".\"acl\", NULL) IS NULL AND (cardinality(\"document\".\"acl\") = 0 OR (cardinality(\"document\".\"acl\") = array_length(string_to_array(array_to_string(\"document\".\"acl\", E'\\n'), E'\\n'), 1) AND array_to_string(\"document\".\"acl\", E'\\n') ~ '^((ws|pub|link|u:[^\\nA-Z]+@[^\\nA-Z]+|[gs]:[^\\n:]+:[^\\n:]+:[^\\n]+)(\\n(ws|pub|link|u:[^\\nA-Z]+@[^\\nA-Z]+|[gs]:[^\\n:]+:[^\\n:]+:[^\\n]+))*)$'))" + } + }, + "isRLSEnabled": false + }, + "public.document_secret_provenance": { + "name": "document_secret_provenance", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "document_secret_provenance_document_id_document_id_fk": { + "name": "document_secret_provenance_document_id_document_id_fk", + "tableFrom": "document_secret_provenance", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "document_secret_provenance_status_check": { + "name": "document_secret_provenance_status_check", + "value": "\"document_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.embedding": { + "name": "embedding", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chunk_index": { + "name": "chunk_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "chunk_hash": { + "name": "chunk_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "content_length": { + "name": "content_length", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "embedding_384": { + "name": "embedding_384", + "type": "vector(384)", + "primaryKey": false, + "notNull": false + }, + "embedding_768": { + "name": "embedding_768", + "type": "vector(768)", + "primaryKey": false, + "notNull": false + }, + "embedding_1024": { + "name": "embedding_1024", + "type": "vector(1024)", + "primaryKey": false, + "notNull": false + }, + "embedding_3072": { + "name": "embedding_3072", + "type": "vector(3072)", + "primaryKey": false, + "notNull": false + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "start_offset": { + "name": "start_offset", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "end_offset": { + "name": "end_offset", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "tag1": { + "name": "tag1", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag2": { + "name": "tag2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag3": { + "name": "tag3", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag4": { + "name": "tag4", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag5": { + "name": "tag5", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag6": { + "name": "tag6", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag7": { + "name": "tag7", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "number1": { + "name": "number1", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number2": { + "name": "number2", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number3": { + "name": "number3", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number4": { + "name": "number4", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number5": { + "name": "number5", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "date1": { + "name": "date1", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "date2": { + "name": "date2", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "boolean1": { + "name": "boolean1", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean2": { + "name": "boolean2", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean3": { + "name": "boolean3", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "content_tsv": { + "name": "content_tsv", + "type": "tsvector", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "to_tsvector('english', \"embedding\".\"content\")", + "type": "stored" + } + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "emb_doc_chunk_idx": { + "name": "emb_doc_chunk_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chunk_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_model_idx": { + "name": "emb_kb_model_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "embedding_model", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_enabled_idx": { + "name": "emb_kb_enabled_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_doc_enabled_idx": { + "name": "emb_doc_enabled_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag1_lower_idx": { + "name": "emb_kb_tag1_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag1\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag2_lower_idx": { + "name": "emb_kb_tag2_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag2\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag3_lower_idx": { + "name": "emb_kb_tag3_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag3\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag4_lower_idx": { + "name": "emb_kb_tag4_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag4\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag5_lower_idx": { + "name": "emb_kb_tag5_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag5\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag6_lower_idx": { + "name": "emb_kb_tag6_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag6\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag7_lower_idx": { + "name": "emb_kb_tag7_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag7\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number1_idx": { + "name": "emb_number1_idx", + "columns": [ + { + "expression": "number1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number2_idx": { + "name": "emb_number2_idx", + "columns": [ + { + "expression": "number2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number3_idx": { + "name": "emb_number3_idx", + "columns": [ + { + "expression": "number3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number4_idx": { + "name": "emb_number4_idx", + "columns": [ + { + "expression": "number4", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number5_idx": { + "name": "emb_number5_idx", + "columns": [ + { + "expression": "number5", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_date1_idx": { + "name": "emb_date1_idx", + "columns": [ + { + "expression": "date1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "emb_date2_idx": { + "name": "emb_date2_idx", + "columns": [ + { + "expression": "date2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "emb_boolean1_idx": { + "name": "emb_boolean1_idx", + "columns": [ + { + "expression": "boolean1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_boolean2_idx": { + "name": "emb_boolean2_idx", + "columns": [ + { + "expression": "boolean2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_boolean3_idx": { + "name": "emb_boolean3_idx", + "columns": [ + { + "expression": "boolean3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_content_fts_idx": { + "name": "emb_content_fts_idx", + "columns": [ + { + "expression": "content_tsv", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": { + "fastupdate": "off" + } + } + }, + "foreignKeys": { + "embedding_knowledge_base_id_knowledge_base_id_fk": { + "name": "embedding_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "embedding", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "embedding_document_id_document_id_fk": { + "name": "embedding_document_id_document_id_fk", + "tableFrom": "embedding", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_width_check": { + "name": "embedding_width_check", + "value": "num_nonnulls(\"embedding\", \"embedding_384\", \"embedding_768\", \"embedding_1024\", \"embedding_3072\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.embedding_search": { + "name": "embedding_search", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "acl": { + "name": "acl", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "binary": { + "name": "binary", + "type": "bit(1536)", + "primaryKey": false, + "notNull": false + }, + "binary_384": { + "name": "binary_384", + "type": "bit(384)", + "primaryKey": false, + "notNull": false + }, + "binary_768": { + "name": "binary_768", + "type": "bit(768)", + "primaryKey": false, + "notNull": false + }, + "binary_1024": { + "name": "binary_1024", + "type": "bit(1024)", + "primaryKey": false, + "notNull": false + }, + "binary_3072": { + "name": "binary_3072", + "type": "bit(3072)", + "primaryKey": false, + "notNull": false + }, + "vector": { + "name": "vector", + "type": "halfvec(1536)", + "primaryKey": false, + "notNull": false + }, + "vector_384": { + "name": "vector_384", + "type": "halfvec(384)", + "primaryKey": false, + "notNull": false + }, + "vector_512": { + "name": "vector_512", + "type": "halfvec(512)", + "primaryKey": false, + "notNull": false + }, + "vector_768": { + "name": "vector_768", + "type": "halfvec(768)", + "primaryKey": false, + "notNull": false + }, + "vector_1024": { + "name": "vector_1024", + "type": "halfvec(1024)", + "primaryKey": false, + "notNull": false + }, + "vector_3072": { + "name": "vector_3072", + "type": "halfvec(3072)", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "embedding_search_kb_idx": { + "name": "embedding_search_kb_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "embedding_search_document_lookup_idx": { + "name": "embedding_search_document_lookup_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"embedding_search\".\"enabled\"", + "concurrently": true, + "method": "btree", + "with": {} + }, + "embedding_search_cosine_hnsw_idx": { + "name": "embedding_search_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_512_cosine_hnsw_idx": { + "name": "embedding_search_512_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_512", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_384_cosine_hnsw_idx": { + "name": "embedding_search_384_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_384", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_768_cosine_hnsw_idx": { + "name": "embedding_search_768_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_768", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_1024_cosine_hnsw_idx": { + "name": "embedding_search_1024_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_1024", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_3072_cosine_hnsw_idx": { + "name": "embedding_search_3072_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_3072", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + } + }, + "foreignKeys": { + "embedding_search_id_embedding_id_fk": { + "name": "embedding_search_id_embedding_id_fk", + "tableFrom": "embedding_search", + "tableTo": "embedding", + "columnsFrom": ["id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_search_width_check": { + "name": "embedding_search_width_check", + "value": "num_nonnulls(\"binary\", \"binary_384\", \"binary_768\", \"binary_1024\", \"binary_3072\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.embedding_secret_provenance": { + "name": "embedding_secret_provenance", + "schema": "", + "columns": { + "embedding_id": { + "name": "embedding_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "embedding_secret_provenance_embedding_id_embedding_id_fk": { + "name": "embedding_secret_provenance_embedding_id_embedding_id_fk", + "tableFrom": "embedding_secret_provenance", + "tableTo": "embedding", + "columnsFrom": ["embedding_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_secret_provenance_status_check": { + "name": "embedding_secret_provenance_status_check", + "value": "\"embedding_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.enterprise_seat_true_up": { + "name": "enterprise_seat_true_up", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "subscription_id": { + "name": "subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "window_start": { + "name": "window_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "window_end": { + "name": "window_end", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "peak_extra_seats": { + "name": "peak_extra_seats", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "seat_price_cents": { + "name": "seat_price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "amount_cents": { + "name": "amount_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "billed_at": { + "name": "billed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "enterprise_seat_true_up_subscription_window_unique": { + "name": "enterprise_seat_true_up_subscription_window_unique", + "columns": [ + { + "expression": "subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "window_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "enterprise_seat_true_up_organization_id_idx": { + "name": "enterprise_seat_true_up_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "enterprise_seat_true_up_unbilled_idx": { + "name": "enterprise_seat_true_up_unbilled_idx", + "columns": [ + { + "expression": "window_end", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "billed_at IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "enterprise_seat_true_up_subscription_id_subscription_id_fk": { + "name": "enterprise_seat_true_up_subscription_id_subscription_id_fk", + "tableFrom": "enterprise_seat_true_up", + "tableTo": "subscription", + "columnsFrom": ["subscription_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "enterprise_seat_true_up_organization_id_organization_id_fk": { + "name": "enterprise_seat_true_up_organization_id_organization_id_fk", + "tableFrom": "enterprise_seat_true_up", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.environment": { + "name": "environment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "environment_user_id_user_id_fk": { + "name": "environment_user_id_user_id_fk", + "tableFrom": "environment", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "environment_user_id_unique": { + "name": "environment_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_value_dependencies": { + "name": "execution_large_value_dependencies", + "schema": "", + "columns": { + "parent_key": { + "name": "parent_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_key": { + "name": "child_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "execution_large_value_dependencies_workspace_parent_key_idx": { + "name": "execution_large_value_dependencies_workspace_parent_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_value_dependencies_workspace_child_key_idx": { + "name": "execution_large_value_dependencies_workspace_child_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_value_dependencies_workspace_id_workspace_id_fk": { + "name": "execution_large_value_dependencies_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_value_dependencies", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "execution_large_value_dependencies_parent_key_child_key_pk": { + "name": "execution_large_value_dependencies_parent_key_child_key_pk", + "columns": ["parent_key", "child_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_value_references": { + "name": "execution_large_value_references", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "execution_large_value_reference_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "execution_large_value_references_workspace_execution_source_idx": { + "name": "execution_large_value_references_workspace_execution_source_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_value_references_workflow_id_idx": { + "name": "execution_large_value_references_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_value_references_workspace_id_workspace_id_fk": { + "name": "execution_large_value_references_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_value_references", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_large_value_references_workflow_id_workflow_id_fk": { + "name": "execution_large_value_references_workflow_id_workflow_id_fk", + "tableFrom": "execution_large_value_references", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "execution_large_value_references_key_execution_id_source_pk": { + "name": "execution_large_value_references_key_execution_id_source_pk", + "columns": ["key", "execution_id", "source"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_values": { + "name": "execution_large_values", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_execution_id": { + "name": "owner_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "execution_large_values_owner_execution_id_idx": { + "name": "execution_large_values_owner_execution_id_idx", + "columns": [ + { + "expression": "owner_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_cleanup_idx": { + "name": "execution_large_values_cleanup_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"execution_large_values\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_tombstone_cleanup_idx": { + "name": "execution_large_values_tombstone_cleanup_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"execution_large_values\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_workflow_id_idx": { + "name": "execution_large_values_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_workspace_id_idx": { + "name": "execution_large_values_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_values_workspace_id_workspace_id_fk": { + "name": "execution_large_values_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_values", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_large_values_workflow_id_workflow_id_fk": { + "name": "execution_large_values_workflow_id_workflow_id_fk", + "tableFrom": "execution_large_values", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.file_search_dependency": { + "name": "file_search_dependency", + "schema": "", + "columns": { + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "file_search_dependency_file_idx": { + "name": "file_search_dependency_file_idx", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "file_search_dependency_owner_idx": { + "name": "file_search_dependency_owner_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "file_search_dependency_build_id_workspace_file_search_build_id_fk": { + "name": "file_search_dependency_build_id_workspace_file_search_build_id_fk", + "tableFrom": "file_search_dependency", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "file_search_dependency_build_id_file_id_pk": { + "name": "file_search_dependency_build_id_file_id_pk", + "columns": ["build_id", "file_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.file_search_dispatch_queue": { + "name": "file_search_dispatch_queue", + "schema": "", + "columns": { + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enqueued_at": { + "name": "enqueued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_dispatched_at": { + "name": "last_dispatched_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "file_search_dispatch_schedule_idx": { + "name": "file_search_dispatch_schedule_idx", + "columns": [ + { + "expression": "last_dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "first" + }, + { + "expression": "enqueued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "file_search_dispatch_queue_entity_type_entity_id_pk": { + "name": "file_search_dispatch_queue_entity_type_entity_id_pk", + "columns": ["entity_type", "entity_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_dispatch_owner_check": { + "name": "file_search_dispatch_owner_check", + "value": "\"file_search_dispatch_queue\".\"entity_type\" IN ('workspace', 'project') AND length(\"file_search_dispatch_queue\".\"entity_id\") > 0" + } + }, + "isRLSEnabled": false + }, + "public.folder": { + "name": "folder", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_type": { + "name": "resource_type", + "type": "folder_resource_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parent_id": { + "name": "parent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "folder_project_id_idx": { + "name": "folder_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "folder_project_resource_parent_name_active_unique": { + "name": "folder_project_resource_parent_name_active_unique", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"parent_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"folder\".\"deleted_at\" IS NULL AND \"folder\".\"project_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "folder_user_idx": { + "name": "folder_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_resource_parent_idx": { + "name": "folder_workspace_resource_parent_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_parent_sort_idx": { + "name": "folder_parent_sort_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_deleted_at_idx": { + "name": "folder_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_deleted_partial_idx": { + "name": "folder_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"folder\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_resource_parent_name_active_unique": { + "name": "folder_workspace_resource_parent_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"parent_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"folder\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "folder_project_id_project_id_fk": { + "name": "folder_project_id_project_id_fk", + "tableFrom": "folder", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "folder_user_id_user_id_fk": { + "name": "folder_user_id_user_id_fk", + "tableFrom": "folder", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "folder_workspace_id_workspace_id_fk": { + "name": "folder_workspace_id_workspace_id_fk", + "tableFrom": "folder", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "folder_parent_id_folder_id_fk": { + "name": "folder_parent_id_folder_id_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "folder_workspace_parent_owner_fk": { + "name": "folder_workspace_parent_owner_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id", "workspace_id", "resource_type"], + "columnsTo": ["id", "workspace_id", "resource_type"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "folder_project_parent_owner_fk": { + "name": "folder_project_parent_owner_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id", "project_id", "resource_type"], + "columnsTo": ["id", "project_id", "resource_type"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "folder_workspace_owner_type_unique": { + "name": "folder_workspace_owner_type_unique", + "nullsNotDistinct": false, + "columns": ["id", "workspace_id", "resource_type"] + }, + "folder_project_owner_type_unique": { + "name": "folder_project_owner_type_unique", + "nullsNotDistinct": false, + "columns": ["id", "project_id", "resource_type"] + } + }, + "policies": {}, + "checkConstraints": { + "folder_owner_check": { + "name": "folder_owner_check", + "value": "num_nonnulls(\"folder\".\"workspace_id\", \"folder\".\"project_id\") = 1 AND (\"folder\".\"project_id\" IS NULL OR \"folder\".\"resource_type\" = 'file')" + } + }, + "isRLSEnabled": false + }, + "public.idempotency_key": { + "name": "idempotency_key", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "result": { + "name": "result", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idempotency_key_created_at_idx": { + "name": "idempotency_key_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitation": { + "name": "invitation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "invitation_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'organization'" + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "inviter_id": { + "name": "inviter_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "membership_intent": { + "name": "membership_intent", + "type": "invitation_membership_intent", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'internal'" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "invitation_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "invitation_email_idx": { + "name": "invitation_email_idx", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_organization_id_idx": { + "name": "invitation_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_status_idx": { + "name": "invitation_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_pending_email_org_unique": { + "name": "invitation_pending_email_org_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"invitation\".\"status\" = 'pending' AND \"invitation\".\"organization_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitation_inviter_id_user_id_fk": { + "name": "invitation_inviter_id_user_id_fk", + "tableFrom": "invitation", + "tableTo": "user", + "columnsFrom": ["inviter_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_organization_id_organization_id_fk": { + "name": "invitation_organization_id_organization_id_fk", + "tableFrom": "invitation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "invitation_token_unique": { + "name": "invitation_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitation_workspace_grant": { + "name": "invitation_workspace_grant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "invitation_id": { + "name": "invitation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "invitation_workspace_grant_unique": { + "name": "invitation_workspace_grant_unique", + "columns": [ + { + "expression": "invitation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_workspace_grant_workspace_id_idx": { + "name": "invitation_workspace_grant_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitation_workspace_grant_invitation_id_invitation_id_fk": { + "name": "invitation_workspace_grant_invitation_id_invitation_id_fk", + "tableFrom": "invitation_workspace_grant", + "tableTo": "invitation", + "columnsFrom": ["invitation_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_workspace_grant_workspace_id_workspace_id_fk": { + "name": "invitation_workspace_grant_workspace_id_workspace_id_fk", + "tableFrom": "invitation_workspace_grant", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.job_execution_logs": { + "name": "job_execution_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "schedule_id": { + "name": "schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_duration_ms": { + "name": "total_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "execution_data": { + "name": "execution_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "cost": { + "name": "cost", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "occurrence_at": { + "name": "occurrence_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_request_id": { + "name": "billing_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "job_execution_logs_schedule_occurrence_unique": { + "name": "job_execution_logs_schedule_occurrence_unique", + "columns": [ + { + "expression": "schedule_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "occurrence_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_billing_request_unique": { + "name": "job_execution_logs_billing_request_unique", + "columns": [ + { + "expression": "billing_request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"job_execution_logs\".\"billing_request_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_open_idx": { + "name": "job_execution_logs_open_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"job_execution_logs\".\"status\" IN ('queued', 'running')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_workspace_started_at_idx": { + "name": "job_execution_logs_workspace_started_at_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_workspace_ended_at_id_idx": { + "name": "job_execution_logs_workspace_ended_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"ended_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_execution_id_unique": { + "name": "job_execution_logs_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_trigger_idx": { + "name": "job_execution_logs_trigger_idx", + "columns": [ + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "job_execution_logs_schedule_id_workflow_schedule_id_fk": { + "name": "job_execution_logs_schedule_id_workflow_schedule_id_fk", + "tableFrom": "job_execution_logs", + "tableTo": "workflow_schedule", + "columnsFrom": ["schedule_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "job_execution_logs_workspace_id_workspace_id_fk": { + "name": "job_execution_logs_workspace_id_workspace_id_fk", + "tableFrom": "job_execution_logs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_base": { + "name": "knowledge_base", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_search_index": { + "name": "is_search_index", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "embedding_dimension": { + "name": "embedding_dimension", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1536 + }, + "chunking_config": { + "name": "chunking_config", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{\"maxSize\": 1024, \"minSize\": 1, \"overlap\": 200}'" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kb_organization_id_idx": { + "name": "kb_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_organization_search_index_unique": { + "name": "kb_organization_search_index_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"is_search_index\" = true AND \"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_organization_name_active_unique": { + "name": "kb_organization_name_active_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_id_idx": { + "name": "kb_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_user_workspace_idx": { + "name": "kb_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_folder_id_idx": { + "name": "kb_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_deleted_at_idx": { + "name": "kb_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_deleted_partial_idx": { + "name": "kb_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_base\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_name_active_unique": { + "name": "kb_workspace_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_search_index_unique": { + "name": "kb_workspace_search_index_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"is_search_index\" = true AND \"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_user_id_user_id_fk": { + "name": "knowledge_base_user_id_user_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_workspace_id_workspace_id_fk": { + "name": "knowledge_base_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_organization_id_organization_id_fk": { + "name": "knowledge_base_organization_id_organization_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_folder_id_folder_id_fk": { + "name": "knowledge_base_folder_id_folder_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kb_owner_check": { + "name": "kb_owner_check", + "value": "num_nonnulls(\"knowledge_base\".\"workspace_id\", \"knowledge_base\".\"organization_id\") = 1" + }, + "kb_organization_search_index_check": { + "name": "kb_organization_search_index_check", + "value": "\"knowledge_base\".\"organization_id\" IS NULL OR \"knowledge_base\".\"is_search_index\"" + }, + "kb_organization_folder_check": { + "name": "kb_organization_folder_check", + "value": "\"knowledge_base\".\"organization_id\" IS NULL OR \"knowledge_base\".\"folder_id\" IS NULL" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_base_import": { + "name": "knowledge_base_import", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_key": { + "name": "source_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "documents_total": { + "name": "documents_total", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "documents_imported": { + "name": "documents_imported", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "documents_failed": { + "name": "documents_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "vectors_reused": { + "name": "vectors_reused", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "failures": { + "name": "failures", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "knowledge_base_import_watchdog_idx": { + "name": "knowledge_base_import_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "knowledge_base_import_knowledge_base_id_idx": { + "name": "knowledge_base_import_knowledge_base_id_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_import_workspace_id_workspace_id_fk": { + "name": "knowledge_base_import_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_base_import", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_import_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_base_import_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_base_import", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_base_tag_definitions": { + "name": "knowledge_base_tag_definitions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tag_slot": { + "name": "tag_slot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "field_type": { + "name": "field_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kb_tag_definitions_kb_slot_idx": { + "name": "kb_tag_definitions_kb_slot_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tag_slot", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_tag_definitions_kb_display_name_idx": { + "name": "kb_tag_definitions_kb_display_name_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_tag_definitions_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_base_tag_definitions_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_base_tag_definitions", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector": { + "name": "knowledge_connector", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_config": { + "name": "source_config", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "sync_mode": { + "name": "sync_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'full'" + }, + "sync_interval_minutes": { + "name": "sync_interval_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1440 + }, + "access_mode": { + "name": "access_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'workspace'" + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_option_id": { + "name": "credential_group_option_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_status": { + "name": "member_sync_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'idle'" + }, + "member_sync_lock_token": { + "name": "member_sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_lock_lease_at": { + "name": "member_sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "next_member_sync_at": { + "name": "next_member_sync_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": false + }, + "last_member_sync_at": { + "name": "last_member_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_member_sync_error": { + "name": "last_member_sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_consecutive_failures": { + "name": "member_sync_consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "access_rewrite_pending": { + "name": "access_rewrite_pending", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image_removal_pending": { + "name": "image_removal_pending", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "member_tombstone_cursor": { + "name": "member_tombstone_cursor", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "member_resurrection_cursor": { + "name": "member_resurrection_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "last_sync_at": { + "name": "last_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_sync_error": { + "name": "last_sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_sync_doc_count": { + "name": "last_sync_doc_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "listing_checkpoint": { + "name": "listing_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "directory_checkpoint": { + "name": "directory_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "next_sync_at": { + "name": "next_sync_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": false + }, + "next_directory_sync_at": { + "name": "next_directory_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "sync_lock_token": { + "name": "sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_lock_lease_at": { + "name": "sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "detached_at": { + "name": "detached_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "detach_reserved_bytes": { + "name": "detach_reserved_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "kc_knowledge_base_id_idx": { + "name": "kc_knowledge_base_id_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_status_next_sync_idx": { + "name": "kc_status_next_sync_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_archived_at_partial_idx": { + "name": "kc_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_deleted_at_partial_idx": { + "name": "kc_deleted_at_partial_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_member_sync_due_idx": { + "name": "kc_member_sync_due_idx", + "columns": [ + { + "expression": "member_sync_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_member_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"access_mode\" = 'members' AND \"knowledge_connector\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_directory_sync_due_idx": { + "name": "kc_directory_sync_due_idx", + "columns": [ + { + "expression": "next_directory_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"access_mode\" = 'admin' AND \"knowledge_connector\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_connector_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_connector", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_credential_group_id_credential_group_id_fk": { + "name": "knowledge_connector_credential_group_id_credential_group_id_fk", + "tableFrom": "knowledge_connector", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kc_access_mode_check": { + "name": "kc_access_mode_check", + "value": "\"knowledge_connector\".\"access_mode\" IN ('workspace', 'members', 'admin')" + }, + "kc_member_sync_status_check": { + "name": "kc_member_sync_status_check", + "value": "\"knowledge_connector\".\"member_sync_status\" IN ('idle', 'pending', 'running', 'error', 'disabled')" + }, + "kc_sync_lock_exclusive_check": { + "name": "kc_sync_lock_exclusive_check", + "value": "NOT (\"knowledge_connector\".\"sync_lock_token\" IS NOT NULL AND \"knowledge_connector\".\"member_sync_lock_token\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_member": { + "name": "knowledge_connector_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_started_at": { + "name": "last_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_complete_listing_at": { + "name": "last_complete_listing_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_listed_count": { + "name": "last_listed_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_synced_through": { + "name": "member_synced_through", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope_renewed_at": { + "name": "scope_renewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope_renewal_cursor": { + "name": "scope_renewal_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope_renewal_started_at": { + "name": "scope_renewal_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "change_cursor": { + "name": "change_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "listing_checkpoint": { + "name": "listing_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kcm_organization_id_idx": { + "name": "kcm_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_connector_credential_unique": { + "name": "kcm_connector_credential_unique", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_connector_queue_idx": { + "name": "kcm_connector_queue_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "first" + }, + { + "expression": "last_started_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_credential_idx": { + "name": "kcm_credential_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_member_workspace_id_workspace_id_fk": { + "name": "knowledge_connector_member_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_organization_id_organization_id_fk": { + "name": "knowledge_connector_member_organization_id_organization_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_member_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_credential_id_credential_id_fk": { + "name": "knowledge_connector_member_credential_id_credential_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcm_owner_check": { + "name": "kcm_owner_check", + "value": "num_nonnulls(\"knowledge_connector_member\".\"workspace_id\", \"knowledge_connector_member\".\"organization_id\") = 1" + }, + "kcm_status_check": { + "name": "kcm_status_check", + "value": "\"knowledge_connector_member\".\"status\" IN ('active', 'suspended', 'disabled')" + }, + "kcm_subject_token_shape_check": { + "name": "kcm_subject_token_shape_check", + "value": "\"knowledge_connector_member\".\"subject_token\" ~ '^s:[^:]+:[^:]+:.+$'" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_member_sync_log": { + "name": "knowledge_connector_member_sync_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "members_claimed": { + "name": "members_claimed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_completed": { + "name": "members_completed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_incomplete": { + "name": "members_incomplete", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_failed": { + "name": "members_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_failed": { + "name": "docs_failed", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "processing_dispatch_failed": { + "name": "processing_dispatch_failed", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "docs_listed": { + "name": "docs_listed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_added": { + "name": "docs_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_updated": { + "name": "docs_updated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_unchanged": { + "name": "docs_unchanged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_hydrated_once": { + "name": "docs_hydrated_once", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_added": { + "name": "observations_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_renewed": { + "name": "observations_renewed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_removed": { + "name": "observations_removed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_tombstoned": { + "name": "docs_tombstoned", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_resurrected": { + "name": "docs_resurrected", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_purged": { + "name": "docs_purged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "credentials_audited": { + "name": "credentials_audited", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "database_failure_class": { + "name": "database_failure_class", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcmsl_connector_started_at_idx": { + "name": "kcmsl_connector_started_at_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcmsl_started_at_partial_idx": { + "name": "kcmsl_started_at_partial_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_member_sync_log\".\"status\" = 'started'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_member_sync_log_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_member_sync_log_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_member_sync_log", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcmsl_status_check": { + "name": "kcmsl_status_check", + "value": "\"knowledge_connector_member_sync_log\".\"status\" IN ('started', 'partial', 'completed', 'failed')" + }, + "kcmsl_database_failure_class_check": { + "name": "kcmsl_database_failure_class_check", + "value": "\"knowledge_connector_member_sync_log\".\"database_failure_class\" IN ('capacity', 'conflict', 'connection')" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_partition": { + "name": "knowledge_connector_partition", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "partition_key": { + "name": "partition_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation_id": { + "name": "generation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context": { + "name": "context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "retry_at": { + "name": "retry_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "permission_cursor": { + "name": "permission_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_attempts": { + "name": "permission_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "permission_retry_at": { + "name": "permission_retry_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "permission_last_served_at": { + "name": "permission_last_served_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_started_at": { + "name": "permission_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_failure": { + "name": "permission_failure", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcp_content_due_idx": { + "name": "kcp_content_due_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "retry_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_served_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcp_permission_due_idx": { + "name": "kcp_permission_due_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_retry_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_last_served_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_partition_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_partition_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_partition", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcp_pk": { + "name": "kcp_pk", + "columns": ["connector_id", "partition_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcp_partition_key_check": { + "name": "kcp_partition_key_check", + "value": "octet_length(\"knowledge_connector_partition\".\"partition_key\") BETWEEN 1 AND 1024" + }, + "kcp_context_check": { + "name": "kcp_context_check", + "value": "jsonb_typeof(\"knowledge_connector_partition\".\"context\") = 'object' AND octet_length(\"knowledge_connector_partition\".\"context\"::text) <= 16384" + }, + "kcp_status_check": { + "name": "kcp_status_check", + "value": "\"knowledge_connector_partition\".\"status\" IN ('pending', 'complete', 'blocked')" + }, + "kcp_cursor_check": { + "name": "kcp_cursor_check", + "value": "(\"knowledge_connector_partition\".\"cursor\" IS NULL OR octet_length(\"knowledge_connector_partition\".\"cursor\") <= 393216) AND (\"knowledge_connector_partition\".\"permission_cursor\" IS NULL OR octet_length(\"knowledge_connector_partition\".\"permission_cursor\") <= 393216)" + }, + "kcp_attempts_check": { + "name": "kcp_attempts_check", + "value": "\"knowledge_connector_partition\".\"attempts\" >= 0 AND \"knowledge_connector_partition\".\"permission_attempts\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_grant": { + "name": "knowledge_connector_permission_grant", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_key": { + "name": "group_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpg_subject_idx": { + "name": "kcpg_subject_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "kcpg_snapshot_fk": { + "name": "kcpg_snapshot_fk", + "tableFrom": "knowledge_connector_permission_grant", + "tableTo": "knowledge_connector_permission_snapshot", + "columnsFrom": ["connector_id"], + "columnsTo": ["connector_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpg_pk": { + "name": "kcpg_pk", + "columns": ["connector_id", "group_key", "subject_token"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcpg_group_check": { + "name": "kcpg_group_check", + "value": "length(\"knowledge_connector_permission_grant\".\"group_key\") BETWEEN 1 AND 255" + }, + "kcpg_subject_check": { + "name": "kcpg_subject_check", + "value": "\"knowledge_connector_permission_grant\".\"subject_token\" ~ '^u:[^[:space:]A-Z]+@[^[:space:]A-Z]+$'" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import": { + "name": "knowledge_connector_permission_import", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_binding": { + "name": "credential_binding", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expected_revision": { + "name": "expected_revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "manifest": { + "name": "manifest", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "part_digests": { + "name": "part_digests", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "user_rows": { + "name": "user_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "project_rows": { + "name": "project_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "completed_revision": { + "name": "completed_revision", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpi_connector_idx": { + "name": "kcpi_connector_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcpi_expires_idx": { + "name": "kcpi_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_permission_import_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_permission_import", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcpi_revision_check": { + "name": "kcpi_revision_check", + "value": "\"knowledge_connector_permission_import\".\"expected_revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import_grant": { + "name": "knowledge_connector_permission_import_grant", + "schema": "", + "columns": { + "import_id": { + "name": "import_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_path": { + "name": "project_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_key": { + "name": "group_key", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcpig_subject_idx": { + "name": "kcpig_subject_idx", + "columns": [ + { + "expression": "import_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_grant_import_id_knowledge_connector_permission_import_id_fk": { + "name": "knowledge_connector_permission_import_grant_import_id_knowledge_connector_permission_import_id_fk", + "tableFrom": "knowledge_connector_permission_import_grant", + "tableTo": "knowledge_connector_permission_import", + "columnsFrom": ["import_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpig_pk": { + "name": "kcpig_pk", + "columns": ["import_id", "project_path", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import_identity": { + "name": "knowledge_connector_permission_import_identity", + "schema": "", + "columns": { + "import_id": { + "name": "import_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpii_subject_import_idx": { + "name": "kcpii_subject_import_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "import_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_identity_import_id_knowledge_connector_permission_import_id_fk": { + "name": "knowledge_connector_permission_import_identity_import_id_knowledge_connector_permission_import_id_fk", + "tableFrom": "knowledge_connector_permission_import_identity", + "tableTo": "knowledge_connector_permission_import", + "columnsFrom": ["import_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpii_pk": { + "name": "kcpii_pk", + "columns": ["import_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_snapshot": { + "name": "knowledge_connector_permission_snapshot", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "kcps_connector_fk": { + "name": "kcps_connector_fk", + "tableFrom": "knowledge_connector_permission_snapshot", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcps_revision_check": { + "name": "kcps_revision_check", + "value": "\"knowledge_connector_permission_snapshot\".\"revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_sync_log": { + "name": "knowledge_connector_sync_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "docs_added": { + "name": "docs_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_updated": { + "name": "docs_updated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_deleted": { + "name": "docs_deleted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_unchanged": { + "name": "docs_unchanged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_skipped": { + "name": "docs_skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_failed": { + "name": "docs_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "listed_count": { + "name": "listed_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "database_failure_class": { + "name": "database_failure_class", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcsl_connector_started_at_idx": { + "name": "kcsl_connector_started_at_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcsl_started_at_partial_idx": { + "name": "kcsl_started_at_partial_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_sync_log\".\"status\" = 'started'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcsl_terminal_started_at_idx": { + "name": "kcsl_terminal_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_sync_log\".\"status\" IN ('completed', 'failed')", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_sync_log_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_sync_log_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_sync_log", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcsl_database_failure_class_check": { + "name": "kcsl_database_failure_class_check", + "value": "\"knowledge_connector_sync_log\".\"database_failure_class\" IN ('capacity', 'conflict', 'connection')" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_document_observation": { + "name": "knowledge_document_observation", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kdo_member_idx": { + "name": "kdo_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_document_observation_document_id_document_id_fk": { + "name": "knowledge_document_observation_document_id_document_id_fk", + "tableFrom": "knowledge_document_observation", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_document_observation_member_id_knowledge_connector_member_id_fk": { + "name": "knowledge_document_observation_member_id_knowledge_connector_member_id_fk", + "tableFrom": "knowledge_document_observation", + "tableTo": "knowledge_connector_member", + "columnsFrom": ["member_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "knowledge_document_observation_document_id_member_id_pk": { + "name": "knowledge_document_observation_document_id_member_id_pk", + "columns": ["document_id", "member_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_external_directory": { + "name": "knowledge_external_directory", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sync_lock_token": { + "name": "sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_lock_lease_at": { + "name": "sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_started_at": { + "name": "last_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_complete_sync_at": { + "name": "last_complete_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "ked_workspace_identity_unique": { + "name": "ked_workspace_identity_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "ked_organization_identity_unique": { + "name": "ked_organization_identity_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_external_directory_workspace_id_workspace_id_fk": { + "name": "knowledge_external_directory_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_external_directory", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_external_directory_organization_id_organization_id_fk": { + "name": "knowledge_external_directory_organization_id_organization_id_fk", + "tableFrom": "knowledge_external_directory", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ked_owner_check": { + "name": "ked_owner_check", + "value": "num_nonnulls(\"knowledge_external_directory\".\"workspace_id\", \"knowledge_external_directory\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_external_group": { + "name": "knowledge_external_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_group_id": { + "name": "external_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "keg_organization_identity_unique": { + "name": "keg_organization_identity_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_organization_synced_idx": { + "name": "keg_organization_synced_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_synced_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_identity_unique": { + "name": "keg_identity_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_workspace_synced_idx": { + "name": "keg_workspace_synced_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_synced_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_external_group_organization_id_organization_id_fk": { + "name": "knowledge_external_group_organization_id_organization_id_fk", + "tableFrom": "knowledge_external_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "keg_workspace_fk": { + "name": "keg_workspace_fk", + "tableFrom": "knowledge_external_group", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "keg_owner_check": { + "name": "keg_owner_check", + "value": "num_nonnulls(\"knowledge_external_group\".\"workspace_id\", \"knowledge_external_group\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_external_group_member": { + "name": "knowledge_external_group_member", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kegm_subject_token_idx": { + "name": "kegm_subject_token_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "kegm_group_fk": { + "name": "kegm_group_fk", + "tableFrom": "knowledge_external_group_member", + "tableTo": "knowledge_external_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "knowledge_external_group_member_group_id_subject_token_pk": { + "name": "knowledge_external_group_member_group_id_subject_token_pk", + "columns": ["group_id", "subject_token"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_projection_dirty": { + "name": "knowledge_projection_dirty", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "content": { + "name": "content", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "marked_at": { + "name": "marked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "knowledge_projection_dirty_marked_at_idx": { + "name": "knowledge_projection_dirty_marked_at_idx", + "columns": [ + { + "expression": "marked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_projection_dirty_document_id_document_id_fk": { + "name": "knowledge_projection_dirty_document_id_document_id_fk", + "tableFrom": "knowledge_projection_dirty", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mcp_server_oauth": { + "name": "mcp_server_oauth", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "mcp_server_id": { + "name": "mcp_server_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_information": { + "name": "client_information", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tokens": { + "name": "tokens", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_verifier": { + "name": "code_verifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state_created_at": { + "name": "state_created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_refreshed_at": { + "name": "last_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mcp_server_oauth_server_unique": { + "name": "mcp_server_oauth_server_unique", + "columns": [ + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_server_oauth_state_idx": { + "name": "mcp_server_oauth_state_idx", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mcp_server_oauth_mcp_server_id_mcp_servers_id_fk": { + "name": "mcp_server_oauth_mcp_server_id_mcp_servers_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "mcp_servers", + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_server_oauth_user_id_user_id_fk": { + "name": "mcp_server_oauth_user_id_user_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "mcp_server_oauth_workspace_id_workspace_id_fk": { + "name": "mcp_server_oauth_workspace_id_workspace_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_server_oauth_organization_id_organization_id_fk": { + "name": "mcp_server_oauth_organization_id_organization_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_server_oauth_owner_check": { + "name": "mcp_server_oauth_owner_check", + "value": "num_nonnulls(\"mcp_server_oauth\".\"workspace_id\", \"mcp_server_oauth\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.mcp_servers": { + "name": "mcp_servers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "managed_connector_id": { + "name": "managed_connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config_version": { + "name": "oauth_config_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "transport": { + "name": "transport", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'headers'" + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_client_secret": { + "name": "oauth_client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "headers": { + "name": "headers", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "timeout": { + "name": "timeout", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 30000 + }, + "retries": { + "name": "retries", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 3 + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "last_connected": { + "name": "last_connected", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "connection_status": { + "name": "connection_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'disconnected'" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status_config": { + "name": "status_config", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "tool_count": { + "name": "tool_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_tools_refresh": { + "name": "last_tools_refresh", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_requests": { + "name": "total_requests", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mcp_servers_organization_id_idx": { + "name": "mcp_servers_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_workspace_enabled_idx": { + "name": "mcp_servers_workspace_enabled_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_credential_group_idx": { + "name": "mcp_servers_credential_group_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_credential_group_managed_connector_unique": { + "name": "mcp_servers_credential_group_managed_connector_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "managed_connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"mcp_servers\".\"credential_group_id\" IS NOT NULL AND \"mcp_servers\".\"managed_connector_id\" IS NOT NULL AND \"mcp_servers\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_workspace_deleted_partial_idx": { + "name": "mcp_servers_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"mcp_servers\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mcp_servers_workspace_id_workspace_id_fk": { + "name": "mcp_servers_workspace_id_workspace_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_servers_organization_id_organization_id_fk": { + "name": "mcp_servers_organization_id_organization_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_servers_credential_group_id_credential_group_id_fk": { + "name": "mcp_servers_credential_group_id_credential_group_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "mcp_servers_created_by_user_id_fk": { + "name": "mcp_servers_created_by_user_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_servers_owner_check": { + "name": "mcp_servers_owner_check", + "value": "num_nonnulls(\"mcp_servers\".\"workspace_id\", \"mcp_servers\".\"organization_id\") = 1" + }, + "mcp_servers_organization_managed_check": { + "name": "mcp_servers_organization_managed_check", + "value": "\"mcp_servers\".\"organization_id\" IS NULL OR \"mcp_servers\".\"credential_group_id\" IS NOT NULL" + }, + "mcp_servers_credential_group_managed_connector_check": { + "name": "mcp_servers_credential_group_managed_connector_check", + "value": "\"mcp_servers\".\"credential_group_id\" IS NULL OR \"mcp_servers\".\"managed_connector_id\" IS NOT NULL" + }, + "mcp_servers_managed_connector_oauth_check": { + "name": "mcp_servers_managed_connector_oauth_check", + "value": "\"mcp_servers\".\"managed_connector_id\" IS NULL OR \"mcp_servers\".\"auth_type\" = 'oauth'" + } + }, + "isRLSEnabled": false + }, + "public.member": { + "name": "member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "member_user_id_unique": { + "name": "member_user_id_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_organization_id_idx": { + "name": "member_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "member_user_id_user_id_fk": { + "name": "member_user_id_user_id_fk", + "tableFrom": "member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_organization_id_organization_id_fk": { + "name": "member_organization_id_organization_id_fk", + "tableFrom": "member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.member_profile": { + "name": "member_profile", + "schema": "", + "columns": { + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "manager_member_id": { + "name": "manager_member_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "member_profile_manager_member_id_idx": { + "name": "member_profile_manager_member_id_idx", + "columns": [ + { + "expression": "manager_member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_profile_updated_by_idx": { + "name": "member_profile_updated_by_idx", + "columns": [ + { + "expression": "updated_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "member_profile_member_id_member_id_fk": { + "name": "member_profile_member_id_member_id_fk", + "tableFrom": "member_profile", + "tableTo": "member", + "columnsFrom": ["member_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_profile_manager_member_id_member_id_fk": { + "name": "member_profile_manager_member_id_member_id_fk", + "tableFrom": "member_profile", + "tableTo": "member", + "columnsFrom": ["manager_member_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "member_profile_updated_by_user_id_fk": { + "name": "member_profile_updated_by_user_id_fk", + "tableFrom": "member_profile", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "member_profile_not_own_manager": { + "name": "member_profile_not_own_manager", + "value": "\"member_profile\".\"manager_member_id\" <> \"member_profile\".\"member_id\"" + } + }, + "isRLSEnabled": false + }, + "public.memory": { + "name": "memory", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "storage_version": { + "name": "storage_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "encrypted_context_summary": { + "name": "encrypted_context_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "memory_key_idx": { + "name": "memory_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_workspace_key_idx": { + "name": "memory_workspace_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_workspace_deleted_partial_idx": { + "name": "memory_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"memory\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_workspace_id_workspace_id_fk": { + "name": "memory_workspace_id_workspace_id_fk", + "tableFrom": "memory", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_artifact": { + "name": "memory_artifact", + "schema": "", + "columns": { + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "memory_artifact_key_idx": { + "name": "memory_artifact_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_artifact_memory_id_memory_id_fk": { + "name": "memory_artifact_memory_id_memory_id_fk", + "tableFrom": "memory_artifact", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "memory_artifact_key_execution_large_values_key_fk": { + "name": "memory_artifact_key_execution_large_values_key_fk", + "tableFrom": "memory_artifact", + "tableTo": "execution_large_values", + "columnsFrom": ["key"], + "columnsTo": ["key"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "memory_artifact_memory_id_key_pk": { + "name": "memory_artifact_memory_id_key_pk", + "columns": ["memory_id", "key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_item": { + "name": "memory_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sequence": { + "name": "sequence", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "memory_item_sequence_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "append_key": { + "name": "append_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "turn_id": { + "name": "turn_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provenance_status": { + "name": "provenance_status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provenance_entries": { + "name": "provenance_entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "memory_item_append_unique": { + "name": "memory_item_append_unique", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "append_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_item_sequence_idx": { + "name": "memory_item_sequence_idx", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sequence", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_item_memory_id_memory_id_fk": { + "name": "memory_item_memory_id_memory_id_fk", + "tableFrom": "memory_item", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "memory_item_kind_check": { + "name": "memory_item_kind_check", + "value": "\"memory_item\".\"kind\" IN ('message', 'exchange')" + }, + "memory_item_provenance_status_check": { + "name": "memory_item_provenance_status_check", + "value": "\"memory_item\".\"provenance_status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.memory_secret_provenance": { + "name": "memory_secret_provenance", + "schema": "", + "columns": { + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "memory_secret_provenance_memory_id_memory_id_fk": { + "name": "memory_secret_provenance_memory_id_memory_id_fk", + "tableFrom": "memory_secret_provenance", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "memory_secret_provenance_status_check": { + "name": "memory_secret_provenance_status_check", + "value": "\"memory_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.mothership_benchmark_runs": { + "name": "mothership_benchmark_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "benchmark_id": { + "name": "benchmark_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "evaluation_key": { + "name": "evaluation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reviews": { + "name": "reviews", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "correct": { + "name": "correct", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "automatic_correct": { + "name": "automatic_correct", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "total": { + "name": "total", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "artifacts": { + "name": "artifacts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_benchmark_runs_benchmark_created_idx": { + "name": "mothership_benchmark_runs_benchmark_created_idx", + "columns": [ + { + "expression": "benchmark_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_benchmark_runs_benchmark_id_mothership_benchmarks_id_fk": { + "name": "mothership_benchmark_runs_benchmark_id_mothership_benchmarks_id_fk", + "tableFrom": "mothership_benchmark_runs", + "tableTo": "mothership_benchmarks", + "columnsFrom": ["benchmark_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mothership_benchmark_runs_score_check": { + "name": "mothership_benchmark_runs_score_check", + "value": "\"mothership_benchmark_runs\".\"total\" > 0 AND \"mothership_benchmark_runs\".\"correct\" >= 0 AND \"mothership_benchmark_runs\".\"correct\" <= \"mothership_benchmark_runs\".\"total\"" + }, + "mothership_benchmark_runs_version_check": { + "name": "mothership_benchmark_runs_version_check", + "value": "\"mothership_benchmark_runs\".\"version\" > 0" + }, + "mothership_benchmark_runs_automatic_score_check": { + "name": "mothership_benchmark_runs_automatic_score_check", + "value": "\"mothership_benchmark_runs\".\"automatic_correct\" >= 0 AND \"mothership_benchmark_runs\".\"automatic_correct\" <= \"mothership_benchmark_runs\".\"total\"" + } + }, + "isRLSEnabled": false + }, + "public.mothership_benchmarks": { + "name": "mothership_benchmarks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_as_user_id": { + "name": "run_as_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "artifacts": { + "name": "artifacts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "running_stage": { + "name": "running_stage", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attempt_id": { + "name": "attempt_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "planner_chat_id": { + "name": "planner_chat_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_benchmarks_owner_created_idx": { + "name": "mothership_benchmarks_owner_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mothership_benchmarks_workspace_idx": { + "name": "mothership_benchmarks_workspace_idx", + "columns": [ + { + "expression": "source_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_benchmarks_organization_id_organization_id_fk": { + "name": "mothership_benchmarks_organization_id_organization_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_user_id_user_id_fk": { + "name": "mothership_benchmarks_user_id_user_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_run_as_user_id_user_id_fk": { + "name": "mothership_benchmarks_run_as_user_id_user_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "user", + "columnsFrom": ["run_as_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_source_workspace_id_workspace_id_fk": { + "name": "mothership_benchmarks_source_workspace_id_workspace_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "workspace", + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mothership_benchmarks_version_check": { + "name": "mothership_benchmarks_version_check", + "value": "\"mothership_benchmarks\".\"version\" > 0" + }, + "mothership_benchmarks_attempt_check": { + "name": "mothership_benchmarks_attempt_check", + "value": "(\"mothership_benchmarks\".\"running_stage\" IS NULL AND \"mothership_benchmarks\".\"attempt_id\" IS NULL AND \"mothership_benchmarks\".\"lease_expires_at\" IS NULL) OR (\"mothership_benchmarks\".\"running_stage\" IS NOT NULL AND \"mothership_benchmarks\".\"running_stage\" IN ('distill', 'redact', 'plan', 'reconstruct', 'grade') AND \"mothership_benchmarks\".\"attempt_id\" IS NOT NULL AND \"mothership_benchmarks\".\"lease_expires_at\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.mothership_inbox_allowed_sender": { + "name": "mothership_inbox_allowed_sender", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "added_by": { + "name": "added_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "inbox_sender_ws_email_idx": { + "name": "inbox_sender_ws_email_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_inbox_allowed_sender_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_allowed_sender_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_allowed_sender", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_inbox_allowed_sender_added_by_user_id_fk": { + "name": "mothership_inbox_allowed_sender_added_by_user_id_fk", + "tableFrom": "mothership_inbox_allowed_sender", + "tableTo": "user", + "columnsFrom": ["added_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_inbox_task": { + "name": "mothership_inbox_task", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_email": { + "name": "from_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sender_authenticated": { + "name": "sender_authenticated", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "from_name": { + "name": "from_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body_preview": { + "name": "body_preview", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_text": { + "name": "body_text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_html": { + "name": "body_html", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_message_id": { + "name": "email_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "in_reply_to": { + "name": "in_reply_to", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "response_message_id": { + "name": "response_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agentmail_message_id": { + "name": "agentmail_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'received'" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "trigger_job_id": { + "name": "trigger_job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "result_summary": { + "name": "result_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rejection_reason": { + "name": "rejection_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "has_attachments": { + "name": "has_attachments", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "cc_recipients": { + "name": "cc_recipients", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "processing_started_at": { + "name": "processing_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "inbox_task_ws_created_at_idx": { + "name": "inbox_task_ws_created_at_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_ws_status_idx": { + "name": "inbox_task_ws_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_response_msg_id_idx": { + "name": "inbox_task_response_msg_id_idx", + "columns": [ + { + "expression": "response_message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_email_msg_id_idx": { + "name": "inbox_task_email_msg_id_idx", + "columns": [ + { + "expression": "email_message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_inbox_task_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_task_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_task", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_inbox_task_chat_id_copilot_chats_id_fk": { + "name": "mothership_inbox_task_chat_id_copilot_chats_id_fk", + "tableFrom": "mothership_inbox_task", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_inbox_webhook": { + "name": "mothership_inbox_webhook", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "webhook_id": { + "name": "webhook_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_inbox_webhook_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_webhook_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_webhook", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "mothership_inbox_webhook_workspace_id_unique": { + "name": "mothership_inbox_webhook_workspace_id_unique", + "nullsNotDistinct": false, + "columns": ["workspace_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_memory_selections": { + "name": "mothership_memory_selections", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "space_id": { + "name": "space_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_memory_selections_user_id_user_id_fk": { + "name": "mothership_memory_selections_user_id_user_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_selections_organization_id_organization_id_fk": { + "name": "mothership_memory_selections_organization_id_organization_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_selections_space_id_mothership_memory_spaces_id_fk": { + "name": "mothership_memory_selections_space_id_mothership_memory_spaces_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "mothership_memory_spaces", + "columnsFrom": ["space_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "mothership_memory_selections_user_id_organization_id_pk": { + "name": "mothership_memory_selections_user_id_organization_id_pk", + "columns": ["user_id", "organization_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_memory_spaces": { + "name": "mothership_memory_spaces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_memory_spaces_owner_idx": { + "name": "mothership_memory_spaces_owner_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_memory_spaces_user_id_user_id_fk": { + "name": "mothership_memory_spaces_user_id_user_id_fk", + "tableFrom": "mothership_memory_spaces", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_spaces_organization_id_organization_id_fk": { + "name": "mothership_memory_spaces_organization_id_organization_id_fk", + "tableFrom": "mothership_memory_spaces", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_resource_effects": { + "name": "mothership_resource_effects", + "schema": "", + "columns": { + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "effect_id": { + "name": "effect_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_resource_effects_chat_id_copilot_chats_id_fk": { + "name": "mothership_resource_effects_chat_id_copilot_chats_id_fk", + "tableFrom": "mothership_resource_effects", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "mothership_resource_effects_chat_id_effect_id_pk": { + "name": "mothership_resource_effects_chat_id_effect_id_pk", + "columns": ["chat_id", "effect_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_access_token": { + "name": "oauth_access_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_id": { + "name": "refresh_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "oauth_access_token_client_id_idx": { + "name": "oauth_access_token_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_session_id_idx": { + "name": "oauth_access_token_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_refresh_id_idx": { + "name": "oauth_access_token_refresh_id_idx", + "columns": [ + { + "expression": "refresh_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_user_client_idx": { + "name": "oauth_access_token_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_expires_at_idx": { + "name": "oauth_access_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_access_token_client_id_oauth_client_client_id_fk": { + "name": "oauth_access_token_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_token_session_id_session_id_fk": { + "name": "oauth_access_token_session_id_session_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_access_token_user_id_user_id_fk": { + "name": "oauth_access_token_user_id_user_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_token_refresh_id_oauth_refresh_token_id_fk": { + "name": "oauth_access_token_refresh_id_oauth_refresh_token_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "oauth_refresh_token", + "columnsFrom": ["refresh_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_access_token_token_unique": { + "name": "oauth_access_token_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": { + "oauth_access_token_search_resource_check": { + "name": "oauth_access_token_search_resource_check", + "value": "NOT ('search:read' = ANY(\"oauth_access_token\".\"scopes\")) OR \"oauth_access_token\".\"resource\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.oauth_client": { + "name": "oauth_client", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_secret": { + "name": "client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "disabled": { + "name": "disabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "skip_consent": { + "name": "skip_consent", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "enable_end_session": { + "name": "enable_end_session", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "subject_type": { + "name": "subject_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "uri": { + "name": "uri", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "contacts": { + "name": "contacts", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "tos": { + "name": "tos", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_id": { + "name": "software_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_version": { + "name": "software_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_statement": { + "name": "software_statement", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "post_logout_redirect_uris": { + "name": "post_logout_redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "token_endpoint_auth_method": { + "name": "token_endpoint_auth_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "grant_types": { + "name": "grant_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "response_types": { + "name": "response_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "require_pkce": { + "name": "require_pkce", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "oauth_client_user_id_idx": { + "name": "oauth_client_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_client_user_id_user_id_fk": { + "name": "oauth_client_user_id_user_id_fk", + "tableFrom": "oauth_client", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_client_client_id_unique": { + "name": "oauth_client_client_id_unique", + "nullsNotDistinct": false, + "columns": ["client_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_consent": { + "name": "oauth_consent", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_consent_client_id_idx": { + "name": "oauth_consent_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_consent_client_id_oauth_client_client_id_fk": { + "name": "oauth_consent_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_consent", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_consent_user_id_user_id_fk": { + "name": "oauth_consent_user_id_user_id_fk", + "tableFrom": "oauth_consent", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_consent_user_client_reference_unique": { + "name": "oauth_consent_user_client_reference_unique", + "nullsNotDistinct": true, + "columns": ["user_id", "client_id", "reference_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_refresh_token": { + "name": "oauth_refresh_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "revoked": { + "name": "revoked", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "auth_time": { + "name": "auth_time", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "family_id": { + "name": "family_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_refresh_token_client_id_idx": { + "name": "oauth_refresh_token_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_session_id_idx": { + "name": "oauth_refresh_token_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_user_client_idx": { + "name": "oauth_refresh_token_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_expires_at_idx": { + "name": "oauth_refresh_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_refresh_token_client_id_oauth_client_client_id_fk": { + "name": "oauth_refresh_token_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_refresh_token_session_id_session_id_fk": { + "name": "oauth_refresh_token_session_id_session_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_refresh_token_user_id_user_id_fk": { + "name": "oauth_refresh_token_user_id_user_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_refresh_token_family_id_oauth_token_family_id_fk": { + "name": "oauth_refresh_token_family_id_oauth_token_family_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "oauth_token_family", + "columnsFrom": ["family_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_refresh_token_token_unique": { + "name": "oauth_refresh_token_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + }, + "oauth_refresh_token_family_generation_unique": { + "name": "oauth_refresh_token_family_generation_unique", + "nullsNotDistinct": false, + "columns": ["family_id", "generation"] + } + }, + "policies": {}, + "checkConstraints": { + "oauth_refresh_token_generation_check": { + "name": "oauth_refresh_token_generation_check", + "value": "\"oauth_refresh_token\".\"generation\" BETWEEN 0 AND 1000" + }, + "oauth_refresh_token_search_resource_check": { + "name": "oauth_refresh_token_search_resource_check", + "value": "NOT ('search:read' = ANY(\"oauth_refresh_token\".\"scopes\")) OR \"oauth_refresh_token\".\"resource\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.oauth_token_family": { + "name": "oauth_token_family", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "consent_id": { + "name": "consent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "current_generation": { + "name": "current_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_token_family_client_id_idx": { + "name": "oauth_token_family_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_session_id_idx": { + "name": "oauth_token_family_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_user_client_idx": { + "name": "oauth_token_family_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_consent_id_idx": { + "name": "oauth_token_family_consent_id_idx", + "columns": [ + { + "expression": "consent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_expires_at_idx": { + "name": "oauth_token_family_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_token_family_client_id_oauth_client_client_id_fk": { + "name": "oauth_token_family_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_token_family_session_id_session_id_fk": { + "name": "oauth_token_family_session_id_session_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_token_family_user_id_user_id_fk": { + "name": "oauth_token_family_user_id_user_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_token_family_consent_id_oauth_consent_id_fk": { + "name": "oauth_token_family_consent_id_oauth_consent_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "oauth_consent", + "columnsFrom": ["consent_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "oauth_token_family_generation_check": { + "name": "oauth_token_family_generation_check", + "value": "\"oauth_token_family\".\"current_generation\" BETWEEN 0 AND 1000" + } + }, + "isRLSEnabled": false + }, + "public.organization": { + "name": "organization", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "session_policy_settings": { + "name": "session_policy_settings", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "security_policy_version": { + "name": "security_policy_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "require_sso": { + "name": "require_sso", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "data_retention_settings": { + "name": "data_retention_settings", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "org_usage_limit": { + "name": "org_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "self_serve_usage_limit": { + "name": "self_serve_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit_notifications": { + "name": "limit_notifications", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "credit_balance": { + "name": "credit_balance", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_access_request_settings": { + "name": "organization_access_request_settings", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "allow_requests": { + "name": "allow_requests", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "organization_access_request_settings_organization_id_organization_id_fk": { + "name": "organization_access_request_settings_organization_id_organization_id_fk", + "tableFrom": "organization_access_request_settings", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_access_request_settings_updated_by_user_id_fk": { + "name": "organization_access_request_settings_updated_by_user_id_fk", + "tableFrom": "organization_access_request_settings", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_byok_keys": { + "name": "organization_byok_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_byok_organization_provider_idx": { + "name": "organization_byok_organization_provider_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_byok_keys_organization_id_organization_id_fk": { + "name": "organization_byok_keys_organization_id_organization_id_fk", + "tableFrom": "organization_byok_keys", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_byok_keys_created_by_user_id_fk": { + "name": "organization_byok_keys_created_by_user_id_fk", + "tableFrom": "organization_byok_keys", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_member_activity_daily": { + "name": "organization_member_activity_daily", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_count": { + "name": "event_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "first_at": { + "name": "first_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_at": { + "name": "last_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "organization_member_activity_daily_day_idx": { + "name": "organization_member_activity_daily_day_idx", + "columns": [ + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_member_activity_daily_user_idx": { + "name": "organization_member_activity_daily_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_member_activity_daily_organization_id_organization_id_fk": { + "name": "organization_member_activity_daily_organization_id_organization_id_fk", + "tableFrom": "organization_member_activity_daily", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_activity_daily_user_id_user_id_fk": { + "name": "organization_member_activity_daily_user_id_user_id_fk", + "tableFrom": "organization_member_activity_daily", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_member_activity_daily_pk": { + "name": "organization_member_activity_daily_pk", + "columns": ["organization_id", "day", "surface", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_member_activity_daily_surface_check": { + "name": "organization_member_activity_daily_surface_check", + "value": "\"organization_member_activity_daily\".\"surface\" IN ('assistant', 'agent', 'search', 'search_mcp', 'slack', 'workflows')" + }, + "organization_member_activity_daily_count_check": { + "name": "organization_member_activity_daily_count_check", + "value": "\"organization_member_activity_daily\".\"event_count\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.organization_member_usage_limit": { + "name": "organization_member_usage_limit", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "usage_limit": { + "name": "usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "set_by": { + "name": "set_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "org_member_usage_limit_org_user_unique": { + "name": "org_member_usage_limit_org_user_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "org_member_usage_limit_organization_id_idx": { + "name": "org_member_usage_limit_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_member_usage_limit_organization_id_organization_id_fk": { + "name": "organization_member_usage_limit_organization_id_organization_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_usage_limit_user_id_user_id_fk": { + "name": "organization_member_usage_limit_user_id_user_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_usage_limit_set_by_user_id_fk": { + "name": "organization_member_usage_limit_set_by_user_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "user", + "columnsFrom": ["set_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_history": { + "name": "organization_search_history", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sources": { + "name": "sources", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "queries": { + "name": "queries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": { + "organization_search_history_user_idx": { + "name": "organization_search_history_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_search_history_organization_id_organization_id_fk": { + "name": "organization_search_history_organization_id_organization_id_fk", + "tableFrom": "organization_search_history", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_search_history_user_id_user_id_fk": { + "name": "organization_search_history_user_id_user_id_fk", + "tableFrom": "organization_search_history", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_history_organization_id_user_id_pk": { + "name": "organization_search_history_organization_id_user_id_pk", + "columns": ["organization_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_integration": { + "name": "organization_search_integration", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "approved": { + "name": "approved", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "organization_search_integration_organization_id_organization_id_fk": { + "name": "organization_search_integration_organization_id_organization_id_fk", + "tableFrom": "organization_search_integration", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_integration_organization_id_connector_type_pk": { + "name": "organization_search_integration_organization_id_connector_type_pk", + "columns": ["organization_id", "connector_type"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_integration_daily": { + "name": "organization_search_integration_daily", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "searches_ok": { + "name": "searches_ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_partial": { + "name": "searches_partial", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_reconnect": { + "name": "searches_reconnect", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_rate_limited": { + "name": "searches_rate_limited", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_unavailable": { + "name": "searches_unavailable", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_timeout": { + "name": "searches_timeout", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "opens": { + "name": "opens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "organization_search_integration_daily_day_idx": { + "name": "organization_search_integration_daily_day_idx", + "columns": [ + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_integration_daily_user_idx": { + "name": "organization_search_integration_daily_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_search_integration_daily_organization_id_organization_id_fk": { + "name": "organization_search_integration_daily_organization_id_organization_id_fk", + "tableFrom": "organization_search_integration_daily", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_search_integration_daily_user_id_user_id_fk": { + "name": "organization_search_integration_daily_user_id_user_id_fk", + "tableFrom": "organization_search_integration_daily", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_integration_daily_pk": { + "name": "organization_search_integration_daily_pk", + "columns": ["organization_id", "day", "surface", "connector_type", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_search_integration_daily_surface_check": { + "name": "organization_search_integration_daily_surface_check", + "value": "\"organization_search_integration_daily\".\"surface\" IN ('assistant', 'agent', 'search', 'search_mcp', 'slack', 'workflows')" + }, + "organization_search_integration_daily_connector_type_check": { + "name": "organization_search_integration_daily_connector_type_check", + "value": "\"organization_search_integration_daily\".\"connector_type\" ~ '^[a-z][a-z0-9_]{0,63}$'" + }, + "organization_search_integration_daily_counts_check": { + "name": "organization_search_integration_daily_counts_check", + "value": "LEAST(\"organization_search_integration_daily\".\"searches_ok\", \"organization_search_integration_daily\".\"searches_partial\", \"organization_search_integration_daily\".\"searches_reconnect\", \"organization_search_integration_daily\".\"searches_rate_limited\", \"organization_search_integration_daily\".\"searches_unavailable\", \"organization_search_integration_daily\".\"searches_timeout\", \"organization_search_integration_daily\".\"opens\") >= 0" + }, + "organization_search_integration_daily_total_check": { + "name": "organization_search_integration_daily_total_check", + "value": "\"organization_search_integration_daily\".\"searches_ok\" + \"organization_search_integration_daily\".\"searches_partial\" + \"organization_search_integration_daily\".\"searches_reconnect\" + \"organization_search_integration_daily\".\"searches_rate_limited\" + \"organization_search_integration_daily\".\"searches_unavailable\" + \"organization_search_integration_daily\".\"searches_timeout\" + \"organization_search_integration_daily\".\"opens\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.organization_search_mcp_invocation": { + "name": "organization_search_mcp_invocation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_name": { + "name": "client_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_search_mcp_invocation_org_created_idx": { + "name": "organization_search_mcp_invocation_org_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_mcp_invocation_user_idx": { + "name": "organization_search_mcp_invocation_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_mcp_invocation_created_idx": { + "name": "organization_search_mcp_invocation_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "org_search_mcp_invocation_org_fk": { + "name": "org_search_mcp_invocation_org_fk", + "tableFrom": "organization_search_mcp_invocation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "org_search_mcp_invocation_user_fk": { + "name": "org_search_mcp_invocation_user_fk", + "tableFrom": "organization_search_mcp_invocation", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_search_mcp_invocation_tool_check": { + "name": "organization_search_mcp_invocation_tool_check", + "value": "\"organization_search_mcp_invocation\".\"tool_name\" IN ('search', 'read_document', 'chat', 'search_people', 'search_experts', 'list_my_activity', 'list_my_chat_history')" + }, + "organization_search_mcp_invocation_outcome_check": { + "name": "organization_search_mcp_invocation_outcome_check", + "value": "\"organization_search_mcp_invocation\".\"outcome\" IN ('success', 'error', 'cancelled', 'rate_limited')" + }, + "organization_search_mcp_invocation_duration_check": { + "name": "organization_search_mcp_invocation_duration_check", + "value": "\"organization_search_mcp_invocation\".\"duration_ms\" >= 0" + }, + "organization_search_mcp_invocation_client_name_check": { + "name": "organization_search_mcp_invocation_client_name_check", + "value": "length(\"organization_search_mcp_invocation\".\"client_name\") <= 256" + }, + "organization_search_mcp_invocation_auth_check": { + "name": "organization_search_mcp_invocation_auth_check", + "value": "(\"organization_search_mcp_invocation\".\"auth_kind\" = 'oauth_access_token' AND \"organization_search_mcp_invocation\".\"oauth_client_id\" IS NOT NULL)\n OR (\"organization_search_mcp_invocation\".\"auth_kind\" IN ('personal_api_key', 'workspace_api_key') AND \"organization_search_mcp_invocation\".\"oauth_client_id\" IS NULL AND \"organization_search_mcp_invocation\".\"client_name\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.organization_secret": { + "name": "organization_secret", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_value": { + "name": "encrypted_value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_secret_shared_unique": { + "name": "organization_secret_shared_unique", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organization_secret\".\"owner_user_id\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_secret_member_unique": { + "name": "organization_secret_member_unique", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organization_secret\".\"owner_user_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_secret_owner_idx": { + "name": "organization_secret_owner_idx", + "columns": [ + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_secret_source_id_organization_secret_source_id_fk": { + "name": "organization_secret_source_id_organization_secret_source_id_fk", + "tableFrom": "organization_secret", + "tableTo": "organization_secret_source", + "columnsFrom": ["source_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_secret_owner_user_id_user_id_fk": { + "name": "organization_secret_owner_user_id_user_id_fk", + "tableFrom": "organization_secret", + "tableTo": "user", + "columnsFrom": ["owner_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_secret_source": { + "name": "organization_secret_source", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_secret_source_org_unique": { + "name": "organization_secret_source_org_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_secret_source_organization_id_organization_id_fk": { + "name": "organization_secret_source_organization_id_organization_id_fk", + "tableFrom": "organization_secret_source", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_secret_source_mode_check": { + "name": "organization_secret_source_mode_check", + "value": "\"organization_secret_source\".\"mode\" IN ('organization', 'member')" + } + }, + "isRLSEnabled": false + }, + "public.outbox_event": { + "name": "outbox_event", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "available_at": { + "name": "available_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "locked_at": { + "name": "locked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "outbox_event_status_available_idx": { + "name": "outbox_event_status_available_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_pending_type_available_idx": { + "name": "outbox_event_pending_type_available_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"outbox_event\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_locked_at_idx": { + "name": "outbox_event_locked_at_idx", + "columns": [ + { + "expression": "locked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_type_created_idx": { + "name": "outbox_event_type_created_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.paused_executions": { + "name": "paused_executions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_snapshot": { + "name": "execution_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "pause_points": { + "name": "pause_points", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "total_pause_count": { + "name": "total_pause_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "resumed_count": { + "name": "resumed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "automatic_resume_retry_count": { + "name": "automatic_resume_retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'paused'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "paused_at": { + "name": "paused_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "next_resume_at": { + "name": "next_resume_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "paused_executions_workflow_id_idx": { + "name": "paused_executions_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_status_idx": { + "name": "paused_executions_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_execution_id_unique": { + "name": "paused_executions_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_next_resume_at_idx": { + "name": "paused_executions_next_resume_at_idx", + "columns": [ + { + "expression": "next_resume_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'paused' AND next_resume_at IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "paused_executions_workflow_id_workflow_id_fk": { + "name": "paused_executions_workflow_id_workflow_id_fk", + "tableFrom": "paused_executions", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pending_credential_draft": { + "name": "pending_credential_draft", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config": { + "name": "oauth_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "pending_draft_organization_id_idx": { + "name": "pending_draft_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pending_draft_user_provider_org": { + "name": "pending_draft_user_provider_org", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pending_draft_user_provider_ws": { + "name": "pending_draft_user_provider_ws", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "pending_credential_draft_user_id_user_id_fk": { + "name": "pending_credential_draft_user_id_user_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_workspace_id_workspace_id_fk": { + "name": "pending_credential_draft_workspace_id_workspace_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_organization_id_organization_id_fk": { + "name": "pending_credential_draft_organization_id_organization_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_credential_id_credential_id_fk": { + "name": "pending_credential_draft_credential_id_credential_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "pending_draft_owner_check": { + "name": "pending_draft_owner_check", + "value": "num_nonnulls(\"pending_credential_draft\".\"workspace_id\", \"pending_credential_draft\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.people_directory_entry": { + "name": "people_directory_entry", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manager_external_id": { + "name": "manager_external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "people_directory_entry_source_id_idx": { + "name": "people_directory_entry_source_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_entry_email_idx": { + "name": "people_directory_entry_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_entry_manager_idx": { + "name": "people_directory_entry_manager_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "manager_external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_entry_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_entry_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_entry", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_issue": { + "name": "people_directory_issue", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fields": { + "name": "fields", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "resolution": { + "name": "resolution", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference": { + "name": "reference", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kept_previous": { + "name": "kept_previous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "since": { + "name": "since", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "people_directory_issue_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_issue_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_issue", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_issue_organization_id_external_id_kind_pk": { + "name": "people_directory_issue_organization_id_external_id_kind_pk", + "columns": ["organization_id", "external_id", "kind"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_page": { + "name": "people_directory_page", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "page_hash": { + "name": "page_hash", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "people_directory_page_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_page_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_page", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_page_organization_id_run_id_page_hash_pk": { + "name": "people_directory_page_organization_id_run_id_page_hash_pk", + "columns": ["organization_id", "run_id", "page_hash"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_scim_change": { + "name": "people_directory_scim_change", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "changed_at": { + "name": "changed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "people_directory_scim_change_due_idx": { + "name": "people_directory_scim_change_due_idx", + "columns": [ + { + "expression": "changed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_scim_change_organization_id_organization_id_fk": { + "name": "people_directory_scim_change_organization_id_organization_id_fk", + "tableFrom": "people_directory_scim_change", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_stage": { + "name": "people_directory_stage", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "proposed_id": { + "name": "proposed_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "employee_number": { + "name": "employee_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue": { + "name": "issue", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue_fields": { + "name": "issue_fields", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manager_external_id": { + "name": "manager_external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reports_cursor": { + "name": "reports_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reports_complete": { + "name": "reports_complete", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "people_directory_stage_run_email_idx": { + "name": "people_directory_stage_run_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_stage_pending_idx": { + "name": "people_directory_stage_pending_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "NOT \"people_directory_stage\".\"reports_complete\"", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_stage_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_stage_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_stage", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_stage_organization_id_run_id_external_id_pk": { + "name": "people_directory_stage_organization_id_run_id_external_id_pk", + "columns": ["organization_id", "run_id", "external_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "people_directory_stage_email_check": { + "name": "people_directory_stage_email_check", + "value": "\"people_directory_stage\".\"email\" IS NOT NULL OR \"people_directory_stage\".\"issue\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.people_directory_sync": { + "name": "people_directory_sync", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_target": { + "name": "source_target", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_credential": { + "name": "encrypted_credential", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "configured_by": { + "name": "configured_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_token": { + "name": "lease_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "run_started_at": { + "name": "run_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "users_read": { + "name": "users_read", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "unmatched_managers": { + "name": "unmatched_managers", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "retry_count": { + "name": "retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_sync_at": { + "name": "next_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_attempt_at": { + "name": "last_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_success_at": { + "name": "last_success_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_directory_sync_due_idx": { + "name": "people_directory_sync_due_idx", + "columns": [ + { + "expression": "next_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_sync_organization_id_organization_id_fk": { + "name": "people_directory_sync_organization_id_organization_id_fk", + "tableFrom": "people_directory_sync", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "people_directory_sync_configured_by_user_id_fk": { + "name": "people_directory_sync_configured_by_user_id_fk", + "tableFrom": "people_directory_sync", + "tableTo": "user", + "columnsFrom": ["configured_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_slack_identity": { + "name": "people_slack_identity", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_team_id": { + "name": "slack_team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_user_id": { + "name": "slack_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_slack_identity_email_idx": { + "name": "people_slack_identity_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_slack_identity_organization_id_organization_id_fk": { + "name": "people_slack_identity_organization_id_organization_id_fk", + "tableFrom": "people_slack_identity", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_slack_identity_organization_id_slack_team_id_email_pk": { + "name": "people_slack_identity_organization_id_slack_team_id_email_pk", + "columns": ["organization_id", "slack_team_id", "email"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_slack_sync": { + "name": "people_slack_sync", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "next_refresh_at": { + "name": "next_refresh_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "lease_token": { + "name": "lease_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refreshed_at": { + "name": "refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_slack_sync_due_idx": { + "name": "people_slack_sync_due_idx", + "columns": [ + { + "expression": "next_refresh_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_slack_sync_organization_id_organization_id_fk": { + "name": "people_slack_sync_organization_id_organization_id_fk", + "tableFrom": "people_slack_sync", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_access_request": { + "name": "permission_access_request", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requester_id": { + "name": "requester_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope_key": { + "name": "scope_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_key": { + "name": "target_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target": { + "name": "target", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "target_label": { + "name": "target_label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "membership_id": { + "name": "membership_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "group_name": { + "name": "group_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decision": { + "name": "decision", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "decided_at": { + "name": "decided_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "permission_access_request_pending_unique": { + "name": "permission_access_request_pending_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requester_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"permission_access_request\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_access_request_org_queue_idx": { + "name": "permission_access_request_org_queue_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_access_request_requester_idx": { + "name": "permission_access_request_requester_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requester_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_access_request_organization_id_organization_id_fk": { + "name": "permission_access_request_organization_id_organization_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_access_request_requester_id_user_id_fk": { + "name": "permission_access_request_requester_id_user_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "user", + "columnsFrom": ["requester_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_access_request_decided_by_user_id_fk": { + "name": "permission_access_request_decided_by_user_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "user", + "columnsFrom": ["decided_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "permission_access_request_status_check": { + "name": "permission_access_request_status_check", + "value": "\"permission_access_request\".\"status\" in ('pending', 'fulfilled', 'declined', 'cancelled', 'closed')" + } + }, + "isRLSEnabled": false + }, + "public.permission_group": { + "name": "permission_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "membership_mode": { + "name": "membership_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'inherit'" + } + }, + "indexes": { + "permission_group_created_by_idx": { + "name": "permission_group_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_organization_name_unique": { + "name": "permission_group_organization_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_organization_default_unique": { + "name": "permission_group_organization_default_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "is_default = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_organization_id_organization_id_fk": { + "name": "permission_group_organization_id_organization_id_fk", + "tableFrom": "permission_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_created_by_user_id_fk": { + "name": "permission_group_created_by_user_id_fk", + "tableFrom": "permission_group", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_group_member": { + "name": "permission_group_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permission_group_member_group_user_unique": { + "name": "permission_group_member_group_user_unique", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_member_organization_user_idx": { + "name": "permission_group_member_organization_user_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_member_permission_group_id_permission_group_id_fk": { + "name": "permission_group_member_permission_group_id_permission_group_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_organization_id_organization_id_fk": { + "name": "permission_group_member_organization_id_organization_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_user_id_user_id_fk": { + "name": "permission_group_member_user_id_user_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_assigned_by_user_id_fk": { + "name": "permission_group_member_assigned_by_user_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "user", + "columnsFrom": ["assigned_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_group_workspace": { + "name": "permission_group_workspace", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permission_group_workspace_workspace_id_idx": { + "name": "permission_group_workspace_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_workspace_group_workspace_unique": { + "name": "permission_group_workspace_group_workspace_unique", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_workspace_permission_group_id_permission_group_id_fk": { + "name": "permission_group_workspace_permission_group_id_permission_group_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_workspace_workspace_id_workspace_id_fk": { + "name": "permission_group_workspace_workspace_id_workspace_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_workspace_organization_id_organization_id_fk": { + "name": "permission_group_workspace_organization_id_organization_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permissions": { + "name": "permissions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permissions_entity_idx": { + "name": "permissions_entity_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permissions_user_entity_permission_idx": { + "name": "permissions_user_entity_permission_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permissions_unique_constraint": { + "name": "permissions_unique_constraint", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permissions_user_id_user_id_fk": { + "name": "permissions_user_id_user_id_fk", + "tableFrom": "permissions", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pinned_item": { + "name": "pinned_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pinned_at": { + "name": "pinned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "pinned_item_user_workspace_idx": { + "name": "pinned_item_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pinned_item_resource_idx": { + "name": "pinned_item_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pinned_item_user_resource_unique": { + "name": "pinned_item_user_resource_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "pinned_item_user_id_user_id_fk": { + "name": "pinned_item_user_id_user_id_fk", + "tableFrom": "pinned_item", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pinned_item_workspace_id_workspace_id_fk": { + "name": "pinned_item_workspace_id_workspace_id_fk", + "tableFrom": "pinned_item", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project": { + "name": "project", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_scope_key": { + "name": "organization_scope_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END", + "type": "stored" + } + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "project_organization_archive_id_idx": { + "name": "project_organization_archive_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "project_owner_archive_id_idx": { + "name": "project_owner_archive_id_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_organization_id_organization_id_fk": { + "name": "project_organization_id_organization_id_fk", + "tableFrom": "project", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "project_owner_id_user_id_fk": { + "name": "project_owner_id_user_id_fk", + "tableFrom": "project", + "tableTo": "user", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "project_id_organization_scope_unique": { + "name": "project_id_organization_scope_unique", + "nullsNotDistinct": false, + "columns": ["id", "organization_scope_key"] + } + }, + "policies": {}, + "checkConstraints": { + "project_name_length": { + "name": "project_name_length", + "value": "char_length(btrim(\"project\".\"name\")) BETWEEN 1 AND 100" + } + }, + "isRLSEnabled": false + }, + "public.public_share": { + "name": "public_share", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_emails": { + "name": "allowed_emails", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "public_share_entity_id_idx": { + "name": "public_share_entity_id_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_token_unique": { + "name": "public_share_token_unique", + "columns": [ + { + "expression": "token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_resource_unique": { + "name": "public_share_resource_unique", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_resource_id_idx": { + "name": "public_share_resource_id_idx", + "columns": [ + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_workspace_id_idx": { + "name": "public_share_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "public_share_workspace_id_workspace_id_fk": { + "name": "public_share_workspace_id_workspace_id_fk", + "tableFrom": "public_share", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "public_share_created_by_user_id_fk": { + "name": "public_share_created_by_user_id_fk", + "tableFrom": "public_share", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "public_share_entity_binding_check": { + "name": "public_share_entity_binding_check", + "value": "\n (\"public_share\".\"entity_type\" IS NULL AND \"public_share\".\"entity_id\" IS NULL AND \"public_share\".\"workspace_id\" IS NOT NULL)\n OR (\"public_share\".\"entity_type\" IS NOT NULL AND \"public_share\".\"entity_id\" IS NOT NULL AND char_length(\"public_share\".\"entity_id\") > 0\n AND ((\"public_share\".\"entity_type\" = 'workspace' AND \"public_share\".\"workspace_id\" IS NOT NULL AND \"public_share\".\"entity_id\" = \"public_share\".\"workspace_id\")\n OR (\"public_share\".\"entity_type\" = 'project' AND \"public_share\".\"workspace_id\" IS NULL AND \"public_share\".\"resource_type\" = 'file')))\n " + } + }, + "isRLSEnabled": false + }, + "public.resource_policy": { + "name": "resource_policy", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "document": { + "name": "document", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "resource_policy_organization_id_idx": { + "name": "resource_policy_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resource_policy_resource_unique": { + "name": "resource_policy_resource_unique", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resource_policy_workspace_id_idx": { + "name": "resource_policy_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resource_policy_workspace_id_workspace_id_fk": { + "name": "resource_policy_workspace_id_workspace_id_fk", + "tableFrom": "resource_policy", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "resource_policy_organization_id_organization_id_fk": { + "name": "resource_policy_organization_id_organization_id_fk", + "tableFrom": "resource_policy", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "resource_policy_created_by_user_id_fk": { + "name": "resource_policy_created_by_user_id_fk", + "tableFrom": "resource_policy", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "resource_policy_updated_by_user_id_fk": { + "name": "resource_policy_updated_by_user_id_fk", + "tableFrom": "resource_policy", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "resource_policy_owner_check": { + "name": "resource_policy_owner_check", + "value": "num_nonnulls(\"resource_policy\".\"workspace_id\", \"resource_policy\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.resume_queue": { + "name": "resume_queue", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "paused_execution_id": { + "name": "paused_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_execution_id": { + "name": "parent_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "new_execution_id": { + "name": "new_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context_id": { + "name": "context_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resume_input": { + "name": "resume_input", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "queued_at": { + "name": "queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "resume_queue_parent_status_idx": { + "name": "resume_queue_parent_status_idx", + "columns": [ + { + "expression": "parent_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resume_queue_new_execution_idx": { + "name": "resume_queue_new_execution_idx", + "columns": [ + { + "expression": "new_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resume_queue_paused_execution_id_paused_executions_id_fk": { + "name": "resume_queue_paused_execution_id_paused_executions_id_fk", + "tableFrom": "resume_queue", + "tableTo": "paused_executions", + "columnsFrom": ["paused_execution_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sandbox_image": { + "name": "sandbox_image", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "spec_hash": { + "name": "spec_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "spec": { + "name": "spec", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "sandbox_image_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "image_ref": { + "name": "image_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_image_id": { + "name": "provider_image_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "materialization_generation": { + "name": "materialization_generation", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_detail": { + "name": "error_detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sandbox_image_provider_spec_unique": { + "name": "sandbox_image_provider_spec_unique", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "spec_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sandbox_image_status_idx": { + "name": "sandbox_image_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sandbox_image_last_used_idx": { + "name": "sandbox_image_last_used_idx", + "columns": [ + { + "expression": "last_used_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_connection": { + "name": "scim_connection", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "settings": { + "name": "settings", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_request_at": { + "name": "last_request_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "reconcile_lock_token": { + "name": "reconcile_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reconcile_lease_at": { + "name": "reconcile_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "reconciled_at": { + "name": "reconciled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_connection_organization_unique": { + "name": "scim_connection_organization_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_connection_reconcile_due_idx": { + "name": "scim_connection_reconcile_due_idx", + "columns": [ + { + "expression": "reconciled_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_connection_organization_id_organization_id_fk": { + "name": "scim_connection_organization_id_organization_id_fk", + "tableFrom": "scim_connection", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_connection_created_by_user_id_fk": { + "name": "scim_connection_created_by_user_id_fk", + "tableFrom": "scim_connection", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_credential": { + "name": "scim_credential", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_by": { + "name": "revoked_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_credential_token_hash_unique": { + "name": "scim_credential_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_credential_connection_idx": { + "name": "scim_credential_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_credential_connection_id_scim_connection_id_fk": { + "name": "scim_credential_connection_id_scim_connection_id_fk", + "tableFrom": "scim_credential", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_credential_revoked_by_user_id_fk": { + "name": "scim_credential_revoked_by_user_id_fk", + "tableFrom": "scim_credential", + "tableTo": "user", + "columnsFrom": ["revoked_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "scim_credential_created_by_user_id_fk": { + "name": "scim_credential_created_by_user_id_fk", + "tableFrom": "scim_credential", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_group": { + "name": "scim_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name_key": { + "name": "display_name_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_connection_display_name_unique": { + "name": "scim_group_connection_display_name_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_connection_external_id_unique": { + "name": "scim_group_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "external_id is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_connection_order_idx": { + "name": "scim_group_connection_order_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_connection_id_scim_connection_id_fk": { + "name": "scim_group_connection_id_scim_connection_id_fk", + "tableFrom": "scim_group", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_group_mapping": { + "name": "scim_group_mapping", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_kind": { + "name": "target_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_mapping_permission_group_idx": { + "name": "scim_group_mapping_permission_group_idx", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_mapping_workspace_idx": { + "name": "scim_group_mapping_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_mapping_group_target_unique": { + "name": "scim_group_mapping_group_target_unique", + "columns": [ + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"permission_group_id\", \"workspace_id\", \"role\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_mapping_group_id_scim_group_id_fk": { + "name": "scim_group_mapping_group_id_scim_group_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "scim_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_permission_group_id_permission_group_id_fk": { + "name": "scim_group_mapping_permission_group_id_permission_group_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_workspace_id_workspace_id_fk": { + "name": "scim_group_mapping_workspace_id_workspace_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_created_by_user_id_fk": { + "name": "scim_group_mapping_created_by_user_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "scim_group_mapping_target_shape": { + "name": "scim_group_mapping_target_shape", + "value": "(\n (\"scim_group_mapping\".\"target_kind\" = 'permission_group' AND \"scim_group_mapping\".\"permission_group_id\" IS NOT NULL AND \"scim_group_mapping\".\"workspace_id\" IS NULL AND \"scim_group_mapping\".\"permission_type\" IS NULL AND \"scim_group_mapping\".\"role\" IS NULL)\n OR (\"scim_group_mapping\".\"target_kind\" = 'workspace' AND \"scim_group_mapping\".\"workspace_id\" IS NOT NULL AND \"scim_group_mapping\".\"permission_type\" IS NOT NULL AND \"scim_group_mapping\".\"permission_group_id\" IS NULL AND \"scim_group_mapping\".\"role\" IS NULL)\n OR (\"scim_group_mapping\".\"target_kind\" = 'org_role' AND \"scim_group_mapping\".\"role\" IS NOT NULL AND \"scim_group_mapping\".\"permission_group_id\" IS NULL AND \"scim_group_mapping\".\"workspace_id\" IS NULL AND \"scim_group_mapping\".\"permission_type\" IS NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.scim_group_member": { + "name": "scim_group_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scim_user_id": { + "name": "scim_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_member_group_user_unique": { + "name": "scim_group_member_group_user_unique", + "columns": [ + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_member_scim_user_idx": { + "name": "scim_group_member_scim_user_idx", + "columns": [ + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_member_group_id_scim_group_id_fk": { + "name": "scim_group_member_group_id_scim_group_id_fk", + "tableFrom": "scim_group_member", + "tableTo": "scim_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_member_scim_user_id_scim_user_id_fk": { + "name": "scim_group_member_scim_user_id_scim_user_id_fk", + "tableFrom": "scim_group_member", + "tableTo": "scim_user", + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_projection_grant": { + "name": "scim_projection_grant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scim_user_id": { + "name": "scim_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_kind": { + "name": "target_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "baseline_permission": { + "name": "baseline_permission", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'directory'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_projection_grant_user_target_unique": { + "name": "scim_projection_grant_user_target_unique", + "columns": [ + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_projection_grant_connection_idx": { + "name": "scim_projection_grant_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_projection_grant_connection_id_scim_connection_id_fk": { + "name": "scim_projection_grant_connection_id_scim_connection_id_fk", + "tableFrom": "scim_projection_grant", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_projection_grant_scim_user_id_scim_user_id_fk": { + "name": "scim_projection_grant_scim_user_id_scim_user_id_fk", + "tableFrom": "scim_projection_grant", + "tableTo": "scim_user", + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_request_log": { + "name": "scim_request_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scim_type": { + "name": "scim_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_request_log_connection_created_idx": { + "name": "scim_request_log_connection_created_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_request_log_connection_id_scim_connection_id_fk": { + "name": "scim_request_log_connection_id_scim_connection_id_fk", + "tableFrom": "scim_request_log", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_user": { + "name": "scim_user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_name": { + "name": "user_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "attributes": { + "name": "attributes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_user_connection_user_unique": { + "name": "scim_user_connection_user_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_user_name_unique": { + "name": "scim_user_connection_user_name_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_external_id_unique": { + "name": "scim_user_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "external_id is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_order_idx": { + "name": "scim_user_connection_order_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_user_idx": { + "name": "scim_user_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_user_connection_id_scim_connection_id_fk": { + "name": "scim_user_connection_id_scim_connection_id_fk", + "tableFrom": "scim_user", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_user_user_id_user_id_fk": { + "name": "scim_user_user_id_user_id_fk", + "tableFrom": "scim_user", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_user_tombstone": { + "name": "scim_user_tombstone", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_user_tombstone_connection_external_id_unique": { + "name": "scim_user_tombstone_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_tombstone_user_idx": { + "name": "scim_user_tombstone_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_user_tombstone_connection_id_scim_connection_id_fk": { + "name": "scim_user_tombstone_connection_id_scim_connection_id_fk", + "tableFrom": "scim_user_tombstone", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_user_tombstone_user_id_user_id_fk": { + "name": "scim_user_tombstone_user_id_user_id_fk", + "tableFrom": "scim_user_tombstone", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.secret_usage": { + "name": "secret_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_name": { + "name": "secret_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_scope": { + "name": "secret_scope", + "type": "secret_usage_scope", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "secret_owner_user_id": { + "name": "secret_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "source": { + "name": "source", + "type": "secret_usage_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "usage_date": { + "name": "usage_date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "use_count": { + "name": "use_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "last_execution_id": { + "name": "last_execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_trigger": { + "name": "last_trigger", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "secret_usage_bucket_unique": { + "name": "secret_usage_bucket_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_date", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "secret_usage_secret_recent_idx": { + "name": "secret_usage_secret_recent_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_used_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "secret_usage_workspace_id_workspace_id_fk": { + "name": "secret_usage_workspace_id_workspace_id_fk", + "tableFrom": "secret_usage", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "active_organization_id": { + "name": "active_organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "session_user_id_idx": { + "name": "session_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "session_active_organization_id_organization_id_fk": { + "name": "session_active_organization_id_organization_id_fk", + "tableFrom": "session", + "tableTo": "organization", + "columnsFrom": ["active_organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "theme": { + "name": "theme", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "auto_connect": { + "name": "auto_connect", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "telemetry_enabled": { + "name": "telemetry_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "email_preferences": { + "name": "email_preferences", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "billing_usage_notifications_enabled": { + "name": "billing_usage_notifications_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "super_user_mode_enabled": { + "name": "super_user_mode_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "mothership_environment": { + "name": "mothership_environment", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "error_notifications_enabled": { + "name": "error_notifications_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "snap_to_grid_size": { + "name": "snap_to_grid_size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "show_action_bar": { + "name": "show_action_bar", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "auto_focus_on_click": { + "name": "auto_focus_on_click", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "copilot_auto_allowed_tools": { + "name": "copilot_auto_allowed_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "last_active_workspace_id": { + "name": "last_active_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "settings_user_id_user_id_fk": { + "name": "settings_user_id_user_id_fk", + "tableFrom": "settings", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "settings_user_id_unique": { + "name": "settings_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sim_link": { + "name": "sim_link", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_name": { + "name": "normalized_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_url": { + "name": "default_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "unlisted": { + "name": "unlisted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "restrict_edit": { + "name": "restrict_edit", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "visit_count": { + "name": "visit_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_visited_at": { + "name": "last_visited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sim_link_organization_name_unique": { + "name": "sim_link_organization_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sim_link_created_by_idx": { + "name": "sim_link_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sim_link_organization_id_organization_id_fk": { + "name": "sim_link_organization_id_organization_id_fk", + "tableFrom": "sim_link", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sim_link_created_by_user_id_fk": { + "name": "sim_link_created_by_user_id_fk", + "tableFrom": "sim_link", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sim_trigger_state": { + "name": "sim_trigger_state", + "schema": "", + "columns": { + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope_key": { + "name": "scope_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "last_fired_at": { + "name": "last_fired_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "sim_trigger_state_workflow_id_workflow_id_fk": { + "name": "sim_trigger_state_workflow_id_workflow_id_fk", + "tableFrom": "sim_trigger_state", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "sim_trigger_state_workflow_id_block_id_scope_key_pk": { + "name": "sim_trigger_state_workflow_id_block_id_scope_key_pk", + "columns": ["workflow_id", "block_id", "scope_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill": { + "name": "skill", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_workspace_name_unique": { + "name": "skill_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_workspace_id_workspace_id_fk": { + "name": "skill_workspace_id_workspace_id_fk", + "tableFrom": "skill", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_user_id_user_id_fk": { + "name": "skill_user_id_user_id_fk", + "tableFrom": "skill", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill_member": { + "name": "skill_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_member_user_id_idx": { + "name": "skill_member_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skill_member_unique": { + "name": "skill_member_unique", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_member_skill_id_skill_id_fk": { + "name": "skill_member_skill_id_skill_id_fk", + "tableFrom": "skill_member", + "tableTo": "skill", + "columnsFrom": ["skill_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_member_user_id_user_id_fk": { + "name": "skill_member_user_id_user_id_fk", + "tableFrom": "skill_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_member_invited_by_user_id_fk": { + "name": "skill_member_invited_by_user_id_fk", + "tableFrom": "skill_member", + "tableTo": "user", + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_app": { + "name": "slack_app", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_client_secret": { + "name": "encrypted_client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_signing_secret": { + "name": "encrypted_signing_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "slack_app_organization_id_organization_id_fk": { + "name": "slack_app_organization_id_organization_id_fk", + "tableFrom": "slack_app", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "slack_app_owner_check": { + "name": "slack_app_owner_check", + "value": "(\"slack_app\".\"kind\" = 'custom' AND \"slack_app\".\"organization_id\" IS NOT NULL) OR (\"slack_app\".\"kind\" = 'shared' AND \"slack_app\".\"organization_id\" IS NULL)" + }, + "slack_app_custom_credentials_check": { + "name": "slack_app_custom_credentials_check", + "value": "\"slack_app\".\"kind\" = 'shared' OR (\"slack_app\".\"client_id\" IS NOT NULL AND \"slack_app\".\"encrypted_client_secret\" IS NOT NULL AND \"slack_app\".\"encrypted_signing_secret\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.slack_search_installation": { + "name": "slack_search_installation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_id": { + "name": "app_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_app_id": { + "name": "slack_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team_name": { + "name": "team_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bot_user_id": { + "name": "bot_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enterprise_id": { + "name": "enterprise_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "credential_version": { + "name": "credential_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_outcome": { + "name": "last_outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_event_at": { + "name": "last_event_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "slack_search_installation_organization_idx": { + "name": "slack_search_installation_organization_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_credential_unique": { + "name": "slack_search_installation_credential_unique", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_app_team_unique": { + "name": "slack_search_installation_app_team_unique", + "columns": [ + { + "expression": "app_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_active_team_unique": { + "name": "slack_search_installation_active_team_unique", + "columns": [ + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"slack_search_installation\".\"enabled\" = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_search_installation_organization_id_organization_id_fk": { + "name": "slack_search_installation_organization_id_organization_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_search_installation_credential_id_credential_id_fk": { + "name": "slack_search_installation_credential_id_credential_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_search_installation_slack_app_id_slack_app_id_fk": { + "name": "slack_search_installation_slack_app_id_slack_app_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "slack_app", + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_search_turn": { + "name": "slack_search_turn", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "slack_search_turn_ordinal_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "conversation_key": { + "name": "conversation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "lease_id": { + "name": "lease_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "slack_search_turn_event_unique": { + "name": "slack_search_turn_event_unique", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_pending_idx": { + "name": "slack_search_turn_pending_idx", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_thread_idx": { + "name": "slack_search_turn_thread_idx", + "columns": [ + { + "expression": "conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_active_thread_unique": { + "name": "slack_search_turn_active_thread_unique", + "columns": [ + { + "expression": "conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"slack_search_turn\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_search_turn_installation_id_slack_search_installation_id_fk": { + "name": "slack_search_turn_installation_id_slack_search_installation_id_fk", + "tableFrom": "slack_search_turn", + "tableTo": "slack_search_installation", + "columnsFrom": ["installation_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sso_domain": { + "name": "sso_domain", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "verification_token": { + "name": "verification_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "verified_at": { + "name": "verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "primary_provider_id": { + "name": "primary_provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sso_domain_domain_idx": { + "name": "sso_domain_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_domain_org_domain_unique": { + "name": "sso_domain_org_domain_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_domain_verified_unique": { + "name": "sso_domain_verified_unique", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "status = 'verified'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sso_domain_organization_id_organization_id_fk": { + "name": "sso_domain_organization_id_organization_id_fk", + "tableFrom": "sso_domain", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sso_domain_created_by_user_id_fk": { + "name": "sso_domain_created_by_user_id_fk", + "tableFrom": "sso_domain", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sso_provider": { + "name": "sso_provider", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oidc_config": { + "name": "oidc_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "saml_config": { + "name": "saml_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "domain_verified": { + "name": "domain_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "jit_provisioning_enabled": { + "name": "jit_provisioning_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + } + }, + "indexes": { + "sso_provider_provider_id_unique": { + "name": "sso_provider_provider_id_unique", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_domain_idx": { + "name": "sso_provider_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_user_id_idx": { + "name": "sso_provider_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_organization_id_idx": { + "name": "sso_provider_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sso_provider_user_id_user_id_fk": { + "name": "sso_provider_user_id_user_id_fk", + "tableFrom": "sso_provider", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sso_provider_organization_id_organization_id_fk": { + "name": "sso_provider_organization_id_organization_id_fk", + "tableFrom": "sso_provider", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.subscription": { + "name": "subscription", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "period_start": { + "name": "period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "period_end": { + "name": "period_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "cancel_at": { + "name": "cancel_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "canceled_at": { + "name": "canceled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "seats": { + "name": "seats", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "trial_start": { + "name": "trial_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trial_end": { + "name": "trial_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "billing_interval": { + "name": "billing_interval", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_schedule_id": { + "name": "stripe_schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "last_closed_period_start": { + "name": "last_closed_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "allowance_period_start": { + "name": "allowance_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "allowance_seats": { + "name": "allowance_seats", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "allowance_seat_months": { + "name": "allowance_seat_months", + "type": "numeric", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "subscription_reference_status_idx": { + "name": "subscription_reference_status_idx", + "columns": [ + { + "expression": "reference_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "subscription_cycle_close_lagging_idx": { + "name": "subscription_cycle_close_lagging_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"subscription\".\"status\" in ('active', 'past_due') and \"subscription\".\"period_start\" is not null and (\"subscription\".\"last_closed_period_start\" is null or \"subscription\".\"last_closed_period_start\" < \"subscription\".\"period_start\")", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "check_enterprise_metadata": { + "name": "check_enterprise_metadata", + "value": "plan != 'enterprise' OR metadata IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.table_jobs": { + "name": "table_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "rows_processed": { + "name": "rows_processed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "table_jobs_one_active_per_table": { + "name": "table_jobs_one_active_per_table", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"table_jobs\".\"status\" = 'running' AND \"table_jobs\".\"type\" <> 'export'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_jobs_watchdog_idx": { + "name": "table_jobs_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_jobs_table_started_idx": { + "name": "table_jobs_table_started_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_jobs_table_id_user_table_definitions_id_fk": { + "name": "table_jobs_table_id_user_table_definitions_id_fk", + "tableFrom": "table_jobs", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_jobs_workspace_id_workspace_id_fk": { + "name": "table_jobs_workspace_id_workspace_id_fk", + "tableFrom": "table_jobs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_row_executions": { + "name": "table_row_executions", + "schema": "", + "columns": { + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "row_id": { + "name": "row_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "running_block_ids": { + "name": "running_block_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "block_errors": { + "name": "block_errors", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "capability_governed_user_id": { + "name": "capability_governed_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enrichment_details": { + "name": "enrichment_details", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "table_row_executions_table_status_idx": { + "name": "table_row_executions_table_status_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_row_executions\".\"status\" IN ('queued', 'running', 'pending')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_row_executions_execution_id_idx": { + "name": "table_row_executions_execution_id_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_row_executions\".\"execution_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_row_executions_table_group_idx": { + "name": "table_row_executions_table_group_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_row_executions_table_id_user_table_definitions_id_fk": { + "name": "table_row_executions_table_id_user_table_definitions_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_row_executions_row_id_user_table_rows_id_fk": { + "name": "table_row_executions_row_id_user_table_rows_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user_table_rows", + "columnsFrom": ["row_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_row_executions_capability_governed_user_id_user_id_fk": { + "name": "table_row_executions_capability_governed_user_id_user_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user", + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "table_row_executions_row_id_group_id_pk": { + "name": "table_row_executions_row_id_group_id_pk", + "columns": ["row_id", "group_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_run_dispatches": { + "name": "table_run_dispatches", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "cursor": { + "name": "cursor", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit": { + "name": "limit", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "processed_count": { + "name": "processed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_manual_run": { + "name": "is_manual_run", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "triggered_by_user_id": { + "name": "triggered_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capability_governed_user_id": { + "name": "capability_governed_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_at": { + "name": "requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "heartbeat_at": { + "name": "heartbeat_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "table_run_dispatches_active_idx": { + "name": "table_run_dispatches_active_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_run_dispatches_watchdog_idx": { + "name": "table_run_dispatches_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requested_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_run_dispatches_governed_active_idx": { + "name": "table_run_dispatches_governed_active_idx", + "columns": [ + { + "expression": "capability_governed_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_run_dispatches\".\"status\" IN ('pending', 'dispatching')", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_run_dispatches_table_id_user_table_definitions_id_fk": { + "name": "table_run_dispatches_table_id_user_table_definitions_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_run_dispatches_workspace_id_workspace_id_fk": { + "name": "table_run_dispatches_workspace_id_workspace_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_run_dispatches_triggered_by_user_id_user_id_fk": { + "name": "table_run_dispatches_triggered_by_user_id_user_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user", + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "table_run_dispatches_capability_governed_user_id_user_id_fk": { + "name": "table_run_dispatches_capability_governed_user_id_user_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user", + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_views": { + "name": "table_views", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "table_views_table_created_idx": { + "name": "table_views_table_created_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_views_workspace_created_idx": { + "name": "table_views_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_views_table_default_unique": { + "name": "table_views_table_default_unique", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "is_default = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_views_table_id_user_table_definitions_id_fk": { + "name": "table_views_table_id_user_table_definitions_id_fk", + "tableFrom": "table_views", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_views_workspace_id_workspace_id_fk": { + "name": "table_views_workspace_id_workspace_id_fk", + "tableFrom": "table_views", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_views_created_by_user_id_fk": { + "name": "table_views_created_by_user_id_fk", + "tableFrom": "table_views", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.trial_card": { + "name": "trial_card", + "schema": "", + "columns": { + "fingerprint": { + "name": "fingerprint", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "trial_card_user_id_idx": { + "name": "trial_card_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "trial_card_user_id_user_id_fk": { + "name": "trial_card_user_id_user_id_fk", + "tableFrom": "trial_card", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.upload_session": { + "name": "upload_session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "purpose": { + "name": "purpose", + "type": "upload_session_purpose", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "upload_session_method", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "storage_context": { + "name": "storage_context", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "final_key": { + "name": "final_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_provider": { + "name": "storage_provider", + "type": "upload_session_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "provider_upload_id": { + "name": "provider_upload_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_object_version": { + "name": "provider_object_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_size": { + "name": "file_size", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "part_size": { + "name": "part_size", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "part_count": { + "name": "part_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "upload_session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'uploading'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "processing_lease_id": { + "name": "processing_lease_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_lease_expires_at": { + "name": "processing_lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_file_id": { + "name": "completed_file_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "upload_session_token_hash_unique": { + "name": "upload_session_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "upload_session_final_key_unique": { + "name": "upload_session_final_key_unique", + "columns": [ + { + "expression": "final_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "upload_session_status_expires_at_idx": { + "name": "upload_session_status_expires_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.usage_log": { + "name": "usage_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category": { + "name": "category", + "type": "usage_log_category", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "usage_log_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "cost": { + "name": "cost", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "event_key": { + "name": "event_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_entity_type": { + "name": "billing_entity_type", + "type": "billing_entity_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "billing_entity_id": { + "name": "billing_entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_period_start": { + "name": "billing_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "billing_period_end": { + "name": "billing_period_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "usage_log_user_created_at_idx": { + "name": "usage_log_user_created_at_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_source_idx": { + "name": "usage_log_source_idx", + "columns": [ + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_workflow_id_idx": { + "name": "usage_log_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_event_key_unique": { + "name": "usage_log_event_key_unique", + "columns": [ + { + "expression": "event_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"usage_log\".\"event_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_billing_entity_period_cost_idx": { + "name": "usage_log_billing_entity_period_cost_idx", + "columns": [ + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_period_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_period_end", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"usage_log\".\"billing_entity_type\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_billing_entity_created_at_cost_idx": { + "name": "usage_log_billing_entity_created_at_cost_idx", + "columns": [ + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"usage_log\".\"billing_entity_type\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_workspace_created_at_cost_idx": { + "name": "usage_log_workspace_created_at_cost_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_execution_id_idx": { + "name": "usage_log_execution_id_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "usage_log_user_id_user_id_fk": { + "name": "usage_log_user_id_user_id_fk", + "tableFrom": "usage_log", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "usage_log_workspace_id_workspace_id_fk": { + "name": "usage_log_workspace_id_workspace_id_fk", + "tableFrom": "usage_log", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "usage_log_workflow_id_workflow_id_fk": { + "name": "usage_log_workflow_id_workflow_id_fk", + "tableFrom": "usage_log", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "usage_log_billing_scope_all_or_none": { + "name": "usage_log_billing_scope_all_or_none", + "value": "(\n (\"usage_log\".\"billing_entity_type\" IS NULL AND \"usage_log\".\"billing_entity_id\" IS NULL AND \"usage_log\".\"billing_period_start\" IS NULL AND \"usage_log\".\"billing_period_end\" IS NULL)\n OR\n (\"usage_log\".\"billing_entity_type\" IS NOT NULL AND \"usage_log\".\"billing_entity_id\" IS NOT NULL AND \"usage_log\".\"billing_period_start\" IS NOT NULL AND \"usage_log\".\"billing_period_end\" IS NOT NULL AND \"usage_log\".\"billing_period_start\" < \"usage_log\".\"billing_period_end\")\n )" + } + }, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_email": { + "name": "normalized_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'user'" + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "suspension_source": { + "name": "suspension_source", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_email_lower_idx": { + "name": "user_email_lower_idx", + "columns": [ + { + "expression": "lower(btrim(\"email\"))", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_gmail_mailbox_idx": { + "name": "user_gmail_mailbox_idx", + "columns": [ + { + "expression": "(CASE WHEN split_part(lower(btrim(\"email\")), '@', 2) IN ('gmail.com', 'googlemail.com') THEN replace(split_part(split_part(lower(btrim(\"email\")), '@', 1), '+', 1), '.', '') || '@gmail.com' END)", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "(CASE WHEN split_part(lower(btrim(\"user\".\"email\")), '@', 2) IN ('gmail.com', 'googlemail.com') THEN replace(split_part(split_part(lower(btrim(\"user\".\"email\")), '@', 1), '+', 1), '.', '') || '@gmail.com' END) IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": ["email"] + }, + "user_normalized_email_unique": { + "name": "user_normalized_email_unique", + "nullsNotDistinct": false, + "columns": ["normalized_email"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_stats": { + "name": "user_stats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "current_usage_limit": { + "name": "current_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'5'" + }, + "usage_limit_updated_at": { + "name": "usage_limit_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "last_period_cost": { + "name": "last_period_cost", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'0'" + }, + "billed_overage_this_period": { + "name": "billed_overage_this_period", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "credit_balance": { + "name": "credit_balance", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "last_period_copilot_cost": { + "name": "last_period_copilot_cost", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'0'" + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "free_tier_eligible": { + "name": "free_tier_eligible", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "billing_blocked": { + "name": "billing_blocked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "billing_blocked_reason": { + "name": "billing_blocked_reason", + "type": "billing_blocked_reason", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "limit_notifications": { + "name": "limit_notifications", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + } + }, + "indexes": {}, + "foreignKeys": { + "user_stats_user_id_user_id_fk": { + "name": "user_stats_user_id_user_id_fk", + "tableFrom": "user_stats", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_stats_user_id_unique": { + "name": "user_stats_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_definitions": { + "name": "user_table_definitions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "schema": { + "name": "schema", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "max_rows": { + "name": "max_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10000 + }, + "row_count": { + "name": "row_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "rows_version": { + "name": "rows_version", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "schema_locked": { + "name": "schema_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "insert_locked": { + "name": "insert_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "update_locked": { + "name": "update_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "delete_locked": { + "name": "delete_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "user_table_def_workspace_id_idx": { + "name": "user_table_def_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_folder_id_idx": { + "name": "user_table_def_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_created_by_idx": { + "name": "user_table_def_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "user_table_def_workspace_name_unique": { + "name": "user_table_def_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"user_table_definitions\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_archived_at_idx": { + "name": "user_table_def_archived_at_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_workspace_archived_partial_idx": { + "name": "user_table_def_workspace_archived_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"user_table_definitions\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_definitions_workspace_id_workspace_id_fk": { + "name": "user_table_definitions_workspace_id_workspace_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_definitions_folder_id_folder_id_fk": { + "name": "user_table_definitions_folder_id_folder_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "user_table_definitions_created_by_user_id_fk": { + "name": "user_table_definitions_created_by_user_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_row_changes": { + "name": "user_table_row_changes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "user_table_row_changes_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "row_delta": { + "name": "row_delta", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "user_table_row_changes_table_id_idx": { + "name": "user_table_row_changes_table_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_row_changes_table_id_user_table_definitions_id_fk": { + "name": "user_table_row_changes_table_id_user_table_definitions_id_fk", + "tableFrom": "user_table_row_changes", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_row_secret_provenance": { + "name": "user_table_row_secret_provenance", + "schema": "", + "columns": { + "row_id": { + "name": "row_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_table_row_secret_provenance_row_id_user_table_rows_id_fk": { + "name": "user_table_row_secret_provenance_row_id_user_table_rows_id_fk", + "tableFrom": "user_table_row_secret_provenance", + "tableTo": "user_table_rows", + "columnsFrom": ["row_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_table_row_secret_provenance_status_check": { + "name": "user_table_row_secret_provenance_status_check", + "value": "\"user_table_row_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.user_table_rows": { + "name": "user_table_rows", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_table_rows_created_by_idx": { + "name": "user_table_rows_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"user_table_rows\".\"created_by\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "user_table_rows_tenant_data_gin_idx": { + "name": "user_table_rows_tenant_data_gin_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"data\" jsonb_path_ops", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "user_table_rows_workspace_table_idx": { + "name": "user_table_rows_workspace_table_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_position_idx": { + "name": "user_table_rows_table_position_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_order_key_idx": { + "name": "user_table_rows_table_order_key_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_created_id_idx": { + "name": "user_table_rows_table_created_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_id_id_idx": { + "name": "user_table_rows_table_id_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_rows_table_id_user_table_definitions_id_fk": { + "name": "user_table_rows_table_id_user_table_definitions_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_rows_workspace_id_workspace_id_fk": { + "name": "user_table_rows_workspace_id_workspace_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_rows_created_by_user_id_fk": { + "name": "user_table_rows_created_by_user_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "verification_expires_at_idx": { + "name": "verification_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.webhook": { + "name": "webhook", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_status": { + "name": "registration_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_generation": { + "name": "registration_generation", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "config_fingerprint": { + "name": "config_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "prepared_at": { + "name": "prepared_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "routing_key": { + "name": "routing_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_config": { + "name": "provider_config", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "path_deployment_unique": { + "name": "path_deployment_unique", + "columns": [ + { + "expression": "path", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_workflow_deployment_idx": { + "name": "webhook_workflow_deployment_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_routing_key_active_idx": { + "name": "webhook_routing_key_active_idx", + "columns": [ + { + "expression": "routing_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"webhook\".\"archived_at\" IS NULL AND \"webhook\".\"routing_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_archived_at_partial_idx": { + "name": "webhook_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"webhook\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_webhook_on_provider_is_active_workflow_id_deploym_bdeed5468": { + "name": "idx_webhook_on_provider_is_active_workflow_id_deploym_bdeed5468", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_webhook_on_workflow_id_block_id_updated_at_desc": { + "name": "idx_webhook_on_workflow_id_block_id_updated_at_desc", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_active_registration_unique": { + "name": "webhook_active_registration_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"registration_status\" = 'active' AND \"webhook\".\"block_id\" IS NOT NULL AND \"webhook\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_candidate_registration_unique": { + "name": "webhook_candidate_registration_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"registration_status\" = 'candidate' AND \"webhook\".\"block_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_registration_status_generation_idx": { + "name": "webhook_registration_status_generation_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "registration_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "registration_generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "webhook_workflow_id_workflow_id_fk": { + "name": "webhook_workflow_id_workflow_id_fk", + "tableFrom": "webhook", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "webhook_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "webhook_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "webhook", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "webhook_registration_status_check": { + "name": "webhook_registration_status_check", + "value": "\"webhook\".\"registration_status\" IS NULL OR \"webhook\".\"registration_status\" IN ('active', 'candidate', 'retired', 'orphaned')" + }, + "webhook_registration_generation_check": { + "name": "webhook_registration_generation_check", + "value": "\"webhook\".\"registration_generation\" IS NULL OR \"webhook\".\"registration_generation\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.webhook_path_claim": { + "name": "webhook_path_claim", + "schema": "", + "columns": { + "path": { + "name": "path", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "webhook_path_claim_workflow_idx": { + "name": "webhook_path_claim_workflow_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "webhook_path_claim_workflow_id_workflow_id_fk": { + "name": "webhook_path_claim_workflow_id_workflow_id_fk", + "tableFrom": "webhook_path_claim", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "webhook_path_claim_generation_check": { + "name": "webhook_path_claim_generation_check", + "value": "\"webhook_path_claim\".\"generation\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.workflow": { + "name": "workflow", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_synced": { + "name": "last_synced", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "is_deployed": { + "name": "is_deployed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deployed_at": { + "name": "deployed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "is_public_api": { + "name": "is_public_api", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "fork_sync_excluded": { + "name": "fork_sync_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_workspace_id_idx": { + "name": "workflow_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_user_workspace_idx": { + "name": "workflow_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_workspace_folder_name_active_unique": { + "name": "workflow_workspace_folder_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_folder_sort_idx": { + "name": "workflow_folder_sort_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_active_workspace_sort_idx": { + "name": "workflow_active_workspace_sort_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_archived_at_idx": { + "name": "workflow_archived_at_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_workspace_archived_partial_idx": { + "name": "workflow_workspace_archived_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_user_id_user_id_fk": { + "name": "workflow_user_id_user_id_fk", + "tableFrom": "workflow", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_workspace_id_workspace_id_fk": { + "name": "workflow_workspace_id_workspace_id_fk", + "tableFrom": "workflow", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_folder_id_folder_id_fk": { + "name": "workflow_folder_id_folder_id_fk", + "tableFrom": "workflow", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_activity_hourly": { + "name": "workflow_activity_hourly", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "runs": { + "name": "runs", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "completed": { + "name": "completed", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cancelled": { + "name": "cancelled", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "in_flight": { + "name": "in_flight", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "duration_sum_ms": { + "name": "duration_sum_ms", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "duration_count": { + "name": "duration_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "computed_at": { + "name": "computed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_activity_hourly_read_idx": { + "name": "workflow_activity_hourly_read_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "bucket_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "runs", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "completed", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "failed", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cancelled", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "in_flight", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "duration_sum_ms", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "duration_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_activity_hourly_bucket_start_idx": { + "name": "workflow_activity_hourly_bucket_start_idx", + "columns": [ + { + "expression": "bucket_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "workflow_activity_hourly_pk": { + "name": "workflow_activity_hourly_pk", + "columns": ["workspace_id", "bucket_start", "workflow_id", "trigger"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_blocks": { + "name": "workflow_blocks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position_x": { + "name": "position_x", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "position_y": { + "name": "position_y", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "horizontal_handles": { + "name": "horizontal_handles", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "is_wide": { + "name": "is_wide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "advanced_mode": { + "name": "advanced_mode", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "trigger_mode": { + "name": "trigger_mode", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "error_enabled": { + "name": "error_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "retry": { + "name": "retry", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "height": { + "name": "height", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "sub_blocks": { + "name": "sub_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "outputs": { + "name": "outputs", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_blocks_workflow_id_idx": { + "name": "workflow_blocks_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_blocks_type_idx": { + "name": "workflow_blocks_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_blocks_workflow_id_workflow_id_fk": { + "name": "workflow_blocks_workflow_id_workflow_id_fk", + "tableFrom": "workflow_blocks", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_checkpoints": { + "name": "workflow_checkpoints", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_state": { + "name": "workflow_state", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_checkpoints_chat_id_idx": { + "name": "workflow_checkpoints_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_message_id_idx": { + "name": "workflow_checkpoints_message_id_idx", + "columns": [ + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_user_workflow_idx": { + "name": "workflow_checkpoints_user_workflow_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_workflow_chat_idx": { + "name": "workflow_checkpoints_workflow_chat_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_created_at_idx": { + "name": "workflow_checkpoints_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_chat_created_at_idx": { + "name": "workflow_checkpoints_chat_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_checkpoints_user_id_user_id_fk": { + "name": "workflow_checkpoints_user_id_user_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_checkpoints_workflow_id_workflow_id_fk": { + "name": "workflow_checkpoints_workflow_id_workflow_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_checkpoints_chat_id_copilot_chats_id_fk": { + "name": "workflow_checkpoints_chat_id_copilot_chats_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_deployment_operation": { + "name": "workflow_deployment_operation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "previous_active_version_id": { + "name": "previous_active_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "protocol_version": { + "name": "protocol_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'preparing'" + }, + "component_readiness": { + "name": "component_readiness", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_deployment_operation_workflow_generation_unique": { + "name": "workflow_deployment_operation_workflow_generation_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_idempotency_unique": { + "name": "workflow_deployment_operation_workflow_idempotency_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_deployment_operation\".\"idempotency_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_in_flight_unique": { + "name": "workflow_deployment_operation_workflow_in_flight_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_deployment_operation\".\"status\" IN ('preparing', 'activating')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_status_idx": { + "name": "workflow_deployment_operation_workflow_status_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_deployment_version_idx": { + "name": "workflow_deployment_operation_deployment_version_idx", + "columns": [ + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_version_generation_idx": { + "name": "workflow_deployment_operation_workflow_version_generation_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_deployment_operation_workflow_id_workflow_id_fk": { + "name": "workflow_deployment_operation_workflow_id_workflow_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_deployment_operation_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_deployment_operation_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_deployment_operation_previous_active_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_deployment_operation_previous_active_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["previous_active_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workflow_deployment_operation_action_check": { + "name": "workflow_deployment_operation_action_check", + "value": "\"workflow_deployment_operation\".\"action\" IN ('deploy', 'activate')" + }, + "workflow_deployment_operation_status_check": { + "name": "workflow_deployment_operation_status_check", + "value": "\"workflow_deployment_operation\".\"status\" IN ('preparing', 'activating', 'active', 'failed', 'superseded')" + }, + "workflow_deployment_operation_generation_check": { + "name": "workflow_deployment_operation_generation_check", + "value": "\"workflow_deployment_operation\".\"generation\" > 0" + }, + "workflow_deployment_operation_protocol_version_check": { + "name": "workflow_deployment_operation_protocol_version_check", + "value": "\"workflow_deployment_operation\".\"protocol_version\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.workflow_deployment_version": { + "name": "workflow_deployment_version", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_deployment_version_workflow_version_unique": { + "name": "workflow_deployment_version_workflow_version_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_version_workflow_active_idx": { + "name": "workflow_deployment_version_workflow_active_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_version_created_at_idx": { + "name": "workflow_deployment_version_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_deployment_version_workflow_id_workflow_id_fk": { + "name": "workflow_deployment_version_workflow_id_workflow_id_fk", + "tableFrom": "workflow_deployment_version", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_edges": { + "name": "workflow_edges", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_block_id": { + "name": "source_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_block_id": { + "name": "target_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_handle": { + "name": "source_handle", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_handle": { + "name": "target_handle", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_edges_workflow_source_idx": { + "name": "workflow_edges_workflow_source_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_workflow_target_idx": { + "name": "workflow_edges_workflow_target_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_source_block_fk_idx": { + "name": "workflow_edges_source_block_fk_idx", + "columns": [ + { + "expression": "source_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_target_block_fk_idx": { + "name": "workflow_edges_target_block_fk_idx", + "columns": [ + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_edges_workflow_id_workflow_id_fk": { + "name": "workflow_edges_workflow_id_workflow_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_edges_source_block_id_workflow_blocks_id_fk": { + "name": "workflow_edges_source_block_id_workflow_blocks_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow_blocks", + "columnsFrom": ["source_block_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_edges_target_block_id_workflow_blocks_id_fk": { + "name": "workflow_edges_target_block_id_workflow_blocks_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow_blocks", + "columnsFrom": ["target_block_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_execution_logs": { + "name": "workflow_execution_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state_snapshot_id": { + "name": "state_snapshot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "execution_deadline_at": { + "name": "execution_deadline_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_duration_ms": { + "name": "total_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "execution_data": { + "name": "execution_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "cost_total": { + "name": "cost_total", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "models_used": { + "name": "models_used", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_execution_logs_state_snapshot_id_idx": { + "name": "workflow_execution_logs_state_snapshot_id_idx", + "columns": [ + { + "expression": "state_snapshot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_deployment_version_id_idx": { + "name": "workflow_execution_logs_deployment_version_id_idx", + "columns": [ + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_trigger_idx": { + "name": "workflow_execution_logs_trigger_idx", + "columns": [ + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_level_idx": { + "name": "workflow_execution_logs_level_idx", + "columns": [ + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_started_at_idx": { + "name": "workflow_execution_logs_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_execution_id_unique": { + "name": "workflow_execution_logs_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workflow_started_at_idx": { + "name": "workflow_execution_logs_workflow_started_at_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_activity_level_idx": { + "name": "workflow_execution_logs_workspace_activity_level_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "total_duration_ms", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_started_at_id_desc_idx": { + "name": "workflow_execution_logs_workspace_started_at_id_desc_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC NULLS LAST", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "\"id\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_cost_total_idx": { + "name": "workflow_execution_logs_workspace_cost_total_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost_total", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_models_used_idx": { + "name": "workflow_execution_logs_models_used_idx", + "columns": [ + { + "expression": "models_used", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "workflow_execution_logs_workspace_ended_at_id_idx": { + "name": "workflow_execution_logs_workspace_ended_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"ended_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_running_started_at_idx": { + "name": "workflow_execution_logs_running_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_running_deadline_idx": { + "name": "workflow_execution_logs_running_deadline_idx", + "columns": [ + { + "expression": "execution_deadline_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'running' AND \"workflow_execution_logs\".\"execution_deadline_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_redacting_started_at_idx": { + "name": "workflow_execution_logs_redacting_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'redacting'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_redacting_deadline_idx": { + "name": "workflow_execution_logs_redacting_deadline_idx", + "columns": [ + { + "expression": "execution_deadline_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'redacting' AND \"workflow_execution_logs\".\"execution_deadline_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_completed_ended_at_idx": { + "name": "workflow_execution_logs_completed_ended_at_idx", + "columns": [ + { + "expression": "ended_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'completed' AND \"workflow_execution_logs\".\"level\" = 'info' AND \"workflow_execution_logs\".\"ended_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_late_end_idx": { + "name": "workflow_execution_logs_late_end_idx", + "columns": [ + { + "expression": "ended_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"ended_at\" >= \"workflow_execution_logs\".\"started_at\" + interval '2 hours'", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_execution_logs_workflow_id_workflow_id_fk": { + "name": "workflow_execution_logs_workflow_id_workflow_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workflow_execution_logs_workspace_id_workspace_id_fk": { + "name": "workflow_execution_logs_workspace_id_workspace_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_execution_logs_state_snapshot_id_workflow_execution_snapshots_id_fk": { + "name": "workflow_execution_logs_state_snapshot_id_workflow_execution_snapshots_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow_execution_snapshots", + "columnsFrom": ["state_snapshot_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workflow_execution_logs_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_execution_logs_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_execution_snapshots": { + "name": "workflow_execution_snapshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state_hash": { + "name": "state_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state_data": { + "name": "state_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_snapshots_hash_idx": { + "name": "workflow_snapshots_hash_idx", + "columns": [ + { + "expression": "state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_snapshots_workflow_hash_idx": { + "name": "workflow_snapshots_workflow_hash_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_snapshots_created_at_idx": { + "name": "workflow_snapshots_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_execution_snapshots_workflow_id_workflow_id_fk": { + "name": "workflow_execution_snapshots_workflow_id_workflow_id_fk", + "tableFrom": "workflow_execution_snapshots", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_mcp_server": { + "name": "workflow_mcp_server", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_public": { + "name": "is_public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_mcp_server_workspace_id_idx": { + "name": "workflow_mcp_server_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_created_by_idx": { + "name": "workflow_mcp_server_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_deleted_at_idx": { + "name": "workflow_mcp_server_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_workspace_deleted_partial_idx": { + "name": "workflow_mcp_server_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_mcp_server\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_mcp_server_workspace_id_workspace_id_fk": { + "name": "workflow_mcp_server_workspace_id_workspace_id_fk", + "tableFrom": "workflow_mcp_server", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_mcp_server_created_by_user_id_fk": { + "name": "workflow_mcp_server_created_by_user_id_fk", + "tableFrom": "workflow_mcp_server", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_mcp_tool": { + "name": "workflow_mcp_tool", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "server_id": { + "name": "server_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_description": { + "name": "tool_description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parameter_schema": { + "name": "parameter_schema", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "parameter_description_overrides": { + "name": "parameter_description_overrides", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'::json" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_mcp_tool_server_id_idx": { + "name": "workflow_mcp_tool_server_id_idx", + "columns": [ + { + "expression": "server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_workflow_id_idx": { + "name": "workflow_mcp_tool_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_server_workflow_unique": { + "name": "workflow_mcp_tool_server_workflow_unique", + "columns": [ + { + "expression": "server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_mcp_tool\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_archived_at_partial_idx": { + "name": "workflow_mcp_tool_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_mcp_tool\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_mcp_tool_server_id_workflow_mcp_server_id_fk": { + "name": "workflow_mcp_tool_server_id_workflow_mcp_server_id_fk", + "tableFrom": "workflow_mcp_tool", + "tableTo": "workflow_mcp_server", + "columnsFrom": ["server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_mcp_tool_workflow_id_workflow_id_fk": { + "name": "workflow_mcp_tool_workflow_id_workflow_id_fk", + "tableFrom": "workflow_mcp_tool", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_schedule": { + "name": "workflow_schedule", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_operation_id": { + "name": "deployment_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cron_expression": { + "name": "cron_expression", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_ran_at": { + "name": "last_ran_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_queued_at": { + "name": "last_queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trigger_type": { + "name": "trigger_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'UTC'" + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "infra_retry_count": { + "name": "infra_retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "disabled_reason": { + "name": "disabled_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'workflow'" + }, + "job_title": { + "name": "job_title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'persistent'" + }, + "success_condition": { + "name": "success_condition", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "max_runs": { + "name": "max_runs", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "source_chat_id": { + "name": "source_chat_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_task_name": { + "name": "source_task_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_user_id": { + "name": "source_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_scope": { + "name": "secret_scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'all'" + }, + "mounted_secrets": { + "name": "mounted_secrets", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "job_history": { + "name": "job_history", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "contexts": { + "name": "contexts", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "excluded_dates": { + "name": "excluded_dates", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_budget_usd": { + "name": "run_budget_usd", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_schedule_workflow_block_deployment_unique": { + "name": "workflow_schedule_workflow_block_deployment_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_workflow_deployment_idx": { + "name": "workflow_schedule_workflow_deployment_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_archived_at_partial_idx": { + "name": "workflow_schedule_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_workflow_schedule_on_source_workspace_id_source_t_c07f3bba6": { + "name": "idx_workflow_schedule_on_source_workspace_id_source_t_c07f3bba6", + "columns": [ + { + "expression": "source_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_due_workflow_idx": { + "name": "workflow_schedule_due_workflow_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL AND \"workflow_schedule\".\"status\" NOT IN ('disabled', 'completed') AND (\"workflow_schedule\".\"source_type\" = 'workflow' OR \"workflow_schedule\".\"source_type\" IS NULL)", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_due_job_idx": { + "name": "workflow_schedule_due_job_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL AND \"workflow_schedule\".\"status\" NOT IN ('disabled', 'completed') AND \"workflow_schedule\".\"source_type\" = 'job'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_schedule_workflow_id_workflow_id_fk": { + "name": "workflow_schedule_workflow_id_workflow_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_schedule_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_deployment_operation_id_workflow_deployment_operation_id_fk": { + "name": "workflow_schedule_deployment_operation_id_workflow_deployment_operation_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow_deployment_operation", + "columnsFrom": ["deployment_operation_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workflow_schedule_source_user_id_user_id_fk": { + "name": "workflow_schedule_source_user_id_user_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "user", + "columnsFrom": ["source_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_source_workspace_id_workspace_id_fk": { + "name": "workflow_schedule_source_workspace_id_workspace_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workspace", + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_source_meta": { + "name": "workflow_source_meta", + "schema": "", + "columns": { + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "meta": { + "name": "meta", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workflow_source_meta_workflow_id_workflow_id_fk": { + "name": "workflow_source_meta_workflow_id_workflow_id_fk", + "tableFrom": "workflow_source_meta", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_subflows": { + "name": "workflow_subflows", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_subflows_workflow_type_idx": { + "name": "workflow_subflows_workflow_type_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_subflows_workflow_id_workflow_id_fk": { + "name": "workflow_subflows_workflow_id_workflow_id_fk", + "tableFrom": "workflow_subflows", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_test": { + "name": "workflow_test", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_file_id": { + "name": "body_file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cases": { + "name": "cases", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_test_workspace_name_unique": { + "name": "workflow_test_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_test\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_test_body_file_unique": { + "name": "workflow_test_body_file_unique", + "columns": [ + { + "expression": "body_file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_test_workspace_id_workspace_id_fk": { + "name": "workflow_test_workspace_id_workspace_id_fk", + "tableFrom": "workflow_test", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_body_file_id_workspace_files_id_fk": { + "name": "workflow_test_body_file_id_workspace_files_id_fk", + "tableFrom": "workflow_test", + "tableTo": "workspace_files", + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workflow_test_created_by_user_id_user_id_fk": { + "name": "workflow_test_created_by_user_id_user_id_fk", + "tableFrom": "workflow_test", + "tableTo": "user", + "columnsFrom": ["created_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_test_run": { + "name": "workflow_test_run", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "test_id": { + "name": "test_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "passed": { + "name": "passed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "skipped": { + "name": "skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "report": { + "name": "report", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ran_against": { + "name": "ran_against", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "progress": { + "name": "progress", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "triggered_by_actor": { + "name": "triggered_by_actor", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "triggered_by_user_id": { + "name": "triggered_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_test_run_test_version_started_idx": { + "name": "workflow_test_run_test_version_started_idx", + "columns": [ + { + "expression": "test_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_test_run_test_id_workflow_test_id_fk": { + "name": "workflow_test_run_test_id_workflow_test_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "workflow_test", + "columnsFrom": ["test_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_run_workspace_id_workspace_id_fk": { + "name": "workflow_test_run_workspace_id_workspace_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_run_triggered_by_user_id_user_id_fk": { + "name": "workflow_test_run_triggered_by_user_id_user_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "user", + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workflow_test_run_version_check": { + "name": "workflow_test_run_version_check", + "value": "\"workflow_test_run\".\"version\" IN ('draft', 'deployed')" + }, + "workflow_test_run_status_check": { + "name": "workflow_test_run_status_check", + "value": "\"workflow_test_run\".\"status\" IN ('running', 'passed', 'failed', 'error')" + }, + "workflow_test_run_completed_check": { + "name": "workflow_test_run_completed_check", + "value": "(\"workflow_test_run\".\"status\" = 'running') = (\"workflow_test_run\".\"completed_at\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workload_identity_pending_subject": { + "name": "workload_identity_pending_subject", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "workload_identity_pending_subject_subject_unique": { + "name": "workload_identity_pending_subject_subject_unique", + "columns": [ + { + "expression": "subject", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workload_identity_pending_subject_issuer_idx": { + "name": "workload_identity_pending_subject_issuer_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workload_identity_pending_subject_user_id_idx": { + "name": "workload_identity_pending_subject_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workload_identity_pending_subject_workspace_id_workspace_id_fk": { + "name": "workload_identity_pending_subject_workspace_id_workspace_id_fk", + "tableFrom": "workload_identity_pending_subject", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workload_identity_pending_subject_user_id_user_id_fk": { + "name": "workload_identity_pending_subject_user_id_user_id_fk", + "tableFrom": "workload_identity_pending_subject", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace": { + "name": "workspace", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'#33C482'" + }, + "logo_url": { + "name": "logo_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_scope_key": { + "name": "organization_scope_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END", + "type": "stored" + } + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_mode": { + "name": "workspace_mode", + "type": "workspace_mode", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'grandfathered_shared'" + }, + "billed_account_user_id": { + "name": "billed_account_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "allow_personal_api_keys": { + "name": "allow_personal_api_keys", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "inbox_enabled": { + "name": "inbox_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "inbox_address": { + "name": "inbox_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbox_provider_id": { + "name": "inbox_provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbox_secret_scope": { + "name": "inbox_secret_scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'all'" + }, + "inbox_mounted_secrets": { + "name": "inbox_mounted_secrets", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "organization_assigned_at": { + "name": "organization_assigned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "forked_from_workspace_id": { + "name": "forked_from_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fork_sync_new_workflows_excluded": { + "name": "fork_sync_new_workflows_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_owner_id_idx": { + "name": "workspace_owner_id_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_organization_id_idx": { + "name": "workspace_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_billed_account_user_id_idx": { + "name": "workspace_billed_account_user_id_idx", + "columns": [ + { + "expression": "billed_account_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_project_id_id_idx": { + "name": "workspace_project_id_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_mode_idx": { + "name": "workspace_mode_idx", + "columns": [ + { + "expression": "workspace_mode", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_forked_from_workspace_id_idx": { + "name": "workspace_forked_from_workspace_id_idx", + "columns": [ + { + "expression": "forked_from_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_inbox_provider_id_idx": { + "name": "workspace_inbox_provider_id_idx", + "columns": [ + { + "expression": "inbox_provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace\".\"inbox_provider_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_owner_id_user_id_fk": { + "name": "workspace_owner_id_user_id_fk", + "tableFrom": "workspace", + "tableTo": "user", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_organization_id_organization_id_fk": { + "name": "workspace_organization_id_organization_id_fk", + "tableFrom": "workspace", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_project_id_project_id_fk": { + "name": "workspace_project_id_project_id_fk", + "tableFrom": "workspace", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "workspace_billed_account_user_id_user_id_fk": { + "name": "workspace_billed_account_user_id_user_id_fk", + "tableFrom": "workspace", + "tableTo": "user", + "columnsFrom": ["billed_account_user_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workspace_forked_from_workspace_id_workspace_id_fk": { + "name": "workspace_forked_from_workspace_id_workspace_id_fk", + "tableFrom": "workspace", + "tableTo": "workspace", + "columnsFrom": ["forked_from_workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_project_organization_fk": { + "name": "workspace_project_organization_fk", + "tableFrom": "workspace", + "tableTo": "project", + "columnsFrom": ["project_id", "organization_scope_key"], + "columnsTo": ["id", "organization_scope_key"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workspace_fork_project_fk": { + "name": "workspace_fork_project_fk", + "tableFrom": "workspace", + "tableTo": "workspace", + "columnsFrom": ["forked_from_workspace_id", "project_id"], + "columnsTo": ["id", "project_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "workspace_id_project_unique": { + "name": "workspace_id_project_unique", + "nullsNotDistinct": false, + "columns": ["id", "project_id"] + } + }, + "policies": {}, + "checkConstraints": { + "workspace_storage_used_bytes_non_negative": { + "name": "workspace_storage_used_bytes_non_negative", + "value": "\"workspace\".\"storage_used_bytes\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.workspace_byok_keys": { + "name": "workspace_byok_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_byok_workspace_provider_idx": { + "name": "workspace_byok_workspace_provider_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_byok_keys_workspace_id_workspace_id_fk": { + "name": "workspace_byok_keys_workspace_id_workspace_id_fk", + "tableFrom": "workspace_byok_keys", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_byok_keys_created_by_user_id_fk": { + "name": "workspace_byok_keys_created_by_user_id_fk", + "tableFrom": "workspace_byok_keys", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_environment": { + "name": "workspace_environment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_environment_workspace_unique": { + "name": "workspace_environment_workspace_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_environment_workspace_id_workspace_id_fk": { + "name": "workspace_environment_workspace_id_workspace_id_fk", + "tableFrom": "workspace_environment", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file": { + "name": "workspace_file", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_file_workspace_id_idx": { + "name": "workspace_file_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_deleted_at_idx": { + "name": "workspace_file_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_workspace_deleted_partial_idx": { + "name": "workspace_file_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_uploaded_by_idx": { + "name": "workspace_file_uploaded_by_idx", + "columns": [ + { + "expression": "uploaded_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_workspace_id_workspace_id_fk": { + "name": "workspace_file_workspace_id_workspace_id_fk", + "tableFrom": "workspace_file", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_uploaded_by_user_id_fk": { + "name": "workspace_file_uploaded_by_user_id_fk", + "tableFrom": "workspace_file", + "tableTo": "user", + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "workspace_file_key_unique": { + "name": "workspace_file_key_unique", + "nullsNotDistinct": false, + "columns": ["key"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_collab_state": { + "name": "workspace_file_collab_state", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "doc_state": { + "name": "doc_state", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_file_collab_state_file_id_workspace_files_id_fk": { + "name": "workspace_file_collab_state_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_collab_state", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_search_backfill": { + "name": "workspace_file_search_backfill", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "after_workspace_id": { + "name": "after_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_entity_type": { + "name": "after_entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_entity_id": { + "name": "after_entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_file_id": { + "name": "after_file_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_search_build": { + "name": "workspace_file_search_build", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "artifact_key": { + "name": "artifact_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_file_search_build_file_idx": { + "name": "workspace_file_search_build_file_idx", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_build_cleanup_idx": { + "name": "workspace_file_search_build_cleanup_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_build\".\"expires_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_build_owner_check": { + "name": "file_search_build_owner_check", + "value": "(\"workspace_file_search_build\".\"entity_type\" IS NULL AND \"workspace_file_search_build\".\"entity_id\" IS NULL AND \"workspace_file_search_build\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_build\".\"entity_type\" = 'workspace' AND \"workspace_file_search_build\".\"entity_id\" = \"workspace_file_search_build\".\"workspace_id\") OR (\"workspace_file_search_build\".\"entity_type\" = 'project' AND length(\"workspace_file_search_build\".\"entity_id\") > 0 AND \"workspace_file_search_build\".\"workspace_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_search_chunk": { + "name": "workspace_file_search_chunk", + "schema": "", + "columns": { + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "line_start": { + "name": "line_start", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "fragment": { + "name": "fragment", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "overlap": { + "name": "overlap", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "file_search_chunk_owner_content_idx": { + "name": "file_search_chunk_owner_content_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "content", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_chunk\".\"entity_type\" = 'project'", + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "workspace_file_search_chunk_line_idx": { + "name": "workspace_file_search_chunk_line_idx", + "columns": [ + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "line_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ordinal", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_chunk_content_idx": { + "name": "workspace_file_search_chunk_content_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "content", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + } + }, + "foreignKeys": { + "workspace_file_search_chunk_build_id_workspace_file_search_build_id_fk": { + "name": "workspace_file_search_chunk_build_id_workspace_file_search_build_id_fk", + "tableFrom": "workspace_file_search_chunk", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_file_search_chunk_pk": { + "name": "workspace_file_search_chunk_pk", + "columns": ["build_id", "ordinal"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_chunk_owner_check": { + "name": "file_search_chunk_owner_check", + "value": "(\"workspace_file_search_chunk\".\"entity_type\" IS NULL AND \"workspace_file_search_chunk\".\"entity_id\" IS NULL AND \"workspace_file_search_chunk\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_chunk\".\"entity_type\" = 'workspace' AND \"workspace_file_search_chunk\".\"entity_id\" = \"workspace_file_search_chunk\".\"workspace_id\") OR (\"workspace_file_search_chunk\".\"entity_type\" = 'project' AND length(\"workspace_file_search_chunk\".\"entity_id\") > 0 AND \"workspace_file_search_chunk\".\"workspace_id\" IS NULL)" + }, + "workspace_file_search_chunk_content_size": { + "name": "workspace_file_search_chunk_content_size", + "value": "octet_length(\"workspace_file_search_chunk\".\"content\") <= 8192" + }, + "workspace_file_search_chunk_position": { + "name": "workspace_file_search_chunk_position", + "value": "\"workspace_file_search_chunk\".\"ordinal\" >= 0 AND \"workspace_file_search_chunk\".\"line_start\" > 0 AND \"workspace_file_search_chunk\".\"overlap\" BETWEEN 0 AND 2" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_search_revision": { + "name": "workspace_file_search_revision", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "workspace_file_search_index_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "line_count": { + "name": "line_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "indexed_bytes": { + "name": "indexed_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "dispatched_at": { + "name": "dispatched_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "handoff_expires_at": { + "name": "handoff_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "build_started_at": { + "name": "build_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "abandoned_builds": { + "name": "abandoned_builds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_build_artifact_key": { + "name": "last_build_artifact_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "file_search_revision_owner_pending_idx": { + "name": "file_search_revision_owner_pending_idx", + "columns": [ + { + "expression": "coalesce(\"entity_type\", 'workspace')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"entity_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_content_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "file_search_revision_owner_status_idx": { + "name": "file_search_revision_owner_status_idx", + "columns": [ + { + "expression": "coalesce(\"entity_type\", 'workspace')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"entity_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_workspace_status_idx": { + "name": "workspace_file_search_revision_workspace_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_build_idx": { + "name": "workspace_file_search_revision_build_idx", + "columns": [ + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_pending_idx": { + "name": "workspace_file_search_revision_pending_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_content_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_active_idx": { + "name": "workspace_file_search_revision_active_idx", + "columns": [ + { + "expression": "dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_search_revision_file_id_workspace_files_id_fk": { + "name": "workspace_file_search_revision_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_search_revision", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_search_revision_build_id_workspace_file_search_build_id_fk": { + "name": "workspace_file_search_revision_build_id_workspace_file_search_build_id_fk", + "tableFrom": "workspace_file_search_revision", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_revision_owner_check": { + "name": "file_search_revision_owner_check", + "value": "(\"workspace_file_search_revision\".\"entity_type\" IS NULL AND \"workspace_file_search_revision\".\"entity_id\" IS NULL AND \"workspace_file_search_revision\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_revision\".\"entity_type\" = 'workspace' AND \"workspace_file_search_revision\".\"entity_id\" = \"workspace_file_search_revision\".\"workspace_id\") OR (\"workspace_file_search_revision\".\"entity_type\" = 'project' AND length(\"workspace_file_search_revision\".\"entity_id\") > 0 AND \"workspace_file_search_revision\".\"workspace_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_secret_provenance": { + "name": "workspace_file_secret_provenance", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_file_secret_provenance_file_id_workspace_files_id_fk": { + "name": "workspace_file_secret_provenance_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_secret_provenance", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_file_secret_provenance_status_check": { + "name": "workspace_file_secret_provenance_status_check", + "value": "\"workspace_file_secret_provenance\".\"status\" IN ('exact', 'unknown', 'unrecorded')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_version": { + "name": "workspace_file_version", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "superseded_at": { + "name": "superseded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "workspace_file_version_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "author_user_ids": { + "name": "author_user_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "restored_from_version": { + "name": "restored_from_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_status": { + "name": "secret_provenance_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_entries": { + "name": "secret_provenance_entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_file_version_file_version_unique": { + "name": "workspace_file_version_file_version_unique", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_key_unique": { + "name": "workspace_file_version_key_unique", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_workspace_id_idx": { + "name": "workspace_file_version_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_workspace_superseded_idx": { + "name": "workspace_file_version_workspace_superseded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "superseded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_version\".\"superseded_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_version_file_id_workspace_files_id_fk": { + "name": "workspace_file_version_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_version", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_version_workspace_id_workspace_id_fk": { + "name": "workspace_file_version_workspace_id_workspace_id_fk", + "tableFrom": "workspace_file_version", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_file_version_provenance_status_check": { + "name": "workspace_file_version_provenance_status_check", + "value": "\"workspace_file_version\".\"secret_provenance_status\" IS NULL OR \"workspace_file_version\".\"secret_provenance_status\" IN ('exact', 'unknown', 'unrecorded')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_files": { + "name": "workspace_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "context": { + "name": "context", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "original_name": { + "name": "original_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "date_trunc('milliseconds', now())" + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_files_project_id_idx": { + "name": "workspace_files_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_project_folder_name_active_unique": { + "name": "workspace_files_project_folder_name_active_unique", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"project_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_key_active_unique": { + "name": "workspace_files_key_active_unique", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_folder_name_active_unique": { + "name": "workspace_files_workspace_folder_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_search_owner_keyset_idx": { + "name": "workspace_files_search_owner_keyset_idx", + "columns": [ + { + "expression": "(CASE WHEN \"project_id\" IS NOT NULL THEN 'project' ELSE 'workspace' END)", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"project_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND ((\"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL) OR (\"workspace_files\".\"context\" = 'project' AND \"workspace_files\".\"project_id\" IS NOT NULL))", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_keyset_idx": { + "name": "workspace_files_workspace_active_keyset_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_uploaded_idx": { + "name": "workspace_files_workspace_active_uploaded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_updated_idx": { + "name": "workspace_files_workspace_active_updated_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_folder_uploaded_idx": { + "name": "workspace_files_workspace_folder_uploaded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_name_trgm_idx": { + "name": "workspace_files_workspace_name_trgm_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "workspace_files_workspace_display_name_idx": { + "name": "workspace_files_workspace_display_name_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "regexp_replace(regexp_replace(regexp_replace(normalize(\"original_name\", NFC), '^[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+|[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+$', '', 'g'), '[\\x01-\\x1f\\x7f]', '', 'g'), '[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+', ' ', 'g')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_chat_display_name_unique": { + "name": "workspace_files_chat_display_name_unique", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"context\" = 'mothership' AND \"workspace_files\".\"chat_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_organization_id_idx": { + "name": "workspace_files_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_key_idx": { + "name": "workspace_files_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_user_id_idx": { + "name": "workspace_files_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_id_idx": { + "name": "workspace_files_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_folder_id_idx": { + "name": "workspace_files_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_context_idx": { + "name": "workspace_files_context_idx", + "columns": [ + { + "expression": "context", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_chat_id_idx": { + "name": "workspace_files_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_deleted_at_idx": { + "name": "workspace_files_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_deleted_partial_idx": { + "name": "workspace_files_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_files_project_id_project_id_fk": { + "name": "workspace_files_project_id_project_id_fk", + "tableFrom": "workspace_files", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "workspace_files_user_id_user_id_fk": { + "name": "workspace_files_user_id_user_id_fk", + "tableFrom": "workspace_files", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_workspace_id_workspace_id_fk": { + "name": "workspace_files_workspace_id_workspace_id_fk", + "tableFrom": "workspace_files", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_organization_id_organization_id_fk": { + "name": "workspace_files_organization_id_organization_id_fk", + "tableFrom": "workspace_files", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_folder_id_folder_id_fk": { + "name": "workspace_files_folder_id_folder_id_fk", + "tableFrom": "workspace_files", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_files_chat_id_copilot_chats_id_fk": { + "name": "workspace_files_chat_id_copilot_chats_id_fk", + "tableFrom": "workspace_files", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_files_owner_check": { + "name": "workspace_files_owner_check", + "value": "num_nonnulls(\"workspace_files\".\"workspace_id\", \"workspace_files\".\"project_id\", \"workspace_files\".\"organization_id\") <= 1" + }, + "workspace_files_workspace_binding_check": { + "name": "workspace_files_workspace_binding_check", + "value": "\"workspace_files\".\"context\" NOT IN ('workspace', 'chat', 'mothership', 'execution', 'workspace-logos') OR \"workspace_files\".\"workspace_id\" IS NOT NULL" + }, + "workspace_files_project_binding_check": { + "name": "workspace_files_project_binding_check", + "value": "(\"workspace_files\".\"project_id\" IS NOT NULL) = (\"workspace_files\".\"context\" = 'project') AND (\"workspace_files\".\"project_id\" IS NULL OR \"workspace_files\".\"chat_id\" IS NULL)" + }, + "workspace_files_organization_binding_check": { + "name": "workspace_files_organization_binding_check", + "value": "\"workspace_files\".\"organization_id\" IS NULL OR (\"workspace_files\".\"workspace_id\" IS NULL AND \"workspace_files\".\"context\" = 'knowledge-base' AND \"workspace_files\".\"folder_id\" IS NULL AND \"workspace_files\".\"chat_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_fork_block_map": { + "name": "workspace_fork_block_map", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_workflow_id": { + "name": "parent_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_block_id": { + "name": "parent_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_workflow_id": { + "name": "child_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_block_id": { + "name": "child_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_block_map_child_ws_parent_unique": { + "name": "workspace_fork_block_map_child_ws_parent_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_child_unique": { + "name": "workspace_fork_block_map_child_ws_child_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_parent_wf_idx": { + "name": "workspace_fork_block_map_child_ws_parent_wf_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_child_wf_idx": { + "name": "workspace_fork_block_map_child_ws_child_wf_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_block_map_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_block_map_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_block_map", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_dependent_value": { + "name": "workspace_fork_dependent_value", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workflow_id": { + "name": "target_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_block_id": { + "name": "target_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sub_block_key": { + "name": "sub_block_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_dependent_value_field_unique": { + "name": "workspace_fork_dependent_value_field_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sub_block_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_dependent_value_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_dependent_value_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_dependent_value", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_promote_run": { + "name": "workspace_fork_promote_run", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workspace_id": { + "name": "target_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "direction": { + "name": "direction", + "type": "workspace_fork_promote_direction", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "snapshot": { + "name": "snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_promote_run_child_ws_target_unique": { + "name": "workspace_fork_promote_run_child_ws_target_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_promote_run_target_ws_idx": { + "name": "workspace_fork_promote_run_target_ws_idx", + "columns": [ + { + "expression": "target_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_promote_run_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_promote_run_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_promote_run", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_promote_run_created_by_user_id_fk": { + "name": "workspace_fork_promote_run_created_by_user_id_fk", + "tableFrom": "workspace_fork_promote_run", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_resource_map": { + "name": "workspace_fork_resource_map", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "workspace_fork_resource_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "parent_resource_id": { + "name": "parent_resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_resource_id": { + "name": "child_resource_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_resource_map_child_type_parent_unique": { + "name": "workspace_fork_resource_map_child_type_parent_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_resource_map_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_resource_map_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_resource_map", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_resource_map_created_by_user_id_fk": { + "name": "workspace_fork_resource_map_created_by_user_id_fk", + "tableFrom": "workspace_fork_resource_map", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_workflow_sync": { + "name": "workspace_fork_workflow_sync", + "schema": "", + "columns": { + "deployment_operation_id": { + "name": "deployment_operation_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_workflow_id": { + "name": "source_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workflow_id": { + "name": "target_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_deployment_version_id": { + "name": "source_deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sequence": { + "name": "sequence", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "workspace_fork_workflow_sync_sequence_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "promote_run_id": { + "name": "promote_run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "activated_at": { + "name": "activated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "rollback_operation_id": { + "name": "rollback_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rolled_back_at": { + "name": "rolled_back_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_fork_workflow_sync_baseline_idx": { + "name": "workspace_fork_workflow_sync_baseline_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sequence", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_fork_workflow_sync\".\"activated_at\" IS NOT NULL AND \"workspace_fork_workflow_sync\".\"rolled_back_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_run_idx": { + "name": "workspace_fork_workflow_sync_run_idx", + "columns": [ + { + "expression": "promote_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_rollback_idx": { + "name": "workspace_fork_workflow_sync_rollback_idx", + "columns": [ + { + "expression": "rollback_operation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_fork_workflow_sync\".\"rollback_operation_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_source_idx": { + "name": "workspace_fork_workflow_sync_source_idx", + "columns": [ + { + "expression": "source_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_target_idx": { + "name": "workspace_fork_workflow_sync_target_idx", + "columns": [ + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_child_workspace_idx": { + "name": "workspace_fork_workflow_sync_child_workspace_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_workflow_sync_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_workflow_sync_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_workflow_sync_source_workflow_id_workflow_id_fk": { + "name": "workspace_fork_workflow_sync_source_workflow_id_workflow_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workflow", + "columnsFrom": ["source_workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_workflow_sync_target_workflow_id_workflow_id_fk": { + "name": "workspace_fork_workflow_sync_target_workflow_id_workflow_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workflow", + "columnsFrom": ["target_workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_operation_receipt": { + "name": "workspace_operation_receipt", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "report": { + "name": "report", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_operation_receipt_request_unique": { + "name": "workspace_operation_receipt_request_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_operation_receipt_workspace_created_idx": { + "name": "workspace_operation_receipt_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_operation_receipt_workspace_id_workspace_id_fk": { + "name": "workspace_operation_receipt_workspace_id_workspace_id_fk", + "tableFrom": "workspace_operation_receipt", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_resource_key": { + "name": "workspace_resource_key", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "workspace_resource_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_resource_key_ws_kind_key_unique": { + "name": "workspace_resource_key_ws_kind_key_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_resource_key_ws_kind_resource_unique": { + "name": "workspace_resource_key_ws_kind_resource_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_resource_key_workspace_id_workspace_id_fk": { + "name": "workspace_resource_key_workspace_id_workspace_id_fk", + "tableFrom": "workspace_resource_key", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_resource_key_created_by_user_id_fk": { + "name": "workspace_resource_key_created_by_user_id_fk", + "tableFrom": "workspace_resource_key", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_resource_key_key_format": { + "name": "workspace_resource_key_key_format", + "value": "\"workspace_resource_key\".\"key\" ~ '^[a-z][a-z0-9_-]{0,63}$'" + }, + "workspace_resource_key_origin_check": { + "name": "workspace_resource_key_origin_check", + "value": "\"workspace_resource_key\".\"origin\" IN ('allocated', 'adopted', 'created')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_sandbox": { + "name": "workspace_sandbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "language": { + "name": "language", + "type": "sandbox_language", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "dependencies": { + "name": "dependencies", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "cli_tools": { + "name": "cli_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "system_packages": { + "name": "system_packages", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "spec_hash": { + "name": "spec_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_sandbox_workspace_name_unique": { + "name": "workspace_sandbox_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_sandbox_spec_hash_idx": { + "name": "workspace_sandbox_spec_hash_idx", + "columns": [ + { + "expression": "spec_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_sandbox_workspace_id_workspace_id_fk": { + "name": "workspace_sandbox_workspace_id_workspace_id_fk", + "tableFrom": "workspace_sandbox", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_sandbox_created_by_user_id_fk": { + "name": "workspace_sandbox_created_by_user_id_fk", + "tableFrom": "workspace_sandbox", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_source_apply_lease": { + "name": "workspace_source_apply_lease", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "acquired_at": { + "name": "acquired_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_source_apply_lease_workspace_id_workspace_id_fk": { + "name": "workspace_source_apply_lease_workspace_id_workspace_id_fk", + "tableFrom": "workspace_source_apply_lease", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_source_staged_blob": { + "name": "workspace_source_staged_blob", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "consumed_at": { + "name": "consumed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_source_staged_blob_scope_hash_unique": { + "name": "workspace_source_staged_blob_scope_hash_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sha256", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_source_staged_blob_expires_at_idx": { + "name": "workspace_source_staged_blob_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_source_staged_blob_workspace_id_workspace_id_fk": { + "name": "workspace_source_staged_blob_workspace_id_workspace_id_fk", + "tableFrom": "workspace_source_staged_blob", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_visit": { + "name": "workspace_visit", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visited_at": { + "name": "visited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_visit_workspace_idx": { + "name": "workspace_visit_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_visit_user_id_user_id_fk": { + "name": "workspace_visit_user_id_user_id_fk", + "tableFrom": "workspace_visit", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_visit_workspace_id_workspace_id_fk": { + "name": "workspace_visit_workspace_id_workspace_id_fk", + "tableFrom": "workspace_visit", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_visit_user_id_workspace_id_pk": { + "name": "workspace_visit_user_id_workspace_id_pk", + "columns": ["user_id", "workspace_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.api_key_access": { + "name": "api_key_access", + "schema": "public", + "values": ["read", "write"] + }, + "public.aws_marketplace_license_status": { + "name": "aws_marketplace_license_status", + "schema": "public", + "values": ["pending", "active", "inactive"] + }, + "public.aws_marketplace_usage_report_status": { + "name": "aws_marketplace_usage_report_status", + "schema": "public", + "values": ["pending", "reported", "rejected"] + }, + "public.background_work_kind": { + "name": "background_work_kind", + "schema": "public", + "values": ["deployment_side_effects", "fork_content_copy", "fork_sync", "fork_rollback"] + }, + "public.background_work_status_value": { + "name": "background_work_status_value", + "schema": "public", + "values": ["pending", "processing", "completed", "completed_with_warnings", "failed"] + }, + "public.billing_blocked_reason": { + "name": "billing_blocked_reason", + "schema": "public", + "values": ["payment_failed", "dispute"] + }, + "public.billing_entity_type": { + "name": "billing_entity_type", + "schema": "public", + "values": ["user", "organization"] + }, + "public.chat_type": { + "name": "chat_type", + "schema": "public", + "values": ["mothership", "copilot"] + }, + "public.copilot_async_tool_status": { + "name": "copilot_async_tool_status", + "schema": "public", + "values": ["pending", "running", "completed", "failed", "cancelled", "delivered"] + }, + "public.copilot_run_status": { + "name": "copilot_run_status", + "schema": "public", + "values": ["active", "paused_waiting_for_tool", "resuming", "complete", "error", "cancelled"] + }, + "public.copilot_tool_permission_decision": { + "name": "copilot_tool_permission_decision", + "schema": "public", + "values": ["allow", "allow_chat", "always_allow", "skip"] + }, + "public.credential_group_enrollment_status": { + "name": "credential_group_enrollment_status", + "schema": "public", + "values": ["invited", "delivery_failed", "in_progress", "completed", "revoked"] + }, + "public.credential_group_status": { + "name": "credential_group_status", + "schema": "public", + "values": ["active", "disabled"] + }, + "public.credential_member_role": { + "name": "credential_member_role", + "schema": "public", + "values": ["admin", "member"] + }, + "public.credential_member_status": { + "name": "credential_member_status", + "schema": "public", + "values": ["active", "pending", "revoked"] + }, + "public.credential_type": { + "name": "credential_type", + "schema": "public", + "values": [ + "oauth", + "managed_oauth", + "managed_mcp", + "env_workspace", + "env_personal", + "service_account", + "personal_token" + ] + }, + "public.data_drain_cadence": { + "name": "data_drain_cadence", + "schema": "public", + "values": ["every_15_minutes", "hourly", "daily"] + }, + "public.data_drain_destination": { + "name": "data_drain_destination", + "schema": "public", + "values": [ + "s3", + "gcs", + "azure_blob", + "sentinel", + "datadog", + "splunk", + "bigquery", + "snowflake", + "webhook" + ] + }, + "public.data_drain_run_status": { + "name": "data_drain_run_status", + "schema": "public", + "values": ["running", "success", "failed"] + }, + "public.data_drain_run_trigger": { + "name": "data_drain_run_trigger", + "schema": "public", + "values": ["cron", "manual"] + }, + "public.data_drain_source": { + "name": "data_drain_source", + "schema": "public", + "values": ["workflow_logs", "job_logs", "audit_logs", "copilot_chats", "copilot_runs"] + }, + "public.execution_large_value_reference_source": { + "name": "execution_large_value_reference_source", + "schema": "public", + "values": ["execution_log", "paused_snapshot"] + }, + "public.folder_resource_type": { + "name": "folder_resource_type", + "schema": "public", + "values": ["workflow", "file", "knowledge_base", "table"] + }, + "public.invitation_kind": { + "name": "invitation_kind", + "schema": "public", + "values": ["organization", "workspace"] + }, + "public.invitation_membership_intent": { + "name": "invitation_membership_intent", + "schema": "public", + "values": ["internal", "external"] + }, + "public.invitation_status": { + "name": "invitation_status", + "schema": "public", + "values": ["pending", "accepted", "rejected", "cancelled", "expired"] + }, + "public.managed_oauth_credential_status": { + "name": "managed_oauth_credential_status", + "schema": "public", + "values": ["active", "needs_reauth", "revoked"] + }, + "public.permission_type": { + "name": "permission_type", + "schema": "public", + "values": ["admin", "write", "read"] + }, + "public.sandbox_image_status": { + "name": "sandbox_image_status", + "schema": "public", + "values": ["pending", "building", "ready", "failed"] + }, + "public.sandbox_language": { + "name": "sandbox_language", + "schema": "public", + "values": ["javascript", "python"] + }, + "public.secret_usage_scope": { + "name": "secret_usage_scope", + "schema": "public", + "values": ["workspace", "personal"] + }, + "public.secret_usage_source": { + "name": "secret_usage_source", + "schema": "public", + "values": ["workflow", "copilot", "mcp"] + }, + "public.upload_session_method": { + "name": "upload_session_method", + "schema": "public", + "values": ["put", "multipart"] + }, + "public.upload_session_provider": { + "name": "upload_session_provider", + "schema": "public", + "values": ["local", "s3", "blob", "gcs"] + }, + "public.upload_session_purpose": { + "name": "upload_session_purpose", + "schema": "public", + "values": [ + "workspace_file", + "project_file", + "table_import", + "knowledge_import", + "knowledge_document", + "profile_picture", + "workspace_logo", + "organization_logo", + "mothership_attachment", + "execution_attachment" + ] + }, + "public.upload_session_status": { + "name": "upload_session_status", + "schema": "public", + "values": [ + "uploading", + "completing", + "finalizing", + "completed", + "aborting", + "aborted", + "failed", + "expired" + ] + }, + "public.usage_log_category": { + "name": "usage_log_category", + "schema": "public", + "values": ["model", "fixed", "tool", "model_unbilled"] + }, + "public.usage_log_source": { + "name": "usage_log_source", + "schema": "public", + "values": [ + "workflow", + "wand", + "copilot", + "workspace-chat", + "mcp_copilot", + "mothership_block", + "knowledge-base", + "voice-input", + "enrichment", + "voice-output", + "api-tool", + "workflow-test" + ] + }, + "public.workspace_file_search_index_status": { + "name": "workspace_file_search_index_status", + "schema": "public", + "values": ["pending", "ready", "skipped", "failed"] + }, + "public.workspace_file_version_source": { + "name": "workspace_file_version_source", + "schema": "public", + "values": ["upload", "user", "api", "copilot", "workflow", "collab", "revert", "unknown"] + }, + "public.workspace_fork_promote_direction": { + "name": "workspace_fork_promote_direction", + "schema": "public", + "values": ["push", "pull"] + }, + "public.workspace_fork_resource_type": { + "name": "workspace_fork_resource_type", + "schema": "public", + "values": [ + "workflow", + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "knowledge_document", + "file", + "file_folder", + "mcp_server", + "workflow_mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ] + }, + "public.workspace_mode": { + "name": "workspace_mode", + "schema": "public", + "values": ["personal", "organization", "grandfathered_shared"] + }, + "public.workspace_resource_kind": { + "name": "workspace_resource_kind", + "schema": "public", + "values": [ + "credential", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ] + } + }, + "schemas": {}, + "sequences": { + "public.copilot_async_tool_calls_persist_seq": { + "name": "copilot_async_tool_calls_persist_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 1f746538122..df04a1de462 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -3417,6 +3417,13 @@ "when": 1796283260143, "tag": "0488_people_manager_matching", "breakpoints": true + }, + { + "idx": 489, + "version": "7", + "when": 1796325583945, + "tag": "0489_credential_group_workflow_requests", + "breakpoints": true } ] } diff --git a/packages/db/schema.ts b/packages/db/schema.ts index 9ed28fef08a..f35bdbebe8d 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7421,6 +7421,8 @@ export const credentialGroupEnrollment = pgTable( revokedAt: timestamp('revoked_at'), lastDeliveryError: text('last_delivery_error'), createdBy: text('created_by').references(() => user.id, { onDelete: 'set null' }), + /** Set when a workflow's connection request created the row; admin invitations leave it null. */ + requestedByWorkflowId: text('requested_by_workflow_id'), createdAt: timestamp('created_at').notNull().defaultNow(), updatedAt: timestamp('updated_at').notNull().defaultNow(), }, diff --git a/packages/testing/src/mocks/schema-tables.generated.ts b/packages/testing/src/mocks/schema-tables.generated.ts index 3992fff9994..da28ec84c67 100644 --- a/packages/testing/src/mocks/schema-tables.generated.ts +++ b/packages/testing/src/mocks/schema-tables.generated.ts @@ -1875,6 +1875,7 @@ export const GENERATED_SCHEMA_TABLES = { 'revokedAt', 'lastDeliveryError', 'createdBy', + 'requestedByWorkflowId', 'createdAt', 'updatedAt', ], From 0fe496b955042b52ff930166a7e3cd7148c359c7 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 13:40:01 -0600 Subject: [PATCH 05/26] feat(credential-groups): connect page, focused links, auto-complete - /credential-groups//connect resolves the signed-in, verified person's own enrollment (resolveCredentialGroupConnectTarget, session operation credential_groups.connect.resolve) and mints a one-hour 'connect' link focused on the single matching option, then hands off to the enroll page. Outcomes: ready, wrong_account, not_invited, revoked, choose_option, unavailable (unknown ID, disabled group, entitlement off and unoffered provider answer identically). Organization members with no enrollment go through member self-enroll. `provider` is the credential provider ID; `return=slack` opens slack://open, other values must pass the Slack allowlist. The session is the authority, so an unbound enrollment whose invitation expired (or that a workflow requested with no link) still connects. Per-IP and per-user rate limits. - Focused links are enforced server-side: OAuth start/complete for another option and MCP start/complete are refused (CredentialGroupLinkFocusError, redirected with oauth=other_option), and the enroll page shows only the focused option with no Submit. - A connection saved through a focused link completes the enrollment and fires form_submitted once, through the same path as Submit. - findCredentialGroupEnrollmentLinkRecord resolves through the link table (legacy column fallback as liveEnrollmentLinkCondition), so revoked and expired links are explained; a link revoked by a disconnect on a live enrollment reads "Link no longer active". - lib/credential-groups/connect-url.ts (shared with W3), publicId in the org accounts response, and a "Copy connect link" menu on the People tab. - Unavailable / wrong-account states lifted into app/credential-groups/link-states.tsx. --- .../enroll/[token]/mcp/[mcpServerId]/route.ts | 3 + .../enroll/[token]/oauth/[optionId]/route.ts | 7 +- .../[publicId]/connect/page.tsx | 159 +++++ .../credential-groups/enroll/[token]/page.tsx | 93 +-- .../sim/app/credential-groups/link-states.tsx | 81 +++ .../organization-account-people.tsx | 73 ++- .../organization-account-providers.test.tsx | 1 + .../organization-connected-accounts.tsx | 4 +- .../api/contracts/organization-accounts.ts | 1 + .../connect-target.integration.ts | 563 ++++++++++++++++++ .../enrollment-link-outcome.integration.ts | 64 +- .../application/connect-target.ts | 161 +++++ .../application/enrollment-link-outcome.ts | 11 +- .../application/public-enrollment.test.ts | 1 + .../application/public-enrollment.ts | 90 ++- apps/sim/lib/credential-groups/connect-url.ts | 19 + apps/sim/lib/credential-groups/enrollments.ts | 162 ++++- .../organization-account-options.test.ts | 1 + .../lib/credential-groups/provider-adapter.ts | 9 + apps/sim/lib/credential-groups/rate-limit.ts | 16 + apps/sim/lib/credential-groups/service.ts | 1 + apps/sim/lib/credential-groups/types.ts | 2 + .../credential-groups-enrollments.mock.ts | 13 +- 23 files changed, 1430 insertions(+), 105 deletions(-) create mode 100644 apps/sim/app/credential-groups/[publicId]/connect/page.tsx create mode 100644 apps/sim/app/credential-groups/link-states.tsx create mode 100644 apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts create mode 100644 apps/sim/lib/credential-groups/application/connect-target.ts create mode 100644 apps/sim/lib/credential-groups/connect-url.ts diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts index 2fc0ce969b0..a556c5cc6d4 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts @@ -7,6 +7,7 @@ import { parseRequest } from '@/lib/api/server' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { authenticateCredentialGroupEnrollment } from '@/lib/credential-groups/application/enrollment-auth' import { startPublicCredentialGroupMcpOAuth } from '@/lib/credential-groups/application/public-enrollment' +import { CredentialGroupLinkFocusError } from '@/lib/credential-groups/provider-adapter' import { enforceCredentialGroupEnrollmentOAuthRateLimit, enforcePublicCredentialGroupOAuthStartIpRateLimit, @@ -59,6 +60,8 @@ export const GET = withRouteHandler( response.headers.set('Referrer-Policy', 'no-referrer') return response } catch (error) { + if (error instanceof CredentialGroupLinkFocusError) + return createCredentialGroupEnrollmentRedirect(token, { oauth: 'other_option' }) logger.error('Failed to start managed MCP OAuth authorization', { error: getErrorMessage(error), }) diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts index 51715c3c988..ec10d2eadc5 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts @@ -7,7 +7,10 @@ import { parseRequest } from '@/lib/api/server' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { authenticateCredentialGroupEnrollment } from '@/lib/credential-groups/application/enrollment-auth' import { startPublicCredentialGroupOAuth } from '@/lib/credential-groups/application/public-enrollment' -import { CredentialGroupOAuthError } from '@/lib/credential-groups/provider-adapter' +import { + CredentialGroupLinkFocusError, + CredentialGroupOAuthError, +} from '@/lib/credential-groups/provider-adapter' import { enforceCredentialGroupEnrollmentOAuthRateLimit, enforcePublicCredentialGroupOAuthStartIpRateLimit, @@ -67,6 +70,8 @@ export const GET = withRouteHandler( response.headers.set('Referrer-Policy', 'no-referrer') return response } catch (error) { + if (error instanceof CredentialGroupLinkFocusError) + return createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth: 'other_option' }) logger.error('Failed to start managed OAuth authorization', { error: getErrorMessage(error), }) diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx new file mode 100644 index 00000000000..b0d19a72130 --- /dev/null +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -0,0 +1,159 @@ +import { AuthLinkButton as ChipLink } from '@sim/auth-ui' +import type { Metadata } from 'next' +import { headers } from 'next/headers' +import { redirect } from 'next/navigation' +import { getSession } from '@/lib/auth' +import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' +import { getCredentialGroupProviderService } from '@/lib/credential-groups/providers' +import { + enforcePublicCredentialGroupIpRateLimit, + isCredentialGroupConnectUserRateLimited, +} from '@/lib/credential-groups/rate-limit' +import { AuthHeader } from '@/app/(auth)/components' +import { + CredentialGroupPageShell, + UnavailableInvitation, + WrongAccount, +} from '@/app/credential-groups/link-states' + +export const metadata: Metadata = { + title: 'Connect your account', + robots: { index: false, follow: false }, +} + +/** Every visit mints a fresh link for whoever is signed in, so nothing here may be cached. */ +export const dynamic = 'force-dynamic' +export const revalidate = 0 + +const MAX_PARAM_LENGTH = 2048 + +interface CredentialGroupConnectPageProps { + params: Promise<{ publicId: string }> + searchParams: Promise> +} + +function getSearchParam( + searchParams: Record, + key: string +): string | undefined { + const value = searchParams[key] + const first = Array.isArray(value) ? value[0] : value + return first && first.length <= MAX_PARAM_LENGTH ? first : undefined +} + +const UNAVAILABLE_MESSAGE = + 'This link isn’t available. Ask the person or app that sent it for a new one.' + +/** + * The secret-free link a workflow shows when someone has not connected an account yet. Signs the + * person in, resolves their own enrollment, and hands off to the enrollment page with a + * short-lived link focused on the one account asked for. Link unfurlers and prefetchers are never + * signed in, so they stop at the login redirect and mint nothing. + */ +export default async function CredentialGroupConnectPage({ + params, + searchParams, +}: CredentialGroupConnectPageProps) { + const { publicId } = await params + const query = await searchParams + const provider = getSearchParam(query, 'provider') + const optionId = getSearchParam(query, 'optionId') + const returnValue = getSearchParam(query, 'return') + + const limited = await enforcePublicCredentialGroupIpRateLimit( + { headers: await headers() }, + 'metadata' + ) + if (limited) return + if (!publicId || publicId.length > 128 || !provider || provider.length > 128) + return + + const callbackQuery = new URLSearchParams({ provider }) + if (optionId) callbackQuery.set('optionId', optionId) + if (returnValue) callbackQuery.set('return', returnValue) + const callbackUrl = `/credential-groups/${encodeURIComponent(publicId)}/connect?${callbackQuery}` + + const session = await getSession() + if (!session?.user) redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) + if (!session.user.emailVerified) + return ( + + ) + if (await isCredentialGroupConnectUserRateLimited(session.user.id)) + return + + const target = await resolveCredentialGroupConnectTarget.execute({ + principal: { kind: 'session', userId: session.user.id, sessionId: session.session.id }, + input: { + publicId, + provider, + ...(optionId ? { optionId } : {}), + ...(returnValue ? { returnUrl: returnValue } : {}), + }, + }) + + switch (target.kind) { + case 'ready': { + const next = new URLSearchParams({ optionId: target.optionId, returnTo: 'connect' }) + if (target.returnUrl) next.set('return', target.returnUrl) + return redirect( + `/credential-groups/enroll/${encodeURIComponent(target.invitationToken)}?${next}` + ) + } + case 'wrong_account': + return ( + + ) + case 'not_invited': { + const integration = getCredentialGroupProviderService(target.provider).name + return ( + + ) + } + case 'revoked': + return ( + + ) + case 'choose_option': { + const integration = getCredentialGroupProviderService(target.provider).name + return ( + + +
+ {target.options.map((option) => { + const choice = new URLSearchParams(callbackQuery) + choice.set('optionId', option.id) + return ( + + {option.label} + + ) + })} +
+
+ ) + } + case 'unavailable': + return + } +} diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index 2bde9272ecf..98ac5b1666b 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -1,4 +1,4 @@ -import { type ReactNode, Suspense } from 'react' +import { Suspense } from 'react' import { AuthButton as Chip, AuthLinkButton as ChipLink, @@ -26,11 +26,15 @@ import { getCredentialGroupProviderService } from '@/lib/credential-groups/provi import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { APP_ENTRY_PATH, organizationRoutes } from '@/lib/navigation/paths' -import { AuthHeader, AuthShell as LogoShell, SupportFooter } from '@/app/(auth)/components' +import { AuthHeader } from '@/app/(auth)/components' import { OAuthConnectLink } from '@/app/credential-groups/enroll/[token]/oauth-reconnect-link' import { CredentialGroupOAuthToast } from '@/app/credential-groups/enroll/[token]/oauth-toast' +import { + CredentialGroupPageShell as PageShell, + UnavailableInvitation, + WrongAccount, +} from '@/app/credential-groups/link-states' import { SourceCompletion } from '@/app/desktop/connect/source-completion' -import { SwitchAccount } from '@/app/desktop/connect/switch-account' export const metadata: Metadata = { title: 'Connect accounts', @@ -44,56 +48,6 @@ interface CredentialGroupEnrollmentPageProps { searchParams: Promise> } -interface PageShellProps { - children: ReactNode -} - -function PageShell({ children }: PageShellProps) { - return ( - }> -
{children}
-
- ) -} - -interface UnavailableInvitationProps { - token?: string - title?: string - rateLimited?: boolean - message?: string - recoveryHref?: string - recoveryLabel?: string -} - -function UnavailableInvitation({ - token, - title, - rateLimited = false, - message, - recoveryHref = APP_ENTRY_PATH, - recoveryLabel = 'Open Sim', -}: UnavailableInvitationProps) { - return ( - - {token && } -
- -
- {recoveryLabel} -
-
-
- ) -} - interface EnrollmentLinkProblemProps { token: string outcome: CredentialGroupEnrollmentLinkOutcome @@ -126,18 +80,11 @@ function EnrollmentLinkProblem({ switch (outcome.kind) { case 'wrong_account': return ( - - -
- -
- -
-
-
+ ) case 'revoked': return ( @@ -202,6 +149,7 @@ const OAUTH_MESSAGES = { configuration_changed: 'This credential option changed. Reload the page and try again.', unavailable: 'Account authorization is temporarily unavailable. Please try again.', failed: 'Account authorization did not complete. Please try again.', + other_option: 'This link only connects the account shown here.', } as const function getSearchParam( @@ -269,18 +217,20 @@ export default async function CredentialGroupEnrollmentPage({ if (!principal) return explainLinkProblem() const returnTo = getSearchParam(resolvedSearchParams, 'returnTo') const returnToSearch = returnTo === 'search' - const focusedReturnTo = + const requestedReturnTo = returnTo === 'search' || returnTo === 'accounts' || returnTo === 'connect' ? returnTo : undefined - const focused = focusedReturnTo !== undefined const requestedOptionId = resolvedSearchParams.optionId - const focusedOptionId = + const requestedFocusOptionId = typeof requestedOptionId === 'string' && requestedOptionId.length <= 128 ? requestedOptionId : '' const enrollmentResult = await readPublicCredentialGroupEnrollment - .execute({ principal, input: focused ? { optionId: focusedOptionId } : {} }) + .execute({ + principal, + input: requestedReturnTo ? { optionId: requestedFocusOptionId } : {}, + }) .catch((error: unknown) => { if (error instanceof CredentialGroupEnrollmentError) return { enrollment: null, enrollmentError: error.message } @@ -293,6 +243,11 @@ export default async function CredentialGroupEnrollmentPage({ if ('enrollmentError' in enrollmentResult) return explainLinkProblem(enrollmentResult.enrollmentError) const { enrollment } = enrollmentResult + /** A link limited to one option is focused on it whatever the query says; the server enforces it. */ + const linkOptionId = 'focusOptionId' in enrollmentResult ? enrollmentResult.focusOptionId : null + const focusedReturnTo = linkOptionId ? (requestedReturnTo ?? 'connect') : requestedReturnTo + const focused = focusedReturnTo !== undefined + const focusedOptionId = linkOptionId ?? requestedFocusOptionId const canReturnToSearch = returnToSearch && ('canSearch' in enrollmentResult ? enrollmentResult.canSearch : !principal.organizationId) diff --git a/apps/sim/app/credential-groups/link-states.tsx b/apps/sim/app/credential-groups/link-states.tsx new file mode 100644 index 00000000000..c2f1d1bb05d --- /dev/null +++ b/apps/sim/app/credential-groups/link-states.tsx @@ -0,0 +1,81 @@ +import type { ReactNode } from 'react' +import { AuthLinkButton as ChipLink } from '@sim/auth-ui' +import { APP_ENTRY_PATH } from '@/lib/navigation/paths' +import { AuthHeader, AuthShell as LogoShell, SupportFooter } from '@/app/(auth)/components' +import { SourceCompletion } from '@/app/desktop/connect/source-completion' +import { SwitchAccount } from '@/app/desktop/connect/switch-account' + +interface CredentialGroupPageShellProps { + children: ReactNode +} + +/** The logo-and-footer frame every public connect and enrollment page renders in. */ +export function CredentialGroupPageShell({ children }: CredentialGroupPageShellProps) { + return ( + }> +
{children}
+
+ ) +} + +interface UnavailableInvitationProps { + /** The enrollment token, when the page was opened from one, so a desktop handoff can finish. */ + token?: string + title?: string + rateLimited?: boolean + message?: string + recoveryHref?: string + recoveryLabel?: string +} + +/** A terminal state with a title, one line of copy, and one way out. */ +export function UnavailableInvitation({ + token, + title, + rateLimited = false, + message, + recoveryHref = APP_ENTRY_PATH, + recoveryLabel = 'Open Sim', +}: UnavailableInvitationProps) { + return ( + + {token && } +
+ +
+ {recoveryLabel} +
+
+
+ ) +} + +interface WrongAccountProps { + token?: string + description: string + /** Where to come back to after signing in as someone else. */ + callbackUrl: string +} + +/** The signed-in person is not the one this link is for; offers to switch accounts. */ +export function WrongAccount({ token, description, callbackUrl }: WrongAccountProps) { + return ( + + {token && } +
+ +
+ +
+
+
+ ) +} diff --git a/apps/sim/ee/credential-groups/components/organization-account-people.tsx b/apps/sim/ee/credential-groups/components/organization-account-people.tsx index 9cfd4436925..9d96f864ac8 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-people.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-people.tsx @@ -1,9 +1,29 @@ 'use client' import { useState } from 'react' -import { Avatar, Badge, Chip, ChipConfirmModal, ChipModalError, toast } from '@sim/emcn' +import { + Avatar, + Badge, + Chip, + ChipConfirmModal, + ChipModalError, + chipVariants, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, + toast, + writeTextToClipboard, +} from '@sim/emcn' import { Plus } from '@sim/emcn/icons' import type { CredentialGroupEnrollmentDetail } from '@/lib/api/contracts/credential-groups' +import type { OrganizationAccountsSettings } from '@/lib/api/contracts/organization-accounts' +import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' +import { + type CredentialGroupProvider, + getCredentialGroupProviderId, + getCredentialGroupProviderService, +} from '@/lib/credential-groups/providers' import { SEARCH_DEBOUNCE_MS } from '@/lib/url-state' import { RowActionsMenu } from '@/app/workspace/[workspaceId]/settings/components/row-actions-menu' import { @@ -27,6 +47,42 @@ import { useOrganizationAccountPeopleSearch } from '@/hooks/use-organization-acc interface OrganizationAccountPeopleProps { organizationId: string + group: NonNullable +} + +interface CopyConnectLinkMenuProps { + publicId: string + providers: CredentialGroupProvider[] +} + +/** + * Copies the stable connect URL for one integration. The URL carries no secret: whoever opens it + * signs in and only reaches their own enrollment. + */ +function CopyConnectLinkMenu({ publicId, providers }: CopyConnectLinkMenuProps) { + const copy = (provider: CredentialGroupProvider) => + writeTextToClipboard( + buildCredentialGroupConnectUrl({ publicId, provider: getCredentialGroupProviderId(provider) }) + ).then( + () => toast.success('Link copied'), + () => toast.error('Could not copy the link') + ) + return ( + + + + + + {providers.map((provider) => ( + void copy(provider)}> + {getCredentialGroupProviderService(provider).name} + + ))} + + + ) } const PERSON_STATUS_BADGES = { @@ -57,7 +113,10 @@ function getPersonStatus( return 'invited' } -export function OrganizationAccountPeople({ organizationId }: OrganizationAccountPeopleProps) { +export function OrganizationAccountPeople({ + organizationId, + group, +}: OrganizationAccountPeopleProps) { const resend = useResendOrganizationAccountInvitation() const revoke = useRevokeOrganizationAccountEnrollment() const [peopleSearch, setPeopleSearch] = useOrganizationAccountPeopleSearch() @@ -68,6 +127,11 @@ export function OrganizationAccountPeople({ organizationId }: OrganizationAccoun const error = resend.error ?? revoke.error const pending = resend.isPending || revoke.isPending const enrollments = people.data?.pages.flatMap((page) => page.enrollments) ?? [] + const connectProviders = [ + ...new Set( + group.options.filter((option) => option.status === 'active').map((option) => option.provider) + ), + ] return ( + {connectProviders.length > 0 && ( +
+ +
+ )} {people.isPending && ( Loading people… )} diff --git a/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx b/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx index cff794b4f16..ca311851ab6 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx @@ -39,6 +39,7 @@ import { OrganizationAccountProviders } from '@/ee/credential-groups/components/ const group: NonNullable = { id: 'group-1', + publicId: 'group-public-1', organizationId: 'org-1', workspaceId: null, name: 'Connected accounts', diff --git a/apps/sim/ee/credential-groups/components/organization-connected-accounts.tsx b/apps/sim/ee/credential-groups/components/organization-connected-accounts.tsx index 6c2ea23fe51..b118042e076 100644 --- a/apps/sim/ee/credential-groups/components/organization-connected-accounts.tsx +++ b/apps/sim/ee/credential-groups/components/organization-connected-accounts.tsx @@ -83,7 +83,9 @@ export function OrganizationConnectedAccounts({ availableMcpConnectors={accounts.data.availableMcpConnectors} /> )} - {tab === 'people' && } + {tab === 'people' && ( + + )} {tab === 'workspace-access' && ( )} diff --git a/apps/sim/lib/api/contracts/organization-accounts.ts b/apps/sim/lib/api/contracts/organization-accounts.ts index 39c0426b337..a4064dc8602 100644 --- a/apps/sim/lib/api/contracts/organization-accounts.ts +++ b/apps/sim/lib/api/contracts/organization-accounts.ts @@ -31,6 +31,7 @@ import { const organizationAccountsParamsSchema = z.object({ id: organizationIdSchema }) const organizationCredentialGroupSchema = credentialGroupSchema.extend({ + publicId: z.string().min(1).max(128), workspaceId: z.null(), organizationId: organizationIdSchema, }) diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts new file mode 100644 index 00000000000..816c6ca1cc8 --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -0,0 +1,563 @@ +/** + * The secret-free connect URL against real Postgres: who it opens for, what it mints, and how the + * focused link it mints is held to its one account option. Failure modes: an invited person + * (minted link scoped to the option, one hour, enrollment fields untouched), an enrollment bound + * to someone else, an unverified session, a revoked enrollment, a stranger, an organization member + * with no enrollment, a disabled group or unknown provider (indistinguishable from an unknown + * public ID), a provider with two options, a workflow-requested enrollment with no live link, a + * focused link used for another option or an MCP server, and the saved connection completing the + * enrollment exactly once. Only email delivery, the provider code exchange, and the workflow + * trigger fan-out are faked. + */ +import type { CredentialGroupEnrollmentPrincipal } from '@sim/auth/principal' +import { db } from '@sim/db' +import { + credential, + credentialGroup, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + member, + organization, + user, +} from '@sim/db/schema' +import { sha256Hex } from '@sim/security/hash' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, describe, expect, it, vi } from 'vitest' +import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' +import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' +import { + completePublicCredentialGroupOAuth, + startPublicCredentialGroupMcpOAuth, + startPublicCredentialGroupOAuth, +} from '@/lib/credential-groups/application/public-enrollment' +import { + authenticatePublicCredentialGroupEnrollment, + inviteCredentialGroupEnrollment, + revokeCredentialGroupEnrollment, +} from '@/lib/credential-groups/enrollments' +import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' +import { CredentialGroupLinkFocusError } from '@/lib/credential-groups/provider-adapter' +import type { CredentialGroupProvider } from '@/lib/credential-groups/providers' +import { ensureWorkspaceAccountsGroup } from '@/lib/credential-groups/service' + +const POLICY = { authorizationAppId: 'fixture-app', requiredScopes: ['read'], scopeVersion: 1 } + +const triggerEvents: Array<{ event: string; enrollmentId: string }> = [] + +vi.mock('@/lib/credential-groups/scoped-availability', () => ({ + isScopedCredentialGroupsAvailable: async () => true, +})) + +vi.mock('@/components/emails/credential-groups/render', () => ({ + renderCredentialGroupInvitationEmail: async (input: { invitationLink: string }) => + input.invitationLink, +})) + +vi.mock('@/lib/messaging/email/mailer', () => ({ + sendEmail: async () => ({ success: true, message: 'sent' }), +})) + +vi.mock('@/lib/credential-groups/trigger', () => ({ + fireCredentialGroupTrigger: async (input: { event: string; enrollmentId: string }) => { + triggerEvents.push({ event: input.event, enrollmentId: input.enrollmentId }) + }, +})) + +vi.mock('@/lib/credential-groups/provider-registry', async (importOriginal) => { + const { getCredentialGroupProviderId } = await import('@/lib/credential-groups/providers') + return { + ...(await importOriginal()), + getCredentialGroupProviderAdapter: (provider: CredentialGroupProvider) => { + const policy = { ...POLICY, provider, providerId: getCredentialGroupProviderId(provider) } + return { + provider, + requiresRefreshToken: false, + getPolicy: async () => policy, + exchangeAndVerify: async ({ code }: { code: string }) => ({ + providerId: policy.providerId, + providerSubjectId: code, + providerTenantId: null, + displayName: code, + metadata: { email: code }, + accessToken: `token-for-${code}`, + grantedScopes: POLICY.requiredScopes, + accessTokenExpiresAt: null, + refreshTokenExpiresAt: null, + }), + } + }, + } +}) + +function driveOption(id: string, label = 'Google Drive') { + return { + id, + provider: 'google-drive' as const, + label, + authorizationAppId: POLICY.authorizationAppId, + requiredScopes: POLICY.requiredScopes, + scopeVersion: POLICY.scopeVersion, + required: false, + status: 'active' as const, + } +} + +const DRIVE = driveOption('option-google-drive') +const DRIVE_PROVIDER_ID = 'google-drive' +const HOUR_MS = 60 * 60 * 1000 + +const userIds: string[] = [] +const organizationIds: string[] = [] + +interface Fixture { + adminId: string + organizationId: string + groupId: string + publicId: string + scope: { kind: 'organization'; organizationId: string } +} + +async function createOrganization( + options: ReturnType[] = [DRIVE] +): Promise { + const { userId: adminId } = await createPerson() + const organizationId = generateId() + organizationIds.push(organizationId) + await db.insert(organization).values({ id: organizationId, name: 'Acme', slug: organizationId }) + await db + .insert(member) + .values({ id: generateId(), organizationId, userId: adminId, role: 'owner' }) + const scope = { kind: 'organization' as const, organizationId } + const group = await ensureWorkspaceAccountsGroup(scope, adminId) + const [updated] = await db + .update(credentialGroup) + .set({ options }) + .where(eq(credentialGroup.id, group.id)) + .returning({ publicId: credentialGroup.publicId }) + if (!updated) throw new Error('Group fixture missing') + return { adminId, organizationId, groupId: group.id, publicId: updated.publicId, scope } +} + +async function createPerson(emailVerified = true): Promise<{ userId: string; email: string }> { + const userId = generateId() + const email = `${userId}@connect.test` + await db.insert(user).values({ + id: userId, + name: 'Connect fixture', + email, + emailVerified, + createdAt: new Date(), + updatedAt: new Date(), + }) + userIds.push(userId) + return { userId, email } +} + +function resolveTarget( + userId: string, + input: { publicId: string; provider?: string; optionId?: string; returnUrl?: string } +) { + return resolveCredentialGroupConnectTarget.execute({ + principal: createSessionPrincipal({ userId }), + input: { provider: DRIVE_PROVIDER_ID, ...input }, + }) +} + +async function readyToken( + userId: string, + input: { publicId: string; optionId?: string } +): Promise { + const target = await resolveTarget(userId, input) + if (target.kind !== 'ready') throw new Error(`Expected ready, got ${target.kind}`) + return target.invitationToken +} + +async function principalFor( + token: string, + userId: string +): Promise { + const identity = await authenticatePublicCredentialGroupEnrollment(token) + if (!identity) throw new Error('Link did not resolve') + return { + kind: 'credential_group_enrollment', + userId, + ...resourceScopeFields(resourceScopeFromOwner(identity)), + credentialGroupId: identity.credentialGroupId, + enrollmentId: identity.enrollmentId, + email: identity.email, + invitationTokenHash: identity.invitationTokenHash, + } +} + +function attemptFor( + fixture: Fixture, + principal: CredentialGroupEnrollmentPrincipal, + token: string, + optionId: string +): CredentialGroupOAuthAttempt { + return { + userId: principal.userId, + state: generateId(), + provider: 'google-drive', + nonceHash: 'nonce', + organizationId: fixture.organizationId, + email: principal.email, + enrollmentId: principal.enrollmentId, + credentialGroupId: fixture.groupId, + optionId, + authorizationAppId: POLICY.authorizationAppId, + scopeVersion: POLICY.scopeVersion, + requiredScopes: POLICY.requiredScopes, + redirectUri: 'https://sim.test/callback', + invitationToken: token, + createdAt: Date.now(), + } +} + +async function enrollmentOf(groupId: string, email: string) { + const [row] = await db + .select() + .from(credentialGroupEnrollment) + .where(eq(credentialGroupEnrollment.credentialGroupId, groupId)) + if (!row || row.email !== email) throw new Error('Enrollment not found') + return row +} + +afterAll(async () => { + await db.delete(credential).where(inArray(credential.organizationId, organizationIds)) + await db.delete(organization).where(inArray(organization.id, organizationIds)) + await db.delete(user).where(inArray(user.id, userIds)) +}) + +describe('resolveCredentialGroupConnectTarget', () => { + it('mints a one-hour connect link scoped to the option and binds the invited person', async () => { + const fixture = await createOrganization() + const person = await createPerson() + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + const before = await enrollmentOf(fixture.groupId, person.email) + + const target = await resolveTarget(person.userId, { + publicId: fixture.publicId, + returnUrl: 'slack', + }) + + expect(target).toMatchObject({ kind: 'ready', optionId: DRIVE.id, returnUrl: 'slack://open' }) + if (target.kind !== 'ready') return + const [link] = await db + .select() + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.tokenHash, sha256Hex(target.invitationToken))) + expect(link).toMatchObject({ purpose: 'connect', optionId: DRIVE.id, revokedAt: null }) + const ttl = (link?.expiresAt.getTime() ?? 0) - Date.now() + expect(ttl).toBeGreaterThan(HOUR_MS - 60_000) + expect(ttl).toBeLessThanOrEqual(HOUR_MS) + const after = await enrollmentOf(fixture.groupId, person.email) + expect(after).toMatchObject({ + userId: person.userId, + status: before.status, + createdBy: before.createdBy, + invitedAt: before.invitedAt, + invitationTokenHash: before.invitationTokenHash, + }) + }) + + it('refuses an enrollment bound to another user as the wrong account', async () => { + const fixture = await createOrganization() + const person = await createPerson() + const other = await createPerson() + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + await db + .update(credentialGroupEnrollment) + .set({ userId: other.userId }) + .where(eq(credentialGroupEnrollment.credentialGroupId, fixture.groupId)) + + await expect(resolveTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'wrong_account', + organizationName: 'Acme', + }) + }) + + it('refuses an unverified session', async () => { + const fixture = await createOrganization() + const person = await createPerson(false) + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + + await expect( + resolveTarget(person.userId, { publicId: fixture.publicId }) + ).rejects.toMatchObject({ code: 'forbidden' }) + const enrollment = await enrollmentOf(fixture.groupId, person.email) + expect(enrollment.userId).toBeNull() + }) + + it('tells a revoked person the connection is no longer needed and mints nothing', async () => { + const fixture = await createOrganization() + const person = await createPerson() + const enrollment = await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + await revokeCredentialGroupEnrollment(fixture.scope, fixture.groupId, enrollment.id) + + await expect(resolveTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'revoked', + organizationName: 'Acme', + provider: 'google-drive', + }) + const links = await db + .select() + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollment.id)) + expect(links.every((link) => link.purpose !== 'connect')).toBe(true) + }) + + it('tells someone with no enrollment outside the organization they were not asked', async () => { + const fixture = await createOrganization() + const stranger = await createPerson() + + await expect(resolveTarget(stranger.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'not_invited', + organizationName: 'Acme', + provider: 'google-drive', + }) + const enrollments = await db + .select() + .from(credentialGroupEnrollment) + .where(eq(credentialGroupEnrollment.credentialGroupId, fixture.groupId)) + expect(enrollments).toHaveLength(0) + }) + + it('enrolls an organization member with no enrollment and mints their link', async () => { + const fixture = await createOrganization() + const teammate = await createPerson() + await db.insert(member).values({ + id: generateId(), + organizationId: fixture.organizationId, + userId: teammate.userId, + role: 'member', + }) + + const target = await resolveTarget(teammate.userId, { publicId: fixture.publicId }) + + expect(target).toMatchObject({ kind: 'ready', optionId: DRIVE.id }) + const enrollment = await enrollmentOf(fixture.groupId, teammate.email) + expect(enrollment.userId).toBe(teammate.userId) + }) + + it('answers a disabled group, an unoffered provider and an unknown ID identically', async () => { + const fixture = await createOrganization() + const disabled = await createOrganization() + const person = await createPerson() + await inviteCredentialGroupEnrollment( + disabled.scope, + disabled.groupId, + disabled.adminId, + 'Admin', + person.email + ) + await db + .update(credentialGroup) + .set({ status: 'disabled' }) + .where(eq(credentialGroup.id, disabled.groupId)) + + const unknown = await resolveTarget(person.userId, { publicId: generateId() }) + expect(unknown).toEqual({ kind: 'unavailable' }) + await expect(resolveTarget(person.userId, { publicId: disabled.publicId })).resolves.toEqual( + unknown + ) + const disabledEnrollment = await enrollmentOf(disabled.groupId, person.email) + const mintedForDisabled = await db + .select() + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, disabledEnrollment.id)) + expect(mintedForDisabled.every((link) => link.purpose !== 'connect')).toBe(true) + await expect( + resolveTarget(person.userId, { publicId: fixture.publicId, provider: 'slack' }) + ).resolves.toEqual(unknown) + await expect( + resolveTarget(person.userId, { publicId: fixture.publicId, provider: 'not-a-provider' }) + ).resolves.toEqual(unknown) + }) + + it('asks which account to connect when the provider has two options', async () => { + const fixture = await createOrganization([ + driveOption('drive-work', 'Work Drive'), + driveOption('drive-shared', 'Shared Drive'), + ]) + const person = await createPerson() + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + + await expect(resolveTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'choose_option', + organizationName: 'Acme', + provider: 'google-drive', + options: [ + { id: 'drive-work', label: 'Work Drive' }, + { id: 'drive-shared', label: 'Shared Drive' }, + ], + }) + await expect( + resolveTarget(person.userId, { publicId: fixture.publicId, optionId: 'drive-shared' }) + ).resolves.toMatchObject({ kind: 'ready', optionId: 'drive-shared' }) + }) + + it('opens a workflow-requested enrollment whose only invitation is long expired', async () => { + const fixture = await createOrganization() + const person = await createPerson() + await db.insert(credentialGroupEnrollment).values({ + id: generateId(), + credentialGroupId: fixture.groupId, + email: person.email, + status: 'invited', + invitationTokenHash: sha256Hex(generateId()), + invitationExpiresAt: new Date(Date.now() - 30 * 24 * HOUR_MS), + invitedAt: new Date(), + }) + + const token = await readyToken(person.userId, { publicId: fixture.publicId }) + + await expect(authenticatePublicCredentialGroupEnrollment(token)).resolves.toMatchObject({ + userId: person.userId, + }) + }) +}) + +describe('a focused connect link', () => { + it('refuses to start OAuth for another option or an MCP server', async () => { + const fixture = await createOrganization([ + driveOption('drive-work', 'Work Drive'), + driveOption('drive-shared', 'Shared Drive'), + ]) + const person = await createPerson() + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + const token = await readyToken(person.userId, { + publicId: fixture.publicId, + optionId: 'drive-work', + }) + const principal = await principalFor(token, person.userId) + + await expect( + startPublicCredentialGroupOAuth.execute({ + principal, + input: { invitationToken: token, optionId: 'drive-shared' }, + }) + ).rejects.toBeInstanceOf(CredentialGroupLinkFocusError) + await expect( + startPublicCredentialGroupMcpOAuth.execute({ + principal, + input: { invitationToken: token, mcpServerId: generateId() }, + }) + ).rejects.toBeInstanceOf(CredentialGroupLinkFocusError) + await expect( + completePublicCredentialGroupOAuth.execute({ + principal, + input: { + attempt: attemptFor(fixture, principal, token, 'drive-shared'), + code: `${person.userId}@drive.test`, + }, + }) + ).rejects.toBeInstanceOf(CredentialGroupLinkFocusError) + }) + + it('completes the enrollment when its connection is saved, firing form_submitted once', async () => { + const fixture = await createOrganization() + const person = await createPerson() + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + const token = await readyToken(person.userId, { publicId: fixture.publicId }) + const principal = await principalFor(token, person.userId) + + for (const code of ['same@drive.test', 'same@drive.test']) { + await completePublicCredentialGroupOAuth.execute({ + principal, + input: { attempt: attemptFor(fixture, principal, token, DRIVE.id), code }, + }) + } + + const enrollment = await enrollmentOf(fixture.groupId, person.email) + expect(enrollment.status).toBe('completed') + expect( + triggerEvents.filter( + (event) => event.enrollmentId === enrollment.id && event.event === 'form_submitted' + ) + ).toHaveLength(1) + }) + + it('leaves an enrollment connected through an unfocused link for Submit', async () => { + const fixture = await createOrganization() + const person = await createPerson() + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + await readyToken(person.userId, { publicId: fixture.publicId }) + const enrollment = await enrollmentOf(fixture.groupId, person.email) + const token = generateId() + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId: enrollment.id, + tokenHash: sha256Hex(token), + purpose: 'email', + expiresAt: new Date(Date.now() + HOUR_MS), + }) + const principal = await principalFor(token, person.userId) + + await completePublicCredentialGroupOAuth.execute({ + principal, + input: { + attempt: attemptFor(fixture, principal, token, DRIVE.id), + code: `${person.userId}@drive.test`, + }, + }) + + const after = await enrollmentOf(fixture.groupId, person.email) + expect(after.status).not.toBe('completed') + expect( + triggerEvents.some( + (event) => event.enrollmentId === enrollment.id && event.event === 'form_submitted' + ) + ).toBe(false) + }) +}) diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts index d1b327b9f8b..6c117908274 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts @@ -3,13 +3,20 @@ * the token lookup, the joins that name the organization and inviter, and the identity check run * on stored rows. Failure modes: an unknown token, a forwarded link opened by someone else (who * must learn nothing but a masked address, whatever state the enrollment is in), a revoked - * enrollment, a disabled group, a failed delivery, and an expired link. + * enrollment, a disabled group, a failed delivery, an expired link, and a link revoked (by a + * disconnect) while its enrollment stays live. */ import { db } from '@sim/db' -import { credentialGroup, credentialGroupEnrollment, organization, user } from '@sim/db/schema' +import { + credentialGroup, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + organization, + user, +} from '@sim/db/schema' import { sha256Hex } from '@sim/security/hash' import { generateId } from '@sim/utils/id' -import { inArray } from 'drizzle-orm' +import { eq, inArray } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { explainCredentialGroupEnrollmentLink } from '@/lib/credential-groups/application/enrollment-link-outcome' @@ -67,6 +74,28 @@ async function seedEnrollment( return token } +/** Adds a link row to the enrollment `enrollmentToken` names and returns the link's own token. */ +async function seedLink( + enrollmentToken: string, + values: Partial = {} +): Promise { + const [enrollment] = await db + .select({ id: credentialGroupEnrollment.id }) + .from(credentialGroupEnrollment) + .where(eq(credentialGroupEnrollment.invitationTokenHash, sha256Hex(enrollmentToken))) + if (!enrollment) throw new Error('Seeded enrollment not found') + const token = generateId() + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId: enrollment.id, + tokenHash: sha256Hex(token), + purpose: 'email', + expiresAt: new Date(Date.now() + DAY_MS), + ...values, + }) + return token +} + beforeAll(async () => { const now = new Date() await db.insert(user).values( @@ -184,4 +213,33 @@ describe('explainCredentialGroupEnrollmentLink', () => { explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) ).resolves.toEqual({ kind: 'unavailable' }) }) + + it('tells the person a link revoked by a disconnect needs reissuing while the enrollment lives', async () => { + const enrollmentToken = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) + const token = await seedLink(enrollmentToken, { revokedAt: new Date() }) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) + ).resolves.toEqual({ + kind: 'needs_new_link', + reason: 'link_revoked', + organizationName: 'Acme Corp', + inviterName: 'Ada Admin', + }) + }) + + it('never calls an expired link of a bound person expired', async () => { + const enrollmentToken = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) + const token = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) + ).resolves.toEqual({ kind: 'unavailable' }) + }) + + it('reports an unbound link expired by its own expiry, not the legacy column', async () => { + const enrollmentToken = await seedEnrollment({ email: inviteeEmail }) + const token = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) + ).resolves.toMatchObject({ kind: 'needs_new_link', reason: 'expired' }) + }) }) diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts new file mode 100644 index 00000000000..a42ae8df427 --- /dev/null +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -0,0 +1,161 @@ +import type { SessionPrincipal } from '@sim/auth/principal' +import { defineOperation } from '@/lib/core/application' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { resourceScopeFromOwner } from '@/lib/core/resource-scope' +import { + authenticatePublicCredentialGroupEnrollment, + bindCredentialGroupEnrollmentUser, + issueCredentialGroupConnectLink, + loadCredentialGroupConnectSubject, +} from '@/lib/credential-groups/enrollments' +import { + type CredentialGroupProvider, + findCredentialGroupProviderFromProviderId, +} from '@/lib/credential-groups/providers' +import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' +import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' +import { createViewerCredentialGroupEnrollment } from '@/lib/credential-groups/self-enrollment' +import { defineAuthorizedCredentialUserUseCase } from '@/lib/credentials/application/authorized-user-use-case' +import { getOrganizationSettingsAccess } from '@/lib/organizations/settings-access' + +const credentialGroupConnectOperations = { + /** + * permission-group-exempt: the person connecting may be outside the organization; authority is + * their own verified email or bound enrollment, never a workspace role. + */ + resolve: defineOperation({ + id: 'credential_groups.connect.resolve', + principalKinds: ['session'], + capability: 'none', + }), +} as const + +/** + * Where the `return` query of a connect URL may send the person once connected. The keyword + * `slack` (what workflows put on the link, since they hold no Slack team or app id) opens the + * Slack app through its generic deep link; anything else must be an allowlisted Slack URL, and an + * invalid value is dropped rather than refused. + */ +const SLACK_APP_RETURN_URL = 'slack://open' + +function resolveReturnUrl(raw: string | undefined): string | undefined { + if (!raw) return undefined + if (raw === 'slack') return SLACK_APP_RETURN_URL + return parseCredentialGroupReturnUrl(raw)?.href +} + +export interface ResolveCredentialGroupConnectTargetInput { + publicId: string + /** The credential provider ID the workflow asked for (e.g. `google-drive`). */ + provider: string + optionId?: string + /** Raw `return` query value: the keyword `slack` or an allowlisted Slack URL. */ + returnUrl?: string +} + +/** + * What the connect page does for the signed-in person. Every refusal that would reveal whether a + * group exists, is enabled, or offers the provider is the same `unavailable`; the organization is + * only named once the group is known to be active and to offer the provider, since the link holder + * got the URL from that organization. + */ +export type CredentialGroupConnectTarget = + | { kind: 'ready'; invitationToken: string; optionId: string; returnUrl?: string } + | { kind: 'unavailable' } + | { kind: 'not_invited'; organizationName: string; provider: CredentialGroupProvider } + | { kind: 'wrong_account'; organizationName: string } + | { kind: 'revoked'; organizationName: string; provider: CredentialGroupProvider } + | { + kind: 'choose_option' + organizationName: string + provider: CredentialGroupProvider + options: Array<{ id: string; label: string }> + } + +const UNAVAILABLE = { kind: 'unavailable' } as const + +/** + * Resolves a secret-free connect URL to the signed-in person's own enrollment and, only then, + * mints a one-hour link focused on the single matching account option. The session is the + * authority, not an earlier invitation: an unbound enrollment whose emailed link (or legacy + * invitation column) expired, or that a workflow requested with no link at all, is still + * connectable by the person at its email, because the fresh link carries its own expiry. An organization member + * with no enrollment is enrolled through the member self-enroll path; anyone else must already + * hold an enrollment bound to them or invited at their verified email. + */ +export const resolveCredentialGroupConnectTarget = defineAuthorizedCredentialUserUseCase({ + operation: credentialGroupConnectOperations.resolve, + async execute({ + principal, + input, + }: { + principal: SessionPrincipal + input: ResolveCredentialGroupConnectTargetInput + }): Promise { + const subject = await loadCredentialGroupConnectSubject({ + publicId: input.publicId, + userId: principal.userId, + }) + if (subject && !subject.viewer.emailVerified) + throw new OrchestrationError('forbidden', 'Verify your email address before connecting') + if (!subject || subject.group.status !== 'active') return UNAVAILABLE + const { group, enrollment } = subject + const provider = findCredentialGroupProviderFromProviderId(input.provider) + if (!provider) return UNAVAILABLE + if (!(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(group)))) + return UNAVAILABLE + const options = group.options.filter( + (option) => + option.provider === provider && + option.status === 'active' && + (input.optionId === undefined || option.id === input.optionId) + ) + const [option] = options + if (!option) return UNAVAILABLE + const { organizationName } = group + + if (enrollment?.userId && enrollment.userId !== principal.userId) + return { kind: 'wrong_account', organizationName } + if (enrollment && (enrollment.status === 'revoked' || enrollment.revokedAt)) + return { kind: 'revoked', organizationName, provider } + if ( + !enrollment && + !( + group.organizationId && + (await getOrganizationSettingsAccess(group.organizationId, principal.userId)).isMember + ) + ) + return { kind: 'not_invited', organizationName, provider } + if (options.length > 1) + return { + kind: 'choose_option', + organizationName, + provider, + options: options.map(({ id, label }) => ({ id, label })), + } + + let enrollmentId = enrollment?.id + if (!enrollmentId) { + const enrolled = await createViewerCredentialGroupEnrollment({ + ...(group.organizationId ? { organizationId: group.organizationId } : {}), + credentialGroupId: group.id, + userId: principal.userId, + }) + enrollmentId = enrolled.enrollment.id + } + const invitationToken = await issueCredentialGroupConnectLink(enrollmentId, option.id) + if (!invitationToken) return { kind: 'revoked', organizationName, provider } + if (!enrollment?.userId) { + const identity = await authenticatePublicCredentialGroupEnrollment(invitationToken) + if (!identity) return UNAVAILABLE + await bindCredentialGroupEnrollmentUser(identity, principal.userId) + } + const returnUrl = resolveReturnUrl(input.returnUrl) + return { + kind: 'ready', + invitationToken, + optionId: option.id, + ...(returnUrl ? { returnUrl } : {}), + } + }, +}) diff --git a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts index e6e50fb7055..a6464adfd10 100644 --- a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts +++ b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts @@ -13,7 +13,7 @@ export type CredentialGroupEnrollmentLinkOutcome = | { kind: 'paused'; organizationName: string } | { kind: 'needs_new_link' - reason: 'expired' | 'delivery_failed' + reason: 'expired' | 'delivery_failed' | 'link_revoked' organizationName: string inviterName: string | null } @@ -48,6 +48,13 @@ export async function explainCredentialGroupEnrollmentLink({ const { organizationName } = record if (record.revoked) return { kind: 'revoked', organizationName } if (!record.groupActive) return { kind: 'paused', organizationName } + if (record.linkRevoked) + return { + kind: 'needs_new_link', + reason: 'link_revoked', + organizationName, + inviterName: record.inviterName, + } if (record.status === 'delivery_failed') return { kind: 'needs_new_link', @@ -55,7 +62,7 @@ export async function explainCredentialGroupEnrollmentLink({ organizationName, inviterName: record.inviterName, } - if (record.expiresAt.getTime() <= Date.now()) + if (record.expired) return { kind: 'needs_new_link', reason: 'expired', diff --git a/apps/sim/lib/credential-groups/application/public-enrollment.test.ts b/apps/sim/lib/credential-groups/application/public-enrollment.test.ts index eeffeececc7..bebf1240f53 100644 --- a/apps/sim/lib/credential-groups/application/public-enrollment.test.ts +++ b/apps/sim/lib/credential-groups/application/public-enrollment.test.ts @@ -159,6 +159,7 @@ describe('public Credential Group enrollment application operations', () => { expect(mocks.getEnrollment).toHaveBeenCalledWith(identity, undefined) expect(result).toEqual({ canSearch: false, + focusOptionId: null, enrollment: { status: 'invited', credentialGroupName: 'Credential Group', diff --git a/apps/sim/lib/credential-groups/application/public-enrollment.ts b/apps/sim/lib/credential-groups/application/public-enrollment.ts index 01564379a0d..a9e3bc6330b 100644 --- a/apps/sim/lib/credential-groups/application/public-enrollment.ts +++ b/apps/sim/lib/credential-groups/application/public-enrollment.ts @@ -16,6 +16,7 @@ import { getAuthorizedCredentialGroupMcpOAuthContext, getAuthorizedCredentialGroupOAuthContext, getAuthorizedPublicCredentialGroupEnrollment, + getCredentialGroupEnrollmentLinkOptionId, getCredentialGroupMcpOAuthContextForEnrollment, getCredentialGroupOAuthContextForEnrollment, type PublicCredentialGroupEnrollmentIdentity, @@ -30,16 +31,36 @@ import { startCredentialGroupOAuth, } from '@/lib/credential-groups/oauth' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' -import { CredentialGroupInvitationUnavailableError } from '@/lib/credential-groups/provider-adapter' +import { + CredentialGroupInvitationUnavailableError, + CredentialGroupLinkFocusError, +} from '@/lib/credential-groups/provider-adapter' import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { fireCredentialGroupTrigger } from '@/lib/credential-groups/trigger' import { isKnowledgeMemberAccessAvailable } from '@/lib/knowledge/access/availability' import { getOrganizationSettingsAccess } from '@/lib/organizations/settings-access' +/** What an operation's input connects, for holding a focused link to its one account option. */ +type EnrollmentConnectionTarget = { optionId: string } | { mcpServerId: string } + interface AuthorizedCredentialGroupEnrollmentUseCaseDefinition { operation: O - resolveContext(args: { principal: CredentialGroupEnrollmentPrincipal; input: I }): Promise - execute(args: { principal: CredentialGroupEnrollmentPrincipal; input: I; context: C }): Promise + /** + * The account this input connects, when the operation connects one. A link limited to an + * option refuses every other option and every MCP server. + */ + target?(input: I): EnrollmentConnectionTarget + resolveContext(args: { + principal: CredentialGroupEnrollmentPrincipal + input: I + linkOptionId: string | null + }): Promise + execute(args: { + principal: CredentialGroupEnrollmentPrincipal + input: I + context: C + linkOptionId: string | null + }): Promise } function requireCredentialGroupEnrollmentPrincipal( @@ -81,9 +102,15 @@ function defineAuthorizedCredentialGroupEnrollmentUseCase< async function authorize(principal: Principal, input: I) { requireCredentialGroupEnrollmentPrincipal(principal) await bindCredentialGroupEnrollmentUser(identityFromPrincipal(principal), principal.userId) - const context = await definition.resolveContext({ principal, input }) + const linkOptionId = await getCredentialGroupEnrollmentLinkOptionId( + principal.invitationTokenHash + ) + const target = definition.target?.(input) + if (linkOptionId && target && !('optionId' in target && target.optionId === linkOptionId)) + throw new CredentialGroupLinkFocusError() + const context = await definition.resolveContext({ principal, input, linkOptionId }) requireMatchingContext(principal, context) - return { principal, input, context } + return { principal, input, context, linkOptionId } } return { @@ -140,19 +167,22 @@ async function resolvePublicEnrollmentContext( export const readPublicCredentialGroupEnrollment = defineAuthorizedCredentialGroupEnrollmentUseCase( { operation: credentialGroupEnrollmentOperations.read, + /** A focused link only ever shows its one option, whatever the page asked for. */ resolveContext: ({ principal, input, + linkOptionId, }: { principal: CredentialGroupEnrollmentPrincipal input: { optionId?: string } - }) => resolvePublicEnrollmentContext(principal, input.optionId), - async execute({ context, principal }) { + linkOptionId: string | null + }) => resolvePublicEnrollmentContext(principal, linkOptionId ?? input.optionId), + async execute({ context, principal, linkOptionId }) { const canSearch = !context.organizationId || ((await getOrganizationSettingsAccess(context.organizationId, principal.userId)).isMember && (await isKnowledgeMemberAccessAvailable({ organizationId: context.organizationId }))) - return { enrollment: context.enrollment, canSearch } + return { enrollment: context.enrollment, canSearch, focusOptionId: linkOptionId } }, } ) @@ -162,22 +192,35 @@ export const completePublicCredentialGroupEnrollment = operation: credentialGroupEnrollmentOperations.complete, resolveContext: ({ principal }) => resolvePublicEnrollmentContext(principal), async execute({ context }) { - const completion = await completeAuthorizedCredentialGroupEnrollment(context) - if (completion?.transitioned && context.organizationId) { - await fireCredentialGroupTrigger({ - event: 'form_submitted', - organizationId: context.organizationId, - credentialGroupId: context.credentialGroupId, - credentialGroupName: context.enrollment.credentialGroupName, - enrollmentId: context.enrollmentId, - email: context.email, - enrollmentStatus: 'completed', - }) + return { + completed: await completeEnrollment(context, context.enrollment.credentialGroupName), } - return { completed: completion?.completed ?? null } }, }) +/** + * Marks the enrollment submitted and, the first time only, tells the organization's workflows. + * Shared by the Submit button and by a focused link, whose saved connection is the submission. + */ +async function completeEnrollment( + identity: PublicCredentialGroupEnrollmentIdentity, + credentialGroupName: string +): Promise { + const completion = await completeAuthorizedCredentialGroupEnrollment(identity) + if (completion?.transitioned && identity.organizationId) { + await fireCredentialGroupTrigger({ + event: 'form_submitted', + organizationId: identity.organizationId, + credentialGroupId: identity.credentialGroupId, + credentialGroupName, + enrollmentId: identity.enrollmentId, + email: identity.email, + enrollmentStatus: 'completed', + }) + } + return completion?.completed ?? null +} + interface PublicCredentialGroupOAuthInput { invitationToken: string optionId: string @@ -202,6 +245,7 @@ async function resolvePublicOAuthContext( export const startPublicCredentialGroupOAuth = defineAuthorizedCredentialGroupEnrollmentUseCase({ operation: credentialGroupEnrollmentOperations.startOAuth, + target: (input) => ({ optionId: input.optionId }), resolveContext: ({ principal, input, @@ -265,6 +309,7 @@ async function resolveOAuthAttemptContext( export const completePublicCredentialGroupOAuth = defineAuthorizedCredentialGroupEnrollmentUseCase({ operation: credentialGroupEnrollmentOperations.completeOAuth, + target: (input) => ({ optionId: input.attempt.optionId }), resolveContext: ({ principal, input, @@ -272,7 +317,7 @@ export const completePublicCredentialGroupOAuth = defineAuthorizedCredentialGrou principal: CredentialGroupEnrollmentPrincipal input: CompletePublicCredentialGroupOAuthInput }) => resolveOAuthAttemptContext(principal, input.attempt), - async execute({ principal, input, context }) { + async execute({ principal, input, context, linkOptionId }) { requireInvitationToken(principal, input.attempt.invitationToken) const completion = await completeCredentialGroupOAuth(context.oauth, input.attempt, input.code) if (context.organizationId) @@ -292,6 +337,7 @@ export const completePublicCredentialGroupOAuth = defineAuthorizedCredentialGrou displayName: completion.displayName, }, }) + if (linkOptionId) await completeEnrollment(context, context.oauth.credentialGroupName) return { connectedOptionId: context.oauth.option.id } }, }) @@ -317,6 +363,7 @@ async function resolvePublicMcpOAuthContext( export const startPublicCredentialGroupMcpOAuth = defineAuthorizedCredentialGroupEnrollmentUseCase({ operation: credentialGroupEnrollmentOperations.startMcpOAuth, + target: (input) => ({ mcpServerId: input.mcpServerId }), resolveContext: ({ principal, input, @@ -340,6 +387,7 @@ interface CompletePublicCredentialGroupMcpOAuthInput { export const completePublicCredentialGroupMcpOAuth = defineAuthorizedCredentialGroupEnrollmentUseCase({ operation: credentialGroupEnrollmentOperations.completeMcpOAuth, + target: (input) => ({ mcpServerId: input.attempt.mcpServerId }), async resolveContext({ principal, input, diff --git a/apps/sim/lib/credential-groups/connect-url.ts b/apps/sim/lib/credential-groups/connect-url.ts new file mode 100644 index 00000000000..55593aa4f13 --- /dev/null +++ b/apps/sim/lib/credential-groups/connect-url.ts @@ -0,0 +1,19 @@ +import { getBaseUrl } from '@/lib/core/utils/urls' + +/** + * The stable, secret-free link a person opens to connect one integration for a Credential Group. + * Safe to show anywhere: the page it opens verifies who is signed in before minting anything. + */ +export function buildCredentialGroupConnectUrl({ + publicId, + provider, + returnKey, +}: { + publicId: string + provider: string + returnKey?: 'slack' +}): string { + const query = new URLSearchParams({ provider }) + if (returnKey) query.set('return', returnKey) + return `${getBaseUrl()}/credential-groups/${encodeURIComponent(publicId)}/connect?${query}` +} diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 4b37640bba3..448e1857792 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -674,6 +674,134 @@ async function issueInvitation( } } +const CONNECT_LINK_TTL_MS = 60 * 60 * 1000 + +/** + * Mints a short-lived link focused on one account option for an enrollment the caller already + * matched to the signed-in person. Inserts a link row only: the enrollment's issuer, timestamps, + * status and legacy token column stay as they are. Returns the bearer token, or null when the + * enrollment was revoked or removed before the lifecycle lock was taken. + */ +export async function issueCredentialGroupConnectLink( + enrollmentId: string, + optionId: string +): Promise { + const token = generateId() + const now = new Date() + return db.transaction(async (tx) => { + await lockCredentialGroupEnrollmentLifecycle(tx, enrollmentId) + const [current] = await tx + .select({ status: credentialGroupEnrollment.status }) + .from(credentialGroupEnrollment) + .where( + and( + eq(credentialGroupEnrollment.id, enrollmentId), + isNull(credentialGroupEnrollment.revokedAt) + ) + ) + .limit(1) + if (!current || current.status === 'revoked') return null + await tx.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId, + tokenHash: hashInvitationToken(token), + purpose: 'connect', + optionId, + expiresAt: new Date(now.getTime() + CONNECT_LINK_TTL_MS), + createdAt: now, + }) + return token + }) +} + +/** + * The single account option a link is limited to, or null when the link (or a legacy token with + * no link row) may connect any option. + */ +export async function getCredentialGroupEnrollmentLinkOptionId( + invitationTokenHash: string +): Promise { + const [row] = await db + .select({ optionId: credentialGroupEnrollmentLink.optionId }) + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.tokenHash, invitationTokenHash)) + .limit(1) + return row?.optionId ?? null +} + +export interface CredentialGroupConnectSubject { + viewer: { email: string; emailVerified: boolean } + group: { + id: string + workspaceId: string | null + organizationId: string | null + status: 'active' | 'disabled' + options: CredentialGroupOptionConfig[] + organizationName: string + } + enrollment: Pick | null +} + +/** + * Loads the group a public connect URL names and the enrollment that belongs to the signed-in + * person: the one bound to them, else the one invited at their email. Null for an unknown + * public ID or user. Authorizes nothing; the connect use case decides what the person may do. + */ +export async function loadCredentialGroupConnectSubject(input: { + publicId: string + userId: string +}): Promise { + const [viewer] = await db + .select({ email: user.email, emailVerified: user.emailVerified }) + .from(user) + .where(eq(user.id, input.userId)) + .limit(1) + if (!viewer) return null + const [group] = await db + .select({ + id: credentialGroup.id, + workspaceId: credentialGroup.workspaceId, + organizationId: credentialGroup.organizationId, + status: credentialGroup.status, + options: credentialGroup.options, + organizationName: organization.name, + workspaceName: workspace.name, + }) + .from(credentialGroup) + .leftJoin(workspace, eq(workspace.id, credentialGroup.workspaceId)) + .leftJoin(organization, eq(organization.id, credentialGroup.organizationId)) + .where(eq(credentialGroup.publicId, input.publicId)) + .limit(1) + if (!group) return null + const enrollments = await db + .select({ + id: credentialGroupEnrollment.id, + email: credentialGroupEnrollment.email, + userId: credentialGroupEnrollment.userId, + status: credentialGroupEnrollment.status, + revokedAt: credentialGroupEnrollment.revokedAt, + }) + .from(credentialGroupEnrollment) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, group.id), + or( + eq(credentialGroupEnrollment.userId, input.userId), + eq(credentialGroupEnrollment.email, normalizeEmail(viewer.email)) + ) + ) + ) + .limit(2) + const enrollment = + enrollments.find((candidate) => candidate.userId === input.userId) ?? enrollments[0] ?? null + const { workspaceName, organizationName, ...rest } = group + return { + viewer, + group: { ...rest, organizationName: organizationName ?? workspaceName ?? '' }, + enrollment, + } +} + /** True while the link an invitation was sent with is unrevoked. */ function enrollmentLinkStillLive(linkId: string): SQL { const link = credentialGroupEnrollmentLink @@ -1578,8 +1706,12 @@ export interface CredentialGroupEnrollmentLinkRecord { email: string userId: string | null status: CredentialGroupEnrollmentStatus - expiresAt: Date + /** Past its expiry while the enrollment has no bound user, the only time expiry applies. */ + expired: boolean + /** The enrollment itself was revoked by an admin. */ revoked: boolean + /** This link alone was revoked (a disconnect) while the enrollment may still be live. */ + linkRevoked: boolean groupActive: boolean organizationName: string inviterName: string | null @@ -1587,20 +1719,26 @@ export interface CredentialGroupEnrollmentLinkRecord { /** * Reads the enrollment an invitation token names in any state, so the person holding it can be - * told why it stopped working. Grants no authority: live-link callers use + * told why it stopped working. Resolves the token the way {@link liveEnrollmentLinkCondition} + * does (its link row, else the legacy column when no link row carries the hash) without the + * liveness filter. Grants no authority: live-link callers use * {@link authenticatePublicCredentialGroupEnrollment}. */ export async function findCredentialGroupEnrollmentLinkRecord( token: string ): Promise { if (!token.trim() || token.length > 128) return null + const tokenHash = hashInvitationToken(token) + const link = credentialGroupEnrollmentLink const [row] = await db .select({ email: credentialGroupEnrollment.email, userId: credentialGroupEnrollment.userId, status: credentialGroupEnrollment.status, - expiresAt: credentialGroupEnrollment.invitationExpiresAt, + legacyExpiresAt: credentialGroupEnrollment.invitationExpiresAt, revokedAt: credentialGroupEnrollment.revokedAt, + linkExpiresAt: link.expiresAt, + linkRevokedAt: link.revokedAt, groupStatus: credentialGroup.status, workspaceId: credentialGroup.workspaceId, organizationId: credentialGroup.organizationId, @@ -1610,18 +1748,32 @@ export async function findCredentialGroupEnrollmentLinkRecord( }) .from(credentialGroupEnrollment) .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) + .leftJoin( + link, + and(eq(link.enrollmentId, credentialGroupEnrollment.id), eq(link.tokenHash, tokenHash)) + ) .leftJoin(workspace, eq(workspace.id, credentialGroup.workspaceId)) .leftJoin(organization, eq(organization.id, credentialGroup.organizationId)) .leftJoin(user, eq(user.id, credentialGroupEnrollment.createdBy)) - .where(eq(credentialGroupEnrollment.invitationTokenHash, hashInvitationToken(token))) + .where( + or( + isNotNull(link.id), + and( + eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), + sql`not exists (select 1 from ${link} where ${eq(link.tokenHash, tokenHash)})` + ) + ) + ) .limit(1) if (!row || !(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(row)))) return null + const expiresAt = row.linkExpiresAt ?? row.legacyExpiresAt return { email: row.email, userId: row.userId, status: row.status, - expiresAt: row.expiresAt, + expired: !row.userId && expiresAt.getTime() <= Date.now(), revoked: row.status === 'revoked' || row.revokedAt !== null, + linkRevoked: row.linkRevokedAt !== null, groupActive: row.groupStatus === 'active', organizationName: row.organizationName ?? row.workspaceName ?? '', inviterName: row.inviterName, diff --git a/apps/sim/lib/credential-groups/organization-account-options.test.ts b/apps/sim/lib/credential-groups/organization-account-options.test.ts index 684dd2140fb..7523ba78fbd 100644 --- a/apps/sim/lib/credential-groups/organization-account-options.test.ts +++ b/apps/sim/lib/credential-groups/organization-account-options.test.ts @@ -11,6 +11,7 @@ describe('organization account update options', () => { const slackBotCredentialId = '12345678-1234-4123-8123-123456789012' const group: NonNullable = { id: 'group-1', + publicId: 'group-public-1', workspaceId: null, organizationId: 'org-1', name: 'Connected accounts', diff --git a/apps/sim/lib/credential-groups/provider-adapter.ts b/apps/sim/lib/credential-groups/provider-adapter.ts index 09badad09a0..743c908a367 100644 --- a/apps/sim/lib/credential-groups/provider-adapter.ts +++ b/apps/sim/lib/credential-groups/provider-adapter.ts @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto' import type { CredentialGroupOptionConfig, ManagedOAuthProviderMetadata } from '@sim/db/schema' +import { OrchestrationError } from '@/lib/core/orchestration/types' import type { CredentialGroupOAuthContext } from '@/lib/credential-groups/enrollments' import type { CredentialGroupOAuthFailure } from '@/lib/credential-groups/oauth-completion' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' @@ -94,6 +95,14 @@ export class CredentialGroupOAuthError extends Error { } } +/** A link focused on one account option was used to connect a different one. */ +export class CredentialGroupLinkFocusError extends OrchestrationError { + constructor() { + super('forbidden', 'This link only connects the account it was sent for') + this.name = 'CredentialGroupLinkFocusError' + } +} + export class CredentialGroupInvitationUnavailableError extends CredentialGroupOAuthError { constructor() { super('This account invitation was revoked.', 409) diff --git a/apps/sim/lib/credential-groups/rate-limit.ts b/apps/sim/lib/credential-groups/rate-limit.ts index c1865c3e5b8..3e23755cd93 100644 --- a/apps/sim/lib/credential-groups/rate-limit.ts +++ b/apps/sim/lib/credential-groups/rate-limit.ts @@ -110,6 +110,22 @@ export async function enforceCredentialGroupEnrollmentOAuthRateLimit( : rateLimitResponse(result.retryAfterMs, PUBLIC_OAUTH_START_RATE_LIMIT.refillIntervalMs) } +const CONNECT_LINK_USER_RATE_LIMIT: TokenBucketConfig = { + maxTokens: 20, + refillRate: 20, + refillIntervalMs: 15 * 60_000, +} + +/** Bounds how many connect links one signed-in person can mint, wherever they open them from. */ +export async function isCredentialGroupConnectUserRateLimited(userId: string): Promise { + const result = await rateLimiter.checkRateLimitDirect( + `credential-group-connect:user:${userId}`, + CONNECT_LINK_USER_RATE_LIMIT, + { failClosed: true } + ) + return !result.allowed +} + export class CredentialGroupInvitationRateLimitError extends RateLimitError { constructor( readonly retryAfterSeconds: number, diff --git a/apps/sim/lib/credential-groups/service.ts b/apps/sim/lib/credential-groups/service.ts index 3acd3a02672..0a75a7423d1 100644 --- a/apps/sim/lib/credential-groups/service.ts +++ b/apps/sim/lib/credential-groups/service.ts @@ -159,6 +159,7 @@ async function toCredentialGroup( ) return { id: row.id, + publicId: row.publicId, workspaceId: row.workspaceId, ...(row.organizationId ? { organizationId: row.organizationId } : {}), name: row.name, diff --git a/apps/sim/lib/credential-groups/types.ts b/apps/sim/lib/credential-groups/types.ts index 6698a99dcc6..95ab79485fc 100644 --- a/apps/sim/lib/credential-groups/types.ts +++ b/apps/sim/lib/credential-groups/types.ts @@ -51,6 +51,8 @@ export type CredentialGroupOption = export interface CredentialGroupRecord { id: string + /** Names the group in secret-free connect URLs. */ + publicId: string workspaceId: string | null organizationId?: string name: string diff --git a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts index a591031c6d2..170ef88edd2 100644 --- a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts +++ b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts @@ -18,7 +18,8 @@ export class MockCredentialGroupEnrollmentError extends Error { * Controllable mock functions for `@/lib/credential-groups/enrollments`. * * Every function is a bare `vi.fn()` except `mockLockCredentialGroupEnrollmentLifecycle` and - * `mockRevokeCredentialGroupEnrollmentLinks`, which resolve `undefined`, and + * `mockRevokeCredentialGroupEnrollmentLinks`, which resolve `undefined`, + * `mockGetCredentialGroupEnrollmentLinkOptionId`, which resolves `null` (an unfocused link), and * `mockLiveEnrollmentLinkCondition`, which returns a `{ type: 'liveEnrollmentLink', tokenHash }` * condition node a test can find in a WHERE tree. * @@ -59,6 +60,12 @@ export const credentialGroupsEnrollmentsMockFns = { mockGetCredentialGroupOAuthContextForEnrollment: vi.fn(), mockGetAuthorizedCredentialGroupMcpOAuthContext: vi.fn(), mockGetCredentialGroupMcpOAuthContextForEnrollment: vi.fn(), + mockGetCredentialGroupEnrollmentLinkOptionId: vi.fn( + async (_invitationTokenHash: string): Promise => null + ), + mockIssueCredentialGroupConnectLink: vi.fn(), + mockLoadCredentialGroupConnectSubject: vi.fn(), + mockFindCredentialGroupEnrollmentLinkRecord: vi.fn(), } const fns = credentialGroupsEnrollmentsMockFns @@ -96,4 +103,8 @@ export const credentialGroupsEnrollmentsMock = { getAuthorizedCredentialGroupMcpOAuthContext: fns.mockGetAuthorizedCredentialGroupMcpOAuthContext, getCredentialGroupMcpOAuthContextForEnrollment: fns.mockGetCredentialGroupMcpOAuthContextForEnrollment, + getCredentialGroupEnrollmentLinkOptionId: fns.mockGetCredentialGroupEnrollmentLinkOptionId, + issueCredentialGroupConnectLink: fns.mockIssueCredentialGroupConnectLink, + loadCredentialGroupConnectSubject: fns.mockLoadCredentialGroupConnectSubject, + findCredentialGroupEnrollmentLinkRecord: fns.mockFindCredentialGroupEnrollmentLinkRecord, } From c821e6cb0e7cad0bb2a7172ddc67341f3c67e4ab Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 13:49:18 -0600 Subject: [PATCH 06/26] fix(credential-groups): store workflow request policy apart from Access - Request policy moves to its own table (credential_group_connection_request_policy, own revision; no row = off). The Access resource-policy document, its codec, the DB validator, and the Access save path are back to staging byte for byte, so old pods and rollbacks keep reading every Access document. The connections.request evaluator action is gone. - Turning requests off skips workspace/integration cross-checks and prunes stale ids; reads prune them too. Policy lists normalize on parse (no separate sorted refine); oversized lists are validation errors. - Request log table (credential_group_connection_request): every accepted request, whatever the person's state, is logged and counts toward the daily cap, which is checked before any per-address lookup and fails identically for every target. - Emails go through the outbox (enqueued in the request transaction, delivered detached right away, retried by the worker), so the response never waits on rendering or sending. The handler re-reads the enrollment and sends nothing to a revoked or bound person; success clears lastDeliveryError. - Reminders: only for workflow-created, unbound, invited enrollments, when no request for the address was logged in the last day, at most 3, none after 30 days; the claim is a conditional UPDATE so a racing revoke sends nothing. - request_connection refuses + aliases. Invitation email names the requesting workflow (from the workflow record) and the organization. - Block drops the redundant provider output; docs updated. connect-url.ts matches the shared builder. requireCurrentWorkflow exported instead of a wrapper. - Admin UI: "Connection requests from workflows", summary with workspaces and email state, exact-domain and daily-limit hints, inline free-mail domain warning. - Integration tests: stale-policy disable, cap counts existing addresses, identical cap error, plus-alias refusal, reminder cap and 30-day stop, revoke race, Access and request policy saves independent. --- .../docs/workflows/blocks/credential.mdx | 3 +- apps/sim/blocks/blocks/credential.ts | 5 - .../credential-group-invitation-email.tsx | 58 +- .../emails/credential-groups/render.ts | 2 +- apps/sim/components/emails/subjects.ts | 9 + .../organization-connection-requests.tsx | 56 +- .../hooks/queries/organization-accounts.ts | 4 +- .../utils/organization-accounts-keys.ts | 2 +- .../api/contracts/organization-accounts.ts | 44 +- apps/sim/lib/core/outbox/handlers.ts | 10 + apps/sim/lib/core/outbox/retention.ts | 2 + ...orkflow-connection-requests.integration.ts | 309 +- .../application/authorization.ts | 10 +- .../application/connection-requests.ts | 52 +- .../application/organization-access.ts | 18 +- .../organization-connection-requests.ts | 139 +- .../workspace-access-policy.test.ts | 82 +- .../application/workspace-access-policy.ts | 149 +- apps/sim/lib/credential-groups/connect-url.ts | 24 +- .../connection-request-email.ts | 104 + .../connection-request-event.ts | 11 + .../connection-request-policy.ts | 95 +- .../credential-groups/connection-requests.ts | 298 +- apps/sim/lib/resource-policies/registry.ts | 8 +- .../db/credential-group-resource-policies.ts | 62 - ...0_credential_group_connection_requests.sql | 26 + .../db/migrations/meta/0490_snapshot.json | 34922 ++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/schema.ts | 58 + .../src/mocks/schema-tables.generated.ts | 17 + 30 files changed, 35948 insertions(+), 638 deletions(-) create mode 100644 apps/sim/lib/credential-groups/connection-request-email.ts create mode 100644 apps/sim/lib/credential-groups/connection-request-event.ts create mode 100644 packages/db/migrations/0490_credential_group_connection_requests.sql create mode 100644 packages/db/migrations/meta/0490_snapshot.json diff --git a/apps/docs/content/docs/workflows/blocks/credential.mdx b/apps/docs/content/docs/workflows/blocks/credential.mdx index c29cbf4b3dc..a40963d2ab0 100644 --- a/apps/docs/content/docs/workflows/blocks/credential.mdx +++ b/apps/docs/content/docs/workflows/blocks/credential.mdx @@ -99,12 +99,11 @@ For example, name the block **Account**, choose Find Organization Account, set E | `status` | `connected`, `not_connected`, or `needs_reconnect` | | `connected` | Whether a usable account exists | | `credentialId` | The account Find Organization Account would return, or `null` unless connected | -| `provider` | The provider the status refers to | | `connectUrl` | A link the person opens to sign in to Sim and connect this provider | The status never says whether the person was invited, removed, or never asked. `connectUrl` carries no secret: the page checks that the signed-in person is the one with that email before anything is connected, so it is safe to post, for example as a Slack button. -**Request Connection** returns `requested` and `connectUrl`. It works only when an admin turns on **Let workflows request connections** on the connected accounts **Access** tab, for the workflow's workspace, the person's email domain, and the provider. A request outside those settings, or past the daily limit, fails with an error. Otherwise the result is the same whether the person was already asked, already connected, or removed; a removed person is never re-invited. When the admin chose to also email the person, Sim sends the link once a day at most. +**Request Connection** returns `requested` and `connectUrl`. It works only when an admin turns on **Let workflows request connections** under **Connection requests from workflows** on the connected accounts **Access** tab, for the workflow's workspace, the person's email domain, and the provider. A request outside those settings, or past the daily limit, fails with an error. Otherwise the result is the same whether the person was already asked, already connected, or removed; a removed person is never re-invited. Use the person's primary address: an address with a `+` alias is refused. The daily limit counts every accepted request across all workspaces, including repeat requests for the same person. When the admin chose to also email the person, Sim emails the link with the workflow's name. It sends up to 3 reminders, each only when a workflow asks again after a day with no request for that person, and none after 30 days. ### Managed MCP diff --git a/apps/sim/blocks/blocks/credential.ts b/apps/sim/blocks/blocks/credential.ts index 3023486fa34..e8f7a5531e2 100644 --- a/apps/sim/blocks/blocks/credential.ts +++ b/apps/sim/blocks/blocks/credential.ts @@ -235,11 +235,6 @@ export const CredentialBlock: BlockConfig = { description: 'Whether the person has a usable account for the provider', condition: { field: 'operation', value: 'get_connection_status' }, }, - provider: { - type: 'string', - description: 'Provider ID the status refers to', - condition: { field: 'operation', value: 'get_connection_status' }, - }, connectUrl: { type: 'string', description: diff --git a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx index 948ec786d1a..98d03f143af 100644 --- a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx +++ b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx @@ -14,7 +14,7 @@ interface CredentialGroupInvitationEmailProps { * Set when a workflow asked for one integration. The link is then the stable connect * page, which signs the person in instead of expiring, so the footer says so. */ - requestedProviderName?: string + workflowRequest?: { workflowName: string; providerName: string } } export function CredentialGroupInvitationEmail({ @@ -24,43 +24,49 @@ export function CredentialGroupInvitationEmail({ credentialGroupName, invitationLink, searchProviderName, - requestedProviderName, + workflowRequest, }: CredentialGroupInvitationEmailProps) { - const providerName = searchProviderName ?? requestedProviderName + const providerName = searchProviderName ?? workflowRequest?.providerName return ( Hello, - {inviterName ? ( + {workflowRequest ? ( <> - {inviterName} invited {recipientEmail} + {workflowRequest.workflowName} in {workspaceName}{' '} + asked you to connect {workflowRequest.providerName}. ) : ( <> - {recipientEmail} has been invited - - )}{' '} - {searchProviderName ? ( - <> - to connect your {searchProviderName} account for Search in{' '} - {workspaceName}. - - ) : requestedProviderName ? ( - <> - to connect your {requestedProviderName} account for {workspaceName} on - Sim. - - ) : ( - <> - to connect accounts for {credentialGroupName} in the{' '} - {workspaceName} workspace on Sim. + {inviterName ? ( + <> + {inviterName} invited {recipientEmail} + + ) : ( + <> + {recipientEmail} has been invited + + )}{' '} + {searchProviderName ? ( + <> + to connect your {searchProviderName} account for Search in{' '} + {workspaceName}. + + ) : ( + <> + to connect accounts for {credentialGroupName} in the{' '} + {workspaceName} workspace on Sim. + + )} )} @@ -79,7 +85,7 @@ export function CredentialGroupInvitationEmail({
- {requestedProviderName + {workflowRequest ? `Sign in to Sim as ${recipientEmail} to continue. ` : 'This private link expires in 7 days. '} Sim will send you to each provider to sign in and will never ask for your provider password. diff --git a/apps/sim/components/emails/credential-groups/render.ts b/apps/sim/components/emails/credential-groups/render.ts index 561e5b84c7c..b33828da09a 100644 --- a/apps/sim/components/emails/credential-groups/render.ts +++ b/apps/sim/components/emails/credential-groups/render.ts @@ -8,7 +8,7 @@ export async function renderCredentialGroupInvitationEmail(params: { credentialGroupName: string invitationLink: string searchProviderName?: string - requestedProviderName?: string + workflowRequest?: { workflowName: string; providerName: string } }): Promise { return await render(CredentialGroupInvitationEmail(params)) } diff --git a/apps/sim/components/emails/subjects.ts b/apps/sim/components/emails/subjects.ts index 3572424736d..0d44c3db1a5 100644 --- a/apps/sim/components/emails/subjects.ts +++ b/apps/sim/components/emails/subjects.ts @@ -136,6 +136,15 @@ export function getOtpSubject(resourceLabel: string): string { * Names the workspace so an external recipient can identify the request, and the * inviter when there is one — a workflow-issued invitation has no person to name. */ +/** Names the requesting workflow and organization; never text a workflow passed at run time. */ +export function getCredentialGroupConnectionRequestSubject(input: { + workflowName: string + organizationName: string + providerName: string +}): string { + return `${input.workflowName} in ${input.organizationName} asked you to connect ${input.providerName}` +} + export function getCredentialGroupInvitationSubject( inviterName: string | undefined, workspaceName: string diff --git a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx index f1818b25350..3084d467e85 100644 --- a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx +++ b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx @@ -18,6 +18,8 @@ import type { OrganizationConnectionRequestPolicyState } from '@/lib/api/contrac import { CONNECTION_REQUEST_DAILY_LIMIT_DEFAULT, CONNECTION_REQUEST_DAILY_LIMIT_MAX, + FREE_MAIL_DOMAINS, + normalizeConnectionRequestList, } from '@/lib/credential-groups/connection-request-policy' import { SettingsQueryErrorState } from '@/app/workspace/[workspaceId]/settings/components/settings-empty-state' import { SettingsResourceRow } from '@/app/workspace/[workspaceId]/settings/components/settings-resource-row' @@ -29,8 +31,23 @@ import { type Policy = NonNullable const ALL_WORKSPACES = 'all' +const SECTION_LABEL = 'Connection requests from workflows' const TOGGLE_LABEL = 'Let workflows request connections' +const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? '' : 's'}` + +function summarize(policy: Policy): string { + return [ + policy.workspaces.mode === 'all' + ? 'All workspaces' + : plural(policy.workspaces.workspaceIds.length, 'workspace'), + policy.emailDomains.join(', '), + plural(policy.providers.length, 'integration'), + `${policy.dailyLimit} a day`, + policy.sendEmail ? 'Email on' : 'Email off', + ].join(' · ') +} + interface OrganizationConnectionRequestsProps { organizationId: string } @@ -45,10 +62,10 @@ export function OrganizationConnectionRequests({ if (state.error) return ( - + void state.refetch()} variant='inline' @@ -62,21 +79,17 @@ export function OrganizationConnectionRequests({ try { await update.mutateAsync({ organizationId, revision, policy: next }) setEditing(false) - toast.success('Workflow requests updated') + toast.success('Connection requests updated') } catch (error) { - toast.error(getErrorMessage(error, 'Could not update workflow requests')) + toast.error(getErrorMessage(error, 'Could not update connection requests')) } } return ( - + {policy && ( @@ -144,10 +157,10 @@ function ConnectionRequestPolicyModal({ ) const [sendEmail, setSendEmail] = useState(initial?.sendEmail ?? true) - const emailDomains = domains - .split(',') - .map((domain) => domain.trim().toLowerCase().replace(/^@/, '')) - .filter(Boolean) + const emailDomains = normalizeConnectionRequestList( + domains.split(',').map((domain) => domain.trim().replace(/^@/, '')) + ) + const freeMailDomains = emailDomains.filter((domain) => FREE_MAIL_DOMAINS.has(domain)) const limit = Number(dailyLimit) const limitValid = Number.isInteger(limit) && limit >= 1 && limit <= CONNECTION_REQUEST_DAILY_LIMIT_MAX @@ -158,12 +171,12 @@ function ConnectionRequestPolicyModal({ !open && !disabled && onClose()} > - Workflow requests + {SECTION_LABEL} @@ -208,7 +221,15 @@ function ConnectionRequestPolicyModal({ value={domains} onChange={setDomains} placeholder='example.com' - hint='Comma-separated. Only these addresses can be asked.' + hint={ + freeMailDomains.length ? ( + + Anyone with a {freeMailDomains.join(', ')} address could be asked + + ) : ( + "Exact domains only; subdomains aren't included" + ) + } disabled={disabled} /> @@ -241,6 +262,7 @@ function ConnectionRequestPolicyModal({ value={dailyLimit} onChange={setDailyLimit} inputMode='numeric' + hint='Across all workspaces, including reminders' error={ dailyLimit && !limitValid ? `Enter a number from 1 to ${CONNECTION_REQUEST_DAILY_LIMIT_MAX}` diff --git a/apps/sim/hooks/queries/organization-accounts.ts b/apps/sim/hooks/queries/organization-accounts.ts index d01be12887d..7a49ef21c42 100644 --- a/apps/sim/hooks/queries/organization-accounts.ts +++ b/apps/sim/hooks/queries/organization-accounts.ts @@ -372,7 +372,9 @@ export function useUpdateOrganizationConnectionRequestPolicy() { body, }), onSettled: (_data, _error, { organizationId }) => - queryClient.invalidateQueries({ queryKey: organizationAccountsKeys.access(organizationId) }), + queryClient.invalidateQueries({ + queryKey: organizationAccountsKeys.connectionRequests(organizationId), + }), }) } export function useOrganizationAccountPeople( diff --git a/apps/sim/hooks/queries/utils/organization-accounts-keys.ts b/apps/sim/hooks/queries/utils/organization-accounts-keys.ts index 8e45b675d1d..f7077971222 100644 --- a/apps/sim/hooks/queries/utils/organization-accounts-keys.ts +++ b/apps/sim/hooks/queries/utils/organization-accounts-keys.ts @@ -12,7 +12,7 @@ export const organizationAccountsKeys = { workspace: (workspaceId?: string) => [...organizationAccountsKeys.workspaces(), workspaceId ?? ''] as const, access: (id?: string) => [...organizationAccountsKeys.detail(id), 'access'] as const, - /** Under `access`: both edit one policy revision, so invalidating Access refreshes this too. */ + /** Under `access`: its workspace and integration choices come from the Access allowlist. */ connectionRequests: (id?: string) => [...organizationAccountsKeys.access(id), 'connection-requests'] as const, people: (id?: string) => [...organizationAccountsKeys.detail(id), 'people'] as const, diff --git a/apps/sim/lib/api/contracts/organization-accounts.ts b/apps/sim/lib/api/contracts/organization-accounts.ts index 79f5cc6bbb9..6072b1c9498 100644 --- a/apps/sim/lib/api/contracts/organization-accounts.ts +++ b/apps/sim/lib/api/contracts/organization-accounts.ts @@ -17,10 +17,9 @@ import { import { organizationIdSchema, workspaceIdSchema } from '@/lib/api/contracts/primitives' import { defineRouteContract } from '@/lib/api/contracts/types' import { - CONNECTION_REQUEST_DAILY_LIMIT_MAX, - CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT, CONNECTION_REQUEST_PROVIDER_LIMIT, connectionRequestPolicySchema, + storedConnectionRequestPolicySchema, } from '@/lib/credential-groups/connection-request-policy' import { ORGANIZATION_CREDENTIAL_TYPES } from '@/lib/credential-groups/credential-types' import { @@ -223,8 +222,9 @@ export const getOrganizationConnectionRequestPolicyContract = defineRouteContrac response: { mode: 'json', schema: z.object({ - revision: z.number().int().positive(), - policy: connectionRequestPolicySchema.nullable(), + /** `0` while no policy was ever saved, which means requests are off. */ + revision: z.number().int().nonnegative(), + policy: storedConnectionRequestPolicySchema.nullable(), workspaces: z .array(z.object({ id: workspaceIdSchema, name: z.string().max(256) })) .max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT), @@ -235,42 +235,22 @@ export const getOrganizationConnectionRequestPolicyContract = defineRouteContrac }, }) -/** Lists may arrive unsorted or mixed-case; the use case normalizes them before validating. */ -const updateOrganizationConnectionRequestPolicyBodySchema = z - .object({ - revision: z.number().int().positive(), - policy: z - .object({ - enabled: z.boolean(), - workspaces: z.discriminatedUnion('mode', [ - z.object({ mode: z.literal('all') }).strict(), - z - .object({ - mode: z.literal('selected'), - workspaceIds: z.array(workspaceIdSchema).max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT), - }) - .strict(), - ]), - emailDomains: z.array(z.string().max(253)).max(CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT), - providers: z.array(z.string().max(64)).max(CONNECTION_REQUEST_PROVIDER_LIMIT), - dailyLimit: z.number().int().min(1).max(CONNECTION_REQUEST_DAILY_LIMIT_MAX), - sendEmail: z.boolean(), - }) - .strict() - .nullable(), - }) - .strict() - export const updateOrganizationConnectionRequestPolicyContract = defineRouteContract({ method: 'PUT', path: '/api/organizations/[id]/connected-accounts/workflow-requests', params: organizationAccountsParamsSchema, - body: updateOrganizationConnectionRequestPolicyBodySchema, + body: z + .object({ + /** `0` when no policy was saved yet. */ + revision: z.number().int().nonnegative(), + policy: connectionRequestPolicySchema, + }) + .strict(), response: { mode: 'json', schema: z.object({ revision: z.number().int().positive(), - policy: connectionRequestPolicySchema.nullable(), + policy: storedConnectionRequestPolicySchema, }), }, }) diff --git a/apps/sim/lib/core/outbox/handlers.ts b/apps/sim/lib/core/outbox/handlers.ts index a370e2bfebb..9597c28bf11 100644 --- a/apps/sim/lib/core/outbox/handlers.ts +++ b/apps/sim/lib/core/outbox/handlers.ts @@ -22,6 +22,7 @@ import { CHAT_INLINE_IMAGE_CLEANUP_EVENT, } from '@/lib/cleanup/chat-backend-cleanup-event' import type { LazyOutboxHandlerGroup } from '@/lib/core/outbox/service' +import { CONNECTION_REQUEST_EMAIL_EVENT } from '@/lib/credential-groups/connection-request-event' import { EXECUTION_REMOVAL_STOP_EVENT } from '@/lib/execution/removal-stop-event' import { DIRECT_GRANT_EMAIL_EVENT_TYPE } from '@/lib/invitations/direct-grant-event' import { SLACK_SEARCH_TURN_EVENT } from '@/lib/knowledge/application/slack-search/turn-event' @@ -173,6 +174,15 @@ export const OUTBOX_HANDLER_GROUPS: readonly LazyOutboxHandlerGroup[] = [ return invitationMigrationOutboxHandlers }, }, + { + events: [CONNECTION_REQUEST_EMAIL_EVENT], + load: async () => { + const { credentialGroupConnectionRequestOutboxHandlers } = await import( + '@/lib/credential-groups/connection-request-email' + ) + return credentialGroupConnectionRequestOutboxHandlers + }, + }, { events: [DIRECT_GRANT_EMAIL_EVENT_TYPE], load: async () => { diff --git a/apps/sim/lib/core/outbox/retention.ts b/apps/sim/lib/core/outbox/retention.ts index 4814c2ee9f3..22ddc79cf2e 100644 --- a/apps/sim/lib/core/outbox/retention.ts +++ b/apps/sim/lib/core/outbox/retention.ts @@ -9,6 +9,7 @@ import { CHAT_INLINE_IMAGE_CLEANUP_EVENT, } from '@/lib/cleanup/chat-backend-cleanup-event' import { getRedisClient } from '@/lib/core/config/redis' +import { CONNECTION_REQUEST_EMAIL_EVENT } from '@/lib/credential-groups/connection-request-event' import { EMBEDDING_CHECKPOINT_CLEANUP_EVENT, OCR_CHECKPOINT_CLEANUP_OUTBOX_EVENT, @@ -58,6 +59,7 @@ const PRUNABLE_OUTBOX_EVENT_TYPES = [ MEMORY_CLEANUP_EVENT, CHAT_BACKEND_CLEANUP_EVENT, CHAT_INLINE_IMAGE_CLEANUP_EVENT, + CONNECTION_REQUEST_EMAIL_EVENT, ] as const /** diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index cf36b483a2f..18aa7fbc0eb 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -7,24 +7,32 @@ * workspace outside the Access allowlist reading status; another organization's accounts leaking * in; a request without (or outside) the admin policy succeeding; a request reactivating a * revoked person or re-attributing an admin invitation; concurrent requests creating two rows; - * the daily cap being exceeded; per-person outcomes being distinguishable from the result. + * the daily cap being exceeded, or skipped for an address that already has an enrollment; the cap + * error differing by target; a `+` alias slipping in; reminders beyond the per-enrollment cap or + * after 30 days; a revocation racing a reminder still emailing; an admin unable to turn requests + * off after their choices went stale; saving either the request policy or Access changing the + * other. */ import type { WorkflowExecutionDelegatedPrincipal } from '@sim/auth/principal' import { db } from '@sim/db' import { credential, credentialGroup, + credentialGroupConnectionRequest, + credentialGroupConnectionRequestPolicy, credentialGroupEnrollment, member, organization, + outboxEvent, resourcePolicy, user, workspace, } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' import { sha256Hex } from '@sim/security/hash' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' import { generateId } from '@sim/utils/id' -import { and, eq, inArray, isNotNull } from 'drizzle-orm' +import { and, eq, inArray, isNotNull, sql } from 'drizzle-orm' import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { OrchestrationError } from '@/lib/core/orchestration/types' import { CREDENTIAL_GROUP_DELEGATION_AUDIENCE } from '@/lib/credential-groups/application/authorization' @@ -32,7 +40,13 @@ import { getOrganizationAccountConnectionStatus, requestOrganizationAccountConnection, } from '@/lib/credential-groups/application/connection-requests' +import { updateOrganizationAccountWorkspaceAccess } from '@/lib/credential-groups/application/organization-access' +import { + getOrganizationConnectionRequestPolicy, + updateOrganizationConnectionRequestPolicy, +} from '@/lib/credential-groups/application/organization-connection-requests' import { buildOrganizationAccountAccessPolicy } from '@/lib/credential-groups/application/workspace-access-policy' +import { CONNECTION_REQUEST_EMAIL_EVENT } from '@/lib/credential-groups/connection-request-event' import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' import type { CredentialGroupOAuthContext } from '@/lib/credential-groups/enrollments' import { completeCredentialGroupOAuth } from '@/lib/credential-groups/oauth' @@ -46,6 +60,11 @@ vi.mock('@/lib/credential-groups/scoped-availability', () => ({ isScopedCredentialGroupsAvailable: async () => true, })) +/** Delivery is outside this suite: the enqueued outbox event is what a request controls. */ +vi.mock('@/lib/messaging/email/mailer', () => ({ + sendEmail: async () => ({ success: true, message: 'sent' }), +})) + vi.mock('@/lib/credential-groups/provider-registry', async (importOriginal) => { const { getCredentialGroupProviderId: providerIdOf } = await import( '@/lib/credential-groups/providers' @@ -91,6 +110,7 @@ interface OrgFixture { workspaceId: string outsideWorkspaceId: string policyId: string + adminId: string } const ownerId = generateId() @@ -99,6 +119,8 @@ const domain = `${generateId().slice(0, 12).toLowerCase()}.test` const people = new Map() let orgA: OrgFixture let orgB: OrgFixture +let orgC: OrgFixture +const DAY_MS = 24 * 60 * 60 * 1000 const address = (label: string) => `${label}@${domain}` @@ -110,6 +132,7 @@ async function createOrg(): Promise { workspaceId: generateId(), outsideWorkspaceId: generateId(), policyId: generateId(), + adminId: generateId(), } await db.insert(organization).values({ id: fixture.organizationId, @@ -117,6 +140,22 @@ async function createOrg(): Promise { slug: fixture.organizationId, createdAt: new Date(), }) + await db.insert(user).values({ + id: fixture.adminId, + name: 'Admin', + email: `admin-${fixture.adminId}@${domain}`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }) + people.set(fixture.adminId, fixture.adminId) + await db.insert(member).values({ + id: generateId(), + organizationId: fixture.organizationId, + userId: fixture.adminId, + role: 'owner', + createdAt: new Date(), + }) await insertWorkspaceFixture( db, [fixture.workspaceId, fixture.outsideWorkspaceId].map((id) => ({ @@ -148,15 +187,12 @@ async function createOrg(): Promise { async function setRequestPolicy(fixture: OrgFixture, requests: ConnectionRequestPolicy | null) { await db - .update(resourcePolicy) - .set({ - document: buildOrganizationAccountAccessPolicy( - fixture.groupId, - [{ workspaceId: fixture.workspaceId, access: { mode: 'all' } }], - requests - ), - }) - .where(eq(resourcePolicy.id, fixture.policyId)) + .delete(credentialGroupConnectionRequestPolicy) + .where(eq(credentialGroupConnectionRequestPolicy.credentialGroupId, fixture.groupId)) + if (requests) + await db + .insert(credentialGroupConnectionRequestPolicy) + .values({ credentialGroupId: fixture.groupId, policy: requests }) } const OPEN_POLICY: ConnectionRequestPolicy = { @@ -294,6 +330,46 @@ async function connectPerson(fixture: OrgFixture, email: string) { return { enrollmentId, credentialId } } +const emailEvents = (enrollmentId: string) => + db + .select({ id: outboxEvent.id }) + .from(outboxEvent) + .where( + and( + eq(outboxEvent.eventType, CONNECTION_REQUEST_EMAIL_EVENT), + sql`${outboxEvent.payload} ->> 'enrollmentId' = ${enrollmentId}` + ) + ) + +/** Moves every logged request for this address back past the one-day windows. */ +const ageRequests = (fixture: OrgFixture, email: string) => + db + .update(credentialGroupConnectionRequest) + .set({ createdAt: new Date(Date.now() - DAY_MS - 3_600_000) }) + .where( + and( + eq(credentialGroupConnectionRequest.credentialGroupId, fixture.groupId), + eq(credentialGroupConnectionRequest.email, email) + ) + ) + +const clearRequestLog = (fixture: OrgFixture) => + db + .delete(credentialGroupConnectionRequest) + .where(eq(credentialGroupConnectionRequest.credentialGroupId, fixture.groupId)) + +/** Resolves once some query waits on a row lock, so a test can commit the holder mid-request. */ +async function waitForLockedQuery() { + for (let attempt = 0; attempt < 200; attempt++) { + const waiting = await db.execute( + sql`SELECT 1 FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query ILIKE '%credential_group_enrollment%'` + ) + if (waiting.length) return + await new Promise((resolve) => setTimeout(resolve, 25)) + } + throw new Error('The request never waited on the revocation') +} + const enrollmentsFor = (fixture: OrgFixture, email: string) => db .select() @@ -316,10 +392,21 @@ beforeAll(async () => { }) orgA = await createOrg() orgB = await createOrg() + orgC = await createOrg() }) afterAll(async () => { - const organizations = [orgA, orgB].flatMap((fixture) => (fixture ? [fixture.organizationId] : [])) + await db + .delete(outboxEvent) + .where( + and( + eq(outboxEvent.eventType, CONNECTION_REQUEST_EMAIL_EVENT), + sql`${outboxEvent.payload} ->> 'workflowId' = ${workflowId}` + ) + ) + const organizations = [orgA, orgB, orgC].flatMap((fixture) => + fixture ? [fixture.organizationId] : [] + ) await deleteWorkspaceFixture(db, inArray(workspace.organizationId, organizations)) await db.delete(organization).where(inArray(organization.id, organizations)) await db.delete(user).where(inArray(user.id, [ownerId, ...people.values()])) @@ -335,7 +422,6 @@ describe('get_connection_status', () => { status: 'connected', connected: true, credentialId, - provider: DRIVE_ID, connectUrl: connectUrl(), }) }) @@ -350,7 +436,6 @@ describe('get_connection_status', () => { status: 'needs_reconnect', connected: false, credentialId: null, - provider: DRIVE_ID, connectUrl: connectUrl(), }) }) @@ -375,7 +460,6 @@ describe('get_connection_status', () => { status: 'not_connected', connected: false, credentialId: null, - provider: DRIVE_ID, connectUrl: connectUrl(), }) }) @@ -503,3 +587,198 @@ describe('request_connection', () => { expect((await refusal(request(orgB, address('cap-5')))).code).toBe('conflict') }) }) + +describe('request_connection input and daily limit', () => { + beforeEach(async () => { + await setRequestPolicy(orgA, OPEN_POLICY) + await setRequestPolicy(orgC, { ...OPEN_POLICY, dailyLimit: 2 }) + await clearRequestLog(orgC) + }) + + it('refuses a + alias before anything about the person is read or logged', async () => { + const alias = `alias+tag@${domain}` + const error = await refusal(request(orgA, alias)) + expect(error.code).toBe('validation') + expect(error.message).toContain('primary email address') + expect(await enrollmentsFor(orgA, alias)).toEqual([]) + expect( + await db + .select({ id: credentialGroupConnectionRequest.id }) + .from(credentialGroupConnectionRequest) + .where(eq(credentialGroupConnectionRequest.email, alias)) + ).toEqual([]) + }) + + it('counts requests for an address that already has an enrollment', async () => { + await enroll(orgC, address('limit-existing')) + await request(orgC, address('limit-existing')) + await request(orgC, address('limit-existing')) + expect((await refusal(request(orgC, address('limit-new')))).code).toBe('conflict') + expect(await enrollmentsFor(orgC, address('limit-new'))).toEqual([]) + }) + + it('fails the same way at the limit whatever the target', async () => { + await enroll(orgC, address('limit-known')) + await request(orgC, address('limit-filler-1')) + await request(orgC, address('limit-filler-2')) + const known = await refusal(request(orgC, address('limit-known'))) + const revoked = await refusal(request(orgC, address('revoked-request'))) + const unknown = await refusal(request(orgC, address('limit-unknown'))) + for (const error of [known, revoked]) + expect({ code: error.code, message: error.message }).toEqual({ + code: unknown.code, + message: unknown.message, + }) + }) +}) + +describe('connection request emails', () => { + beforeEach(async () => { + await setRequestPolicy(orgA, { ...OPEN_POLICY, sendEmail: true }) + }) + + it('emails a new request, then at most three reminders, each after a day without a request', async () => { + const email = address('reminded') + await request(orgA, email) + const [enrollment] = await enrollmentsFor(orgA, email) + if (!enrollment) throw new Error('Request created no enrollment') + expect(await emailEvents(enrollment.id)).toHaveLength(1) + await request(orgA, email) + expect(await emailEvents(enrollment.id)).toHaveLength(1) + for (const expected of [2, 3, 4, 4]) { + await ageRequests(orgA, email) + await request(orgA, email) + expect(await emailEvents(enrollment.id)).toHaveLength(expected) + } + }) + + it('sends no reminder once the enrollment was requested more than 30 days ago', async () => { + const email = address('long-ago') + await request(orgA, email) + const [enrollment] = await enrollmentsFor(orgA, email) + if (!enrollment) throw new Error('Request created no enrollment') + await db + .update(credentialGroupEnrollment) + .set({ createdAt: new Date(Date.now() - 31 * DAY_MS) }) + .where(eq(credentialGroupEnrollment.id, enrollment.id)) + await ageRequests(orgA, email) + await request(orgA, email) + expect(await emailEvents(enrollment.id)).toHaveLength(1) + }) + + it('sends nothing when a revocation commits while the reminder is being claimed', async () => { + const email = address('revoke-race') + await request(orgA, email) + const [enrollment] = await enrollmentsFor(orgA, email) + if (!enrollment) throw new Error('Request created no enrollment') + await ageRequests(orgA, email) + + let release = () => {} + const held = new Promise((resolve) => { + release = resolve + }) + let markLocked = () => {} + const locked = new Promise((resolve) => { + markLocked = resolve + }) + const revocation = db.transaction(async (tx) => { + await tx + .update(credentialGroupEnrollment) + .set({ status: 'revoked', revokedAt: new Date() }) + .where(eq(credentialGroupEnrollment.id, enrollment.id)) + markLocked() + await held + }) + await locked + const reminder = request(orgA, email) + await waitForLockedQuery() + release() + await revocation + expect(await reminder).toMatchObject({ requested: true }) + expect(await emailEvents(enrollment.id)).toHaveLength(1) + }) +}) + +describe('admin connection request settings', () => { + const admin = (fixture: OrgFixture) => + createSessionPrincipal({ userId: fixture.adminId, sessionId: generateId() }) + const read = (fixture: OrgFixture) => + getOrganizationConnectionRequestPolicy.execute({ + principal: admin(fixture), + input: { organizationId: fixture.organizationId }, + }) + const save = (fixture: OrgFixture, revision: number, policy: ConnectionRequestPolicy) => + updateOrganizationConnectionRequestPolicy.execute({ + principal: admin(fixture), + input: { organizationId: fixture.organizationId, revision, policy }, + }) + const setAccess = (fixture: OrgFixture, workspaceIds: string[]) => + db + .update(resourcePolicy) + .set({ + document: buildOrganizationAccountAccessPolicy( + fixture.groupId, + workspaceIds.map((workspaceId) => ({ workspaceId, access: { mode: 'all' as const } })) + ), + }) + .where(eq(resourcePolicy.id, fixture.policyId)) + const accessRow = (fixture: OrgFixture) => + db + .select({ + document: sql`${resourcePolicy.document}::text`, + revision: resourcePolicy.revision, + }) + .from(resourcePolicy) + .where(eq(resourcePolicy.id, fixture.policyId)) + const requestPolicyRow = (fixture: OrgFixture) => + db + .select() + .from(credentialGroupConnectionRequestPolicy) + .where(eq(credentialGroupConnectionRequestPolicy.credentialGroupId, fixture.groupId)) + const selected = (fixture: OrgFixture): ConnectionRequestPolicy => ({ + ...OPEN_POLICY, + workspaces: { mode: 'selected', workspaceIds: [fixture.workspaceId] }, + }) + + beforeEach(async () => { + await setRequestPolicy(orgC, null) + await setAccess(orgC, [orgC.workspaceId]) + }) + + it('lets an admin turn requests off after a selected workspace left the Access tab', async () => { + const saved = await save(orgC, 0, selected(orgC)) + await setAccess(orgC, [orgC.outsideWorkspaceId]) + + const state = await read(orgC) + expect(state.policy?.workspaces).toEqual({ mode: 'selected', workspaceIds: [] }) + const off = await save(orgC, saved.revision, { ...selected(orgC), enabled: false }) + expect(off.policy).toMatchObject({ + enabled: false, + workspaces: { mode: 'selected', workspaceIds: [] }, + }) + expect((await refusal(save(orgC, off.revision, selected(orgC)))).code).toBe('validation') + }) + + it('leaves the Access document untouched, and Access saves leave the request policy alone', async () => { + const accessBefore = await accessRow(orgC) + await save(orgC, 0, selected(orgC)) + expect(await accessRow(orgC)).toEqual(accessBefore) + + const [access] = accessBefore + if (!access) throw new Error('Access policy is missing') + const requestsBefore = await requestPolicyRow(orgC) + await updateOrganizationAccountWorkspaceAccess.execute({ + principal: admin(orgC), + input: { + organizationId: orgC.organizationId, + revision: access.revision, + grants: [orgC.workspaceId, orgC.outsideWorkspaceId].map((workspaceId) => ({ + workspaceId, + access: { mode: 'all' as const }, + })), + }, + }) + expect((await accessRow(orgC))[0]?.revision).toBe(access.revision + 1) + expect(await requestPolicyRow(orgC)).toEqual(requestsBefore) + }) +}) diff --git a/apps/sim/lib/credential-groups/application/authorization.ts b/apps/sim/lib/credential-groups/application/authorization.ts index 2cf5260e06c..a291f092678 100644 --- a/apps/sim/lib/credential-groups/application/authorization.ts +++ b/apps/sim/lib/credential-groups/application/authorization.ts @@ -63,7 +63,8 @@ function requireWorkflowExecutionPrincipal(principal: Principal): WorkflowExecut return executionPrincipal } -function requireCurrentWorkflow(principal: Principal): WorkflowExecutionAuthority { +/** The workflow whose run holds this executor delegation. */ +export function requireCurrentWorkflow(principal: Principal): WorkflowExecutionAuthority { if (principal.kind !== 'delegated' || principal.serviceId !== 'executor') { throw new Error('Credential Group use requires an executor delegation') } @@ -91,13 +92,6 @@ function requireConsistentWorkflowSubject( return subject } -/** The workflow whose run holds this executor delegation, for attribution only. */ -export function requireCredentialGroupCurrentWorkflow( - principal: Principal -): WorkflowExecutionAuthority { - return requireCurrentWorkflow(principal) -} - /** * Asserts the delegation still names the subject its run was minted for, without * requiring that subject to be a Sim user. diff --git a/apps/sim/lib/credential-groups/application/connection-requests.ts b/apps/sim/lib/credential-groups/application/connection-requests.ts index 7b9e25aa6ea..d210db3dc8f 100644 --- a/apps/sim/lib/credential-groups/application/connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/connection-requests.ts @@ -2,10 +2,12 @@ import { AuditAction, AuditResourceType } from '@sim/audit' import { isValidEmailSyntax, normalizeEmail } from '@sim/utils/string' import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' import { OrchestrationError } from '@/lib/core/orchestration/types' +import { processOutboxEventById } from '@/lib/core/outbox/service' +import { runDetached } from '@/lib/core/utils/background' import { credentialGroupDelegationPolicy, - requireCredentialGroupCurrentWorkflow, requireCredentialGroupWorkflowActor, + requireCurrentWorkflow, } from '@/lib/credential-groups/application/authorization' import { credentialGroupOperations } from '@/lib/credential-groups/application/operations' import { @@ -16,16 +18,15 @@ import { import { type OrganizationAccountAccessPolicy, organizationAccountPolicyAllowsWorkspace, - readWorkflowConnectionRequestPolicy, } from '@/lib/credential-groups/application/workspace-access-policy' import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' import { ConnectionRequestDailyLimitError, loadConnectionRequestGroup, + loadConnectionRequestPolicy, loadOrganizationAccountConnectionStatus, type OrganizationAccountConnectionStatus, recordCredentialGroupConnectionRequest, - sendConnectionRequestEmail, } from '@/lib/credential-groups/connection-requests' import { getCredentialGroupProviderId, @@ -43,7 +44,6 @@ export interface OrganizationAccountConnectionStatusResult { status: OrganizationAccountConnectionStatus connected: boolean credentialId: string | null - provider: string connectUrl: string } @@ -60,6 +60,30 @@ function requireEmail(value: string): string { return email } +/** + * A request is bound to the address an enrollment would be. A `+` alias would let one mailbox + * collect several enrollments and daily-limit slots, so it is refused before anything is read. + */ +function requireRequestableEmail(value: string): string { + const email = requireEmail(value) + if (email.slice(0, email.lastIndexOf('@')).includes('+')) + throw new OrchestrationError( + 'validation', + "Use the person's primary email address, without a + alias" + ) + return email +} + +/** Sends the enqueued email now, off the request path; the outbox worker retries it otherwise. */ +function deliverSoon(eventId: string) { + runDetached('credential-group-connection-request-email', async () => { + const { credentialGroupConnectionRequestOutboxHandlers } = await import( + '@/lib/credential-groups/connection-request-email' + ) + await processOutboxEventById(eventId, credentialGroupConnectionRequestOutboxHandlers) + }) +} + /** * Resolves the group options collecting this provider that the executing workspace may use, * with the same errors List Organization Accounts gives for an inactive or disallowed provider. @@ -135,7 +159,6 @@ export const getOrganizationAccountConnectionStatus = defineAuthorizedWorkspaceU status, connected: status === 'connected', credentialId, - provider: input.providerId, connectUrl: buildCredentialGroupConnectUrl({ publicId: group.publicId, provider: input.providerId, @@ -167,10 +190,10 @@ export const requestOrganizationAccountConnection = defineAuthorizedWorkspaceUse context.workspaceAccessPolicy = await requireOrganizationAccountsWorkspaceAccess(context) }, execute: async ({ principal, input, context }): Promise => { - const { workflowId } = requireCredentialGroupCurrentWorkflow(principal) - const email = requireEmail(input.email) + const { workflowId } = requireCurrentWorkflow(principal) + const email = requireRequestableEmail(input.email) const accessPolicy = requireWorkspacePolicy(context) - const requests = readWorkflowConnectionRequestPolicy(accessPolicy) + const { policy: requests } = await loadConnectionRequestPolicy(context.credentialGroupId) if (!requests?.enabled) throw new OrchestrationError( 'forbidden', @@ -207,7 +230,10 @@ export const requestOrganizationAccountConnection = defineAuthorizedWorkspaceUse recorded = await recordCredentialGroupConnectionRequest({ credentialGroupId: context.credentialGroupId, email, + workspaceId: context.workspaceId, workflowId, + providerName: label, + connectUrl, dailyLimit: requests.dailyLimit, sendEmail: requests.sendEmail, }) @@ -216,15 +242,7 @@ export const requestOrganizationAccountConnection = defineAuthorizedWorkspaceUse throw new OrchestrationError('conflict', error.message) throw error } - if (recorded.notify) - await sendConnectionRequestEmail({ - enrollmentId: recorded.enrollmentId, - email, - organizationName: group.organizationName, - credentialGroupName: group.groupName, - providerName: label, - connectUrl, - }) + if (recorded.emailEventId) deliverSoon(recorded.emailEventId) return { requested: true, connectUrl, diff --git a/apps/sim/lib/credential-groups/application/organization-access.ts b/apps/sim/lib/credential-groups/application/organization-access.ts index c16516f49af..f05d749ee24 100644 --- a/apps/sim/lib/credential-groups/application/organization-access.ts +++ b/apps/sim/lib/credential-groups/application/organization-access.ts @@ -10,7 +10,6 @@ import { buildOrganizationAccountAccessPolicy, listOrganizationAccountWorkspaceGrants, organizationAccountAccessPolicyCodec, - readWorkflowConnectionRequestPolicy, } from '@/lib/credential-groups/application/workspace-access-policy' import { getOrganizationCredentialTypeCatalog } from '@/lib/credential-groups/credential-types' import { loadScopedAccountsCredentialListContext } from '@/lib/credential-groups/credentials' @@ -126,22 +125,7 @@ export const updateOrganizationAccountWorkspaceAccess = defineOrganizationAccoun 'Every allowed workspace must be active and belong to this organization' ) } - const current = await requireResourcePolicy({ - organizationId: context.organizationId, - resourceType: 'credential_group', - resourceId: group.credentialGroupId, - codec: organizationAccountAccessPolicyCodec, - }) - if (current.revision !== input.revision) - throw new OrchestrationError( - 'conflict', - 'Workspace access changed. Reload before saving again.' - ) - const document = buildOrganizationAccountAccessPolicy( - group.credentialGroupId, - parsed.data, - readWorkflowConnectionRequestPolicy(current.document) - ) + const document = buildOrganizationAccountAccessPolicy(group.credentialGroupId, parsed.data) /** Indented JSON conservatively includes the whitespace PostgreSQL adds to jsonb text. */ if ( Buffer.byteLength(JSON.stringify(document, null, 1), 'utf8') > diff --git a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts index 4a02eaa3167..67dfec53b24 100644 --- a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts @@ -8,24 +8,23 @@ import { defineOrganizationAccountsUseCase } from '@/lib/credential-groups/appli import { listOrganizationAccountWorkspaceIds, organizationAccountAccessPolicyCodec, - readWorkflowConnectionRequestPolicy, - withWorkflowConnectionRequestPolicy, } from '@/lib/credential-groups/application/workspace-access-policy' import { type ConnectionRequestPolicy, + type ConnectionRequestPolicyInput, connectionRequestPolicySchema, - normalizeConnectionRequestList, } from '@/lib/credential-groups/connection-request-policy' +import { + ConnectionRequestPolicyConflictError, + loadConnectionRequestPolicy, + writeConnectionRequestPolicy, +} from '@/lib/credential-groups/connection-requests' import { loadScopedAccountsCredentialListContext } from '@/lib/credential-groups/credentials' import { getCredentialGroupProviderId, isCredentialGroupProvider, } from '@/lib/credential-groups/providers' -import { - ResourcePolicyRevisionConflictError, - requireResourcePolicy, - writeResourcePolicy, -} from '@/lib/resource-policies/repository' +import { requireResourcePolicy } from '@/lib/resource-policies/repository' export const organizationConnectionRequestOperations = { read: defineOrganizationOperation({ @@ -55,13 +54,16 @@ async function loadConnectionRequestState(organizationId: string) { }) if (!group) throw new OrchestrationError('not_found', 'Organization connected accounts are not configured') - const policy = await requireResourcePolicy({ - organizationId, - resourceType: 'credential_group', - resourceId: group.credentialGroupId, - codec: organizationAccountAccessPolicyCodec, - }) - const accessWorkspaceIds = listOrganizationAccountWorkspaceIds(policy.document) + const [access, stored] = await Promise.all([ + requireResourcePolicy({ + organizationId, + resourceType: 'credential_group', + resourceId: group.credentialGroupId, + codec: organizationAccountAccessPolicyCodec, + }), + loadConnectionRequestPolicy(group.credentialGroupId), + ]) + const accessWorkspaceIds = listOrganizationAccountWorkspaceIds(access.document) const workspaces = accessWorkspaceIds.length ? await db .select({ id: workspace.id, name: workspace.name }) @@ -80,107 +82,114 @@ async function loadConnectionRequestState(organizationId: string) { ? [{ id: getCredentialGroupProviderId(option.provider), label: option.label }] : [] ) - return { group, policy, workspaces, providers } + return { group, stored, workspaces, providers } +} + +/** + * Drops workspaces no longer on the Access tab and integrations no longer active. Requests from + * those are refused anyway; pruning keeps the admin from seeing or re-saving stale choices. + */ +function pruneConnectionRequestPolicy( + policy: ConnectionRequestPolicy, + workspaceIds: ReadonlySet, + providerIds: ReadonlySet +): ConnectionRequestPolicy { + return { + ...policy, + workspaces: + policy.workspaces.mode === 'all' + ? policy.workspaces + : { + mode: 'selected', + workspaceIds: policy.workspaces.workspaceIds.filter((id) => workspaceIds.has(id)), + }, + providers: policy.providers.filter((id) => providerIds.has(id)), + } } export const getOrganizationConnectionRequestPolicy = defineOrganizationAccountsUseCase({ operation: organizationConnectionRequestOperations.read, async execute({ context }) { - const { policy, workspaces, providers } = await loadConnectionRequestState( + const { stored, workspaces, providers } = await loadConnectionRequestState( context.organizationId ) return { - revision: policy.revision, - policy: readWorkflowConnectionRequestPolicy(policy.document), + revision: stored.revision, + policy: + stored.policy && + pruneConnectionRequestPolicy( + stored.policy, + new Set(workspaces.map((entry) => entry.id)), + new Set(providers.map((provider) => provider.id)) + ), workspaces, providers, } }, }) +/** + * Saves the admin's policy. Turning requests on requires every chosen workspace to be on the + * Access tab and every integration to be active; turning them off never fails on choices that + * went stale, which are pruned instead. + */ export const updateOrganizationConnectionRequestPolicy = defineOrganizationAccountsUseCase({ operation: organizationConnectionRequestOperations.update, async execute({ input, context, }: { - input: { organizationId: string; revision: number; policy: ConnectionRequestPolicy | null } + input: { organizationId: string; revision: number; policy: ConnectionRequestPolicyInput } context: OrganizationMembershipContext }) { - const parsed = input.policy - ? connectionRequestPolicySchema.safeParse({ - ...input.policy, - emailDomains: normalizeConnectionRequestList(input.policy.emailDomains), - providers: normalizeConnectionRequestList(input.policy.providers), - workspaces: - input.policy.workspaces.mode === 'all' - ? input.policy.workspaces - : { - mode: 'selected', - workspaceIds: [...new Set(input.policy.workspaces.workspaceIds)].sort(), - }, - }) - : null - if (parsed && !parsed.success) + const parsed = connectionRequestPolicySchema.safeParse(input.policy) + if (!parsed.success) throw new OrchestrationError( 'validation', parsed.error.issues[0]?.message ?? 'Connection request settings are invalid' ) - const next = parsed?.data ?? null - const { group, policy, workspaces, providers } = await loadConnectionRequestState( + const { group, workspaces, providers } = await loadConnectionRequestState( context.organizationId ) - if (policy.revision !== input.revision) - throw new OrchestrationError( - 'conflict', - 'Connection request settings changed. Reload before saving again.' - ) - if (next) { - const allowedProviders = new Set(providers.map((provider) => provider.id)) - if (next.providers.some((provider) => !allowedProviders.has(provider))) + const workspaceIds = new Set(workspaces.map((entry) => entry.id)) + const providerIds = new Set(providers.map((provider) => provider.id)) + const next = parsed.data + if (next.enabled) { + if (next.providers.some((provider) => !providerIds.has(provider))) throw new OrchestrationError( 'validation', 'Every integration must be an active integration in this organization' ) - const allowedWorkspaces = new Set(workspaces.map((entry) => entry.id)) if ( next.workspaces.mode === 'selected' && - next.workspaces.workspaceIds.some((workspaceId) => !allowedWorkspaces.has(workspaceId)) + next.workspaces.workspaceIds.some((workspaceId) => !workspaceIds.has(workspaceId)) ) throw new OrchestrationError( 'validation', 'Every workspace must already be allowed on the Access tab' ) } + const policy = next.enabled + ? next + : pruneConnectionRequestPolicy(next, workspaceIds, providerIds) try { - const written = await writeResourcePolicy({ - organizationId: context.organizationId, - resourceType: 'credential_group', - resourceId: group.credentialGroupId, - codec: organizationAccountAccessPolicyCodec, + const revision = await writeConnectionRequestPolicy({ + credentialGroupId: group.credentialGroupId, expectedRevision: input.revision, - document: withWorkflowConnectionRequestPolicy(policy.document, next), + policy, actorUserId: context.userId, }) - return { - credentialGroupId: group.credentialGroupId, - name: group.name, - revision: written.revision, - policy: readWorkflowConnectionRequestPolicy(written.document), - } + return { credentialGroupId: group.credentialGroupId, name: group.name, revision, policy } } catch (error) { - if (error instanceof ResourcePolicyRevisionConflictError) - throw new OrchestrationError( - 'conflict', - 'Connection request settings changed. Reload before saving again.' - ) + if (error instanceof ConnectionRequestPolicyConflictError) + throw new OrchestrationError('conflict', error.message) throw error } }, projectAudit: (result) => ({ resourceId: result.credentialGroupId, resourceName: result.name, - description: result.policy?.enabled + description: result.policy.enabled ? 'Allowed workflows to request account connections' : 'Turned off workflow connection requests', }), diff --git a/apps/sim/lib/credential-groups/application/workspace-access-policy.test.ts b/apps/sim/lib/credential-groups/application/workspace-access-policy.test.ts index 52f2033f54c..7af6872999c 100644 --- a/apps/sim/lib/credential-groups/application/workspace-access-policy.test.ts +++ b/apps/sim/lib/credential-groups/application/workspace-access-policy.test.ts @@ -1,4 +1,3 @@ -import { validateOrganizationAccountPolicyDocument } from '@sim/db/credential-group-resource-policies' import { describe, expect, it } from 'vitest' import { buildOrganizationAccountAccessPolicy, @@ -6,10 +5,7 @@ import { listOrganizationAccountWorkspaceIds, organizationAccountAccessPolicyCodec, organizationAccountPolicyAllowsWorkspace, - readWorkflowConnectionRequestPolicy, - withWorkflowConnectionRequestPolicy, } from '@/lib/credential-groups/application/workspace-access-policy' -import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' import { organizationAccountWorkspaceGrantsSchema } from '@/lib/credential-groups/workspace-grants' describe('organization account workspace policy', () => { @@ -157,9 +153,7 @@ describe('integration-specific organization grants', () => { ...policy, statements: [ { - ...policy.statements.find( - (statement) => 'condition' in statement && statement.condition - ), + ...policy.statements.find((statement) => statement.condition), condition: { StringEquals: { 'credential_group:CredentialType': types } }, }, ], @@ -171,12 +165,8 @@ describe('integration-specific organization grants', () => { }) it('rejects ambiguous overlapping or duplicate statements', () => { - const selected = policy.statements.find( - (statement) => 'condition' in statement && statement.condition - )! - const unrestricted = policy.statements.find( - (statement) => !('condition' in statement && statement.condition) - )! + const selected = policy.statements.find((statement) => statement.condition)! + const unrestricted = policy.statements.find((statement) => !statement.condition)! for (const statements of [ [selected, selected], [selected, { ...unrestricted, principals: selected.principals }], @@ -191,69 +181,3 @@ describe('integration-specific organization grants', () => { } }) }) - -describe('workflow connection request statement', () => { - const expected = { type: 'credential_group' as const, id: 'group-1' } - const requests: ConnectionRequestPolicy = { - enabled: true, - workspaces: { mode: 'selected', workspaceIds: ['workspace-requests'] }, - emailDomains: ['example.com'], - providers: ['google-drive'], - dailyLimit: 50, - sendEmail: true, - } - const grants = [{ workspaceId: 'workspace-1', access: { mode: 'all' as const } }] - - it('parses a version 2 document saved before requests existed, with requests off', () => { - const stored = { - version: 2, - resource: { type: 'credential_group', id: 'group-1' }, - statements: [ - { - sid: 'WorkspaceCredentialAccess', - effect: 'allow', - actions: ['credential_groups.credentials.use'], - principals: [{ type: 'workspace', workspaceId: 'workspace-1' }], - }, - ], - } - const document = organizationAccountAccessPolicyCodec.parse(stored, expected) - expect(readWorkflowConnectionRequestPolicy(document)).toBeNull() - expect(listOrganizationAccountWorkspaceGrants(document)).toEqual(grants) - }) - - it('round-trips the policy without granting its workspaces credential use', () => { - const document = organizationAccountAccessPolicyCodec.parse( - buildOrganizationAccountAccessPolicy('group-1', grants, requests), - expected - ) - expect(readWorkflowConnectionRequestPolicy(document)).toEqual(requests) - expect(listOrganizationAccountWorkspaceGrants(document)).toEqual(grants) - expect(listOrganizationAccountWorkspaceIds(document)).toEqual(['workspace-1']) - expect(organizationAccountPolicyAllowsWorkspace(document, 'workspace-requests')).toBe(false) - expect(organizationAccountPolicyAllowsWorkspace(document, 'workspace-1')).toBe(true) - expect( - readWorkflowConnectionRequestPolicy(withWorkflowConnectionRequestPolicy(document, null)) - ).toBeNull() - }) - - it('is accepted by the database policy validator', () => { - for (const workspaces of [requests.workspaces, { mode: 'all' as const }]) - expect(() => - validateOrganizationAccountPolicyDocument( - buildOrganizationAccountAccessPolicy('group-1', grants, { ...requests, workspaces }), - 'group-1' - ) - ).not.toThrow() - }) - - it('rejects wildcard domains, an empty domain list, and an out-of-range daily limit', () => { - for (const invalid of [ - { ...requests, emailDomains: ['*.example.com'] }, - { ...requests, emailDomains: [] }, - { ...requests, dailyLimit: 1001 }, - { ...requests, dailyLimit: 0 }, - ]) - expect(() => buildOrganizationAccountAccessPolicy('group-1', grants, invalid)).toThrow() - }) -}) diff --git a/apps/sim/lib/credential-groups/application/workspace-access-policy.ts b/apps/sim/lib/credential-groups/application/workspace-access-policy.ts index 447dede82db..bc037f9277c 100644 --- a/apps/sim/lib/credential-groups/application/workspace-access-policy.ts +++ b/apps/sim/lib/credential-groups/application/workspace-access-policy.ts @@ -1,8 +1,4 @@ import { z } from 'zod' -import { - type ConnectionRequestPolicy, - connectionRequestSettingsSchema, -} from '@/lib/credential-groups/connection-request-policy' import { ORGANIZATION_CREDENTIAL_TYPES, type OrganizationCredentialType, @@ -16,10 +12,7 @@ import { import { CREDENTIAL_TYPE_CONDITION_KEY } from '@/lib/resource-policies/conditions/credential-type' import { evaluateResourcePolicy } from '@/lib/resource-policies/evaluator' import { workspaceResourcePolicyPrincipalSchema } from '@/lib/resource-policies/principals/workspace' -import { - CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION, - CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION, -} from '@/lib/resource-policies/registry' +import { CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION } from '@/lib/resource-policies/registry' import type { ResourcePolicyCodec } from '@/lib/resource-policies/types' const workspaceAccessStatementSchema = z @@ -62,43 +55,6 @@ const workspaceAccessStatementSchema = z } }) -const WORKFLOW_CONNECTION_REQUEST_SID = 'WorkflowConnectionRequests' - -/** - * Whether, and within which limits, workflows may ask a person to connect an account. - * No principals means every workspace the Access statements allow; the request is - * still refused for a workspace those statements do not allow. - */ -const workflowConnectionRequestStatementSchema = z - .object({ - sid: z.literal(WORKFLOW_CONNECTION_REQUEST_SID), - effect: z.literal('allow'), - actions: z.tuple([z.literal(CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION)]), - principals: z - .array(workspaceResourcePolicyPrincipalSchema) - .max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT) - .refine( - (principals) => - principals.every( - (principal, index) => - index === 0 || principals[index - 1].workspaceId < principal.workspaceId - ), - 'Workspace principals must be sorted and unique' - ), - settings: connectionRequestSettingsSchema, - }) - .strict() - -type WorkspaceAccessStatement = z.output -type WorkflowConnectionRequestStatement = z.output - -function isWorkspaceAccessStatement( - statement: WorkspaceAccessStatement | WorkflowConnectionRequestStatement -): statement is WorkspaceAccessStatement { - return statement.sid !== WORKFLOW_CONNECTION_REQUEST_SID -} - -/** Version 2 documents written before connection requests existed parse unchanged. */ export const organizationAccountAccessPolicySchema = z .object({ version: z.literal(2), @@ -106,15 +62,14 @@ export const organizationAccountAccessPolicySchema = z .object({ type: z.literal('credential_group'), id: z.string().min(1).max(128) }) .strict(), statements: z - .array(z.union([workspaceAccessStatementSchema, workflowConnectionRequestStatementSchema])) - .max(ORGANIZATION_CREDENTIAL_TYPES.length + 2), + .array(workspaceAccessStatementSchema) + .max(ORGANIZATION_CREDENTIAL_TYPES.length + 1), }) .strict() - .superRefine(({ statements: allStatements }, context) => { - const statementIds = new Set(allStatements.map((statement) => statement.sid)) - if (statementIds.size !== allStatements.length) + .superRefine(({ statements }, context) => { + const statementIds = new Set(statements.map((statement) => statement.sid)) + if (statementIds.size !== statements.length) context.addIssue({ code: 'custom', message: 'Workspace statements must be unique' }) - const statements = allStatements.filter(isWorkspaceAccessStatement) const unrestricted = new Set( statements .filter((statement) => !statement.condition) @@ -150,14 +105,9 @@ export const organizationAccountAccessPolicyCodec: ResourcePolicyCodec< }, } -/** - * Builds the Access statements from grants. Pass the current document's connection - * request statement through `requests` so saving Access never drops it. - */ export function buildOrganizationAccountAccessPolicy( credentialGroupId: string, - grants: OrganizationAccountWorkspaceGrant[], - requests: ConnectionRequestPolicy | null = null + grants: OrganizationAccountWorkspaceGrant[] ): OrganizationAccountAccessPolicy { const parsed = organizationAccountWorkspaceGrantsSchema.parse(grants) const byType = new Map() @@ -172,80 +122,25 @@ export function buildOrganizationAccountAccessPolicy( return organizationAccountAccessPolicySchema.parse({ version: 2, resource: { type: 'credential_group', id: credentialGroupId }, - statements: [ - ...[...byType] - .sort(([left], [right]) => left.localeCompare(right)) - .map(([type, workspaceIds]) => ({ - sid: type === 'all' ? 'WorkspaceCredentialAccess' : `WorkspaceCredentialAccess:${type}`, - effect: 'allow', - actions: [CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION], - principals: workspaceIds - .sort() - .map((workspaceId) => ({ type: 'workspace', workspaceId })), - ...(type === 'all' - ? {} - : { condition: { StringEquals: { [CREDENTIAL_TYPE_CONDITION_KEY]: type } } }), - })), - ...(requests ? [toWorkflowConnectionRequestStatement(requests)] : []), - ], + statements: [...byType] + .sort(([left], [right]) => left.localeCompare(right)) + .map(([type, workspaceIds]) => ({ + sid: type === 'all' ? 'WorkspaceCredentialAccess' : `WorkspaceCredentialAccess:${type}`, + effect: 'allow', + actions: [CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION], + principals: workspaceIds.sort().map((workspaceId) => ({ type: 'workspace', workspaceId })), + ...(type === 'all' + ? {} + : { condition: { StringEquals: { [CREDENTIAL_TYPE_CONDITION_KEY]: type } } }), + })), }) } -function toWorkflowConnectionRequestStatement({ - workspaces, - ...settings -}: ConnectionRequestPolicy): WorkflowConnectionRequestStatement { - return { - sid: WORKFLOW_CONNECTION_REQUEST_SID, - effect: 'allow', - actions: [CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION], - principals: - workspaces.mode === 'all' - ? [] - : workspaces.workspaceIds.map((workspaceId) => ({ type: 'workspace', workspaceId })), - settings, - } -} - -/** Replaces (or, with `null`, removes) the connection request statement, keeping Access as is. */ -export function withWorkflowConnectionRequestPolicy( - document: OrganizationAccountAccessPolicy, - requests: ConnectionRequestPolicy | null -): OrganizationAccountAccessPolicy { - return organizationAccountAccessPolicySchema.parse({ - ...document, - statements: [ - ...document.statements.filter(isWorkspaceAccessStatement), - ...(requests ? [toWorkflowConnectionRequestStatement(requests)] : []), - ], - }) -} - -/** The admin's connection request policy, or `null` when none was ever saved (requests are off). */ -export function readWorkflowConnectionRequestPolicy( - document: OrganizationAccountAccessPolicy -): ConnectionRequestPolicy | null { - const statement = document.statements.find( - (candidate): candidate is WorkflowConnectionRequestStatement => - !isWorkspaceAccessStatement(candidate) - ) - if (!statement) return null - return { - ...statement.settings, - workspaces: statement.principals.length - ? { - mode: 'selected', - workspaceIds: statement.principals.map((principal) => principal.workspaceId), - } - : { mode: 'all' }, - } -} - export function listOrganizationAccountWorkspaceGrants( document: OrganizationAccountAccessPolicy ): OrganizationAccountWorkspaceGrant[] { const grants = new Map() - for (const statement of document.statements.filter(isWorkspaceAccessStatement)) { + for (const statement of document.statements) { const type = statement.condition?.StringEquals[CREDENTIAL_TYPE_CONDITION_KEY] for (const { workspaceId } of statement.principals) { if (!type) { @@ -272,9 +167,9 @@ export function listOrganizationAccountWorkspaceIds( ): string[] { return [ ...new Set( - document.statements - .filter(isWorkspaceAccessStatement) - .flatMap((statement) => statement.principals.map((principal) => principal.workspaceId)) + document.statements.flatMap((statement) => + statement.principals.map((principal) => principal.workspaceId) + ) ), ].sort() } diff --git a/apps/sim/lib/credential-groups/connect-url.ts b/apps/sim/lib/credential-groups/connect-url.ts index 2ebb6ce0c31..55593aa4f13 100644 --- a/apps/sim/lib/credential-groups/connect-url.ts +++ b/apps/sim/lib/credential-groups/connect-url.ts @@ -1,13 +1,8 @@ import { getBaseUrl } from '@/lib/core/utils/urls' -/** Destinations the connect page may offer a button back to once the account is connected. */ -export type CredentialGroupConnectReturnKey = 'slack' - /** - * The stable link that asks a person to connect one integration in an organization's - * Credential Group. It carries no secret: the page verifies the signed-in person against - * their own enrollment before minting anything, so the link is safe to show a workflow - * or to copy from the People tab. + * The stable, secret-free link a person opens to connect one integration for a Credential Group. + * Safe to show anywhere: the page it opens verifies who is signed in before minting anything. */ export function buildCredentialGroupConnectUrl({ publicId, @@ -15,17 +10,10 @@ export function buildCredentialGroupConnectUrl({ returnKey, }: { publicId: string - /** Credential provider ID of the group option to connect (for example `google-email`). */ provider: string - returnKey?: CredentialGroupConnectReturnKey + returnKey?: 'slack' }): string { - if (!publicId.trim()) throw new Error('Credential group public ID is required') - if (!provider.trim()) throw new Error('Credential provider is required') - const url = new URL( - `/credential-groups/${encodeURIComponent(publicId)}/connect`, - `${getBaseUrl()}/` - ) - url.searchParams.set('provider', provider) - if (returnKey) url.searchParams.set('return', returnKey) - return url.toString() + const query = new URLSearchParams({ provider }) + if (returnKey) query.set('return', returnKey) + return `${getBaseUrl()}/credential-groups/${encodeURIComponent(publicId)}/connect?${query}` } diff --git a/apps/sim/lib/credential-groups/connection-request-email.ts b/apps/sim/lib/credential-groups/connection-request-email.ts new file mode 100644 index 00000000000..f916994995b --- /dev/null +++ b/apps/sim/lib/credential-groups/connection-request-email.ts @@ -0,0 +1,104 @@ +import { db } from '@sim/db' +import { credentialGroup, credentialGroupEnrollment, organization, workflow } from '@sim/db/schema' +import { createLogger } from '@sim/logger' +import { isRecordLike } from '@sim/utils/object' +import { truncate } from '@sim/utils/string' +import { and, eq, isNull } from 'drizzle-orm' +import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' +import { getCredentialGroupConnectionRequestSubject } from '@/components/emails/subjects' +import type { OutboxHandler } from '@/lib/core/outbox/service' +import { + CONNECTION_REQUEST_EMAIL_EVENT, + type ConnectionRequestEmailPayload, +} from '@/lib/credential-groups/connection-request-event' +import { sendEmail } from '@/lib/messaging/email/mailer' +import { getFromEmailAddress } from '@/lib/messaging/email/utils' + +const logger = createLogger('CredentialGroupConnectionRequestEmail') + +function parsePayload(payload: unknown): ConnectionRequestEmailPayload { + if ( + !isRecordLike(payload) || + typeof payload.enrollmentId !== 'string' || + typeof payload.workspaceId !== 'string' || + typeof payload.workflowId !== 'string' || + typeof payload.providerName !== 'string' || + typeof payload.connectUrl !== 'string' + ) + throw new Error('Invalid connection request email payload') + return { + enrollmentId: payload.enrollmentId, + workspaceId: payload.workspaceId, + workflowId: payload.workflowId, + providerName: payload.providerName, + connectUrl: payload.connectUrl, + } +} + +/** + * Sends the email a workflow's connection request enqueued. The enrollment is read again first, + * so a person who was revoked, or who connected, after the request was accepted gets nothing. + * A failed delivery is recorded on the enrollment for admins and retried by the outbox; a + * successful one clears it. + */ +const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { + const payload = parsePayload(rawPayload) + const [target] = await db + .select({ + email: credentialGroupEnrollment.email, + organizationName: organization.name, + credentialGroupName: credentialGroup.name, + }) + .from(credentialGroupEnrollment) + .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) + .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) + .where( + and( + eq(credentialGroupEnrollment.id, payload.enrollmentId), + eq(credentialGroupEnrollment.status, 'invited'), + isNull(credentialGroupEnrollment.userId) + ) + ) + .limit(1) + if (!target) return + const [requester] = await db + .select({ name: workflow.name }) + .from(workflow) + .where(and(eq(workflow.id, payload.workflowId), eq(workflow.workspaceId, payload.workspaceId))) + .limit(1) + const workflowName = requester?.name ?? 'A workflow' + + const html = await renderCredentialGroupInvitationEmail({ + recipientEmail: target.email, + workspaceName: target.organizationName, + credentialGroupName: target.credentialGroupName, + invitationLink: payload.connectUrl, + workflowRequest: { workflowName, providerName: payload.providerName }, + }) + const result = await sendEmail({ + to: target.email, + subject: getCredentialGroupConnectionRequestSubject({ + workflowName, + organizationName: target.organizationName, + providerName: payload.providerName, + }), + html, + from: getFromEmailAddress(), + emailType: 'transactional', + }) + await db + .update(credentialGroupEnrollment) + .set({ + lastDeliveryError: result.success ? null : truncate(result.message, 500), + updatedAt: new Date(), + }) + .where(eq(credentialGroupEnrollment.id, payload.enrollmentId)) + if (!result.success) { + logger.warn('Connection request email failed', { enrollmentId: payload.enrollmentId }) + throw new Error('Connection request email delivery failed') + } +} + +export const credentialGroupConnectionRequestOutboxHandlers = { + [CONNECTION_REQUEST_EMAIL_EVENT]: sendConnectionRequestEmail, +} as const diff --git a/apps/sim/lib/credential-groups/connection-request-event.ts b/apps/sim/lib/credential-groups/connection-request-event.ts new file mode 100644 index 00000000000..8033c20b1f6 --- /dev/null +++ b/apps/sim/lib/credential-groups/connection-request-event.ts @@ -0,0 +1,11 @@ +/** Emails a person the connect link a workflow's connection request points them to. */ +export const CONNECTION_REQUEST_EMAIL_EVENT = 'credential-group.connection-request-email' + +export interface ConnectionRequestEmailPayload { + enrollmentId: string + workspaceId: string + /** The requesting workflow; the email names it, read from the workflow record when sent. */ + workflowId: string + providerName: string + connectUrl: string +} diff --git a/apps/sim/lib/credential-groups/connection-request-policy.ts b/apps/sim/lib/credential-groups/connection-request-policy.ts index bf16c82449c..a334f18d7bb 100644 --- a/apps/sim/lib/credential-groups/connection-request-policy.ts +++ b/apps/sim/lib/credential-groups/connection-request-policy.ts @@ -3,39 +3,30 @@ import { ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT } from '@/lib/credential-groups/li export const CONNECTION_REQUEST_DAILY_LIMIT_MAX = 1000 export const CONNECTION_REQUEST_DAILY_LIMIT_DEFAULT = 50 -export const CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT = 50 +const CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT = 50 export const CONNECTION_REQUEST_PROVIDER_LIMIT = 100 +/** + * Consumer mailbox providers. Allowing one lets a workflow ask anyone with an address there, + * so the admin settings warn when one is entered. + */ +export const FREE_MAIL_DOMAINS: ReadonlySet = new Set([ + 'gmail.com', + 'outlook.com', + 'hotmail.com', + 'yahoo.com', + 'icloud.com', + 'proton.me', +]) + const EMAIL_DOMAIN_PATTERN = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/ const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/ -function sortedUnique(values: readonly string[]): boolean { - return values.every((value, index) => index === 0 || values[index - 1] < value) +/** Lowercases, trims, de-duplicates, and sorts admin input, so stored lists compare stably. */ +export function normalizeConnectionRequestList(values: readonly string[]): string[] { + return [...new Set(values.map((value) => value.trim().toLowerCase()).filter(Boolean))].sort() } -/** A bare, lowercase domain such as `example.com`; wildcards and addresses are refused. */ -const connectionRequestEmailDomainSchema = z - .string() - .regex(EMAIL_DOMAIN_PATTERN, 'Enter a domain such as example.com') - -export const connectionRequestSettingsSchema = z - .object({ - enabled: z.boolean(), - emailDomains: z - .array(connectionRequestEmailDomainSchema) - .min(1, 'Add at least one email domain') - .max(CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT) - .refine(sortedUnique, 'Email domains must be sorted and unique'), - providers: z - .array(z.string().regex(PROVIDER_ID_PATTERN)) - .min(1, 'Select at least one integration') - .max(CONNECTION_REQUEST_PROVIDER_LIMIT) - .refine(sortedUnique, 'Integrations must be sorted and unique'), - dailyLimit: z.number().int().min(1).max(CONNECTION_REQUEST_DAILY_LIMIT_MAX), - sendEmail: z.boolean(), - }) - .strict() - const connectionRequestWorkspacesSchema = z.discriminatedUnion('mode', [ z.object({ mode: z.literal('all') }).strict(), z @@ -43,24 +34,52 @@ const connectionRequestWorkspacesSchema = z.discriminatedUnion('mode', [ mode: z.literal('selected'), workspaceIds: z .array(z.string().min(1).max(128)) - .min(1, 'Select at least one workspace') - .max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT) - .refine(sortedUnique, 'Workspaces must be sorted and unique'), + .max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT, 'Too many workspaces selected') + .transform((ids) => [...new Set(ids)].sort()), }) .strict(), ]) /** - * What an organization admin allows workflows to ask for. "All" workspaces means every - * workspace already allowed on the Access tab; a request never widens that allowlist. + * What an organization admin allows workflows to ask for, as stored. "All" workspaces means + * every workspace already allowed on the Access tab; a request never widens that allowlist. + * Lists are normalized on parse. Lists may be empty here: a turned-off policy keeps whatever is + * left, and a stored policy may name workspaces or integrations that have since gone away. */ -export const connectionRequestPolicySchema = connectionRequestSettingsSchema - .extend({ workspaces: connectionRequestWorkspacesSchema }) +export const storedConnectionRequestPolicySchema = z + .object({ + enabled: z.boolean(), + workspaces: connectionRequestWorkspacesSchema, + emailDomains: z + .array(z.string().max(253)) + .max(CONNECTION_REQUEST_EMAIL_DOMAIN_LIMIT, 'Too many email domains') + .transform(normalizeConnectionRequestList) + .pipe(z.array(z.string().regex(EMAIL_DOMAIN_PATTERN, 'Enter a domain such as example.com'))), + providers: z + .array(z.string().max(64)) + .max(CONNECTION_REQUEST_PROVIDER_LIMIT, 'Too many integrations selected') + .transform(normalizeConnectionRequestList) + .pipe(z.array(z.string().regex(PROVIDER_ID_PATTERN, 'Unknown integration'))), + dailyLimit: z.number().int().min(1).max(CONNECTION_REQUEST_DAILY_LIMIT_MAX), + sendEmail: z.boolean(), + }) .strict() -export type ConnectionRequestPolicy = z.output +/** + * A policy an admin saves. Turning requests on needs at least one domain, integration, and + * workspace; a turned-off policy may hold empty lists, so an admin can always pause requests. + */ +export const connectionRequestPolicySchema = storedConnectionRequestPolicySchema.superRefine( + (policy, context) => { + if (!policy.enabled) return + if (!policy.emailDomains.length) + context.addIssue({ code: 'custom', message: 'Add at least one email domain' }) + if (!policy.providers.length) + context.addIssue({ code: 'custom', message: 'Select at least one integration' }) + if (policy.workspaces.mode === 'selected' && !policy.workspaces.workspaceIds.length) + context.addIssue({ code: 'custom', message: 'Select at least one workspace' }) + } +) -/** Lowercases, trims, sorts, and de-duplicates admin input before it is validated. */ -export function normalizeConnectionRequestList(values: readonly string[]): string[] { - return [...new Set(values.map((value) => value.trim().toLowerCase()).filter(Boolean))].sort() -} +export type ConnectionRequestPolicy = z.output +export type ConnectionRequestPolicyInput = z.input diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index 206cc1c898c..b6159109152 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -2,33 +2,38 @@ import { db } from '@sim/db' import { credential, credentialGroup, + credentialGroupConnectionRequest, + credentialGroupConnectionRequestPolicy, credentialGroupEnrollment, - organization, } from '@sim/db/schema' -import { createLogger } from '@sim/logger' import { sha256Hex } from '@sim/security/hash' -import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' -import { truncate } from '@sim/utils/string' -import { and, count, eq, gt, inArray, isNotNull } from 'drizzle-orm' -import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' -import { getCredentialGroupInvitationSubject } from '@/components/emails/subjects' +import { and, count, eq, gt, inArray, isNotNull, isNull, lt, sql } from 'drizzle-orm' +import { enqueueOutboxEvent } from '@/lib/core/outbox/service' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' import { resourceScopeCondition } from '@/lib/core/resource-scope.server' +import { + CONNECTION_REQUEST_EMAIL_EVENT, + type ConnectionRequestEmailPayload, +} from '@/lib/credential-groups/connection-request-event' +import { + type ConnectionRequestPolicy, + storedConnectionRequestPolicySchema, +} from '@/lib/credential-groups/connection-request-policy' import { LIVE_ENROLLMENT_STATUSES, listCredentialGroupCredentialReferences, } from '@/lib/credential-groups/credentials' import { lockCredentialGroupInvitationTarget } from '@/lib/credential-groups/enrollments' import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' -import { sendEmail } from '@/lib/messaging/email/mailer' -import { getFromEmailAddress } from '@/lib/messaging/email/utils' - -const logger = createLogger('CredentialGroupConnectionRequests') const DAY_MS = 24 * 60 * 60 * 1000 /** Matches the admin invitation lifetime, so an unbound requested enrollment ages out alike. */ const REQUESTED_ENROLLMENT_TTL_MS = 7 * DAY_MS +/** Reminders a workflow-requested enrollment may receive after its first email. */ +const CONNECTION_REQUEST_MAX_REMINDERS = 3 +/** No reminder goes out for an enrollment requested longer ago than this. */ +const CONNECTION_REQUEST_REMINDER_WINDOW_MS = 30 * DAY_MS /** What a workflow may learn about one person and integration. Nothing finer is exposed. */ export type OrganizationAccountConnectionStatus = 'connected' | 'not_connected' | 'needs_reconnect' @@ -97,49 +102,130 @@ export async function loadOrganizationAccountConnectionStatus(input: { : { status: 'not_connected', credentialId: null } } -/** The group's public identity and display names, for the connect link and its email. */ +/** The group's public identity, for the connect link. */ export async function loadConnectionRequestGroup(credentialGroupId: string) { const [row] = await db - .select({ - publicId: credentialGroup.publicId, - groupName: credentialGroup.name, - organizationName: organization.name, - }) + .select({ publicId: credentialGroup.publicId }) .from(credentialGroup) - .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) .where(eq(credentialGroup.id, credentialGroupId)) .limit(1) if (!row) throw new Error('Credential group not found') return row } -export interface RecordedConnectionRequest { +/** + * The admin's stored connection request policy and its revision. `revision` is `0` and + * `policy` is `null` while none was ever saved, which means requests are off. + */ +export async function loadConnectionRequestPolicy( + credentialGroupId: string +): Promise<{ revision: number; policy: ConnectionRequestPolicy | null }> { + const [row] = await db + .select({ + revision: credentialGroupConnectionRequestPolicy.revision, + policy: credentialGroupConnectionRequestPolicy.policy, + }) + .from(credentialGroupConnectionRequestPolicy) + .where(eq(credentialGroupConnectionRequestPolicy.credentialGroupId, credentialGroupId)) + .limit(1) + if (!row) return { revision: 0, policy: null } + return { revision: row.revision, policy: storedConnectionRequestPolicySchema.parse(row.policy) } +} + +export class ConnectionRequestPolicyConflictError extends Error { + constructor() { + super('Connection request settings changed. Reload before saving again.') + this.name = 'ConnectionRequestPolicyConflictError' + } +} + +/** + * Saves the policy when the stored revision still equals `expectedRevision` (`0` for the first + * save), returning the new revision. + */ +export async function writeConnectionRequestPolicy(input: { + credentialGroupId: string + expectedRevision: number + policy: ConnectionRequestPolicy + actorUserId: string +}): Promise { + const now = new Date() + const written = + input.expectedRevision === 0 + ? await db + .insert(credentialGroupConnectionRequestPolicy) + .values({ + credentialGroupId: input.credentialGroupId, + policy: input.policy, + revision: 1, + updatedBy: input.actorUserId, + createdAt: now, + updatedAt: now, + }) + .onConflictDoNothing() + .returning({ revision: credentialGroupConnectionRequestPolicy.revision }) + : await db + .update(credentialGroupConnectionRequestPolicy) + .set({ + policy: input.policy, + revision: input.expectedRevision + 1, + updatedBy: input.actorUserId, + updatedAt: now, + }) + .where( + and( + eq(credentialGroupConnectionRequestPolicy.credentialGroupId, input.credentialGroupId), + eq(credentialGroupConnectionRequestPolicy.revision, input.expectedRevision) + ) + ) + .returning({ revision: credentialGroupConnectionRequestPolicy.revision }) + const [row] = written + if (!row) throw new ConnectionRequestPolicyConflictError() + return row.revision +} + +interface RecordedConnectionRequest { enrollmentId: string /** Whether this request created the enrollment. */ created: boolean - /** Whether the person should be emailed now: a new request, or a reminder past the cooldown. */ - notify: boolean + /** The outbox event that will email the person, when one was enqueued. */ + emailEventId: string | null } /** - * Records one workflow's request that a person connect an account. Runs in one transaction: - * the group lock serializes the daily cap, and the per-email invitation lock is the one admin - * invitations take, so a request never races an invite for the same address. + * Records one workflow's request that a person connect an account, in one transaction. + * + * The group lock serializes the daily cap, which counts every accepted request in the request + * log, before the address is looked up: whatever the person's state, a request past the cap + * fails the same way, and a request under it is logged and counted the same way. The per-email + * invitation lock is the one admin invitations take, so a request never races an invite for the + * same address. * - * Only an absent enrollment is created. An existing one is never changed in status or - * attribution: a revoked person stays revoked, an admin's invitation stays the admin's, and a - * connected person stays connected. The only write to an existing row is claiming the reminder - * slot on an unbound, still-invited enrollment a workflow created, at most once a day. + * Only an absent enrollment is created. An existing one keeps its status and attribution: a + * revoked person stays revoked, an admin's invitation stays the admin's, and a connected person + * stays connected. The only write to an existing row is a reminder on an unbound, still-invited + * enrollment a workflow created: when nobody asked for this address in the last day, the + * enrollment was requested within the last 30 days, and it has had fewer than + * {@link CONNECTION_REQUEST_MAX_REMINDERS} reminders. That update re-checks the row's state, so a + * revocation committed meanwhile sends nothing. + * + * Emails are enqueued on the outbox in the same transaction, so nothing here waits on rendering + * or delivery. Log rows are only read inside the cap's one-day window; nothing prunes older ones + * yet. */ export async function recordCredentialGroupConnectionRequest(input: { credentialGroupId: string email: string + workspaceId: string workflowId: string + providerName: string + connectUrl: string dailyLimit: number sendEmail: boolean }): Promise { return db.transaction(async (tx) => { const now = new Date() + const dayAgo = new Date(now.getTime() - DAY_MS) await acquireAdvisoryXactLock( tx, 'credential_group_connection_request', @@ -147,49 +233,97 @@ export async function recordCredentialGroupConnectionRequest(input: { ) const [recent] = await tx .select({ total: count() }) - .from(credentialGroupEnrollment) + .from(credentialGroupConnectionRequest) .where( and( - eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId), - isNotNull(credentialGroupEnrollment.requestedByWorkflowId), - gt(credentialGroupEnrollment.createdAt, new Date(now.getTime() - DAY_MS)) + eq(credentialGroupConnectionRequest.credentialGroupId, input.credentialGroupId), + gt(credentialGroupConnectionRequest.createdAt, dayAgo) ) ) - /** Checked before the address is looked up, so hitting the cap says nothing about the person. */ if ((recent?.total ?? 0) >= input.dailyLimit) throw new ConnectionRequestDailyLimitError() await lockCredentialGroupInvitationTarget(tx, input.credentialGroupId, input.email) - const [existing] = await tx - .select({ - id: credentialGroupEnrollment.id, - status: credentialGroupEnrollment.status, - userId: credentialGroupEnrollment.userId, - sentAt: credentialGroupEnrollment.sentAt, - requestedByWorkflowId: credentialGroupEnrollment.requestedByWorkflowId, - }) - .from(credentialGroupEnrollment) - .where( - and( - eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId), - eq(credentialGroupEnrollment.email, input.email) + const [[askedToday], [existing]] = await Promise.all([ + tx + .select({ id: credentialGroupConnectionRequest.id }) + .from(credentialGroupConnectionRequest) + .where( + and( + eq(credentialGroupConnectionRequest.credentialGroupId, input.credentialGroupId), + eq(credentialGroupConnectionRequest.email, input.email), + gt(credentialGroupConnectionRequest.createdAt, dayAgo) + ) + ) + .limit(1), + tx + .select({ + id: credentialGroupEnrollment.id, + requestedByWorkflowId: credentialGroupEnrollment.requestedByWorkflowId, + }) + .from(credentialGroupEnrollment) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId), + eq(credentialGroupEnrollment.email, input.email) + ) ) + .limit(1), + ]) + await tx.insert(credentialGroupConnectionRequest).values({ + id: generateId(), + credentialGroupId: input.credentialGroupId, + email: input.email, + workspaceId: input.workspaceId, + workflowId: input.workflowId, + createdAt: now, + }) + + const enqueueEmail = (enrollmentId: string) => + enqueueOutboxEvent( + tx, + CONNECTION_REQUEST_EMAIL_EVENT, + { + enrollmentId, + workspaceId: input.workspaceId, + workflowId: input.workflowId, + providerName: input.providerName, + connectUrl: input.connectUrl, + }, + { maxAttempts: 3 } ) - .limit(1) if (existing) { - const remind = - input.sendEmail && - existing.requestedByWorkflowId !== null && - existing.status === 'invited' && - existing.userId === null && - (!existing.sentAt || existing.sentAt.getTime() <= now.getTime() - DAY_MS) - if (remind) { - await tx - .update(credentialGroupEnrollment) - .set({ sentAt: now, updatedAt: now }) - .where(eq(credentialGroupEnrollment.id, existing.id)) + if (!input.sendEmail || askedToday || existing.requestedByWorkflowId === null) + return { enrollmentId: existing.id, created: false, emailEventId: null } + const [reminded] = await tx + .update(credentialGroupEnrollment) + .set({ + sentAt: now, + connectionRequestReminders: sql`${credentialGroupEnrollment.connectionRequestReminders} + 1`, + updatedAt: now, + }) + .where( + and( + eq(credentialGroupEnrollment.id, existing.id), + eq(credentialGroupEnrollment.status, 'invited'), + isNull(credentialGroupEnrollment.userId), + isNotNull(credentialGroupEnrollment.requestedByWorkflowId), + lt( + credentialGroupEnrollment.connectionRequestReminders, + CONNECTION_REQUEST_MAX_REMINDERS + ), + gt( + credentialGroupEnrollment.createdAt, + new Date(now.getTime() - CONNECTION_REQUEST_REMINDER_WINDOW_MS) + ) + ) + ) + .returning({ id: credentialGroupEnrollment.id }) + return { + enrollmentId: existing.id, + created: false, + emailEventId: reminded ? await enqueueEmail(existing.id) : null, } - return { enrollmentId: existing.id, created: false, notify: remind } } const enrollmentId = generateId() @@ -208,46 +342,10 @@ export async function recordCredentialGroupConnectionRequest(input: { createdAt: now, updatedAt: now, }) - return { enrollmentId, created: true, notify: input.sendEmail } + return { + enrollmentId, + created: true, + emailEventId: input.sendEmail ? await enqueueEmail(enrollmentId) : null, + } }) } - -/** - * Emails the person the stable connect link. A failed delivery is recorded for admins on the - * enrollment and never surfaces to the workflow, whose result must not depend on the person. - */ -export async function sendConnectionRequestEmail(input: { - enrollmentId: string - email: string - organizationName: string - credentialGroupName: string - providerName: string - connectUrl: string -}): Promise { - let failure: string - try { - const html = await renderCredentialGroupInvitationEmail({ - recipientEmail: input.email, - workspaceName: input.organizationName, - credentialGroupName: input.credentialGroupName, - invitationLink: input.connectUrl, - requestedProviderName: input.providerName, - }) - const result = await sendEmail({ - to: input.email, - subject: getCredentialGroupInvitationSubject(undefined, input.organizationName), - html, - from: getFromEmailAddress(), - emailType: 'transactional', - }) - if (result.success) return - failure = result.message - } catch (error) { - failure = getErrorMessage(error, 'Failed to send connection request email') - } - logger.warn('Connection request email failed', { enrollmentId: input.enrollmentId }) - await db - .update(credentialGroupEnrollment) - .set({ lastDeliveryError: truncate(failure, 500), updatedAt: new Date() }) - .where(eq(credentialGroupEnrollment.id, input.enrollmentId)) -} diff --git a/apps/sim/lib/resource-policies/registry.ts b/apps/sim/lib/resource-policies/registry.ts index c15c3c31f29..32c42363bdc 100644 --- a/apps/sim/lib/resource-policies/registry.ts +++ b/apps/sim/lib/resource-policies/registry.ts @@ -3,13 +3,7 @@ import type { ResourcePolicyPrincipalType } from '@/lib/resource-policies/princi export const RESOURCE_POLICY_RESOURCE_TYPES = ['credential_group'] as const export const CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION = 'credential_groups.credentials.use' as const -/** Lets a workflow ask a person to connect an account; the statement carries the admin's limits. */ -export const CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION = - 'credential_groups.connections.request' as const -export const RESOURCE_POLICY_ACTIONS = [ - CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION, - CREDENTIAL_GROUP_CONNECTION_REQUEST_ACTION, -] as const +export const RESOURCE_POLICY_ACTIONS = [CREDENTIAL_GROUP_CREDENTIAL_USE_ACTION] as const export type ResourcePolicyResourceType = (typeof RESOURCE_POLICY_RESOURCE_TYPES)[number] export type ResourcePolicyAction = (typeof RESOURCE_POLICY_ACTIONS)[number] diff --git a/packages/db/credential-group-resource-policies.ts b/packages/db/credential-group-resource-policies.ts index 7bac34d0516..c21292ed4fb 100644 --- a/packages/db/credential-group-resource-policies.ts +++ b/packages/db/credential-group-resource-policies.ts @@ -10,8 +10,6 @@ const WORKFLOW_ACCESS_SID = 'WorkflowCredentialAccess' /** Statements the knowledge module writes for connectors crawling through an option. */ const KNOWLEDGE_CONNECTOR_ACCESS_SID_PREFIX = 'KnowledgeConnectorCredentialAccess:' const CREDENTIAL_USE_ACTION = 'credential_groups.credentials.use' -const CONNECTION_REQUEST_SID = 'WorkflowConnectionRequests' -const CONNECTION_REQUEST_ACTION = 'credential_groups.connections.request' const ACTOR_OWNS_CREDENTIAL_CONDITION_KEY = 'credential_group:ActorOwnsCredential' const DEPLOYMENT_MODE_CONDITION_KEY = 'execution:WorkflowMode' @@ -379,13 +377,6 @@ export function validateOrganizationAccountPolicyDocument( const selectedWorkspaces = new Set() for (const value of document.statements) { const statement = requireRecord(value, 'Organization account workspace statement') - if (statement.sid === CONNECTION_REQUEST_SID) { - if (seenStatements.has(CONNECTION_REQUEST_SID)) - throw new Error('Organization account policy repeats its connection request statement') - seenStatements.add(CONNECTION_REQUEST_SID) - validateConnectionRequestStatement(statement) - continue - } requireExactKeys( statement, [ @@ -451,59 +442,6 @@ export function validateOrganizationAccountPolicyDocument( throw new Error('Organization account policy supports at most 1000 workspaces') } -/** The workflow connection request statement; the application owns its settings' finer rules. */ -function validateConnectionRequestStatement(statement: Record): void { - requireExactKeys( - statement, - ['sid', 'effect', 'actions', 'principals', 'settings'], - 'Organization account connection request statement' - ) - if ( - statement.effect !== 'allow' || - !Array.isArray(statement.actions) || - statement.actions.length !== 1 || - statement.actions[0] !== CONNECTION_REQUEST_ACTION || - !Array.isArray(statement.principals) || - statement.principals.length > 1000 - ) - throw new Error('Organization account connection request statement is invalid') - let previous = '' - for (const value of statement.principals) { - const principal = requireRecord(value, 'Organization account connection request principal') - requireExactKeys( - principal, - ['type', 'workspaceId'], - 'Organization account connection request principal' - ) - const id = requireCanonicalId(principal.workspaceId, 'Organization account workspace ID') - if (principal.type !== 'workspace' || id <= previous) - throw new Error('Organization account workspace principals must be unique and sorted') - previous = id - } - const settings = requireRecord(statement.settings, 'Organization account connection request') - requireExactKeys( - settings, - ['enabled', 'emailDomains', 'providers', 'dailyLimit', 'sendEmail'], - 'Organization account connection request' - ) - const { dailyLimit } = settings - if ( - typeof settings.enabled !== 'boolean' || - typeof settings.sendEmail !== 'boolean' || - typeof dailyLimit !== 'number' || - !Number.isInteger(dailyLimit) || - dailyLimit < 1 || - dailyLimit > 1000 || - !Array.isArray(settings.emailDomains) || - settings.emailDomains.length < 1 || - !settings.emailDomains.every((domain) => typeof domain === 'string') || - !Array.isArray(settings.providers) || - settings.providers.length < 1 || - !settings.providers.every((provider) => typeof provider === 'string') - ) - throw new Error('Organization account connection request settings are invalid') -} - function assertPage( rows: T[], afterId: string, diff --git a/packages/db/migrations/0490_credential_group_connection_requests.sql b/packages/db/migrations/0490_credential_group_connection_requests.sql new file mode 100644 index 00000000000..eae2385b5bd --- /dev/null +++ b/packages/db/migrations/0490_credential_group_connection_requests.sql @@ -0,0 +1,26 @@ +CREATE TABLE "credential_group_connection_request" ( + "id" text PRIMARY KEY NOT NULL, + "credential_group_id" text NOT NULL, + "email" text NOT NULL, + "workspace_id" text NOT NULL, + "workflow_id" text NOT NULL, + "created_at" timestamp DEFAULT now() NOT NULL, + CONSTRAINT "credential_group_connection_request_normalized_email_check" CHECK ("credential_group_connection_request"."email" = lower(btrim("credential_group_connection_request"."email")) AND length("credential_group_connection_request"."email") BETWEEN 3 AND 320) +); +--> statement-breakpoint +CREATE TABLE "credential_group_connection_request_policy" ( + "credential_group_id" text PRIMARY KEY NOT NULL, + "policy" jsonb NOT NULL, + "revision" integer DEFAULT 1 NOT NULL, + "updated_by" text, + "created_at" timestamp DEFAULT now() NOT NULL, + "updated_at" timestamp DEFAULT now() NOT NULL, + CONSTRAINT "credential_group_connection_request_policy_revision_check" CHECK ("credential_group_connection_request_policy"."revision" >= 1) +); +--> statement-breakpoint +ALTER TABLE "credential_group_enrollment" ADD COLUMN "connection_request_reminders" integer DEFAULT 0 NOT NULL;--> statement-breakpoint +ALTER TABLE "credential_group_connection_request" ADD CONSTRAINT "credential_group_connection_request_credential_group_id_credential_group_id_fk" FOREIGN KEY ("credential_group_id") REFERENCES "public"."credential_group"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "credential_group_connection_request_policy" ADD CONSTRAINT "credential_group_connection_request_policy_credential_group_id_credential_group_id_fk" FOREIGN KEY ("credential_group_id") REFERENCES "public"."credential_group"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "credential_group_connection_request_policy" ADD CONSTRAINT "credential_group_connection_request_policy_updated_by_user_id_fk" FOREIGN KEY ("updated_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "credential_group_connection_request_group_created_at_idx" ON "credential_group_connection_request" USING btree ("credential_group_id","created_at");--> statement-breakpoint +CREATE INDEX "credential_group_connection_request_group_email_created_at_idx" ON "credential_group_connection_request" USING btree ("credential_group_id","email","created_at"); \ No newline at end of file diff --git a/packages/db/migrations/meta/0490_snapshot.json b/packages/db/migrations/meta/0490_snapshot.json new file mode 100644 index 00000000000..2e4497a9f12 --- /dev/null +++ b/packages/db/migrations/meta/0490_snapshot.json @@ -0,0 +1,34922 @@ +{ + "id": "d8a1e567-5080-4ca9-8d20-c9dd774be4a2", + "prevId": "bcdab562-c001-4b25-abf0-955e2efbc4b6", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config": { + "name": "oauth_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_at": { + "name": "refresh_revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_code": { + "name": "refresh_revoked_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_revoked_token_hash": { + "name": "refresh_revoked_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "account_user_id_idx": { + "name": "account_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_account_on_account_id_provider_id": { + "name": "idx_account_on_account_id_provider_id", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_blocked": { + "name": "activity_rollup_blocked", + "schema": "", + "columns": { + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": true, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "retry_at": { + "name": "retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_dirty": { + "name": "activity_rollup_dirty", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "due_at": { + "name": "due_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "activity_rollup_dirty_due_at_idx": { + "name": "activity_rollup_dirty_due_at_idx", + "columns": [ + { + "expression": "due_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "activity_rollup_dirty_workspace_id_bucket_start_pk": { + "name": "activity_rollup_dirty_workspace_id_bucket_start_pk", + "columns": ["workspace_id", "bucket_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_inflight": { + "name": "activity_rollup_inflight", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "next_check_at": { + "name": "next_check_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "activity_rollup_inflight_next_check_at_idx": { + "name": "activity_rollup_inflight_next_check_at_idx", + "columns": [ + { + "expression": "next_check_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "activity_rollup_inflight_workspace_id_bucket_start_pk": { + "name": "activity_rollup_inflight_workspace_id_bucket_start_pk", + "columns": ["workspace_id", "bucket_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.activity_rollup_state": { + "name": "activity_rollup_state", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "coverage_start": { + "name": "coverage_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "fresh_through": { + "name": "fresh_through", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "backfill_completed_at": { + "name": "backfill_completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_end_scan": { + "name": "last_end_scan", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "lease_owner": { + "name": "lease_owner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "housekeeping_at": { + "name": "housekeeping_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "maintained_at": { + "name": "maintained_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "failed_passes": { + "name": "failed_passes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "corrections_at": { + "name": "corrections_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_memory_turn": { + "name": "agent_memory_turn", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_order": { + "name": "execution_order", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "encrypted_state": { + "name": "encrypted_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "agent_memory_turn_invocation_unique": { + "name": "agent_memory_turn_invocation_unique", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "node_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_memory_turn_workflow_idx": { + "name": "agent_memory_turn_workflow_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "agent_memory_turn_memory_id_memory_id_fk": { + "name": "agent_memory_turn_memory_id_memory_id_fk", + "tableFrom": "agent_memory_turn", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "agent_memory_turn_workflow_id_workflow_id_fk": { + "name": "agent_memory_turn_workflow_id_workflow_id_fk", + "tableFrom": "agent_memory_turn", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.api_key": { + "name": "api_key", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key_hash": { + "name": "key_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'personal'" + }, + "access": { + "name": "access", + "type": "api_key_access", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'write'" + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "api_key_workspace_type_idx": { + "name": "api_key_workspace_type_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "api_key_user_type_idx": { + "name": "api_key_user_type_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "api_key_key_hash_idx": { + "name": "api_key_key_hash_idx", + "columns": [ + { + "expression": "key_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "api_key_user_id_user_id_fk": { + "name": "api_key_user_id_user_id_fk", + "tableFrom": "api_key", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "api_key_workspace_id_workspace_id_fk": { + "name": "api_key_workspace_id_workspace_id_fk", + "tableFrom": "api_key", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "api_key_created_by_user_id_fk": { + "name": "api_key_created_by_user_id_fk", + "tableFrom": "api_key", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "api_key_key_unique": { + "name": "api_key_key_unique", + "nullsNotDistinct": false, + "columns": ["key"] + } + }, + "policies": {}, + "checkConstraints": { + "workspace_type_check": { + "name": "workspace_type_check", + "value": "(type = 'workspace' AND workspace_id IS NOT NULL) OR (type = 'personal' AND workspace_id IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.assistant_tool_permission": { + "name": "assistant_tool_permission", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "read_policy": { + "name": "read_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'allow'" + }, + "write_policy": { + "name": "write_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'ask'" + }, + "overrides": { + "name": "overrides", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "assistant_tool_permission_credential_idx": { + "name": "assistant_tool_permission_credential_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "assistant_tool_permission_user_idx": { + "name": "assistant_tool_permission_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assistant_tool_permission_organization_id_organization_id_fk": { + "name": "assistant_tool_permission_organization_id_organization_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_tool_permission_user_id_user_id_fk": { + "name": "assistant_tool_permission_user_id_user_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_tool_permission_credential_id_credential_id_fk": { + "name": "assistant_tool_permission_credential_id_credential_id_fk", + "tableFrom": "assistant_tool_permission", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "assistant_tool_permission_organization_id_user_id_credential_id_pk": { + "name": "assistant_tool_permission_organization_id_user_id_credential_id_pk", + "columns": ["organization_id", "user_id", "credential_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "assistant_tool_permission_policy_check": { + "name": "assistant_tool_permission_policy_check", + "value": "\"assistant_tool_permission\".\"read_policy\" IN ('allow', 'ask', 'block') AND \"assistant_tool_permission\".\"write_policy\" IN ('allow', 'ask', 'block')" + }, + "assistant_tool_permission_revision_check": { + "name": "assistant_tool_permission_revision_check", + "value": "\"assistant_tool_permission\".\"revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.async_jobs": { + "name": "async_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_at": { + "name": "run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 3 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "async_jobs_status_started_at_idx": { + "name": "async_jobs_status_started_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_status_completed_at_idx": { + "name": "async_jobs_status_completed_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "completed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_pending_run_at_idx": { + "name": "async_jobs_schedule_pending_run_at_idx", + "columns": [ + { + "expression": "run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_processing_started_at_idx": { + "name": "async_jobs_schedule_processing_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" = 'processing'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "async_jobs_schedule_unreconciled_terminal_idx": { + "name": "async_jobs_schedule_unreconciled_terminal_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"async_jobs\".\"type\" = 'schedule-execution' AND \"async_jobs\".\"status\" IN ('completed', 'failed', 'cancelled') AND COALESCE(\"async_jobs\".\"metadata\" ->> 'scheduleReconciled', 'false') <> 'true'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.audit_log": { + "name": "audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_email": { + "name": "actor_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_name": { + "name": "resource_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "audit_log_workspace_created_idx": { + "name": "audit_log_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_workspace_created_at_id_idx": { + "name": "audit_log_workspace_created_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_actor_created_idx": { + "name": "audit_log_actor_created_idx", + "columns": [ + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_org_level_created_at_id_idx": { + "name": "audit_log_org_level_created_at_id_idx", + "columns": [ + { + "expression": "(\"metadata\"->>'organizationId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"audit_log\".\"workspace_id\" IS NULL AND (\"audit_log\".\"metadata\"->>'organizationId') IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "audit_log_resource_idx": { + "name": "audit_log_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_action_idx": { + "name": "audit_log_action_idx", + "columns": [ + { + "expression": "action", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "audit_log_workspace_id_workspace_id_fk": { + "name": "audit_log_workspace_id_workspace_id_fk", + "tableFrom": "audit_log", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "audit_log_actor_id_user_id_fk": { + "name": "audit_log_actor_id_user_id_fk", + "tableFrom": "audit_log", + "tableTo": "user", + "columnsFrom": ["actor_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_license": { + "name": "aws_marketplace_license", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "license_arn": { + "name": "license_arn", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "product_code": { + "name": "product_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "customer_aws_account_id": { + "name": "customer_aws_account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agreement_id": { + "name": "agreement_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agreement_seen_at": { + "name": "agreement_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "renewed_agreement_id": { + "name": "renewed_agreement_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "aws_marketplace_license_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_verified_at": { + "name": "last_verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "last_verification_attempt_at": { + "name": "last_verification_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "license_event_received_at": { + "name": "license_event_received_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "claim_token_hash": { + "name": "claim_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_expires_at": { + "name": "claim_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "linked_by_user_id": { + "name": "linked_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_linked_at": { + "name": "organization_linked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "contact_email": { + "name": "contact_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "company_name": { + "name": "company_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "aws_marketplace_license_arn_unique": { + "name": "aws_marketplace_license_arn_unique", + "columns": [ + { + "expression": "license_arn", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_claim_token_hash_unique": { + "name": "aws_marketplace_license_claim_token_hash_unique", + "columns": [ + { + "expression": "claim_token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_agreement_id_idx": { + "name": "aws_marketplace_license_agreement_id_idx", + "columns": [ + { + "expression": "agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_renewed_agreement_id_idx": { + "name": "aws_marketplace_license_renewed_agreement_id_idx", + "columns": [ + { + "expression": "renewed_agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_account_product_idx": { + "name": "aws_marketplace_license_account_product_idx", + "columns": [ + { + "expression": "customer_aws_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "product_code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_last_attempt_idx": { + "name": "aws_marketplace_license_last_attempt_idx", + "columns": [ + { + "expression": "last_verification_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_organization_id_idx": { + "name": "aws_marketplace_license_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_license_linked_by_user_id_idx": { + "name": "aws_marketplace_license_linked_by_user_id_idx", + "columns": [ + { + "expression": "linked_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "aws_marketplace_license_organization_id_organization_id_fk": { + "name": "aws_marketplace_license_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_license", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "aws_marketplace_license_linked_by_user_id_user_id_fk": { + "name": "aws_marketplace_license_linked_by_user_id_user_id_fk", + "tableFrom": "aws_marketplace_license", + "tableTo": "user", + "columnsFrom": ["linked_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_usage_report": { + "name": "aws_marketplace_usage_report", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "license_id": { + "name": "license_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hour_start": { + "name": "hour_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "quantity": { + "name": "quantity", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "aws_marketplace_usage_report_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "metering_record_id": { + "name": "metering_record_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reported_at": { + "name": "reported_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "aws_marketplace_usage_report_license_dimension_hour_unique": { + "name": "aws_marketplace_usage_report_license_dimension_hour_unique", + "columns": [ + { + "expression": "license_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dimension", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "hour_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_usage_report_status_hour_idx": { + "name": "aws_marketplace_usage_report_status_hour_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "hour_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "aws_marketplace_usage_report_organization_id_idx": { + "name": "aws_marketplace_usage_report_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "aws_marketplace_usage_report_organization_id_organization_id_fk": { + "name": "aws_marketplace_usage_report_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_usage_report", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "aws_marketplace_usage_report_license_id_aws_marketplace_license_id_fk": { + "name": "aws_marketplace_usage_report_license_id_aws_marketplace_license_id_fk", + "tableFrom": "aws_marketplace_usage_report", + "tableTo": "aws_marketplace_license", + "columnsFrom": ["license_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.aws_marketplace_usage_tally": { + "name": "aws_marketplace_usage_tally", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dimension": { + "name": "dimension", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "period_start": { + "name": "period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "counted_from": { + "name": "counted_from", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "cost_usd": { + "name": "cost_usd", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "units": { + "name": "units", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "aws_marketplace_usage_tally_organization_id_organization_id_fk": { + "name": "aws_marketplace_usage_tally_organization_id_organization_id_fk", + "tableFrom": "aws_marketplace_usage_tally", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "aws_marketplace_usage_tally_organization_id_dimension_period_start_pk": { + "name": "aws_marketplace_usage_tally_organization_id_dimension_period_start_pk", + "columns": ["organization_id", "dimension", "period_start"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.background_work_status": { + "name": "background_work_status", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "background_work_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "background_work_status_value", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "background_work_status_workspace_status_idx": { + "name": "background_work_status_workspace_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_workflow_status_idx": { + "name": "background_work_status_workflow_status_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_meta_child_ws_idx": { + "name": "background_work_status_meta_child_ws_idx", + "columns": [ + { + "expression": "(\"metadata\" ->> 'childWorkspaceId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "background_work_status_meta_other_ws_idx": { + "name": "background_work_status_meta_other_ws_idx", + "columns": [ + { + "expression": "(\"metadata\" ->> 'otherWorkspaceId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "background_work_status_workspace_id_workspace_id_fk": { + "name": "background_work_status_workspace_id_workspace_id_fk", + "tableFrom": "background_work_status", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "background_work_status_workflow_id_workflow_id_fk": { + "name": "background_work_status_workflow_id_workflow_id_fk", + "tableFrom": "background_work_status", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.changelog_change": { + "name": "changelog_change", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "release_id": { + "name": "release_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "changelog_change_release_position_unique": { + "name": "changelog_change_release_position_unique", + "columns": [ + { + "expression": "release_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "changelog_change_release_id_changelog_release_id_fk": { + "name": "changelog_change_release_id_changelog_release_id_fk", + "tableFrom": "changelog_change", + "tableTo": "changelog_release", + "columnsFrom": ["release_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "changelog_change_workflow_id_workflow_id_fk": { + "name": "changelog_change_workflow_id_workflow_id_fk", + "tableFrom": "changelog_change", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_change_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "changelog_change_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "changelog_change", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_change_chat_id_copilot_chats_id_fk": { + "name": "changelog_change_chat_id_copilot_chats_id_fk", + "tableFrom": "changelog_change", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.changelog_release": { + "name": "changelog_release", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version_major": { + "name": "version_major", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version_minor": { + "name": "version_minor", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version_patch": { + "name": "version_patch", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "bump_reason": { + "name": "bump_reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body_file_id": { + "name": "body_file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "published_at": { + "name": "published_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "changelog_release_workspace_version_unique": { + "name": "changelog_release_workspace_version_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_major", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_minor", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version_patch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "changelog_release_body_file_unique": { + "name": "changelog_release_body_file_unique", + "columns": [ + { + "expression": "body_file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "changelog_release_workspace_published_idx": { + "name": "changelog_release_workspace_published_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "published_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "changelog_release_workspace_id_workspace_id_fk": { + "name": "changelog_release_workspace_id_workspace_id_fk", + "tableFrom": "changelog_release", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "changelog_release_body_file_id_workspace_files_id_fk": { + "name": "changelog_release_body_file_id_workspace_files_id_fk", + "tableFrom": "changelog_release", + "tableTo": "workspace_files", + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "changelog_release_created_by_user_id_fk": { + "name": "changelog_release_created_by_user_id_fk", + "tableFrom": "changelog_release", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "changelog_release_updated_by_user_id_fk": { + "name": "changelog_release_updated_by_user_id_fk", + "tableFrom": "changelog_release", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "changelog_release_version_check": { + "name": "changelog_release_version_check", + "value": "\"changelog_release\".\"version_major\" >= 0 AND \"changelog_release\".\"version_minor\" >= 0 AND \"changelog_release\".\"version_patch\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.chat": { + "name": "chat", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "customizations": { + "name": "customizations", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_emails": { + "name": "allowed_emails", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "output_configs": { + "name": "output_configs", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "include_thinking": { + "name": "include_thinking", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "include_tool_calls": { + "name": "include_tool_calls", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "identifier_idx": { + "name": "identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"chat\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_archived_at_partial_idx": { + "name": "chat_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_chat_on_workflow_id_archived_at": { + "name": "idx_chat_on_workflow_id_archived_at", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_user_id_idx": { + "name": "chat_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_workflow_id_workflow_id_fk": { + "name": "chat_workflow_id_workflow_id_fk", + "tableFrom": "chat", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_user_id_user_id_fk": { + "name": "chat_user_id_user_id_fk", + "tableFrom": "chat", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.client_credential_token": { + "name": "client_credential_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "encrypted_value": { + "name": "encrypted_value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token_digest": { + "name": "access_token_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "client_credential_token_expires_at_idx": { + "name": "client_credential_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"client_credential_token\".\"access_token_digest\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "client_credential_token_access_token_digest_idx": { + "name": "client_credential_token_access_token_digest_idx", + "columns": [ + { + "expression": "access_token_digest", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"client_credential_token\".\"access_token_digest\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_async_tool_calls": { + "name": "copilot_async_tool_calls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "checkpoint_id": { + "name": "checkpoint_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "tool_call_id": { + "name": "tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "args": { + "name": "args", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "executable_name": { + "name": "executable_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_workspace_id": { + "name": "target_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_args": { + "name": "approved_args", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "assistant_action": { + "name": "assistant_action", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "execution_retryable": { + "name": "execution_retryable", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "status": { + "name": "status", + "type": "copilot_async_tool_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "result": { + "name": "result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_decision": { + "name": "permission_decision", + "type": "copilot_tool_permission_decision", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "permission_decided_at": { + "name": "permission_decided_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_requested_at": { + "name": "permission_requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "pickup_deadline_at": { + "name": "pickup_deadline_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "persist_seq": { + "name": "persist_seq", + "type": "bigint", + "primaryKey": false, + "notNull": false, + "default": "nextval('copilot_async_tool_calls_persist_seq')" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "claimed_by": { + "name": "claimed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "browser_download_started_at": { + "name": "browser_download_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_started_at": { + "name": "execution_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_settled_at": { + "name": "execution_settled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "execution_owner_token": { + "name": "execution_owner_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_lease_expires_at": { + "name": "execution_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execution_revoked_at": { + "name": "execution_revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execution_attempts": { + "name": "execution_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "execution_deadline_at": { + "name": "execution_deadline_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "client_workflow_execution_id": { + "name": "client_workflow_execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sandbox_processes": { + "name": "sandbox_processes", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_async_tool_calls_checkpoint_id_idx": { + "name": "copilot_async_tool_calls_checkpoint_id_idx", + "columns": [ + { + "expression": "checkpoint_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_status_idx": { + "name": "copilot_async_tool_calls_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_run_status_idx": { + "name": "copilot_async_tool_calls_run_status_idx", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_async_tool_calls_tool_call_id_unique": { + "name": "copilot_async_tool_calls_tool_call_id_unique", + "columns": [ + { + "expression": "tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_async_tool_calls_run_id_copilot_runs_id_fk": { + "name": "copilot_async_tool_calls_run_id_copilot_runs_id_fk", + "tableFrom": "copilot_async_tool_calls", + "tableTo": "copilot_runs", + "columnsFrom": ["run_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_async_tool_calls_checkpoint_id_copilot_run_checkpoints_id_fk": { + "name": "copilot_async_tool_calls_checkpoint_id_copilot_run_checkpoints_id_fk", + "tableFrom": "copilot_async_tool_calls", + "tableTo": "copilot_run_checkpoints", + "columnsFrom": ["checkpoint_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_chats": { + "name": "copilot_chats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "memory_space_id": { + "name": "memory_space_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "chat_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'copilot'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude-3-7-sonnet-latest'" + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_conversation_key": { + "name": "external_conversation_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_conversation_metadata": { + "name": "external_conversation_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "preview_yaml": { + "name": "preview_yaml", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "resources": { + "name": "resources", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "auto_allowed_tools": { + "name": "auto_allowed_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "pinned": { + "name": "pinned", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_chats_organization_id_idx": { + "name": "copilot_chats_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_external_conversation_unique": { + "name": "copilot_chats_external_conversation_unique", + "columns": [ + { + "expression": "external_conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"copilot_chats\".\"external_conversation_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_org_created_idx": { + "name": "copilot_chats_user_org_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_workflow_id_idx": { + "name": "copilot_chats_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workflow_idx": { + "name": "copilot_chats_user_workflow_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workspace_idx": { + "name": "copilot_chats_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_created_at_idx": { + "name": "copilot_chats_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_updated_at_idx": { + "name": "copilot_chats_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_workspace_created_at_id_idx": { + "name": "copilot_chats_workspace_created_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"created_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_chats_user_workspace_deleted_partial_idx": { + "name": "copilot_chats_user_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_chats\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_chats_user_id_user_id_fk": { + "name": "copilot_chats_user_id_user_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_workflow_id_workflow_id_fk": { + "name": "copilot_chats_workflow_id_workflow_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_workspace_id_workspace_id_fk": { + "name": "copilot_chats_workspace_id_workspace_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_chats_organization_id_organization_id_fk": { + "name": "copilot_chats_organization_id_organization_id_fk", + "tableFrom": "copilot_chats", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "copilot_chats_owner_check": { + "name": "copilot_chats_owner_check", + "value": "num_nonnulls(\"copilot_chats\".\"workspace_id\", \"copilot_chats\".\"organization_id\") <= 1" + }, + "copilot_chats_organization_workflow_check": { + "name": "copilot_chats_organization_workflow_check", + "value": "\"copilot_chats\".\"organization_id\" IS NULL OR \"copilot_chats\".\"workflow_id\" IS NULL" + } + }, + "isRLSEnabled": false + }, + "public.copilot_feedback": { + "name": "copilot_feedback", + "schema": "", + "columns": { + "feedback_id": { + "name": "feedback_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_query": { + "name": "user_query", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent_response": { + "name": "agent_response", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_positive": { + "name": "is_positive", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "feedback": { + "name": "feedback", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_yaml": { + "name": "workflow_yaml", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_feedback_user_id_idx": { + "name": "copilot_feedback_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_chat_id_idx": { + "name": "copilot_feedback_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_user_chat_idx": { + "name": "copilot_feedback_user_chat_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_is_positive_idx": { + "name": "copilot_feedback_is_positive_idx", + "columns": [ + { + "expression": "is_positive", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_feedback_created_at_idx": { + "name": "copilot_feedback_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_feedback_user_id_user_id_fk": { + "name": "copilot_feedback_user_id_user_id_fk", + "tableFrom": "copilot_feedback", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_feedback_chat_id_copilot_chats_id_fk": { + "name": "copilot_feedback_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_feedback", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_messages": { + "name": "copilot_messages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "display_content": { + "name": "display_content", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_messages_chat_message_unique": { + "name": "copilot_messages_chat_message_unique", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_created_at_idx": { + "name": "copilot_messages_chat_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_seq_idx": { + "name": "copilot_messages_chat_seq_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_stream_idx": { + "name": "copilot_messages_chat_stream_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "stream_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"stream_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_user_seq_idx": { + "name": "copilot_messages_chat_user_seq_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_chat_user_created_at_idx": { + "name": "copilot_messages_chat_user_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user' AND \"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_messages_user_created_at_idx": { + "name": "copilot_messages_user_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_messages\".\"role\" = 'user' AND \"copilot_messages\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_messages_chat_id_copilot_chats_id_fk": { + "name": "copilot_messages_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_messages", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_organization_request_stops": { + "name": "copilot_organization_request_stops", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stopped_at": { + "name": "stopped_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "copilot_organization_request_stops_user_id_user_id_fk": { + "name": "copilot_organization_request_stops_user_id_user_id_fk", + "tableFrom": "copilot_organization_request_stops", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_organization_request_stops_organization_id_organization_id_fk": { + "name": "copilot_organization_request_stops_organization_id_organization_id_fk", + "tableFrom": "copilot_organization_request_stops", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "copilot_organization_request_stops_user_id_organization_id_stream_id_pk": { + "name": "copilot_organization_request_stops_user_id_organization_id_stream_id_pk", + "columns": ["user_id", "organization_id", "stream_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_request_stops": { + "name": "copilot_request_stops", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stopped_at": { + "name": "stopped_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "copilot_request_stops_user_id_user_id_fk": { + "name": "copilot_request_stops_user_id_user_id_fk", + "tableFrom": "copilot_request_stops", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_request_stops_workspace_id_workspace_id_fk": { + "name": "copilot_request_stops_workspace_id_workspace_id_fk", + "tableFrom": "copilot_request_stops", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "copilot_request_stops_user_id_workspace_id_stream_id_pk": { + "name": "copilot_request_stops_user_id_workspace_id_stream_id_pk", + "columns": ["user_id", "workspace_id", "stream_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_run_checkpoints": { + "name": "copilot_run_checkpoints", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "pending_tool_call_id": { + "name": "pending_tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "conversation_snapshot": { + "name": "conversation_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "agent_state": { + "name": "agent_state", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "provider_request": { + "name": "provider_request", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "copilot_run_checkpoints_pending_tool_call_id_idx": { + "name": "copilot_run_checkpoints_pending_tool_call_id_idx", + "columns": [ + { + "expression": "pending_tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_run_checkpoints_run_pending_tool_unique": { + "name": "copilot_run_checkpoints_run_pending_tool_unique", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "pending_tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_run_checkpoints_run_id_copilot_runs_id_fk": { + "name": "copilot_run_checkpoints_run_id_copilot_runs_id_fk", + "tableFrom": "copilot_run_checkpoints", + "tableTo": "copilot_runs", + "columnsFrom": ["run_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_runs": { + "name": "copilot_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_execution_version": { + "name": "tool_execution_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tool_admission_closed_at": { + "name": "tool_admission_closed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "parent_run_id": { + "name": "parent_run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stream_id": { + "name": "stream_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agent": { + "name": "agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "copilot_run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "request_context": { + "name": "request_context", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "desktop_device_id": { + "name": "desktop_device_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "copilot_runs_parent_run_id_idx": { + "name": "copilot_runs_parent_run_id_idx", + "columns": [ + { + "expression": "parent_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_chat_started_at_idx": { + "name": "copilot_runs_chat_started_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_user_id_idx": { + "name": "copilot_runs_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_workflow_id_idx": { + "name": "copilot_runs_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_status_idx": { + "name": "copilot_runs_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_chat_execution_idx": { + "name": "copilot_runs_chat_execution_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_execution_started_at_idx": { + "name": "copilot_runs_execution_started_at_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_workspace_completed_at_id_idx": { + "name": "copilot_runs_workspace_completed_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"completed_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_stream_id_unique": { + "name": "copilot_runs_stream_id_unique", + "columns": [ + { + "expression": "stream_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "copilot_runs_desktop_device_started_at_idx": { + "name": "copilot_runs_desktop_device_started_at_idx", + "columns": [ + { + "expression": "desktop_device_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"copilot_runs\".\"desktop_device_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "copilot_runs_chat_id_copilot_chats_id_fk": { + "name": "copilot_runs_chat_id_copilot_chats_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_user_id_user_id_fk": { + "name": "copilot_runs_user_id_user_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_workflow_id_workflow_id_fk": { + "name": "copilot_runs_workflow_id_workflow_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_workspace_id_workspace_id_fk": { + "name": "copilot_runs_workspace_id_workspace_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_organization_id_organization_id_fk": { + "name": "copilot_runs_organization_id_organization_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "copilot_runs_desktop_device_id_desktop_devices_id_fk": { + "name": "copilot_runs_desktop_device_id_desktop_devices_id_fk", + "tableFrom": "copilot_runs", + "tableTo": "desktop_devices", + "columnsFrom": ["desktop_device_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.copilot_service_usage": { + "name": "copilot_service_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "stream_id": { + "name": "stream_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tool_call_id": { + "name": "tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "service": { + "name": "service", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cost_usd": { + "name": "cost_usd", + "type": "numeric(12, 8)", + "primaryKey": false, + "notNull": false + }, + "worker_origin": { + "name": "worker_origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "delivered_at": { + "name": "delivered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "copilot_service_usage_pending_idx": { + "name": "copilot_service_usage_pending_idx", + "columns": [ + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "delivered_at IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.credential": { + "name": "credential", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "slack_app_id": { + "name": "slack_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "credential_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "unredacted": { + "name": "unredacted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_key": { + "name": "env_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_owner_user_id": { + "name": "env_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_service_account_key": { + "name": "encrypted_service_account_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_personal_token": { + "name": "encrypted_personal_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "authorization_app_id": { + "name": "authorization_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_enrollment_id": { + "name": "credential_group_enrollment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_option_id": { + "name": "credential_group_option_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_server_id": { + "name": "mcp_server_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_oauth_config_version": { + "name": "mcp_oauth_config_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "managed_oauth_scope_version": { + "name": "managed_oauth_scope_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "provider_subject_id": { + "name": "provider_subject_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_tenant_id": { + "name": "provider_tenant_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "managed_oauth_status": { + "name": "managed_oauth_status", + "type": "managed_oauth_credential_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "granted_scopes": { + "name": "granted_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "provider_metadata": { + "name": "provider_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "encrypted_oauth_token_set": { + "name": "encrypted_oauth_token_set", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mcp_tools": { + "name": "mcp_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "mcp_tools_refreshed_at": { + "name": "mcp_tools_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_refreshed_at": { + "name": "last_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_organization_id_idx": { + "name": "credential_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_organization_account_unique": { + "name": "credential_organization_account_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"account_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_org_personal_token_unique": { + "name": "credential_org_personal_token_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'personal_token'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_id_idx": { + "name": "credential_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_type_idx": { + "name": "credential_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_provider_id_idx": { + "name": "credential_provider_id_idx", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_account_id_idx": { + "name": "credential_account_id_idx", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_env_owner_user_id_idx": { + "name": "credential_env_owner_user_id_idx", + "columns": [ + { + "expression": "env_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_idx": { + "name": "credential_group_enrollment_idx", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_mcp_server_idx": { + "name": "credential_mcp_server_idx", + "columns": [ + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_option_identity_unique": { + "name": "credential_group_option_identity_unique", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "credential_group_option_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_tenant_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'managed_oauth'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_managed_mcp_enrollment_server_identity_unique": { + "name": "credential_managed_mcp_enrollment_server_identity_unique", + "columns": [ + { + "expression": "credential_group_enrollment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_subject_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"provider_tenant_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential\".\"type\" = 'managed_mcp'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_account_unique": { + "name": "credential_workspace_account_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "account_id IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_env_unique": { + "name": "credential_workspace_env_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "type = 'env_workspace'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_workspace_personal_env_unique": { + "name": "credential_workspace_personal_env_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "env_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "type = 'env_personal'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_workspace_id_workspace_id_fk": { + "name": "credential_workspace_id_workspace_id_fk", + "tableFrom": "credential", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_organization_id_organization_id_fk": { + "name": "credential_organization_id_organization_id_fk", + "tableFrom": "credential", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_slack_app_id_slack_app_id_fk": { + "name": "credential_slack_app_id_slack_app_id_fk", + "tableFrom": "credential", + "tableTo": "slack_app", + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "credential_account_id_account_id_fk": { + "name": "credential_account_id_account_id_fk", + "tableFrom": "credential", + "tableTo": "account", + "columnsFrom": ["account_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_env_owner_user_id_user_id_fk": { + "name": "credential_env_owner_user_id_user_id_fk", + "tableFrom": "credential", + "tableTo": "user", + "columnsFrom": ["env_owner_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_credential_group_enrollment_id_credential_group_enrollment_id_fk": { + "name": "credential_credential_group_enrollment_id_credential_group_enrollment_id_fk", + "tableFrom": "credential", + "tableTo": "credential_group_enrollment", + "columnsFrom": ["credential_group_enrollment_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_mcp_server_id_mcp_servers_id_fk": { + "name": "credential_mcp_server_id_mcp_servers_id_fk", + "tableFrom": "credential", + "tableTo": "mcp_servers", + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_created_by_user_id_fk": { + "name": "credential_created_by_user_id_fk", + "tableFrom": "credential", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_owner_check": { + "name": "credential_owner_check", + "value": "num_nonnulls(\"credential\".\"workspace_id\", \"credential\".\"organization_id\") = 1" + }, + "credential_organization_type_check": { + "name": "credential_organization_type_check", + "value": "\"credential\".\"organization_id\" IS NULL OR \"credential\".\"type\" IN ('oauth', 'managed_oauth', 'managed_mcp', 'service_account', 'personal_token')" + }, + "credential_personal_token_source_check": { + "name": "credential_personal_token_source_check", + "value": "(type::text <> 'personal_token') OR (\n created_by IS NOT NULL\n AND provider_id IS NOT NULL\n AND provider_id = 'gitlab'\n AND provider_subject_id IS NOT NULL\n AND provider_tenant_id IS NOT NULL\n AND encrypted_personal_token IS NOT NULL\n AND granted_scopes IS NOT NULL\n AND cardinality(granted_scopes) > 0\n AND account_id IS NULL\n AND env_key IS NULL\n AND env_owner_user_id IS NULL\n AND authorization_app_id IS NULL\n AND encrypted_oauth_token_set IS NULL\n AND encrypted_service_account_key IS NULL\n AND unredacted = false\n )" + }, + "credential_oauth_source_check": { + "name": "credential_oauth_source_check", + "value": "(type <> 'oauth') OR (account_id IS NOT NULL AND provider_id IS NOT NULL)" + }, + "credential_managed_oauth_source_check": { + "name": "credential_managed_oauth_source_check", + "value": "(type::text <> 'managed_oauth') OR (\n account_id IS NULL\n AND provider_id IS NOT NULL\n AND authorization_app_id IS NOT NULL\n AND provider_subject_id IS NOT NULL\n AND managed_oauth_status IS NOT NULL\n AND granted_scopes IS NOT NULL\n AND encrypted_oauth_token_set IS NOT NULL\n AND granted_at IS NOT NULL\n )" + }, + "credential_managed_oauth_group_binding_check": { + "name": "credential_managed_oauth_group_binding_check", + "value": "(type::text <> 'managed_oauth') OR (\n credential_group_enrollment_id IS NOT NULL\n AND credential_group_option_id IS NOT NULL\n AND managed_oauth_scope_version IS NOT NULL\n AND managed_oauth_scope_version > 0\n )" + }, + "credential_managed_mcp_source_check": { + "name": "credential_managed_mcp_source_check", + "value": "(type::text <> 'managed_mcp') OR (\n id LIKE 'mcp-cg-%'\n AND account_id IS NULL\n AND provider_id IS NULL\n AND authorization_app_id IS NULL\n AND credential_group_enrollment_id IS NOT NULL\n AND credential_group_option_id IS NULL\n AND mcp_server_id IS NOT NULL\n AND managed_oauth_status IS NOT NULL\n AND (managed_oauth_status <> 'active' OR (\n encrypted_oauth_token_set IS NOT NULL\n AND mcp_tools IS NOT NULL\n ))\n AND granted_at IS NOT NULL\n AND managed_oauth_scope_version IS NULL\n AND granted_scopes IS NULL\n AND provider_metadata IS NULL\n AND created_by IS NULL\n AND env_key IS NULL\n AND env_owner_user_id IS NULL\n AND encrypted_service_account_key IS NULL\n AND unredacted = false\n )" + }, + "credential_creator_source_check": { + "name": "credential_creator_source_check", + "value": "(type::text = 'managed_mcp') OR created_by IS NOT NULL" + }, + "credential_workspace_env_source_check": { + "name": "credential_workspace_env_source_check", + "value": "(type <> 'env_workspace') OR (env_key IS NOT NULL AND env_owner_user_id IS NULL)" + }, + "credential_personal_env_source_check": { + "name": "credential_personal_env_source_check", + "value": "(type <> 'env_personal') OR (env_key IS NOT NULL AND env_owner_user_id IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.credential_group": { + "name": "credential_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "public_id": { + "name": "public_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "encrypted_provider_configuration": { + "name": "encrypted_provider_configuration", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "credential_group_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_organization_unique": { + "name": "credential_group_organization_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_public_id_unique": { + "name": "credential_group_public_id_unique", + "columns": [ + { + "expression": "public_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_workspace_unique": { + "name": "credential_group_workspace_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_workspace_id_workspace_id_fk": { + "name": "credential_group_workspace_id_workspace_id_fk", + "tableFrom": "credential_group", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_organization_id_organization_id_fk": { + "name": "credential_group_organization_id_organization_id_fk", + "tableFrom": "credential_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_created_by_user_id_fk": { + "name": "credential_group_created_by_user_id_fk", + "tableFrom": "credential_group", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_owner_check": { + "name": "credential_group_owner_check", + "value": "num_nonnulls(\"credential_group\".\"workspace_id\", \"credential_group\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.credential_group_connection_request": { + "name": "credential_group_connection_request", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_connection_request_group_created_at_idx": { + "name": "credential_group_connection_request_group_created_at_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_connection_request_group_email_created_at_idx": { + "name": "credential_group_connection_request_group_email_created_at_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_connection_request_credential_group_id_credential_group_id_fk": { + "name": "credential_group_connection_request_credential_group_id_credential_group_id_fk", + "tableFrom": "credential_group_connection_request", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_connection_request_normalized_email_check": { + "name": "credential_group_connection_request_normalized_email_check", + "value": "\"credential_group_connection_request\".\"email\" = lower(btrim(\"credential_group_connection_request\".\"email\")) AND length(\"credential_group_connection_request\".\"email\") BETWEEN 3 AND 320" + } + }, + "isRLSEnabled": false + }, + "public.credential_group_connection_request_policy": { + "name": "credential_group_connection_request_policy", + "schema": "", + "columns": { + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "policy": { + "name": "policy", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "credential_group_connection_request_policy_credential_group_id_credential_group_id_fk": { + "name": "credential_group_connection_request_policy_credential_group_id_credential_group_id_fk", + "tableFrom": "credential_group_connection_request_policy", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_connection_request_policy_updated_by_user_id_fk": { + "name": "credential_group_connection_request_policy_updated_by_user_id_fk", + "tableFrom": "credential_group_connection_request_policy", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_connection_request_policy_revision_check": { + "name": "credential_group_connection_request_policy_revision_check", + "value": "\"credential_group_connection_request_policy\".\"revision\" >= 1" + } + }, + "isRLSEnabled": false + }, + "public.credential_group_enrollment": { + "name": "credential_group_enrollment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "credential_group_enrollment_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'invited'" + }, + "invitation_token_hash": { + "name": "invitation_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invitation_expires_at": { + "name": "invitation_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "invited_at": { + "name": "invited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_delivery_error": { + "name": "last_delivery_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_by_workflow_id": { + "name": "requested_by_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connection_request_reminders": { + "name": "connection_request_reminders", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_group_enrollment_group_user_unique": { + "name": "credential_group_enrollment_group_user_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"credential_group_enrollment\".\"user_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_user_id_idx": { + "name": "credential_group_enrollment_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_email_unique": { + "name": "credential_group_enrollment_group_email_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_invitation_token_hash_unique": { + "name": "credential_group_enrollment_invitation_token_hash_unique", + "columns": [ + { + "expression": "invitation_token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_status_idx": { + "name": "credential_group_enrollment_group_status_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_group_enrollment_group_invited_at_id_idx": { + "name": "credential_group_enrollment_group_invited_at_id_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "invited_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_group_enrollment_credential_group_id_credential_group_id_fk": { + "name": "credential_group_enrollment_credential_group_id_credential_group_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_enrollment_user_id_user_id_fk": { + "name": "credential_group_enrollment_user_id_user_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_group_enrollment_created_by_user_id_fk": { + "name": "credential_group_enrollment_created_by_user_id_fk", + "tableFrom": "credential_group_enrollment", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_group_enrollment_normalized_email_check": { + "name": "credential_group_enrollment_normalized_email_check", + "value": "\"credential_group_enrollment\".\"email\" = lower(btrim(\"credential_group_enrollment\".\"email\")) AND length(\"credential_group_enrollment\".\"email\") BETWEEN 3 AND 320" + }, + "credential_group_enrollment_invitation_token_hash_length_check": { + "name": "credential_group_enrollment_invitation_token_hash_length_check", + "value": "length(\"credential_group_enrollment\".\"invitation_token_hash\") = 64" + } + }, + "isRLSEnabled": false + }, + "public.credential_member": { + "name": "credential_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "credential_member_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "status": { + "name": "status", + "type": "credential_member_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "joined_at": { + "name": "joined_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_member_user_id_idx": { + "name": "credential_member_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_role_idx": { + "name": "credential_member_role_idx", + "columns": [ + { + "expression": "role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_status_idx": { + "name": "credential_member_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_member_unique": { + "name": "credential_member_unique", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_member_credential_id_credential_id_fk": { + "name": "credential_member_credential_id_credential_id_fk", + "tableFrom": "credential_member", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_member_user_id_user_id_fk": { + "name": "credential_member_user_id_user_id_fk", + "tableFrom": "credential_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_member_invited_by_user_id_fk": { + "name": "credential_member_invited_by_user_id_fk", + "tableFrom": "credential_member", + "tableTo": "user", + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_block": { + "name": "custom_block", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "icon_url": { + "name": "icon_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inputs": { + "name": "inputs", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "outputs": { + "name": "outputs", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "trace_child_runs": { + "name": "trace_child_runs", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "custom_block_workflow_id_idx": { + "name": "custom_block_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "custom_block_organization_type_unique": { + "name": "custom_block_organization_type_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "custom_block_organization_id_organization_id_fk": { + "name": "custom_block_organization_id_organization_id_fk", + "tableFrom": "custom_block", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_block_workflow_id_workflow_id_fk": { + "name": "custom_block_workflow_id_workflow_id_fk", + "tableFrom": "custom_block", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_block_created_by_user_id_fk": { + "name": "custom_block_created_by_user_id_fk", + "tableFrom": "custom_block", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_tools": { + "name": "custom_tools", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schema": { + "name": "schema", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "custom_tools_workspace_title_unique": { + "name": "custom_tools_workspace_title_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "custom_tools_workspace_id_workspace_id_fk": { + "name": "custom_tools_workspace_id_workspace_id_fk", + "tableFrom": "custom_tools", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "custom_tools_user_id_user_id_fk": { + "name": "custom_tools_user_id_user_id_fk", + "tableFrom": "custom_tools", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.dashboard": { + "name": "dashboard", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "dashboard_workspace_id_unique": { + "name": "dashboard_workspace_id_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "dashboard_workspace_id_workspace_id_fk": { + "name": "dashboard_workspace_id_workspace_id_fk", + "tableFrom": "dashboard", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "dashboard_created_by_user_id_fk": { + "name": "dashboard_created_by_user_id_fk", + "tableFrom": "dashboard", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "dashboard_updated_by_user_id_fk": { + "name": "dashboard_updated_by_user_id_fk", + "tableFrom": "dashboard", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.data_drain_runs": { + "name": "data_drain_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "drain_id": { + "name": "drain_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "data_drain_run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "data_drain_run_trigger", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "rows_exported": { + "name": "rows_exported", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "bytes_written": { + "name": "bytes_written", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cursor_before": { + "name": "cursor_before", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cursor_after": { + "name": "cursor_after", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locators": { + "name": "locators", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": { + "data_drain_runs_drain_started_idx": { + "name": "data_drain_runs_drain_started_idx", + "columns": [ + { + "expression": "drain_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "data_drain_runs_drain_id_data_drains_id_fk": { + "name": "data_drain_runs_drain_id_data_drains_id_fk", + "tableFrom": "data_drain_runs", + "tableTo": "data_drains", + "columnsFrom": ["drain_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.data_drains": { + "name": "data_drains", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "data_drain_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "destination_type": { + "name": "destination_type", + "type": "data_drain_destination", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "destination_config": { + "name": "destination_config", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "destination_credentials": { + "name": "destination_credentials", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schedule_cadence": { + "name": "schedule_cadence", + "type": "data_drain_cadence", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_success_at": { + "name": "last_success_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "data_drains_due_idx": { + "name": "data_drains_due_idx", + "columns": [ + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "data_drains_org_name_unique": { + "name": "data_drains_org_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "data_drains_organization_id_organization_id_fk": { + "name": "data_drains_organization_id_organization_id_fk", + "tableFrom": "data_drains", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "data_drains_created_by_user_id_fk": { + "name": "data_drains_created_by_user_id_fk", + "tableFrom": "data_drains", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deleted_account_identity": { + "name": "deleted_account_identity", + "schema": "", + "columns": { + "identity_hash": { + "name": "identity_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "deleted_account_identity_expires_at_idx": { + "name": "deleted_account_identity_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.desktop_devices": { + "name": "desktop_devices", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_version": { + "name": "app_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "capabilities": { + "name": "capabilities", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "desktop_devices_user_id_idx": { + "name": "desktop_devices_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "desktop_devices_session_id_idx": { + "name": "desktop_devices_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "desktop_devices_user_id_user_id_fk": { + "name": "desktop_devices_user_id_user_id_fk", + "tableFrom": "desktop_devices", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "desktop_devices_session_id_session_id_fk": { + "name": "desktop_devices_session_id_session_id_fk", + "tableFrom": "desktop_devices", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.docs_embeddings": { + "name": "docs_embeddings", + "schema": "", + "columns": { + "chunk_id": { + "name": "chunk_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chunk_text": { + "name": "chunk_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_document": { + "name": "source_document", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_link": { + "name": "source_link", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "header_text": { + "name": "header_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "header_level": { + "name": "header_level", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": true + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "chunk_text_tsv": { + "name": "chunk_text_tsv", + "type": "tsvector", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "to_tsvector('english', \"docs_embeddings\".\"chunk_text\")", + "type": "stored" + } + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "docs_emb_source_document_idx": { + "name": "docs_emb_source_document_idx", + "columns": [ + { + "expression": "source_document", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_header_level_idx": { + "name": "docs_emb_header_level_idx", + "columns": [ + { + "expression": "header_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_source_header_idx": { + "name": "docs_emb_source_header_idx", + "columns": [ + { + "expression": "source_document", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "header_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_model_idx": { + "name": "docs_emb_model_idx", + "columns": [ + { + "expression": "embedding_model", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_emb_created_at_idx": { + "name": "docs_emb_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "docs_embedding_vector_hnsw_idx": { + "name": "docs_embedding_vector_hnsw_idx", + "columns": [ + { + "expression": "embedding", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "vector_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "docs_emb_metadata_gin_idx": { + "name": "docs_emb_metadata_gin_idx", + "columns": [ + { + "expression": "metadata", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "docs_emb_chunk_text_fts_idx": { + "name": "docs_emb_chunk_text_fts_idx", + "columns": [ + { + "expression": "chunk_text_tsv", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "docs_embedding_not_null_check": { + "name": "docs_embedding_not_null_check", + "value": "\"embedding\" IS NOT NULL" + }, + "docs_header_level_check": { + "name": "docs_header_level_check", + "value": "\"header_level\" >= 1 AND \"header_level\" <= 6" + } + }, + "isRLSEnabled": false + }, + "public.document": { + "name": "document", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_url": { + "name": "file_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file_size": { + "name": "file_size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "file_sha256": { + "name": "file_sha256", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "character_count": { + "name": "character_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "processing_status": { + "name": "processing_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "processing_attempts": { + "name": "processing_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "processing_queued_at": { + "name": "processing_queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_queue_token": { + "name": "processing_queue_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_started_at": { + "name": "processing_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_deferred_until": { + "name": "processing_deferred_until", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_completed_at": { + "name": "processing_completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "processing_error": { + "name": "processing_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_recovery_after": { + "name": "processing_recovery_after", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "user_excluded": { + "name": "user_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "tag1": { + "name": "tag1", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag2": { + "name": "tag2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag3": { + "name": "tag3", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag4": { + "name": "tag4", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag5": { + "name": "tag5", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag6": { + "name": "tag6", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag7": { + "name": "tag7", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "number1": { + "name": "number1", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number2": { + "name": "number2", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number3": { + "name": "number3", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number4": { + "name": "number4", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number5": { + "name": "number5", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "date1": { + "name": "date1", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "date2": { + "name": "date2", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "boolean1": { + "name": "boolean1", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean2": { + "name": "boolean2", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean3": { + "name": "boolean3", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_url": { + "name": "source_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "acl": { + "name": "acl", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{ws}'::text[]" + }, + "acl_requirements": { + "name": "acl_requirements", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "acl_verified_at": { + "name": "acl_verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_modified_at": { + "name": "source_modified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_seen_at": { + "name": "source_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "doc_uploaded_by_idx": { + "name": "doc_uploaded_by_idx", + "columns": [ + { + "expression": "uploaded_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"uploaded_by\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_kb_source_modified_idx": { + "name": "doc_kb_source_modified_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_modified_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_acl_gin_idx": { + "name": "doc_acl_gin_idx", + "columns": [ + { + "expression": "acl", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "array_ops" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "gin", + "with": {} + }, + "doc_filename_idx": { + "name": "doc_filename_idx", + "columns": [ + { + "expression": "filename", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_processing_status_idx": { + "name": "doc_processing_status_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "processing_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_processing_recovery_idx": { + "name": "doc_connector_processing_recovery_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"processing_status\" IN ('pending', 'processing', 'failed') AND \"document\".\"connector_id\" IS NOT NULL AND \"document\".\"content_hash\" IS NOT NULL AND \"document\".\"storage_key\" IS NOT NULL AND \"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_connector_processing_status_idx": { + "name": "doc_connector_processing_status_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "processing_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"processing_status\" IN ('pending', 'processing', 'failed') AND \"document\".\"connector_id\" IS NOT NULL AND \"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_external_id_idx": { + "name": "doc_connector_external_id_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_source_lookup_idx": { + "name": "doc_connector_source_lookup_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_reconciliation_v2_idx": { + "name": "doc_connector_reconciliation_v2_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_active_kb_token_count_idx": { + "name": "doc_active_kb_token_count_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "token_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_storage_key_idx": { + "name": "doc_storage_key_idx", + "columns": [ + { + "expression": "storage_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"storage_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_archived_at_partial_idx": { + "name": "doc_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_deleted_at_partial_idx": { + "name": "doc_deleted_at_partial_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_tombstone_idx": { + "name": "doc_connector_tombstone_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"archived_at\" IS NULL AND (\"document\".\"deleted_at\" IS NOT NULL OR \"document\".\"content_hash\" IS NULL)", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_connector_live_idx": { + "name": "doc_connector_live_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"document\".\"user_excluded\" = false AND \"document\".\"archived_at\" IS NULL AND \"document\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag1_lower_idx": { + "name": "doc_kb_tag1_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag1\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag2_lower_idx": { + "name": "doc_kb_tag2_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag2\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag3_lower_idx": { + "name": "doc_kb_tag3_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag3\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag4_lower_idx": { + "name": "doc_kb_tag4_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag4\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag5_lower_idx": { + "name": "doc_kb_tag5_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag5\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag6_lower_idx": { + "name": "doc_kb_tag6_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag6\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_kb_tag7_lower_idx": { + "name": "doc_kb_tag7_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag7\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number1_idx": { + "name": "doc_number1_idx", + "columns": [ + { + "expression": "number1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number2_idx": { + "name": "doc_number2_idx", + "columns": [ + { + "expression": "number2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number3_idx": { + "name": "doc_number3_idx", + "columns": [ + { + "expression": "number3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number4_idx": { + "name": "doc_number4_idx", + "columns": [ + { + "expression": "number4", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_number5_idx": { + "name": "doc_number5_idx", + "columns": [ + { + "expression": "number5", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_date1_idx": { + "name": "doc_date1_idx", + "columns": [ + { + "expression": "date1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_date2_idx": { + "name": "doc_date2_idx", + "columns": [ + { + "expression": "date2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "doc_boolean1_idx": { + "name": "doc_boolean1_idx", + "columns": [ + { + "expression": "boolean1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_boolean2_idx": { + "name": "doc_boolean2_idx", + "columns": [ + { + "expression": "boolean2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "doc_boolean3_idx": { + "name": "doc_boolean3_idx", + "columns": [ + { + "expression": "boolean3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "document_knowledge_base_id_knowledge_base_id_fk": { + "name": "document_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "document", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "document_connector_id_knowledge_connector_id_fk": { + "name": "document_connector_id_knowledge_connector_id_fk", + "tableFrom": "document", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "document_uploaded_by_user_id_fk": { + "name": "document_uploaded_by_user_id_fk", + "tableFrom": "document", + "tableTo": "user", + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "doc_acl_token_shape_check": { + "name": "doc_acl_token_shape_check", + "value": "array_position(\"document\".\"acl\", NULL) IS NULL AND (cardinality(\"document\".\"acl\") = 0 OR (cardinality(\"document\".\"acl\") = array_length(string_to_array(array_to_string(\"document\".\"acl\", E'\\n'), E'\\n'), 1) AND array_to_string(\"document\".\"acl\", E'\\n') ~ '^((ws|pub|link|u:[^\\nA-Z]+@[^\\nA-Z]+|[gs]:[^\\n:]+:[^\\n:]+:[^\\n]+)(\\n(ws|pub|link|u:[^\\nA-Z]+@[^\\nA-Z]+|[gs]:[^\\n:]+:[^\\n:]+:[^\\n]+))*)$'))" + } + }, + "isRLSEnabled": false + }, + "public.document_secret_provenance": { + "name": "document_secret_provenance", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "document_secret_provenance_document_id_document_id_fk": { + "name": "document_secret_provenance_document_id_document_id_fk", + "tableFrom": "document_secret_provenance", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "document_secret_provenance_status_check": { + "name": "document_secret_provenance_status_check", + "value": "\"document_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.embedding": { + "name": "embedding", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chunk_index": { + "name": "chunk_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "chunk_hash": { + "name": "chunk_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "content_length": { + "name": "content_length", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": false + }, + "embedding_384": { + "name": "embedding_384", + "type": "vector(384)", + "primaryKey": false, + "notNull": false + }, + "embedding_768": { + "name": "embedding_768", + "type": "vector(768)", + "primaryKey": false, + "notNull": false + }, + "embedding_1024": { + "name": "embedding_1024", + "type": "vector(1024)", + "primaryKey": false, + "notNull": false + }, + "embedding_3072": { + "name": "embedding_3072", + "type": "vector(3072)", + "primaryKey": false, + "notNull": false + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "start_offset": { + "name": "start_offset", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "end_offset": { + "name": "end_offset", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "tag1": { + "name": "tag1", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag2": { + "name": "tag2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag3": { + "name": "tag3", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag4": { + "name": "tag4", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag5": { + "name": "tag5", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag6": { + "name": "tag6", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tag7": { + "name": "tag7", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "number1": { + "name": "number1", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number2": { + "name": "number2", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number3": { + "name": "number3", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number4": { + "name": "number4", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "number5": { + "name": "number5", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "date1": { + "name": "date1", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "date2": { + "name": "date2", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "boolean1": { + "name": "boolean1", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean2": { + "name": "boolean2", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "boolean3": { + "name": "boolean3", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "content_tsv": { + "name": "content_tsv", + "type": "tsvector", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "to_tsvector('english', \"embedding\".\"content\")", + "type": "stored" + } + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "emb_doc_chunk_idx": { + "name": "emb_doc_chunk_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chunk_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_model_idx": { + "name": "emb_kb_model_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "embedding_model", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_enabled_idx": { + "name": "emb_kb_enabled_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_doc_enabled_idx": { + "name": "emb_doc_enabled_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag1_lower_idx": { + "name": "emb_kb_tag1_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag1\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag2_lower_idx": { + "name": "emb_kb_tag2_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag2\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag3_lower_idx": { + "name": "emb_kb_tag3_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag3\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag4_lower_idx": { + "name": "emb_kb_tag4_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag4\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag5_lower_idx": { + "name": "emb_kb_tag5_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag5\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag6_lower_idx": { + "name": "emb_kb_tag6_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag6\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_kb_tag7_lower_idx": { + "name": "emb_kb_tag7_lower_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"tag7\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number1_idx": { + "name": "emb_number1_idx", + "columns": [ + { + "expression": "number1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number2_idx": { + "name": "emb_number2_idx", + "columns": [ + { + "expression": "number2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number3_idx": { + "name": "emb_number3_idx", + "columns": [ + { + "expression": "number3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number4_idx": { + "name": "emb_number4_idx", + "columns": [ + { + "expression": "number4", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_number5_idx": { + "name": "emb_number5_idx", + "columns": [ + { + "expression": "number5", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_date1_idx": { + "name": "emb_date1_idx", + "columns": [ + { + "expression": "date1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "emb_date2_idx": { + "name": "emb_date2_idx", + "columns": [ + { + "expression": "date2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "emb_boolean1_idx": { + "name": "emb_boolean1_idx", + "columns": [ + { + "expression": "boolean1", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_boolean2_idx": { + "name": "emb_boolean2_idx", + "columns": [ + { + "expression": "boolean2", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_boolean3_idx": { + "name": "emb_boolean3_idx", + "columns": [ + { + "expression": "boolean3", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "emb_content_fts_idx": { + "name": "emb_content_fts_idx", + "columns": [ + { + "expression": "content_tsv", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": { + "fastupdate": "off" + } + } + }, + "foreignKeys": { + "embedding_knowledge_base_id_knowledge_base_id_fk": { + "name": "embedding_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "embedding", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "embedding_document_id_document_id_fk": { + "name": "embedding_document_id_document_id_fk", + "tableFrom": "embedding", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_width_check": { + "name": "embedding_width_check", + "value": "num_nonnulls(\"embedding\", \"embedding_384\", \"embedding_768\", \"embedding_1024\", \"embedding_3072\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.embedding_search": { + "name": "embedding_search", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "acl": { + "name": "acl", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "binary": { + "name": "binary", + "type": "bit(1536)", + "primaryKey": false, + "notNull": false + }, + "binary_384": { + "name": "binary_384", + "type": "bit(384)", + "primaryKey": false, + "notNull": false + }, + "binary_768": { + "name": "binary_768", + "type": "bit(768)", + "primaryKey": false, + "notNull": false + }, + "binary_1024": { + "name": "binary_1024", + "type": "bit(1024)", + "primaryKey": false, + "notNull": false + }, + "binary_3072": { + "name": "binary_3072", + "type": "bit(3072)", + "primaryKey": false, + "notNull": false + }, + "vector": { + "name": "vector", + "type": "halfvec(1536)", + "primaryKey": false, + "notNull": false + }, + "vector_384": { + "name": "vector_384", + "type": "halfvec(384)", + "primaryKey": false, + "notNull": false + }, + "vector_512": { + "name": "vector_512", + "type": "halfvec(512)", + "primaryKey": false, + "notNull": false + }, + "vector_768": { + "name": "vector_768", + "type": "halfvec(768)", + "primaryKey": false, + "notNull": false + }, + "vector_1024": { + "name": "vector_1024", + "type": "halfvec(1024)", + "primaryKey": false, + "notNull": false + }, + "vector_3072": { + "name": "vector_3072", + "type": "halfvec(3072)", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "embedding_search_kb_idx": { + "name": "embedding_search_kb_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "embedding_search_document_lookup_idx": { + "name": "embedding_search_document_lookup_idx", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"embedding_search\".\"enabled\"", + "concurrently": true, + "method": "btree", + "with": {} + }, + "embedding_search_cosine_hnsw_idx": { + "name": "embedding_search_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_512_cosine_hnsw_idx": { + "name": "embedding_search_512_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_512", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_384_cosine_hnsw_idx": { + "name": "embedding_search_384_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_384", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_768_cosine_hnsw_idx": { + "name": "embedding_search_768_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_768", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_1024_cosine_hnsw_idx": { + "name": "embedding_search_1024_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_1024", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + }, + "embedding_search_3072_cosine_hnsw_idx": { + "name": "embedding_search_3072_cosine_hnsw_idx", + "columns": [ + { + "expression": "vector_3072", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "halfvec_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + } + }, + "foreignKeys": { + "embedding_search_id_embedding_id_fk": { + "name": "embedding_search_id_embedding_id_fk", + "tableFrom": "embedding_search", + "tableTo": "embedding", + "columnsFrom": ["id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_search_width_check": { + "name": "embedding_search_width_check", + "value": "num_nonnulls(\"binary\", \"binary_384\", \"binary_768\", \"binary_1024\", \"binary_3072\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.embedding_secret_provenance": { + "name": "embedding_secret_provenance", + "schema": "", + "columns": { + "embedding_id": { + "name": "embedding_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "embedding_secret_provenance_embedding_id_embedding_id_fk": { + "name": "embedding_secret_provenance_embedding_id_embedding_id_fk", + "tableFrom": "embedding_secret_provenance", + "tableTo": "embedding", + "columnsFrom": ["embedding_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "embedding_secret_provenance_status_check": { + "name": "embedding_secret_provenance_status_check", + "value": "\"embedding_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.enterprise_seat_true_up": { + "name": "enterprise_seat_true_up", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "subscription_id": { + "name": "subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "window_start": { + "name": "window_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "window_end": { + "name": "window_end", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "peak_extra_seats": { + "name": "peak_extra_seats", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "seat_price_cents": { + "name": "seat_price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "amount_cents": { + "name": "amount_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "billed_at": { + "name": "billed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "enterprise_seat_true_up_subscription_window_unique": { + "name": "enterprise_seat_true_up_subscription_window_unique", + "columns": [ + { + "expression": "subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "window_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "enterprise_seat_true_up_organization_id_idx": { + "name": "enterprise_seat_true_up_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "enterprise_seat_true_up_unbilled_idx": { + "name": "enterprise_seat_true_up_unbilled_idx", + "columns": [ + { + "expression": "window_end", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "billed_at IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "enterprise_seat_true_up_subscription_id_subscription_id_fk": { + "name": "enterprise_seat_true_up_subscription_id_subscription_id_fk", + "tableFrom": "enterprise_seat_true_up", + "tableTo": "subscription", + "columnsFrom": ["subscription_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "enterprise_seat_true_up_organization_id_organization_id_fk": { + "name": "enterprise_seat_true_up_organization_id_organization_id_fk", + "tableFrom": "enterprise_seat_true_up", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.environment": { + "name": "environment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "environment_user_id_user_id_fk": { + "name": "environment_user_id_user_id_fk", + "tableFrom": "environment", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "environment_user_id_unique": { + "name": "environment_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_value_dependencies": { + "name": "execution_large_value_dependencies", + "schema": "", + "columns": { + "parent_key": { + "name": "parent_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_key": { + "name": "child_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "execution_large_value_dependencies_workspace_parent_key_idx": { + "name": "execution_large_value_dependencies_workspace_parent_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_value_dependencies_workspace_child_key_idx": { + "name": "execution_large_value_dependencies_workspace_child_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_value_dependencies_workspace_id_workspace_id_fk": { + "name": "execution_large_value_dependencies_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_value_dependencies", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "execution_large_value_dependencies_parent_key_child_key_pk": { + "name": "execution_large_value_dependencies_parent_key_child_key_pk", + "columns": ["parent_key", "child_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_value_references": { + "name": "execution_large_value_references", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "execution_large_value_reference_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "execution_large_value_references_workspace_execution_source_idx": { + "name": "execution_large_value_references_workspace_execution_source_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_value_references_workflow_id_idx": { + "name": "execution_large_value_references_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_value_references_workspace_id_workspace_id_fk": { + "name": "execution_large_value_references_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_value_references", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_large_value_references_workflow_id_workflow_id_fk": { + "name": "execution_large_value_references_workflow_id_workflow_id_fk", + "tableFrom": "execution_large_value_references", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "execution_large_value_references_key_execution_id_source_pk": { + "name": "execution_large_value_references_key_execution_id_source_pk", + "columns": ["key", "execution_id", "source"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_large_values": { + "name": "execution_large_values", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_execution_id": { + "name": "owner_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "execution_large_values_owner_execution_id_idx": { + "name": "execution_large_values_owner_execution_id_idx", + "columns": [ + { + "expression": "owner_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_cleanup_idx": { + "name": "execution_large_values_cleanup_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"execution_large_values\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_tombstone_cleanup_idx": { + "name": "execution_large_values_tombstone_cleanup_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"execution_large_values\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_workflow_id_idx": { + "name": "execution_large_values_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_large_values_workspace_id_idx": { + "name": "execution_large_values_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_large_values_workspace_id_workspace_id_fk": { + "name": "execution_large_values_workspace_id_workspace_id_fk", + "tableFrom": "execution_large_values", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_large_values_workflow_id_workflow_id_fk": { + "name": "execution_large_values_workflow_id_workflow_id_fk", + "tableFrom": "execution_large_values", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.file_search_dependency": { + "name": "file_search_dependency", + "schema": "", + "columns": { + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "file_search_dependency_file_idx": { + "name": "file_search_dependency_file_idx", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "file_search_dependency_owner_idx": { + "name": "file_search_dependency_owner_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "file_search_dependency_build_id_workspace_file_search_build_id_fk": { + "name": "file_search_dependency_build_id_workspace_file_search_build_id_fk", + "tableFrom": "file_search_dependency", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "file_search_dependency_build_id_file_id_pk": { + "name": "file_search_dependency_build_id_file_id_pk", + "columns": ["build_id", "file_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.file_search_dispatch_queue": { + "name": "file_search_dispatch_queue", + "schema": "", + "columns": { + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enqueued_at": { + "name": "enqueued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_dispatched_at": { + "name": "last_dispatched_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "file_search_dispatch_schedule_idx": { + "name": "file_search_dispatch_schedule_idx", + "columns": [ + { + "expression": "last_dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "first" + }, + { + "expression": "enqueued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "file_search_dispatch_queue_entity_type_entity_id_pk": { + "name": "file_search_dispatch_queue_entity_type_entity_id_pk", + "columns": ["entity_type", "entity_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_dispatch_owner_check": { + "name": "file_search_dispatch_owner_check", + "value": "\"file_search_dispatch_queue\".\"entity_type\" IN ('workspace', 'project') AND length(\"file_search_dispatch_queue\".\"entity_id\") > 0" + } + }, + "isRLSEnabled": false + }, + "public.folder": { + "name": "folder", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_type": { + "name": "resource_type", + "type": "folder_resource_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parent_id": { + "name": "parent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "folder_project_id_idx": { + "name": "folder_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "folder_project_resource_parent_name_active_unique": { + "name": "folder_project_resource_parent_name_active_unique", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"parent_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"folder\".\"deleted_at\" IS NULL AND \"folder\".\"project_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "folder_user_idx": { + "name": "folder_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_resource_parent_idx": { + "name": "folder_workspace_resource_parent_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_parent_sort_idx": { + "name": "folder_parent_sort_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_deleted_at_idx": { + "name": "folder_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_deleted_partial_idx": { + "name": "folder_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"folder\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "folder_workspace_resource_parent_name_active_unique": { + "name": "folder_workspace_resource_parent_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"parent_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"folder\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "folder_project_id_project_id_fk": { + "name": "folder_project_id_project_id_fk", + "tableFrom": "folder", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "folder_user_id_user_id_fk": { + "name": "folder_user_id_user_id_fk", + "tableFrom": "folder", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "folder_workspace_id_workspace_id_fk": { + "name": "folder_workspace_id_workspace_id_fk", + "tableFrom": "folder", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "folder_parent_id_folder_id_fk": { + "name": "folder_parent_id_folder_id_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "folder_workspace_parent_owner_fk": { + "name": "folder_workspace_parent_owner_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id", "workspace_id", "resource_type"], + "columnsTo": ["id", "workspace_id", "resource_type"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "folder_project_parent_owner_fk": { + "name": "folder_project_parent_owner_fk", + "tableFrom": "folder", + "tableTo": "folder", + "columnsFrom": ["parent_id", "project_id", "resource_type"], + "columnsTo": ["id", "project_id", "resource_type"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "folder_workspace_owner_type_unique": { + "name": "folder_workspace_owner_type_unique", + "nullsNotDistinct": false, + "columns": ["id", "workspace_id", "resource_type"] + }, + "folder_project_owner_type_unique": { + "name": "folder_project_owner_type_unique", + "nullsNotDistinct": false, + "columns": ["id", "project_id", "resource_type"] + } + }, + "policies": {}, + "checkConstraints": { + "folder_owner_check": { + "name": "folder_owner_check", + "value": "num_nonnulls(\"folder\".\"workspace_id\", \"folder\".\"project_id\") = 1 AND (\"folder\".\"project_id\" IS NULL OR \"folder\".\"resource_type\" = 'file')" + } + }, + "isRLSEnabled": false + }, + "public.idempotency_key": { + "name": "idempotency_key", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "result": { + "name": "result", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idempotency_key_created_at_idx": { + "name": "idempotency_key_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitation": { + "name": "invitation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "invitation_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'organization'" + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "inviter_id": { + "name": "inviter_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "membership_intent": { + "name": "membership_intent", + "type": "invitation_membership_intent", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'internal'" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "invitation_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "invitation_email_idx": { + "name": "invitation_email_idx", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_organization_id_idx": { + "name": "invitation_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_status_idx": { + "name": "invitation_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_pending_email_org_unique": { + "name": "invitation_pending_email_org_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"invitation\".\"status\" = 'pending' AND \"invitation\".\"organization_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitation_inviter_id_user_id_fk": { + "name": "invitation_inviter_id_user_id_fk", + "tableFrom": "invitation", + "tableTo": "user", + "columnsFrom": ["inviter_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_organization_id_organization_id_fk": { + "name": "invitation_organization_id_organization_id_fk", + "tableFrom": "invitation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "invitation_token_unique": { + "name": "invitation_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitation_workspace_grant": { + "name": "invitation_workspace_grant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "invitation_id": { + "name": "invitation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission": { + "name": "permission", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "invitation_workspace_grant_unique": { + "name": "invitation_workspace_grant_unique", + "columns": [ + { + "expression": "invitation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_workspace_grant_workspace_id_idx": { + "name": "invitation_workspace_grant_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitation_workspace_grant_invitation_id_invitation_id_fk": { + "name": "invitation_workspace_grant_invitation_id_invitation_id_fk", + "tableFrom": "invitation_workspace_grant", + "tableTo": "invitation", + "columnsFrom": ["invitation_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_workspace_grant_workspace_id_workspace_id_fk": { + "name": "invitation_workspace_grant_workspace_id_workspace_id_fk", + "tableFrom": "invitation_workspace_grant", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.job_execution_logs": { + "name": "job_execution_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "schedule_id": { + "name": "schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_duration_ms": { + "name": "total_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "execution_data": { + "name": "execution_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "cost": { + "name": "cost", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "occurrence_at": { + "name": "occurrence_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_request_id": { + "name": "billing_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "job_execution_logs_schedule_occurrence_unique": { + "name": "job_execution_logs_schedule_occurrence_unique", + "columns": [ + { + "expression": "schedule_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "occurrence_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_billing_request_unique": { + "name": "job_execution_logs_billing_request_unique", + "columns": [ + { + "expression": "billing_request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"job_execution_logs\".\"billing_request_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_open_idx": { + "name": "job_execution_logs_open_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"job_execution_logs\".\"status\" IN ('queued', 'running')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_workspace_started_at_idx": { + "name": "job_execution_logs_workspace_started_at_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_workspace_ended_at_id_idx": { + "name": "job_execution_logs_workspace_ended_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"ended_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_execution_id_unique": { + "name": "job_execution_logs_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "job_execution_logs_trigger_idx": { + "name": "job_execution_logs_trigger_idx", + "columns": [ + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "job_execution_logs_schedule_id_workflow_schedule_id_fk": { + "name": "job_execution_logs_schedule_id_workflow_schedule_id_fk", + "tableFrom": "job_execution_logs", + "tableTo": "workflow_schedule", + "columnsFrom": ["schedule_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "job_execution_logs_workspace_id_workspace_id_fk": { + "name": "job_execution_logs_workspace_id_workspace_id_fk", + "tableFrom": "job_execution_logs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_base": { + "name": "knowledge_base", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_search_index": { + "name": "is_search_index", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "token_count": { + "name": "token_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "embedding_model": { + "name": "embedding_model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text-embedding-3-small'" + }, + "embedding_dimension": { + "name": "embedding_dimension", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1536 + }, + "chunking_config": { + "name": "chunking_config", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{\"maxSize\": 1024, \"minSize\": 1, \"overlap\": 200}'" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kb_organization_id_idx": { + "name": "kb_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_organization_search_index_unique": { + "name": "kb_organization_search_index_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"is_search_index\" = true AND \"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_organization_name_active_unique": { + "name": "kb_organization_name_active_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_id_idx": { + "name": "kb_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_user_workspace_idx": { + "name": "kb_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_folder_id_idx": { + "name": "kb_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_deleted_at_idx": { + "name": "kb_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_deleted_partial_idx": { + "name": "kb_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_base\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_name_active_unique": { + "name": "kb_workspace_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_workspace_search_index_unique": { + "name": "kb_workspace_search_index_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"knowledge_base\".\"is_search_index\" = true AND \"knowledge_base\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_user_id_user_id_fk": { + "name": "knowledge_base_user_id_user_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_workspace_id_workspace_id_fk": { + "name": "knowledge_base_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_organization_id_organization_id_fk": { + "name": "knowledge_base_organization_id_organization_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_folder_id_folder_id_fk": { + "name": "knowledge_base_folder_id_folder_id_fk", + "tableFrom": "knowledge_base", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kb_owner_check": { + "name": "kb_owner_check", + "value": "num_nonnulls(\"knowledge_base\".\"workspace_id\", \"knowledge_base\".\"organization_id\") = 1" + }, + "kb_organization_search_index_check": { + "name": "kb_organization_search_index_check", + "value": "\"knowledge_base\".\"organization_id\" IS NULL OR \"knowledge_base\".\"is_search_index\"" + }, + "kb_organization_folder_check": { + "name": "kb_organization_folder_check", + "value": "\"knowledge_base\".\"organization_id\" IS NULL OR \"knowledge_base\".\"folder_id\" IS NULL" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_base_import": { + "name": "knowledge_base_import", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_key": { + "name": "source_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "documents_total": { + "name": "documents_total", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "documents_imported": { + "name": "documents_imported", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "documents_failed": { + "name": "documents_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "vectors_reused": { + "name": "vectors_reused", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "failures": { + "name": "failures", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "knowledge_base_import_watchdog_idx": { + "name": "knowledge_base_import_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "knowledge_base_import_knowledge_base_id_idx": { + "name": "knowledge_base_import_knowledge_base_id_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_import_workspace_id_workspace_id_fk": { + "name": "knowledge_base_import_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_base_import", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_base_import_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_base_import_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_base_import", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_base_tag_definitions": { + "name": "knowledge_base_tag_definitions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tag_slot": { + "name": "tag_slot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "field_type": { + "name": "field_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'text'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kb_tag_definitions_kb_slot_idx": { + "name": "kb_tag_definitions_kb_slot_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tag_slot", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kb_tag_definitions_kb_display_name_idx": { + "name": "kb_tag_definitions_kb_display_name_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_base_tag_definitions_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_base_tag_definitions_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_base_tag_definitions", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector": { + "name": "knowledge_connector", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_config": { + "name": "source_config", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "sync_mode": { + "name": "sync_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'full'" + }, + "sync_interval_minutes": { + "name": "sync_interval_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1440 + }, + "access_mode": { + "name": "access_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'workspace'" + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_option_id": { + "name": "credential_group_option_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_status": { + "name": "member_sync_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'idle'" + }, + "member_sync_lock_token": { + "name": "member_sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_lock_lease_at": { + "name": "member_sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "next_member_sync_at": { + "name": "next_member_sync_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": false + }, + "last_member_sync_at": { + "name": "last_member_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_member_sync_error": { + "name": "last_member_sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_sync_consecutive_failures": { + "name": "member_sync_consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "access_rewrite_pending": { + "name": "access_rewrite_pending", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image_removal_pending": { + "name": "image_removal_pending", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "member_tombstone_cursor": { + "name": "member_tombstone_cursor", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "member_resurrection_cursor": { + "name": "member_resurrection_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "last_sync_at": { + "name": "last_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_sync_error": { + "name": "last_sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_sync_doc_count": { + "name": "last_sync_doc_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "listing_checkpoint": { + "name": "listing_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "directory_checkpoint": { + "name": "directory_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "next_sync_at": { + "name": "next_sync_at", + "type": "timestamp (3)", + "primaryKey": false, + "notNull": false + }, + "next_directory_sync_at": { + "name": "next_directory_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "sync_lock_token": { + "name": "sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_lock_lease_at": { + "name": "sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "detached_at": { + "name": "detached_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "detach_reserved_bytes": { + "name": "detach_reserved_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "kc_knowledge_base_id_idx": { + "name": "kc_knowledge_base_id_idx", + "columns": [ + { + "expression": "knowledge_base_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_status_next_sync_idx": { + "name": "kc_status_next_sync_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_archived_at_partial_idx": { + "name": "kc_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_deleted_at_partial_idx": { + "name": "kc_deleted_at_partial_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_member_sync_due_idx": { + "name": "kc_member_sync_due_idx", + "columns": [ + { + "expression": "member_sync_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_member_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"access_mode\" = 'members' AND \"knowledge_connector\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kc_directory_sync_due_idx": { + "name": "kc_directory_sync_due_idx", + "columns": [ + { + "expression": "next_directory_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector\".\"access_mode\" = 'admin' AND \"knowledge_connector\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_knowledge_base_id_knowledge_base_id_fk": { + "name": "knowledge_connector_knowledge_base_id_knowledge_base_id_fk", + "tableFrom": "knowledge_connector", + "tableTo": "knowledge_base", + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_credential_group_id_credential_group_id_fk": { + "name": "knowledge_connector_credential_group_id_credential_group_id_fk", + "tableFrom": "knowledge_connector", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kc_access_mode_check": { + "name": "kc_access_mode_check", + "value": "\"knowledge_connector\".\"access_mode\" IN ('workspace', 'members', 'admin')" + }, + "kc_member_sync_status_check": { + "name": "kc_member_sync_status_check", + "value": "\"knowledge_connector\".\"member_sync_status\" IN ('idle', 'pending', 'running', 'error', 'disabled')" + }, + "kc_sync_lock_exclusive_check": { + "name": "kc_sync_lock_exclusive_check", + "value": "NOT (\"knowledge_connector\".\"sync_lock_token\" IS NOT NULL AND \"knowledge_connector\".\"member_sync_lock_token\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_member": { + "name": "knowledge_connector_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_started_at": { + "name": "last_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_complete_listing_at": { + "name": "last_complete_listing_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_listed_count": { + "name": "last_listed_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "member_synced_through": { + "name": "member_synced_through", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope_renewed_at": { + "name": "scope_renewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope_renewal_cursor": { + "name": "scope_renewal_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope_renewal_started_at": { + "name": "scope_renewal_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "change_cursor": { + "name": "change_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "listing_checkpoint": { + "name": "listing_checkpoint", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kcm_organization_id_idx": { + "name": "kcm_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_connector_credential_unique": { + "name": "kcm_connector_credential_unique", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_connector_queue_idx": { + "name": "kcm_connector_queue_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "first" + }, + { + "expression": "last_started_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcm_credential_idx": { + "name": "kcm_credential_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_member_workspace_id_workspace_id_fk": { + "name": "knowledge_connector_member_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_organization_id_organization_id_fk": { + "name": "knowledge_connector_member_organization_id_organization_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_member_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_connector_member_credential_id_credential_id_fk": { + "name": "knowledge_connector_member_credential_id_credential_id_fk", + "tableFrom": "knowledge_connector_member", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcm_owner_check": { + "name": "kcm_owner_check", + "value": "num_nonnulls(\"knowledge_connector_member\".\"workspace_id\", \"knowledge_connector_member\".\"organization_id\") = 1" + }, + "kcm_status_check": { + "name": "kcm_status_check", + "value": "\"knowledge_connector_member\".\"status\" IN ('active', 'suspended', 'disabled')" + }, + "kcm_subject_token_shape_check": { + "name": "kcm_subject_token_shape_check", + "value": "\"knowledge_connector_member\".\"subject_token\" ~ '^s:[^:]+:[^:]+:.+$'" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_member_sync_log": { + "name": "knowledge_connector_member_sync_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "members_claimed": { + "name": "members_claimed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_completed": { + "name": "members_completed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_incomplete": { + "name": "members_incomplete", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "members_failed": { + "name": "members_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_failed": { + "name": "docs_failed", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "processing_dispatch_failed": { + "name": "processing_dispatch_failed", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "docs_listed": { + "name": "docs_listed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_added": { + "name": "docs_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_updated": { + "name": "docs_updated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_unchanged": { + "name": "docs_unchanged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_hydrated_once": { + "name": "docs_hydrated_once", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_added": { + "name": "observations_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_renewed": { + "name": "observations_renewed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "observations_removed": { + "name": "observations_removed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_tombstoned": { + "name": "docs_tombstoned", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_resurrected": { + "name": "docs_resurrected", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_purged": { + "name": "docs_purged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "credentials_audited": { + "name": "credentials_audited", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "database_failure_class": { + "name": "database_failure_class", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcmsl_connector_started_at_idx": { + "name": "kcmsl_connector_started_at_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcmsl_started_at_partial_idx": { + "name": "kcmsl_started_at_partial_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_member_sync_log\".\"status\" = 'started'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_member_sync_log_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_member_sync_log_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_member_sync_log", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcmsl_status_check": { + "name": "kcmsl_status_check", + "value": "\"knowledge_connector_member_sync_log\".\"status\" IN ('started', 'partial', 'completed', 'failed')" + }, + "kcmsl_database_failure_class_check": { + "name": "kcmsl_database_failure_class_check", + "value": "\"knowledge_connector_member_sync_log\".\"database_failure_class\" IN ('capacity', 'conflict', 'connection')" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_partition": { + "name": "knowledge_connector_partition", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "partition_key": { + "name": "partition_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation_id": { + "name": "generation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context": { + "name": "context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "retry_at": { + "name": "retry_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "permission_cursor": { + "name": "permission_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_attempts": { + "name": "permission_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "permission_retry_at": { + "name": "permission_retry_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "permission_last_served_at": { + "name": "permission_last_served_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_started_at": { + "name": "permission_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "permission_failure": { + "name": "permission_failure", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcp_content_due_idx": { + "name": "kcp_content_due_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "retry_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_served_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcp_permission_due_idx": { + "name": "kcp_permission_due_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_retry_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_last_served_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_partition_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_partition_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_partition", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcp_pk": { + "name": "kcp_pk", + "columns": ["connector_id", "partition_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcp_partition_key_check": { + "name": "kcp_partition_key_check", + "value": "octet_length(\"knowledge_connector_partition\".\"partition_key\") BETWEEN 1 AND 1024" + }, + "kcp_context_check": { + "name": "kcp_context_check", + "value": "jsonb_typeof(\"knowledge_connector_partition\".\"context\") = 'object' AND octet_length(\"knowledge_connector_partition\".\"context\"::text) <= 16384" + }, + "kcp_status_check": { + "name": "kcp_status_check", + "value": "\"knowledge_connector_partition\".\"status\" IN ('pending', 'complete', 'blocked')" + }, + "kcp_cursor_check": { + "name": "kcp_cursor_check", + "value": "(\"knowledge_connector_partition\".\"cursor\" IS NULL OR octet_length(\"knowledge_connector_partition\".\"cursor\") <= 393216) AND (\"knowledge_connector_partition\".\"permission_cursor\" IS NULL OR octet_length(\"knowledge_connector_partition\".\"permission_cursor\") <= 393216)" + }, + "kcp_attempts_check": { + "name": "kcp_attempts_check", + "value": "\"knowledge_connector_partition\".\"attempts\" >= 0 AND \"knowledge_connector_partition\".\"permission_attempts\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_grant": { + "name": "knowledge_connector_permission_grant", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_key": { + "name": "group_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpg_subject_idx": { + "name": "kcpg_subject_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "kcpg_snapshot_fk": { + "name": "kcpg_snapshot_fk", + "tableFrom": "knowledge_connector_permission_grant", + "tableTo": "knowledge_connector_permission_snapshot", + "columnsFrom": ["connector_id"], + "columnsTo": ["connector_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpg_pk": { + "name": "kcpg_pk", + "columns": ["connector_id", "group_key", "subject_token"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcpg_group_check": { + "name": "kcpg_group_check", + "value": "length(\"knowledge_connector_permission_grant\".\"group_key\") BETWEEN 1 AND 255" + }, + "kcpg_subject_check": { + "name": "kcpg_subject_check", + "value": "\"knowledge_connector_permission_grant\".\"subject_token\" ~ '^u:[^[:space:]A-Z]+@[^[:space:]A-Z]+$'" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import": { + "name": "knowledge_connector_permission_import", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_binding": { + "name": "credential_binding", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expected_revision": { + "name": "expected_revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "manifest": { + "name": "manifest", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "part_digests": { + "name": "part_digests", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "user_rows": { + "name": "user_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "project_rows": { + "name": "project_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "completed_revision": { + "name": "completed_revision", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpi_connector_idx": { + "name": "kcpi_connector_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcpi_expires_idx": { + "name": "kcpi_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_permission_import_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_permission_import", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcpi_revision_check": { + "name": "kcpi_revision_check", + "value": "\"knowledge_connector_permission_import\".\"expected_revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import_grant": { + "name": "knowledge_connector_permission_import_grant", + "schema": "", + "columns": { + "import_id": { + "name": "import_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_path": { + "name": "project_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_key": { + "name": "group_key", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcpig_subject_idx": { + "name": "kcpig_subject_idx", + "columns": [ + { + "expression": "import_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_grant_import_id_knowledge_connector_permission_import_id_fk": { + "name": "knowledge_connector_permission_import_grant_import_id_knowledge_connector_permission_import_id_fk", + "tableFrom": "knowledge_connector_permission_import_grant", + "tableTo": "knowledge_connector_permission_import", + "columnsFrom": ["import_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpig_pk": { + "name": "kcpig_pk", + "columns": ["import_id", "project_path", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_import_identity": { + "name": "knowledge_connector_permission_import_identity", + "schema": "", + "columns": { + "import_id": { + "name": "import_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kcpii_subject_import_idx": { + "name": "kcpii_subject_import_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "import_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_permission_import_identity_import_id_knowledge_connector_permission_import_id_fk": { + "name": "knowledge_connector_permission_import_identity_import_id_knowledge_connector_permission_import_id_fk", + "tableFrom": "knowledge_connector_permission_import_identity", + "tableTo": "knowledge_connector_permission_import", + "columnsFrom": ["import_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "kcpii_pk": { + "name": "kcpii_pk", + "columns": ["import_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_connector_permission_snapshot": { + "name": "knowledge_connector_permission_snapshot", + "schema": "", + "columns": { + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "kcps_connector_fk": { + "name": "kcps_connector_fk", + "tableFrom": "knowledge_connector_permission_snapshot", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcps_revision_check": { + "name": "kcps_revision_check", + "value": "\"knowledge_connector_permission_snapshot\".\"revision\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_connector_sync_log": { + "name": "knowledge_connector_sync_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "docs_added": { + "name": "docs_added", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_updated": { + "name": "docs_updated", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_deleted": { + "name": "docs_deleted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_unchanged": { + "name": "docs_unchanged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_skipped": { + "name": "docs_skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "docs_failed": { + "name": "docs_failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "listed_count": { + "name": "listed_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "database_failure_class": { + "name": "database_failure_class", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "kcsl_connector_started_at_idx": { + "name": "kcsl_connector_started_at_idx", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcsl_started_at_partial_idx": { + "name": "kcsl_started_at_partial_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_sync_log\".\"status\" = 'started'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "kcsl_terminal_started_at_idx": { + "name": "kcsl_terminal_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"knowledge_connector_sync_log\".\"status\" IN ('completed', 'failed')", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_connector_sync_log_connector_id_knowledge_connector_id_fk": { + "name": "knowledge_connector_sync_log_connector_id_knowledge_connector_id_fk", + "tableFrom": "knowledge_connector_sync_log", + "tableTo": "knowledge_connector", + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kcsl_database_failure_class_check": { + "name": "kcsl_database_failure_class_check", + "value": "\"knowledge_connector_sync_log\".\"database_failure_class\" IN ('capacity', 'conflict', 'connection')" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_document_observation": { + "name": "knowledge_document_observation", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "kdo_member_idx": { + "name": "kdo_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_document_observation_document_id_document_id_fk": { + "name": "knowledge_document_observation_document_id_document_id_fk", + "tableFrom": "knowledge_document_observation", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_document_observation_member_id_knowledge_connector_member_id_fk": { + "name": "knowledge_document_observation_member_id_knowledge_connector_member_id_fk", + "tableFrom": "knowledge_document_observation", + "tableTo": "knowledge_connector_member", + "columnsFrom": ["member_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "knowledge_document_observation_document_id_member_id_pk": { + "name": "knowledge_document_observation_document_id_member_id_pk", + "columns": ["document_id", "member_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_external_directory": { + "name": "knowledge_external_directory", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sync_lock_token": { + "name": "sync_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_lock_lease_at": { + "name": "sync_lock_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_started_at": { + "name": "last_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_complete_sync_at": { + "name": "last_complete_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "ked_workspace_identity_unique": { + "name": "ked_workspace_identity_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "ked_organization_identity_unique": { + "name": "ked_organization_identity_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_external_directory_workspace_id_workspace_id_fk": { + "name": "knowledge_external_directory_workspace_id_workspace_id_fk", + "tableFrom": "knowledge_external_directory", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "knowledge_external_directory_organization_id_organization_id_fk": { + "name": "knowledge_external_directory_organization_id_organization_id_fk", + "tableFrom": "knowledge_external_directory", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ked_owner_check": { + "name": "ked_owner_check", + "value": "num_nonnulls(\"knowledge_external_directory\".\"workspace_id\", \"knowledge_external_directory\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_external_group": { + "name": "knowledge_external_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_group_id": { + "name": "external_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "keg_organization_identity_unique": { + "name": "keg_organization_identity_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_organization_synced_idx": { + "name": "keg_organization_synced_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_synced_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_identity_unique": { + "name": "keg_identity_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "keg_workspace_synced_idx": { + "name": "keg_workspace_synced_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_synced_at", + "isExpression": false, + "asc": true, + "nulls": "first" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_external_group_organization_id_organization_id_fk": { + "name": "knowledge_external_group_organization_id_organization_id_fk", + "tableFrom": "knowledge_external_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "keg_workspace_fk": { + "name": "keg_workspace_fk", + "tableFrom": "knowledge_external_group", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "keg_owner_check": { + "name": "keg_owner_check", + "value": "num_nonnulls(\"knowledge_external_group\".\"workspace_id\", \"knowledge_external_group\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.knowledge_external_group_member": { + "name": "knowledge_external_group_member", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_token": { + "name": "subject_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "kegm_subject_token_idx": { + "name": "kegm_subject_token_idx", + "columns": [ + { + "expression": "subject_token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "kegm_group_fk": { + "name": "kegm_group_fk", + "tableFrom": "knowledge_external_group_member", + "tableTo": "knowledge_external_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "knowledge_external_group_member_group_id_subject_token_pk": { + "name": "knowledge_external_group_member_group_id_subject_token_pk", + "columns": ["group_id", "subject_token"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.knowledge_projection_dirty": { + "name": "knowledge_projection_dirty", + "schema": "", + "columns": { + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "content": { + "name": "content", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "marked_at": { + "name": "marked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "knowledge_projection_dirty_marked_at_idx": { + "name": "knowledge_projection_dirty_marked_at_idx", + "columns": [ + { + "expression": "marked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "knowledge_projection_dirty_document_id_document_id_fk": { + "name": "knowledge_projection_dirty_document_id_document_id_fk", + "tableFrom": "knowledge_projection_dirty", + "tableTo": "document", + "columnsFrom": ["document_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mcp_server_oauth": { + "name": "mcp_server_oauth", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "mcp_server_id": { + "name": "mcp_server_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_information": { + "name": "client_information", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tokens": { + "name": "tokens", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_verifier": { + "name": "code_verifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state_created_at": { + "name": "state_created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_refreshed_at": { + "name": "last_refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mcp_server_oauth_server_unique": { + "name": "mcp_server_oauth_server_unique", + "columns": [ + { + "expression": "mcp_server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_server_oauth_state_idx": { + "name": "mcp_server_oauth_state_idx", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mcp_server_oauth_mcp_server_id_mcp_servers_id_fk": { + "name": "mcp_server_oauth_mcp_server_id_mcp_servers_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "mcp_servers", + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_server_oauth_user_id_user_id_fk": { + "name": "mcp_server_oauth_user_id_user_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "mcp_server_oauth_workspace_id_workspace_id_fk": { + "name": "mcp_server_oauth_workspace_id_workspace_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_server_oauth_organization_id_organization_id_fk": { + "name": "mcp_server_oauth_organization_id_organization_id_fk", + "tableFrom": "mcp_server_oauth", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_server_oauth_owner_check": { + "name": "mcp_server_oauth_owner_check", + "value": "num_nonnulls(\"mcp_server_oauth\".\"workspace_id\", \"mcp_server_oauth\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.mcp_servers": { + "name": "mcp_servers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_group_id": { + "name": "credential_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "managed_connector_id": { + "name": "managed_connector_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config_version": { + "name": "oauth_config_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "transport": { + "name": "transport", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'headers'" + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_client_secret": { + "name": "oauth_client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "headers": { + "name": "headers", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "timeout": { + "name": "timeout", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 30000 + }, + "retries": { + "name": "retries", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 3 + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "last_connected": { + "name": "last_connected", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "connection_status": { + "name": "connection_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'disconnected'" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status_config": { + "name": "status_config", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "tool_count": { + "name": "tool_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_tools_refresh": { + "name": "last_tools_refresh", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_requests": { + "name": "total_requests", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mcp_servers_organization_id_idx": { + "name": "mcp_servers_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_workspace_enabled_idx": { + "name": "mcp_servers_workspace_enabled_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_credential_group_idx": { + "name": "mcp_servers_credential_group_idx", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_credential_group_managed_connector_unique": { + "name": "mcp_servers_credential_group_managed_connector_unique", + "columns": [ + { + "expression": "credential_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "managed_connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"mcp_servers\".\"credential_group_id\" IS NOT NULL AND \"mcp_servers\".\"managed_connector_id\" IS NOT NULL AND \"mcp_servers\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "mcp_servers_workspace_deleted_partial_idx": { + "name": "mcp_servers_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"mcp_servers\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mcp_servers_workspace_id_workspace_id_fk": { + "name": "mcp_servers_workspace_id_workspace_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_servers_organization_id_organization_id_fk": { + "name": "mcp_servers_organization_id_organization_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mcp_servers_credential_group_id_credential_group_id_fk": { + "name": "mcp_servers_credential_group_id_credential_group_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "credential_group", + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "mcp_servers_created_by_user_id_fk": { + "name": "mcp_servers_created_by_user_id_fk", + "tableFrom": "mcp_servers", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_servers_owner_check": { + "name": "mcp_servers_owner_check", + "value": "num_nonnulls(\"mcp_servers\".\"workspace_id\", \"mcp_servers\".\"organization_id\") = 1" + }, + "mcp_servers_organization_managed_check": { + "name": "mcp_servers_organization_managed_check", + "value": "\"mcp_servers\".\"organization_id\" IS NULL OR \"mcp_servers\".\"credential_group_id\" IS NOT NULL" + }, + "mcp_servers_credential_group_managed_connector_check": { + "name": "mcp_servers_credential_group_managed_connector_check", + "value": "\"mcp_servers\".\"credential_group_id\" IS NULL OR \"mcp_servers\".\"managed_connector_id\" IS NOT NULL" + }, + "mcp_servers_managed_connector_oauth_check": { + "name": "mcp_servers_managed_connector_oauth_check", + "value": "\"mcp_servers\".\"managed_connector_id\" IS NULL OR \"mcp_servers\".\"auth_type\" = 'oauth'" + } + }, + "isRLSEnabled": false + }, + "public.member": { + "name": "member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "member_user_id_unique": { + "name": "member_user_id_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_organization_id_idx": { + "name": "member_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "member_user_id_user_id_fk": { + "name": "member_user_id_user_id_fk", + "tableFrom": "member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_organization_id_organization_id_fk": { + "name": "member_organization_id_organization_id_fk", + "tableFrom": "member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.member_profile": { + "name": "member_profile", + "schema": "", + "columns": { + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "manager_member_id": { + "name": "manager_member_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "member_profile_manager_member_id_idx": { + "name": "member_profile_manager_member_id_idx", + "columns": [ + { + "expression": "manager_member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_profile_updated_by_idx": { + "name": "member_profile_updated_by_idx", + "columns": [ + { + "expression": "updated_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "member_profile_member_id_member_id_fk": { + "name": "member_profile_member_id_member_id_fk", + "tableFrom": "member_profile", + "tableTo": "member", + "columnsFrom": ["member_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_profile_manager_member_id_member_id_fk": { + "name": "member_profile_manager_member_id_member_id_fk", + "tableFrom": "member_profile", + "tableTo": "member", + "columnsFrom": ["manager_member_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "member_profile_updated_by_user_id_fk": { + "name": "member_profile_updated_by_user_id_fk", + "tableFrom": "member_profile", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "member_profile_not_own_manager": { + "name": "member_profile_not_own_manager", + "value": "\"member_profile\".\"manager_member_id\" <> \"member_profile\".\"member_id\"" + } + }, + "isRLSEnabled": false + }, + "public.memory": { + "name": "memory", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "storage_version": { + "name": "storage_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "encrypted_context_summary": { + "name": "encrypted_context_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "memory_key_idx": { + "name": "memory_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_workspace_key_idx": { + "name": "memory_workspace_key_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_workspace_deleted_partial_idx": { + "name": "memory_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"memory\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_workspace_id_workspace_id_fk": { + "name": "memory_workspace_id_workspace_id_fk", + "tableFrom": "memory", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_artifact": { + "name": "memory_artifact", + "schema": "", + "columns": { + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "memory_artifact_key_idx": { + "name": "memory_artifact_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_artifact_memory_id_memory_id_fk": { + "name": "memory_artifact_memory_id_memory_id_fk", + "tableFrom": "memory_artifact", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "memory_artifact_key_execution_large_values_key_fk": { + "name": "memory_artifact_key_execution_large_values_key_fk", + "tableFrom": "memory_artifact", + "tableTo": "execution_large_values", + "columnsFrom": ["key"], + "columnsTo": ["key"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "memory_artifact_memory_id_key_pk": { + "name": "memory_artifact_memory_id_key_pk", + "columns": ["memory_id", "key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_item": { + "name": "memory_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sequence": { + "name": "sequence", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "memory_item_sequence_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "append_key": { + "name": "append_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "turn_id": { + "name": "turn_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provenance_status": { + "name": "provenance_status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provenance_entries": { + "name": "provenance_entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "memory_item_append_unique": { + "name": "memory_item_append_unique", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "append_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "memory_item_sequence_idx": { + "name": "memory_item_sequence_idx", + "columns": [ + { + "expression": "memory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sequence", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memory_item_memory_id_memory_id_fk": { + "name": "memory_item_memory_id_memory_id_fk", + "tableFrom": "memory_item", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "memory_item_kind_check": { + "name": "memory_item_kind_check", + "value": "\"memory_item\".\"kind\" IN ('message', 'exchange')" + }, + "memory_item_provenance_status_check": { + "name": "memory_item_provenance_status_check", + "value": "\"memory_item\".\"provenance_status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.memory_secret_provenance": { + "name": "memory_secret_provenance", + "schema": "", + "columns": { + "memory_id": { + "name": "memory_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "memory_secret_provenance_memory_id_memory_id_fk": { + "name": "memory_secret_provenance_memory_id_memory_id_fk", + "tableFrom": "memory_secret_provenance", + "tableTo": "memory", + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "memory_secret_provenance_status_check": { + "name": "memory_secret_provenance_status_check", + "value": "\"memory_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.mothership_benchmark_runs": { + "name": "mothership_benchmark_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "benchmark_id": { + "name": "benchmark_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "evaluation_key": { + "name": "evaluation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reviews": { + "name": "reviews", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "correct": { + "name": "correct", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "automatic_correct": { + "name": "automatic_correct", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "total": { + "name": "total", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "artifacts": { + "name": "artifacts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_benchmark_runs_benchmark_created_idx": { + "name": "mothership_benchmark_runs_benchmark_created_idx", + "columns": [ + { + "expression": "benchmark_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_benchmark_runs_benchmark_id_mothership_benchmarks_id_fk": { + "name": "mothership_benchmark_runs_benchmark_id_mothership_benchmarks_id_fk", + "tableFrom": "mothership_benchmark_runs", + "tableTo": "mothership_benchmarks", + "columnsFrom": ["benchmark_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mothership_benchmark_runs_score_check": { + "name": "mothership_benchmark_runs_score_check", + "value": "\"mothership_benchmark_runs\".\"total\" > 0 AND \"mothership_benchmark_runs\".\"correct\" >= 0 AND \"mothership_benchmark_runs\".\"correct\" <= \"mothership_benchmark_runs\".\"total\"" + }, + "mothership_benchmark_runs_version_check": { + "name": "mothership_benchmark_runs_version_check", + "value": "\"mothership_benchmark_runs\".\"version\" > 0" + }, + "mothership_benchmark_runs_automatic_score_check": { + "name": "mothership_benchmark_runs_automatic_score_check", + "value": "\"mothership_benchmark_runs\".\"automatic_correct\" >= 0 AND \"mothership_benchmark_runs\".\"automatic_correct\" <= \"mothership_benchmark_runs\".\"total\"" + } + }, + "isRLSEnabled": false + }, + "public.mothership_benchmarks": { + "name": "mothership_benchmarks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_as_user_id": { + "name": "run_as_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "artifacts": { + "name": "artifacts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "running_stage": { + "name": "running_stage", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attempt_id": { + "name": "attempt_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "planner_chat_id": { + "name": "planner_chat_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_benchmarks_owner_created_idx": { + "name": "mothership_benchmarks_owner_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "mothership_benchmarks_workspace_idx": { + "name": "mothership_benchmarks_workspace_idx", + "columns": [ + { + "expression": "source_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_benchmarks_organization_id_organization_id_fk": { + "name": "mothership_benchmarks_organization_id_organization_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_user_id_user_id_fk": { + "name": "mothership_benchmarks_user_id_user_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_run_as_user_id_user_id_fk": { + "name": "mothership_benchmarks_run_as_user_id_user_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "user", + "columnsFrom": ["run_as_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_benchmarks_source_workspace_id_workspace_id_fk": { + "name": "mothership_benchmarks_source_workspace_id_workspace_id_fk", + "tableFrom": "mothership_benchmarks", + "tableTo": "workspace", + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mothership_benchmarks_version_check": { + "name": "mothership_benchmarks_version_check", + "value": "\"mothership_benchmarks\".\"version\" > 0" + }, + "mothership_benchmarks_attempt_check": { + "name": "mothership_benchmarks_attempt_check", + "value": "(\"mothership_benchmarks\".\"running_stage\" IS NULL AND \"mothership_benchmarks\".\"attempt_id\" IS NULL AND \"mothership_benchmarks\".\"lease_expires_at\" IS NULL) OR (\"mothership_benchmarks\".\"running_stage\" IS NOT NULL AND \"mothership_benchmarks\".\"running_stage\" IN ('distill', 'redact', 'plan', 'reconstruct', 'grade') AND \"mothership_benchmarks\".\"attempt_id\" IS NOT NULL AND \"mothership_benchmarks\".\"lease_expires_at\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.mothership_inbox_allowed_sender": { + "name": "mothership_inbox_allowed_sender", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "added_by": { + "name": "added_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "inbox_sender_ws_email_idx": { + "name": "inbox_sender_ws_email_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_inbox_allowed_sender_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_allowed_sender_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_allowed_sender", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_inbox_allowed_sender_added_by_user_id_fk": { + "name": "mothership_inbox_allowed_sender_added_by_user_id_fk", + "tableFrom": "mothership_inbox_allowed_sender", + "tableTo": "user", + "columnsFrom": ["added_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_inbox_task": { + "name": "mothership_inbox_task", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_email": { + "name": "from_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sender_authenticated": { + "name": "sender_authenticated", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "from_name": { + "name": "from_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body_preview": { + "name": "body_preview", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_text": { + "name": "body_text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_html": { + "name": "body_html", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_message_id": { + "name": "email_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "in_reply_to": { + "name": "in_reply_to", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "response_message_id": { + "name": "response_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agentmail_message_id": { + "name": "agentmail_message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'received'" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "trigger_job_id": { + "name": "trigger_job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "result_summary": { + "name": "result_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rejection_reason": { + "name": "rejection_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "has_attachments": { + "name": "has_attachments", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "cc_recipients": { + "name": "cc_recipients", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "processing_started_at": { + "name": "processing_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "inbox_task_ws_created_at_idx": { + "name": "inbox_task_ws_created_at_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_ws_status_idx": { + "name": "inbox_task_ws_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_response_msg_id_idx": { + "name": "inbox_task_response_msg_id_idx", + "columns": [ + { + "expression": "response_message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "inbox_task_email_msg_id_idx": { + "name": "inbox_task_email_msg_id_idx", + "columns": [ + { + "expression": "email_message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_inbox_task_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_task_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_task", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_inbox_task_chat_id_copilot_chats_id_fk": { + "name": "mothership_inbox_task_chat_id_copilot_chats_id_fk", + "tableFrom": "mothership_inbox_task", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_inbox_webhook": { + "name": "mothership_inbox_webhook", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "webhook_id": { + "name": "webhook_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_inbox_webhook_workspace_id_workspace_id_fk": { + "name": "mothership_inbox_webhook_workspace_id_workspace_id_fk", + "tableFrom": "mothership_inbox_webhook", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "mothership_inbox_webhook_workspace_id_unique": { + "name": "mothership_inbox_webhook_workspace_id_unique", + "nullsNotDistinct": false, + "columns": ["workspace_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_memory_selections": { + "name": "mothership_memory_selections", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "space_id": { + "name": "space_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_memory_selections_user_id_user_id_fk": { + "name": "mothership_memory_selections_user_id_user_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_selections_organization_id_organization_id_fk": { + "name": "mothership_memory_selections_organization_id_organization_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_selections_space_id_mothership_memory_spaces_id_fk": { + "name": "mothership_memory_selections_space_id_mothership_memory_spaces_id_fk", + "tableFrom": "mothership_memory_selections", + "tableTo": "mothership_memory_spaces", + "columnsFrom": ["space_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "mothership_memory_selections_user_id_organization_id_pk": { + "name": "mothership_memory_selections_user_id_organization_id_pk", + "columns": ["user_id", "organization_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_memory_spaces": { + "name": "mothership_memory_spaces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "mothership_memory_spaces_owner_idx": { + "name": "mothership_memory_spaces_owner_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "mothership_memory_spaces_user_id_user_id_fk": { + "name": "mothership_memory_spaces_user_id_user_id_fk", + "tableFrom": "mothership_memory_spaces", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "mothership_memory_spaces_organization_id_organization_id_fk": { + "name": "mothership_memory_spaces_organization_id_organization_id_fk", + "tableFrom": "mothership_memory_spaces", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mothership_resource_effects": { + "name": "mothership_resource_effects", + "schema": "", + "columns": { + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "effect_id": { + "name": "effect_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "mothership_resource_effects_chat_id_copilot_chats_id_fk": { + "name": "mothership_resource_effects_chat_id_copilot_chats_id_fk", + "tableFrom": "mothership_resource_effects", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "mothership_resource_effects_chat_id_effect_id_pk": { + "name": "mothership_resource_effects_chat_id_effect_id_pk", + "columns": ["chat_id", "effect_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_access_token": { + "name": "oauth_access_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_id": { + "name": "refresh_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "oauth_access_token_client_id_idx": { + "name": "oauth_access_token_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_session_id_idx": { + "name": "oauth_access_token_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_refresh_id_idx": { + "name": "oauth_access_token_refresh_id_idx", + "columns": [ + { + "expression": "refresh_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_user_client_idx": { + "name": "oauth_access_token_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_access_token_expires_at_idx": { + "name": "oauth_access_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_access_token_client_id_oauth_client_client_id_fk": { + "name": "oauth_access_token_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_token_session_id_session_id_fk": { + "name": "oauth_access_token_session_id_session_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_access_token_user_id_user_id_fk": { + "name": "oauth_access_token_user_id_user_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_token_refresh_id_oauth_refresh_token_id_fk": { + "name": "oauth_access_token_refresh_id_oauth_refresh_token_id_fk", + "tableFrom": "oauth_access_token", + "tableTo": "oauth_refresh_token", + "columnsFrom": ["refresh_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_access_token_token_unique": { + "name": "oauth_access_token_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": { + "oauth_access_token_search_resource_check": { + "name": "oauth_access_token_search_resource_check", + "value": "NOT ('search:read' = ANY(\"oauth_access_token\".\"scopes\")) OR \"oauth_access_token\".\"resource\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.oauth_client": { + "name": "oauth_client", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_secret": { + "name": "client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "disabled": { + "name": "disabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "skip_consent": { + "name": "skip_consent", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "enable_end_session": { + "name": "enable_end_session", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "subject_type": { + "name": "subject_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "uri": { + "name": "uri", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "contacts": { + "name": "contacts", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "tos": { + "name": "tos", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_id": { + "name": "software_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_version": { + "name": "software_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_statement": { + "name": "software_statement", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "post_logout_redirect_uris": { + "name": "post_logout_redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "token_endpoint_auth_method": { + "name": "token_endpoint_auth_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "grant_types": { + "name": "grant_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "response_types": { + "name": "response_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "require_pkce": { + "name": "require_pkce", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "oauth_client_user_id_idx": { + "name": "oauth_client_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_client_user_id_user_id_fk": { + "name": "oauth_client_user_id_user_id_fk", + "tableFrom": "oauth_client", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_client_client_id_unique": { + "name": "oauth_client_client_id_unique", + "nullsNotDistinct": false, + "columns": ["client_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_consent": { + "name": "oauth_consent", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_consent_client_id_idx": { + "name": "oauth_consent_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_consent_client_id_oauth_client_client_id_fk": { + "name": "oauth_consent_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_consent", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_consent_user_id_user_id_fk": { + "name": "oauth_consent_user_id_user_id_fk", + "tableFrom": "oauth_consent", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_consent_user_client_reference_unique": { + "name": "oauth_consent_user_client_reference_unique", + "nullsNotDistinct": true, + "columns": ["user_id", "client_id", "reference_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_refresh_token": { + "name": "oauth_refresh_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "revoked": { + "name": "revoked", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "auth_time": { + "name": "auth_time", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "family_id": { + "name": "family_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_refresh_token_client_id_idx": { + "name": "oauth_refresh_token_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_session_id_idx": { + "name": "oauth_refresh_token_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_user_client_idx": { + "name": "oauth_refresh_token_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_refresh_token_expires_at_idx": { + "name": "oauth_refresh_token_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_refresh_token_client_id_oauth_client_client_id_fk": { + "name": "oauth_refresh_token_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_refresh_token_session_id_session_id_fk": { + "name": "oauth_refresh_token_session_id_session_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_refresh_token_user_id_user_id_fk": { + "name": "oauth_refresh_token_user_id_user_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_refresh_token_family_id_oauth_token_family_id_fk": { + "name": "oauth_refresh_token_family_id_oauth_token_family_id_fk", + "tableFrom": "oauth_refresh_token", + "tableTo": "oauth_token_family", + "columnsFrom": ["family_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_refresh_token_token_unique": { + "name": "oauth_refresh_token_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + }, + "oauth_refresh_token_family_generation_unique": { + "name": "oauth_refresh_token_family_generation_unique", + "nullsNotDistinct": false, + "columns": ["family_id", "generation"] + } + }, + "policies": {}, + "checkConstraints": { + "oauth_refresh_token_generation_check": { + "name": "oauth_refresh_token_generation_check", + "value": "\"oauth_refresh_token\".\"generation\" BETWEEN 0 AND 1000" + }, + "oauth_refresh_token_search_resource_check": { + "name": "oauth_refresh_token_search_resource_check", + "value": "NOT ('search:read' = ANY(\"oauth_refresh_token\".\"scopes\")) OR \"oauth_refresh_token\".\"resource\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.oauth_token_family": { + "name": "oauth_token_family", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "consent_id": { + "name": "consent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "current_generation": { + "name": "current_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "oauth_token_family_client_id_idx": { + "name": "oauth_token_family_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_session_id_idx": { + "name": "oauth_token_family_session_id_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_user_client_idx": { + "name": "oauth_token_family_user_client_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_consent_id_idx": { + "name": "oauth_token_family_consent_id_idx", + "columns": [ + { + "expression": "consent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "oauth_token_family_expires_at_idx": { + "name": "oauth_token_family_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "oauth_token_family_client_id_oauth_client_client_id_fk": { + "name": "oauth_token_family_client_id_oauth_client_client_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "oauth_client", + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_token_family_session_id_session_id_fk": { + "name": "oauth_token_family_session_id_session_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "session", + "columnsFrom": ["session_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_token_family_user_id_user_id_fk": { + "name": "oauth_token_family_user_id_user_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_token_family_consent_id_oauth_consent_id_fk": { + "name": "oauth_token_family_consent_id_oauth_consent_id_fk", + "tableFrom": "oauth_token_family", + "tableTo": "oauth_consent", + "columnsFrom": ["consent_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "oauth_token_family_generation_check": { + "name": "oauth_token_family_generation_check", + "value": "\"oauth_token_family\".\"current_generation\" BETWEEN 0 AND 1000" + } + }, + "isRLSEnabled": false + }, + "public.organization": { + "name": "organization", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "session_policy_settings": { + "name": "session_policy_settings", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "security_policy_version": { + "name": "security_policy_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "require_sso": { + "name": "require_sso", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "data_retention_settings": { + "name": "data_retention_settings", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "org_usage_limit": { + "name": "org_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "self_serve_usage_limit": { + "name": "self_serve_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit_notifications": { + "name": "limit_notifications", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "credit_balance": { + "name": "credit_balance", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_access_request_settings": { + "name": "organization_access_request_settings", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "allow_requests": { + "name": "allow_requests", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "organization_access_request_settings_organization_id_organization_id_fk": { + "name": "organization_access_request_settings_organization_id_organization_id_fk", + "tableFrom": "organization_access_request_settings", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_access_request_settings_updated_by_user_id_fk": { + "name": "organization_access_request_settings_updated_by_user_id_fk", + "tableFrom": "organization_access_request_settings", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_byok_keys": { + "name": "organization_byok_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_byok_organization_provider_idx": { + "name": "organization_byok_organization_provider_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_byok_keys_organization_id_organization_id_fk": { + "name": "organization_byok_keys_organization_id_organization_id_fk", + "tableFrom": "organization_byok_keys", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_byok_keys_created_by_user_id_fk": { + "name": "organization_byok_keys_created_by_user_id_fk", + "tableFrom": "organization_byok_keys", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_member_activity_daily": { + "name": "organization_member_activity_daily", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_count": { + "name": "event_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "first_at": { + "name": "first_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_at": { + "name": "last_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "organization_member_activity_daily_day_idx": { + "name": "organization_member_activity_daily_day_idx", + "columns": [ + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_member_activity_daily_user_idx": { + "name": "organization_member_activity_daily_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_member_activity_daily_organization_id_organization_id_fk": { + "name": "organization_member_activity_daily_organization_id_organization_id_fk", + "tableFrom": "organization_member_activity_daily", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_activity_daily_user_id_user_id_fk": { + "name": "organization_member_activity_daily_user_id_user_id_fk", + "tableFrom": "organization_member_activity_daily", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_member_activity_daily_pk": { + "name": "organization_member_activity_daily_pk", + "columns": ["organization_id", "day", "surface", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_member_activity_daily_surface_check": { + "name": "organization_member_activity_daily_surface_check", + "value": "\"organization_member_activity_daily\".\"surface\" IN ('assistant', 'agent', 'search', 'search_mcp', 'slack', 'workflows')" + }, + "organization_member_activity_daily_count_check": { + "name": "organization_member_activity_daily_count_check", + "value": "\"organization_member_activity_daily\".\"event_count\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.organization_member_usage_limit": { + "name": "organization_member_usage_limit", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "usage_limit": { + "name": "usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "set_by": { + "name": "set_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "org_member_usage_limit_org_user_unique": { + "name": "org_member_usage_limit_org_user_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "org_member_usage_limit_organization_id_idx": { + "name": "org_member_usage_limit_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_member_usage_limit_organization_id_organization_id_fk": { + "name": "organization_member_usage_limit_organization_id_organization_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_usage_limit_user_id_user_id_fk": { + "name": "organization_member_usage_limit_user_id_user_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_member_usage_limit_set_by_user_id_fk": { + "name": "organization_member_usage_limit_set_by_user_id_fk", + "tableFrom": "organization_member_usage_limit", + "tableTo": "user", + "columnsFrom": ["set_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_history": { + "name": "organization_search_history", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sources": { + "name": "sources", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "queries": { + "name": "queries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": { + "organization_search_history_user_idx": { + "name": "organization_search_history_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_search_history_organization_id_organization_id_fk": { + "name": "organization_search_history_organization_id_organization_id_fk", + "tableFrom": "organization_search_history", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_search_history_user_id_user_id_fk": { + "name": "organization_search_history_user_id_user_id_fk", + "tableFrom": "organization_search_history", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_history_organization_id_user_id_pk": { + "name": "organization_search_history_organization_id_user_id_pk", + "columns": ["organization_id", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_integration": { + "name": "organization_search_integration", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "approved": { + "name": "approved", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "organization_search_integration_organization_id_organization_id_fk": { + "name": "organization_search_integration_organization_id_organization_id_fk", + "tableFrom": "organization_search_integration", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_integration_organization_id_connector_type_pk": { + "name": "organization_search_integration_organization_id_connector_type_pk", + "columns": ["organization_id", "connector_type"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_search_integration_daily": { + "name": "organization_search_integration_daily", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connector_type": { + "name": "connector_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "searches_ok": { + "name": "searches_ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_partial": { + "name": "searches_partial", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_reconnect": { + "name": "searches_reconnect", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_rate_limited": { + "name": "searches_rate_limited", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_unavailable": { + "name": "searches_unavailable", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "searches_timeout": { + "name": "searches_timeout", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "opens": { + "name": "opens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "organization_search_integration_daily_day_idx": { + "name": "organization_search_integration_daily_day_idx", + "columns": [ + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_integration_daily_user_idx": { + "name": "organization_search_integration_daily_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_search_integration_daily_organization_id_organization_id_fk": { + "name": "organization_search_integration_daily_organization_id_organization_id_fk", + "tableFrom": "organization_search_integration_daily", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_search_integration_daily_user_id_user_id_fk": { + "name": "organization_search_integration_daily_user_id_user_id_fk", + "tableFrom": "organization_search_integration_daily", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "organization_search_integration_daily_pk": { + "name": "organization_search_integration_daily_pk", + "columns": ["organization_id", "day", "surface", "connector_type", "user_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_search_integration_daily_surface_check": { + "name": "organization_search_integration_daily_surface_check", + "value": "\"organization_search_integration_daily\".\"surface\" IN ('assistant', 'agent', 'search', 'search_mcp', 'slack', 'workflows')" + }, + "organization_search_integration_daily_connector_type_check": { + "name": "organization_search_integration_daily_connector_type_check", + "value": "\"organization_search_integration_daily\".\"connector_type\" ~ '^[a-z][a-z0-9_]{0,63}$'" + }, + "organization_search_integration_daily_counts_check": { + "name": "organization_search_integration_daily_counts_check", + "value": "LEAST(\"organization_search_integration_daily\".\"searches_ok\", \"organization_search_integration_daily\".\"searches_partial\", \"organization_search_integration_daily\".\"searches_reconnect\", \"organization_search_integration_daily\".\"searches_rate_limited\", \"organization_search_integration_daily\".\"searches_unavailable\", \"organization_search_integration_daily\".\"searches_timeout\", \"organization_search_integration_daily\".\"opens\") >= 0" + }, + "organization_search_integration_daily_total_check": { + "name": "organization_search_integration_daily_total_check", + "value": "\"organization_search_integration_daily\".\"searches_ok\" + \"organization_search_integration_daily\".\"searches_partial\" + \"organization_search_integration_daily\".\"searches_reconnect\" + \"organization_search_integration_daily\".\"searches_rate_limited\" + \"organization_search_integration_daily\".\"searches_unavailable\" + \"organization_search_integration_daily\".\"searches_timeout\" + \"organization_search_integration_daily\".\"opens\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.organization_search_mcp_invocation": { + "name": "organization_search_mcp_invocation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_name": { + "name": "client_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_search_mcp_invocation_org_created_idx": { + "name": "organization_search_mcp_invocation_org_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_mcp_invocation_user_idx": { + "name": "organization_search_mcp_invocation_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_search_mcp_invocation_created_idx": { + "name": "organization_search_mcp_invocation_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "org_search_mcp_invocation_org_fk": { + "name": "org_search_mcp_invocation_org_fk", + "tableFrom": "organization_search_mcp_invocation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "org_search_mcp_invocation_user_fk": { + "name": "org_search_mcp_invocation_user_fk", + "tableFrom": "organization_search_mcp_invocation", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_search_mcp_invocation_tool_check": { + "name": "organization_search_mcp_invocation_tool_check", + "value": "\"organization_search_mcp_invocation\".\"tool_name\" IN ('search', 'read_document', 'chat', 'search_people', 'search_experts', 'list_my_activity', 'list_my_chat_history')" + }, + "organization_search_mcp_invocation_outcome_check": { + "name": "organization_search_mcp_invocation_outcome_check", + "value": "\"organization_search_mcp_invocation\".\"outcome\" IN ('success', 'error', 'cancelled', 'rate_limited')" + }, + "organization_search_mcp_invocation_duration_check": { + "name": "organization_search_mcp_invocation_duration_check", + "value": "\"organization_search_mcp_invocation\".\"duration_ms\" >= 0" + }, + "organization_search_mcp_invocation_client_name_check": { + "name": "organization_search_mcp_invocation_client_name_check", + "value": "length(\"organization_search_mcp_invocation\".\"client_name\") <= 256" + }, + "organization_search_mcp_invocation_auth_check": { + "name": "organization_search_mcp_invocation_auth_check", + "value": "(\"organization_search_mcp_invocation\".\"auth_kind\" = 'oauth_access_token' AND \"organization_search_mcp_invocation\".\"oauth_client_id\" IS NOT NULL)\n OR (\"organization_search_mcp_invocation\".\"auth_kind\" IN ('personal_api_key', 'workspace_api_key') AND \"organization_search_mcp_invocation\".\"oauth_client_id\" IS NULL AND \"organization_search_mcp_invocation\".\"client_name\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.organization_secret": { + "name": "organization_secret", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_value": { + "name": "encrypted_value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_secret_shared_unique": { + "name": "organization_secret_shared_unique", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organization_secret\".\"owner_user_id\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_secret_member_unique": { + "name": "organization_secret_member_unique", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"organization_secret\".\"owner_user_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_secret_owner_idx": { + "name": "organization_secret_owner_idx", + "columns": [ + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_secret_source_id_organization_secret_source_id_fk": { + "name": "organization_secret_source_id_organization_secret_source_id_fk", + "tableFrom": "organization_secret", + "tableTo": "organization_secret_source", + "columnsFrom": ["source_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "organization_secret_owner_user_id_user_id_fk": { + "name": "organization_secret_owner_user_id_user_id_fk", + "tableFrom": "organization_secret", + "tableTo": "user", + "columnsFrom": ["owner_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_secret_source": { + "name": "organization_secret_source", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_secret_source_org_unique": { + "name": "organization_secret_source_org_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_secret_source_organization_id_organization_id_fk": { + "name": "organization_secret_source_organization_id_organization_id_fk", + "tableFrom": "organization_secret_source", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_secret_source_mode_check": { + "name": "organization_secret_source_mode_check", + "value": "\"organization_secret_source\".\"mode\" IN ('organization', 'member')" + } + }, + "isRLSEnabled": false + }, + "public.outbox_event": { + "name": "outbox_event", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "max_attempts": { + "name": "max_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "available_at": { + "name": "available_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "locked_at": { + "name": "locked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "outbox_event_status_available_idx": { + "name": "outbox_event_status_available_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_pending_type_available_idx": { + "name": "outbox_event_pending_type_available_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"outbox_event\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_locked_at_idx": { + "name": "outbox_event_locked_at_idx", + "columns": [ + { + "expression": "locked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "outbox_event_type_created_idx": { + "name": "outbox_event_type_created_idx", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.paused_executions": { + "name": "paused_executions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_snapshot": { + "name": "execution_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "pause_points": { + "name": "pause_points", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "total_pause_count": { + "name": "total_pause_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "resumed_count": { + "name": "resumed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "automatic_resume_retry_count": { + "name": "automatic_resume_retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'paused'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "paused_at": { + "name": "paused_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "next_resume_at": { + "name": "next_resume_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "paused_executions_workflow_id_idx": { + "name": "paused_executions_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_status_idx": { + "name": "paused_executions_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_execution_id_unique": { + "name": "paused_executions_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "paused_executions_next_resume_at_idx": { + "name": "paused_executions_next_resume_at_idx", + "columns": [ + { + "expression": "next_resume_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'paused' AND next_resume_at IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "paused_executions_workflow_id_workflow_id_fk": { + "name": "paused_executions_workflow_id_workflow_id_fk", + "tableFrom": "paused_executions", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pending_credential_draft": { + "name": "pending_credential_draft", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oauth_config": { + "name": "oauth_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "pending_draft_organization_id_idx": { + "name": "pending_draft_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pending_draft_user_provider_org": { + "name": "pending_draft_user_provider_org", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pending_draft_user_provider_ws": { + "name": "pending_draft_user_provider_ws", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "pending_credential_draft_user_id_user_id_fk": { + "name": "pending_credential_draft_user_id_user_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_workspace_id_workspace_id_fk": { + "name": "pending_credential_draft_workspace_id_workspace_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_organization_id_organization_id_fk": { + "name": "pending_credential_draft_organization_id_organization_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pending_credential_draft_credential_id_credential_id_fk": { + "name": "pending_credential_draft_credential_id_credential_id_fk", + "tableFrom": "pending_credential_draft", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "pending_draft_owner_check": { + "name": "pending_draft_owner_check", + "value": "num_nonnulls(\"pending_credential_draft\".\"workspace_id\", \"pending_credential_draft\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.people_directory_entry": { + "name": "people_directory_entry", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manager_external_id": { + "name": "manager_external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "people_directory_entry_source_id_idx": { + "name": "people_directory_entry_source_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_entry_email_idx": { + "name": "people_directory_entry_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_entry_manager_idx": { + "name": "people_directory_entry_manager_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "manager_external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_entry_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_entry_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_entry", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_issue": { + "name": "people_directory_issue", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fields": { + "name": "fields", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "resolution": { + "name": "resolution", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference": { + "name": "reference", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kept_previous": { + "name": "kept_previous", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "since": { + "name": "since", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "people_directory_issue_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_issue_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_issue", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_issue_organization_id_external_id_kind_pk": { + "name": "people_directory_issue_organization_id_external_id_kind_pk", + "columns": ["organization_id", "external_id", "kind"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_page": { + "name": "people_directory_page", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "page_hash": { + "name": "page_hash", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "people_directory_page_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_page_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_page", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_page_organization_id_run_id_page_hash_pk": { + "name": "people_directory_page_organization_id_run_id_page_hash_pk", + "columns": ["organization_id", "run_id", "page_hash"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_scim_change": { + "name": "people_directory_scim_change", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "changed_at": { + "name": "changed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "people_directory_scim_change_due_idx": { + "name": "people_directory_scim_change_due_idx", + "columns": [ + { + "expression": "changed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_scim_change_organization_id_organization_id_fk": { + "name": "people_directory_scim_change_organization_id_organization_id_fk", + "tableFrom": "people_directory_scim_change", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_directory_stage": { + "name": "people_directory_stage", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "proposed_id": { + "name": "proposed_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "employee_number": { + "name": "employee_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue": { + "name": "issue", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue_fields": { + "name": "issue_fields", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "department": { + "name": "department", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manager_external_id": { + "name": "manager_external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reports_cursor": { + "name": "reports_cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reports_complete": { + "name": "reports_complete", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "people_directory_stage_run_email_idx": { + "name": "people_directory_stage_run_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_directory_stage_pending_idx": { + "name": "people_directory_stage_pending_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "NOT \"people_directory_stage\".\"reports_complete\"", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_stage_organization_id_people_directory_sync_organization_id_fk": { + "name": "people_directory_stage_organization_id_people_directory_sync_organization_id_fk", + "tableFrom": "people_directory_stage", + "tableTo": "people_directory_sync", + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_directory_stage_organization_id_run_id_external_id_pk": { + "name": "people_directory_stage_organization_id_run_id_external_id_pk", + "columns": ["organization_id", "run_id", "external_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "people_directory_stage_email_check": { + "name": "people_directory_stage_email_check", + "value": "\"people_directory_stage\".\"email\" IS NOT NULL OR \"people_directory_stage\".\"issue\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.people_directory_sync": { + "name": "people_directory_sync", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_target": { + "name": "source_target", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_credential": { + "name": "encrypted_credential", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "configured_by": { + "name": "configured_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_token": { + "name": "lease_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "run_started_at": { + "name": "run_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cursor": { + "name": "cursor", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "users_read": { + "name": "users_read", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "unmatched_managers": { + "name": "unmatched_managers", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "retry_count": { + "name": "retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_sync_at": { + "name": "next_sync_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_attempt_at": { + "name": "last_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_success_at": { + "name": "last_success_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_directory_sync_due_idx": { + "name": "people_directory_sync_due_idx", + "columns": [ + { + "expression": "next_sync_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_directory_sync_organization_id_organization_id_fk": { + "name": "people_directory_sync_organization_id_organization_id_fk", + "tableFrom": "people_directory_sync", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "people_directory_sync_configured_by_user_id_fk": { + "name": "people_directory_sync_configured_by_user_id_fk", + "tableFrom": "people_directory_sync", + "tableTo": "user", + "columnsFrom": ["configured_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_slack_identity": { + "name": "people_slack_identity", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_team_id": { + "name": "slack_team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_user_id": { + "name": "slack_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_slack_identity_email_idx": { + "name": "people_slack_identity_email_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_slack_identity_organization_id_organization_id_fk": { + "name": "people_slack_identity_organization_id_organization_id_fk", + "tableFrom": "people_slack_identity", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "people_slack_identity_organization_id_slack_team_id_email_pk": { + "name": "people_slack_identity_organization_id_slack_team_id_email_pk", + "columns": ["organization_id", "slack_team_id", "email"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_slack_sync": { + "name": "people_slack_sync", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "next_refresh_at": { + "name": "next_refresh_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "lease_token": { + "name": "lease_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refreshed_at": { + "name": "refreshed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_slack_sync_due_idx": { + "name": "people_slack_sync_due_idx", + "columns": [ + { + "expression": "next_refresh_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_slack_sync_organization_id_organization_id_fk": { + "name": "people_slack_sync_organization_id_organization_id_fk", + "tableFrom": "people_slack_sync", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_access_request": { + "name": "permission_access_request", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requester_id": { + "name": "requester_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope_key": { + "name": "scope_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_key": { + "name": "target_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target": { + "name": "target", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "target_label": { + "name": "target_label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "membership_id": { + "name": "membership_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "group_name": { + "name": "group_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decision": { + "name": "decision", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "decided_at": { + "name": "decided_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "permission_access_request_pending_unique": { + "name": "permission_access_request_pending_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requester_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"permission_access_request\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_access_request_org_queue_idx": { + "name": "permission_access_request_org_queue_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_access_request_requester_idx": { + "name": "permission_access_request_requester_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requester_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_access_request_organization_id_organization_id_fk": { + "name": "permission_access_request_organization_id_organization_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_access_request_requester_id_user_id_fk": { + "name": "permission_access_request_requester_id_user_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "user", + "columnsFrom": ["requester_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_access_request_decided_by_user_id_fk": { + "name": "permission_access_request_decided_by_user_id_fk", + "tableFrom": "permission_access_request", + "tableTo": "user", + "columnsFrom": ["decided_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "permission_access_request_status_check": { + "name": "permission_access_request_status_check", + "value": "\"permission_access_request\".\"status\" in ('pending', 'fulfilled', 'declined', 'cancelled', 'closed')" + } + }, + "isRLSEnabled": false + }, + "public.permission_group": { + "name": "permission_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "membership_mode": { + "name": "membership_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'inherit'" + } + }, + "indexes": { + "permission_group_created_by_idx": { + "name": "permission_group_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_organization_name_unique": { + "name": "permission_group_organization_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_organization_default_unique": { + "name": "permission_group_organization_default_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "is_default = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_organization_id_organization_id_fk": { + "name": "permission_group_organization_id_organization_id_fk", + "tableFrom": "permission_group", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_created_by_user_id_fk": { + "name": "permission_group_created_by_user_id_fk", + "tableFrom": "permission_group", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_group_member": { + "name": "permission_group_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permission_group_member_group_user_unique": { + "name": "permission_group_member_group_user_unique", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_member_organization_user_idx": { + "name": "permission_group_member_organization_user_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_member_permission_group_id_permission_group_id_fk": { + "name": "permission_group_member_permission_group_id_permission_group_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_organization_id_organization_id_fk": { + "name": "permission_group_member_organization_id_organization_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_user_id_user_id_fk": { + "name": "permission_group_member_user_id_user_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_member_assigned_by_user_id_fk": { + "name": "permission_group_member_assigned_by_user_id_fk", + "tableFrom": "permission_group_member", + "tableTo": "user", + "columnsFrom": ["assigned_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_group_workspace": { + "name": "permission_group_workspace", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permission_group_workspace_workspace_id_idx": { + "name": "permission_group_workspace_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permission_group_workspace_group_workspace_unique": { + "name": "permission_group_workspace_group_workspace_unique", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_group_workspace_permission_group_id_permission_group_id_fk": { + "name": "permission_group_workspace_permission_group_id_permission_group_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_workspace_workspace_id_workspace_id_fk": { + "name": "permission_group_workspace_workspace_id_workspace_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_group_workspace_organization_id_organization_id_fk": { + "name": "permission_group_workspace_organization_id_organization_id_fk", + "tableFrom": "permission_group_workspace", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permissions": { + "name": "permissions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permissions_entity_idx": { + "name": "permissions_entity_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permissions_user_entity_permission_idx": { + "name": "permissions_user_entity_permission_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "permission_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "permissions_unique_constraint": { + "name": "permissions_unique_constraint", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permissions_user_id_user_id_fk": { + "name": "permissions_user_id_user_id_fk", + "tableFrom": "permissions", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pinned_item": { + "name": "pinned_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pinned_at": { + "name": "pinned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "pinned_item_user_workspace_idx": { + "name": "pinned_item_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pinned_item_resource_idx": { + "name": "pinned_item_resource_idx", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pinned_item_user_resource_unique": { + "name": "pinned_item_user_resource_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "pinned_item_user_id_user_id_fk": { + "name": "pinned_item_user_id_user_id_fk", + "tableFrom": "pinned_item", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pinned_item_workspace_id_workspace_id_fk": { + "name": "pinned_item_workspace_id_workspace_id_fk", + "tableFrom": "pinned_item", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project": { + "name": "project", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_scope_key": { + "name": "organization_scope_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END", + "type": "stored" + } + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "project_organization_archive_id_idx": { + "name": "project_organization_archive_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "project_owner_archive_id_idx": { + "name": "project_owner_archive_id_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "project_organization_id_organization_id_fk": { + "name": "project_organization_id_organization_id_fk", + "tableFrom": "project", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "project_owner_id_user_id_fk": { + "name": "project_owner_id_user_id_fk", + "tableFrom": "project", + "tableTo": "user", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "project_id_organization_scope_unique": { + "name": "project_id_organization_scope_unique", + "nullsNotDistinct": false, + "columns": ["id", "organization_scope_key"] + } + }, + "policies": {}, + "checkConstraints": { + "project_name_length": { + "name": "project_name_length", + "value": "char_length(btrim(\"project\".\"name\")) BETWEEN 1 AND 100" + } + }, + "isRLSEnabled": false + }, + "public.public_share": { + "name": "public_share", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_emails": { + "name": "allowed_emails", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "public_share_entity_id_idx": { + "name": "public_share_entity_id_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_token_unique": { + "name": "public_share_token_unique", + "columns": [ + { + "expression": "token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_resource_unique": { + "name": "public_share_resource_unique", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_resource_id_idx": { + "name": "public_share_resource_id_idx", + "columns": [ + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "public_share_workspace_id_idx": { + "name": "public_share_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "public_share_workspace_id_workspace_id_fk": { + "name": "public_share_workspace_id_workspace_id_fk", + "tableFrom": "public_share", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "public_share_created_by_user_id_fk": { + "name": "public_share_created_by_user_id_fk", + "tableFrom": "public_share", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "public_share_entity_binding_check": { + "name": "public_share_entity_binding_check", + "value": "\n (\"public_share\".\"entity_type\" IS NULL AND \"public_share\".\"entity_id\" IS NULL AND \"public_share\".\"workspace_id\" IS NOT NULL)\n OR (\"public_share\".\"entity_type\" IS NOT NULL AND \"public_share\".\"entity_id\" IS NOT NULL AND char_length(\"public_share\".\"entity_id\") > 0\n AND ((\"public_share\".\"entity_type\" = 'workspace' AND \"public_share\".\"workspace_id\" IS NOT NULL AND \"public_share\".\"entity_id\" = \"public_share\".\"workspace_id\")\n OR (\"public_share\".\"entity_type\" = 'project' AND \"public_share\".\"workspace_id\" IS NULL AND \"public_share\".\"resource_type\" = 'file')))\n " + } + }, + "isRLSEnabled": false + }, + "public.resource_policy": { + "name": "resource_policy", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "document": { + "name": "document", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "resource_policy_organization_id_idx": { + "name": "resource_policy_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resource_policy_resource_unique": { + "name": "resource_policy_resource_unique", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resource_policy_workspace_id_idx": { + "name": "resource_policy_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resource_policy_workspace_id_workspace_id_fk": { + "name": "resource_policy_workspace_id_workspace_id_fk", + "tableFrom": "resource_policy", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "resource_policy_organization_id_organization_id_fk": { + "name": "resource_policy_organization_id_organization_id_fk", + "tableFrom": "resource_policy", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "resource_policy_created_by_user_id_fk": { + "name": "resource_policy_created_by_user_id_fk", + "tableFrom": "resource_policy", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "resource_policy_updated_by_user_id_fk": { + "name": "resource_policy_updated_by_user_id_fk", + "tableFrom": "resource_policy", + "tableTo": "user", + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "resource_policy_owner_check": { + "name": "resource_policy_owner_check", + "value": "num_nonnulls(\"resource_policy\".\"workspace_id\", \"resource_policy\".\"organization_id\") = 1" + } + }, + "isRLSEnabled": false + }, + "public.resume_queue": { + "name": "resume_queue", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "paused_execution_id": { + "name": "paused_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_execution_id": { + "name": "parent_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "new_execution_id": { + "name": "new_execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context_id": { + "name": "context_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resume_input": { + "name": "resume_input", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "queued_at": { + "name": "queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "resume_queue_parent_status_idx": { + "name": "resume_queue_parent_status_idx", + "columns": [ + { + "expression": "parent_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "resume_queue_new_execution_idx": { + "name": "resume_queue_new_execution_idx", + "columns": [ + { + "expression": "new_execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "resume_queue_paused_execution_id_paused_executions_id_fk": { + "name": "resume_queue_paused_execution_id_paused_executions_id_fk", + "tableFrom": "resume_queue", + "tableTo": "paused_executions", + "columnsFrom": ["paused_execution_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sandbox_image": { + "name": "sandbox_image", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "spec_hash": { + "name": "spec_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "spec": { + "name": "spec", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "sandbox_image_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "image_ref": { + "name": "image_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_image_id": { + "name": "provider_image_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "materialization_generation": { + "name": "materialization_generation", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_detail": { + "name": "error_detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sandbox_image_provider_spec_unique": { + "name": "sandbox_image_provider_spec_unique", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "spec_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sandbox_image_status_idx": { + "name": "sandbox_image_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sandbox_image_last_used_idx": { + "name": "sandbox_image_last_used_idx", + "columns": [ + { + "expression": "last_used_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_connection": { + "name": "scim_connection", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "settings": { + "name": "settings", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_request_at": { + "name": "last_request_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "reconcile_lock_token": { + "name": "reconcile_lock_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reconcile_lease_at": { + "name": "reconcile_lease_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "reconciled_at": { + "name": "reconciled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_connection_organization_unique": { + "name": "scim_connection_organization_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_connection_reconcile_due_idx": { + "name": "scim_connection_reconcile_due_idx", + "columns": [ + { + "expression": "reconciled_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_connection_organization_id_organization_id_fk": { + "name": "scim_connection_organization_id_organization_id_fk", + "tableFrom": "scim_connection", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_connection_created_by_user_id_fk": { + "name": "scim_connection_created_by_user_id_fk", + "tableFrom": "scim_connection", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_credential": { + "name": "scim_credential", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked_by": { + "name": "revoked_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_credential_token_hash_unique": { + "name": "scim_credential_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_credential_connection_idx": { + "name": "scim_credential_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_credential_connection_id_scim_connection_id_fk": { + "name": "scim_credential_connection_id_scim_connection_id_fk", + "tableFrom": "scim_credential", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_credential_revoked_by_user_id_fk": { + "name": "scim_credential_revoked_by_user_id_fk", + "tableFrom": "scim_credential", + "tableTo": "user", + "columnsFrom": ["revoked_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "scim_credential_created_by_user_id_fk": { + "name": "scim_credential_created_by_user_id_fk", + "tableFrom": "scim_credential", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_group": { + "name": "scim_group", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name_key": { + "name": "display_name_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_connection_display_name_unique": { + "name": "scim_group_connection_display_name_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_connection_external_id_unique": { + "name": "scim_group_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "external_id is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_connection_order_idx": { + "name": "scim_group_connection_order_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_connection_id_scim_connection_id_fk": { + "name": "scim_group_connection_id_scim_connection_id_fk", + "tableFrom": "scim_group", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_group_mapping": { + "name": "scim_group_mapping", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_kind": { + "name": "target_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_mapping_permission_group_idx": { + "name": "scim_group_mapping_permission_group_idx", + "columns": [ + { + "expression": "permission_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_mapping_workspace_idx": { + "name": "scim_group_mapping_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_mapping_group_target_unique": { + "name": "scim_group_mapping_group_target_unique", + "columns": [ + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"permission_group_id\", \"workspace_id\", \"role\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_mapping_group_id_scim_group_id_fk": { + "name": "scim_group_mapping_group_id_scim_group_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "scim_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_permission_group_id_permission_group_id_fk": { + "name": "scim_group_mapping_permission_group_id_permission_group_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "permission_group", + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_workspace_id_workspace_id_fk": { + "name": "scim_group_mapping_workspace_id_workspace_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_mapping_created_by_user_id_fk": { + "name": "scim_group_mapping_created_by_user_id_fk", + "tableFrom": "scim_group_mapping", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "scim_group_mapping_target_shape": { + "name": "scim_group_mapping_target_shape", + "value": "(\n (\"scim_group_mapping\".\"target_kind\" = 'permission_group' AND \"scim_group_mapping\".\"permission_group_id\" IS NOT NULL AND \"scim_group_mapping\".\"workspace_id\" IS NULL AND \"scim_group_mapping\".\"permission_type\" IS NULL AND \"scim_group_mapping\".\"role\" IS NULL)\n OR (\"scim_group_mapping\".\"target_kind\" = 'workspace' AND \"scim_group_mapping\".\"workspace_id\" IS NOT NULL AND \"scim_group_mapping\".\"permission_type\" IS NOT NULL AND \"scim_group_mapping\".\"permission_group_id\" IS NULL AND \"scim_group_mapping\".\"role\" IS NULL)\n OR (\"scim_group_mapping\".\"target_kind\" = 'org_role' AND \"scim_group_mapping\".\"role\" IS NOT NULL AND \"scim_group_mapping\".\"permission_group_id\" IS NULL AND \"scim_group_mapping\".\"workspace_id\" IS NULL AND \"scim_group_mapping\".\"permission_type\" IS NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.scim_group_member": { + "name": "scim_group_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scim_user_id": { + "name": "scim_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_group_member_group_user_unique": { + "name": "scim_group_member_group_user_unique", + "columns": [ + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_group_member_scim_user_idx": { + "name": "scim_group_member_scim_user_idx", + "columns": [ + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_group_member_group_id_scim_group_id_fk": { + "name": "scim_group_member_group_id_scim_group_id_fk", + "tableFrom": "scim_group_member", + "tableTo": "scim_group", + "columnsFrom": ["group_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_group_member_scim_user_id_scim_user_id_fk": { + "name": "scim_group_member_scim_user_id_scim_user_id_fk", + "tableFrom": "scim_group_member", + "tableTo": "scim_user", + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_projection_grant": { + "name": "scim_projection_grant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scim_user_id": { + "name": "scim_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_kind": { + "name": "target_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "baseline_permission": { + "name": "baseline_permission", + "type": "permission_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'directory'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_projection_grant_user_target_unique": { + "name": "scim_projection_grant_user_target_unique", + "columns": [ + { + "expression": "scim_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_projection_grant_connection_idx": { + "name": "scim_projection_grant_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_projection_grant_connection_id_scim_connection_id_fk": { + "name": "scim_projection_grant_connection_id_scim_connection_id_fk", + "tableFrom": "scim_projection_grant", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_projection_grant_scim_user_id_scim_user_id_fk": { + "name": "scim_projection_grant_scim_user_id_scim_user_id_fk", + "tableFrom": "scim_projection_grant", + "tableTo": "scim_user", + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_request_log": { + "name": "scim_request_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scim_type": { + "name": "scim_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_request_log_connection_created_idx": { + "name": "scim_request_log_connection_created_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_request_log_connection_id_scim_connection_id_fk": { + "name": "scim_request_log_connection_id_scim_connection_id_fk", + "tableFrom": "scim_request_log", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_user": { + "name": "scim_user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_name": { + "name": "user_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "attributes": { + "name": "attributes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_user_connection_user_unique": { + "name": "scim_user_connection_user_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_user_name_unique": { + "name": "scim_user_connection_user_name_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_external_id_unique": { + "name": "scim_user_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "external_id is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_connection_order_idx": { + "name": "scim_user_connection_order_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_user_idx": { + "name": "scim_user_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_user_connection_id_scim_connection_id_fk": { + "name": "scim_user_connection_id_scim_connection_id_fk", + "tableFrom": "scim_user", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_user_user_id_user_id_fk": { + "name": "scim_user_user_id_user_id_fk", + "tableFrom": "scim_user", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scim_user_tombstone": { + "name": "scim_user_tombstone", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scim_user_tombstone_connection_external_id_unique": { + "name": "scim_user_tombstone_connection_external_id_unique", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "scim_user_tombstone_user_idx": { + "name": "scim_user_tombstone_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scim_user_tombstone_connection_id_scim_connection_id_fk": { + "name": "scim_user_tombstone_connection_id_scim_connection_id_fk", + "tableFrom": "scim_user_tombstone", + "tableTo": "scim_connection", + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scim_user_tombstone_user_id_user_id_fk": { + "name": "scim_user_tombstone_user_id_user_id_fk", + "tableFrom": "scim_user_tombstone", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.secret_usage": { + "name": "secret_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_name": { + "name": "secret_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_scope": { + "name": "secret_scope", + "type": "secret_usage_scope", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "secret_owner_user_id": { + "name": "secret_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "source": { + "name": "source", + "type": "secret_usage_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "usage_date": { + "name": "usage_date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "use_count": { + "name": "use_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "last_execution_id": { + "name": "last_execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_trigger": { + "name": "last_trigger", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "secret_usage_bucket_unique": { + "name": "secret_usage_bucket_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_date", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "secret_usage_secret_recent_idx": { + "name": "secret_usage_secret_recent_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_used_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "secret_usage_workspace_id_workspace_id_fk": { + "name": "secret_usage_workspace_id_workspace_id_fk", + "tableFrom": "secret_usage", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "active_organization_id": { + "name": "active_organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "session_user_id_idx": { + "name": "session_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "session_active_organization_id_organization_id_fk": { + "name": "session_active_organization_id_organization_id_fk", + "tableFrom": "session", + "tableTo": "organization", + "columnsFrom": ["active_organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": ["token"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "theme": { + "name": "theme", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "auto_connect": { + "name": "auto_connect", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "telemetry_enabled": { + "name": "telemetry_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "email_preferences": { + "name": "email_preferences", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "billing_usage_notifications_enabled": { + "name": "billing_usage_notifications_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "super_user_mode_enabled": { + "name": "super_user_mode_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "mothership_environment": { + "name": "mothership_environment", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "error_notifications_enabled": { + "name": "error_notifications_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "snap_to_grid_size": { + "name": "snap_to_grid_size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "show_action_bar": { + "name": "show_action_bar", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "auto_focus_on_click": { + "name": "auto_focus_on_click", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "copilot_auto_allowed_tools": { + "name": "copilot_auto_allowed_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "last_active_workspace_id": { + "name": "last_active_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "settings_user_id_user_id_fk": { + "name": "settings_user_id_user_id_fk", + "tableFrom": "settings", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "settings_user_id_unique": { + "name": "settings_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sim_link": { + "name": "sim_link", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_name": { + "name": "normalized_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_url": { + "name": "default_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "unlisted": { + "name": "unlisted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "restrict_edit": { + "name": "restrict_edit", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "visit_count": { + "name": "visit_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_visited_at": { + "name": "last_visited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sim_link_organization_name_unique": { + "name": "sim_link_organization_name_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sim_link_created_by_idx": { + "name": "sim_link_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sim_link_organization_id_organization_id_fk": { + "name": "sim_link_organization_id_organization_id_fk", + "tableFrom": "sim_link", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sim_link_created_by_user_id_fk": { + "name": "sim_link_created_by_user_id_fk", + "tableFrom": "sim_link", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sim_trigger_state": { + "name": "sim_trigger_state", + "schema": "", + "columns": { + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope_key": { + "name": "scope_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "last_fired_at": { + "name": "last_fired_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "sim_trigger_state_workflow_id_workflow_id_fk": { + "name": "sim_trigger_state_workflow_id_workflow_id_fk", + "tableFrom": "sim_trigger_state", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "sim_trigger_state_workflow_id_block_id_scope_key_pk": { + "name": "sim_trigger_state_workflow_id_block_id_scope_key_pk", + "columns": ["workflow_id", "block_id", "scope_key"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill": { + "name": "skill", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_workspace_name_unique": { + "name": "skill_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_workspace_id_workspace_id_fk": { + "name": "skill_workspace_id_workspace_id_fk", + "tableFrom": "skill", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_user_id_user_id_fk": { + "name": "skill_user_id_user_id_fk", + "tableFrom": "skill", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill_member": { + "name": "skill_member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_member_user_id_idx": { + "name": "skill_member_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skill_member_unique": { + "name": "skill_member_unique", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_member_skill_id_skill_id_fk": { + "name": "skill_member_skill_id_skill_id_fk", + "tableFrom": "skill_member", + "tableTo": "skill", + "columnsFrom": ["skill_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_member_user_id_user_id_fk": { + "name": "skill_member_user_id_user_id_fk", + "tableFrom": "skill_member", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_member_invited_by_user_id_fk": { + "name": "skill_member_invited_by_user_id_fk", + "tableFrom": "skill_member", + "tableTo": "user", + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_app": { + "name": "slack_app", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_client_secret": { + "name": "encrypted_client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_signing_secret": { + "name": "encrypted_signing_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "revision": { + "name": "revision", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "slack_app_organization_id_organization_id_fk": { + "name": "slack_app_organization_id_organization_id_fk", + "tableFrom": "slack_app", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "slack_app_owner_check": { + "name": "slack_app_owner_check", + "value": "(\"slack_app\".\"kind\" = 'custom' AND \"slack_app\".\"organization_id\" IS NOT NULL) OR (\"slack_app\".\"kind\" = 'shared' AND \"slack_app\".\"organization_id\" IS NULL)" + }, + "slack_app_custom_credentials_check": { + "name": "slack_app_custom_credentials_check", + "value": "\"slack_app\".\"kind\" = 'shared' OR (\"slack_app\".\"client_id\" IS NOT NULL AND \"slack_app\".\"encrypted_client_secret\" IS NOT NULL AND \"slack_app\".\"encrypted_signing_secret\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.slack_search_installation": { + "name": "slack_search_installation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_id": { + "name": "app_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_app_id": { + "name": "slack_app_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team_name": { + "name": "team_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bot_user_id": { + "name": "bot_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enterprise_id": { + "name": "enterprise_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "credential_version": { + "name": "credential_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "revision": { + "name": "revision", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_outcome": { + "name": "last_outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_event_at": { + "name": "last_event_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "slack_search_installation_organization_idx": { + "name": "slack_search_installation_organization_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_credential_unique": { + "name": "slack_search_installation_credential_unique", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_app_team_unique": { + "name": "slack_search_installation_app_team_unique", + "columns": [ + { + "expression": "app_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_installation_active_team_unique": { + "name": "slack_search_installation_active_team_unique", + "columns": [ + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"slack_search_installation\".\"enabled\" = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_search_installation_organization_id_organization_id_fk": { + "name": "slack_search_installation_organization_id_organization_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_search_installation_credential_id_credential_id_fk": { + "name": "slack_search_installation_credential_id_credential_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "credential", + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_search_installation_slack_app_id_slack_app_id_fk": { + "name": "slack_search_installation_slack_app_id_slack_app_id_fk", + "tableFrom": "slack_search_installation", + "tableTo": "slack_app", + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_search_turn": { + "name": "slack_search_turn", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "slack_search_turn_ordinal_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "conversation_key": { + "name": "conversation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "lease_id": { + "name": "lease_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "slack_search_turn_event_unique": { + "name": "slack_search_turn_event_unique", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_pending_idx": { + "name": "slack_search_turn_pending_idx", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_thread_idx": { + "name": "slack_search_turn_thread_idx", + "columns": [ + { + "expression": "conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_search_turn_active_thread_unique": { + "name": "slack_search_turn_active_thread_unique", + "columns": [ + { + "expression": "conversation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"slack_search_turn\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_search_turn_installation_id_slack_search_installation_id_fk": { + "name": "slack_search_turn_installation_id_slack_search_installation_id_fk", + "tableFrom": "slack_search_turn", + "tableTo": "slack_search_installation", + "columnsFrom": ["installation_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sso_domain": { + "name": "sso_domain", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "verification_token": { + "name": "verification_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "verified_at": { + "name": "verified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "primary_provider_id": { + "name": "primary_provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sso_domain_domain_idx": { + "name": "sso_domain_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_domain_org_domain_unique": { + "name": "sso_domain_org_domain_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_domain_verified_unique": { + "name": "sso_domain_verified_unique", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "status = 'verified'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sso_domain_organization_id_organization_id_fk": { + "name": "sso_domain_organization_id_organization_id_fk", + "tableFrom": "sso_domain", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sso_domain_created_by_user_id_fk": { + "name": "sso_domain_created_by_user_id_fk", + "tableFrom": "sso_domain", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sso_provider": { + "name": "sso_provider", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oidc_config": { + "name": "oidc_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "saml_config": { + "name": "saml_config", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "domain_verified": { + "name": "domain_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "jit_provisioning_enabled": { + "name": "jit_provisioning_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + } + }, + "indexes": { + "sso_provider_provider_id_unique": { + "name": "sso_provider_provider_id_unique", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_domain_idx": { + "name": "sso_provider_domain_idx", + "columns": [ + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_user_id_idx": { + "name": "sso_provider_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sso_provider_organization_id_idx": { + "name": "sso_provider_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sso_provider_user_id_user_id_fk": { + "name": "sso_provider_user_id_user_id_fk", + "tableFrom": "sso_provider", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sso_provider_organization_id_organization_id_fk": { + "name": "sso_provider_organization_id_organization_id_fk", + "tableFrom": "sso_provider", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.subscription": { + "name": "subscription", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "period_start": { + "name": "period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "period_end": { + "name": "period_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "cancel_at": { + "name": "cancel_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "canceled_at": { + "name": "canceled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "seats": { + "name": "seats", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "trial_start": { + "name": "trial_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trial_end": { + "name": "trial_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "billing_interval": { + "name": "billing_interval", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_schedule_id": { + "name": "stripe_schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "last_closed_period_start": { + "name": "last_closed_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "allowance_period_start": { + "name": "allowance_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "allowance_seats": { + "name": "allowance_seats", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "allowance_seat_months": { + "name": "allowance_seat_months", + "type": "numeric", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "subscription_reference_status_idx": { + "name": "subscription_reference_status_idx", + "columns": [ + { + "expression": "reference_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "subscription_cycle_close_lagging_idx": { + "name": "subscription_cycle_close_lagging_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"subscription\".\"status\" in ('active', 'past_due') and \"subscription\".\"period_start\" is not null and (\"subscription\".\"last_closed_period_start\" is null or \"subscription\".\"last_closed_period_start\" < \"subscription\".\"period_start\")", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "check_enterprise_metadata": { + "name": "check_enterprise_metadata", + "value": "plan != 'enterprise' OR metadata IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.table_jobs": { + "name": "table_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "rows_processed": { + "name": "rows_processed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "table_jobs_one_active_per_table": { + "name": "table_jobs_one_active_per_table", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"table_jobs\".\"status\" = 'running' AND \"table_jobs\".\"type\" <> 'export'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_jobs_watchdog_idx": { + "name": "table_jobs_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_jobs_table_started_idx": { + "name": "table_jobs_table_started_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_jobs_table_id_user_table_definitions_id_fk": { + "name": "table_jobs_table_id_user_table_definitions_id_fk", + "tableFrom": "table_jobs", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_jobs_workspace_id_workspace_id_fk": { + "name": "table_jobs_workspace_id_workspace_id_fk", + "tableFrom": "table_jobs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_row_executions": { + "name": "table_row_executions", + "schema": "", + "columns": { + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "row_id": { + "name": "row_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "running_block_ids": { + "name": "running_block_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "block_errors": { + "name": "block_errors", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "capability_governed_user_id": { + "name": "capability_governed_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enrichment_details": { + "name": "enrichment_details", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "table_row_executions_table_status_idx": { + "name": "table_row_executions_table_status_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_row_executions\".\"status\" IN ('queued', 'running', 'pending')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_row_executions_execution_id_idx": { + "name": "table_row_executions_execution_id_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_row_executions\".\"execution_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_row_executions_table_group_idx": { + "name": "table_row_executions_table_group_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_row_executions_table_id_user_table_definitions_id_fk": { + "name": "table_row_executions_table_id_user_table_definitions_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_row_executions_row_id_user_table_rows_id_fk": { + "name": "table_row_executions_row_id_user_table_rows_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user_table_rows", + "columnsFrom": ["row_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_row_executions_capability_governed_user_id_user_id_fk": { + "name": "table_row_executions_capability_governed_user_id_user_id_fk", + "tableFrom": "table_row_executions", + "tableTo": "user", + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "table_row_executions_row_id_group_id_pk": { + "name": "table_row_executions_row_id_group_id_pk", + "columns": ["row_id", "group_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_run_dispatches": { + "name": "table_run_dispatches", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "cursor": { + "name": "cursor", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit": { + "name": "limit", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "processed_count": { + "name": "processed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_manual_run": { + "name": "is_manual_run", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "triggered_by_user_id": { + "name": "triggered_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capability_governed_user_id": { + "name": "capability_governed_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_at": { + "name": "requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "heartbeat_at": { + "name": "heartbeat_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "table_run_dispatches_active_idx": { + "name": "table_run_dispatches_active_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_run_dispatches_watchdog_idx": { + "name": "table_run_dispatches_watchdog_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "requested_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_run_dispatches_governed_active_idx": { + "name": "table_run_dispatches_governed_active_idx", + "columns": [ + { + "expression": "capability_governed_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"table_run_dispatches\".\"status\" IN ('pending', 'dispatching')", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_run_dispatches_table_id_user_table_definitions_id_fk": { + "name": "table_run_dispatches_table_id_user_table_definitions_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_run_dispatches_workspace_id_workspace_id_fk": { + "name": "table_run_dispatches_workspace_id_workspace_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_run_dispatches_triggered_by_user_id_user_id_fk": { + "name": "table_run_dispatches_triggered_by_user_id_user_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user", + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "table_run_dispatches_capability_governed_user_id_user_id_fk": { + "name": "table_run_dispatches_capability_governed_user_id_user_id_fk", + "tableFrom": "table_run_dispatches", + "tableTo": "user", + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.table_views": { + "name": "table_views", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "table_views_table_created_idx": { + "name": "table_views_table_created_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_views_workspace_created_idx": { + "name": "table_views_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "table_views_table_default_unique": { + "name": "table_views_table_default_unique", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "is_default = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "table_views_table_id_user_table_definitions_id_fk": { + "name": "table_views_table_id_user_table_definitions_id_fk", + "tableFrom": "table_views", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_views_workspace_id_workspace_id_fk": { + "name": "table_views_workspace_id_workspace_id_fk", + "tableFrom": "table_views", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "table_views_created_by_user_id_fk": { + "name": "table_views_created_by_user_id_fk", + "tableFrom": "table_views", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.trial_card": { + "name": "trial_card", + "schema": "", + "columns": { + "fingerprint": { + "name": "fingerprint", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "trial_card_user_id_idx": { + "name": "trial_card_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "trial_card_user_id_user_id_fk": { + "name": "trial_card_user_id_user_id_fk", + "tableFrom": "trial_card", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.upload_session": { + "name": "upload_session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "knowledge_base_id": { + "name": "knowledge_base_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "purpose": { + "name": "purpose", + "type": "upload_session_purpose", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "upload_session_method", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "storage_context": { + "name": "storage_context", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "final_key": { + "name": "final_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_provider": { + "name": "storage_provider", + "type": "upload_session_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "provider_upload_id": { + "name": "provider_upload_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_object_version": { + "name": "provider_object_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_size": { + "name": "file_size", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "part_size": { + "name": "part_size", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "part_count": { + "name": "part_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "upload_session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'uploading'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "processing_lease_id": { + "name": "processing_lease_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "processing_lease_expires_at": { + "name": "processing_lease_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_file_id": { + "name": "completed_file_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "upload_session_token_hash_unique": { + "name": "upload_session_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "upload_session_final_key_unique": { + "name": "upload_session_final_key_unique", + "columns": [ + { + "expression": "final_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "upload_session_status_expires_at_idx": { + "name": "upload_session_status_expires_at_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.usage_log": { + "name": "usage_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category": { + "name": "category", + "type": "usage_log_category", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "usage_log_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "cost": { + "name": "cost", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "event_key": { + "name": "event_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_entity_type": { + "name": "billing_entity_type", + "type": "billing_entity_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "billing_entity_id": { + "name": "billing_entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "billing_period_start": { + "name": "billing_period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "billing_period_end": { + "name": "billing_period_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "usage_log_user_created_at_idx": { + "name": "usage_log_user_created_at_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_source_idx": { + "name": "usage_log_source_idx", + "columns": [ + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_workflow_id_idx": { + "name": "usage_log_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_event_key_unique": { + "name": "usage_log_event_key_unique", + "columns": [ + { + "expression": "event_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"usage_log\".\"event_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_billing_entity_period_cost_idx": { + "name": "usage_log_billing_entity_period_cost_idx", + "columns": [ + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_period_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_period_end", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"usage_log\".\"billing_entity_type\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_billing_entity_created_at_cost_idx": { + "name": "usage_log_billing_entity_created_at_cost_idx", + "columns": [ + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"usage_log\".\"billing_entity_type\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_workspace_created_at_cost_idx": { + "name": "usage_log_workspace_created_at_cost_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "billing_entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_log_execution_id_idx": { + "name": "usage_log_execution_id_idx", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "usage_log_user_id_user_id_fk": { + "name": "usage_log_user_id_user_id_fk", + "tableFrom": "usage_log", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "usage_log_workspace_id_workspace_id_fk": { + "name": "usage_log_workspace_id_workspace_id_fk", + "tableFrom": "usage_log", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "usage_log_workflow_id_workflow_id_fk": { + "name": "usage_log_workflow_id_workflow_id_fk", + "tableFrom": "usage_log", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "usage_log_billing_scope_all_or_none": { + "name": "usage_log_billing_scope_all_or_none", + "value": "(\n (\"usage_log\".\"billing_entity_type\" IS NULL AND \"usage_log\".\"billing_entity_id\" IS NULL AND \"usage_log\".\"billing_period_start\" IS NULL AND \"usage_log\".\"billing_period_end\" IS NULL)\n OR\n (\"usage_log\".\"billing_entity_type\" IS NOT NULL AND \"usage_log\".\"billing_entity_id\" IS NOT NULL AND \"usage_log\".\"billing_period_start\" IS NOT NULL AND \"usage_log\".\"billing_period_end\" IS NOT NULL AND \"usage_log\".\"billing_period_start\" < \"usage_log\".\"billing_period_end\")\n )" + } + }, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "normalized_email": { + "name": "normalized_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'user'" + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "suspension_source": { + "name": "suspension_source", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_email_lower_idx": { + "name": "user_email_lower_idx", + "columns": [ + { + "expression": "lower(btrim(\"email\"))", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_gmail_mailbox_idx": { + "name": "user_gmail_mailbox_idx", + "columns": [ + { + "expression": "(CASE WHEN split_part(lower(btrim(\"email\")), '@', 2) IN ('gmail.com', 'googlemail.com') THEN replace(split_part(split_part(lower(btrim(\"email\")), '@', 1), '+', 1), '.', '') || '@gmail.com' END)", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "(CASE WHEN split_part(lower(btrim(\"user\".\"email\")), '@', 2) IN ('gmail.com', 'googlemail.com') THEN replace(split_part(split_part(lower(btrim(\"user\".\"email\")), '@', 1), '+', 1), '.', '') || '@gmail.com' END) IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": ["email"] + }, + "user_normalized_email_unique": { + "name": "user_normalized_email_unique", + "nullsNotDistinct": false, + "columns": ["normalized_email"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_stats": { + "name": "user_stats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "current_usage_limit": { + "name": "current_usage_limit", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'5'" + }, + "usage_limit_updated_at": { + "name": "usage_limit_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "last_period_cost": { + "name": "last_period_cost", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'0'" + }, + "billed_overage_this_period": { + "name": "billed_overage_this_period", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "credit_balance": { + "name": "credit_balance", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "last_period_copilot_cost": { + "name": "last_period_copilot_cost", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": "'0'" + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "free_tier_eligible": { + "name": "free_tier_eligible", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "billing_blocked": { + "name": "billing_blocked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "billing_blocked_reason": { + "name": "billing_blocked_reason", + "type": "billing_blocked_reason", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "limit_notifications": { + "name": "limit_notifications", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + } + }, + "indexes": {}, + "foreignKeys": { + "user_stats_user_id_user_id_fk": { + "name": "user_stats_user_id_user_id_fk", + "tableFrom": "user_stats", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_stats_user_id_unique": { + "name": "user_stats_user_id_unique", + "nullsNotDistinct": false, + "columns": ["user_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_definitions": { + "name": "user_table_definitions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "schema": { + "name": "schema", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "max_rows": { + "name": "max_rows", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10000 + }, + "row_count": { + "name": "row_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "rows_version": { + "name": "rows_version", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "schema_locked": { + "name": "schema_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "insert_locked": { + "name": "insert_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "update_locked": { + "name": "update_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "delete_locked": { + "name": "delete_locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "user_table_def_workspace_id_idx": { + "name": "user_table_def_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_folder_id_idx": { + "name": "user_table_def_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_created_by_idx": { + "name": "user_table_def_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "user_table_def_workspace_name_unique": { + "name": "user_table_def_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"user_table_definitions\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_archived_at_idx": { + "name": "user_table_def_archived_at_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_def_workspace_archived_partial_idx": { + "name": "user_table_def_workspace_archived_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"user_table_definitions\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_definitions_workspace_id_workspace_id_fk": { + "name": "user_table_definitions_workspace_id_workspace_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_definitions_folder_id_folder_id_fk": { + "name": "user_table_definitions_folder_id_folder_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "user_table_definitions_created_by_user_id_fk": { + "name": "user_table_definitions_created_by_user_id_fk", + "tableFrom": "user_table_definitions", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_row_changes": { + "name": "user_table_row_changes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "user_table_row_changes_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "row_delta": { + "name": "row_delta", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "user_table_row_changes_table_id_idx": { + "name": "user_table_row_changes_table_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_row_changes_table_id_user_table_definitions_id_fk": { + "name": "user_table_row_changes_table_id_user_table_definitions_id_fk", + "tableFrom": "user_table_row_changes", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_table_row_secret_provenance": { + "name": "user_table_row_secret_provenance", + "schema": "", + "columns": { + "row_id": { + "name": "row_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_table_row_secret_provenance_row_id_user_table_rows_id_fk": { + "name": "user_table_row_secret_provenance_row_id_user_table_rows_id_fk", + "tableFrom": "user_table_row_secret_provenance", + "tableTo": "user_table_rows", + "columnsFrom": ["row_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_table_row_secret_provenance_status_check": { + "name": "user_table_row_secret_provenance_status_check", + "value": "\"user_table_row_secret_provenance\".\"status\" IN ('exact', 'unknown')" + } + }, + "isRLSEnabled": false + }, + "public.user_table_rows": { + "name": "user_table_rows", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "table_id": { + "name": "table_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "order_key": { + "name": "order_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_table_rows_created_by_idx": { + "name": "user_table_rows_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"user_table_rows\".\"created_by\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "user_table_rows_tenant_data_gin_idx": { + "name": "user_table_rows_tenant_data_gin_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"data\" jsonb_path_ops", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "user_table_rows_workspace_table_idx": { + "name": "user_table_rows_workspace_table_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_position_idx": { + "name": "user_table_rows_table_position_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_order_key_idx": { + "name": "user_table_rows_table_order_key_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "order_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_created_id_idx": { + "name": "user_table_rows_table_created_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_table_rows_table_id_id_idx": { + "name": "user_table_rows_table_id_id_idx", + "columns": [ + { + "expression": "table_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_table_rows_table_id_user_table_definitions_id_fk": { + "name": "user_table_rows_table_id_user_table_definitions_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "user_table_definitions", + "columnsFrom": ["table_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_rows_workspace_id_workspace_id_fk": { + "name": "user_table_rows_workspace_id_workspace_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_table_rows_created_by_user_id_fk": { + "name": "user_table_rows_created_by_user_id_fk", + "tableFrom": "user_table_rows", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "verification_expires_at_idx": { + "name": "verification_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.webhook": { + "name": "webhook", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_status": { + "name": "registration_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_generation": { + "name": "registration_generation", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "config_fingerprint": { + "name": "config_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "prepared_at": { + "name": "prepared_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "routing_key": { + "name": "routing_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_config": { + "name": "provider_config", + "type": "json", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "path_deployment_unique": { + "name": "path_deployment_unique", + "columns": [ + { + "expression": "path", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_workflow_deployment_idx": { + "name": "webhook_workflow_deployment_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_routing_key_active_idx": { + "name": "webhook_routing_key_active_idx", + "columns": [ + { + "expression": "routing_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"webhook\".\"archived_at\" IS NULL AND \"webhook\".\"routing_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_archived_at_partial_idx": { + "name": "webhook_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"webhook\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_webhook_on_provider_is_active_workflow_id_deploym_bdeed5468": { + "name": "idx_webhook_on_provider_is_active_workflow_id_deploym_bdeed5468", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_webhook_on_workflow_id_block_id_updated_at_desc": { + "name": "idx_webhook_on_workflow_id_block_id_updated_at_desc", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_active_registration_unique": { + "name": "webhook_active_registration_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"registration_status\" = 'active' AND \"webhook\".\"block_id\" IS NOT NULL AND \"webhook\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_candidate_registration_unique": { + "name": "webhook_candidate_registration_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"webhook\".\"registration_status\" = 'candidate' AND \"webhook\".\"block_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_registration_status_generation_idx": { + "name": "webhook_registration_status_generation_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "registration_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "registration_generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "webhook_workflow_id_workflow_id_fk": { + "name": "webhook_workflow_id_workflow_id_fk", + "tableFrom": "webhook", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "webhook_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "webhook_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "webhook", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "webhook_registration_status_check": { + "name": "webhook_registration_status_check", + "value": "\"webhook\".\"registration_status\" IS NULL OR \"webhook\".\"registration_status\" IN ('active', 'candidate', 'retired', 'orphaned')" + }, + "webhook_registration_generation_check": { + "name": "webhook_registration_generation_check", + "value": "\"webhook\".\"registration_generation\" IS NULL OR \"webhook\".\"registration_generation\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.webhook_path_claim": { + "name": "webhook_path_claim", + "schema": "", + "columns": { + "path": { + "name": "path", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "webhook_path_claim_workflow_idx": { + "name": "webhook_path_claim_workflow_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "webhook_path_claim_workflow_id_workflow_id_fk": { + "name": "webhook_path_claim_workflow_id_workflow_id_fk", + "tableFrom": "webhook_path_claim", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "webhook_path_claim_generation_check": { + "name": "webhook_path_claim_generation_check", + "value": "\"webhook_path_claim\".\"generation\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.workflow": { + "name": "workflow", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_synced": { + "name": "last_synced", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "is_deployed": { + "name": "is_deployed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deployed_at": { + "name": "deployed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "is_public_api": { + "name": "is_public_api", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "fork_sync_excluded": { + "name": "fork_sync_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_workspace_id_idx": { + "name": "workflow_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_user_workspace_idx": { + "name": "workflow_user_workspace_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_workspace_folder_name_active_unique": { + "name": "workflow_workspace_folder_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_folder_sort_idx": { + "name": "workflow_folder_sort_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_active_workspace_sort_idx": { + "name": "workflow_active_workspace_sort_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_archived_at_idx": { + "name": "workflow_archived_at_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_workspace_archived_partial_idx": { + "name": "workflow_workspace_archived_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_user_id_user_id_fk": { + "name": "workflow_user_id_user_id_fk", + "tableFrom": "workflow", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_workspace_id_workspace_id_fk": { + "name": "workflow_workspace_id_workspace_id_fk", + "tableFrom": "workflow", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_folder_id_folder_id_fk": { + "name": "workflow_folder_id_folder_id_fk", + "tableFrom": "workflow", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_activity_hourly": { + "name": "workflow_activity_hourly", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bucket_start": { + "name": "bucket_start", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "runs": { + "name": "runs", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "completed": { + "name": "completed", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cancelled": { + "name": "cancelled", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "in_flight": { + "name": "in_flight", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "duration_sum_ms": { + "name": "duration_sum_ms", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "duration_count": { + "name": "duration_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "computed_at": { + "name": "computed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_activity_hourly_read_idx": { + "name": "workflow_activity_hourly_read_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "bucket_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "runs", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "completed", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "failed", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cancelled", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "in_flight", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "duration_sum_ms", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "duration_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_activity_hourly_bucket_start_idx": { + "name": "workflow_activity_hourly_bucket_start_idx", + "columns": [ + { + "expression": "bucket_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "workflow_activity_hourly_pk": { + "name": "workflow_activity_hourly_pk", + "columns": ["workspace_id", "bucket_start", "workflow_id", "trigger"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_blocks": { + "name": "workflow_blocks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position_x": { + "name": "position_x", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "position_y": { + "name": "position_y", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "horizontal_handles": { + "name": "horizontal_handles", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "is_wide": { + "name": "is_wide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "advanced_mode": { + "name": "advanced_mode", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "trigger_mode": { + "name": "trigger_mode", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "error_enabled": { + "name": "error_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "retry": { + "name": "retry", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "height": { + "name": "height", + "type": "numeric", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "sub_blocks": { + "name": "sub_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "outputs": { + "name": "outputs", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_blocks_workflow_id_idx": { + "name": "workflow_blocks_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_blocks_type_idx": { + "name": "workflow_blocks_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_blocks_workflow_id_workflow_id_fk": { + "name": "workflow_blocks_workflow_id_workflow_id_fk", + "tableFrom": "workflow_blocks", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_checkpoints": { + "name": "workflow_checkpoints", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow_state": { + "name": "workflow_state", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_checkpoints_chat_id_idx": { + "name": "workflow_checkpoints_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_message_id_idx": { + "name": "workflow_checkpoints_message_id_idx", + "columns": [ + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_user_workflow_idx": { + "name": "workflow_checkpoints_user_workflow_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_workflow_chat_idx": { + "name": "workflow_checkpoints_workflow_chat_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_created_at_idx": { + "name": "workflow_checkpoints_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_checkpoints_chat_created_at_idx": { + "name": "workflow_checkpoints_chat_created_at_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_checkpoints_user_id_user_id_fk": { + "name": "workflow_checkpoints_user_id_user_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_checkpoints_workflow_id_workflow_id_fk": { + "name": "workflow_checkpoints_workflow_id_workflow_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_checkpoints_chat_id_copilot_chats_id_fk": { + "name": "workflow_checkpoints_chat_id_copilot_chats_id_fk", + "tableFrom": "workflow_checkpoints", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_deployment_operation": { + "name": "workflow_deployment_operation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "previous_active_version_id": { + "name": "previous_active_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "protocol_version": { + "name": "protocol_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'preparing'" + }, + "component_readiness": { + "name": "component_readiness", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_deployment_operation_workflow_generation_unique": { + "name": "workflow_deployment_operation_workflow_generation_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_idempotency_unique": { + "name": "workflow_deployment_operation_workflow_idempotency_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_deployment_operation\".\"idempotency_key\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_in_flight_unique": { + "name": "workflow_deployment_operation_workflow_in_flight_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_deployment_operation\".\"status\" IN ('preparing', 'activating')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_status_idx": { + "name": "workflow_deployment_operation_workflow_status_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_deployment_version_idx": { + "name": "workflow_deployment_operation_deployment_version_idx", + "columns": [ + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_operation_workflow_version_generation_idx": { + "name": "workflow_deployment_operation_workflow_version_generation_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_deployment_operation_workflow_id_workflow_id_fk": { + "name": "workflow_deployment_operation_workflow_id_workflow_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_deployment_operation_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_deployment_operation_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_deployment_operation_previous_active_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_deployment_operation_previous_active_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_deployment_operation", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["previous_active_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workflow_deployment_operation_action_check": { + "name": "workflow_deployment_operation_action_check", + "value": "\"workflow_deployment_operation\".\"action\" IN ('deploy', 'activate')" + }, + "workflow_deployment_operation_status_check": { + "name": "workflow_deployment_operation_status_check", + "value": "\"workflow_deployment_operation\".\"status\" IN ('preparing', 'activating', 'active', 'failed', 'superseded')" + }, + "workflow_deployment_operation_generation_check": { + "name": "workflow_deployment_operation_generation_check", + "value": "\"workflow_deployment_operation\".\"generation\" > 0" + }, + "workflow_deployment_operation_protocol_version_check": { + "name": "workflow_deployment_operation_protocol_version_check", + "value": "\"workflow_deployment_operation\".\"protocol_version\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.workflow_deployment_version": { + "name": "workflow_deployment_version", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "json", + "primaryKey": false, + "notNull": true + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_deployment_version_workflow_version_unique": { + "name": "workflow_deployment_version_workflow_version_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_version_workflow_active_idx": { + "name": "workflow_deployment_version_workflow_active_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_deployment_version_created_at_idx": { + "name": "workflow_deployment_version_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_deployment_version_workflow_id_workflow_id_fk": { + "name": "workflow_deployment_version_workflow_id_workflow_id_fk", + "tableFrom": "workflow_deployment_version", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_edges": { + "name": "workflow_edges", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_block_id": { + "name": "source_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_block_id": { + "name": "target_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_handle": { + "name": "source_handle", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_handle": { + "name": "target_handle", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_edges_workflow_source_idx": { + "name": "workflow_edges_workflow_source_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_workflow_target_idx": { + "name": "workflow_edges_workflow_target_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_source_block_fk_idx": { + "name": "workflow_edges_source_block_fk_idx", + "columns": [ + { + "expression": "source_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_edges_target_block_fk_idx": { + "name": "workflow_edges_target_block_fk_idx", + "columns": [ + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_edges_workflow_id_workflow_id_fk": { + "name": "workflow_edges_workflow_id_workflow_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_edges_source_block_id_workflow_blocks_id_fk": { + "name": "workflow_edges_source_block_id_workflow_blocks_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow_blocks", + "columnsFrom": ["source_block_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_edges_target_block_id_workflow_blocks_id_fk": { + "name": "workflow_edges_target_block_id_workflow_blocks_id_fk", + "tableFrom": "workflow_edges", + "tableTo": "workflow_blocks", + "columnsFrom": ["target_block_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_execution_logs": { + "name": "workflow_execution_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state_snapshot_id": { + "name": "state_snapshot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "execution_deadline_at": { + "name": "execution_deadline_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "total_duration_ms": { + "name": "total_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "execution_data": { + "name": "execution_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "cost_total": { + "name": "cost_total", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "models_used": { + "name": "models_used", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_execution_logs_state_snapshot_id_idx": { + "name": "workflow_execution_logs_state_snapshot_id_idx", + "columns": [ + { + "expression": "state_snapshot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_deployment_version_id_idx": { + "name": "workflow_execution_logs_deployment_version_id_idx", + "columns": [ + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_trigger_idx": { + "name": "workflow_execution_logs_trigger_idx", + "columns": [ + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_level_idx": { + "name": "workflow_execution_logs_level_idx", + "columns": [ + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_started_at_idx": { + "name": "workflow_execution_logs_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_execution_id_unique": { + "name": "workflow_execution_logs_execution_id_unique", + "columns": [ + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workflow_started_at_idx": { + "name": "workflow_execution_logs_workflow_started_at_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_activity_level_idx": { + "name": "workflow_execution_logs_workspace_activity_level_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "total_duration_ms", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_started_at_id_desc_idx": { + "name": "workflow_execution_logs_workspace_started_at_id_desc_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"started_at\" DESC NULLS LAST", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "\"id\" DESC", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_workspace_cost_total_idx": { + "name": "workflow_execution_logs_workspace_cost_total_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cost_total", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_models_used_idx": { + "name": "workflow_execution_logs_models_used_idx", + "columns": [ + { + "expression": "models_used", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "workflow_execution_logs_workspace_ended_at_id_idx": { + "name": "workflow_execution_logs_workspace_ended_at_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "date_trunc('milliseconds', \"ended_at\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_running_started_at_idx": { + "name": "workflow_execution_logs_running_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_running_deadline_idx": { + "name": "workflow_execution_logs_running_deadline_idx", + "columns": [ + { + "expression": "execution_deadline_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'running' AND \"workflow_execution_logs\".\"execution_deadline_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_redacting_started_at_idx": { + "name": "workflow_execution_logs_redacting_started_at_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status = 'redacting'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_redacting_deadline_idx": { + "name": "workflow_execution_logs_redacting_deadline_idx", + "columns": [ + { + "expression": "execution_deadline_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'redacting' AND \"workflow_execution_logs\".\"execution_deadline_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_completed_ended_at_idx": { + "name": "workflow_execution_logs_completed_ended_at_idx", + "columns": [ + { + "expression": "ended_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"status\" = 'completed' AND \"workflow_execution_logs\".\"level\" = 'info' AND \"workflow_execution_logs\".\"ended_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_execution_logs_late_end_idx": { + "name": "workflow_execution_logs_late_end_idx", + "columns": [ + { + "expression": "ended_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_execution_logs\".\"ended_at\" >= \"workflow_execution_logs\".\"started_at\" + interval '2 hours'", + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_execution_logs_workflow_id_workflow_id_fk": { + "name": "workflow_execution_logs_workflow_id_workflow_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workflow_execution_logs_workspace_id_workspace_id_fk": { + "name": "workflow_execution_logs_workspace_id_workspace_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_execution_logs_state_snapshot_id_workflow_execution_snapshots_id_fk": { + "name": "workflow_execution_logs_state_snapshot_id_workflow_execution_snapshots_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow_execution_snapshots", + "columnsFrom": ["state_snapshot_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workflow_execution_logs_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_execution_logs_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_execution_logs", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_execution_snapshots": { + "name": "workflow_execution_snapshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state_hash": { + "name": "state_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state_data": { + "name": "state_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_snapshots_hash_idx": { + "name": "workflow_snapshots_hash_idx", + "columns": [ + { + "expression": "state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_snapshots_workflow_hash_idx": { + "name": "workflow_snapshots_workflow_hash_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_snapshots_created_at_idx": { + "name": "workflow_snapshots_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_execution_snapshots_workflow_id_workflow_id_fk": { + "name": "workflow_execution_snapshots_workflow_id_workflow_id_fk", + "tableFrom": "workflow_execution_snapshots", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_mcp_server": { + "name": "workflow_mcp_server", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_public": { + "name": "is_public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_mcp_server_workspace_id_idx": { + "name": "workflow_mcp_server_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_created_by_idx": { + "name": "workflow_mcp_server_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_deleted_at_idx": { + "name": "workflow_mcp_server_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_server_workspace_deleted_partial_idx": { + "name": "workflow_mcp_server_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_mcp_server\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_mcp_server_workspace_id_workspace_id_fk": { + "name": "workflow_mcp_server_workspace_id_workspace_id_fk", + "tableFrom": "workflow_mcp_server", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_mcp_server_created_by_user_id_fk": { + "name": "workflow_mcp_server_created_by_user_id_fk", + "tableFrom": "workflow_mcp_server", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_mcp_tool": { + "name": "workflow_mcp_tool", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "server_id": { + "name": "server_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_description": { + "name": "tool_description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parameter_schema": { + "name": "parameter_schema", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "parameter_description_overrides": { + "name": "parameter_description_overrides", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'::json" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_mcp_tool_server_id_idx": { + "name": "workflow_mcp_tool_server_id_idx", + "columns": [ + { + "expression": "server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_workflow_id_idx": { + "name": "workflow_mcp_tool_workflow_id_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_server_workflow_unique": { + "name": "workflow_mcp_tool_server_workflow_unique", + "columns": [ + { + "expression": "server_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_mcp_tool\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_mcp_tool_archived_at_partial_idx": { + "name": "workflow_mcp_tool_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_mcp_tool\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_mcp_tool_server_id_workflow_mcp_server_id_fk": { + "name": "workflow_mcp_tool_server_id_workflow_mcp_server_id_fk", + "tableFrom": "workflow_mcp_tool", + "tableTo": "workflow_mcp_server", + "columnsFrom": ["server_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_mcp_tool_workflow_id_workflow_id_fk": { + "name": "workflow_mcp_tool_workflow_id_workflow_id_fk", + "tableFrom": "workflow_mcp_tool", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_schedule": { + "name": "workflow_schedule", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_version_id": { + "name": "deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_operation_id": { + "name": "deployment_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "block_id": { + "name": "block_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cron_expression": { + "name": "cron_expression", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_ran_at": { + "name": "last_ran_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_queued_at": { + "name": "last_queued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trigger_type": { + "name": "trigger_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'UTC'" + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "infra_retry_count": { + "name": "infra_retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "disabled_reason": { + "name": "disabled_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_failed_at": { + "name": "last_failed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'workflow'" + }, + "job_title": { + "name": "job_title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "lifecycle": { + "name": "lifecycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'persistent'" + }, + "success_condition": { + "name": "success_condition", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "max_runs": { + "name": "max_runs", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "source_chat_id": { + "name": "source_chat_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_task_name": { + "name": "source_task_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_user_id": { + "name": "source_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_scope": { + "name": "secret_scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'all'" + }, + "mounted_secrets": { + "name": "mounted_secrets", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "job_history": { + "name": "job_history", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "contexts": { + "name": "contexts", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "excluded_dates": { + "name": "excluded_dates", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "run_budget_usd": { + "name": "run_budget_usd", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_schedule_workflow_block_deployment_unique": { + "name": "workflow_schedule_workflow_block_deployment_unique", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_workflow_deployment_idx": { + "name": "workflow_schedule_workflow_deployment_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_archived_at_partial_idx": { + "name": "workflow_schedule_archived_at_partial_idx", + "columns": [ + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_workflow_schedule_on_source_workspace_id_source_t_c07f3bba6": { + "name": "idx_workflow_schedule_on_source_workspace_id_source_t_c07f3bba6", + "columns": [ + { + "expression": "source_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "archived_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_due_workflow_idx": { + "name": "workflow_schedule_due_workflow_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deployment_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL AND \"workflow_schedule\".\"status\" NOT IN ('disabled', 'completed') AND (\"workflow_schedule\".\"source_type\" = 'workflow' OR \"workflow_schedule\".\"source_type\" IS NULL)", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_schedule_due_job_idx": { + "name": "workflow_schedule_due_job_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workflow_schedule\".\"archived_at\" IS NULL AND \"workflow_schedule\".\"status\" NOT IN ('disabled', 'completed') AND \"workflow_schedule\".\"source_type\" = 'job'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_schedule_workflow_id_workflow_id_fk": { + "name": "workflow_schedule_workflow_id_workflow_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_deployment_version_id_workflow_deployment_version_id_fk": { + "name": "workflow_schedule_deployment_version_id_workflow_deployment_version_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow_deployment_version", + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_deployment_operation_id_workflow_deployment_operation_id_fk": { + "name": "workflow_schedule_deployment_operation_id_workflow_deployment_operation_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workflow_deployment_operation", + "columnsFrom": ["deployment_operation_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workflow_schedule_source_user_id_user_id_fk": { + "name": "workflow_schedule_source_user_id_user_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "user", + "columnsFrom": ["source_user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_schedule_source_workspace_id_workspace_id_fk": { + "name": "workflow_schedule_source_workspace_id_workspace_id_fk", + "tableFrom": "workflow_schedule", + "tableTo": "workspace", + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_source_meta": { + "name": "workflow_source_meta", + "schema": "", + "columns": { + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "meta": { + "name": "meta", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workflow_source_meta_workflow_id_workflow_id_fk": { + "name": "workflow_source_meta_workflow_id_workflow_id_fk", + "tableFrom": "workflow_source_meta", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_subflows": { + "name": "workflow_subflows", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workflow_id": { + "name": "workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_subflows_workflow_type_idx": { + "name": "workflow_subflows_workflow_type_idx", + "columns": [ + { + "expression": "workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_subflows_workflow_id_workflow_id_fk": { + "name": "workflow_subflows_workflow_id_workflow_id_fk", + "tableFrom": "workflow_subflows", + "tableTo": "workflow", + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_test": { + "name": "workflow_test", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body_file_id": { + "name": "body_file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cases": { + "name": "cases", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'" + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workflow_test_workspace_name_unique": { + "name": "workflow_test_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workflow_test\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workflow_test_body_file_unique": { + "name": "workflow_test_body_file_unique", + "columns": [ + { + "expression": "body_file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_test_workspace_id_workspace_id_fk": { + "name": "workflow_test_workspace_id_workspace_id_fk", + "tableFrom": "workflow_test", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_body_file_id_workspace_files_id_fk": { + "name": "workflow_test_body_file_id_workspace_files_id_fk", + "tableFrom": "workflow_test", + "tableTo": "workspace_files", + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workflow_test_created_by_user_id_user_id_fk": { + "name": "workflow_test_created_by_user_id_user_id_fk", + "tableFrom": "workflow_test", + "tableTo": "user", + "columnsFrom": ["created_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workflow_test_run": { + "name": "workflow_test_run", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "test_id": { + "name": "test_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "passed": { + "name": "passed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "failed": { + "name": "failed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "skipped": { + "name": "skipped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "report": { + "name": "report", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ran_against": { + "name": "ran_against", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "progress": { + "name": "progress", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "triggered_by_actor": { + "name": "triggered_by_actor", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "triggered_by_user_id": { + "name": "triggered_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workflow_test_run_test_version_started_idx": { + "name": "workflow_test_run_test_version_started_idx", + "columns": [ + { + "expression": "test_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workflow_test_run_test_id_workflow_test_id_fk": { + "name": "workflow_test_run_test_id_workflow_test_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "workflow_test", + "columnsFrom": ["test_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_run_workspace_id_workspace_id_fk": { + "name": "workflow_test_run_workspace_id_workspace_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workflow_test_run_triggered_by_user_id_user_id_fk": { + "name": "workflow_test_run_triggered_by_user_id_user_id_fk", + "tableFrom": "workflow_test_run", + "tableTo": "user", + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workflow_test_run_version_check": { + "name": "workflow_test_run_version_check", + "value": "\"workflow_test_run\".\"version\" IN ('draft', 'deployed')" + }, + "workflow_test_run_status_check": { + "name": "workflow_test_run_status_check", + "value": "\"workflow_test_run\".\"status\" IN ('running', 'passed', 'failed', 'error')" + }, + "workflow_test_run_completed_check": { + "name": "workflow_test_run_completed_check", + "value": "(\"workflow_test_run\".\"status\" = 'running') = (\"workflow_test_run\".\"completed_at\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workload_identity_pending_subject": { + "name": "workload_identity_pending_subject", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "workload_identity_pending_subject_subject_unique": { + "name": "workload_identity_pending_subject_subject_unique", + "columns": [ + { + "expression": "subject", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workload_identity_pending_subject_issuer_idx": { + "name": "workload_identity_pending_subject_issuer_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workload_identity_pending_subject_user_id_idx": { + "name": "workload_identity_pending_subject_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workload_identity_pending_subject_workspace_id_workspace_id_fk": { + "name": "workload_identity_pending_subject_workspace_id_workspace_id_fk", + "tableFrom": "workload_identity_pending_subject", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workload_identity_pending_subject_user_id_user_id_fk": { + "name": "workload_identity_pending_subject_user_id_user_id_fk", + "tableFrom": "workload_identity_pending_subject", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace": { + "name": "workspace", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'#33C482'" + }, + "logo_url": { + "name": "logo_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_scope_key": { + "name": "organization_scope_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END", + "type": "stored" + } + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_mode": { + "name": "workspace_mode", + "type": "workspace_mode", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'grandfathered_shared'" + }, + "billed_account_user_id": { + "name": "billed_account_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_used_bytes": { + "name": "storage_used_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "allow_personal_api_keys": { + "name": "allow_personal_api_keys", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "inbox_enabled": { + "name": "inbox_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "inbox_address": { + "name": "inbox_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbox_provider_id": { + "name": "inbox_provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbox_secret_scope": { + "name": "inbox_secret_scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'all'" + }, + "inbox_mounted_secrets": { + "name": "inbox_mounted_secrets", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "organization_assigned_at": { + "name": "organization_assigned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "forked_from_workspace_id": { + "name": "forked_from_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fork_sync_new_workflows_excluded": { + "name": "fork_sync_new_workflows_excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_owner_id_idx": { + "name": "workspace_owner_id_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_organization_id_idx": { + "name": "workspace_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_billed_account_user_id_idx": { + "name": "workspace_billed_account_user_id_idx", + "columns": [ + { + "expression": "billed_account_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_project_id_id_idx": { + "name": "workspace_project_id_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_mode_idx": { + "name": "workspace_mode_idx", + "columns": [ + { + "expression": "workspace_mode", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_forked_from_workspace_id_idx": { + "name": "workspace_forked_from_workspace_id_idx", + "columns": [ + { + "expression": "forked_from_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_inbox_provider_id_idx": { + "name": "workspace_inbox_provider_id_idx", + "columns": [ + { + "expression": "inbox_provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace\".\"inbox_provider_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_owner_id_user_id_fk": { + "name": "workspace_owner_id_user_id_fk", + "tableFrom": "workspace", + "tableTo": "user", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_organization_id_organization_id_fk": { + "name": "workspace_organization_id_organization_id_fk", + "tableFrom": "workspace", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_project_id_project_id_fk": { + "name": "workspace_project_id_project_id_fk", + "tableFrom": "workspace", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "workspace_billed_account_user_id_user_id_fk": { + "name": "workspace_billed_account_user_id_user_id_fk", + "tableFrom": "workspace", + "tableTo": "user", + "columnsFrom": ["billed_account_user_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workspace_forked_from_workspace_id_workspace_id_fk": { + "name": "workspace_forked_from_workspace_id_workspace_id_fk", + "tableFrom": "workspace", + "tableTo": "workspace", + "columnsFrom": ["forked_from_workspace_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_project_organization_fk": { + "name": "workspace_project_organization_fk", + "tableFrom": "workspace", + "tableTo": "project", + "columnsFrom": ["project_id", "organization_scope_key"], + "columnsTo": ["id", "organization_scope_key"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "workspace_fork_project_fk": { + "name": "workspace_fork_project_fk", + "tableFrom": "workspace", + "tableTo": "workspace", + "columnsFrom": ["forked_from_workspace_id", "project_id"], + "columnsTo": ["id", "project_id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "workspace_id_project_unique": { + "name": "workspace_id_project_unique", + "nullsNotDistinct": false, + "columns": ["id", "project_id"] + } + }, + "policies": {}, + "checkConstraints": { + "workspace_storage_used_bytes_non_negative": { + "name": "workspace_storage_used_bytes_non_negative", + "value": "\"workspace\".\"storage_used_bytes\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.workspace_byok_keys": { + "name": "workspace_byok_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_byok_workspace_provider_idx": { + "name": "workspace_byok_workspace_provider_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_byok_keys_workspace_id_workspace_id_fk": { + "name": "workspace_byok_keys_workspace_id_workspace_id_fk", + "tableFrom": "workspace_byok_keys", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_byok_keys_created_by_user_id_fk": { + "name": "workspace_byok_keys_created_by_user_id_fk", + "tableFrom": "workspace_byok_keys", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_environment": { + "name": "workspace_environment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "variables": { + "name": "variables", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_environment_workspace_unique": { + "name": "workspace_environment_workspace_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_environment_workspace_id_workspace_id_fk": { + "name": "workspace_environment_workspace_id_workspace_id_fk", + "tableFrom": "workspace_environment", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file": { + "name": "workspace_file", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_file_workspace_id_idx": { + "name": "workspace_file_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_deleted_at_idx": { + "name": "workspace_file_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_workspace_deleted_partial_idx": { + "name": "workspace_file_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_uploaded_by_idx": { + "name": "workspace_file_uploaded_by_idx", + "columns": [ + { + "expression": "uploaded_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_workspace_id_workspace_id_fk": { + "name": "workspace_file_workspace_id_workspace_id_fk", + "tableFrom": "workspace_file", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_uploaded_by_user_id_fk": { + "name": "workspace_file_uploaded_by_user_id_fk", + "tableFrom": "workspace_file", + "tableTo": "user", + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "workspace_file_key_unique": { + "name": "workspace_file_key_unique", + "nullsNotDistinct": false, + "columns": ["key"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_collab_state": { + "name": "workspace_file_collab_state", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "doc_state": { + "name": "doc_state", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_file_collab_state_file_id_workspace_files_id_fk": { + "name": "workspace_file_collab_state_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_collab_state", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_search_backfill": { + "name": "workspace_file_search_backfill", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "after_workspace_id": { + "name": "after_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_entity_type": { + "name": "after_entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_entity_id": { + "name": "after_entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "after_file_id": { + "name": "after_file_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_search_build": { + "name": "workspace_file_search_build", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "artifact_key": { + "name": "artifact_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_file_search_build_file_idx": { + "name": "workspace_file_search_build_file_idx", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_build_cleanup_idx": { + "name": "workspace_file_search_build_cleanup_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_build\".\"expires_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_build_owner_check": { + "name": "file_search_build_owner_check", + "value": "(\"workspace_file_search_build\".\"entity_type\" IS NULL AND \"workspace_file_search_build\".\"entity_id\" IS NULL AND \"workspace_file_search_build\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_build\".\"entity_type\" = 'workspace' AND \"workspace_file_search_build\".\"entity_id\" = \"workspace_file_search_build\".\"workspace_id\") OR (\"workspace_file_search_build\".\"entity_type\" = 'project' AND length(\"workspace_file_search_build\".\"entity_id\") > 0 AND \"workspace_file_search_build\".\"workspace_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_search_chunk": { + "name": "workspace_file_search_chunk", + "schema": "", + "columns": { + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "line_start": { + "name": "line_start", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "fragment": { + "name": "fragment", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "overlap": { + "name": "overlap", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "file_search_chunk_owner_content_idx": { + "name": "file_search_chunk_owner_content_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "content", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_chunk\".\"entity_type\" = 'project'", + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "workspace_file_search_chunk_line_idx": { + "name": "workspace_file_search_chunk_line_idx", + "columns": [ + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "line_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ordinal", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_chunk_content_idx": { + "name": "workspace_file_search_chunk_content_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "content", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + } + }, + "foreignKeys": { + "workspace_file_search_chunk_build_id_workspace_file_search_build_id_fk": { + "name": "workspace_file_search_chunk_build_id_workspace_file_search_build_id_fk", + "tableFrom": "workspace_file_search_chunk", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_file_search_chunk_pk": { + "name": "workspace_file_search_chunk_pk", + "columns": ["build_id", "ordinal"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_chunk_owner_check": { + "name": "file_search_chunk_owner_check", + "value": "(\"workspace_file_search_chunk\".\"entity_type\" IS NULL AND \"workspace_file_search_chunk\".\"entity_id\" IS NULL AND \"workspace_file_search_chunk\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_chunk\".\"entity_type\" = 'workspace' AND \"workspace_file_search_chunk\".\"entity_id\" = \"workspace_file_search_chunk\".\"workspace_id\") OR (\"workspace_file_search_chunk\".\"entity_type\" = 'project' AND length(\"workspace_file_search_chunk\".\"entity_id\") > 0 AND \"workspace_file_search_chunk\".\"workspace_id\" IS NULL)" + }, + "workspace_file_search_chunk_content_size": { + "name": "workspace_file_search_chunk_content_size", + "value": "octet_length(\"workspace_file_search_chunk\".\"content\") <= 8192" + }, + "workspace_file_search_chunk_position": { + "name": "workspace_file_search_chunk_position", + "value": "\"workspace_file_search_chunk\".\"ordinal\" >= 0 AND \"workspace_file_search_chunk\".\"line_start\" > 0 AND \"workspace_file_search_chunk\".\"overlap\" BETWEEN 0 AND 2" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_search_revision": { + "name": "workspace_file_search_revision", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "workspace_file_search_index_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "build_id": { + "name": "build_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "line_count": { + "name": "line_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "indexed_bytes": { + "name": "indexed_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "dispatched_at": { + "name": "dispatched_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "handoff_expires_at": { + "name": "handoff_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "build_started_at": { + "name": "build_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "abandoned_builds": { + "name": "abandoned_builds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_build_artifact_key": { + "name": "last_build_artifact_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "file_search_revision_owner_pending_idx": { + "name": "file_search_revision_owner_pending_idx", + "columns": [ + { + "expression": "coalesce(\"entity_type\", 'workspace')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"entity_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_content_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "file_search_revision_owner_status_idx": { + "name": "file_search_revision_owner_status_idx", + "columns": [ + { + "expression": "coalesce(\"entity_type\", 'workspace')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"entity_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_workspace_status_idx": { + "name": "workspace_file_search_revision_workspace_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_build_idx": { + "name": "workspace_file_search_revision_build_idx", + "columns": [ + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_pending_idx": { + "name": "workspace_file_search_revision_pending_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_content_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_revision_active_idx": { + "name": "workspace_file_search_revision_active_idx", + "columns": [ + { + "expression": "dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_revision\".\"status\" = 'pending' AND \"workspace_file_search_revision\".\"dispatched_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_search_revision_file_id_workspace_files_id_fk": { + "name": "workspace_file_search_revision_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_search_revision", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_search_revision_build_id_workspace_file_search_build_id_fk": { + "name": "workspace_file_search_revision_build_id_workspace_file_search_build_id_fk", + "tableFrom": "workspace_file_search_revision", + "tableTo": "workspace_file_search_build", + "columnsFrom": ["build_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "file_search_revision_owner_check": { + "name": "file_search_revision_owner_check", + "value": "(\"workspace_file_search_revision\".\"entity_type\" IS NULL AND \"workspace_file_search_revision\".\"entity_id\" IS NULL AND \"workspace_file_search_revision\".\"workspace_id\" IS NOT NULL) OR (\"workspace_file_search_revision\".\"entity_type\" = 'workspace' AND \"workspace_file_search_revision\".\"entity_id\" = \"workspace_file_search_revision\".\"workspace_id\") OR (\"workspace_file_search_revision\".\"entity_type\" = 'project' AND length(\"workspace_file_search_revision\".\"entity_id\") > 0 AND \"workspace_file_search_revision\".\"workspace_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_secret_provenance": { + "name": "workspace_file_secret_provenance", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entries": { + "name": "entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_file_secret_provenance_file_id_workspace_files_id_fk": { + "name": "workspace_file_secret_provenance_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_secret_provenance", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_file_secret_provenance_status_check": { + "name": "workspace_file_secret_provenance_status_check", + "value": "\"workspace_file_secret_provenance\".\"status\" IN ('exact', 'unknown', 'unrecorded')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_file_version": { + "name": "workspace_file_version", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "superseded_at": { + "name": "superseded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "workspace_file_version_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "author_user_ids": { + "name": "author_user_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "restored_from_version": { + "name": "restored_from_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_status": { + "name": "secret_provenance_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provenance_entries": { + "name": "secret_provenance_entries", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_file_version_file_version_unique": { + "name": "workspace_file_version_file_version_unique", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_key_unique": { + "name": "workspace_file_version_key_unique", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_workspace_id_idx": { + "name": "workspace_file_version_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_version_workspace_superseded_idx": { + "name": "workspace_file_version_workspace_superseded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "superseded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_version\".\"superseded_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_version_file_id_workspace_files_id_fk": { + "name": "workspace_file_version_file_id_workspace_files_id_fk", + "tableFrom": "workspace_file_version", + "tableTo": "workspace_files", + "columnsFrom": ["file_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_version_workspace_id_workspace_id_fk": { + "name": "workspace_file_version_workspace_id_workspace_id_fk", + "tableFrom": "workspace_file_version", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_file_version_provenance_status_check": { + "name": "workspace_file_version_provenance_status_check", + "value": "\"workspace_file_version\".\"secret_provenance_status\" IS NULL OR \"workspace_file_version\".\"secret_provenance_status\" IN ('exact', 'unknown', 'unrecorded')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_files": { + "name": "workspace_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "folder_id": { + "name": "folder_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "context": { + "name": "context", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "original_name": { + "name": "original_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "content_updated_at": { + "name": "content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "date_trunc('milliseconds', now())" + }, + "secret_provenance_version": { + "name": "secret_provenance_version", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_files_project_id_idx": { + "name": "workspace_files_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_project_folder_name_active_unique": { + "name": "workspace_files_project_folder_name_active_unique", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"project_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_key_active_unique": { + "name": "workspace_files_key_active_unique", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_folder_name_active_unique": { + "name": "workspace_files_workspace_folder_name_active_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_search_owner_keyset_idx": { + "name": "workspace_files_search_owner_keyset_idx", + "columns": [ + { + "expression": "(CASE WHEN \"project_id\" IS NOT NULL THEN 'project' ELSE 'workspace' END)", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"project_id\", \"workspace_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND ((\"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL) OR (\"workspace_files\".\"context\" = 'project' AND \"workspace_files\".\"project_id\" IS NOT NULL))", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_keyset_idx": { + "name": "workspace_files_workspace_active_keyset_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_uploaded_idx": { + "name": "workspace_files_workspace_active_uploaded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_active_updated_idx": { + "name": "workspace_files_workspace_active_updated_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_folder_uploaded_idx": { + "name": "workspace_files_workspace_folder_uploaded_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"folder_id\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "uploaded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_name_trgm_idx": { + "name": "workspace_files_workspace_name_trgm_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "original_name", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "gin_trgm_ops" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "gin", + "with": { + "fastupdate": "off" + } + }, + "workspace_files_workspace_display_name_idx": { + "name": "workspace_files_workspace_display_name_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "regexp_replace(regexp_replace(regexp_replace(normalize(\"original_name\", NFC), '^[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+|[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+$', '', 'g'), '[\\x01-\\x1f\\x7f]', '', 'g'), '[ \\t\\n\\v\\f\\r\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+', ' ', 'g')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NULL AND \"workspace_files\".\"context\" = 'workspace' AND \"workspace_files\".\"workspace_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, + "workspace_files_chat_display_name_unique": { + "name": "workspace_files_chat_display_name_unique", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "display_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"workspace_files\".\"context\" = 'mothership' AND \"workspace_files\".\"chat_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_organization_id_idx": { + "name": "workspace_files_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_key_idx": { + "name": "workspace_files_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_user_id_idx": { + "name": "workspace_files_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_id_idx": { + "name": "workspace_files_workspace_id_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_folder_id_idx": { + "name": "workspace_files_folder_id_idx", + "columns": [ + { + "expression": "folder_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_context_idx": { + "name": "workspace_files_context_idx", + "columns": [ + { + "expression": "context", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_chat_id_idx": { + "name": "workspace_files_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_deleted_at_idx": { + "name": "workspace_files_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_files_workspace_deleted_partial_idx": { + "name": "workspace_files_workspace_deleted_partial_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_files\".\"deleted_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_files_project_id_project_id_fk": { + "name": "workspace_files_project_id_project_id_fk", + "tableFrom": "workspace_files", + "tableTo": "project", + "columnsFrom": ["project_id"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "workspace_files_user_id_user_id_fk": { + "name": "workspace_files_user_id_user_id_fk", + "tableFrom": "workspace_files", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_workspace_id_workspace_id_fk": { + "name": "workspace_files_workspace_id_workspace_id_fk", + "tableFrom": "workspace_files", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_organization_id_organization_id_fk": { + "name": "workspace_files_organization_id_organization_id_fk", + "tableFrom": "workspace_files", + "tableTo": "organization", + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_files_folder_id_folder_id_fk": { + "name": "workspace_files_folder_id_folder_id_fk", + "tableFrom": "workspace_files", + "tableTo": "folder", + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_files_chat_id_copilot_chats_id_fk": { + "name": "workspace_files_chat_id_copilot_chats_id_fk", + "tableFrom": "workspace_files", + "tableTo": "copilot_chats", + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_files_owner_check": { + "name": "workspace_files_owner_check", + "value": "num_nonnulls(\"workspace_files\".\"workspace_id\", \"workspace_files\".\"project_id\", \"workspace_files\".\"organization_id\") <= 1" + }, + "workspace_files_workspace_binding_check": { + "name": "workspace_files_workspace_binding_check", + "value": "\"workspace_files\".\"context\" NOT IN ('workspace', 'chat', 'mothership', 'execution', 'workspace-logos') OR \"workspace_files\".\"workspace_id\" IS NOT NULL" + }, + "workspace_files_project_binding_check": { + "name": "workspace_files_project_binding_check", + "value": "(\"workspace_files\".\"project_id\" IS NOT NULL) = (\"workspace_files\".\"context\" = 'project') AND (\"workspace_files\".\"project_id\" IS NULL OR \"workspace_files\".\"chat_id\" IS NULL)" + }, + "workspace_files_organization_binding_check": { + "name": "workspace_files_organization_binding_check", + "value": "\"workspace_files\".\"organization_id\" IS NULL OR (\"workspace_files\".\"workspace_id\" IS NULL AND \"workspace_files\".\"context\" = 'knowledge-base' AND \"workspace_files\".\"folder_id\" IS NULL AND \"workspace_files\".\"chat_id\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.workspace_fork_block_map": { + "name": "workspace_fork_block_map", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_workflow_id": { + "name": "parent_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_block_id": { + "name": "parent_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_workflow_id": { + "name": "child_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_block_id": { + "name": "child_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_block_map_child_ws_parent_unique": { + "name": "workspace_fork_block_map_child_ws_parent_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_child_unique": { + "name": "workspace_fork_block_map_child_ws_child_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_parent_wf_idx": { + "name": "workspace_fork_block_map_child_ws_parent_wf_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_block_map_child_ws_child_wf_idx": { + "name": "workspace_fork_block_map_child_ws_child_wf_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "child_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_block_map_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_block_map_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_block_map", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_dependent_value": { + "name": "workspace_fork_dependent_value", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workflow_id": { + "name": "target_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_block_id": { + "name": "target_block_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sub_block_key": { + "name": "sub_block_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_dependent_value_field_unique": { + "name": "workspace_fork_dependent_value_field_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sub_block_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_dependent_value_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_dependent_value_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_dependent_value", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_promote_run": { + "name": "workspace_fork_promote_run", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_workspace_id": { + "name": "source_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workspace_id": { + "name": "target_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "direction": { + "name": "direction", + "type": "workspace_fork_promote_direction", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "snapshot": { + "name": "snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_promote_run_child_ws_target_unique": { + "name": "workspace_fork_promote_run_child_ws_target_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_promote_run_target_ws_idx": { + "name": "workspace_fork_promote_run_target_ws_idx", + "columns": [ + { + "expression": "target_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_promote_run_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_promote_run_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_promote_run", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_promote_run_created_by_user_id_fk": { + "name": "workspace_fork_promote_run_created_by_user_id_fk", + "tableFrom": "workspace_fork_promote_run", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_resource_map": { + "name": "workspace_fork_resource_map", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "workspace_fork_resource_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "parent_resource_id": { + "name": "parent_resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "child_resource_id": { + "name": "child_resource_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_fork_resource_map_child_type_parent_unique": { + "name": "workspace_fork_resource_map_child_type_parent_unique", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "parent_resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_resource_map_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_resource_map_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_resource_map", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_resource_map_created_by_user_id_fk": { + "name": "workspace_fork_resource_map_created_by_user_id_fk", + "tableFrom": "workspace_fork_resource_map", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_fork_workflow_sync": { + "name": "workspace_fork_workflow_sync", + "schema": "", + "columns": { + "deployment_operation_id": { + "name": "deployment_operation_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "child_workspace_id": { + "name": "child_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_workflow_id": { + "name": "source_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_workflow_id": { + "name": "target_workflow_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_deployment_version_id": { + "name": "source_deployment_version_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sequence": { + "name": "sequence", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "workspace_fork_workflow_sync_sequence_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "promote_run_id": { + "name": "promote_run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "activated_at": { + "name": "activated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "rollback_operation_id": { + "name": "rollback_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rolled_back_at": { + "name": "rolled_back_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_fork_workflow_sync_baseline_idx": { + "name": "workspace_fork_workflow_sync_baseline_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sequence", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_fork_workflow_sync\".\"activated_at\" IS NOT NULL AND \"workspace_fork_workflow_sync\".\"rolled_back_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_run_idx": { + "name": "workspace_fork_workflow_sync_run_idx", + "columns": [ + { + "expression": "promote_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_rollback_idx": { + "name": "workspace_fork_workflow_sync_rollback_idx", + "columns": [ + { + "expression": "rollback_operation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_fork_workflow_sync\".\"rollback_operation_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_source_idx": { + "name": "workspace_fork_workflow_sync_source_idx", + "columns": [ + { + "expression": "source_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_target_idx": { + "name": "workspace_fork_workflow_sync_target_idx", + "columns": [ + { + "expression": "target_workflow_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_fork_workflow_sync_child_workspace_idx": { + "name": "workspace_fork_workflow_sync_child_workspace_idx", + "columns": [ + { + "expression": "child_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_fork_workflow_sync_child_workspace_id_workspace_id_fk": { + "name": "workspace_fork_workflow_sync_child_workspace_id_workspace_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workspace", + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_workflow_sync_source_workflow_id_workflow_id_fk": { + "name": "workspace_fork_workflow_sync_source_workflow_id_workflow_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workflow", + "columnsFrom": ["source_workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_fork_workflow_sync_target_workflow_id_workflow_id_fk": { + "name": "workspace_fork_workflow_sync_target_workflow_id_workflow_id_fk", + "tableFrom": "workspace_fork_workflow_sync", + "tableTo": "workflow", + "columnsFrom": ["target_workflow_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_operation_receipt": { + "name": "workspace_operation_receipt", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "report": { + "name": "report", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_operation_receipt_request_unique": { + "name": "workspace_operation_receipt_request_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_operation_receipt_workspace_created_idx": { + "name": "workspace_operation_receipt_workspace_created_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_operation_receipt_workspace_id_workspace_id_fk": { + "name": "workspace_operation_receipt_workspace_id_workspace_id_fk", + "tableFrom": "workspace_operation_receipt", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_resource_key": { + "name": "workspace_resource_key", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "workspace_resource_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_resource_key_ws_kind_key_unique": { + "name": "workspace_resource_key_ws_kind_key_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_resource_key_ws_kind_resource_unique": { + "name": "workspace_resource_key_ws_kind_resource_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_resource_key_workspace_id_workspace_id_fk": { + "name": "workspace_resource_key_workspace_id_workspace_id_fk", + "tableFrom": "workspace_resource_key", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_resource_key_created_by_user_id_fk": { + "name": "workspace_resource_key_created_by_user_id_fk", + "tableFrom": "workspace_resource_key", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "workspace_resource_key_key_format": { + "name": "workspace_resource_key_key_format", + "value": "\"workspace_resource_key\".\"key\" ~ '^[a-z][a-z0-9_-]{0,63}$'" + }, + "workspace_resource_key_origin_check": { + "name": "workspace_resource_key_origin_check", + "value": "\"workspace_resource_key\".\"origin\" IN ('allocated', 'adopted', 'created')" + } + }, + "isRLSEnabled": false + }, + "public.workspace_sandbox": { + "name": "workspace_sandbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "language": { + "name": "language", + "type": "sandbox_language", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "dependencies": { + "name": "dependencies", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "cli_tools": { + "name": "cli_tools", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "system_packages": { + "name": "system_packages", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "spec_hash": { + "name": "spec_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_sandbox_workspace_name_unique": { + "name": "workspace_sandbox_workspace_name_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_sandbox_spec_hash_idx": { + "name": "workspace_sandbox_spec_hash_idx", + "columns": [ + { + "expression": "spec_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_sandbox_workspace_id_workspace_id_fk": { + "name": "workspace_sandbox_workspace_id_workspace_id_fk", + "tableFrom": "workspace_sandbox", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_sandbox_created_by_user_id_fk": { + "name": "workspace_sandbox_created_by_user_id_fk", + "tableFrom": "workspace_sandbox", + "tableTo": "user", + "columnsFrom": ["created_by"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_source_apply_lease": { + "name": "workspace_source_apply_lease", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "acquired_at": { + "name": "acquired_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "workspace_source_apply_lease_workspace_id_workspace_id_fk": { + "name": "workspace_source_apply_lease_workspace_id_workspace_id_fk", + "tableFrom": "workspace_source_apply_lease", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_source_staged_blob": { + "name": "workspace_source_staged_blob", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "consumed_at": { + "name": "consumed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "workspace_source_staged_blob_scope_hash_unique": { + "name": "workspace_source_staged_blob_scope_hash_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sha256", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_source_staged_blob_expires_at_idx": { + "name": "workspace_source_staged_blob_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_source_staged_blob_workspace_id_workspace_id_fk": { + "name": "workspace_source_staged_blob_workspace_id_workspace_id_fk", + "tableFrom": "workspace_source_staged_blob", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_visit": { + "name": "workspace_visit", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visited_at": { + "name": "visited_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_visit_workspace_idx": { + "name": "workspace_visit_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_visit_user_id_user_id_fk": { + "name": "workspace_visit_user_id_user_id_fk", + "tableFrom": "workspace_visit", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_visit_workspace_id_workspace_id_fk": { + "name": "workspace_visit_workspace_id_workspace_id_fk", + "tableFrom": "workspace_visit", + "tableTo": "workspace", + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_visit_user_id_workspace_id_pk": { + "name": "workspace_visit_user_id_workspace_id_pk", + "columns": ["user_id", "workspace_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.api_key_access": { + "name": "api_key_access", + "schema": "public", + "values": ["read", "write"] + }, + "public.aws_marketplace_license_status": { + "name": "aws_marketplace_license_status", + "schema": "public", + "values": ["pending", "active", "inactive"] + }, + "public.aws_marketplace_usage_report_status": { + "name": "aws_marketplace_usage_report_status", + "schema": "public", + "values": ["pending", "reported", "rejected"] + }, + "public.background_work_kind": { + "name": "background_work_kind", + "schema": "public", + "values": ["deployment_side_effects", "fork_content_copy", "fork_sync", "fork_rollback"] + }, + "public.background_work_status_value": { + "name": "background_work_status_value", + "schema": "public", + "values": ["pending", "processing", "completed", "completed_with_warnings", "failed"] + }, + "public.billing_blocked_reason": { + "name": "billing_blocked_reason", + "schema": "public", + "values": ["payment_failed", "dispute"] + }, + "public.billing_entity_type": { + "name": "billing_entity_type", + "schema": "public", + "values": ["user", "organization"] + }, + "public.chat_type": { + "name": "chat_type", + "schema": "public", + "values": ["mothership", "copilot"] + }, + "public.copilot_async_tool_status": { + "name": "copilot_async_tool_status", + "schema": "public", + "values": ["pending", "running", "completed", "failed", "cancelled", "delivered"] + }, + "public.copilot_run_status": { + "name": "copilot_run_status", + "schema": "public", + "values": ["active", "paused_waiting_for_tool", "resuming", "complete", "error", "cancelled"] + }, + "public.copilot_tool_permission_decision": { + "name": "copilot_tool_permission_decision", + "schema": "public", + "values": ["allow", "allow_chat", "always_allow", "skip"] + }, + "public.credential_group_enrollment_status": { + "name": "credential_group_enrollment_status", + "schema": "public", + "values": ["invited", "delivery_failed", "in_progress", "completed", "revoked"] + }, + "public.credential_group_status": { + "name": "credential_group_status", + "schema": "public", + "values": ["active", "disabled"] + }, + "public.credential_member_role": { + "name": "credential_member_role", + "schema": "public", + "values": ["admin", "member"] + }, + "public.credential_member_status": { + "name": "credential_member_status", + "schema": "public", + "values": ["active", "pending", "revoked"] + }, + "public.credential_type": { + "name": "credential_type", + "schema": "public", + "values": [ + "oauth", + "managed_oauth", + "managed_mcp", + "env_workspace", + "env_personal", + "service_account", + "personal_token" + ] + }, + "public.data_drain_cadence": { + "name": "data_drain_cadence", + "schema": "public", + "values": ["every_15_minutes", "hourly", "daily"] + }, + "public.data_drain_destination": { + "name": "data_drain_destination", + "schema": "public", + "values": [ + "s3", + "gcs", + "azure_blob", + "sentinel", + "datadog", + "splunk", + "bigquery", + "snowflake", + "webhook" + ] + }, + "public.data_drain_run_status": { + "name": "data_drain_run_status", + "schema": "public", + "values": ["running", "success", "failed"] + }, + "public.data_drain_run_trigger": { + "name": "data_drain_run_trigger", + "schema": "public", + "values": ["cron", "manual"] + }, + "public.data_drain_source": { + "name": "data_drain_source", + "schema": "public", + "values": ["workflow_logs", "job_logs", "audit_logs", "copilot_chats", "copilot_runs"] + }, + "public.execution_large_value_reference_source": { + "name": "execution_large_value_reference_source", + "schema": "public", + "values": ["execution_log", "paused_snapshot"] + }, + "public.folder_resource_type": { + "name": "folder_resource_type", + "schema": "public", + "values": ["workflow", "file", "knowledge_base", "table"] + }, + "public.invitation_kind": { + "name": "invitation_kind", + "schema": "public", + "values": ["organization", "workspace"] + }, + "public.invitation_membership_intent": { + "name": "invitation_membership_intent", + "schema": "public", + "values": ["internal", "external"] + }, + "public.invitation_status": { + "name": "invitation_status", + "schema": "public", + "values": ["pending", "accepted", "rejected", "cancelled", "expired"] + }, + "public.managed_oauth_credential_status": { + "name": "managed_oauth_credential_status", + "schema": "public", + "values": ["active", "needs_reauth", "revoked"] + }, + "public.permission_type": { + "name": "permission_type", + "schema": "public", + "values": ["admin", "write", "read"] + }, + "public.sandbox_image_status": { + "name": "sandbox_image_status", + "schema": "public", + "values": ["pending", "building", "ready", "failed"] + }, + "public.sandbox_language": { + "name": "sandbox_language", + "schema": "public", + "values": ["javascript", "python"] + }, + "public.secret_usage_scope": { + "name": "secret_usage_scope", + "schema": "public", + "values": ["workspace", "personal"] + }, + "public.secret_usage_source": { + "name": "secret_usage_source", + "schema": "public", + "values": ["workflow", "copilot", "mcp"] + }, + "public.upload_session_method": { + "name": "upload_session_method", + "schema": "public", + "values": ["put", "multipart"] + }, + "public.upload_session_provider": { + "name": "upload_session_provider", + "schema": "public", + "values": ["local", "s3", "blob", "gcs"] + }, + "public.upload_session_purpose": { + "name": "upload_session_purpose", + "schema": "public", + "values": [ + "workspace_file", + "project_file", + "table_import", + "knowledge_import", + "knowledge_document", + "profile_picture", + "workspace_logo", + "organization_logo", + "mothership_attachment", + "execution_attachment" + ] + }, + "public.upload_session_status": { + "name": "upload_session_status", + "schema": "public", + "values": [ + "uploading", + "completing", + "finalizing", + "completed", + "aborting", + "aborted", + "failed", + "expired" + ] + }, + "public.usage_log_category": { + "name": "usage_log_category", + "schema": "public", + "values": ["model", "fixed", "tool", "model_unbilled"] + }, + "public.usage_log_source": { + "name": "usage_log_source", + "schema": "public", + "values": [ + "workflow", + "wand", + "copilot", + "workspace-chat", + "mcp_copilot", + "mothership_block", + "knowledge-base", + "voice-input", + "enrichment", + "voice-output", + "api-tool", + "workflow-test" + ] + }, + "public.workspace_file_search_index_status": { + "name": "workspace_file_search_index_status", + "schema": "public", + "values": ["pending", "ready", "skipped", "failed"] + }, + "public.workspace_file_version_source": { + "name": "workspace_file_version_source", + "schema": "public", + "values": ["upload", "user", "api", "copilot", "workflow", "collab", "revert", "unknown"] + }, + "public.workspace_fork_promote_direction": { + "name": "workspace_fork_promote_direction", + "schema": "public", + "values": ["push", "pull"] + }, + "public.workspace_fork_resource_type": { + "name": "workspace_fork_resource_type", + "schema": "public", + "values": [ + "workflow", + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "knowledge_document", + "file", + "file_folder", + "mcp_server", + "workflow_mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ] + }, + "public.workspace_mode": { + "name": "workspace_mode", + "schema": "public", + "values": ["personal", "organization", "grandfathered_shared"] + }, + "public.workspace_resource_kind": { + "name": "workspace_resource_kind", + "schema": "public", + "values": [ + "credential", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ] + } + }, + "schemas": {}, + "sequences": { + "public.copilot_async_tool_calls_persist_seq": { + "name": "copilot_async_tool_calls_persist_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index df04a1de462..6ae9ef06ec4 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -3424,6 +3424,13 @@ "when": 1796325583945, "tag": "0489_credential_group_workflow_requests", "breakpoints": true + }, + { + "idx": 490, + "version": "7", + "when": 1796326788518, + "tag": "0490_credential_group_connection_requests", + "breakpoints": true } ] } diff --git a/packages/db/schema.ts b/packages/db/schema.ts index f35bdbebe8d..21e42aeca58 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7423,6 +7423,8 @@ export const credentialGroupEnrollment = pgTable( createdBy: text('created_by').references(() => user.id, { onDelete: 'set null' }), /** Set when a workflow's connection request created the row; admin invitations leave it null. */ requestedByWorkflowId: text('requested_by_workflow_id'), + /** Reminder emails sent for a workflow-requested enrollment after its first invitation. */ + connectionRequestReminders: integer('connection_request_reminders').notNull().default(0), createdAt: timestamp('created_at').notNull().defaultNow(), updatedAt: timestamp('updated_at').notNull().defaultNow(), }, @@ -7458,6 +7460,62 @@ export const credentialGroupEnrollment = pgTable( }) ) +/** + * The organization admin's policy for workflow connection requests, one row per Credential Group. + * Kept apart from the group's Access resource policy so neither document format depends on the + * other. No row means requests are off; `revision` guards concurrent admin edits. + */ +export const credentialGroupConnectionRequestPolicy = pgTable( + 'credential_group_connection_request_policy', + { + credentialGroupId: text('credential_group_id') + .primaryKey() + .references(() => credentialGroup.id, { onDelete: 'cascade' }), + policy: jsonb('policy').$type().notNull(), + revision: integer('revision').notNull().default(1), + updatedBy: text('updated_by').references(() => user.id, { onDelete: 'set null' }), + createdAt: timestamp('created_at').notNull().defaultNow(), + updatedAt: timestamp('updated_at').notNull().defaultNow(), + }, + (table) => ({ + revisionPositive: check( + 'credential_group_connection_request_policy_revision_check', + sql`${table.revision} >= 1` + ), + }) +) + +/** + * One row per accepted workflow connection request, whatever the person's state, so the daily cap + * counts every request and reminder alike. Rows are never read after the cap's 24-hour window. + */ +export const credentialGroupConnectionRequest = pgTable( + 'credential_group_connection_request', + { + id: text('id').primaryKey(), + credentialGroupId: text('credential_group_id') + .notNull() + .references(() => credentialGroup.id, { onDelete: 'cascade' }), + email: text('email').notNull(), + workspaceId: text('workspace_id').notNull(), + workflowId: text('workflow_id').notNull(), + createdAt: timestamp('created_at').notNull().defaultNow(), + }, + (table) => ({ + groupCreatedAtIdx: index('credential_group_connection_request_group_created_at_idx').on( + table.credentialGroupId, + table.createdAt + ), + groupEmailCreatedAtIdx: index( + 'credential_group_connection_request_group_email_created_at_idx' + ).on(table.credentialGroupId, table.email, table.createdAt), + normalizedEmail: check( + 'credential_group_connection_request_normalized_email_check', + sql`${table.email} = lower(btrim(${table.email})) AND length(${table.email}) BETWEEN 3 AND 320` + ), + }) +) + /** Personal Assistant preferences never confer access to another account or override organization policy. */ export const assistantToolPermission = pgTable( 'assistant_tool_permission', diff --git a/packages/testing/src/mocks/schema-tables.generated.ts b/packages/testing/src/mocks/schema-tables.generated.ts index da28ec84c67..146a7abbd18 100644 --- a/packages/testing/src/mocks/schema-tables.generated.ts +++ b/packages/testing/src/mocks/schema-tables.generated.ts @@ -1876,9 +1876,26 @@ export const GENERATED_SCHEMA_TABLES = { 'lastDeliveryError', 'createdBy', 'requestedByWorkflowId', + 'connectionRequestReminders', 'createdAt', 'updatedAt', ], + credentialGroupConnectionRequestPolicy: [ + 'credentialGroupId', + 'policy', + 'revision', + 'updatedBy', + 'createdAt', + 'updatedAt', + ], + credentialGroupConnectionRequest: [ + 'id', + 'credentialGroupId', + 'email', + 'workspaceId', + 'workflowId', + 'createdAt', + ], assistantToolPermission: [ 'organizationId', 'userId', From f678919f86bffe8544c83c37b410485e2d2655c7 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 13:52:12 -0600 Subject: [PATCH 07/26] fix(credential-groups): link lifecycle and Slack return audit findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Reinviting an enrollment the released app revoked (status only) now revokes every link into it first, so old emailed/self links cannot come back to life. - A legacy-column invitation with no link row (emailed by the released app during a deploy) is adopted as an 'email' link before the column is overwritten. - Delivery bookkeeping is guarded on invitedAt as well, so a slower, older send can no longer record delivery_failed (or sentAt) over a newer send. - 'self' and 'connect' links always expire after one hour; only an emailed link outlives its expiry once the enrollment is bound. The link outcome explains an expired connect link accordingly. invitation_expires_at (the admin-visible expiry) now tracks the newest emailed link only. - Removed the session-less bearer completeCredentialGroupEnrollment and getPublicCredentialGroupEnrollment (no production callers), their tests and mocks, plus a mock-asserting and a constant-restating test assertion. - The completion page no longer reads ?return=: a Slack destination is stored server-side bound to the signed-in user (completion-return) and only its opaque returnId travels in the redirect, from both the OAuth callback and the Submit path. On failure it offers Open Sim and Return to Slack. - Return allowlist narrowed to slack.com/app_redirect (app/team/channel only), slack://open, and slack://app?team=T…&id=A…. - The OAuth start route no longer validates the return URL itself; the use case and attempt state do. An overlong return (up to 8192) is ignored, not a 400. - Copy: revoked shows the title only, needs-new-link asks "an admin at {Org} for a new link", completion copy uses "accounts". - Login recognizes absolute same-origin /credential-groups/ callbacks and shows the divider in connect mode whenever another method follows social sign-in. --- apps/sim/app/(auth)/auth-redirect.ts | 14 ++ apps/sim/app/(auth)/login/login-form.tsx | 16 +- .../enroll/[token]/complete/route.ts | 27 ++-- .../enroll/[token]/oauth/[optionId]/route.ts | 5 +- .../credential-groups/enrollment-redirect.ts | 8 +- .../credential-groups/oauth-callback.test.ts | 38 +++++ .../api/credential-groups/oauth-callback.ts | 27 ++-- .../[publicId]/connect/page.tsx | 7 +- .../complete/completion-view.ts | 54 +++++++ .../app/credential-groups/complete/page.tsx | 73 ++++----- .../credential-groups/enroll/[token]/page.tsx | 16 +- .../sim/app/credential-groups/link-states.tsx | 13 +- .../lib/api/contracts/credential-groups.ts | 19 ++- .../enrollment-link-outcome.integration.ts | 13 +- .../enrollment-links.integration.ts | 108 +++++++++++-- .../slack-return.integration.ts | 86 ++++++++++ .../application/public-enrollment.ts | 26 ++- .../credential-groups/completion-return.ts | 71 ++++++++ .../lib/credential-groups/enrollments.test.ts | 95 ----------- apps/sim/lib/credential-groups/enrollments.ts | 153 ++++++++++-------- .../lib/credential-groups/return-url.test.ts | 23 ++- apps/sim/lib/credential-groups/return-url.ts | 70 ++++---- apps/sim/lib/credentials/managed-mcp.test.ts | 3 - .../lib/credentials/personal-tokens.test.ts | 8 +- .../credential-groups-enrollments.mock.ts | 4 - scripts/check-unused-exports.baseline.json | 1 - 26 files changed, 646 insertions(+), 332 deletions(-) create mode 100644 apps/sim/app/credential-groups/complete/completion-view.ts create mode 100644 apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts create mode 100644 apps/sim/lib/credential-groups/completion-return.ts diff --git a/apps/sim/app/(auth)/auth-redirect.ts b/apps/sim/app/(auth)/auth-redirect.ts index 4f178548c87..e11d8d742b4 100644 --- a/apps/sim/app/(auth)/auth-redirect.ts +++ b/apps/sim/app/(auth)/auth-redirect.ts @@ -98,6 +98,20 @@ export function isOAuthAuthorizationCallback(callbackUrl: string, origin: string } } +/** + * Whether sign-in continues into a Credential Group connect or enrollment page, written either as + * a path or as an absolute URL on this origin. + */ +export function isCredentialGroupConnectCallback(callbackUrl: string, origin: string): boolean { + if (!callbackUrl) return false + try { + const callback = new URL(callbackUrl, origin) + return callback.origin === origin && callback.pathname.startsWith('/credential-groups/') + } catch { + return false + } +} + interface AuthCrossLinkParams { /** Validated post-auth destination to carry over, or null to drop it. */ callbackUrl: string | null diff --git a/apps/sim/app/(auth)/login/login-form.tsx b/apps/sim/app/(auth)/login/login-form.tsx index 73e8f800589..989b10574c1 100644 --- a/apps/sim/app/(auth)/login/login-form.tsx +++ b/apps/sim/app/(auth)/login/login-form.tsx @@ -12,7 +12,11 @@ import { client } from '@/lib/auth/client' import { validateCallbackUrl } from '@/lib/core/security/input-validation' import { getBaseUrl } from '@/lib/core/utils/urls' import { quickValidateEmail } from '@/lib/messaging/email/validation' -import { DEFAULT_POST_AUTH_ROUTE, POST_AUTH_REDIRECT_STORAGE_KEY } from '@/app/(auth)/auth-redirect' +import { + DEFAULT_POST_AUTH_ROUTE, + isCredentialGroupConnectCallback, + POST_AUTH_REDIRECT_STORAGE_KEY, +} from '@/app/(auth)/auth-redirect' import { AuthDivider, AuthEmailInput, @@ -106,7 +110,9 @@ export default function LoginPage({ } const callbackUrl = isValidCallbackUrl ? callbackUrlParam! : DEFAULT_POST_AUTH_ROUTE /** Invitees connecting accounts mostly arrive from a link; Google and Microsoft come first. */ - const connectFlow = isValidCallbackUrl && callbackUrl.startsWith('/credential-groups/') + const connectFlow = + isValidCallbackUrl && + isCredentialGroupConnectCallback(callbackUrl, new URL(getBaseUrl()).origin) const [forgotPasswordOpen, setForgotPasswordOpen] = useState(false) const [forgotPasswordEmail, setForgotPasswordEmail] = useState('') @@ -442,8 +448,10 @@ export default function LoginPage({ )} {connectFlow && showBottomSection && socialButtons} - {connectFlow && emailPasswordEnabled && showBottomSection && ( - + {connectFlow && showDivider && ( + )} {showTopSSO && ( diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts index 7c1ffec4029..0fb791bc9c3 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts @@ -22,23 +22,26 @@ export const POST = withRouteHandler( const parsed = await parseRequest(completeCredentialGroupEnrollmentContract, request, context) if (!parsed.success) return parsed.response const { token } = parsed.data.params + const { return: returnUrl } = parsed.data.query + const unavailable = () => + createCredentialGroupEnrollmentRedirect(token, { + oauth: 'unavailable', + ...(returnUrl ? { return: returnUrl } : {}), + }) const principal = await authenticateCredentialGroupEnrollment(token) - if (!principal) { - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'unavailable' }) - } + if (!principal) return unavailable() const completion = await completePublicCredentialGroupEnrollment - .execute({ principal, input: {}, request }) + .execute({ principal, input: returnUrl ? { returnUrl } : {}, request }) .catch((error: unknown) => { if (asOrchestrationError(error)?.code === 'not_found') return null throw error }) - if (!completion) { - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'unavailable' }) - } - const { completed } = completion - if (completed === null) { - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'unavailable' }) - } - return createCredentialGroupCompletionRedirect() + if (!completion || completion.completed === null) return unavailable() + return createCredentialGroupCompletionRedirect( + undefined, + undefined, + undefined, + completion.completionReturnId + ) } ) diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts index ec10d2eadc5..6ba213f5d53 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts @@ -15,7 +15,6 @@ import { enforceCredentialGroupEnrollmentOAuthRateLimit, enforcePublicCredentialGroupOAuthStartIpRateLimit, } from '@/lib/credential-groups/rate-limit' -import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { createCredentialGroupEnrollmentRedirect } from '@/app/api/credential-groups/enrollment-redirect' export const dynamic = 'force-dynamic' @@ -33,8 +32,8 @@ export const GET = withRouteHandler( const parsed = await parseRequest(startCredentialGroupOAuthContract, request, context) if (!parsed.success) return limited ?? parsed.response const { token, optionId } = parsed.data.params - const { returnTo, return: rawReturnUrl } = parsed.data.query - const returnUrl = rawReturnUrl ? parseCredentialGroupReturnUrl(rawReturnUrl)?.href : undefined + const { returnTo, return: returnUrl } = parsed.data.query + /** Passed through as given: the use case and the enrollment page each keep only an allowed one. */ const focus: Record = { ...(returnTo ? { optionId, returnTo } : {}), ...(returnUrl ? { return: returnUrl } : {}), diff --git a/apps/sim/app/api/credential-groups/enrollment-redirect.ts b/apps/sim/app/api/credential-groups/enrollment-redirect.ts index 11a3afe45c4..43eadeeab8b 100644 --- a/apps/sim/app/api/credential-groups/enrollment-redirect.ts +++ b/apps/sim/app/api/credential-groups/enrollment-redirect.ts @@ -21,17 +21,21 @@ export function createCredentialGroupEnrollmentRedirect( }) } +/** + * Sends the person to the completion page. A Slack return travels only as `completionReturnId`, + * the opaque ID of a destination the server stored for them, never as a URL in the query. + */ export function createCredentialGroupCompletionRedirect( oauth?: CredentialGroupOAuthFailure, completionId?: string, organizationId?: string, - returnUrl?: string + completionReturnId?: string ): NextResponse { const query = new URLSearchParams() if (oauth) query.set('oauth', oauth) if (completionId) query.set('completionId', completionId) if (organizationId) query.set('organizationId', organizationId) - if (returnUrl) query.set('return', returnUrl) + if (completionReturnId) query.set('returnId', completionReturnId) return new NextResponse(null, { status: 303, headers: { diff --git a/apps/sim/app/api/credential-groups/oauth-callback.test.ts b/apps/sim/app/api/credential-groups/oauth-callback.test.ts index 1f118b2b028..dc25b3bafd9 100644 --- a/apps/sim/app/api/credential-groups/oauth-callback.test.ts +++ b/apps/sim/app/api/credential-groups/oauth-callback.test.ts @@ -268,3 +268,41 @@ describe('Integrations OAuth completion', () => { } ) }) + +describe('Slack return destination', () => { + const forgedReturn = 'https://slack.com/app_redirect?app=AFORGED' + + function callbackWithForgedReturn() { + return handleCredentialGroupOAuthCallback({ + request: createMockRequest({ + url: `https://sim.test/api/auth/oauth2/callback/github-repositories?state=cg_state&code=code-1&return=${encodeURIComponent(forgedReturn)}`, + }), + provider: 'github-repositories', + query: { state: 'cg_state', code: 'code-1' }, + limited: null, + }) + } + + beforeEach(() => { + mocks.authenticate.mockResolvedValue({ kind: 'credential_group_enrollment' }) + mocks.completeOAuth.mockResolvedValue({ connectedOptionId: attempt.optionId }) + }) + + it.each([ + { stored: undefined, expected: null }, + { stored: 'slack://open', expected: 'slack://open' }, + ])( + 'returns to $expected from the stored attempt, ignoring the callback query', + async ({ stored, expected }) => { + mocks.consumeAttempt.mockResolvedValueOnce({ + ...attempt, + returnTo: 'connect', + ...(stored ? { returnUrl: stored } : {}), + }) + const response = await callbackWithForgedReturn() + const destination = new URL(response.headers.get('location') ?? '', 'https://sim.test') + expect(destination.pathname).toBe('/credential-groups/enroll/invitation-token') + expect(destination.searchParams.get('return')).toBe(expected) + } + ) +}) diff --git a/apps/sim/app/api/credential-groups/oauth-callback.ts b/apps/sim/app/api/credential-groups/oauth-callback.ts index a991c887674..1a25ef698f3 100644 --- a/apps/sim/app/api/credential-groups/oauth-callback.ts +++ b/apps/sim/app/api/credential-groups/oauth-callback.ts @@ -7,6 +7,7 @@ import { internalSessionAuth } from '@/lib/api/server/routes' import { asOrchestrationError, statusForOrchestrationError } from '@/lib/core/orchestration/types' import { credentialGroupOAuthAttemptPrincipal } from '@/lib/credential-groups/application/enrollment-auth' import { completePublicCredentialGroupOAuth } from '@/lib/credential-groups/application/public-enrollment' +import { createCredentialGroupCompletionReturn } from '@/lib/credential-groups/completion-return' import { CredentialGroupOAuthStateVersionError } from '@/lib/credential-groups/oauth-attempt-version' import type { CredentialGroupOAuthFailure } from '@/lib/credential-groups/oauth-completion' import { consumeCredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' @@ -88,16 +89,21 @@ export async function handleCredentialGroupOAuthCallback({ attempt.returnTo === 'github-installation' && attempt.organizationId && attempt.completionId const returnOrganizationId = attempt.returnTo === 'integrations' ? attempt.organizationId : undefined - const failureRedirect = (oauth: CredentialGroupOAuthFailure) => + const completionRedirect = async (oauth?: CredentialGroupOAuthFailure) => + createCredentialGroupCompletionRedirect( + oauth, + attempt.completionId, + returnOrganizationId, + await createCredentialGroupCompletionReturn({ + userId: attempt.userId, + returnUrl: attempt.returnUrl, + }) + ) + const failureRedirect = async (oauth: CredentialGroupOAuthFailure) => installationSetup ? setupRedirect(oauth) : attempt.completionRedirect - ? createCredentialGroupCompletionRedirect( - oauth, - attempt.completionId, - returnOrganizationId, - attempt.returnUrl - ) + ? completionRedirect(oauth) : createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { ...focus, oauth }) if (limited) { return failureRedirect('rate_limited') @@ -126,12 +132,7 @@ export async function handleCredentialGroupOAuthCallback({ request, }) return attempt.completionRedirect - ? createCredentialGroupCompletionRedirect( - undefined, - attempt.completionId, - returnOrganizationId, - attempt.returnUrl - ) + ? completionRedirect() : createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { ...focus, connected: attempt.optionId, diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index b0d19a72130..f1bcbd860a2 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -122,12 +122,7 @@ export default async function CredentialGroupConnectPage({ ) } case 'revoked': - return ( - - ) + return case 'choose_option': { const integration = getCredentialGroupProviderService(target.provider).name return ( diff --git a/apps/sim/app/credential-groups/complete/completion-view.ts b/apps/sim/app/credential-groups/complete/completion-view.ts new file mode 100644 index 00000000000..1a975b861cd --- /dev/null +++ b/apps/sim/app/credential-groups/complete/completion-view.ts @@ -0,0 +1,54 @@ +import { isValidUuid } from '@sim/utils/id' +import { readCredentialGroupCompletionReturn } from '@/lib/credential-groups/completion-return' +import { + type CredentialGroupOAuthFailure, + isCredentialGroupOAuthFailure, +} from '@/lib/credential-groups/oauth-completion' +import { organizationRoutes } from '@/lib/navigation/paths' + +type CompletionSearchParams = Record + +export interface CredentialGroupCompletionView { + failure?: CredentialGroupOAuthFailure + /** The opener tab's correlation ID, for the cross-tab completion handoff. */ + completionId?: string + /** Back to the organization's Integrations page, for a connection started there. */ + integrationsHref?: string + /** A "Return to Slack" destination, only ever from server-held state bound to the viewer. */ + slackReturnHref?: string +} + +function single(value: string | string[] | undefined): string | undefined { + return typeof value === 'string' ? value : undefined +} + +/** + * Resolves what the completion page shows from its query and the signed-in viewer. A Slack + * destination comes only from `returnId`, an opaque ID the server stored for this viewer; a + * `return` URL in the query is never read. + */ +export async function resolveCredentialGroupCompletionView({ + searchParams, + userId, +}: { + searchParams: CompletionSearchParams + userId: string | undefined +}): Promise { + const oauth = searchParams.oauth + const completionId = single(searchParams.completionId) + const organizationId = single(searchParams.organizationId) + const slackReturnHref = await readCredentialGroupCompletionReturn({ + returnId: single(searchParams.returnId), + userId, + }) + return { + ...(oauth === undefined + ? {} + : { failure: isCredentialGroupOAuthFailure(oauth) ? oauth : 'failed' }), + ...(completionId && isValidUuid(completionId) ? { completionId } : {}), + ...(organizationId && organizationId.length <= 128 + ? { integrationsHref: organizationRoutes(encodeURIComponent(organizationId)).integrations } + : {}), + ...(slackReturnHref ? { slackReturnHref } : {}), + } +} diff --git a/apps/sim/app/credential-groups/complete/page.tsx b/apps/sim/app/credential-groups/complete/page.tsx index 37a9b6c45e2..7fe1b477c46 100644 --- a/apps/sim/app/credential-groups/complete/page.tsx +++ b/apps/sim/app/credential-groups/complete/page.tsx @@ -1,75 +1,68 @@ import { AuthLinkButton as ChipLink } from '@sim/auth-ui' -import { isValidUuid } from '@sim/utils/id' import type { Metadata } from 'next' -import { - CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES, - isCredentialGroupOAuthFailure, -} from '@/lib/credential-groups/oauth-completion' -import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' -import { APP_ENTRY_PATH, organizationRoutes } from '@/lib/navigation/paths' +import { getSession } from '@/lib/auth' +import { CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES } from '@/lib/credential-groups/oauth-completion' +import { APP_ENTRY_PATH } from '@/lib/navigation/paths' import { AuthHeader, AuthShell } from '@/app/(auth)/components' import { CredentialGroupCompletionHandoff } from '@/app/credential-groups/complete/completion-handoff' +import { resolveCredentialGroupCompletionView } from '@/app/credential-groups/complete/completion-view' export const metadata: Metadata = { title: 'Accounts connected', robots: { index: false, follow: false }, } +export const dynamic = 'force-dynamic' + export default async function CredentialGroupCompletePage({ searchParams, }: { - searchParams: Promise<{ - oauth?: string | string[] - completionId?: string | string[] - organizationId?: string | string[] - return?: string | string[] - }> + searchParams: Promise> }) { - const { oauth, completionId, organizationId, return: rawReturnUrl } = await searchParams - const failure = - oauth === undefined ? undefined : isCredentialGroupOAuthFailure(oauth) ? oauth : 'failed' - const returnHref = - typeof organizationId === 'string' && organizationId.length > 0 && organizationId.length <= 128 - ? organizationRoutes(encodeURIComponent(organizationId)).integrations - : undefined - /** Rendered only as a link the person clicks: no automatic hop to an external scheme. */ - const slackReturnHref = - typeof rawReturnUrl === 'string' ? parseCredentialGroupReturnUrl(rawReturnUrl)?.href : undefined + const session = await getSession() + const { failure, completionId, integrationsHref, slackReturnHref } = + await resolveCredentialGroupCompletionView({ + searchParams: await searchParams, + userId: session?.user.id, + }) const error = failure ? CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure] : undefined + /** Rendered only as links the person clicks: no automatic hop to an external scheme. */ + const appLink = + error || integrationsHref ? ( + + {integrationsHref ? 'Return to Integrations' : 'Open Sim'} + + ) : null + const slackLink = slackReturnHref ? ( + + Return to Slack + + ) : null return ( - {typeof completionId === 'string' && isValidUuid(completionId) && ( + {completionId && ( )} - {slackReturnHref ? ( -
- - Return to Slack - + {(appLink || slackLink) && ( +
+ {appLink} + {slackLink}
- ) : ( - (error || returnHref) && ( -
- - {returnHref ? 'Return to Integrations' : 'Open Sim'} - -
- ) )} ) diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index 98ac5b1666b..c701630a4f9 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -59,10 +59,10 @@ interface EnrollmentLinkProblemProps { function needsNewLinkCopy( outcome: Extract ): string { - const asker = outcome.inviterName ?? (outcome.organizationName || 'an admin') - return outcome.reason === 'expired' - ? `This link expired. Ask ${asker} for a new one.` - : `This link is no longer active. Ask ${asker} for a new one.` + const asker = + outcome.inviterName ?? + (outcome.organizationName ? `an admin at ${outcome.organizationName}` : 'an admin') + return `Ask ${asker} for a new link.` } /** Tells a signed-in person why their link did not open; unknown links stay generic. */ @@ -88,11 +88,7 @@ function EnrollmentLinkProblem({ ) case 'revoked': return ( - + ) case 'paused': return ( @@ -425,7 +421,7 @@ export default async function CredentialGroupEnrollmentPage({
) : ( diff --git a/apps/sim/app/credential-groups/link-states.tsx b/apps/sim/app/credential-groups/link-states.tsx index c2f1d1bb05d..375e5974c79 100644 --- a/apps/sim/app/credential-groups/link-states.tsx +++ b/apps/sim/app/credential-groups/link-states.tsx @@ -23,7 +23,8 @@ interface UnavailableInvitationProps { token?: string title?: string rateLimited?: boolean - message?: string + /** The line under the title; `null` when the title says it all. */ + message?: string | null recoveryHref?: string recoveryLabel?: string } @@ -44,10 +45,12 @@ export function UnavailableInvitation({
diff --git a/apps/sim/lib/api/contracts/credential-groups.ts b/apps/sim/lib/api/contracts/credential-groups.ts index 288ce4aa440..be5e59243e1 100644 --- a/apps/sim/lib/api/contracts/credential-groups.ts +++ b/apps/sim/lib/api/contracts/credential-groups.ts @@ -16,7 +16,7 @@ import { CREDENTIAL_GROUP_PROVIDER_IDS, CREDENTIAL_GROUP_STANDARD_OAUTH_PROVIDER_IDS, } from '@/lib/credential-groups/providers' -import { CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH } from '@/lib/credential-groups/return-url' +import { CREDENTIAL_GROUP_RETURN_QUERY_MAX_LENGTH } from '@/lib/credential-groups/return-url' export const credentialGroupProviderSchema = z.enum(CREDENTIAL_GROUP_PROVIDER_IDS) export const credentialGroupStatusSchema = z.enum(['active', 'disabled']) @@ -571,10 +571,22 @@ export const slackCredentialGroupConfigurationCallbackContract = defineRouteCont response: { mode: 'text' }, }) +/** + * A Slack destination to offer once the person is done. The use case keeps it only when it passes + * the return allowlist; an invalid or oversized value is ignored, never refused. + */ +const credentialGroupReturnQuerySchema = z + .string() + .max(CREDENTIAL_GROUP_RETURN_QUERY_MAX_LENGTH) + .optional() + +const completeCredentialGroupEnrollmentQuerySchema = z.object({ + return: credentialGroupReturnQuerySchema, +}) + export const startCredentialGroupOAuthQuerySchema = z.object({ returnTo: z.enum(['search', 'accounts', 'connect']).optional(), - /** A Slack destination; the server keeps it only when it passes the return allowlist. */ - return: z.string().max(CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH).optional(), + return: credentialGroupReturnQuerySchema, }) export type StartCredentialGroupOAuthQuery = z.output @@ -597,6 +609,7 @@ export const completeCredentialGroupEnrollmentContract = defineRouteContract({ method: 'POST', path: '/api/credential-groups/enroll/[token]/complete', params: publicCredentialGroupEnrollmentParamsSchema, + query: completeCredentialGroupEnrollmentQuerySchema, response: { mode: 'empty' }, }) diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts index 6c117908274..a5504cc1511 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts @@ -227,7 +227,7 @@ describe('explainCredentialGroupEnrollmentLink', () => { }) }) - it('never calls an expired link of a bound person expired', async () => { + it('never calls an expired emailed link of a bound person expired', async () => { const enrollmentToken = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) const token = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) await expect( @@ -235,6 +235,17 @@ describe('explainCredentialGroupEnrollmentLink', () => { ).resolves.toEqual({ kind: 'unavailable' }) }) + it('calls an expired connect link of a bound person expired', async () => { + const enrollmentToken = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) + const token = await seedLink(enrollmentToken, { + purpose: 'connect', + expiresAt: new Date(Date.now() - DAY_MS), + }) + await expect( + explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) + ).resolves.toMatchObject({ kind: 'needs_new_link', reason: 'expired' }) + }) + it('reports an unbound link expired by its own expiry, not the legacy column', async () => { const enrollmentToken = await seedEnrollment({ email: inviteeEmail }) const token = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts index 239298c9f96..2025e1fbb90 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts @@ -1,6 +1,7 @@ /** - * Enrollment links against real Postgres: issuing a link never invalidates another, expiry binds - * only an unbound enrollment, and disconnect or revocation kills every link. Only the email + * Enrollment links against real Postgres: issuing a link never invalidates another, an emailed + * link's expiry binds only an unbound enrollment while self and connect links always expire, and + * disconnect or revocation (by this app or the released one) kills every link. Only the email * transport and the provider code exchange are faked; the emailed link is read from what would * have been sent. */ @@ -26,6 +27,7 @@ import { completeAuthorizedCredentialGroupEnrollment, getCredentialGroupOAuthContextForEnrollment, inviteCredentialGroupEnrollment, + issueCredentialGroupConnectLink, resendCredentialGroupEnrollment, revokeCredentialGroupEnrollment, } from '@/lib/credential-groups/enrollments' @@ -40,6 +42,11 @@ const POLICY = { authorizationAppId: 'fixture-app', requiredScopes: ['read'], sc /** The last invitation link each recipient was emailed. */ const emailedLinks = new Map() +type SendResult = { success: boolean; message: string } + +/** Per-recipient delivery outcomes, consumed in order; a recipient with none is delivered to. */ +const pendingDeliveries = new Map>>() + vi.mock('@/lib/credential-groups/scoped-availability', () => ({ isScopedCredentialGroupsAvailable: async () => true, })) @@ -52,7 +59,8 @@ vi.mock('@/components/emails/credential-groups/render', () => ({ vi.mock('@/lib/messaging/email/mailer', () => ({ sendEmail: async (input: { to: string; html: string }) => { emailedLinks.set(input.to, input.html) - return { success: true, message: 'sent' } + const outcome = pendingDeliveries.get(input.to)?.shift() + return outcome ?? { success: true, message: 'sent' } }, })) @@ -262,23 +270,38 @@ describe('credential group enrollment links', () => { expect(await resolves(resent)).toBe(true) }) - it('lets a bound, completed person reuse an expired link', async () => { + it('lets a bound, completed person reuse an expired emailed link', async () => { const person = await createPerson() - const self = await selfEnroll(person.userId) - const identity = await authenticatePublicCredentialGroupEnrollment(self.token) + const emailed = await adminInvite(person.email) + const identity = await authenticatePublicCredentialGroupEnrollment(emailed.token) if (!identity) throw new Error('Fresh link did not resolve') + await bindCredentialGroupEnrollmentUser(identity, person.userId) await expect(completeAuthorizedCredentialGroupEnrollment(identity)).resolves.toMatchObject({ completed: true, }) - await expire(self.enrollmentId) + await expire(emailed.enrollmentId) - const later = await authenticatePublicCredentialGroupEnrollment(self.token) - expect(later).toMatchObject({ enrollmentId: self.enrollmentId, userId: person.userId }) + const later = await authenticatePublicCredentialGroupEnrollment(emailed.token) + expect(later).toMatchObject({ enrollmentId: emailed.enrollmentId, userId: person.userId }) if (!later) throw new Error('Expired link of a bound person did not resolve') await expect(bindCredentialGroupEnrollmentUser(later, person.userId)).resolves.toBeUndefined() }) + it('expires self and connect links even once the enrollment is bound', async () => { + const person = await createPerson() + const self = await selfEnroll(person.userId) + const connectToken = await issueCredentialGroupConnectLink(self.enrollmentId, DRIVE.id) + if (!connectToken) throw new Error('Connect link was not minted') + expect(await resolves(self.token)).toBe(true) + expect(await resolves(connectToken)).toBe(true) + + await expire(self.enrollmentId) + + expect(await resolves(self.token)).toBe(false) + expect(await resolves(connectToken)).toBe(false) + }) + it('rejects an expired link while the enrollment is unbound', async () => { const person = await createPerson() const emailed = await adminInvite(person.email) @@ -323,6 +346,73 @@ describe('credential group enrollment links', () => { expect(await resolves(self.token)).toBe(false) }) + it('kills links into an enrollment the pre-link app revoked when it is reinvited', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + const self = await selfEnroll(person.userId) + /** The released app revokes the enrollment row only; its links stay unrevoked. */ + await db + .update(credentialGroupEnrollment) + .set({ status: 'revoked', revokedAt: new Date() }) + .where(eq(credentialGroupEnrollment.id, emailed.enrollmentId)) + + const reinvited = await adminInvite(person.email) + + expect(reinvited.enrollmentId).toBe(emailed.enrollmentId) + expect(await resolves(reinvited.token)).toBe(true) + expect(await resolves(emailed.token)).toBe(false) + expect(await resolves(self.token)).toBe(false) + }) + + it('keeps an invitation the pre-link app emailed during a deploy working after a resend', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + const legacyToken = generateId() + await db + .update(credentialGroupEnrollment) + .set({ + invitationTokenHash: sha256Hex(legacyToken), + invitationExpiresAt: new Date(Date.now() + 60_000), + }) + .where(eq(credentialGroupEnrollment.id, emailed.enrollmentId)) + + const resent = await resend(emailed.enrollmentId, person.email) + + expect(await resolves(legacyToken)).toBe(true) + expect(await resolves(resent)).toBe(true) + expect(await resolves(emailed.token)).toBe(true) + }) + + it('never lets a slower, older send record its failure over a newer send', async () => { + const person = await createPerson() + const { enrollmentId } = await adminInvite(person.email) + let failOlderSend: (result: SendResult) => void = () => {} + pendingDeliveries.set(person.email, [ + new Promise((resolve) => { + failOlderSend = resolve + }), + ]) + + const olderSend = resendCredentialGroupEnrollment( + scope, + groupId, + enrollmentId, + adminId, + 'Admin' + ) + await vi.waitFor(() => expect(pendingDeliveries.get(person.email)).toHaveLength(0)) + await resendCredentialGroupEnrollment(scope, groupId, enrollmentId, adminId, 'Admin') + failOlderSend({ success: false, message: 'mailbox unavailable' }) + + await expect(olderSend).rejects.toMatchObject({ status: 409 }) + const [row] = await db + .select() + .from(credentialGroupEnrollment) + .where(eq(credentialGroupEnrollment.id, enrollmentId)) + expect(row).toMatchObject({ status: 'invited', lastDeliveryError: null }) + expect(row?.sentAt).not.toBeNull() + }) + it('resolves an invitation the pre-link app wrote during a deploy', async () => { const person = await createPerson() const token = generateId() diff --git a/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts b/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts new file mode 100644 index 00000000000..1ff2079724f --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts @@ -0,0 +1,86 @@ +/** + * The "Return to Slack" destination against real Redis: it survives the OAuth attempt round trip, + * and the completion page shows it only from a destination the server stored for the signed-in + * viewer, never from a `return` URL in its own query. + */ +import { generateId } from '@sim/utils/id' +import { describe, expect, it } from 'vitest' +import { createCredentialGroupCompletionReturn } from '@/lib/credential-groups/completion-return' +import { + consumeCredentialGroupOAuthAttempt, + createCredentialGroupOAuthAttempt, +} from '@/lib/credential-groups/oauth-state' +import { resolveCredentialGroupCompletionView } from '@/app/credential-groups/complete/completion-view' + +const SLACK_APP = 'slack://app?team=T123&id=A123' +const FORGED = 'https://slack.com/app_redirect?app=AFORGED' + +describe('Slack return destination', () => { + it('survives the OAuth attempt create and consume round trip', async () => { + const { state } = await createCredentialGroupOAuthAttempt({ + provider: 'google-drive', + organizationId: generateId(), + userId: generateId(), + email: 'person@example.com', + enrollmentId: generateId(), + credentialGroupId: generateId(), + optionId: 'option-drive', + authorizationAppId: 'google:app', + scopeVersion: 1, + requiredScopes: ['openid'], + redirectUri: 'https://sim.test/api/auth/oauth2/callback/google-drive', + invitationToken: generateId(), + returnTo: 'connect', + returnUrl: SLACK_APP, + }) + + await expect(consumeCredentialGroupOAuthAttempt(state)).resolves.toMatchObject({ + returnTo: 'connect', + returnUrl: SLACK_APP, + }) + }) + + it('shows no return button for a crafted completion link', async () => { + const view = await resolveCredentialGroupCompletionView({ + searchParams: { return: FORGED }, + userId: generateId(), + }) + + expect(view.slackReturnHref).toBeUndefined() + }) + + it('shows the destination the server stored for the viewer, and only to them', async () => { + const viewer = generateId() + const returnId = await createCredentialGroupCompletionReturn({ + userId: viewer, + returnUrl: SLACK_APP, + }) + if (!returnId) throw new Error('Completion return was not stored') + + const own = await resolveCredentialGroupCompletionView({ + searchParams: { returnId, return: FORGED }, + userId: viewer, + }) + const someoneElse = await resolveCredentialGroupCompletionView({ + searchParams: { returnId }, + userId: generateId(), + }) + const signedOut = await resolveCredentialGroupCompletionView({ + searchParams: { returnId }, + userId: undefined, + }) + + expect(own.slackReturnHref).toBe(SLACK_APP) + expect(someoneElse.slackReturnHref).toBeUndefined() + expect(signedOut.slackReturnHref).toBeUndefined() + }) + + it('stores nothing for a destination outside the allowlist', async () => { + await expect( + createCredentialGroupCompletionReturn({ + userId: generateId(), + returnUrl: 'https://evil.example/app_redirect?app=A1', + }) + ).resolves.toBeUndefined() + }) +}) diff --git a/apps/sim/lib/credential-groups/application/public-enrollment.ts b/apps/sim/lib/credential-groups/application/public-enrollment.ts index a9e3bc6330b..3ffab031e5a 100644 --- a/apps/sim/lib/credential-groups/application/public-enrollment.ts +++ b/apps/sim/lib/credential-groups/application/public-enrollment.ts @@ -10,6 +10,7 @@ import { sameResourceScope, } from '@/lib/core/resource-scope' import { credentialGroupEnrollmentOperations } from '@/lib/credential-groups/application/enrollment-operations' +import { createCredentialGroupCompletionReturn } from '@/lib/credential-groups/completion-return' import { bindCredentialGroupEnrollmentUser, completeAuthorizedCredentialGroupEnrollment, @@ -187,14 +188,29 @@ export const readPublicCredentialGroupEnrollment = defineAuthorizedCredentialGro } ) +interface CompletePublicCredentialGroupEnrollmentInput { + /** Raw `return` query value; kept for the completion page only when it is an allowed Slack destination. */ + returnUrl?: string +} + export const completePublicCredentialGroupEnrollment = defineAuthorizedCredentialGroupEnrollmentUseCase({ operation: credentialGroupEnrollmentOperations.complete, - resolveContext: ({ principal }) => resolvePublicEnrollmentContext(principal), - async execute({ context }) { - return { - completed: await completeEnrollment(context, context.enrollment.credentialGroupName), - } + resolveContext: ({ + principal, + }: { + principal: CredentialGroupEnrollmentPrincipal + input: CompletePublicCredentialGroupEnrollmentInput + }) => resolvePublicEnrollmentContext(principal), + async execute({ context, principal, input }) { + const completed = await completeEnrollment(context, context.enrollment.credentialGroupName) + const completionReturnId = completed + ? await createCredentialGroupCompletionReturn({ + userId: principal.userId, + returnUrl: input.returnUrl, + }) + : undefined + return { completed, ...(completionReturnId ? { completionReturnId } : {}) } }, }) diff --git a/apps/sim/lib/credential-groups/completion-return.ts b/apps/sim/lib/credential-groups/completion-return.ts new file mode 100644 index 00000000000..aa3cc9470ff --- /dev/null +++ b/apps/sim/lib/credential-groups/completion-return.ts @@ -0,0 +1,71 @@ +import { createLogger } from '@sim/logger' +import { sha256Hex } from '@sim/security/hash' +import { getErrorMessage } from '@sim/utils/errors' +import { generateId, isValidUuid } from '@sim/utils/id' +import { getRedisClient } from '@/lib/core/config/redis' +import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' + +/** + * Server-held "Return to Slack" destinations for the completion page. A connect flow that ends on + * `/credential-groups/complete` stores its validated return URL here, bound to the signed-in + * person, and passes only the opaque ID in the redirect; the page never reads a destination from + * its own query, so a crafted completion link cannot show a return button. + */ + +const logger = createLogger('CredentialGroupCompletionReturn') + +const COMPLETION_RETURN_TTL_MS = 30 * 60 * 1000 + +interface StoredCompletionReturn { + userId: string + returnUrl: string +} + +function completionReturnKey(returnId: string): string { + return `credential-group:completion-return:${sha256Hex(returnId)}` +} + +/** + * Stores where `userId` may return to once their connection finishes. Returns the opaque ID for + * the completion redirect, or undefined when there is no allowed destination to keep or it could + * not be stored. + */ +export async function createCredentialGroupCompletionReturn(input: { + userId: string + returnUrl: string | undefined +}): Promise { + const returnUrl = input.returnUrl ? parseCredentialGroupReturnUrl(input.returnUrl)?.href : null + if (!returnUrl || !input.userId) return undefined + const returnId = generateId() + const stored: StoredCompletionReturn = { userId: input.userId, returnUrl } + try { + await getRedisClient().set( + completionReturnKey(returnId), + JSON.stringify(stored), + 'PX', + COMPLETION_RETURN_TTL_MS + ) + return returnId + } catch (error) { + /** The connection already finished; losing the return button must not fail it. */ + logger.warn('Failed to store credential group completion return', { + error: getErrorMessage(error), + }) + return undefined + } +} + +/** The destination stored under `returnId` for `userId`, or undefined for anyone else. */ +export async function readCredentialGroupCompletionReturn(input: { + returnId: string | undefined + userId: string | undefined +}): Promise { + if (!input.returnId || !isValidUuid(input.returnId) || !input.userId) return undefined + const raw = await getRedisClient().get(completionReturnKey(input.returnId)) + if (!raw) return undefined + const stored: unknown = JSON.parse(raw) + if (!stored || typeof stored !== 'object') return undefined + const { userId, returnUrl } = stored as Partial + if (userId !== input.userId || typeof returnUrl !== 'string') return undefined + return parseCredentialGroupReturnUrl(returnUrl)?.href +} diff --git a/apps/sim/lib/credential-groups/enrollments.test.ts b/apps/sim/lib/credential-groups/enrollments.test.ts index 947f7fea68b..8822c073c79 100644 --- a/apps/sim/lib/credential-groups/enrollments.test.ts +++ b/apps/sim/lib/credential-groups/enrollments.test.ts @@ -42,7 +42,6 @@ vi.mock('@/lib/credential-groups/provider-registry', () => credentialGroupsProvi import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' import { bindCredentialGroupEnrollmentUser, - completeCredentialGroupEnrollment, createCredentialGroupSelfEnrollmentLink, deleteCredentialGroupEnrollment, getAuthorizedCredentialGroupOAuthContext, @@ -505,100 +504,6 @@ describe('deleteCredentialGroupEnrollment', () => { }) }) -describe('completeCredentialGroupEnrollment', () => { - beforeEach(() => { - resetDbChainMock() - }) - - it('returns unavailable when revocation wins before completion acquires the lifecycle lock', async () => { - queueTableRows(schemaMock.credentialGroupEnrollment, [ - { - enrollment: { ...ENROLLMENT, status: 'in_progress' }, - groupId: 'group-1', - groupName: 'Group', - groupStatus: 'active', - options: [ - { - id: 'option-1', - provider: 'gmail', - label: 'Gmail', - required: true, - status: 'active', - }, - ], - workspaceId: 'workspace-1', - workspaceName: 'Workspace', - workspaceOwnerId: 'owner-1', - inviterName: 'Inviter', - }, - ]) - queueTableRows(schemaMock.credentialGroupEnrollment, [ - { - status: 'revoked', - invitationTokenHash: ENROLLMENT.invitationTokenHash, - invitationExpiresAt: ENROLLMENT.invitationExpiresAt, - }, - ]) - - await expect(completeCredentialGroupEnrollment('invitation-token')).resolves.toBeNull() - - expect(dbChainMockFns.execute).toHaveBeenCalledTimes(1) - expect(dbChainMockFns.update).not.toHaveBeenCalled() - }) - - it('completes when the recipient skips every optional account', async () => { - queueTableRows(schemaMock.credentialGroupEnrollment, [ - { - enrollment: { ...ENROLLMENT, status: 'invited' }, - groupId: 'group-1', - groupName: 'Group', - groupStatus: 'active', - options: [ - { - id: 'option-1', - provider: 'gmail', - label: 'Gmail', - required: true, - status: 'active', - }, - ], - workspaceId: 'workspace-1', - workspaceName: 'Workspace', - workspaceOwnerId: 'owner-1', - inviterName: 'Inviter', - }, - ]) - queueTableRows(schemaMock.credentialGroupEnrollment, [ - { - status: 'invited', - invitationTokenHash: ENROLLMENT.invitationTokenHash, - invitationExpiresAt: ENROLLMENT.invitationExpiresAt, - }, - ]) - queueTableRows(schemaMock.credentialGroup, [ - { - status: 'active', - options: [ - { - id: 'option-1', - provider: 'gmail', - label: 'Gmail', - required: true, - status: 'active', - }, - ], - }, - ]) - dbChainMockFns.returning.mockResolvedValueOnce([{ id: ENROLLMENT.id }]) - - await expect(completeCredentialGroupEnrollment('invitation-token')).resolves.toBe(true) - - expect(dbChainMockFns.update).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment) - expect(dbChainMockFns.from).not.toHaveBeenCalledWith(schemaMock.credential) - expect(adapter.getPolicy).not.toHaveBeenCalled() - }) -}) - describe('enrollment context for session-authorized or consumed-attempt OAuth', () => { const identity = { workspaceId: 'workspace-1', diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 448e1857792..cf08afb8cc5 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -67,6 +67,8 @@ import { getFromEmailAddress } from '@/lib/messaging/email/utils' import { isSearchProviderEnabled } from '@/lib/sim-search/live/provider-rollout' const INVITATION_TTL_MS = 7 * 24 * 60 * 60 * 1000 +/** How long a `self` or `connect` link lives: it is opened in the sitting it was minted for. */ +const SESSION_LINK_TTL_MS = 60 * 60 * 1000 const DELIVERY_CONCURRENCY = 5 const MAX_ENROLLMENT_PAGE_SIZE = 100 const CONNECTION_SUMMARIES_PER_ENROLLMENT = (CREDENTIAL_GROUP_PROVIDER_IDS.length + 1) * 3 @@ -282,10 +284,12 @@ function hashInvitationToken(token: string): string { } /** - * Matches the enrollment row that `tokenHash` is a live link into: an unrevoked link, unexpired - * unless the enrollment is already bound to a user (from then on the signed-in user is the - * authority, not the link's age). A hash with no link row falls back to the enrollment's legacy - * column, which the pre-link app still writes during a deploy or rollback. + * Matches the enrollment row that `tokenHash` is a live link into: an unrevoked, unexpired link. + * Only an emailed link outlives its expiry, and only once the enrollment is bound to a user (from + * then on the signed-in user is the authority, not the email's age); `self` and `connect` links + * are minted for one sitting and always expire. A hash with no link row falls back to the + * enrollment's legacy column, an emailed invitation the pre-link app still writes during a + * deploy or rollback. */ export function liveEnrollmentLinkCondition(tokenHash: string, now = new Date()): SQL { const link = credentialGroupEnrollmentLink @@ -294,7 +298,7 @@ export function liveEnrollmentLinkCondition(tokenHash: string, now = new Date()) eq(link.enrollmentId, credentialGroupEnrollment.id), eq(link.tokenHash, tokenHash), isNull(link.revokedAt), - or(bound, gt(link.expiresAt, now)) + or(and(bound, eq(link.purpose, 'email')), gt(link.expiresAt, now)) )}) or (${and( eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), or(bound, gt(credentialGroupEnrollment.invitationExpiresAt, now)) @@ -561,6 +565,26 @@ async function getInvitationContext( } } +/** + * Gives the invitation in an enrollment's legacy column a link row when it has none, so that + * overwriting the column does not kill a link the released app emailed during a deploy. A revoked + * enrollment's adopted link is revoked with it. + */ +async function adoptLegacyInvitationLink(tx: DbTransaction, current: EnrollmentRow, now: Date) { + await tx + .insert(credentialGroupEnrollmentLink) + .values({ + id: generateId(), + enrollmentId: current.id, + tokenHash: current.invitationTokenHash, + purpose: 'email', + expiresAt: current.invitationExpiresAt, + revokedAt: current.status === 'revoked' || current.revokedAt ? now : null, + createdAt: current.invitedAt, + }) + .onConflictDoNothing({ target: credentialGroupEnrollmentLink.tokenHash }) +} + async function issueInvitation( context: InvitationContext, /** @@ -577,7 +601,9 @@ async function issueInvitation( const now = new Date() const token = generateId() const tokenHash = hashInvitationToken(token) - const expiresAt = new Date(now.getTime() + INVITATION_TTL_MS) + const expiresAt = new Date( + now.getTime() + (options.purpose === 'email' ? INVITATION_TTL_MS : SESSION_LINK_TTL_MS) + ) const issued = await db.transaction(async (tx) => { await lockCredentialGroupInvitationTarget(tx, context.groupId, email) @@ -615,19 +641,22 @@ async function issueInvitation( if (current?.status === 'revoked' && options.revokedEnrollment === 'reject') { throw new CredentialGroupEnrollmentError('Revoked enrollment cannot be resent', 409) } + if (current) { + await adoptLegacyInvitationLink(tx, current, now) + /** + * The released app revokes by status alone, so links into an enrollment it revoked may + * still be unrevoked; none of them may survive a reinvitation. + */ + if (current.status === 'revoked' || current.revokedAt) + await revokeCredentialGroupEnrollmentLinks(tx, current.id, now) + } const preservesProgress = current?.status === 'in_progress' || current?.status === 'completed' const nextStatus = preservesProgress ? current.status : ('invited' as const) - const linkValues = { - invitationTokenHash: tokenHash, - invitationExpiresAt: - current && current.invitationExpiresAt > expiresAt - ? current.invitationExpiresAt - : expiresAt, - updatedAt: now, - } + /** The legacy column mirrors the newest emailed link, the one an admin sees expire. */ const invitationValues = { - ...linkValues, + invitationTokenHash: tokenHash, + invitationExpiresAt: expiresAt, status: nextStatus, invitedAt: now, sentAt: null, @@ -635,23 +664,30 @@ async function issueInvitation( revokedAt: null, lastDeliveryError: null, createdBy: userId ?? null, + updatedAt: now, } - const [next] = current + const [next] = !current ? await tx - .update(credentialGroupEnrollment) - .set(options.purpose === 'email' ? invitationValues : linkValues) - .where(eq(credentialGroupEnrollment.id, current.id)) - .returning() - : await tx .insert(credentialGroupEnrollment) .values({ id: generateId(), credentialGroupId: context.groupId, email, ...invitationValues, + /** No email was sent, so the admin-facing invitation window is the default one. */ + ...(options.purpose === 'email' + ? {} + : { invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS) }), createdAt: now, }) .returning() + : options.purpose === 'email' + ? await tx + .update(credentialGroupEnrollment) + .set(invitationValues) + .where(eq(credentialGroupEnrollment.id, current.id)) + .returning() + : [current] if (!next) throw new Error('Credential group enrollment write returned no row') const [link] = await tx .insert(credentialGroupEnrollmentLink) @@ -674,8 +710,6 @@ async function issueInvitation( } } -const CONNECT_LINK_TTL_MS = 60 * 60 * 1000 - /** * Mints a short-lived link focused on one account option for an enrollment the caller already * matched to the signed-in person. Inserts a link row only: the enrollment's issuer, timestamps, @@ -707,7 +741,7 @@ export async function issueCredentialGroupConnectLink( tokenHash: hashInvitationToken(token), purpose: 'connect', optionId, - expiresAt: new Date(now.getTime() + CONNECT_LINK_TTL_MS), + expiresAt: new Date(now.getTime() + SESSION_LINK_TTL_MS), createdAt: now, }) return token @@ -802,14 +836,25 @@ export async function loadCredentialGroupConnectSubject(input: { } } -/** True while the link an invitation was sent with is unrevoked. */ -function enrollmentLinkStillLive(linkId: string): SQL { +/** + * True while an emailed invitation is still the enrollment's newest one, unrevoked and in the + * state it was issued in, so a slower send never records its outcome over a later send's. Only + * an emailed issuance moves `invitedAt`. + */ +function deliveryStillCurrent( + issued: Pick, + linkId: string +): SQL | undefined { const link = credentialGroupEnrollmentLink - return sql`exists (select 1 from ${link} where ${and( - eq(link.id, linkId), - eq(link.enrollmentId, credentialGroupEnrollment.id), - isNull(link.revokedAt) - )})` + return and( + eq(credentialGroupEnrollment.invitedAt, issued.invitedAt), + eq(credentialGroupEnrollment.status, issued.status), + sql`exists (select 1 from ${link} where ${and( + eq(link.id, linkId), + eq(link.enrollmentId, credentialGroupEnrollment.id), + isNull(link.revokedAt) + )})` + ) } async function sendInvitation( @@ -858,13 +903,7 @@ async function sendInvitation( lastDeliveryError: truncate(result.message, 500), updatedAt: new Date(), }) - .where( - and( - eq(credentialGroupEnrollment.id, issued.id), - enrollmentLinkStillLive(linkId), - eq(credentialGroupEnrollment.status, issued.status) - ) - ) + .where(and(eq(credentialGroupEnrollment.id, issued.id), deliveryStillCurrent(issued, linkId))) .returning({ id: credentialGroupEnrollment.id }) if (!failed) { throw new CredentialGroupEnrollmentError( @@ -878,13 +917,7 @@ async function sendInvitation( const [sent] = await db .update(credentialGroupEnrollment) .set({ sentAt: new Date(), lastDeliveryError: null, updatedAt: new Date() }) - .where( - and( - eq(credentialGroupEnrollment.id, issued.id), - enrollmentLinkStillLive(linkId), - eq(credentialGroupEnrollment.status, issued.status) - ) - ) + .where(and(eq(credentialGroupEnrollment.id, issued.id), deliveryStillCurrent(issued, linkId))) .returning() if (!sent) { throw new CredentialGroupEnrollmentError( @@ -1319,15 +1352,6 @@ export async function revokeCredentialGroupEnrollment( }) } -export async function getPublicCredentialGroupEnrollment( - token: string -): Promise { - const row = await resolvePublicEnrollmentRowByIdentity({ - invitationTokenHash: hashInvitationToken(token), - }) - return row ? buildPublicCredentialGroupEnrollment(row) : null -} - export async function getAuthorizedPublicCredentialGroupEnrollment( identity: PublicCredentialGroupEnrollmentIdentity, projection?: { optionId: string } @@ -1488,17 +1512,6 @@ async function buildPublicCredentialGroupEnrollment( } /** Finalizes an enrollment after the recipient finishes their optional account selections. */ -export async function completeCredentialGroupEnrollment(token: string): Promise { - const invitationTokenHash = hashInvitationToken(token) - const row = await resolvePublicEnrollmentRowByIdentity({ invitationTokenHash }) - if (!row) return null - const result = await completeResolvedCredentialGroupEnrollment( - row, - identityForPublicEnrollmentRow(row, invitationTokenHash) - ) - return result?.completed ?? null -} - export async function completeAuthorizedCredentialGroupEnrollment( identity: PublicCredentialGroupEnrollmentIdentity ): Promise { @@ -1706,7 +1719,10 @@ export interface CredentialGroupEnrollmentLinkRecord { email: string userId: string | null status: CredentialGroupEnrollmentStatus - /** Past its expiry while the enrollment has no bound user, the only time expiry applies. */ + /** + * Past its expiry, matching {@link liveEnrollmentLinkCondition}: a `self` or `connect` link + * always expires, an emailed one only while the enrollment has no bound user. + */ expired: boolean /** The enrollment itself was revoked by an admin. */ revoked: boolean @@ -1738,6 +1754,7 @@ export async function findCredentialGroupEnrollmentLinkRecord( legacyExpiresAt: credentialGroupEnrollment.invitationExpiresAt, revokedAt: credentialGroupEnrollment.revokedAt, linkExpiresAt: link.expiresAt, + linkPurpose: link.purpose, linkRevokedAt: link.revokedAt, groupStatus: credentialGroup.status, workspaceId: credentialGroup.workspaceId, @@ -1771,7 +1788,9 @@ export async function findCredentialGroupEnrollmentLinkRecord( email: row.email, userId: row.userId, status: row.status, - expired: !row.userId && expiresAt.getTime() <= Date.now(), + expired: + (!row.userId || (row.linkPurpose ?? 'email') !== 'email') && + expiresAt.getTime() <= Date.now(), revoked: row.status === 'revoked' || row.revokedAt !== null, linkRevoked: row.linkRevokedAt !== null, groupActive: row.groupStatus === 'active', diff --git a/apps/sim/lib/credential-groups/return-url.test.ts b/apps/sim/lib/credential-groups/return-url.test.ts index 1e39defe4d6..dca6a26ce7e 100644 --- a/apps/sim/lib/credential-groups/return-url.test.ts +++ b/apps/sim/lib/credential-groups/return-url.test.ts @@ -5,12 +5,9 @@ describe('parseCredentialGroupReturnUrl', () => { it.each([ 'https://slack.com/app_redirect?app=A123&team=T123', 'https://slack.com/app_redirect?channel=C123&team=T123', - 'https://acme.slack.com/archives/C123/p1700000000000100', - 'https://acme.enterprise.slack.com/', - 'https://app.slack.com/client/T123/D456#thread', + 'https://slack.com/app_redirect?app=A123', 'slack://app?team=T123&id=A123', - 'slack://open?team=T123', - 'slack://channel?team=T123&id=C123', + 'slack://open', ])('accepts the Slack destination %s', (raw) => { expect(parseCredentialGroupReturnUrl(raw)?.href).toBe(raw) }) @@ -52,6 +49,22 @@ describe('parseCredentialGroupReturnUrl', () => { ['a slack scheme with a port', 'slack://app:1?team=T1'], ['a slack scheme lookalike action', 'slack://application?team=T1'], ['a slack-like scheme', 'slacks://app?team=T1'], + ['a Slack workspace page', 'https://acme.slack.com/archives/C123/p1700000000000100'], + ['an enterprise Slack host', 'https://acme.enterprise.slack.com/'], + ['the Slack web client', 'https://app.slack.com/client/T123/D456'], + ['an app_redirect with no query', 'https://slack.com/app_redirect'], + ['an app_redirect with only a team', 'https://slack.com/app_redirect?team=T123'], + ['an app_redirect with another parameter', 'https://slack.com/app_redirect?app=A1&next=x'], + ['an app_redirect with a repeated parameter', 'https://slack.com/app_redirect?app=A1&app=A2'], + ['an app_redirect with an encoded value', 'https://slack.com/app_redirect?app=A%31'], + ['an app_redirect with a fragment', 'https://slack.com/app_redirect?app=A1#x'], + ['an app_redirect with an empty value', 'https://slack.com/app_redirect?app='], + ['a slack open link with a query', 'slack://open?team=T123'], + ['a slack channel link', 'slack://channel?team=T123&id=C123'], + ['a slack app link with its parameters swapped', 'slack://app?id=A123&team=T123'], + ['a slack app link with an extra parameter', 'slack://app?team=T123&id=A123&x=1'], + ['a slack app link with a lowercase ID', 'slack://app?team=t123&id=A123'], + ['a slack app link with a non-app ID', 'slack://app?team=T123&id=U123'], ['an overlong URL', `https://slack.com/app_redirect?app=${'A'.repeat(2048)}`], ['an empty string', ''], ])('rejects %s', (_label, raw) => { diff --git a/apps/sim/lib/credential-groups/return-url.ts b/apps/sim/lib/credential-groups/return-url.ts index b5562697a3f..3aa344844af 100644 --- a/apps/sim/lib/credential-groups/return-url.ts +++ b/apps/sim/lib/credential-groups/return-url.ts @@ -1,53 +1,49 @@ /** * The closed allowlist of places a connect flow may send someone back to once their account is - * connected. Only Slack is allowed: `https://slack.com/app_redirect`, any `https://*.slack.com` - * page, and the `slack://app|open|channel` deep links. + * connected. Only three Slack shapes are allowed: + * - `https://slack.com/app_redirect?…` with only `app`, `team` and `channel` query parameters + * - `slack://open` with no query + * - `slack://app?team=T…&id=A…` with exactly those two parameters * * The raw string is matched before it is parsed, so parser normalization (percent-decoding, * backslash folding, default-port stripping, IDNA) can never turn a rejected spelling into an - * accepted host. The result is only ever rendered as a link the person clicks, never followed by + * accepted one. The result is only ever rendered as a link the person clicks, never followed by * an automatic redirect. */ -export const CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH = 2048 +const CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH = 2048 -/** Printable ASCII only: no whitespace, control characters, or non-ASCII lookalikes. */ -const PRINTABLE_ASCII = /^[\x21-\x7e]+$/ -const SLACK_WEB_URL = - /^https:\/\/((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*slack\.com)(?[/?#][^\\]*)?$/ -const SLACK_APP_URL = /^slack:\/\/(app|open|channel)(\?[^#\\]*)?$/ +/** + * The longest `return` query value a route accepts at all. Anything over + * {@link CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH} is then ignored rather than refused, so an + * oversized value never turns a connect link into an error page. + */ +export const CREDENTIAL_GROUP_RETURN_QUERY_MAX_LENGTH = 8192 -/** Returns the parsed URL when `raw` is an allowed Slack destination, else `null`. */ -export function parseCredentialGroupReturnUrl(raw: string): URL | null { - if (raw.length === 0 || raw.length > CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH) return null - if (!PRINTABLE_ASCII.test(raw) || raw.includes('\\')) return null +const SLACK_ID = '[A-Z0-9]{1,32}' +const SLACK_APP_REDIRECT = /^https:\/\/slack\.com\/app_redirect\?(?[A-Za-z0-9=&]+)$/ +const SLACK_APP_REDIRECT_PARAMS = new Set(['app', 'team', 'channel']) +const SLACK_APP_REDIRECT_PARAM = new RegExp(`^(?[a-z]+)=${SLACK_ID}$`) +const SLACK_OPEN = 'slack://open' +const SLACK_APP = new RegExp(`^slack://app\\?team=T${SLACK_ID}&id=A${SLACK_ID}$`) - if (raw.startsWith('slack://')) { - const match = SLACK_APP_URL.exec(raw) - if (!match) return null - const url = URL.canParse(raw) ? new URL(raw) : null - return url && url.protocol === 'slack:' && url.host === match[1] && url.href === raw - ? url - : null +function isSlackAppRedirect(raw: string): boolean { + const query = SLACK_APP_REDIRECT.exec(raw)?.groups?.query + if (!query) return false + const seen = new Set() + for (const pair of query.split('&')) { + const key = SLACK_APP_REDIRECT_PARAM.exec(pair)?.groups?.key + if (!key || !SLACK_APP_REDIRECT_PARAMS.has(key) || seen.has(key)) return false + seen.add(key) } + return seen.has('app') || seen.has('channel') +} - const match = SLACK_WEB_URL.exec(raw) - if (!match) return null - const host = match[1] - if (host === 'slack.com' && !/^\/app_redirect(?:\?|$)/.test(match.groups?.rest ?? '')) { - return null - } +/** Returns the parsed URL when `raw` is an allowed Slack destination, else `null`. */ +export function parseCredentialGroupReturnUrl(raw: string): URL | null { + if (raw.length === 0 || raw.length > CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH) return null + if (raw !== SLACK_OPEN && !SLACK_APP.test(raw) && !isSlackAppRedirect(raw)) return null if (!URL.canParse(raw)) return null const url = new URL(raw) - if ( - url.protocol !== 'https:' || - url.username || - url.password || - url.port || - url.hostname !== host || - (host === 'slack.com' && url.pathname !== '/app_redirect') - ) { - return null - } - return url + return url.href === raw ? url : null } diff --git a/apps/sim/lib/credentials/managed-mcp.test.ts b/apps/sim/lib/credentials/managed-mcp.test.ts index 6e44d29afa0..f4ac9dd8008 100644 --- a/apps/sim/lib/credentials/managed-mcp.test.ts +++ b/apps/sim/lib/credentials/managed-mcp.test.ts @@ -88,9 +88,6 @@ describe('managed MCP grant persistence', () => { connectionId: expect.stringMatching(/^mcp-cg-/), }) expect(eq).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.userId, 'person-1') - expect(credentialGroupsEnrollmentsMockFns.mockLiveEnrollmentLinkCondition).toHaveBeenCalledWith( - input.invitationTokenHash - ) expect(eq).toHaveBeenCalledWith(schemaMock.mcpServers.oauthConfigVersion, 2) expect(dbChainMockFns.values).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/apps/sim/lib/credentials/personal-tokens.test.ts b/apps/sim/lib/credentials/personal-tokens.test.ts index 2c3a26fd94d..cc57d9cdf98 100644 --- a/apps/sim/lib/credentials/personal-tokens.test.ts +++ b/apps/sim/lib/credentials/personal-tokens.test.ts @@ -11,7 +11,7 @@ import { credentialGroupsSelfEnrollmentMock, credentialGroupsSelfEnrollmentMockFns, } from '@sim/testing/mocks/credential-groups-self-enrollment.mock' -import { eq, inArray, isNull } from 'drizzle-orm' +import { eq, isNull } from 'drizzle-orm' import { beforeEach, describe, expect, it, vi } from 'vitest' const hoisted = vi.hoisted(() => ({ @@ -82,12 +82,6 @@ function expectLiveBinding() { expect(eq).toHaveBeenCalledWith(schemaMock.user.id, 'owner') expect(eq).toHaveBeenCalledWith(schemaMock.user.emailVerified, true) expect(eq).toHaveBeenCalledWith(schemaMock.user.id, schemaMock.credentialGroupEnrollment.userId) - expect(inArray).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.status, [ - 'invited', - 'delivery_failed', - 'in_progress', - 'completed', - ]) expect(isNull).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.revokedAt) } diff --git a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts index 170ef88edd2..7b4d4d11d06 100644 --- a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts +++ b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts @@ -52,9 +52,7 @@ export const credentialGroupsEnrollmentsMockFns = { mockResendCredentialGroupEnrollment: vi.fn(), mockDeleteCredentialGroupEnrollment: vi.fn(), mockRevokeCredentialGroupEnrollment: vi.fn(), - mockGetPublicCredentialGroupEnrollment: vi.fn(), mockGetAuthorizedPublicCredentialGroupEnrollment: vi.fn(), - mockCompleteCredentialGroupEnrollment: vi.fn(), mockCompleteAuthorizedCredentialGroupEnrollment: vi.fn(), mockGetAuthorizedCredentialGroupOAuthContext: vi.fn(), mockGetCredentialGroupOAuthContextForEnrollment: vi.fn(), @@ -93,10 +91,8 @@ export const credentialGroupsEnrollmentsMock = { resendCredentialGroupEnrollment: fns.mockResendCredentialGroupEnrollment, deleteCredentialGroupEnrollment: fns.mockDeleteCredentialGroupEnrollment, revokeCredentialGroupEnrollment: fns.mockRevokeCredentialGroupEnrollment, - getPublicCredentialGroupEnrollment: fns.mockGetPublicCredentialGroupEnrollment, getAuthorizedPublicCredentialGroupEnrollment: fns.mockGetAuthorizedPublicCredentialGroupEnrollment, - completeCredentialGroupEnrollment: fns.mockCompleteCredentialGroupEnrollment, completeAuthorizedCredentialGroupEnrollment: fns.mockCompleteAuthorizedCredentialGroupEnrollment, getAuthorizedCredentialGroupOAuthContext: fns.mockGetAuthorizedCredentialGroupOAuthContext, getCredentialGroupOAuthContextForEnrollment: fns.mockGetCredentialGroupOAuthContextForEnrollment, diff --git a/scripts/check-unused-exports.baseline.json b/scripts/check-unused-exports.baseline.json index 4635383ead6..b7d1083eca3 100644 --- a/scripts/check-unused-exports.baseline.json +++ b/scripts/check-unused-exports.baseline.json @@ -4175,7 +4175,6 @@ "apps/sim/lib/credential-groups/credentials.ts#ManagedOAuthCredentialStatus", "apps/sim/lib/credential-groups/credentials.ts#loadCredentialGroupEnrollmentAccess", "apps/sim/lib/credential-groups/enrollments.ts#CredentialGroupEnrollmentStatus", - "apps/sim/lib/credential-groups/enrollments.ts#getPublicCredentialGroupEnrollment", "apps/sim/lib/credential-groups/limits.ts#ORGANIZATION_ACCOUNT_INDEXING_SOURCE_LIMIT", "apps/sim/lib/credential-groups/managed-mcp-connector-icons.ts#MANAGED_MCP_CONNECTOR_ICONS", "apps/sim/lib/credential-groups/provider-adapter.ts#PreparedCredentialGroupAuthorization", From 9cfee8e0cf5eb359451cc2fe434d9925d8afbe09 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 14:06:46 -0600 Subject: [PATCH 08/26] fix(credential-groups): connect page audit findings and wave seams - Connect page: an org member with no enrollment is enrolled only by a confirmation POST (/api/credential-groups/connect/[publicId]), never on GET, and only after the member self-enroll checks (integrations.manage permission group, finished setup); refusals read not_invited. A revocation racing self-enrollment reads revoked, other refusals unavailable; no second bind after self-enroll. - Focused links refuse Submit (/complete); the MCP start route keeps returnTo/return on every redirect back. Copy: stable-link unavailable message, masked email on wrong_account, "You can close this tab." beside Return to Slack. - Enrollments created without an emailed link (self-enroll, workflow request, disconnect) store an unissued placeholder in the legacy token column that no token hashes to, so link adoption skips it and pruning a session link cannot revive its token through the column. - Retention: the outbox processor prunes connection request rows after two days and self/connect links a day past expiry, in bounded batches, with indexes for both. - 0490 is replay-safe; connect URLs and the enroll handoff come from connect-url.ts. - Fix a TDZ read of `focused` in the enroll page's error handler. --- .../connect/[publicId]/route.ts | 67 +++++++ .../enroll/[token]/complete/route.ts | 11 +- .../enroll/[token]/mcp/[mcpServerId]/route.ts | 23 ++- .../[publicId]/connect/page.tsx | 71 ++++--- .../app/credential-groups/complete/page.tsx | 4 +- .../credential-groups/enroll/[token]/page.tsx | 2 +- .../lib/api/contracts/credential-groups.ts | 17 ++ apps/sim/lib/core/outbox/processor.test.ts | 9 + apps/sim/lib/core/outbox/processor.ts | 21 +- .../connect-target.integration.ts | 179 ++++++++++++++++-- .../__integration__/retention.integration.ts | 117 ++++++++++++ ...orkflow-connection-requests.integration.ts | 91 ++++++++- .../application/connect-target.ts | 111 +++++++++-- .../application/enrollment-link-outcome.ts | 2 +- .../personal-organization-accounts.ts | 5 +- .../application/public-enrollment.ts | 4 +- apps/sim/lib/credential-groups/connect-url.ts | 36 +++- .../credential-groups/connection-requests.ts | 12 +- apps/sim/lib/credential-groups/enrollments.ts | 29 ++- apps/sim/lib/credential-groups/retention.ts | 97 ++++++++++ ...0489_credential_group_enrollment_links.sql | 1 + ...0_credential_group_connection_requests.sql | 32 +++- .../db/migrations/meta/0489_snapshot.json | 16 ++ .../db/migrations/meta/0490_snapshot.json | 33 +++- packages/db/migrations/meta/_journal.json | 2 +- packages/db/schema.ts | 9 +- .../credential-groups-enrollments.mock.ts | 5 +- 27 files changed, 897 insertions(+), 109 deletions(-) create mode 100644 apps/sim/app/api/credential-groups/connect/[publicId]/route.ts create mode 100644 apps/sim/lib/credential-groups/__integration__/retention.integration.ts create mode 100644 apps/sim/lib/credential-groups/retention.ts diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts new file mode 100644 index 00000000000..52cf1f45e56 --- /dev/null +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts @@ -0,0 +1,67 @@ +import type { NextRequest } from 'next/server' +import { NextResponse } from 'next/server' +import { confirmCredentialGroupConnectContract } from '@/lib/api/contracts/credential-groups' +import { parseRequest } from '@/lib/api/server' +import { getSession } from '@/lib/auth' +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' +import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' +import { + buildCredentialGroupConnectHandoffPath, + buildCredentialGroupConnectPath, +} from '@/lib/credential-groups/connect-url' +import { + enforcePublicCredentialGroupIpRateLimit, + isCredentialGroupConnectUserRateLimited, +} from '@/lib/credential-groups/rate-limit' + +export const dynamic = 'force-dynamic' +export const runtime = 'nodejs' + +function seeOther(location: string): NextResponse { + return new NextResponse(null, { + status: 303, + headers: { Location: location, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' }, + }) +} + +/** + * The connect page's "Connect" button for an organization member with no enrollment: enrolls + * them and continues to the focused enrollment page. Any other outcome goes back to the connect + * page, which explains it, so this route never renders a state of its own. + */ +export const POST = withRouteHandler( + async (request: NextRequest, context: { params: Promise<{ publicId: string }> }) => { + const limited = await enforcePublicCredentialGroupIpRateLimit(request, 'metadata') + if (limited) return limited + + const parsed = await parseRequest(confirmCredentialGroupConnectContract, request, context) + if (!parsed.success) return parsed.response + const { publicId } = parsed.data.params + const { provider, optionId, return: returnValue } = parsed.data.query + const connectPath = buildCredentialGroupConnectPath({ + publicId, + provider, + optionId, + returnValue, + }) + + const session = await getSession() + if (!session?.user?.emailVerified) return seeOther(connectPath) + if (await isCredentialGroupConnectUserRateLimited(session.user.id)) return seeOther(connectPath) + + const target = await resolveCredentialGroupConnectTarget.execute({ + principal: { kind: 'session', userId: session.user.id, sessionId: session.session.id }, + input: { + publicId, + provider, + ...(optionId ? { optionId } : {}), + ...(returnValue ? { returnUrl: returnValue } : {}), + confirmSelfEnrollment: true, + }, + request, + }) + return seeOther( + target.kind === 'ready' ? buildCredentialGroupConnectHandoffPath(target) : connectPath + ) + } +) diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts index 0fb791bc9c3..59135e2dd08 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts @@ -5,6 +5,7 @@ import { asOrchestrationError } from '@/lib/core/orchestration/types' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { authenticateCredentialGroupEnrollment } from '@/lib/credential-groups/application/enrollment-auth' import { completePublicCredentialGroupEnrollment } from '@/lib/credential-groups/application/public-enrollment' +import { CredentialGroupLinkFocusError } from '@/lib/credential-groups/provider-adapter' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' import { createCredentialGroupCompletionRedirect, @@ -23,20 +24,22 @@ export const POST = withRouteHandler( if (!parsed.success) return parsed.response const { token } = parsed.data.params const { return: returnUrl } = parsed.data.query - const unavailable = () => + const backToEnrollment = (oauth: 'unavailable' | 'other_option') => createCredentialGroupEnrollmentRedirect(token, { - oauth: 'unavailable', + oauth, ...(returnUrl ? { return: returnUrl } : {}), }) const principal = await authenticateCredentialGroupEnrollment(token) - if (!principal) return unavailable() + if (!principal) return backToEnrollment('unavailable') const completion = await completePublicCredentialGroupEnrollment .execute({ principal, input: returnUrl ? { returnUrl } : {}, request }) .catch((error: unknown) => { + if (error instanceof CredentialGroupLinkFocusError) return 'focused' as const if (asOrchestrationError(error)?.code === 'not_found') return null throw error }) - if (!completion || completion.completed === null) return unavailable() + if (completion === 'focused') return backToEnrollment('other_option') + if (!completion || completion.completed === null) return backToEnrollment('unavailable') return createCredentialGroupCompletionRedirect( undefined, undefined, diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts index a556c5cc6d4..640e9761ef9 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts @@ -31,18 +31,22 @@ export const GET = withRouteHandler( const parsed = await parseRequest(startCredentialGroupMcpOAuthContract, request, context) if (!parsed.success) return limited ?? parsed.response const { token, mcpServerId } = parsed.data.params - if (limited) return createCredentialGroupEnrollmentRedirect(token, { oauth: 'rate_limited' }) + const { returnTo, return: returnUrl } = parsed.data.query + /** Passed back as given, like the OAuth start route: the enrollment page keeps only allowed ones. */ + const focus: Record = { + ...(returnTo ? { returnTo } : {}), + ...(returnUrl ? { return: returnUrl } : {}), + } + const backToEnrollment = (oauth: string) => + createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth }) + if (limited) return backToEnrollment('rate_limited') const principal = await authenticateCredentialGroupEnrollment(token) - if (!principal) { - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'unavailable' }) - } + if (!principal) return backToEnrollment('unavailable') const enrollmentLimited = await enforceCredentialGroupEnrollmentOAuthRateLimit( principal.enrollmentId ) - if (enrollmentLimited) { - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'rate_limited' }) - } + if (enrollmentLimited) return backToEnrollment('rate_limited') try { const { authorizationUrl } = await timedStep( @@ -60,12 +64,11 @@ export const GET = withRouteHandler( response.headers.set('Referrer-Policy', 'no-referrer') return response } catch (error) { - if (error instanceof CredentialGroupLinkFocusError) - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'other_option' }) + if (error instanceof CredentialGroupLinkFocusError) return backToEnrollment('other_option') logger.error('Failed to start managed MCP OAuth authorization', { error: getErrorMessage(error), }) - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'unavailable' }) + return backToEnrollment('unavailable') } } ) diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index f1bcbd860a2..c574f750cf1 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -1,9 +1,13 @@ -import { AuthLinkButton as ChipLink } from '@sim/auth-ui' +import { AuthButton as Chip, AuthLinkButton as ChipLink } from '@sim/auth-ui' import type { Metadata } from 'next' import { headers } from 'next/headers' import { redirect } from 'next/navigation' import { getSession } from '@/lib/auth' import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' +import { + buildCredentialGroupConnectHandoffPath, + buildCredentialGroupConnectPath, +} from '@/lib/credential-groups/connect-url' import { getCredentialGroupProviderService } from '@/lib/credential-groups/providers' import { enforcePublicCredentialGroupIpRateLimit, @@ -42,13 +46,14 @@ function getSearchParam( } const UNAVAILABLE_MESSAGE = - 'This link isn’t available. Ask the person or app that sent it for a new one.' + 'This link isn’t available. Ask whoever sent it to check it’s still set up.' /** * The secret-free link a workflow shows when someone has not connected an account yet. Signs the * person in, resolves their own enrollment, and hands off to the enrollment page with a * short-lived link focused on the one account asked for. Link unfurlers and prefetchers are never - * signed in, so they stop at the login redirect and mint nothing. + * signed in, so they stop at the login redirect and mint nothing. An organization member with no + * enrollment confirms with a button whose POST enrolls them; this GET never creates one. */ export default async function CredentialGroupConnectPage({ params, @@ -68,10 +73,7 @@ export default async function CredentialGroupConnectPage({ if (!publicId || publicId.length > 128 || !provider || provider.length > 128) return - const callbackQuery = new URLSearchParams({ provider }) - if (optionId) callbackQuery.set('optionId', optionId) - if (returnValue) callbackQuery.set('return', returnValue) - const callbackUrl = `/credential-groups/${encodeURIComponent(publicId)}/connect?${callbackQuery}` + const callbackUrl = buildCredentialGroupConnectPath({ publicId, provider, optionId, returnValue }) const session = await getSession() if (!session?.user) redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) @@ -98,20 +100,34 @@ export default async function CredentialGroupConnectPage({ }) switch (target.kind) { - case 'ready': { - const next = new URLSearchParams({ optionId: target.optionId, returnTo: 'connect' }) - if (target.returnUrl) next.set('return', target.returnUrl) - return redirect( - `/credential-groups/enroll/${encodeURIComponent(target.invitationToken)}?${next}` - ) - } + case 'ready': + return redirect(buildCredentialGroupConnectHandoffPath(target)) case 'wrong_account': return ( ) + case 'confirm_self_enrollment': { + const integration = getCredentialGroupProviderService(target.provider).name + const confirmQuery = new URLSearchParams({ provider, optionId: target.optionId }) + if (returnValue) confirmQuery.set('return', returnValue) + return ( + + + + + Connect {integration} + + + + ) + } case 'not_invited': { const integration = getCredentialGroupProviderService(target.provider).name return ( @@ -132,18 +148,19 @@ export default async function CredentialGroupConnectPage({ description={`${target.organizationName} collects more than one ${integration} account. Choose which to connect.`} />
- {target.options.map((option) => { - const choice = new URLSearchParams(callbackQuery) - choice.set('optionId', option.id) - return ( - - {option.label} - - ) - })} + {target.options.map((option) => ( + + {option.label} + + ))}
) diff --git a/apps/sim/app/credential-groups/complete/page.tsx b/apps/sim/app/credential-groups/complete/page.tsx index 7fe1b477c46..0a45460e317 100644 --- a/apps/sim/app/credential-groups/complete/page.tsx +++ b/apps/sim/app/credential-groups/complete/page.tsx @@ -53,9 +53,7 @@ export default async function CredentialGroupCompletePage({ error ?? (integrationsHref ? 'Returning to Integrations.' - : slackReturnHref - ? 'Your accounts are ready to use.' - : 'Your accounts are ready to use — you can close this tab.') + : 'Your accounts are ready to use. You can close this tab.') } /> {(appLink || slackLink) && ( diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index c701630a4f9..0362a9f0290 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -231,7 +231,7 @@ export default async function CredentialGroupEnrollmentPage({ if (error instanceof CredentialGroupEnrollmentError) return { enrollment: null, enrollmentError: error.message } if (asOrchestrationError(error)?.code === 'not_found') return null - if (focused && error instanceof CredentialGroupProviderConfigurationError) + if (requestedReturnTo && error instanceof CredentialGroupProviderConfigurationError) return { enrollment: null } throw error }) diff --git a/apps/sim/lib/api/contracts/credential-groups.ts b/apps/sim/lib/api/contracts/credential-groups.ts index be5e59243e1..c2d0facc77c 100644 --- a/apps/sim/lib/api/contracts/credential-groups.ts +++ b/apps/sim/lib/api/contracts/credential-groups.ts @@ -602,9 +602,26 @@ export const startCredentialGroupMcpOAuthContract = defineRouteContract({ method: 'GET', path: '/api/credential-groups/enroll/[token]/mcp/[mcpServerId]', params: startCredentialGroupMcpOAuthParamsSchema, + query: startCredentialGroupOAuthQuerySchema, response: { mode: 'empty' }, }) +/** + * The connect page's confirmation, the only request that enrolls an organization member who has + * no enrollment yet. A form POST, so a cross-site navigation (sent with Lax cookies) cannot make it. + */ +export const confirmCredentialGroupConnectContract = defineRouteContract({ + method: 'POST', + path: '/api/credential-groups/connect/[publicId]', + params: z.object({ publicId: z.string().min(1).max(128) }), + query: z.object({ + provider: z.string().min(1).max(128), + optionId: z.string().min(1).max(128).optional(), + return: credentialGroupReturnQuerySchema, + }), + response: { mode: 'redirect' }, +}) + export const completeCredentialGroupEnrollmentContract = defineRouteContract({ method: 'POST', path: '/api/credential-groups/enroll/[token]/complete', diff --git a/apps/sim/lib/core/outbox/processor.test.ts b/apps/sim/lib/core/outbox/processor.test.ts index 98913f0a8e0..ab696f286f7 100644 --- a/apps/sim/lib/core/outbox/processor.test.ts +++ b/apps/sim/lib/core/outbox/processor.test.ts @@ -5,9 +5,13 @@ const mocks = vi.hoisted(() => ({ recover: vi.fn(), reap: vi.fn(), prune: vi.fn(), + pruneCredentialGroups: vi.fn(), })) vi.mock('@/lib/core/outbox/service', () => outboxServiceMock) vi.mock('@/lib/core/outbox/retention', () => ({ pruneCompletedOutboxEvents: mocks.prune })) +vi.mock('@/lib/credential-groups/retention', () => ({ + pruneCredentialGroupConnectHistory: mocks.pruneCredentialGroups, +})) vi.mock('@/lib/knowledge/documents/processing-recovery', () => ({ recoverKnowledgeDocumentProcessing: mocks.recover, })) @@ -40,6 +44,7 @@ describe('outbox processor recovery', () => { mocks.recover.mockResolvedValue(2) mocks.reap.mockResolvedValue(3) mocks.prune.mockResolvedValue(4) + mocks.pruneCredentialGroups.mockResolvedValue({ connectionRequests: 0, sessionLinks: 0 }) }) afterEach(() => vi.useRealTimers()) @@ -50,6 +55,7 @@ describe('outbox processor recovery', () => { recoveredDocuments: 0, reapedBackgroundWork: 3, prunedEvents: 4, + prunedCredentialGroupRows: 0, }) }) @@ -60,6 +66,7 @@ describe('outbox processor recovery', () => { recoveredDocuments: 2, reapedBackgroundWork: 0, prunedEvents: 4, + prunedCredentialGroupRows: 0, }) }) @@ -70,6 +77,7 @@ describe('outbox processor recovery', () => { recoveredDocuments: 2, reapedBackgroundWork: 3, prunedEvents: 0, + prunedCredentialGroupRows: 0, }) }) @@ -83,6 +91,7 @@ describe('outbox processor recovery', () => { recoveredDocuments: 0, reapedBackgroundWork: 3, prunedEvents: 4, + prunedCredentialGroupRows: 0, }) expect(mocks.recover).not.toHaveBeenCalled() }) diff --git a/apps/sim/lib/core/outbox/processor.ts b/apps/sim/lib/core/outbox/processor.ts index 240e78a7502..99a035e5606 100644 --- a/apps/sim/lib/core/outbox/processor.ts +++ b/apps/sim/lib/core/outbox/processor.ts @@ -9,6 +9,7 @@ import { OUTBOX_HANDLER_GROUPS } from '@/lib/core/outbox/handlers' import { pruneCompletedOutboxEvents } from '@/lib/core/outbox/retention' import { type ProcessOutboxResult, processOutboxEvents } from '@/lib/core/outbox/service' import { DeadlineExceededError } from '@/lib/core/utils/deadline' +import { pruneCredentialGroupConnectHistory } from '@/lib/credential-groups/retention' import { getConnectorFailureDiagnostic } from '@/lib/knowledge/connectors/error' import { recoverKnowledgeDocumentProcessing } from '@/lib/knowledge/documents/processing-recovery' import { reapStaleBackgroundWork } from '@/ee/workspace-forking/lib/background-work/store' @@ -20,6 +21,7 @@ export interface OutboxProcessorResult { recoveredDocuments: number reapedBackgroundWork: number prunedEvents: number + prunedCredentialGroupRows: number } /** Processes one bounded batch and its recovery work in either the worker or self-hosted cron. */ @@ -63,11 +65,22 @@ export async function runOutboxProcessor(): Promise { logger.error('Completed outbox pruning failed', { error: toError(error).message }) } + let prunedCredentialGroupRows = 0 + try { + const pruned = await pruneCredentialGroupConnectHistory() + prunedCredentialGroupRows = pruned.connectionRequests + pruned.sessionLinks + } catch (error) { + logger.error('Credential group connect history pruning failed', { + error: toError(error).message, + }) + } + const summary = { ...result, reapedBackgroundWork, recoveredDocuments, prunedEvents, + prunedCredentialGroupRows, durationMs: Date.now() - startedAt, } /** Fail the run so a broken handler module stays as visible as the crash its static import caused. */ @@ -77,5 +90,11 @@ export async function runOutboxProcessor(): Promise { throw new Error(message) } logger.info('Outbox processing completed', summary) - return { result, reapedBackgroundWork, recoveredDocuments, prunedEvents } + return { + result, + reapedBackgroundWork, + recoveredDocuments, + prunedEvents, + prunedCredentialGroupRows, + } } diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index 816c6ca1cc8..0b1edab686c 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -3,14 +3,17 @@ * focused link it mints is held to its one account option. Failure modes: an invited person * (minted link scoped to the option, one hour, enrollment fields untouched), an enrollment bound * to someone else, an unverified session, a revoked enrollment, a stranger, an organization member - * with no enrollment, a disabled group or unknown provider (indistinguishable from an unknown - * public ID), a provider with two options, a workflow-requested enrollment with no live link, a - * focused link used for another option or an MCP server, and the saved connection completing the - * enrollment exactly once. Only email delivery, the provider code exchange, and the workflow - * trigger fan-out are faked. + * with no enrollment (enrolled only on the confirmation, never on the page load), a member the + * Integrations permission group or an unfinished setup keeps from self-enrolling, a revocation + * landing while a member self-enrolls, a disabled group or unknown provider (indistinguishable + * from an unknown public ID), a provider with two options, a workflow-requested enrollment with no + * live link, a focused link used for another option, an MCP server or Submit, and the saved + * connection completing the enrollment exactly once. Only email delivery, the provider code + * exchange, the workflow trigger fan-out, and the Enterprise entitlement that turns permission + * groups on are faked. */ import type { CredentialGroupEnrollmentPrincipal } from '@sim/auth/principal' -import { db } from '@sim/db' +import { db, runOutsideTransactionContext } from '@sim/db' import { credential, credentialGroup, @@ -18,16 +21,21 @@ import { credentialGroupEnrollmentLink, member, organization, + permissionGroup, + resourcePolicy, user, } from '@sim/db/schema' import { sha256Hex } from '@sim/security/hash' import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { envFlagsMock } from '@sim/testing/mocks/env-flags.mock' +import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' -import { eq, inArray } from 'drizzle-orm' +import { and, eq, inArray, sql } from 'drizzle-orm' import { afterAll, describe, expect, it, vi } from 'vitest' import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' import { + completePublicCredentialGroupEnrollment, completePublicCredentialGroupOAuth, startPublicCredentialGroupMcpOAuth, startPublicCredentialGroupOAuth, @@ -35,6 +43,7 @@ import { import { authenticatePublicCredentialGroupEnrollment, inviteCredentialGroupEnrollment, + lockCredentialGroupInvitationTarget, revokeCredentialGroupEnrollment, } from '@/lib/credential-groups/enrollments' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' @@ -50,6 +59,13 @@ vi.mock('@/lib/credential-groups/scoped-availability', () => ({ isScopedCredentialGroupsAvailable: async () => true, })) +/** Permission groups govern only Enterprise organizations under Access Control. */ +vi.mock('@/lib/core/config/env-flags', () => ({ ...envFlagsMock, isAccessControlEnabled: true })) +vi.mock('@/lib/billing/core/subscription', async (importOriginal) => ({ + ...(await importOriginal()), + isOrganizationGovernanceActive: async () => true, +})) + vi.mock('@/components/emails/credential-groups/render', () => ({ renderCredentialGroupInvitationEmail: async (input: { invitationLink: string }) => input.invitationLink, @@ -155,9 +171,28 @@ async function createPerson(emailVerified = true): Promise<{ userId: string; ema return { userId, email } } +async function addMember(fixture: Fixture, userId: string) { + await db + .insert(member) + .values({ id: generateId(), organizationId: fixture.organizationId, userId, role: 'member' }) +} + +async function enrollmentsIn(groupId: string) { + return db + .select() + .from(credentialGroupEnrollment) + .where(eq(credentialGroupEnrollment.credentialGroupId, groupId)) +} + function resolveTarget( userId: string, - input: { publicId: string; provider?: string; optionId?: string; returnUrl?: string } + input: { + publicId: string + provider?: string + optionId?: string + returnUrl?: string + confirmSelfEnrollment?: boolean + } ) { return resolveCredentialGroupConnectTarget.execute({ principal: createSessionPrincipal({ userId }), @@ -225,6 +260,18 @@ async function enrollmentOf(groupId: string, email: string) { return row } +/** Resolves once a query waits on an advisory lock, so a test can commit the holder mid-request. */ +async function waitForAdvisoryLockWaiter() { + for (let attempt = 0; attempt < 200; attempt++) { + const waiting = await db.execute( + sql`SELECT 1 FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND wait_event = 'advisory'` + ) + if (waiting.length) return + await sleep(25) + } + throw new Error('The self-enrollment never waited on the invitation lock') +} + afterAll(async () => { await db.delete(credential).where(inArray(credential.organizationId, organizationIds)) await db.delete(organization).where(inArray(organization.id, organizationIds)) @@ -288,6 +335,7 @@ describe('resolveCredentialGroupConnectTarget', () => { await expect(resolveTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ kind: 'wrong_account', organizationName: 'Acme', + maskedEmail: `${person.email[0]}***@connect.test`, }) }) @@ -349,23 +397,103 @@ describe('resolveCredentialGroupConnectTarget', () => { expect(enrollments).toHaveLength(0) }) - it('enrolls an organization member with no enrollment and mints their link', async () => { + it('asks a member with no enrollment to confirm, enrolling them only on the confirmation', async () => { const fixture = await createOrganization() const teammate = await createPerson() - await db.insert(member).values({ - id: generateId(), - organizationId: fixture.organizationId, - userId: teammate.userId, - role: 'member', + await addMember(fixture, teammate.userId) + + await expect(resolveTarget(teammate.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'confirm_self_enrollment', + organizationName: 'Acme', + provider: 'google-drive', + optionId: DRIVE.id, }) + expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) - const target = await resolveTarget(teammate.userId, { publicId: fixture.publicId }) + const target = await resolveTarget(teammate.userId, { + publicId: fixture.publicId, + confirmSelfEnrollment: true, + }) expect(target).toMatchObject({ kind: 'ready', optionId: DRIVE.id }) const enrollment = await enrollmentOf(fixture.groupId, teammate.email) expect(enrollment.userId).toBe(teammate.userId) }) + it('refuses self-enrollment to a member the Integrations permission group restricts', async () => { + const fixture = await createOrganization() + const teammate = await createPerson() + await addMember(fixture, teammate.userId) + await db.insert(permissionGroup).values({ + id: generateId(), + organizationId: fixture.organizationId, + name: 'No integrations', + createdBy: fixture.adminId, + config: { hideIntegrationsTab: true }, + isDefault: true, + }) + + for (const confirmSelfEnrollment of [false, true]) + await expect( + resolveTarget(teammate.userId, { publicId: fixture.publicId, confirmSelfEnrollment }) + ).resolves.toEqual({ + kind: 'not_invited', + organizationName: 'Acme', + provider: 'google-drive', + }) + expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) + }) + + it('refuses self-enrollment while the organization has not finished setting up', async () => { + const fixture = await createOrganization() + const teammate = await createPerson() + await addMember(fixture, teammate.userId) + await db + .delete(resourcePolicy) + .where( + and( + eq(resourcePolicy.resourceType, 'credential_group'), + eq(resourcePolicy.resourceId, fixture.groupId) + ) + ) + + await expect( + resolveTarget(teammate.userId, { publicId: fixture.publicId, confirmSelfEnrollment: true }) + ).resolves.toEqual({ kind: 'not_invited', organizationName: 'Acme', provider: 'google-drive' }) + expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) + }) + + it('tells a member revoked while they self-enroll that the connection is no longer needed', async () => { + const fixture = await createOrganization() + const teammate = await createPerson() + await addMember(fixture, teammate.userId) + + const { pending } = await db.transaction(async (tx) => { + await lockCredentialGroupInvitationTarget(tx, fixture.groupId, teammate.email) + await tx.insert(credentialGroupEnrollment).values({ + id: generateId(), + credentialGroupId: fixture.groupId, + email: teammate.email, + status: 'revoked', + revokedAt: new Date(), + invitationTokenHash: sha256Hex(generateId()), + invitationExpiresAt: new Date(Date.now() + HOUR_MS), + invitedAt: new Date(), + }) + const pending = runOutsideTransactionContext(() => + resolveTarget(teammate.userId, { publicId: fixture.publicId, confirmSelfEnrollment: true }) + ) + await runOutsideTransactionContext(waitForAdvisoryLockWaiter) + return { pending } + }) + + await expect(pending).resolves.toEqual({ + kind: 'revoked', + organizationName: 'Acme', + provider: 'google-drive', + }) + }) + it('answers a disabled group, an unoffered provider and an unknown ID identically', async () => { const fixture = await createOrganization() const disabled = await createOrganization() @@ -451,7 +579,7 @@ describe('resolveCredentialGroupConnectTarget', () => { }) describe('a focused connect link', () => { - it('refuses to start OAuth for another option or an MCP server', async () => { + it('refuses to start or complete OAuth for another option, or start an MCP server', async () => { const fixture = await createOrganization([ driveOption('drive-work', 'Work Drive'), driveOption('drive-shared', 'Shared Drive'), @@ -493,6 +621,25 @@ describe('a focused connect link', () => { ).rejects.toBeInstanceOf(CredentialGroupLinkFocusError) }) + it('refuses Submit, which a focused link never shows, leaving the enrollment open', async () => { + const fixture = await createOrganization() + const person = await createPerson() + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + const token = await readyToken(person.userId, { publicId: fixture.publicId }) + const principal = await principalFor(token, person.userId) + + await expect( + completePublicCredentialGroupEnrollment.execute({ principal, input: {} }) + ).rejects.toBeInstanceOf(CredentialGroupLinkFocusError) + expect((await enrollmentOf(fixture.groupId, person.email)).status).toBe('invited') + }) + it('completes the enrollment when its connection is saved, firing form_submitted once', async () => { const fixture = await createOrganization() const person = await createPerson() diff --git a/apps/sim/lib/credential-groups/__integration__/retention.integration.ts b/apps/sim/lib/credential-groups/__integration__/retention.integration.ts new file mode 100644 index 00000000000..99bb33795a5 --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/retention.integration.ts @@ -0,0 +1,117 @@ +/** + * Retention of the connect flow's short-lived rows against real PostgreSQL. Failure modes: a + * request log row the daily cap still reads being deleted; an expired session link a day past + * expiry being kept; an emailed link, which outlives its expiry once bound, being deleted; a + * session link the enrollment's legacy invitation column still names being deleted, which would + * let its token resolve through the column with no expiry. + */ +import { db } from '@sim/db' +import { + credentialGroup, + credentialGroupConnectionRequest, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + organization, +} from '@sim/db/schema' +import { sha256Hex } from '@sim/security/hash' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, describe, expect, it } from 'vitest' +import { pruneCredentialGroupConnectHistory } from '@/lib/credential-groups/retention' + +const HOUR_MS = 60 * 60 * 1000 +const DAY_MS = 24 * HOUR_MS +const organizationIds: string[] = [] + +async function createEnrollment(legacyTokenHash: string) { + const organizationId = generateId() + organizationIds.push(organizationId) + await db + .insert(organization) + .values({ id: organizationId, name: 'Retention', slug: organizationId }) + const groupId = generateId() + await db.insert(credentialGroup).values({ + id: groupId, + organizationId, + publicId: generateId(), + name: 'Connected accounts', + options: [], + }) + const enrollmentId = generateId() + await db.insert(credentialGroupEnrollment).values({ + id: enrollmentId, + credentialGroupId: groupId, + email: `${enrollmentId}@retention.test`, + status: 'invited', + invitationTokenHash: legacyTokenHash, + invitationExpiresAt: new Date(Date.now() + 7 * DAY_MS), + invitedAt: new Date(), + }) + return { groupId, enrollmentId } +} + +async function insertLink( + enrollmentId: string, + purpose: 'email' | 'self' | 'connect', + expiresAt: Date, + tokenHash = sha256Hex(generateId()) +) { + const id = generateId() + await db + .insert(credentialGroupEnrollmentLink) + .values({ id, enrollmentId, tokenHash, purpose, expiresAt }) + return id +} + +async function insertRequest(groupId: string, createdAt: Date) { + const id = generateId() + await db.insert(credentialGroupConnectionRequest).values({ + id, + credentialGroupId: groupId, + email: `${id}@retention.test`, + workspaceId: generateId(), + workflowId: generateId(), + createdAt, + }) + return id +} + +afterAll(async () => { + await db.delete(organization).where(inArray(organization.id, organizationIds)) +}) + +describe('pruneCredentialGroupConnectHistory', () => { + it('deletes request log rows past two days and session links a day past expiry, nothing else', async () => { + const legacyTokenHash = sha256Hex(generateId()) + const { groupId, enrollmentId } = await createEnrollment(legacyTokenHash) + const now = Date.now() + await insertRequest(groupId, new Date(now - 2 * DAY_MS - HOUR_MS)) + const recentRequest = await insertRequest(groupId, new Date(now - DAY_MS - HOUR_MS)) + await insertLink(enrollmentId, 'self', new Date(now - DAY_MS - HOUR_MS)) + await insertLink(enrollmentId, 'connect', new Date(now - 2 * DAY_MS)) + const recentlyExpired = await insertLink(enrollmentId, 'connect', new Date(now - HOUR_MS)) + const live = await insertLink(enrollmentId, 'connect', new Date(now + HOUR_MS)) + const oldEmail = await insertLink(enrollmentId, 'email', new Date(now - 30 * DAY_MS)) + const namedByLegacyColumn = await insertLink( + enrollmentId, + 'self', + new Date(now - 30 * DAY_MS), + legacyTokenHash + ) + + await pruneCredentialGroupConnectHistory(new Date(now)) + + const requests = await db + .select({ id: credentialGroupConnectionRequest.id }) + .from(credentialGroupConnectionRequest) + .where(eq(credentialGroupConnectionRequest.credentialGroupId, groupId)) + expect(requests.map((row) => row.id)).toEqual([recentRequest]) + const links = await db + .select({ id: credentialGroupEnrollmentLink.id }) + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId)) + expect(links.map((row) => row.id).sort()).toEqual( + [recentlyExpired, live, oldEmail, namedByLegacyColumn].sort() + ) + }) +}) diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index 18aa7fbc0eb..7d523a45b7a 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -11,7 +11,8 @@ * error differing by target; a `+` alias slipping in; reminders beyond the per-enrollment cap or * after 30 days; a revocation racing a reminder still emailing; an admin unable to turn requests * off after their choices went stale; saving either the request policy or Access changing the - * other. + * other; a request's placeholder invitation being adopted as a link by a later admin invite; the + * emailed link not opening the requested enrollment on the connect page. */ import type { WorkflowExecutionDelegatedPrincipal } from '@sim/auth/principal' import { db } from '@sim/db' @@ -21,6 +22,7 @@ import { credentialGroupConnectionRequest, credentialGroupConnectionRequestPolicy, credentialGroupEnrollment, + credentialGroupEnrollmentLink, member, organization, outboxEvent, @@ -31,11 +33,13 @@ import { import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' import { sha256Hex } from '@sim/security/hash' import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' import { and, eq, inArray, isNotNull, sql } from 'drizzle-orm' import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { OrchestrationError } from '@/lib/core/orchestration/types' import { CREDENTIAL_GROUP_DELEGATION_AUDIENCE } from '@/lib/credential-groups/application/authorization' +import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' import { getOrganizationAccountConnectionStatus, requestOrganizationAccountConnection, @@ -46,9 +50,14 @@ import { updateOrganizationConnectionRequestPolicy, } from '@/lib/credential-groups/application/organization-connection-requests' import { buildOrganizationAccountAccessPolicy } from '@/lib/credential-groups/application/workspace-access-policy' +import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' import { CONNECTION_REQUEST_EMAIL_EVENT } from '@/lib/credential-groups/connection-request-event' import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' -import type { CredentialGroupOAuthContext } from '@/lib/credential-groups/enrollments' +import { + authenticatePublicCredentialGroupEnrollment, + type CredentialGroupOAuthContext, + inviteCredentialGroupEnrollment, +} from '@/lib/credential-groups/enrollments' import { completeCredentialGroupOAuth } from '@/lib/credential-groups/oauth' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' import type { CredentialGroupProvider } from '@/lib/credential-groups/providers' @@ -65,6 +74,11 @@ vi.mock('@/lib/messaging/email/mailer', () => ({ sendEmail: async () => ({ success: true, message: 'sent' }), })) +vi.mock('@/components/emails/credential-groups/render', () => ({ + renderCredentialGroupInvitationEmail: async (input: { invitationLink: string }) => + input.invitationLink, +})) + vi.mock('@/lib/credential-groups/provider-registry', async (importOriginal) => { const { getCredentialGroupProviderId: providerIdOf } = await import( '@/lib/credential-groups/providers' @@ -365,7 +379,7 @@ async function waitForLockedQuery() { sql`SELECT 1 FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query ILIKE '%credential_group_enrollment%'` ) if (waiting.length) return - await new Promise((resolve) => setTimeout(resolve, 25)) + await sleep(25) } throw new Error('The request never waited on the revocation') } @@ -699,6 +713,77 @@ describe('connection request emails', () => { }) }) +describe('a requested enrollment on the connect page', () => { + beforeEach(async () => { + await setRequestPolicy(orgA, { ...OPEN_POLICY, sendEmail: true }) + }) + + it('opens the enrollment the emailed connect link names for the person at that address', async () => { + const email = address('emailed-connect') + await request(orgA, email) + const [enrollment] = await enrollmentsFor(orgA, email) + if (!enrollment) throw new Error('Request created no enrollment') + const [event] = await db + .select({ payload: outboxEvent.payload }) + .from(outboxEvent) + .where( + and( + eq(outboxEvent.eventType, CONNECTION_REQUEST_EMAIL_EVENT), + sql`${outboxEvent.payload} ->> 'enrollmentId' = ${enrollment.id}` + ) + ) + expect(event?.payload).toMatchObject({ + connectUrl: buildCredentialGroupConnectUrl({ publicId: orgA.publicId, provider: DRIVE_ID }), + }) + + const userId = generateId() + people.set(email, userId) + await db.insert(user).values({ + id: userId, + name: email, + email, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }) + const target = await resolveCredentialGroupConnectTarget.execute({ + principal: createSessionPrincipal({ userId }), + input: { publicId: orgA.publicId, provider: DRIVE_ID }, + }) + + expect(target).toMatchObject({ kind: 'ready', optionId: DRIVE.id }) + if (target.kind !== 'ready') return + await expect( + authenticatePublicCredentialGroupEnrollment(target.invitationToken) + ).resolves.toMatchObject({ enrollmentId: enrollment.id, userId }) + }) + + it('leaves an admin invite to a requested person with only the link it emailed', async () => { + const email = address('requested-then-invited') + await request(orgA, email) + const [requested] = await enrollmentsFor(orgA, email) + if (!requested) throw new Error('Request created no enrollment') + + await inviteCredentialGroupEnrollment( + { kind: 'organization', organizationId: orgA.organizationId }, + orgA.groupId, + orgA.adminId, + 'Admin', + email + ) + + const [invited] = await enrollmentsFor(orgA, email) + const links = await db + .select({ + tokenHash: credentialGroupEnrollmentLink.tokenHash, + purpose: credentialGroupEnrollmentLink.purpose, + }) + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, requested.id)) + expect(links).toEqual([{ tokenHash: invited?.invitationTokenHash, purpose: 'email' }]) + }) +}) + describe('admin connection request settings', () => { const admin = (fixture: OrgFixture) => createSessionPrincipal({ userId: fixture.adminId, sessionId: generateId() }) diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts index a42ae8df427..282a867b7c4 100644 --- a/apps/sim/lib/credential-groups/application/connect-target.ts +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -1,13 +1,25 @@ import type { SessionPrincipal } from '@sim/auth/principal' import { defineOperation } from '@/lib/core/application' -import { OrchestrationError } from '@/lib/core/orchestration/types' +import { ForbiddenOperationError } from '@/lib/core/application/forbidden' +import { + authorizeOrganizationOperation, + OrganizationMembershipNotFoundError, +} from '@/lib/core/application/organization-authorization' +import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' +import { maskEnrollmentEmail } from '@/lib/credential-groups/application/enrollment-link-outcome' +import { organizationAccountOperations } from '@/lib/credential-groups/application/organization-accounts' import { authenticatePublicCredentialGroupEnrollment, bindCredentialGroupEnrollmentUser, + CredentialGroupEnrollmentError, issueCredentialGroupConnectLink, loadCredentialGroupConnectSubject, } from '@/lib/credential-groups/enrollments' +import { + OrganizationAccountsSetupRequiredError, + requireOrganizationAccountsSetup, +} from '@/lib/credential-groups/organization-setup' import { type CredentialGroupProvider, findCredentialGroupProviderFromProviderId, @@ -16,7 +28,6 @@ import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-ur import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import { createViewerCredentialGroupEnrollment } from '@/lib/credential-groups/self-enrollment' import { defineAuthorizedCredentialUserUseCase } from '@/lib/credentials/application/authorized-user-use-case' -import { getOrganizationSettingsAccess } from '@/lib/organizations/settings-access' const credentialGroupConnectOperations = { /** @@ -51,6 +62,11 @@ export interface ResolveCredentialGroupConnectTargetInput { optionId?: string /** Raw `return` query value: the keyword `slack` or an allowlisted Slack URL. */ returnUrl?: string + /** + * Set only by the confirmation POST. Without it an organization member with no enrollment is + * asked to confirm instead of enrolled, so a cross-site navigation enrolls nobody. + */ + confirmSelfEnrollment?: boolean } /** @@ -63,7 +79,13 @@ export type CredentialGroupConnectTarget = | { kind: 'ready'; invitationToken: string; optionId: string; returnUrl?: string } | { kind: 'unavailable' } | { kind: 'not_invited'; organizationName: string; provider: CredentialGroupProvider } - | { kind: 'wrong_account'; organizationName: string } + | { kind: 'wrong_account'; organizationName: string; maskedEmail: string } + | { + kind: 'confirm_self_enrollment' + organizationName: string + provider: CredentialGroupProvider + optionId: string + } | { kind: 'revoked'; organizationName: string; provider: CredentialGroupProvider } | { kind: 'choose_option' @@ -74,14 +96,63 @@ export type CredentialGroupConnectTarget = const UNAVAILABLE = { kind: 'unavailable' } as const +/** + * Whether the member may enroll themselves, under the same checks as the member self-enroll path + * (`organization_accounts.connect`): membership, the Integrations permission-group capability, + * and an organization whose Connected accounts setup is complete. + */ +async function canSelfEnroll( + principal: SessionPrincipal, + organizationId: string, + credentialGroupId: string +): Promise { + try { + await authorizeOrganizationOperation(principal, organizationAccountOperations.connect, { + organizationId, + }) + await requireOrganizationAccountsSetup(organizationId, credentialGroupId) + return true + } catch (error) { + if ( + error instanceof ForbiddenOperationError || + error instanceof OrganizationMembershipNotFoundError || + error instanceof OrganizationAccountsSetupRequiredError + ) + return false + throw error + } +} + +/** + * Enrolls the member, mapping a revocation that landed after the enrollment was read to + * `revoked` and any other refusal to `unavailable`. + */ +async function selfEnroll(input: { + organizationId: string + credentialGroupId: string + userId: string +}): Promise<{ enrollmentId: string } | 'revoked' | 'unavailable'> { + try { + const enrolled = await createViewerCredentialGroupEnrollment(input) + return { enrollmentId: enrolled.enrollment.id } + } catch (error) { + if (error instanceof CredentialGroupEnrollmentError) return 'unavailable' + const code = asOrchestrationError(error)?.code + if (code === 'forbidden') return 'revoked' + if (code) return 'unavailable' + throw error + } +} + /** * Resolves a secret-free connect URL to the signed-in person's own enrollment and, only then, * mints a one-hour link focused on the single matching account option. The session is the * authority, not an earlier invitation: an unbound enrollment whose emailed link (or legacy * invitation column) expired, or that a workflow requested with no link at all, is still - * connectable by the person at its email, because the fresh link carries its own expiry. An organization member - * with no enrollment is enrolled through the member self-enroll path; anyone else must already - * hold an enrollment bound to them or invited at their verified email. + * connectable by the person at its email, because the fresh link carries its own expiry. An + * organization member with no enrollment who passes the member self-enroll checks is asked to + * confirm, and enrolled only by the confirmation POST; anyone else must already hold an + * enrollment bound to them or invited at their verified email. */ export const resolveCredentialGroupConnectTarget = defineAuthorizedCredentialUserUseCase({ operation: credentialGroupConnectOperations.resolve, @@ -115,15 +186,16 @@ export const resolveCredentialGroupConnectTarget = defineAuthorizedCredentialUse const { organizationName } = group if (enrollment?.userId && enrollment.userId !== principal.userId) - return { kind: 'wrong_account', organizationName } + return { + kind: 'wrong_account', + organizationName, + maskedEmail: maskEnrollmentEmail(enrollment.email), + } if (enrollment && (enrollment.status === 'revoked' || enrollment.revokedAt)) return { kind: 'revoked', organizationName, provider } if ( !enrollment && - !( - group.organizationId && - (await getOrganizationSettingsAccess(group.organizationId, principal.userId)).isMember - ) + !(group.organizationId && (await canSelfEnroll(principal, group.organizationId, group.id))) ) return { kind: 'not_invited', organizationName, provider } if (options.length > 1) @@ -135,17 +207,24 @@ export const resolveCredentialGroupConnectTarget = defineAuthorizedCredentialUse } let enrollmentId = enrollment?.id - if (!enrollmentId) { - const enrolled = await createViewerCredentialGroupEnrollment({ - ...(group.organizationId ? { organizationId: group.organizationId } : {}), + let bound = Boolean(enrollment?.userId) + if (!enrollmentId && group.organizationId) { + if (!input.confirmSelfEnrollment) + return { kind: 'confirm_self_enrollment', organizationName, provider, optionId: option.id } + const enrolled = await selfEnroll({ + organizationId: group.organizationId, credentialGroupId: group.id, userId: principal.userId, }) - enrollmentId = enrolled.enrollment.id + if (enrolled === 'revoked') return { kind: 'revoked', organizationName, provider } + if (enrolled === 'unavailable') return UNAVAILABLE + enrollmentId = enrolled.enrollmentId + bound = true } + if (!enrollmentId) return UNAVAILABLE const invitationToken = await issueCredentialGroupConnectLink(enrollmentId, option.id) if (!invitationToken) return { kind: 'revoked', organizationName, provider } - if (!enrollment?.userId) { + if (!bound) { const identity = await authenticatePublicCredentialGroupEnrollment(invitationToken) if (!identity) return UNAVAILABLE await bindCredentialGroupEnrollmentUser(identity, principal.userId) diff --git a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts index a6464adfd10..69bfbbf3927 100644 --- a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts +++ b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts @@ -25,7 +25,7 @@ interface ExplainCredentialGroupEnrollmentLinkParams { } /** Masks an address as `b***@example.com` so a forwarded link never reveals who it was for. */ -function maskEnrollmentEmail(email: string): string { +export function maskEnrollmentEmail(email: string): string { const at = email.lastIndexOf('@') if (at < 1) return '***' return `${email[0]}***${email.slice(at)}` diff --git a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts index 8c07f833577..5c41a01f6af 100644 --- a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts +++ b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts @@ -8,8 +8,6 @@ import { mcpServers, organization, } from '@sim/db/schema' -import { sha256Hex } from '@sim/security/hash' -import { generateId } from '@sim/utils/id' import { and, asc, eq, gt, inArray, isNotNull } from 'drizzle-orm' import { defineOperation } from '@/lib/core/application' import { runWithOutboundOrganization } from '@/lib/core/network/context.server' @@ -17,6 +15,7 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import { sameResourceScopeCondition } from '@/lib/core/resource-scope.server' import { createCredentialGroupOAuthStartUrl } from '@/lib/credential-groups/enrollment-links' import { + createUnissuedInvitationTokenHash, lockCredentialGroupEnrollmentLifecycle, revokeCredentialGroupEnrollmentLinks, } from '@/lib/credential-groups/enrollments' @@ -227,7 +226,7 @@ export const disconnectPersonalOrganizationAccount = defineAuthorizedCredentialU await revokeCredentialGroupEnrollmentLinks(tx, current.enrollmentId, now) await tx .update(credentialGroupEnrollment) - .set({ invitationTokenHash: sha256Hex(generateId()), updatedAt: now }) + .set({ invitationTokenHash: createUnissuedInvitationTokenHash(), updatedAt: now }) .where(eq(credentialGroupEnrollment.id, current.enrollmentId)) }) return { diff --git a/apps/sim/lib/credential-groups/application/public-enrollment.ts b/apps/sim/lib/credential-groups/application/public-enrollment.ts index 3ffab031e5a..b91bf95622b 100644 --- a/apps/sim/lib/credential-groups/application/public-enrollment.ts +++ b/apps/sim/lib/credential-groups/application/public-enrollment.ts @@ -202,7 +202,9 @@ export const completePublicCredentialGroupEnrollment = principal: CredentialGroupEnrollmentPrincipal input: CompletePublicCredentialGroupEnrollmentInput }) => resolvePublicEnrollmentContext(principal), - async execute({ context, principal, input }) { + /** A focused link completes itself when its connection is saved; it has no Submit. */ + async execute({ context, principal, input, linkOptionId }) { + if (linkOptionId) throw new CredentialGroupLinkFocusError() const completed = await completeEnrollment(context, context.enrollment.credentialGroupName) const completionReturnId = completed ? await createCredentialGroupCompletionReturn({ diff --git a/apps/sim/lib/credential-groups/connect-url.ts b/apps/sim/lib/credential-groups/connect-url.ts index 55593aa4f13..d17041cc705 100644 --- a/apps/sim/lib/credential-groups/connect-url.ts +++ b/apps/sim/lib/credential-groups/connect-url.ts @@ -1,5 +1,26 @@ import { getBaseUrl } from '@/lib/core/utils/urls' +interface CredentialGroupConnectPathInput { + publicId: string + provider: string + optionId?: string + /** The raw `return` query value: the keyword `slack` or an allowlisted Slack URL. */ + returnValue?: string +} + +/** The connect page's path and query, relative to the app origin. */ +export function buildCredentialGroupConnectPath({ + publicId, + provider, + optionId, + returnValue, +}: CredentialGroupConnectPathInput): string { + const query = new URLSearchParams({ provider }) + if (optionId) query.set('optionId', optionId) + if (returnValue) query.set('return', returnValue) + return `/credential-groups/${encodeURIComponent(publicId)}/connect?${query}` +} + /** * The stable, secret-free link a person opens to connect one integration for a Credential Group. * Safe to show anywhere: the page it opens verifies who is signed in before minting anything. @@ -13,7 +34,16 @@ export function buildCredentialGroupConnectUrl({ provider: string returnKey?: 'slack' }): string { - const query = new URLSearchParams({ provider }) - if (returnKey) query.set('return', returnKey) - return `${getBaseUrl()}/credential-groups/${encodeURIComponent(publicId)}/connect?${query}` + return `${getBaseUrl()}${buildCredentialGroupConnectPath({ publicId, provider, returnValue: returnKey })}` +} + +/** Where a resolved connect link continues: the enrollment page, focused on its one option. */ +export function buildCredentialGroupConnectHandoffPath(target: { + invitationToken: string + optionId: string + returnUrl?: string +}): string { + const query = new URLSearchParams({ optionId: target.optionId, returnTo: 'connect' }) + if (target.returnUrl) query.set('return', target.returnUrl) + return `/credential-groups/enroll/${encodeURIComponent(target.invitationToken)}?${query}` } diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index b6159109152..8b36f2f2be4 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -6,7 +6,6 @@ import { credentialGroupConnectionRequestPolicy, credentialGroupEnrollment, } from '@sim/db/schema' -import { sha256Hex } from '@sim/security/hash' import { generateId } from '@sim/utils/id' import { and, count, eq, gt, inArray, isNotNull, isNull, lt, sql } from 'drizzle-orm' import { enqueueOutboxEvent } from '@/lib/core/outbox/service' @@ -24,7 +23,10 @@ import { LIVE_ENROLLMENT_STATUSES, listCredentialGroupCredentialReferences, } from '@/lib/credential-groups/credentials' -import { lockCredentialGroupInvitationTarget } from '@/lib/credential-groups/enrollments' +import { + createUnissuedInvitationTokenHash, + lockCredentialGroupInvitationTarget, +} from '@/lib/credential-groups/enrollments' import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' const DAY_MS = 24 * 60 * 60 * 1000 @@ -210,8 +212,8 @@ interface RecordedConnectionRequest { * revocation committed meanwhile sends nothing. * * Emails are enqueued on the outbox in the same transaction, so nothing here waits on rendering - * or delivery. Log rows are only read inside the cap's one-day window; nothing prunes older ones - * yet. + * or delivery. Log rows are only read inside the cap's one-day window and are pruned after two + * days by {@link pruneCredentialGroupConnectHistory}. */ export async function recordCredentialGroupConnectionRequest(input: { credentialGroupId: string @@ -333,7 +335,7 @@ export async function recordCredentialGroupConnectionRequest(input: { email: input.email, status: 'invited', /** No invitation link is issued: the person signs in on the connect page instead. */ - invitationTokenHash: sha256Hex(generateId()), + invitationTokenHash: createUnissuedInvitationTokenHash(), invitationExpiresAt: new Date(now.getTime() + REQUESTED_ENROLLMENT_TTL_MS), invitedAt: now, sentAt: input.sendEmail ? now : null, diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 9269fc031c8..9432ae4420d 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -283,6 +283,23 @@ function hashInvitationToken(token: string): string { return sha256Hex(token) } +const UNISSUED_INVITATION_PREFIX = 'unissued:' + +/** + * A value for the legacy `invitation_token_hash` column of an enrollment created without an + * emailed link (by self-enrollment or a workflow's connection request). It contains a character + * no hex digest does, so no token ever hashes to it: the legacy branch of + * {@link liveEnrollmentLinkCondition} never matches it and link adoption skips it. It is unique + * and 64 characters long, as the column requires. + */ +export function createUnissuedInvitationTokenHash(): string { + return `${UNISSUED_INVITATION_PREFIX}${sha256Hex(generateId()).slice(UNISSUED_INVITATION_PREFIX.length)}` +} + +function isUnissuedInvitationTokenHash(value: string): boolean { + return value.startsWith(UNISSUED_INVITATION_PREFIX) +} + /** * Matches the enrollment row that `tokenHash` is a live link into: an unrevoked, unexpired link. * Only an emailed link outlives its expiry, and only once the enrollment is bound to a user (from @@ -571,6 +588,7 @@ async function getInvitationContext( * enrollment's adopted link is revoked with it. */ async function adoptLegacyInvitationLink(tx: DbTransaction, current: EnrollmentRow, now: Date) { + if (isUnissuedInvitationTokenHash(current.invitationTokenHash)) return await tx .insert(credentialGroupEnrollmentLink) .values({ @@ -674,10 +692,17 @@ async function issueInvitation( credentialGroupId: context.groupId, email, ...invitationValues, - /** No email was sent, so the admin-facing invitation window is the default one. */ + /** + * No email was sent: the admin-facing invitation window is the default one, and the + * legacy column names no link, so pruning the session link cannot leave its token + * resolving through the column. + */ ...(options.purpose === 'email' ? {} - : { invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS) }), + : { + invitationTokenHash: createUnissuedInvitationTokenHash(), + invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), + }), createdAt: now, }) .returning() diff --git a/apps/sim/lib/credential-groups/retention.ts b/apps/sim/lib/credential-groups/retention.ts new file mode 100644 index 00000000000..c66104155c8 --- /dev/null +++ b/apps/sim/lib/credential-groups/retention.ts @@ -0,0 +1,97 @@ +import { db } from '@sim/db' +import { + credentialGroupConnectionRequest, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, +} from '@sim/db/schema' +import { createLogger } from '@sim/logger' +import { and, asc, eq, inArray, lt, sql } from 'drizzle-orm' + +const logger = createLogger('CredentialGroupRetention') + +const DAY_MS = 24 * 60 * 60 * 1000 +/** The daily cap reads one day of the request log; a second day is slack for clock skew. */ +const CONNECTION_REQUEST_RETENTION_MS = 2 * DAY_MS +/** Session links expire after an hour; a day past that they only explain an old link. */ +const EXPIRED_SESSION_LINK_RETENTION_MS = DAY_MS +const CREDENTIAL_GROUP_PRUNE_BATCH_SIZE = 1_000 +/** Batches per table per run; a larger backlog drains over the next runs. */ +const MAX_BATCHES_PER_TABLE = 5 + +/** Runs a bounded batch delete until one comes up short or the batch cap is reached. */ +async function drain(deleteBatch: () => Promise): Promise { + let deleted = 0 + for (let batch = 0; batch < MAX_BATCHES_PER_TABLE; batch += 1) { + const count = await deleteBatch() + deleted += count + if (count < CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) break + } + return deleted +} + +/** + * Deletes workflow connection request log rows older than two days, and `self` and `connect` + * links that expired more than a day ago. Emailed links are kept: once bound, they outlive their + * expiry. A session link whose hash an enrollment's legacy invitation column still names is kept + * too, since deleting its row would let that token resolve through the column instead. Each + * batch takes its rows oldest first, skipping rows another run has locked. + */ +export async function pruneCredentialGroupConnectHistory( + now = new Date() +): Promise<{ connectionRequests: number; sessionLinks: number }> { + const requestCutoff = new Date(now.getTime() - CONNECTION_REQUEST_RETENTION_MS) + const linkCutoff = new Date(now.getTime() - EXPIRED_SESSION_LINK_RETENTION_MS) + const request = credentialGroupConnectionRequest + const link = credentialGroupEnrollmentLink + + const connectionRequests = await drain(async () => { + const removed = await db + .delete(request) + .where( + inArray( + request.id, + db + .select({ id: request.id }) + .from(request) + .where(lt(request.createdAt, requestCutoff)) + .orderBy(asc(request.createdAt)) + .limit(CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) + .for('update', { skipLocked: true }) + ) + ) + .returning({ id: request.id }) + return removed.length + }) + + const sessionLinks = await drain(async () => { + const removed = await db + .delete(link) + .where( + inArray( + link.id, + db + .select({ id: link.id }) + .from(link) + .where( + and( + inArray(link.purpose, ['self', 'connect']), + lt(link.expiresAt, linkCutoff), + sql`not exists (select 1 from ${credentialGroupEnrollment} where ${and( + eq(credentialGroupEnrollment.id, link.enrollmentId), + eq(credentialGroupEnrollment.invitationTokenHash, link.tokenHash) + )})` + ) + ) + .orderBy(asc(link.expiresAt)) + .limit(CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) + .for('update', { skipLocked: true }) + ) + ) + .returning({ id: link.id }) + return removed.length + }) + + if (connectionRequests > 0 || sessionLinks > 0) + logger.info('Pruned credential group connect history', { connectionRequests, sessionLinks }) + return { connectionRequests, sessionLinks } +} diff --git a/packages/db/migrations/0489_credential_group_enrollment_links.sql b/packages/db/migrations/0489_credential_group_enrollment_links.sql index c6bdc690a0d..7d171d4b903 100644 --- a/packages/db/migrations/0489_credential_group_enrollment_links.sql +++ b/packages/db/migrations/0489_credential_group_enrollment_links.sql @@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS "credential_group_enrollment_link" ( --> statement-breakpoint CREATE UNIQUE INDEX IF NOT EXISTS "credential_group_enrollment_link_token_hash_unique" ON "credential_group_enrollment_link" USING btree ("token_hash");--> statement-breakpoint CREATE INDEX IF NOT EXISTS "credential_group_enrollment_link_enrollment_id_idx" ON "credential_group_enrollment_link" USING btree ("enrollment_id");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "credential_group_enrollment_link_session_expires_at_idx" ON "credential_group_enrollment_link" USING btree ("expires_at") WHERE "credential_group_enrollment_link"."purpose" in ('self', 'connect');--> statement-breakpoint -- Backfill: each existing enrollment's current invitation becomes its first link. One row per -- enrollment (a small table), and ON CONFLICT on the unique token hash makes a replay a no-op. -- Rows the released app writes after this runs carry no link and resolve through the legacy diff --git a/packages/db/migrations/0490_credential_group_connection_requests.sql b/packages/db/migrations/0490_credential_group_connection_requests.sql index 0dd28cda3cc..dd82ca24ffc 100644 --- a/packages/db/migrations/0490_credential_group_connection_requests.sql +++ b/packages/db/migrations/0490_credential_group_connection_requests.sql @@ -1,4 +1,8 @@ -CREATE TABLE "credential_group_connection_request" ( +-- Expand: workflow connection requests. A request log the daily cap counts, the admin's request +-- policy, and two enrollment columns (the requesting workflow and its reminder count). Every +-- statement is idempotent: a replay after an earlier migration's embedded COMMIT re-runs this +-- file in autocommit. +CREATE TABLE IF NOT EXISTS "credential_group_connection_request" ( "id" text PRIMARY KEY NOT NULL, "credential_group_id" text NOT NULL, "email" text NOT NULL, @@ -8,7 +12,7 @@ CREATE TABLE "credential_group_connection_request" ( CONSTRAINT "credential_group_connection_request_normalized_email_check" CHECK ("credential_group_connection_request"."email" = lower(btrim("credential_group_connection_request"."email")) AND length("credential_group_connection_request"."email") BETWEEN 3 AND 320) ); --> statement-breakpoint -CREATE TABLE "credential_group_connection_request_policy" ( +CREATE TABLE IF NOT EXISTS "credential_group_connection_request_policy" ( "credential_group_id" text PRIMARY KEY NOT NULL, "policy" jsonb NOT NULL, "revision" integer DEFAULT 1 NOT NULL, @@ -18,10 +22,20 @@ CREATE TABLE "credential_group_connection_request_policy" ( CONSTRAINT "credential_group_connection_request_policy_revision_check" CHECK ("credential_group_connection_request_policy"."revision" >= 1) ); --> statement-breakpoint -ALTER TABLE "credential_group_enrollment" ADD COLUMN "requested_by_workflow_id" text;--> statement-breakpoint -ALTER TABLE "credential_group_enrollment" ADD COLUMN "connection_request_reminders" integer DEFAULT 0 NOT NULL;--> statement-breakpoint -ALTER TABLE "credential_group_connection_request" ADD CONSTRAINT "credential_group_connection_request_credential_group_id_credential_group_id_fk" FOREIGN KEY ("credential_group_id") REFERENCES "public"."credential_group"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "credential_group_connection_request_policy" ADD CONSTRAINT "credential_group_connection_request_policy_credential_group_id_credential_group_id_fk" FOREIGN KEY ("credential_group_id") REFERENCES "public"."credential_group"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "credential_group_connection_request_policy" ADD CONSTRAINT "credential_group_connection_request_policy_updated_by_user_id_fk" FOREIGN KEY ("updated_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint -CREATE INDEX "credential_group_connection_request_group_created_at_idx" ON "credential_group_connection_request" USING btree ("credential_group_id","created_at");--> statement-breakpoint -CREATE INDEX "credential_group_connection_request_group_email_created_at_idx" ON "credential_group_connection_request" USING btree ("credential_group_id","email","created_at"); \ No newline at end of file +ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "requested_by_workflow_id" text;--> statement-breakpoint +ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "connection_request_reminders" integer DEFAULT 0 NOT NULL;--> statement-breakpoint +DO $$ BEGIN + ALTER TABLE "credential_group_connection_request" ADD CONSTRAINT "credential_group_connection_request_credential_group_id_credential_group_id_fk" FOREIGN KEY ("credential_group_id") REFERENCES "public"."credential_group"("id") ON DELETE cascade ON UPDATE no action; +EXCEPTION WHEN duplicate_object THEN NULL; +END $$;--> statement-breakpoint +DO $$ BEGIN + ALTER TABLE "credential_group_connection_request_policy" ADD CONSTRAINT "credential_group_connection_request_policy_credential_group_id_credential_group_id_fk" FOREIGN KEY ("credential_group_id") REFERENCES "public"."credential_group"("id") ON DELETE cascade ON UPDATE no action; +EXCEPTION WHEN duplicate_object THEN NULL; +END $$;--> statement-breakpoint +DO $$ BEGIN + ALTER TABLE "credential_group_connection_request_policy" ADD CONSTRAINT "credential_group_connection_request_policy_updated_by_user_id_fk" FOREIGN KEY ("updated_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action; +EXCEPTION WHEN duplicate_object THEN NULL; +END $$;--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "credential_group_connection_request_group_created_at_idx" ON "credential_group_connection_request" USING btree ("credential_group_id","created_at");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "credential_group_connection_request_group_email_created_at_idx" ON "credential_group_connection_request" USING btree ("credential_group_id","email","created_at");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "credential_group_connection_request_created_at_idx" ON "credential_group_connection_request" USING btree ("created_at"); diff --git a/packages/db/migrations/meta/0489_snapshot.json b/packages/db/migrations/meta/0489_snapshot.json index fc6f9f3f9bd..f74c605f619 100644 --- a/packages/db/migrations/meta/0489_snapshot.json +++ b/packages/db/migrations/meta/0489_snapshot.json @@ -5822,6 +5822,22 @@ "concurrently": false, "method": "btree", "with": {} + }, + "credential_group_enrollment_link_session_expires_at_idx": { + "name": "credential_group_enrollment_link_session_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"credential_group_enrollment_link\".\"purpose\" in ('self', 'connect')", + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { diff --git a/packages/db/migrations/meta/0490_snapshot.json b/packages/db/migrations/meta/0490_snapshot.json index a2993a3c2a8..f028d7472a1 100644 --- a/packages/db/migrations/meta/0490_snapshot.json +++ b/packages/db/migrations/meta/0490_snapshot.json @@ -1,5 +1,5 @@ { - "id": "c5ec6216-7edd-48db-b20e-c98af878b359", + "id": "8f3072de-7078-4d5b-8379-60c0b92dc8d3", "prevId": "c545d68d-eef3-405a-89ea-36781560bffd", "version": "7", "dialect": "postgresql", @@ -5561,6 +5561,21 @@ "concurrently": false, "method": "btree", "with": {} + }, + "credential_group_connection_request_created_at_idx": { + "name": "credential_group_connection_request_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -6025,6 +6040,22 @@ "concurrently": false, "method": "btree", "with": {} + }, + "credential_group_enrollment_link_session_expires_at_idx": { + "name": "credential_group_enrollment_link_session_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"credential_group_enrollment_link\".\"purpose\" in ('self', 'connect')", + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index b1ca9428a60..be1ef852a0e 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -3428,7 +3428,7 @@ { "idx": 490, "version": "7", - "when": 1796327580611, + "when": 1796328036290, "tag": "0490_credential_group_connection_requests", "breakpoints": true } diff --git a/packages/db/schema.ts b/packages/db/schema.ts index 0cc04913066..663c8cd455d 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7499,6 +7499,10 @@ export const credentialGroupEnrollmentLink = pgTable( enrollmentIdx: index('credential_group_enrollment_link_enrollment_id_idx').on( table.enrollmentId ), + /** Retention deletes expired session links oldest first. */ + sessionExpiresAtIdx: index('credential_group_enrollment_link_session_expires_at_idx') + .on(table.expiresAt) + .where(sql`${table.purpose} in ('self', 'connect')`), tokenHashLength: check( 'credential_group_enrollment_link_token_hash_length_check', sql`length(${table.tokenHash}) = 64` @@ -7533,7 +7537,8 @@ export const credentialGroupConnectionRequestPolicy = pgTable( /** * One row per accepted workflow connection request, whatever the person's state, so the daily cap - * counts every request and reminder alike. Rows are never read after the cap's 24-hour window. + * counts every request and reminder alike. Rows are never read after the cap's 24-hour window and + * are pruned two days after they were written. */ export const credentialGroupConnectionRequest = pgTable( 'credential_group_connection_request', @@ -7555,6 +7560,8 @@ export const credentialGroupConnectionRequest = pgTable( groupEmailCreatedAtIdx: index( 'credential_group_connection_request_group_email_created_at_idx' ).on(table.credentialGroupId, table.email, table.createdAt), + /** Retention deletes rows past the cap's window oldest first, across every group. */ + createdAtIdx: index('credential_group_connection_request_created_at_idx').on(table.createdAt), normalizedEmail: check( 'credential_group_connection_request_normalized_email_check', sql`${table.email} = lower(btrim(${table.email})) AND length(${table.email}) BETWEEN 3 AND 320` diff --git a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts index 7b4d4d11d06..a8558d13784 100644 --- a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts +++ b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts @@ -21,7 +21,8 @@ export class MockCredentialGroupEnrollmentError extends Error { * `mockRevokeCredentialGroupEnrollmentLinks`, which resolve `undefined`, * `mockGetCredentialGroupEnrollmentLinkOptionId`, which resolves `null` (an unfocused link), and * `mockLiveEnrollmentLinkCondition`, which returns a `{ type: 'liveEnrollmentLink', tokenHash }` - * condition node a test can find in a WHERE tree. + * condition node a test can find in a WHERE tree, and `mockCreateUnissuedInvitationTokenHash`, + * which returns a fixed unissued placeholder. * * @example * ```ts @@ -64,6 +65,7 @@ export const credentialGroupsEnrollmentsMockFns = { mockIssueCredentialGroupConnectLink: vi.fn(), mockLoadCredentialGroupConnectSubject: vi.fn(), mockFindCredentialGroupEnrollmentLinkRecord: vi.fn(), + mockCreateUnissuedInvitationTokenHash: vi.fn((): string => `unissued:${'0'.repeat(55)}`), } const fns = credentialGroupsEnrollmentsMockFns @@ -103,4 +105,5 @@ export const credentialGroupsEnrollmentsMock = { issueCredentialGroupConnectLink: fns.mockIssueCredentialGroupConnectLink, loadCredentialGroupConnectSubject: fns.mockLoadCredentialGroupConnectSubject, findCredentialGroupEnrollmentLinkRecord: fns.mockFindCredentialGroupEnrollmentLinkRecord, + createUnissuedInvitationTokenHash: fns.mockCreateUnissuedInvitationTokenHash, } From 9e2a87e8d223ba84e9a7f4427912b3d1f4784e30 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 14:17:56 -0600 Subject: [PATCH 09/26] fix(credential-groups): connect UI, copy, and docs review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Integrations rows get Copy connect link; People drops the floating menu - People: Send reminder hidden only when connected or revoked, no menu on revoked rows, gray account chips, Loading… and request-led empty state - Workflow connection requests: clearer labels, All workspaces, free-mail warning through the field hint - Connect page: Connect your {Integration} account with a centered button, shorter not-invited copy, Return to Slack on dead ends (also on enroll) - Completion: Try again after a failed Integrations connection, Slack secondary on failure, failure-aware page title, Slack continue copy - Sign-in title, invitation email footer for workflow requests - Credential block: Integration labels, person@example.com placeholder, Request Connection guidance; docs follow --- .../docs/platform/connected-accounts.mdx | 6 +- .../docs/workflows/blocks/credential.mdx | 28 ++-- apps/sim/app/(auth)/login/login-form.tsx | 2 +- .../[publicId]/connect/page.tsx | 37 ++++- .../app/credential-groups/complete/page.tsx | 41 +++-- .../credential-groups/enroll/[token]/page.tsx | 20 ++- apps/sim/blocks/blocks/credential.ts | 26 ++-- .../credential-group-invitation-email.tsx | 8 +- .../organization-account-people.tsx | 140 +++++------------- .../organization-account-providers.tsx | 24 ++- .../organization-connected-accounts.tsx | 4 +- .../organization-connection-requests.tsx | 16 +- .../organization-person-connections.tsx | 11 +- 13 files changed, 178 insertions(+), 185 deletions(-) diff --git a/apps/docs/content/docs/platform/connected-accounts.mdx b/apps/docs/content/docs/platform/connected-accounts.mdx index a756ac26288..819f6408127 100644 --- a/apps/docs/content/docs/platform/connected-accounts.mdx +++ b/apps/docs/content/docs/platform/connected-accounts.mdx @@ -24,12 +24,12 @@ Open the organization's **Settings → Credential Groups**. If no pool exists, s | Tab | Purpose | | --- | --- | | **Integrations** | Add providers and manage their shared configuration | -| **People** | Request connections, inspect accounts, resend invitations, and revoke access | +| **People** | Request connections, inspect accounts, send reminders, and revoke access | | **Access** | Grant a workspace all or selected integrations | ### 1. Add integrations -In **Integrations**, select **Add integration**, search the catalog, and complete any required setup. Use **Configure** to change an added provider's settings or **Remove** in its menu to remove it. +In **Integrations**, select **Add integration**, search the catalog, and complete any required setup. Use **Configure** to change an added provider's settings, **Copy connect link** in its menu to share a link people open to connect it, or **Remove** in its menu to remove it. | Provider | Required organization setup | | --- | --- | @@ -62,7 +62,7 @@ On first use, the invitation email must match the signed-in user's verified Sim The verified Sim user who starts authorization must complete it. The provider account may have a different email; its contribution belongs to the bound Sim user. Managed MCP connections use that person's authorization too. Search separately checks current provider identity and source-specific access requirements. -Use **Resend** in a person's menu when they need the invitation again. **Revoke** stops the organization from using their contributions. They cannot undo an administrator's revocation by reconnecting themselves. +Use **Send reminder** in a person's menu when they need the invitation again. **Revoke** stops the organization from using their contributions. They cannot undo an administrator's revocation by reconnecting themselves. ### 3. Grant workspace access diff --git a/apps/docs/content/docs/workflows/blocks/credential.mdx b/apps/docs/content/docs/workflows/blocks/credential.mdx index a40963d2ab0..0a4295d4e36 100644 --- a/apps/docs/content/docs/workflows/blocks/credential.mdx +++ b/apps/docs/content/docs/workflows/blocks/credential.mdx @@ -25,11 +25,11 @@ A credential ID is a reference, not a token. The downstream block resolves and a | Operation | Behavior | | --- | --- | | **Select Credential** | Return one workspace OAuth credential reference. | -| **List Credentials** | Return workspace OAuth credential references, optionally filtered by providers. | -| **Find Organization Account** | Find exactly one active OAuth contribution by invitation email and provider. | -| **List Organization Accounts** | Page through active OAuth contributions, optionally filtered by email and providers. | -| **Get Connection Status** | Report whether a person has connected a provider, with a link they can open to connect it. | -| **Request Connection** | Ask a person to connect a provider, when an organization admin allows workflow requests. | +| **List Credentials** | Return workspace OAuth credential references, optionally filtered by integrations. | +| **Find Organization Account** | Find exactly one active OAuth contribution by invitation email and integration. | +| **List Organization Accounts** | Page through active OAuth contributions, optionally filtered by email and integrations. | +| **Get Connection Status** | Report whether a person has connected an integration, with a link they can open to connect it. | +| **Request Connection** | Ask a person to connect an integration, when an organization admin allows workflow requests. | | **Find Organization MCP Connection** | Find exactly one active managed MCP connection by invitation email and MCP provider. | | **List Organization MCP Connections** | Page through active managed MCP connections, optionally filtered by email and provider. | @@ -41,7 +41,7 @@ These operations do not select secrets or service accounts. Function can read a For **Select Credential**, choose **Credential** from the workspace's connected OAuth accounts. Advanced mode accepts a **Credential ID** copied from Credentials settings or resolved from an earlier output. -For **List Credentials**, optionally select one or more **Provider** values. The picker shows providers with connected credentials; leave it empty for all workspace OAuth credentials. +For **List Credentials**, optionally select one or more **Integrations**. The picker shows integrations with connected credentials; leave it empty for all workspace OAuth credentials. ### Organization accounts [#organization-accounts] @@ -51,10 +51,10 @@ Authorized workflows in an allowed workspace can discover active contributions f | Operation | Required | Optional | | --- | --- | --- | -| Find Organization Account | **Email**, **Provider** | — | -| List Organization Accounts | — | **Email**, **Providers**, **Limit**, **Cursor** | -| Get Connection Status | **Email**, **Provider** | — | -| Request Connection | **Email**, **Provider** | — | +| Find Organization Account | **Email**, **Integration** | — | +| List Organization Accounts | — | **Email**, **Integrations**, **Limit**, **Cursor** | +| Get Connection Status | **Email**, **Integration** | — | +| Request Connection | **Email**, **Integration** | — | | Find Organization MCP Connection | **Email**, **MCP provider** | — | | List Organization MCP Connections | — | **Email**, **MCP provider**, **Limit**, **Cursor** | @@ -99,11 +99,13 @@ For example, name the block **Account**, choose Find Organization Account, set E | `status` | `connected`, `not_connected`, or `needs_reconnect` | | `connected` | Whether a usable account exists | | `credentialId` | The account Find Organization Account would return, or `null` unless connected | -| `connectUrl` | A link the person opens to sign in to Sim and connect this provider | +| `connectUrl` | A link the person opens to sign in to Sim and connect this integration | The status never says whether the person was invited, removed, or never asked. `connectUrl` carries no secret: the page checks that the signed-in person is the one with that email before anything is connected, so it is safe to post, for example as a Slack button. -**Request Connection** returns `requested` and `connectUrl`. It works only when an admin turns on **Let workflows request connections** under **Connection requests from workflows** on the connected accounts **Access** tab, for the workflow's workspace, the person's email domain, and the provider. A request outside those settings, or past the daily limit, fails with an error. Otherwise the result is the same whether the person was already asked, already connected, or removed; a removed person is never re-invited. Use the person's primary address: an address with a `+` alias is refused. The daily limit counts every accepted request across all workspaces, including repeat requests for the same person. When the admin chose to also email the person, Sim emails the link with the workflow's name. It sends up to 3 reminders, each only when a workflow asks again after a day with no request for that person, and none after 30 days. +When `connected` is false, call **Request Connection** first (or make sure an admin invited the person), then show `connectUrl`. + +**Request Connection** returns `requested` and `connectUrl`. It works only when an admin turns on **Allow workflow requests** under **Workflow connection requests** in **Settings → Credential Groups → Access**, for the workflow's workspace, the person's email domain, and the integration. A request outside those settings, or past the daily limit, fails with an error. Otherwise the result is the same whether the person was already asked, already connected, or removed; a removed person is never re-invited. Use the person's primary address: an address with a `+` alias is refused. The daily limit counts every accepted request across all workspaces, including repeat requests for the same person. When the admin chose to also email the person, Sim emails the link with the workflow's name. It sends up to 3 reminders, each only when a workflow asks again after a day with no request for that person, and none after 30 days. ### Managed MCP @@ -122,7 +124,7 @@ Use `credentialId` to select the person's connection in an MCP Tool block. `mcpS ## List accounts and process each one -1. Name the Credential block **Accounts**. Select **List Credentials** and filter **Provider** to Gmail, or use **List Organization Accounts** and filter **Providers** to Gmail. +1. Name the Credential block **Accounts**. Select **List Credentials** and filter **Integrations** to Gmail, or use **List Organization Accounts** and filter **Integrations** to Gmail. 2. Pass `` into a For Each loop. 3. Inside the loop, set the Gmail credential to ``. 4. For organization lists, repeat with `nextCursor` while `hasMore` is true, preserving filters. diff --git a/apps/sim/app/(auth)/login/login-form.tsx b/apps/sim/app/(auth)/login/login-form.tsx index 989b10574c1..519b6f4a63e 100644 --- a/apps/sim/app/(auth)/login/login-form.tsx +++ b/apps/sim/app/(auth)/login/login-form.tsx @@ -442,7 +442,7 @@ export default function LoginPage({ <>
{connectFlow ? ( - + ) : ( )} diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index c574f750cf1..885c08443e8 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -13,6 +13,7 @@ import { enforcePublicCredentialGroupIpRateLimit, isCredentialGroupConnectUserRateLimited, } from '@/lib/credential-groups/rate-limit' +import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { AuthHeader } from '@/app/(auth)/components' import { CredentialGroupPageShell, @@ -48,6 +49,15 @@ function getSearchParam( const UNAVAILABLE_MESSAGE = 'This link isn’t available. Ask whoever sent it to check it’s still set up.' +/** + * Where a dead end sends the person back to: `return=slack` is the Slack app, and any other value + * must pass the Slack allowlist. Rendered only as a link the person clicks. + */ +function resolveSlackReturnHref(returnValue: string | undefined): string | undefined { + if (!returnValue) return undefined + return parseCredentialGroupReturnUrl(returnValue === 'slack' ? 'slack://open' : returnValue)?.href +} + /** * The secret-free link a workflow shows when someone has not connected an account yet. Signs the * person in, resolves their own enrollment, and hands off to the enrollment page with a @@ -64,6 +74,10 @@ export default async function CredentialGroupConnectPage({ const provider = getSearchParam(query, 'provider') const optionId = getSearchParam(query, 'optionId') const returnValue = getSearchParam(query, 'return') + const slackReturnHref = resolveSlackReturnHref(returnValue) + const recovery = slackReturnHref + ? { recoveryHref: slackReturnHref, recoveryLabel: 'Return to Slack' } + : {} const limited = await enforcePublicCredentialGroupIpRateLimit( { headers: await headers() }, @@ -71,7 +85,9 @@ export default async function CredentialGroupConnectPage({ ) if (limited) return if (!publicId || publicId.length > 128 || !provider || provider.length > 128) - return + return ( + + ) const callbackUrl = buildCredentialGroupConnectPath({ publicId, provider, optionId, returnValue }) @@ -115,11 +131,11 @@ export default async function CredentialGroupConnectPage({ if (returnValue) confirmQuery.set('return', returnValue) return ( - +
Connect {integration} @@ -133,12 +149,15 @@ export default async function CredentialGroupConnectPage({ return ( ) } case 'revoked': - return + return ( + + ) case 'choose_option': { const integration = getCredentialGroupProviderService(target.provider).name return ( @@ -166,6 +185,12 @@ export default async function CredentialGroupConnectPage({ ) } case 'unavailable': - return + return ( + + ) } } diff --git a/apps/sim/app/credential-groups/complete/page.tsx b/apps/sim/app/credential-groups/complete/page.tsx index 0a45460e317..219adbe252b 100644 --- a/apps/sim/app/credential-groups/complete/page.tsx +++ b/apps/sim/app/credential-groups/complete/page.tsx @@ -7,18 +7,25 @@ import { AuthHeader, AuthShell } from '@/app/(auth)/components' import { CredentialGroupCompletionHandoff } from '@/app/credential-groups/complete/completion-handoff' import { resolveCredentialGroupCompletionView } from '@/app/credential-groups/complete/completion-view' -export const metadata: Metadata = { - title: 'Accounts connected', - robots: { index: false, follow: false }, +interface CredentialGroupCompletePageProps { + searchParams: Promise> +} + +export async function generateMetadata({ + searchParams, +}: CredentialGroupCompletePageProps): Promise { + const { oauth } = await searchParams + return { + title: oauth === undefined ? 'Accounts connected' : 'Account not connected', + robots: { index: false, follow: false }, + } } export const dynamic = 'force-dynamic' export default async function CredentialGroupCompletePage({ searchParams, -}: { - searchParams: Promise> -}) { +}: CredentialGroupCompletePageProps) { const session = await getSession() const { failure, completionId, integrationsHref, slackReturnHref } = await resolveCredentialGroupCompletionView({ @@ -26,15 +33,21 @@ export default async function CredentialGroupCompletePage({ userId: session?.user.id, }) const error = failure ? CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure] : undefined - /** Rendered only as links the person clicks: no automatic hop to an external scheme. */ + /** + * Rendered only as links the person clicks: no automatic hop to an external scheme. After a + * failure, Integrations is where the connection started, so it is the way to try again. + */ const appLink = error || integrationsHref ? ( - - {integrationsHref ? 'Return to Integrations' : 'Open Sim'} + + {integrationsHref ? (error ? 'Try again' : 'Return to Integrations') : 'Open Sim'} ) : null const slackLink = slackReturnHref ? ( - + Return to Slack ) : null @@ -51,9 +64,11 @@ export default async function CredentialGroupCompletePage({ title={error ? 'Account not connected' : 'Accounts connected'} description={ error ?? - (integrationsHref - ? 'Returning to Integrations.' - : 'Your accounts are ready to use. You can close this tab.') + (slackReturnHref + ? 'Return to Slack to continue.' + : integrationsHref + ? 'Returning to Integrations.' + : 'Your accounts are ready to use. You can close this tab.') } /> {(appLink || slackLink) && ( diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index 0362a9f0290..c028bd25783 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -54,6 +54,8 @@ interface EnrollmentLinkProblemProps { signedInEmail: string callbackUrl: string fallbackMessage?: string + /** An allowlisted Slack destination, offered as the way out of a dead end. */ + slackReturnUrl?: string } function needsNewLinkCopy( @@ -72,7 +74,11 @@ function EnrollmentLinkProblem({ signedInEmail, callbackUrl, fallbackMessage, + slackReturnUrl, }: EnrollmentLinkProblemProps) { + const recovery = slackReturnUrl + ? { recoveryHref: slackReturnUrl, recoveryLabel: 'Return to Slack' } + : {} const organizationName = 'organizationName' in outcome && outcome.organizationName ? outcome.organizationName @@ -88,7 +94,12 @@ function EnrollmentLinkProblem({ ) case 'revoked': return ( - + ) case 'paused': return ( @@ -96,6 +107,7 @@ function EnrollmentLinkProblem({ token={token} title='Connections paused' message={`${organizationName} isn’t collecting account connections right now.`} + {...recovery} /> ) case 'needs_new_link': @@ -104,12 +116,13 @@ function EnrollmentLinkProblem({ token={token} title={outcome.reason === 'expired' ? 'Link expired' : 'Link no longer active'} message={needsNewLinkCopy(outcome)} + {...recovery} /> ) case 'unavailable': - return + return case 'unknown': - return + return } } @@ -207,6 +220,7 @@ export default async function CredentialGroupEnrollmentPage({ signedInEmail={signedInUser.email} callbackUrl={callbackUrl} fallbackMessage={fallbackMessage} + slackReturnUrl={slackReturnUrl} /> ) const principal = await authenticateCredentialGroupEnrollment(token) diff --git a/apps/sim/blocks/blocks/credential.ts b/apps/sim/blocks/blocks/credential.ts index e8f7a5531e2..906d7ec05c1 100644 --- a/apps/sim/blocks/blocks/credential.ts +++ b/apps/sim/blocks/blocks/credential.ts @@ -24,16 +24,16 @@ export const CredentialBlock: BlockConfig = { description: 'Select credentials, find organization accounts and MCP connections, or ask people to connect', longDescription: - 'Select workspace OAuth credentials or find and list organization accounts in an allowlisted workspace. List Organization Accounts discovers connected accounts by provider without requiring an email. An optional exact enrollment email narrows the list. Only active accounts for integrations allowed in the executing workspace are returned; disconnected accounts are excluded. Results are paginated using hasMore and nextCursor. Get Connection Status reports whether a person has connected an integration and returns a link they can open to connect it. Request Connection asks them to connect, when an organization admin allows workflow connection requests. Manage invitations in organization settings.', + 'Select workspace OAuth credentials or find and list organization accounts in an allowlisted workspace. List Organization Accounts discovers connected accounts by integration without requiring an email. An optional exact enrollment email narrows the list. Only active accounts for integrations allowed in the executing workspace are returned; disconnected accounts are excluded. Results are paginated using hasMore and nextCursor. Get Connection Status reports whether a person has connected an integration and returns a link they can open to connect it. Request Connection asks them to connect, when an organization admin allows workflow connection requests. Manage invitations in organization settings.', bestPractices: ` - Use "Select Credential" to define an OAuth credential once and reference in multiple downstream blocks instead of repeating credential IDs. - Use "List Credentials" with a ForEach loop to iterate over all OAuth accounts (e.g. all Gmail accounts). - - Use the Provider filter to narrow results to specific services (e.g. Gmail, Slack). - - Use "List Organization Accounts" with Providers selected and Email blank to discover all accessible accounts for those integrations. + - Use the Integrations filter to narrow results to specific services (e.g. Gmail, Slack). + - Use "List Organization Accounts" with Integrations selected and Email blank to discover all accessible accounts for those integrations. - Organization lists return one page at a time. While hasMore is true, pass nextCursor as Cursor with the same filters to get every matching account. - - "Find Organization Account" requires an exact enrollment email and provider, and returns that person's first connected account for the provider, or fails if there is none. Use "List Organization Accounts" to reach their other accounts. - - Use "Get Connection Status" before acting for a person: when connected is false, show them connectUrl (for example as a Slack button). The status is only connected, not_connected, or needs_reconnect. - - Use "Request Connection" to also notify the person, when organization settings allow workflow connection requests for that email domain and integration. It returns the same result whatever the person's state. + - "Find Organization Account" requires an exact enrollment email and integration, and returns that person's first connected account for the integration, or fails if there is none. Use "List Organization Accounts" to reach their other accounts. + - Use "Get Connection Status" before acting for a person. When connected is false, call "Request Connection" first (or make sure an admin invited the person), then show connectUrl, for example as a Slack button. The status is only connected, not_connected, or needs_reconnect. + - "Request Connection" works when organization settings allow workflow connection requests for that email domain and integration. It returns the same result whatever the person's state. - Outputs contain account identities and credential references, never secret values. - To switch credentials across environments, replace the single Credential block rather than updating every downstream block. `, @@ -93,7 +93,7 @@ export const CredentialBlock: BlockConfig = { }, { id: 'providerFilter', - title: 'Provider', + title: 'Integrations', type: 'dropdown', selectorKey: 'workspace.credentialProviders', multiSelect: true, @@ -121,7 +121,7 @@ export const CredentialBlock: BlockConfig = { }, { id: 'organizationProvider', - title: 'Provider', + title: 'Integration', type: 'dropdown', selectorKey: 'workspace.credentialGroupProviders', condition: { @@ -132,9 +132,9 @@ export const CredentialBlock: BlockConfig = { }, { id: 'organizationProviders', - title: 'Providers', + title: 'Integrations', type: 'dropdown', - placeholder: 'All allowed providers', + placeholder: 'All allowed integrations', emptyIsValid: true, multiSelect: true, selectorKey: 'workspace.credentialGroupProviders', @@ -152,7 +152,7 @@ export const CredentialBlock: BlockConfig = { id: 'email', title: 'Email', type: 'short-input', - placeholder: 'Optional for lists; exact enrollment email', + placeholder: 'person@example.com', condition: { field: 'operation', value: ORGANIZATION_OPERATIONS }, required: { field: 'operation', @@ -232,13 +232,13 @@ export const CredentialBlock: BlockConfig = { }, connected: { type: 'boolean', - description: 'Whether the person has a usable account for the provider', + description: 'Whether the person has a usable account for the integration', condition: { field: 'operation', value: 'get_connection_status' }, }, connectUrl: { type: 'string', description: - 'Link the person opens to sign in and connect this provider. Safe to share; it carries no secret.', + 'Link the person opens to sign in and connect this integration. Safe to share; it carries no secret.', condition: { field: 'operation', value: CONNECTION_OPERATIONS }, }, requested: { diff --git a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx index 49028b4d71f..f27efe034f6 100644 --- a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx +++ b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx @@ -89,7 +89,7 @@ export function CredentialGroupInvitationEmail({ - {providerName ? `Connect ${providerName}` : 'Connect Accounts'} + {providerName ? `Connect ${providerName}` : 'Connect accounts'} @@ -97,10 +97,8 @@ export function CredentialGroupInvitationEmail({ {workflowRequest - ? `Sign in to Sim as ${recipientEmail} to continue. ` - : 'This private link expires in 7 days. '} - Sim will send you to each provider to sign in and will never ask for your provider password. - If you did not expect this invitation, you can ignore it. + ? `Sign in to Sim as ${recipientEmail} to continue. Sim will send you to ${workflowRequest.providerName} to sign in and will never ask for your ${workflowRequest.providerName} password. If you did not expect this request, you can ignore it.` + : 'This private link expires in 7 days. Sim will send you to each provider to sign in and will never ask for your provider password. If you did not expect this invitation, you can ignore it.'} ) diff --git a/apps/sim/ee/credential-groups/components/organization-account-people.tsx b/apps/sim/ee/credential-groups/components/organization-account-people.tsx index 9d96f864ac8..8d35091c8fb 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-people.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-people.tsx @@ -1,29 +1,9 @@ 'use client' import { useState } from 'react' -import { - Avatar, - Badge, - Chip, - ChipConfirmModal, - ChipModalError, - chipVariants, - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, - toast, - writeTextToClipboard, -} from '@sim/emcn' +import { Avatar, Badge, Chip, ChipConfirmModal, ChipModalError, toast } from '@sim/emcn' import { Plus } from '@sim/emcn/icons' import type { CredentialGroupEnrollmentDetail } from '@/lib/api/contracts/credential-groups' -import type { OrganizationAccountsSettings } from '@/lib/api/contracts/organization-accounts' -import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' -import { - type CredentialGroupProvider, - getCredentialGroupProviderId, - getCredentialGroupProviderService, -} from '@/lib/credential-groups/providers' import { SEARCH_DEBOUNCE_MS } from '@/lib/url-state' import { RowActionsMenu } from '@/app/workspace/[workspaceId]/settings/components/row-actions-menu' import { @@ -47,42 +27,6 @@ import { useOrganizationAccountPeopleSearch } from '@/hooks/use-organization-acc interface OrganizationAccountPeopleProps { organizationId: string - group: NonNullable -} - -interface CopyConnectLinkMenuProps { - publicId: string - providers: CredentialGroupProvider[] -} - -/** - * Copies the stable connect URL for one integration. The URL carries no secret: whoever opens it - * signs in and only reaches their own enrollment. - */ -function CopyConnectLinkMenu({ publicId, providers }: CopyConnectLinkMenuProps) { - const copy = (provider: CredentialGroupProvider) => - writeTextToClipboard( - buildCredentialGroupConnectUrl({ publicId, provider: getCredentialGroupProviderId(provider) }) - ).then( - () => toast.success('Link copied'), - () => toast.error('Could not copy the link') - ) - return ( - - - - - - {providers.map((provider) => ( - void copy(provider)}> - {getCredentialGroupProviderService(provider).name} - - ))} - - - ) } const PERSON_STATUS_BADGES = { @@ -113,10 +57,7 @@ function getPersonStatus( return 'invited' } -export function OrganizationAccountPeople({ - organizationId, - group, -}: OrganizationAccountPeopleProps) { +export function OrganizationAccountPeople({ organizationId }: OrganizationAccountPeopleProps) { const resend = useResendOrganizationAccountInvitation() const revoke = useRevokeOrganizationAccountEnrollment() const [peopleSearch, setPeopleSearch] = useOrganizationAccountPeopleSearch() @@ -127,11 +68,6 @@ export function OrganizationAccountPeople({ const error = resend.error ?? revoke.error const pending = resend.isPending || revoke.isPending const enrollments = people.data?.pages.flatMap((page) => page.enrollments) ?? [] - const connectProviders = [ - ...new Set( - group.options.filter((option) => option.status === 'active').map((option) => option.provider) - ), - ] return ( - {connectProviders.length > 0 && ( -
- -
- )} - {people.isPending && ( - Loading people… - )} + {people.isPending && Loading…} {people.error && !people.isFetchNextPageError && ( {enrollments.length === 0 ? ( - {search ? 'No people match your search' : 'No people invited yet'} + {search ? 'No people match your search' : 'No connection requests yet'} ) : (
{enrollments.map((person) => { - const status = PERSON_STATUS_BADGES[getPersonStatus(person)] - const revoked = person.status === 'revoked' + const personStatus = getPersonStatus(person) + const status = PERSON_STATUS_BADGES[personStatus] + const revoked = personStatus === 'revoked' return ( } trailing={ - - resend.mutate( - { organizationId, enrollmentId: person.id }, - { onSuccess: () => toast.success('Reminder sent') } - ), - }, - ]), - { - label: 'Revoke', - destructive: true, - disabled: pending || revoked, - onSelect: () => { - revoke.reset() - setRevokingPerson({ id: person.id, email: person.email }) + revoked ? undefined : ( + + resend.mutate( + { organizationId, enrollmentId: person.id }, + { onSuccess: () => toast.success('Reminder sent') } + ), + }, + ]), + { + label: 'Revoke', + destructive: true, + disabled: pending, + onSelect: () => { + revoke.reset() + setRevokingPerson({ id: person.id, email: person.email }) + }, }, - }, - ]} - /> + ]} + /> + ) } /> ) @@ -226,7 +158,7 @@ export function OrganizationAccountPeople({ )} {people.hasNextPage && !people.isFetchNextPageError && ( void people.fetchNextPage()}> - {people.isFetchingNextPage ? 'Loading...' : 'Load more'} + {people.isFetchingNextPage ? 'Loading…' : 'Load more'} )} diff --git a/apps/sim/ee/credential-groups/components/organization-account-providers.tsx b/apps/sim/ee/credential-groups/components/organization-account-providers.tsx index 9d2827648eb..eadfbb6f0a8 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-providers.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-providers.tsx @@ -10,11 +10,13 @@ import { ChipModalFooter, ChipModalHeader, toast, + writeTextToClipboard, } from '@sim/emcn' import { Plus } from '@sim/emcn/icons' import { getErrorMessage } from '@sim/utils/errors' import { useQueryState } from 'nuqs' import type { OrganizationAccountsSettings } from '@/lib/api/contracts/organization-accounts' +import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' import { getManagedMcpConnectorIcon } from '@/lib/credential-groups/managed-mcp-connector-icons' import { MANAGED_MCP_CONNECTORS, @@ -23,6 +25,7 @@ import { import { getOrganizationAccountUpdateOptions } from '@/lib/credential-groups/organization-account-options' import { type CredentialGroupProvider, + getCredentialGroupProviderId, getCredentialGroupProviderService, } from '@/lib/credential-groups/providers' import { @@ -51,6 +54,19 @@ import { } from '@/hooks/queries/organization-accounts' import { useDebouncedSearchSetter } from '@/hooks/use-debounced-search-setter' +/** + * Copies the stable connect URL for one integration. The URL carries no secret: whoever opens it + * signs in and only reaches their own enrollment. + */ +function copyConnectLink(publicId: string, provider: CredentialGroupProvider) { + void writeTextToClipboard( + buildCredentialGroupConnectUrl({ publicId, provider: getCredentialGroupProviderId(provider) }) + ).then( + () => toast.success('Link copied'), + () => toast.error('Could not copy the link') + ) +} + interface OrganizationAccountProvidersProps { organizationId: string group: NonNullable @@ -157,6 +173,10 @@ export function OrganizationAccountProviders({ name: service.name, icon: service.icon, configure: option.provider === 'slack' ? () => setSlackOpen(true) : undefined, + copyLink: + option.status === 'active' + ? () => copyConnectLink(group.publicId, option.provider) + : undefined, choice: { kind: 'oauth', provider: option.provider } as const, } }), @@ -171,6 +191,7 @@ export function OrganizationAccountProviders({ icon: getManagedMcpConnectorIcon(server.managedConnectorId), configure: server.managedConnectorId === 'databricks' ? () => setDatabricksOpen(true) : undefined, + copyLink: undefined, choice: { kind: 'mcp', connectorId: server.managedConnectorId } as const, })), ].sort((left, right) => left.name.localeCompare(right.name)) @@ -222,7 +243,7 @@ export function OrganizationAccountProviders({ } >
- {visibleRows.map(({ id, name, icon: Icon, configure, choice }) => ( + {visibleRows.map(({ id, name, icon: Icon, configure, copyLink, choice }) => ( )} - {tab === 'people' && ( - - )} + {tab === 'people' && } {tab === 'workspace-access' && ( )} diff --git a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx index 3084d467e85..ebb40f4ae54 100644 --- a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx +++ b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx @@ -31,8 +31,8 @@ import { type Policy = NonNullable const ALL_WORKSPACES = 'all' -const SECTION_LABEL = 'Connection requests from workflows' -const TOGGLE_LABEL = 'Let workflows request connections' +const SECTION_LABEL = 'Workflow connection requests' +const TOGGLE_LABEL = 'Allow workflow requests' const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? '' : 's'}` @@ -184,7 +184,7 @@ function ConnectionRequestPolicyModal({ ({ value: workspace.id, label: workspace.name, @@ -222,13 +222,9 @@ function ConnectionRequestPolicyModal({ onChange={setDomains} placeholder='example.com' hint={ - freeMailDomains.length ? ( - - Anyone with a {freeMailDomains.join(', ')} address could be asked - - ) : ( - "Exact domains only; subdomains aren't included" - ) + freeMailDomains.length + ? `Anyone with a ${freeMailDomains.join(', ')} address could be asked` + : "Exact domains only; subdomains aren't included" } disabled={disabled} /> diff --git a/apps/sim/ee/credential-groups/components/organization-person-connections.tsx b/apps/sim/ee/credential-groups/components/organization-person-connections.tsx index 1ee65beeff9..dbc73fe101f 100644 --- a/apps/sim/ee/credential-groups/components/organization-person-connections.tsx +++ b/apps/sim/ee/credential-groups/components/organization-person-connections.tsx @@ -75,16 +75,7 @@ export function OrganizationPersonConnections({ person }: OrganizationPersonConn {accounts.map(({ key, name, icon, count, needsReconnect }) => { const label = count > 1 ? `${name} (${count})` : name return ( - + ) From 9f23d7e913367e3edc3514432d9467cb117c7f70 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 15:27:02 -0600 Subject: [PATCH 10/26] refactor(credential-groups): split enrollment links and the connect flow out of enrollments - links.ts holds link storage: liveness condition (now an indexed primary-key lookup instead of an EXISTS-or-legacy filter that scanned every enrollment), its TypeScript expiry rule, link insertion shared by emailed, self and connect links, legacy adoption, the link record reader, and the focus error with a code-based predicate the routes use. - connect-subject.ts loads the connect target and mints the connect link, self-enrolling and binding in the same locked transaction. - The connect page resolves read-only, then a separate start operation writes and audits; a revocation racing it reports revoked, an unfinished setup reports unavailable. - Explaining a failed link is a defined use case; an expired connect link offers Start again, and a failed delivery is no longer an outcome. - The confirmation POST requires a same-origin request and has its own rate-limit bucket. - An admin reinvitation clears a workflow's request marker and reminder count. - Workflow connection lookups read the policy and public ID from the resolved context and refuse through one pure policy check. - Completion redirects take an options object; one DAY_MS and invitation lifetime. - README and 0489 record link lifetimes, revocation semantics during deploy, and the contract phase for the legacy invitation column. --- .../connect/[publicId]/route.test.ts | 59 +++ .../connect/[publicId]/route.ts | 24 +- .../enroll/[token]/complete/route.ts | 13 +- .../enroll/[token]/mcp/[mcpServerId]/route.ts | 4 +- .../enroll/[token]/oauth/[optionId]/route.ts | 8 +- .../credential-groups/enrollment-redirect.ts | 21 +- .../api/credential-groups/oauth-callback.ts | 18 +- .../knowledge/github/setup/callback/route.ts | 2 +- .../knowledge/github/setup/continue/route.ts | 5 +- apps/sim/app/api/mcp/oauth/callback/route.ts | 17 +- .../[publicId]/connect/page.tsx | 30 +- .../enroll/[token]/page.test.tsx | 2 +- .../credential-groups/enroll/[token]/page.tsx | 35 +- apps/sim/lib/credential-groups/README.md | 21 + .../connect-target.integration.ts | 46 +- .../enrollment-link-outcome.integration.ts | 154 ++++-- .../enrollment-links.integration.ts | 43 +- .../application/connect-target.ts | 345 +++++++----- .../application/connection-requests.ts | 77 ++- .../application/enrollment-link-outcome.ts | 133 +++-- .../organization-workspace-access.ts | 2 + .../personal-organization-accounts.ts | 4 +- .../application/public-enrollment.ts | 10 +- .../lib/credential-groups/connect-subject.ts | 231 ++++++++ .../connection-request-policy.ts | 33 +- .../credential-groups/connection-requests.ts | 31 +- apps/sim/lib/credential-groups/credentials.ts | 1 + apps/sim/lib/credential-groups/email-mask.ts | 6 + apps/sim/lib/credential-groups/enrollments.ts | 498 ++++-------------- apps/sim/lib/credential-groups/limits.ts | 1 + apps/sim/lib/credential-groups/links.ts | 349 ++++++++++++ apps/sim/lib/credential-groups/oauth.ts | 2 +- .../lib/credential-groups/provider-adapter.ts | 9 - apps/sim/lib/credential-groups/rate-limit.ts | 4 +- apps/sim/lib/credentials/managed-mcp.ts | 6 +- ...0489_credential_group_enrollment_links.sql | 3 + .../credential-groups-enrollments.mock.ts | 29 +- 37 files changed, 1476 insertions(+), 800 deletions(-) create mode 100644 apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts create mode 100644 apps/sim/lib/credential-groups/connect-subject.ts create mode 100644 apps/sim/lib/credential-groups/email-mask.ts create mode 100644 apps/sim/lib/credential-groups/links.ts diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts new file mode 100644 index 00000000000..1e77d88c8c8 --- /dev/null +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts @@ -0,0 +1,59 @@ +/** + * The connect page's confirmation POST enrolls the signed-in person, so it must only act on a + * request a page on this origin sent. Failure modes: a cross-site form post, a post from another + * origin whose browser sends no `Sec-Fetch-Site`, and a client that sends neither header, each of + * which must be refused before the person is enrolled; a same-origin post must still go through. + */ +import { authMockFns } from '@sim/testing' +import { createMockRequest } from '@sim/testing/mocks/request.mock' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { mockStart } = vi.hoisted(() => ({ mockStart: vi.fn() })) + +vi.mock('@/lib/credential-groups/application/connect-target', () => ({ + startCredentialGroupConnect: { execute: mockStart }, +})) +vi.mock('@/lib/credential-groups/rate-limit', () => ({ + enforcePublicCredentialGroupIpRateLimit: async () => null, + isCredentialGroupConnectUserRateLimited: async () => false, +})) + +import { POST } from '@/app/api/credential-groups/connect/[publicId]/route' + +function confirm(headers: Record) { + return POST( + createMockRequest({ + method: 'POST', + url: 'http://localhost:3000/api/credential-groups/connect/public-1?provider=google-drive', + headers, + }), + { params: Promise.resolve({ publicId: 'public-1' }) } + ) +} + +describe('POST /api/credential-groups/connect/[publicId]', () => { + beforeEach(() => { + authMockFns.mockGetSession.mockResolvedValue({ + user: { id: 'user-1', emailVerified: true }, + session: { id: 'session-1' }, + }) + mockStart.mockResolvedValue({ kind: 'ready', invitationToken: 'token-1', optionId: 'drive' }) + }) + + it.each([ + ['a cross-site form post', { 'sec-fetch-site': 'cross-site' }], + ['a same-site sibling origin', { 'sec-fetch-site': 'same-site' }], + ['another origin with no Sec-Fetch-Site', { origin: 'https://attacker.example' }], + ['a client sending neither header', {}], + ])('refuses %s', async (_label, headers) => { + const response = await confirm(headers) + expect(response.status).toBe(403) + expect(response.headers.get('location')).toBeNull() + }) + + it('continues a same-origin post to the enrollment page', async () => { + const response = await confirm({ 'sec-fetch-site': 'same-origin' }) + expect(response.status).toBe(303) + expect(response.headers.get('location')).toMatch(/^\/credential-groups\/enroll\/token-1\?/) + }) +}) diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts index 52cf1f45e56..393d7b17188 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts @@ -3,8 +3,9 @@ import { NextResponse } from 'next/server' import { confirmCredentialGroupConnectContract } from '@/lib/api/contracts/credential-groups' import { parseRequest } from '@/lib/api/server' import { getSession } from '@/lib/auth' +import { isSameOrigin } from '@/lib/core/utils/validation' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' +import { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' import { buildCredentialGroupConnectHandoffPath, buildCredentialGroupConnectPath, @@ -24,6 +25,18 @@ function seeOther(location: string): NextResponse { }) } +/** + * Whether the POST came from a page on this origin. The browser sets `Sec-Fetch-Site` and + * `Origin` and page script cannot forge either, so a cross-site form or a `same-site` sibling + * subdomain cannot enroll the signed-in person. A client that sends neither is refused. + */ +function isSameOriginPost(request: NextRequest): boolean { + const fetchSite = request.headers.get('sec-fetch-site') + if (fetchSite) return fetchSite === 'same-origin' + const origin = request.headers.get('origin') + return origin !== null && isSameOrigin(origin) +} + /** * The connect page's "Connect" button for an organization member with no enrollment: enrolls * them and continues to the focused enrollment page. Any other outcome goes back to the connect @@ -31,7 +44,12 @@ function seeOther(location: string): NextResponse { */ export const POST = withRouteHandler( async (request: NextRequest, context: { params: Promise<{ publicId: string }> }) => { - const limited = await enforcePublicCredentialGroupIpRateLimit(request, 'metadata') + if (!isSameOriginPost(request)) + return NextResponse.json( + { error: 'Cross-site request refused' }, + { status: 403, headers: { 'Cache-Control': 'no-store' } } + ) + const limited = await enforcePublicCredentialGroupIpRateLimit(request, 'connect-confirm') if (limited) return limited const parsed = await parseRequest(confirmCredentialGroupConnectContract, request, context) @@ -49,7 +67,7 @@ export const POST = withRouteHandler( if (!session?.user?.emailVerified) return seeOther(connectPath) if (await isCredentialGroupConnectUserRateLimited(session.user.id)) return seeOther(connectPath) - const target = await resolveCredentialGroupConnectTarget.execute({ + const target = await startCredentialGroupConnect.execute({ principal: { kind: 'session', userId: session.user.id, sessionId: session.session.id }, input: { publicId, diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts index 59135e2dd08..d54ae38ac6f 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts @@ -5,7 +5,7 @@ import { asOrchestrationError } from '@/lib/core/orchestration/types' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { authenticateCredentialGroupEnrollment } from '@/lib/credential-groups/application/enrollment-auth' import { completePublicCredentialGroupEnrollment } from '@/lib/credential-groups/application/public-enrollment' -import { CredentialGroupLinkFocusError } from '@/lib/credential-groups/provider-adapter' +import { isCredentialGroupLinkFocusError } from '@/lib/credential-groups/links' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' import { createCredentialGroupCompletionRedirect, @@ -34,17 +34,14 @@ export const POST = withRouteHandler( const completion = await completePublicCredentialGroupEnrollment .execute({ principal, input: returnUrl ? { returnUrl } : {}, request }) .catch((error: unknown) => { - if (error instanceof CredentialGroupLinkFocusError) return 'focused' as const + if (isCredentialGroupLinkFocusError(error)) return 'focused' as const if (asOrchestrationError(error)?.code === 'not_found') return null throw error }) if (completion === 'focused') return backToEnrollment('other_option') if (!completion || completion.completed === null) return backToEnrollment('unavailable') - return createCredentialGroupCompletionRedirect( - undefined, - undefined, - undefined, - completion.completionReturnId - ) + return createCredentialGroupCompletionRedirect({ + completionReturnId: completion.completionReturnId, + }) } ) diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts index 640e9761ef9..b4d61d1a8e7 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts @@ -7,7 +7,7 @@ import { parseRequest } from '@/lib/api/server' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { authenticateCredentialGroupEnrollment } from '@/lib/credential-groups/application/enrollment-auth' import { startPublicCredentialGroupMcpOAuth } from '@/lib/credential-groups/application/public-enrollment' -import { CredentialGroupLinkFocusError } from '@/lib/credential-groups/provider-adapter' +import { isCredentialGroupLinkFocusError } from '@/lib/credential-groups/links' import { enforceCredentialGroupEnrollmentOAuthRateLimit, enforcePublicCredentialGroupOAuthStartIpRateLimit, @@ -64,7 +64,7 @@ export const GET = withRouteHandler( response.headers.set('Referrer-Policy', 'no-referrer') return response } catch (error) { - if (error instanceof CredentialGroupLinkFocusError) return backToEnrollment('other_option') + if (isCredentialGroupLinkFocusError(error)) return backToEnrollment('other_option') logger.error('Failed to start managed MCP OAuth authorization', { error: getErrorMessage(error), }) diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts index 6ba213f5d53..a564e45884e 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts @@ -7,10 +7,8 @@ import { parseRequest } from '@/lib/api/server' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { authenticateCredentialGroupEnrollment } from '@/lib/credential-groups/application/enrollment-auth' import { startPublicCredentialGroupOAuth } from '@/lib/credential-groups/application/public-enrollment' -import { - CredentialGroupLinkFocusError, - CredentialGroupOAuthError, -} from '@/lib/credential-groups/provider-adapter' +import { isCredentialGroupLinkFocusError } from '@/lib/credential-groups/links' +import { CredentialGroupOAuthError } from '@/lib/credential-groups/provider-adapter' import { enforceCredentialGroupEnrollmentOAuthRateLimit, enforcePublicCredentialGroupOAuthStartIpRateLimit, @@ -69,7 +67,7 @@ export const GET = withRouteHandler( response.headers.set('Referrer-Policy', 'no-referrer') return response } catch (error) { - if (error instanceof CredentialGroupLinkFocusError) + if (isCredentialGroupLinkFocusError(error)) return createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth: 'other_option' }) logger.error('Failed to start managed OAuth authorization', { error: getErrorMessage(error), diff --git a/apps/sim/app/api/credential-groups/enrollment-redirect.ts b/apps/sim/app/api/credential-groups/enrollment-redirect.ts index 43eadeeab8b..b4abdb74db0 100644 --- a/apps/sim/app/api/credential-groups/enrollment-redirect.ts +++ b/apps/sim/app/api/credential-groups/enrollment-redirect.ts @@ -21,16 +21,25 @@ export function createCredentialGroupEnrollmentRedirect( }) } +interface CredentialGroupCompletionRedirectOptions { + oauth?: CredentialGroupOAuthFailure + completionId?: string + /** Set when the connection started from the organization's Integrations page. */ + organizationId?: string + /** The opaque ID of a Slack return destination the server stored for the person. */ + completionReturnId?: string +} + /** * Sends the person to the completion page. A Slack return travels only as `completionReturnId`, * the opaque ID of a destination the server stored for them, never as a URL in the query. */ -export function createCredentialGroupCompletionRedirect( - oauth?: CredentialGroupOAuthFailure, - completionId?: string, - organizationId?: string, - completionReturnId?: string -): NextResponse { +export function createCredentialGroupCompletionRedirect({ + oauth, + completionId, + organizationId, + completionReturnId, +}: CredentialGroupCompletionRedirectOptions = {}): NextResponse { const query = new URLSearchParams() if (oauth) query.set('oauth', oauth) if (completionId) query.set('completionId', completionId) diff --git a/apps/sim/app/api/credential-groups/oauth-callback.ts b/apps/sim/app/api/credential-groups/oauth-callback.ts index 1a25ef698f3..d3eacbd1cb0 100644 --- a/apps/sim/app/api/credential-groups/oauth-callback.ts +++ b/apps/sim/app/api/credential-groups/oauth-callback.ts @@ -58,15 +58,15 @@ export async function handleCredentialGroupOAuthCallback({ attempt = await consumeCredentialGroupOAuthAttempt(state) } catch (error) { if (error instanceof CredentialGroupOAuthStateVersionError) { - return createCredentialGroupCompletionRedirect('expired') + return createCredentialGroupCompletionRedirect({ oauth: 'expired' }) } logger.error('Failed to consume credential group OAuth state', { error: getErrorMessage(error), }) - return createCredentialGroupCompletionRedirect('unavailable') + return createCredentialGroupCompletionRedirect({ oauth: 'unavailable' }) } if (!attempt || attempt.provider !== provider) { - return createCredentialGroupCompletionRedirect(limited ? 'rate_limited' : 'expired') + return createCredentialGroupCompletionRedirect({ oauth: limited ? 'rate_limited' : 'expired' }) } /** The return destination comes only from server-held attempt state, never the callback query. */ const focus: Record = { @@ -90,15 +90,15 @@ export async function handleCredentialGroupOAuthCallback({ const returnOrganizationId = attempt.returnTo === 'integrations' ? attempt.organizationId : undefined const completionRedirect = async (oauth?: CredentialGroupOAuthFailure) => - createCredentialGroupCompletionRedirect( + createCredentialGroupCompletionRedirect({ oauth, - attempt.completionId, - returnOrganizationId, - await createCredentialGroupCompletionReturn({ + completionId: attempt.completionId, + organizationId: returnOrganizationId, + completionReturnId: await createCredentialGroupCompletionReturn({ userId: attempt.userId, returnUrl: attempt.returnUrl, - }) - ) + }), + }) const failureRedirect = async (oauth: CredentialGroupOAuthFailure) => installationSetup ? setupRedirect(oauth) diff --git a/apps/sim/app/api/knowledge/github/setup/callback/route.ts b/apps/sim/app/api/knowledge/github/setup/callback/route.ts index c951aea0316..3e91ba32df0 100644 --- a/apps/sim/app/api/knowledge/github/setup/callback/route.ts +++ b/apps/sim/app/api/knowledge/github/setup/callback/route.ts @@ -46,6 +46,6 @@ export const GET = withRouteHandler(async (request) => { }, }) } catch { - return createCredentialGroupCompletionRedirect('unavailable') + return createCredentialGroupCompletionRedirect({ oauth: 'unavailable' }) } }) diff --git a/apps/sim/app/api/knowledge/github/setup/continue/route.ts b/apps/sim/app/api/knowledge/github/setup/continue/route.ts index cdd918855de..c304c8c3376 100644 --- a/apps/sim/app/api/knowledge/github/setup/continue/route.ts +++ b/apps/sim/app/api/knowledge/github/setup/continue/route.ts @@ -45,6 +45,9 @@ export const GET = withRouteHandler(async (request) => { }, }) } catch { - return createCredentialGroupCompletionRedirect('unavailable', parsed.data.query.setupId) + return createCredentialGroupCompletionRedirect({ + oauth: 'unavailable', + completionId: parsed.data.query.setupId, + }) } }) diff --git a/apps/sim/app/api/mcp/oauth/callback/route.ts b/apps/sim/app/api/mcp/oauth/callback/route.ts index 7cf3ee76bed..259e74f3335 100644 --- a/apps/sim/app/api/mcp/oauth/callback/route.ts +++ b/apps/sim/app/api/mcp/oauth/callback/route.ts @@ -112,11 +112,11 @@ async function completeManagedMcpCallback(params: { } const failureRedirect = (oauth: CredentialGroupOAuthFailure) => attempt.completionId - ? createCredentialGroupCompletionRedirect( + ? createCredentialGroupCompletionRedirect({ oauth, - attempt.completionId, - attempt.returnTo === 'integrations' ? attempt.organizationId : undefined - ) + completionId: attempt.completionId, + organizationId: attempt.returnTo === 'integrations' ? attempt.organizationId : undefined, + }) : createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { oauth }) if (params.error) { const errorCode = [ @@ -153,11 +153,10 @@ async function completeManagedMcpCallback(params: { request: params.request, }) if (attempt.completionId) - return createCredentialGroupCompletionRedirect( - undefined, - attempt.completionId, - attempt.returnTo === 'integrations' ? attempt.organizationId : undefined - ) + return createCredentialGroupCompletionRedirect({ + completionId: attempt.completionId, + organizationId: attempt.returnTo === 'integrations' ? attempt.organizationId : undefined, + }) return createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { mcp: 'connected', mcpServerId: result.mcpServerId, diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index c574f750cf1..ca1a71e4d16 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -3,7 +3,10 @@ import type { Metadata } from 'next' import { headers } from 'next/headers' import { redirect } from 'next/navigation' import { getSession } from '@/lib/auth' -import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' +import { + resolveCredentialGroupConnectTarget, + startCredentialGroupConnect, +} from '@/lib/credential-groups/application/connect-target' import { buildCredentialGroupConnectHandoffPath, buildCredentialGroupConnectPath, @@ -89,15 +92,22 @@ export default async function CredentialGroupConnectPage({ if (await isCredentialGroupConnectUserRateLimited(session.user.id)) return - const target = await resolveCredentialGroupConnectTarget.execute({ - principal: { kind: 'session', userId: session.user.id, sessionId: session.session.id }, - input: { - publicId, - provider, - ...(optionId ? { optionId } : {}), - ...(returnValue ? { returnUrl: returnValue } : {}), - }, - }) + const principal = { + kind: 'session' as const, + userId: session.user.id, + sessionId: session.session.id, + } + const input = { + publicId, + provider, + ...(optionId ? { optionId } : {}), + ...(returnValue ? { returnUrl: returnValue } : {}), + } + const resolved = await resolveCredentialGroupConnectTarget.execute({ principal, input }) + const target = + resolved.kind === 'connect' + ? await startCredentialGroupConnect.execute({ principal, input }) + : resolved switch (target.kind) { case 'ready': diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.test.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.test.tsx index fbb3aa0b58a..881ad7ad378 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.test.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.test.tsx @@ -16,7 +16,7 @@ vi.mock('@/lib/credential-groups/application/enrollment-auth', () => ({ authenticateCredentialGroupEnrollment: mocks.authenticate, })) vi.mock('@/lib/credential-groups/application/enrollment-link-outcome', () => ({ - explainCredentialGroupEnrollmentLink: async () => ({ kind: 'unknown' }), + explainCredentialGroupEnrollmentLink: { execute: async () => ({ kind: 'unknown' }) }, })) vi.mock('@/lib/credential-groups/application/public-enrollment', () => ({ readPublicCredentialGroupEnrollment: { execute: mocks.read }, diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index 0362a9f0290..468bd38ffc2 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -18,6 +18,7 @@ import { explainCredentialGroupEnrollmentLink, } from '@/lib/credential-groups/application/enrollment-link-outcome' import { readPublicCredentialGroupEnrollment } from '@/lib/credential-groups/application/public-enrollment' +import { buildCredentialGroupConnectPath } from '@/lib/credential-groups/connect-url' import { CredentialGroupEnrollmentError } from '@/lib/credential-groups/enrollments' import { getManagedMcpConnectorIcon } from '@/lib/credential-groups/managed-mcp-connector-icons' import { CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES } from '@/lib/credential-groups/oauth-completion' @@ -53,6 +54,8 @@ interface EnrollmentLinkProblemProps { outcome: CredentialGroupEnrollmentLinkOutcome signedInEmail: string callbackUrl: string + /** An allowed Slack destination the link carried, offered beside a way to start over. */ + slackReturnUrl?: string fallbackMessage?: string } @@ -71,6 +74,7 @@ function EnrollmentLinkProblem({ outcome, signedInEmail, callbackUrl, + slackReturnUrl, fallbackMessage, }: EnrollmentLinkProblemProps) { const organizationName = @@ -98,6 +102,27 @@ function EnrollmentLinkProblem({ message={`${organizationName} isn’t collecting account connections right now.`} /> ) + case 'reopen': + return ( + + +
+ +
+ {slackReturnUrl && Return to Slack} + + Start again + +
+
+
+ ) case 'needs_new_link': return ( ) - const signedInUser = { id: session.user.id, email: session.user.email } const explainLinkProblem = async (fallbackMessage?: string) => ( ) diff --git a/apps/sim/lib/credential-groups/README.md b/apps/sim/lib/credential-groups/README.md index 8fb7aa3766e..ad743ff0639 100644 --- a/apps/sim/lib/credential-groups/README.md +++ b/apps/sim/lib/credential-groups/README.md @@ -66,6 +66,27 @@ Workspace-scoped callers resolve their owning organization's entitlement; person Current bounds: 100 entries per discovery page, 1,000 workspace allowlist entries, and 1,000 deployed event subscriptions per organization. Event delivery is synchronous after enrollment commits; a delivery failure surfaces as an error and does not roll back the saved connection. An outbox/retry mechanism is not included. +## Invitation links + +Every bearer link into an enrollment is a row in `credential_group_enrollment_link` (`lib/credential-groups/links.ts`), so issuing one never invalidates another. Disconnecting an account or revoking the enrollment revokes all of its links. + +| Purpose | Issued by | Lifetime | +| --- | --- | --- | +| `email` | An admin's invitation or resend, or an automatic invitation | 7 days while the enrollment is unbound; no expiry once a verified user is bound | +| `self` | A member enrolling themselves from Integrations | 1 hour, always | +| `connect` | The connect page, for one account option | 1 hour, always; an expired one sends the person back to the connect page to start again | + +The 0489 backfill recorded every existing invitation, including self-enrollment tokens issued before links existed, as `email`, so those keep the emailed lifetime. The hourly `cleanup-credential-group-links` cron job deletes `self` and `connect` links a day after they expire, and the workflow connection-request log after two days. + +An emailed reinvitation deliberately restarts the invitation: the issuer, invited and sent times move to the new send, a workflow's request marker and reminder count are cleared, and the status returns to Invited unless the person already made progress. Earlier links stay live. + +Status is authoritative for revocation. The pre-link app revokes an enrollment by setting its status alone, so during a deploy or rollback its links can stay unrevoked; every link check also refuses a `revoked` enrollment, and a reinvitation revokes such links. The pre-link app's disconnect rewrites only the legacy column, so the same bound person's emailed links stay live through it; the contract migration below revokes links whose enrollment's legacy column no longer names any link. + +Contract phase (after the link expand is fully deployed and no rollback target predates it): + +1. Make `credential_group_enrollment.invitation_token_hash` nullable and stop writing it. Enrollments created without an emailed link store null instead of an `unissued:` value. Revoke live links into enrollments whose legacy column matches no link row. +2. Drop the column with its unique index and length check, and remove the legacy branch of `liveEnrollmentLinkCondition`, `adoptLegacyInvitationLink`, and the legacy fallback of `findCredentialGroupEnrollmentLinkRecord`. + ## Rollout OAuth attempt state changes at this release boundary (OAuth v5 and managed MCP v3). Older attempts lack a verified Sim user binding; older MCP attempts also lack the configuration version. They are deliberately rejected before token exchange, with an explicit instruction to reopen the invitation and connect again. Existing saved credentials are not invalidated by the state version change. Mixed application versions cannot complete each other's in-flight attempts: pause enrollment starts, allow the ten-minute state lifetime to drain, replace the application instances together, and only then reopen enrollment. Do not run enrollment OAuth across mixed versions or roll back with active attempts. diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index 0b1edab686c..25f894ade49 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -1,6 +1,7 @@ /** - * The secret-free connect URL against real Postgres: who it opens for, what it mints, and how the - * focused link it mints is held to its one account option. Failure modes: an invited person + * The secret-free connect URL against real Postgres: who it opens for, what it mints (resolving + * alone mints and binds nothing), and how the focused link it mints is held to its one account + * option. Failure modes: an invited person * (minted link scoped to the option, one hour, enrollment fields untouched), an enrollment bound * to someone else, an unverified session, a revoked enrollment, a stranger, an organization member * with no enrollment (enrolled only on the confirmation, never on the page load), a member the @@ -33,7 +34,10 @@ import { generateId } from '@sim/utils/id' import { and, eq, inArray, sql } from 'drizzle-orm' import { afterAll, describe, expect, it, vi } from 'vitest' import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' -import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' +import { + resolveCredentialGroupConnectTarget, + startCredentialGroupConnect, +} from '@/lib/credential-groups/application/connect-target' import { completePublicCredentialGroupEnrollment, completePublicCredentialGroupOAuth, @@ -46,8 +50,8 @@ import { lockCredentialGroupInvitationTarget, revokeCredentialGroupEnrollment, } from '@/lib/credential-groups/enrollments' +import { CredentialGroupLinkFocusError } from '@/lib/credential-groups/links' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' -import { CredentialGroupLinkFocusError } from '@/lib/credential-groups/provider-adapter' import type { CredentialGroupProvider } from '@/lib/credential-groups/providers' import { ensureWorkspaceAccountsGroup } from '@/lib/credential-groups/service' @@ -194,7 +198,7 @@ function resolveTarget( confirmSelfEnrollment?: boolean } ) { - return resolveCredentialGroupConnectTarget.execute({ + return startCredentialGroupConnect.execute({ principal: createSessionPrincipal({ userId }), input: { provider: DRIVE_PROVIDER_ID, ...input }, }) @@ -278,7 +282,7 @@ afterAll(async () => { await db.delete(user).where(inArray(user.id, userIds)) }) -describe('resolveCredentialGroupConnectTarget', () => { +describe('startCredentialGroupConnect', () => { it('mints a one-hour connect link scoped to the option and binds the invited person', async () => { const fixture = await createOrganization() const person = await createPerson() @@ -316,6 +320,36 @@ describe('resolveCredentialGroupConnectTarget', () => { }) }) + it('resolves without binding the person or minting a link', async () => { + const fixture = await createOrganization() + const person = await createPerson() + const enrollment = await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + + await expect( + resolveCredentialGroupConnectTarget.execute({ + principal: createSessionPrincipal({ userId: person.userId }), + input: { publicId: fixture.publicId, provider: DRIVE_PROVIDER_ID }, + }) + ).resolves.toEqual({ + kind: 'connect', + organizationName: 'Acme', + provider: 'google-drive', + optionId: DRIVE.id, + }) + expect((await enrollmentOf(fixture.groupId, person.email)).userId).toBeNull() + const links = await db + .select() + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollment.id)) + expect(links.every((link) => link.purpose !== 'connect')).toBe(true) + }) + it('refuses an enrollment bound to another user as the wrong account', async () => { const fixture = await createOrganization() const person = await createPerson() diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts index a5504cc1511..437488319e6 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts @@ -3,8 +3,9 @@ * the token lookup, the joins that name the organization and inviter, and the identity check run * on stored rows. Failure modes: an unknown token, a forwarded link opened by someone else (who * must learn nothing but a masked address, whatever state the enrollment is in), a revoked - * enrollment, a disabled group, a failed delivery, an expired link, and a link revoked (by a - * disconnect) while its enrollment stays live. + * enrollment, a disabled group, a failed delivery (which no longer stops a live link, so is never + * the explanation), an expired link, an expired connect-page link (sent back to start again), and + * a link revoked (by a disconnect) while its enrollment stays live. */ import { db } from '@sim/db' import { @@ -15,6 +16,7 @@ import { user, } from '@sim/db/schema' import { sha256Hex } from '@sim/security/hash' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' import { generateId } from '@sim/utils/id' import { eq, inArray } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' @@ -27,12 +29,33 @@ vi.mock('@/lib/credential-groups/scoped-availability', () => ({ const inviterId = generateId() const inviteeId = generateId() const strangerId = generateId() +const shouterId = generateId() const inviteeEmail = `invitee-${inviteeId}@example.test` const strangerEmail = `stranger-${strangerId}@example.test` -const invitee = { id: inviteeId, email: inviteeEmail } -const stranger = { id: strangerId, email: strangerEmail } +const shouterEmail = `SHOUTER-${shouterId}@EXAMPLE.TEST` +const invitee = { id: inviteeId } +const stranger = { id: strangerId } const DAY_MS = 24 * 60 * 60 * 1000 +const DRIVE_OPTION = { + id: 'option-google-drive', + provider: 'google-drive', + label: 'Google Drive', + authorizationAppId: 'fixture-app', + requiredScopes: ['read'], + scopeVersion: 1, + required: false, + status: 'active' as const, +} + +/** Explains `invitationToken` to the signed-in `user`. */ +function explain(invitationToken: string, user: { id: string }) { + return explainCredentialGroupEnrollmentLink.execute({ + principal: createSessionPrincipal({ userId: user.id }), + input: { invitationToken }, + }) +} + const organizationIds: string[] = [] /** @@ -41,7 +64,8 @@ const organizationIds: string[] = [] */ async function seedEnrollment( values: Partial & { email: string }, - groupStatus: 'active' | 'disabled' = 'active' + groupStatus: 'active' | 'disabled' = 'active', + group: { publicId?: string; options?: (typeof credentialGroup.$inferInsert)['options'] } = {} ): Promise { const token = generateId() const organizationId = generateId() @@ -56,9 +80,9 @@ async function seedEnrollment( await db.insert(credentialGroup).values({ id: groupId, organizationId, - publicId: generateId(), + publicId: group.publicId ?? generateId(), name: 'Accounts', - options: [], + options: group.options ?? [], status: groupStatus, }) await db.insert(credentialGroupEnrollment).values({ @@ -103,6 +127,7 @@ beforeAll(async () => { { id: inviterId, name: 'Ada Admin', email: `inviter-${inviterId}@example.test` }, { id: inviteeId, name: 'Invitee', email: inviteeEmail }, { id: strangerId, name: 'Stranger', email: strangerEmail }, + { id: shouterId, name: 'Shouter', email: shouterEmail }, ].map((row) => ({ ...row, emailVerified: true, createdAt: now, updatedAt: now })) ) }) @@ -110,14 +135,12 @@ beforeAll(async () => { afterAll(async () => { await db.delete(credentialGroup).where(inArray(credentialGroup.organizationId, organizationIds)) await db.delete(organization).where(inArray(organization.id, organizationIds)) - await db.delete(user).where(inArray(user.id, [inviterId, inviteeId, strangerId])) + await db.delete(user).where(inArray(user.id, [inviterId, inviteeId, strangerId, shouterId])) }) describe('explainCredentialGroupEnrollmentLink', () => { it('keeps an unknown token generic', async () => { - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: generateId(), user: invitee }) - ).resolves.toEqual({ kind: 'unknown' }) + await expect(explain(generateId(), invitee)).resolves.toEqual({ kind: 'unknown' }) }) it('tells the invitee an expired unbound link needs reissuing by its inviter', async () => { @@ -125,9 +148,7 @@ describe('explainCredentialGroupEnrollmentLink', () => { email: inviteeEmail, invitationExpiresAt: new Date(Date.now() - DAY_MS), }) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) - ).resolves.toEqual({ + await expect(explain(token, invitee)).resolves.toEqual({ kind: 'needs_new_link', reason: 'expired', organizationName: 'Acme Corp', @@ -137,16 +158,14 @@ describe('explainCredentialGroupEnrollmentLink', () => { it('matches the invited email case-insensitively for an unbound link', async () => { const token = await seedEnrollment({ - email: inviteeEmail, + email: shouterEmail.toLowerCase(), status: 'revoked', revokedAt: new Date(), }) - await expect( - explainCredentialGroupEnrollmentLink({ - invitationToken: token, - user: { id: inviteeId, email: inviteeEmail.toUpperCase() }, - }) - ).resolves.toEqual({ kind: 'revoked', organizationName: 'Acme Corp' }) + await expect(explain(token, { id: shouterId })).resolves.toEqual({ + kind: 'revoked', + organizationName: 'Acme Corp', + }) }) it('tells the bound person a revoked enrollment is no longer needed', async () => { @@ -156,27 +175,54 @@ describe('explainCredentialGroupEnrollmentLink', () => { status: 'completed', revokedAt: new Date(), }) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) - ).resolves.toEqual({ kind: 'revoked', organizationName: 'Acme Corp' }) + await expect(explain(token, invitee)).resolves.toEqual({ + kind: 'revoked', + organizationName: 'Acme Corp', + }) }) it('names the paused group to its invitee', async () => { const token = await seedEnrollment({ email: inviteeEmail }, 'disabled') - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) - ).resolves.toEqual({ kind: 'paused', organizationName: 'Acme Corp' }) + await expect(explain(token, invitee)).resolves.toEqual({ + kind: 'paused', + organizationName: 'Acme Corp', + }) }) - it('tells the matching person a link whose delivery failed needs reissuing', async () => { - const token = await seedEnrollment({ email: inviteeEmail, status: 'delivery_failed' }) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) - ).resolves.toEqual({ + it('never blames a failed delivery, which no longer stops a live link', async () => { + const live = await seedEnrollment({ email: inviteeEmail, status: 'delivery_failed' }) + await expect(explain(live, invitee)).resolves.toEqual({ kind: 'unavailable' }) + + const expired = await seedEnrollment({ + email: inviteeEmail, + status: 'delivery_failed', + invitationExpiresAt: new Date(Date.now() - DAY_MS), + }) + await expect(explain(expired, invitee)).resolves.toMatchObject({ kind: 'needs_new_link', - reason: 'delivery_failed', + reason: 'expired', + }) + }) + + it('sends an expired connect-page link back to the connect page to start again', async () => { + const publicId = generateId() + const enrollmentToken = await seedEnrollment( + { email: inviteeEmail, userId: inviteeId }, + 'active', + { + publicId, + options: [DRIVE_OPTION], + } + ) + const token = await seedLink(enrollmentToken, { + purpose: 'connect', + optionId: DRIVE_OPTION.id, + expiresAt: new Date(Date.now() - DAY_MS), + }) + await expect(explain(token, invitee)).resolves.toEqual({ + kind: 'reopen', organizationName: 'Acme Corp', - inviterName: 'Ada Admin', + connect: { publicId, provider: 'google-drive', optionId: DRIVE_OPTION.id }, }) }) @@ -190,9 +236,10 @@ describe('explainCredentialGroupEnrollmentLink', () => { 'shows someone else holding %s only a masked address', async (_label, values, groupStatus) => { const token = await seedEnrollment({ email: inviteeEmail, ...values }, groupStatus) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: stranger }) - ).resolves.toEqual({ kind: 'wrong_account', maskedEmail: 'i***@example.test' }) + await expect(explain(token, stranger)).resolves.toEqual({ + kind: 'wrong_account', + maskedEmail: 'i***@example.test', + }) } ) @@ -202,24 +249,21 @@ describe('explainCredentialGroupEnrollmentLink', () => { userId: inviteeId, status: 'in_progress', }) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: stranger }) - ).resolves.toEqual({ kind: 'wrong_account', maskedEmail: 's***@example.test' }) + await expect(explain(token, stranger)).resolves.toEqual({ + kind: 'wrong_account', + maskedEmail: 's***@example.test', + }) }) it('stays generic for a live link that already belongs to the person', async () => { const token = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) - ).resolves.toEqual({ kind: 'unavailable' }) + await expect(explain(token, invitee)).resolves.toEqual({ kind: 'unavailable' }) }) it('tells the person a link revoked by a disconnect needs reissuing while the enrollment lives', async () => { const enrollmentToken = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) const token = await seedLink(enrollmentToken, { revokedAt: new Date() }) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) - ).resolves.toEqual({ + await expect(explain(token, invitee)).resolves.toEqual({ kind: 'needs_new_link', reason: 'link_revoked', organizationName: 'Acme Corp', @@ -230,9 +274,7 @@ describe('explainCredentialGroupEnrollmentLink', () => { it('never calls an expired emailed link of a bound person expired', async () => { const enrollmentToken = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) const token = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) - ).resolves.toEqual({ kind: 'unavailable' }) + await expect(explain(token, invitee)).resolves.toEqual({ kind: 'unavailable' }) }) it('calls an expired connect link of a bound person expired', async () => { @@ -241,16 +283,18 @@ describe('explainCredentialGroupEnrollmentLink', () => { purpose: 'connect', expiresAt: new Date(Date.now() - DAY_MS), }) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) - ).resolves.toMatchObject({ kind: 'needs_new_link', reason: 'expired' }) + await expect(explain(token, invitee)).resolves.toMatchObject({ + kind: 'needs_new_link', + reason: 'expired', + }) }) it('reports an unbound link expired by its own expiry, not the legacy column', async () => { const enrollmentToken = await seedEnrollment({ email: inviteeEmail }) const token = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) - await expect( - explainCredentialGroupEnrollmentLink({ invitationToken: token, user: invitee }) - ).resolves.toMatchObject({ kind: 'needs_new_link', reason: 'expired' }) + await expect(explain(token, invitee)).resolves.toMatchObject({ + kind: 'needs_new_link', + reason: 'expired', + }) }) }) diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts index 2025e1fbb90..45a5e1d2a68 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts @@ -1,7 +1,8 @@ /** * Enrollment links against real Postgres: issuing a link never invalidates another, an emailed * link's expiry binds only an unbound enrollment while self and connect links always expire, and - * disconnect or revocation (by this app or the released one) kills every link. Only the email + * disconnect or revocation (by this app or the released one) kills every link. A token is resolved + * through indexes, never a scan of every enrollment. Only the email * transport and the provider code exchange are faked; the emailed link is read from what would * have been sent. */ @@ -15,19 +16,20 @@ import { organization, user, } from '@sim/db/schema' +import { explainCaptured } from '@sim/db/testing/explain' import { sha256Hex } from '@sim/security/hash' import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' import { generateId } from '@sim/utils/id' import { eq } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { disconnectPersonalOrganizationAccount } from '@/lib/credential-groups/application/personal-organization-accounts' +import { issueCredentialGroupConnectLink } from '@/lib/credential-groups/connect-subject' import { authenticatePublicCredentialGroupEnrollment, bindCredentialGroupEnrollmentUser, completeAuthorizedCredentialGroupEnrollment, getCredentialGroupOAuthContextForEnrollment, inviteCredentialGroupEnrollment, - issueCredentialGroupConnectLink, resendCredentialGroupEnrollment, revokeCredentialGroupEnrollment, } from '@/lib/credential-groups/enrollments' @@ -234,6 +236,33 @@ afterAll(async () => { }) describe('credential group enrollment links', () => { + it.each([ + ['a link row', false], + ['an invitation in the legacy column', true], + ])( + 'finds the enrollment %s names by an index lookup, never by scanning enrollments', + async (_label, legacy) => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + if (legacy) + await db + .delete(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, emailed.enrollmentId)) + + const plan = await explainCaptured( + db, + async () => expect(await resolves(emailed.token)).toBe(true), + { gucs: { enable_seqscan: 'off' } } + ) + + const enrollmentScans = plan.filter( + (node) => node['Relation Name'] === 'credential_group_enrollment' + ) + expect(enrollmentScans.length).toBeGreaterThan(0) + for (const scan of enrollmentScans) expect(scan['Index Cond']).toBeDefined() + } + ) + it('keeps an emailed link working after the person connects themselves', async () => { const person = await createPerson() const emailed = await adminInvite(person.email) @@ -291,8 +320,14 @@ describe('credential group enrollment links', () => { it('expires self and connect links even once the enrollment is bound', async () => { const person = await createPerson() const self = await selfEnroll(person.userId) - const connectToken = await issueCredentialGroupConnectLink(self.enrollmentId, DRIVE.id) - if (!connectToken) throw new Error('Connect link was not minted') + const connect = await issueCredentialGroupConnectLink({ + credentialGroupId: groupId, + userId: person.userId, + optionId: DRIVE.id, + target: { kind: 'enrollment', enrollmentId: self.enrollmentId }, + }) + if (!connect.issued) throw new Error('Connect link was not minted') + const connectToken = connect.token expect(await resolves(self.token)).toBe(true) expect(await resolves(connectToken)).toBe(true) diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts index 282a867b7c4..dbf84a00550 100644 --- a/apps/sim/lib/credential-groups/application/connect-target.ts +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -1,21 +1,21 @@ +import { AuditAction, AuditResourceType } from '@sim/audit' import type { SessionPrincipal } from '@sim/auth/principal' +import { omit } from '@sim/utils/object' import { defineOperation } from '@/lib/core/application' import { ForbiddenOperationError } from '@/lib/core/application/forbidden' import { authorizeOrganizationOperation, OrganizationMembershipNotFoundError, } from '@/lib/core/application/organization-authorization' -import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' +import { OrchestrationError } from '@/lib/core/orchestration/types' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' -import { maskEnrollmentEmail } from '@/lib/credential-groups/application/enrollment-link-outcome' import { organizationAccountOperations } from '@/lib/credential-groups/application/organization-accounts' import { - authenticatePublicCredentialGroupEnrollment, - bindCredentialGroupEnrollmentUser, - CredentialGroupEnrollmentError, + type CredentialGroupConnectLinkTarget, issueCredentialGroupConnectLink, loadCredentialGroupConnectSubject, -} from '@/lib/credential-groups/enrollments' +} from '@/lib/credential-groups/connect-subject' +import { maskEnrollmentEmail } from '@/lib/credential-groups/email-mask' import { OrganizationAccountsSetupRequiredError, requireOrganizationAccountsSetup, @@ -24,9 +24,7 @@ import { type CredentialGroupProvider, findCredentialGroupProviderFromProviderId, } from '@/lib/credential-groups/providers' -import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' -import { createViewerCredentialGroupEnrollment } from '@/lib/credential-groups/self-enrollment' import { defineAuthorizedCredentialUserUseCase } from '@/lib/credentials/application/authorized-user-use-case' const credentialGroupConnectOperations = { @@ -39,29 +37,39 @@ const credentialGroupConnectOperations = { principalKinds: ['session'], capability: 'none', }), + /** + * permission-group-exempt: as for `resolve`; a member's self-enrollment is held to the + * Integrations capability by the same check the member self-enroll path uses. + */ + start: defineOperation({ + id: 'credential_groups.connect.start', + principalKinds: ['session'], + capability: 'none', + }), } as const /** - * Where the `return` query of a connect URL may send the person once connected. The keyword - * `slack` (what workflows put on the link, since they hold no Slack team or app id) opens the - * Slack app through its generic deep link; anything else must be an allowlisted Slack URL, and an - * invalid value is dropped rather than refused. + * The keyword a connect URL's `return` query may carry. Workflows hold no Slack team or app ID, + * so `slack` opens the Slack app through its generic deep link; nothing else read from the URL is + * a return destination, so a crafted link cannot name one. */ +const SLACK_RETURN_KEYWORD = 'slack' const SLACK_APP_RETURN_URL = 'slack://open' function resolveReturnUrl(raw: string | undefined): string | undefined { - if (!raw) return undefined - if (raw === 'slack') return SLACK_APP_RETURN_URL - return parseCredentialGroupReturnUrl(raw)?.href + return raw === SLACK_RETURN_KEYWORD ? SLACK_APP_RETURN_URL : undefined } -export interface ResolveCredentialGroupConnectTargetInput { +interface CredentialGroupConnectInput { publicId: string /** The credential provider ID the workflow asked for (e.g. `google-drive`). */ provider: string optionId?: string - /** Raw `return` query value: the keyword `slack` or an allowlisted Slack URL. */ + /** Raw `return` query value; only the keyword `slack` is honored. */ returnUrl?: string +} + +interface StartCredentialGroupConnectInput extends CredentialGroupConnectInput { /** * Set only by the confirmation POST. Without it an organization member with no enrollment is * asked to confirm instead of enrolled, so a cross-site navigation enrolls nobody. @@ -69,29 +77,69 @@ export interface ResolveCredentialGroupConnectTargetInput { confirmSelfEnrollment?: boolean } +/** A refusal the connect page explains; the same for {@link resolveCredentialGroupConnectTarget} and the start. */ +type CredentialGroupConnectRefusal = + | { kind: 'unavailable' } + | { kind: 'not_invited'; organizationName: string; provider: CredentialGroupProvider } + | { kind: 'wrong_account'; organizationName: string; maskedEmail: string } + | { kind: 'revoked'; organizationName: string; provider: CredentialGroupProvider } + | { + kind: 'choose_option' + organizationName: string + provider: CredentialGroupProvider + options: Array<{ id: string; label: string }> + } + +interface ConfirmSelfEnrollment { + kind: 'confirm_self_enrollment' + organizationName: string + provider: CredentialGroupProvider + optionId: string +} + /** * What the connect page does for the signed-in person. Every refusal that would reveal whether a * group exists, is enabled, or offers the provider is the same `unavailable`; the organization is * only named once the group is known to be active and to offer the provider, since the link holder - * got the URL from that organization. + * got the URL from that organization. `connect` means the person may connect now, which + * {@link startCredentialGroupConnect} does. */ -export type CredentialGroupConnectTarget = - | { kind: 'ready'; invitationToken: string; optionId: string; returnUrl?: string } - | { kind: 'unavailable' } - | { kind: 'not_invited'; organizationName: string; provider: CredentialGroupProvider } - | { kind: 'wrong_account'; organizationName: string; maskedEmail: string } +type CredentialGroupConnectTarget = + | CredentialGroupConnectRefusal + | ConfirmSelfEnrollment | { - kind: 'confirm_self_enrollment' + kind: 'connect' organizationName: string provider: CredentialGroupProvider optionId: string } - | { kind: 'revoked'; organizationName: string; provider: CredentialGroupProvider } + +/** What starting a connection did: minted the person's focused link, or why it did not. */ +type CredentialGroupConnectStart = + | CredentialGroupConnectRefusal + | ConfirmSelfEnrollment | { - kind: 'choose_option' + kind: 'ready' + invitationToken: string + optionId: string + returnUrl?: string + /** For the audit record; the page never shows these. */ + credentialGroupId: string + enrollmentId: string + created: boolean + bound: boolean + } + +type ConnectDecision = + | CredentialGroupConnectRefusal + | (ConfirmSelfEnrollment & { credentialGroupId: string; organizationId: string }) + | { + kind: 'connect' organizationName: string provider: CredentialGroupProvider - options: Array<{ id: string; label: string }> + optionId: string + credentialGroupId: string + enrollment: { id: string; bound: boolean } } const UNAVAILABLE = { kind: 'unavailable' } as const @@ -124,35 +172,90 @@ async function canSelfEnroll( } /** - * Enrolls the member, mapping a revocation that landed after the enrollment was read to - * `revoked` and any other refusal to `unavailable`. + * Decides what the signed-in person may do with a connect URL. Reads only. The session is the + * authority, not an earlier invitation: an unbound enrollment whose emailed link (or legacy + * invitation column) expired, or that a workflow requested with no link at all, is still + * connectable by the person at its email, because the link minted for it carries its own expiry. + * An organization member with no enrollment who passes the member self-enroll checks is asked to + * confirm; anyone else must already hold an enrollment bound to them or invited at their verified + * email. */ -async function selfEnroll(input: { - organizationId: string - credentialGroupId: string - userId: string -}): Promise<{ enrollmentId: string } | 'revoked' | 'unavailable'> { - try { - const enrolled = await createViewerCredentialGroupEnrollment(input) - return { enrollmentId: enrolled.enrollment.id } - } catch (error) { - if (error instanceof CredentialGroupEnrollmentError) return 'unavailable' - const code = asOrchestrationError(error)?.code - if (code === 'forbidden') return 'revoked' - if (code) return 'unavailable' - throw error +async function decideConnectTarget( + principal: SessionPrincipal, + input: CredentialGroupConnectInput +): Promise { + const subject = await loadCredentialGroupConnectSubject({ + publicId: input.publicId, + userId: principal.userId, + }) + if (subject && !subject.viewer.emailVerified) + throw new OrchestrationError('forbidden', 'Verify your email address before connecting') + if (!subject || subject.group.status !== 'active') return UNAVAILABLE + const { group, enrollment } = subject + const provider = findCredentialGroupProviderFromProviderId(input.provider) + if (!provider) return UNAVAILABLE + if (!(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(group)))) return UNAVAILABLE + const options = group.options.filter( + (option) => + option.provider === provider && + option.status === 'active' && + (input.optionId === undefined || option.id === input.optionId) + ) + const [option] = options + if (!option) return UNAVAILABLE + const { organizationName } = group + + if (enrollment?.userId && enrollment.userId !== principal.userId) + return { + kind: 'wrong_account', + organizationName, + maskedEmail: maskEnrollmentEmail(enrollment.email), + } + if (enrollment && (enrollment.status === 'revoked' || enrollment.revokedAt)) + return { kind: 'revoked', organizationName, provider } + if (!enrollment) { + if (!group.organizationId || !(await canSelfEnroll(principal, group.organizationId, group.id))) + return { kind: 'not_invited', organizationName, provider } + } else if (!enrollment.userId && group.organizationId) { + /** Binding an invited person needs the organization's setup, as the invitation page does. */ + try { + await requireOrganizationAccountsSetup(group.organizationId, group.id) + } catch (error) { + if (error instanceof OrganizationAccountsSetupRequiredError) return UNAVAILABLE + throw error + } + } + if (options.length > 1) + return { + kind: 'choose_option', + organizationName, + provider, + options: options.map(({ id, label }) => ({ id, label })), + } + if (!enrollment) { + if (!group.organizationId) return UNAVAILABLE + return { + kind: 'confirm_self_enrollment', + organizationName, + provider, + optionId: option.id, + credentialGroupId: group.id, + organizationId: group.organizationId, + } + } + return { + kind: 'connect', + organizationName, + provider, + optionId: option.id, + credentialGroupId: group.id, + enrollment: { id: enrollment.id, bound: Boolean(enrollment.userId) }, } } /** - * Resolves a secret-free connect URL to the signed-in person's own enrollment and, only then, - * mints a one-hour link focused on the single matching account option. The session is the - * authority, not an earlier invitation: an unbound enrollment whose emailed link (or legacy - * invitation column) expired, or that a workflow requested with no link at all, is still - * connectable by the person at its email, because the fresh link carries its own expiry. An - * organization member with no enrollment who passes the member self-enroll checks is asked to - * confirm, and enrolled only by the confirmation POST; anyone else must already hold an - * enrollment bound to them or invited at their verified email. + * Tells the connect page what the signed-in person may do with a secret-free connect URL, without + * changing anything: a page load, link unfurler, or prefetch that only resolves leaves no trace. */ export const resolveCredentialGroupConnectTarget = defineAuthorizedCredentialUserUseCase({ operation: credentialGroupConnectOperations.resolve, @@ -161,80 +264,86 @@ export const resolveCredentialGroupConnectTarget = defineAuthorizedCredentialUse input, }: { principal: SessionPrincipal - input: ResolveCredentialGroupConnectTargetInput + input: CredentialGroupConnectInput }): Promise { - const subject = await loadCredentialGroupConnectSubject({ - publicId: input.publicId, - userId: principal.userId, - }) - if (subject && !subject.viewer.emailVerified) - throw new OrchestrationError('forbidden', 'Verify your email address before connecting') - if (!subject || subject.group.status !== 'active') return UNAVAILABLE - const { group, enrollment } = subject - const provider = findCredentialGroupProviderFromProviderId(input.provider) - if (!provider) return UNAVAILABLE - if (!(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(group)))) - return UNAVAILABLE - const options = group.options.filter( - (option) => - option.provider === provider && - option.status === 'active' && - (input.optionId === undefined || option.id === input.optionId) - ) - const [option] = options - if (!option) return UNAVAILABLE - const { organizationName } = group - - if (enrollment?.userId && enrollment.userId !== principal.userId) - return { - kind: 'wrong_account', - organizationName, - maskedEmail: maskEnrollmentEmail(enrollment.email), - } - if (enrollment && (enrollment.status === 'revoked' || enrollment.revokedAt)) - return { kind: 'revoked', organizationName, provider } - if ( - !enrollment && - !(group.organizationId && (await canSelfEnroll(principal, group.organizationId, group.id))) - ) - return { kind: 'not_invited', organizationName, provider } - if (options.length > 1) - return { - kind: 'choose_option', - organizationName, - provider, - options: options.map(({ id, label }) => ({ id, label })), - } - - let enrollmentId = enrollment?.id - let bound = Boolean(enrollment?.userId) - if (!enrollmentId && group.organizationId) { + const decision = await decideConnectTarget(principal, input) + if (decision.kind === 'confirm_self_enrollment') + return omit(decision, ['credentialGroupId', 'organizationId']) + if (decision.kind === 'connect') return omit(decision, ['credentialGroupId', 'enrollment']) + return decision + }, +}) + +/** + * Mints the signed-in person's one-hour link focused on the single matching account option, after + * deciding again what they may do. In one transaction it enrolls a member who confirmed + * self-enrollment, binds the person to an enrollment invited at their email, and inserts the link, + * so a revocation either lands first (and the person is told the connection is no longer needed) + * or kills the new link. Creating or binding an enrollment is audited; minting a link for one + * already bound is not, since the person can repeat it freely. + */ +export const startCredentialGroupConnect = defineAuthorizedCredentialUserUseCase({ + operation: credentialGroupConnectOperations.start, + async execute({ + principal, + input, + }: { + principal: SessionPrincipal + input: StartCredentialGroupConnectInput + }): Promise { + const decision = await decideConnectTarget(principal, input) + let target: CredentialGroupConnectLinkTarget + if (decision.kind === 'connect') { + target = { kind: 'enrollment', enrollmentId: decision.enrollment.id } + } else if (decision.kind === 'confirm_self_enrollment') { if (!input.confirmSelfEnrollment) - return { kind: 'confirm_self_enrollment', organizationName, provider, optionId: option.id } - const enrolled = await selfEnroll({ - organizationId: group.organizationId, - credentialGroupId: group.id, - userId: principal.userId, - }) - if (enrolled === 'revoked') return { kind: 'revoked', organizationName, provider } - if (enrolled === 'unavailable') return UNAVAILABLE - enrollmentId = enrolled.enrollmentId - bound = true - } - if (!enrollmentId) return UNAVAILABLE - const invitationToken = await issueCredentialGroupConnectLink(enrollmentId, option.id) - if (!invitationToken) return { kind: 'revoked', organizationName, provider } - if (!bound) { - const identity = await authenticatePublicCredentialGroupEnrollment(invitationToken) - if (!identity) return UNAVAILABLE - await bindCredentialGroupEnrollmentUser(identity, principal.userId) + return omit(decision, ['credentialGroupId', 'organizationId']) + target = { kind: 'self_enrollment' } + } else { + return decision } + const issued = await issueCredentialGroupConnectLink({ + credentialGroupId: decision.credentialGroupId, + userId: principal.userId, + optionId: decision.optionId, + target, + }) + if (!issued.issued) + return issued.reason === 'revoked' + ? { + kind: 'revoked', + organizationName: decision.organizationName, + provider: decision.provider, + } + : UNAVAILABLE const returnUrl = resolveReturnUrl(input.returnUrl) return { kind: 'ready', - invitationToken, - optionId: option.id, + invitationToken: issued.token, + optionId: decision.optionId, ...(returnUrl ? { returnUrl } : {}), + credentialGroupId: decision.credentialGroupId, + enrollmentId: issued.enrollmentId, + created: issued.created, + bound: issued.bound, } }, + projectAudit: ({ result }) => + result.kind === 'ready' && (result.created || result.bound) + ? { + workspaceId: null, + action: AuditAction.CREDENTIAL_GROUP_UPDATED, + resourceType: AuditResourceType.CREDENTIAL_GROUP, + resourceId: result.credentialGroupId, + description: result.created + ? 'Enrolled themselves to connect an account' + : 'Accepted a request to connect an account', + metadata: { + enrollmentId: result.enrollmentId, + optionId: result.optionId, + created: result.created, + bound: result.bound, + }, + } + : [], }) diff --git a/apps/sim/lib/credential-groups/application/connection-requests.ts b/apps/sim/lib/credential-groups/application/connection-requests.ts index d210db3dc8f..902f702fcb2 100644 --- a/apps/sim/lib/credential-groups/application/connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/connection-requests.ts @@ -20,9 +20,12 @@ import { organizationAccountPolicyAllowsWorkspace, } from '@/lib/credential-groups/application/workspace-access-policy' import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' +import { + CONNECTION_REQUESTS_OFF, + connectionRequestRefusal, +} from '@/lib/credential-groups/connection-request-policy' import { ConnectionRequestDailyLimitError, - loadConnectionRequestGroup, loadConnectionRequestPolicy, loadOrganizationAccountConnectionStatus, type OrganizationAccountConnectionStatus, @@ -38,6 +41,11 @@ export interface OrganizationAccountConnectionInput { email: string /** Credential provider ID, as Find Organization Account takes it. */ providerId: string + /** + * Where the connect page offers to send the person once connected. Only `slack`, the Slack + * app's generic deep link, can be asked for; a workflow never supplies a URL. + */ + returnTo?: 'slack' } export interface OrganizationAccountConnectionStatusResult { @@ -145,23 +153,21 @@ export const getOrganizationAccountConnectionStatus = defineAuthorizedWorkspaceU requireWorkspacePolicy(context), input.providerId ) - const [{ status, credentialId }, group] = await Promise.all([ - loadOrganizationAccountConnectionStatus({ - organizationId: context.organizationId, - credentialGroupId: context.credentialGroupId, - credentialGroupOptionIds: options.map((option) => option.id), - email, - providerId: input.providerId, - }), - loadConnectionRequestGroup(context.credentialGroupId), - ]) + const { status, credentialId } = await loadOrganizationAccountConnectionStatus({ + organizationId: context.organizationId, + credentialGroupId: context.credentialGroupId, + credentialGroupOptionIds: options.map((option) => option.id), + email, + providerId: input.providerId, + }) return { status, connected: status === 'connected', credentialId, connectUrl: buildCredentialGroupConnectUrl({ - publicId: group.publicId, + publicId: context.publicId, provider: input.providerId, + returnKey: input.returnTo, }), } }, @@ -182,8 +188,11 @@ interface RecordedRequest extends OrganizationAccountConnectionRequestResult { */ export const requestOrganizationAccountConnection = defineAuthorizedWorkspaceUseCase({ operation: credentialGroupOperations.requestConnection, - resolveContext: ({ input }: { input: OrganizationAccountConnectionInput }) => - resolveOrganizationAccountsWorkspaceContext(input.workspaceId), + resolveContext: async ({ input }: { input: OrganizationAccountConnectionInput }) => { + const context = await resolveOrganizationAccountsWorkspaceContext(input.workspaceId) + const { policy } = await loadConnectionRequestPolicy(context.credentialGroupId) + return { ...context, connectionRequestPolicy: policy ?? CONNECTION_REQUESTS_OFF } + }, authorizationOptions: { delegation: credentialGroupDelegationPolicy }, async authorizeResource({ principal, context }) { requireCredentialGroupWorkflowActor(principal) @@ -193,37 +202,19 @@ export const requestOrganizationAccountConnection = defineAuthorizedWorkspaceUse const { workflowId } = requireCurrentWorkflow(principal) const email = requireRequestableEmail(input.email) const accessPolicy = requireWorkspacePolicy(context) - const { policy: requests } = await loadConnectionRequestPolicy(context.credentialGroupId) - if (!requests?.enabled) - throw new OrchestrationError( - 'forbidden', - 'Workflow connection requests are turned off for this organization' - ) - if ( - requests.workspaces.mode === 'selected' && - !requests.workspaces.workspaceIds.includes(context.workspaceId) - ) - throw new OrchestrationError( - 'forbidden', - 'This workspace is not allowed to request connections' - ) - const domain = email.slice(email.lastIndexOf('@') + 1) - if (!requests.emailDomains.includes(domain)) - throw new OrchestrationError( - 'forbidden', - `Connection requests are not allowed for ${domain} addresses` - ) - if (!requests.providers.includes(input.providerId)) - throw new OrchestrationError( - 'forbidden', - `Connection requests are not allowed for ${input.providerId}` - ) + const policy = context.connectionRequestPolicy + const refusal = connectionRequestRefusal(policy, { + workspaceId: context.workspaceId, + email, + providerId: input.providerId, + }) + if (refusal) throw new OrchestrationError('forbidden', refusal) const { label } = requireAllowedProviderOptions(context, accessPolicy, input.providerId) - const group = await loadConnectionRequestGroup(context.credentialGroupId) const connectUrl = buildCredentialGroupConnectUrl({ - publicId: group.publicId, + publicId: context.publicId, provider: input.providerId, + returnKey: input.returnTo, }) let recorded try { @@ -234,8 +225,8 @@ export const requestOrganizationAccountConnection = defineAuthorizedWorkspaceUse workflowId, providerName: label, connectUrl, - dailyLimit: requests.dailyLimit, - sendEmail: requests.sendEmail, + dailyLimit: policy.dailyLimit, + sendEmail: policy.sendEmail, }) } catch (error) { if (error instanceof ConnectionRequestDailyLimitError) diff --git a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts index 69bfbbf3927..f4d2ea73aea 100644 --- a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts +++ b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts @@ -1,73 +1,100 @@ +import type { SessionPrincipal } from '@sim/auth/principal' import { normalizeEmail } from '@sim/utils/string' -import { findCredentialGroupEnrollmentLinkRecord } from '@/lib/credential-groups/enrollments' +import { defineOperation } from '@/lib/core/application' +import { maskEnrollmentEmail } from '@/lib/credential-groups/email-mask' +import { loadCredentialGroupInviterIdentity } from '@/lib/credential-groups/enrollments' +import { findCredentialGroupEnrollmentLinkRecord } from '@/lib/credential-groups/links' +import { + getCredentialGroupProviderId, + isCredentialGroupProvider, +} from '@/lib/credential-groups/providers' +import { defineAuthorizedCredentialUserUseCase } from '@/lib/credentials/application/authorized-user-use-case' + +const credentialGroupEnrollmentLinkOperations = { + /** + * permission-group-exempt: the person holding the link may be outside the organization; what + * they learn is limited to their own enrollment, matched by their verified email or binding. + */ + explain: defineOperation({ + id: 'credential_groups.enrollment_link.explain', + principalKinds: ['session'], + capability: 'none', + }), +} as const /** * Why an invitation link did not open for a signed-in, verified person. Enrollment details are * only described to the person the enrollment belongs to; anyone else holding the link learns - * just a masked form of the address it was sent to. + * just a masked form of the address it was sent to. `reopen` is an expired connect-page link: + * the person starts again from the connect URL, which mints a fresh one. */ export type CredentialGroupEnrollmentLinkOutcome = | { kind: 'unknown' } | { kind: 'wrong_account'; maskedEmail: string } | { kind: 'revoked'; organizationName: string } | { kind: 'paused'; organizationName: string } + | { + kind: 'reopen' + organizationName: string + connect: { publicId: string; provider: string; optionId: string } + } | { kind: 'needs_new_link' - reason: 'expired' | 'delivery_failed' | 'link_revoked' + reason: 'expired' | 'link_revoked' organizationName: string inviterName: string | null } | { kind: 'unavailable' } -interface ExplainCredentialGroupEnrollmentLinkParams { - invitationToken: string - user: { id: string; email: string } -} - -/** Masks an address as `b***@example.com` so a forwarded link never reveals who it was for. */ -export function maskEnrollmentEmail(email: string): string { - const at = email.lastIndexOf('@') - if (at < 1) return '***' - return `${email[0]}***${email.slice(at)}` -} - -/** Explains a link that failed to open, for the page that shows the person what to do next. */ -export async function explainCredentialGroupEnrollmentLink({ - invitationToken, - user, -}: ExplainCredentialGroupEnrollmentLinkParams): Promise { - const record = await findCredentialGroupEnrollmentLinkRecord(invitationToken) - if (!record) return { kind: 'unknown' } +/** + * Explains a link that failed to open, for the page that shows the person what to do next. Reads + * only, and only about the enrollment the link names. A `delivery_failed` enrollment is not an + * outcome: it no longer keeps a live link from opening, so a link that failed is explained by + * what did stop it. + */ +export const explainCredentialGroupEnrollmentLink = defineAuthorizedCredentialUserUseCase({ + operation: credentialGroupEnrollmentLinkOperations.explain, + async execute({ + principal, + input, + }: { + principal: SessionPrincipal + input: { invitationToken: string } + }): Promise { + const [record, viewer] = await Promise.all([ + findCredentialGroupEnrollmentLinkRecord(input.invitationToken), + loadCredentialGroupInviterIdentity(principal.userId), + ]) + if (!record || !viewer) return { kind: 'unknown' } - const belongsToUser = record.userId - ? record.userId === user.id - : normalizeEmail(user.email) === record.email - if (!belongsToUser) - return { kind: 'wrong_account', maskedEmail: maskEnrollmentEmail(record.email) } + const belongsToUser = record.userId + ? record.userId === principal.userId + : normalizeEmail(viewer.email) === record.email + if (!belongsToUser) + return { kind: 'wrong_account', maskedEmail: maskEnrollmentEmail(record.email) } - const { organizationName } = record - if (record.revoked) return { kind: 'revoked', organizationName } - if (!record.groupActive) return { kind: 'paused', organizationName } - if (record.linkRevoked) - return { - kind: 'needs_new_link', - reason: 'link_revoked', - organizationName, - inviterName: record.inviterName, - } - if (record.status === 'delivery_failed') - return { - kind: 'needs_new_link', - reason: 'delivery_failed', - organizationName, - inviterName: record.inviterName, - } - if (record.expired) - return { - kind: 'needs_new_link', - reason: 'expired', - organizationName, - inviterName: record.inviterName, - } - return { kind: 'unavailable' } -} + const { organizationName, inviterName } = record + if (record.revoked) return { kind: 'revoked', organizationName } + if (!record.groupActive) return { kind: 'paused', organizationName } + if (record.linkRevoked) + return { kind: 'needs_new_link', reason: 'link_revoked', organizationName, inviterName } + if (!record.expired) return { kind: 'unavailable' } + const focusOption = record.focus?.option + if ( + record.purpose === 'connect' && + record.focus && + focusOption?.status === 'active' && + isCredentialGroupProvider(focusOption.provider) + ) + return { + kind: 'reopen', + organizationName, + connect: { + publicId: record.focus.publicId, + provider: getCredentialGroupProviderId(focusOption.provider), + optionId: focusOption.id, + }, + } + return { kind: 'needs_new_link', reason: 'expired', organizationName, inviterName } + }, +}) diff --git a/apps/sim/lib/credential-groups/application/organization-workspace-access.ts b/apps/sim/lib/credential-groups/application/organization-workspace-access.ts index b6f09a114ac..3e6dc0772f3 100644 --- a/apps/sim/lib/credential-groups/application/organization-workspace-access.ts +++ b/apps/sim/lib/credential-groups/application/organization-workspace-access.ts @@ -13,6 +13,8 @@ import { requireResourcePolicy } from '@/lib/resource-policies/repository' export interface OrganizationAccountsWorkspaceContext extends CredentialGroupApplicationContext { organizationId: string + /** The group's public identity, for secret-free connect links. */ + publicId: string workspaceAccessPolicy?: OrganizationAccountAccessPolicy } diff --git a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts index 5c41a01f6af..57ebb8e081d 100644 --- a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts +++ b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts @@ -14,11 +14,11 @@ import { runWithOutboundOrganization } from '@/lib/core/network/context.server' import { OrchestrationError } from '@/lib/core/orchestration/types' import { sameResourceScopeCondition } from '@/lib/core/resource-scope.server' import { createCredentialGroupOAuthStartUrl } from '@/lib/credential-groups/enrollment-links' +import { lockCredentialGroupEnrollmentLifecycle } from '@/lib/credential-groups/enrollments' import { createUnissuedInvitationTokenHash, - lockCredentialGroupEnrollmentLifecycle, revokeCredentialGroupEnrollmentLinks, -} from '@/lib/credential-groups/enrollments' +} from '@/lib/credential-groups/links' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import { createViewerCredentialGroupEnrollment } from '@/lib/credential-groups/self-enrollment' import { diff --git a/apps/sim/lib/credential-groups/application/public-enrollment.ts b/apps/sim/lib/credential-groups/application/public-enrollment.ts index b91bf95622b..1f991103ade 100644 --- a/apps/sim/lib/credential-groups/application/public-enrollment.ts +++ b/apps/sim/lib/credential-groups/application/public-enrollment.ts @@ -17,11 +17,14 @@ import { getAuthorizedCredentialGroupMcpOAuthContext, getAuthorizedCredentialGroupOAuthContext, getAuthorizedPublicCredentialGroupEnrollment, - getCredentialGroupEnrollmentLinkOptionId, getCredentialGroupMcpOAuthContextForEnrollment, getCredentialGroupOAuthContextForEnrollment, type PublicCredentialGroupEnrollmentIdentity, } from '@/lib/credential-groups/enrollments' +import { + CredentialGroupLinkFocusError, + getCredentialGroupEnrollmentLinkOptionId, +} from '@/lib/credential-groups/links' import { completeCredentialGroupMcpOAuth, startCredentialGroupMcpOAuth, @@ -32,10 +35,7 @@ import { startCredentialGroupOAuth, } from '@/lib/credential-groups/oauth' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' -import { - CredentialGroupInvitationUnavailableError, - CredentialGroupLinkFocusError, -} from '@/lib/credential-groups/provider-adapter' +import { CredentialGroupInvitationUnavailableError } from '@/lib/credential-groups/provider-adapter' import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { fireCredentialGroupTrigger } from '@/lib/credential-groups/trigger' import { isKnowledgeMemberAccessAvailable } from '@/lib/knowledge/access/availability' diff --git a/apps/sim/lib/credential-groups/connect-subject.ts b/apps/sim/lib/credential-groups/connect-subject.ts new file mode 100644 index 00000000000..0e084f5ef02 --- /dev/null +++ b/apps/sim/lib/credential-groups/connect-subject.ts @@ -0,0 +1,231 @@ +import { db } from '@sim/db' +import { + type CredentialGroupOptionConfig, + credentialGroup, + credentialGroupEnrollment, + organization, + user, + workspace, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { normalizeEmail } from '@sim/utils/string' +import { and, eq, or } from 'drizzle-orm' +import { + lockCredentialGroupEnrollmentLifecycle, + lockCredentialGroupInvitationTarget, +} from '@/lib/credential-groups/enrollments' +import { + createUnissuedInvitationTokenHash, + INVITATION_TTL_MS, + insertEnrollmentLink, +} from '@/lib/credential-groups/links' + +/** + * Reads and writes for the secret-free connect URL. The decision of what a signed-in person may + * do lives in the connect use case; these functions only load what it decides on and, once it + * has decided, mint the person's link. + */ + +type EnrollmentRow = typeof credentialGroupEnrollment.$inferSelect + +interface CredentialGroupConnectSubject { + viewer: { email: string; emailVerified: boolean } + group: { + id: string + workspaceId: string | null + organizationId: string | null + status: 'active' | 'disabled' + options: CredentialGroupOptionConfig[] + organizationName: string + } + enrollment: Pick | null +} + +/** + * Loads the group a public connect URL names and the enrollment that belongs to the signed-in + * person: the one bound to them, else the one invited at their email. Null for an unknown + * public ID or user. Authorizes nothing; the connect use case decides what the person may do. + */ +export async function loadCredentialGroupConnectSubject(input: { + publicId: string + userId: string +}): Promise { + const [viewer] = await db + .select({ email: user.email, emailVerified: user.emailVerified }) + .from(user) + .where(eq(user.id, input.userId)) + .limit(1) + if (!viewer) return null + const [group] = await db + .select({ + id: credentialGroup.id, + workspaceId: credentialGroup.workspaceId, + organizationId: credentialGroup.organizationId, + status: credentialGroup.status, + options: credentialGroup.options, + organizationName: organization.name, + workspaceName: workspace.name, + }) + .from(credentialGroup) + .leftJoin(workspace, eq(workspace.id, credentialGroup.workspaceId)) + .leftJoin(organization, eq(organization.id, credentialGroup.organizationId)) + .where(eq(credentialGroup.publicId, input.publicId)) + .limit(1) + if (!group) return null + const enrollments = await db + .select({ + id: credentialGroupEnrollment.id, + email: credentialGroupEnrollment.email, + userId: credentialGroupEnrollment.userId, + status: credentialGroupEnrollment.status, + revokedAt: credentialGroupEnrollment.revokedAt, + }) + .from(credentialGroupEnrollment) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, group.id), + or( + eq(credentialGroupEnrollment.userId, input.userId), + eq(credentialGroupEnrollment.email, normalizeEmail(viewer.email)) + ) + ) + ) + .limit(2) + const enrollment = + enrollments.find((candidate) => candidate.userId === input.userId) ?? enrollments[0] ?? null + const { workspaceName, organizationName, ...rest } = group + return { + viewer, + group: { ...rest, organizationName: organizationName ?? workspaceName ?? '' }, + enrollment, + } +} + +/** Who the connect link is for and which enrollment it opens. */ +export type CredentialGroupConnectLinkTarget = + /** An enrollment the person already holds: bound to them, or invited at their email. */ + | { kind: 'enrollment'; enrollmentId: string } + /** An organization member with no enrollment, who confirmed enrolling themselves. */ + | { kind: 'self_enrollment' } + +type IssuedCredentialGroupConnectLink = + | { + issued: true + token: string + enrollmentId: string + /** The enrollment was created for this link. */ + created: boolean + /** The person was bound to the enrollment by this link. */ + bound: boolean + } + | { issued: false; reason: 'revoked' | 'unavailable' } + +/** + * Mints a short-lived link focused on one account option and, in the same transaction, creates + * the member's enrollment when they confirmed self-enrollment and binds the signed-in person to an + * unbound one. The enrollment's lifecycle lock serializes it with revocation, so a revocation that + * commits first is reported as `revoked` and a later one kills the new link. Inserts a link row + * only: an existing enrollment's issuer, timestamps, status and legacy token column stay as they + * are. + * + * The caller has already decided the person may connect; this re-checks, under the lock, only what + * may have changed since: revocation, the group still being active, the binding, and that the + * person's verified email still matches an unbound enrollment. + */ +export async function issueCredentialGroupConnectLink(input: { + credentialGroupId: string + userId: string + optionId: string + target: CredentialGroupConnectLinkTarget +}): Promise { + return db.transaction(async (tx) => { + const now = new Date() + const [viewer] = await tx + .select({ email: user.email, emailVerified: user.emailVerified }) + .from(user) + .where(eq(user.id, input.userId)) + .limit(1) + if (!viewer?.emailVerified) return { issued: false, reason: 'unavailable' } + const viewerEmail = normalizeEmail(viewer.email) + + let enrollmentId: string + let created = false + if (input.target.kind === 'self_enrollment') { + await lockCredentialGroupInvitationTarget(tx, input.credentialGroupId, viewerEmail) + const [existing] = await tx + .select({ id: credentialGroupEnrollment.id }) + .from(credentialGroupEnrollment) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId), + eq(credentialGroupEnrollment.email, viewerEmail) + ) + ) + .limit(1) + if (existing) { + enrollmentId = existing.id + } else { + enrollmentId = generateId() + created = true + await tx.insert(credentialGroupEnrollment).values({ + id: enrollmentId, + credentialGroupId: input.credentialGroupId, + email: viewerEmail, + status: 'invited', + /** No invitation was emailed; the legacy column names no link. */ + invitationTokenHash: createUnissuedInvitationTokenHash(), + invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), + invitedAt: now, + createdBy: null, + createdAt: now, + updatedAt: now, + }) + } + } else { + enrollmentId = input.target.enrollmentId + } + + await lockCredentialGroupEnrollmentLifecycle(tx, enrollmentId) + const [current] = await tx + .select({ + email: credentialGroupEnrollment.email, + userId: credentialGroupEnrollment.userId, + status: credentialGroupEnrollment.status, + revokedAt: credentialGroupEnrollment.revokedAt, + groupStatus: credentialGroup.status, + }) + .from(credentialGroupEnrollment) + .innerJoin( + credentialGroup, + eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId) + ) + .where( + and( + eq(credentialGroupEnrollment.id, enrollmentId), + eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId) + ) + ) + .limit(1) + .for('update', { of: credentialGroupEnrollment }) + if (!current) return { issued: false, reason: 'unavailable' } + if (current.status === 'revoked' || current.revokedAt) + return { issued: false, reason: 'revoked' } + if (current.groupStatus !== 'active') return { issued: false, reason: 'unavailable' } + if (current.userId ? current.userId !== input.userId : current.email !== viewerEmail) + return { issued: false, reason: 'unavailable' } + + const bound = !current.userId + if (bound) + await tx + .update(credentialGroupEnrollment) + .set({ userId: input.userId, updatedAt: now }) + .where(eq(credentialGroupEnrollment.id, enrollmentId)) + const { token } = await insertEnrollmentLink(tx, { + enrollmentId, + purpose: 'connect', + optionId: input.optionId, + now, + }) + return { issued: true, token, enrollmentId, created, bound } + }) +} diff --git a/apps/sim/lib/credential-groups/connection-request-policy.ts b/apps/sim/lib/credential-groups/connection-request-policy.ts index a334f18d7bb..3a422a6b344 100644 --- a/apps/sim/lib/credential-groups/connection-request-policy.ts +++ b/apps/sim/lib/credential-groups/connection-request-policy.ts @@ -82,4 +82,35 @@ export const connectionRequestPolicySchema = storedConnectionRequestPolicySchema ) export type ConnectionRequestPolicy = z.output -export type ConnectionRequestPolicyInput = z.input + +/** The policy of an organization whose admin never saved one: requests are off. */ +export const CONNECTION_REQUESTS_OFF: ConnectionRequestPolicy = { + enabled: false, + workspaces: { mode: 'all' }, + emailDomains: [], + providers: [], + dailyLimit: CONNECTION_REQUEST_DAILY_LIMIT_DEFAULT, + sendEmail: false, +} + +/** + * Why the admin's policy refuses a workflow's connection request, or null when it allows it. The + * reasons describe the workflow author's configuration, never the person asked. + */ +export function connectionRequestRefusal( + policy: ConnectionRequestPolicy, + request: { workspaceId: string; email: string; providerId: string } +): string | null { + if (!policy.enabled) return 'Workflow connection requests are turned off for this organization' + if ( + policy.workspaces.mode === 'selected' && + !policy.workspaces.workspaceIds.includes(request.workspaceId) + ) + return 'This workspace is not allowed to request connections' + const domain = request.email.slice(request.email.lastIndexOf('@') + 1) + if (!policy.emailDomains.includes(domain)) + return `Connection requests are not allowed for ${domain} addresses` + if (!policy.providers.includes(request.providerId)) + return `Connection requests are not allowed for ${request.providerId}` + return null +} diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index 8b36f2f2be4..cff1635b9c8 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -1,7 +1,6 @@ import { db } from '@sim/db' import { credential, - credentialGroup, credentialGroupConnectionRequest, credentialGroupConnectionRequestPolicy, credentialGroupEnrollment, @@ -23,15 +22,11 @@ import { LIVE_ENROLLMENT_STATUSES, listCredentialGroupCredentialReferences, } from '@/lib/credential-groups/credentials' -import { - createUnissuedInvitationTokenHash, - lockCredentialGroupInvitationTarget, -} from '@/lib/credential-groups/enrollments' +import { lockCredentialGroupInvitationTarget } from '@/lib/credential-groups/enrollments' +import { DAY_MS } from '@/lib/credential-groups/limits' +import { createUnissuedInvitationTokenHash, INVITATION_TTL_MS } from '@/lib/credential-groups/links' import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' -const DAY_MS = 24 * 60 * 60 * 1000 -/** Matches the admin invitation lifetime, so an unbound requested enrollment ages out alike. */ -const REQUESTED_ENROLLMENT_TTL_MS = 7 * DAY_MS /** Reminders a workflow-requested enrollment may receive after its first email. */ const CONNECTION_REQUEST_MAX_REMINDERS = 3 /** No reminder goes out for an enrollment requested longer ago than this. */ @@ -104,17 +99,6 @@ export async function loadOrganizationAccountConnectionStatus(input: { : { status: 'not_connected', credentialId: null } } -/** The group's public identity, for the connect link. */ -export async function loadConnectionRequestGroup(credentialGroupId: string) { - const [row] = await db - .select({ publicId: credentialGroup.publicId }) - .from(credentialGroup) - .where(eq(credentialGroup.id, credentialGroupId)) - .limit(1) - if (!row) throw new Error('Credential group not found') - return row -} - /** * The admin's stored connection request policy and its revision. `revision` is `0` and * `policy` is `null` while none was ever saved, which means requests are off. @@ -206,14 +190,14 @@ interface RecordedConnectionRequest { * Only an absent enrollment is created. An existing one keeps its status and attribution: a * revoked person stays revoked, an admin's invitation stays the admin's, and a connected person * stays connected. The only write to an existing row is a reminder on an unbound, still-invited - * enrollment a workflow created: when nobody asked for this address in the last day, the + * enrollment a workflow created (including one whose last email failed): when nobody asked for this address in the last day, the * enrollment was requested within the last 30 days, and it has had fewer than * {@link CONNECTION_REQUEST_MAX_REMINDERS} reminders. That update re-checks the row's state, so a * revocation committed meanwhile sends nothing. * * Emails are enqueued on the outbox in the same transaction, so nothing here waits on rendering * or delivery. Log rows are only read inside the cap's one-day window and are pruned after two - * days by {@link pruneCredentialGroupConnectHistory}. + * days by the hourly `cleanup-credential-group-links` job. */ export async function recordCredentialGroupConnectionRequest(input: { credentialGroupId: string @@ -307,7 +291,7 @@ export async function recordCredentialGroupConnectionRequest(input: { .where( and( eq(credentialGroupEnrollment.id, existing.id), - eq(credentialGroupEnrollment.status, 'invited'), + inArray(credentialGroupEnrollment.status, ['invited', 'delivery_failed']), isNull(credentialGroupEnrollment.userId), isNotNull(credentialGroupEnrollment.requestedByWorkflowId), lt( @@ -336,7 +320,8 @@ export async function recordCredentialGroupConnectionRequest(input: { status: 'invited', /** No invitation link is issued: the person signs in on the connect page instead. */ invitationTokenHash: createUnissuedInvitationTokenHash(), - invitationExpiresAt: new Date(now.getTime() + REQUESTED_ENROLLMENT_TTL_MS), + /** The admin invitation lifetime, so an unbound requested enrollment ages out alike. */ + invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), invitedAt: now, sentAt: input.sendEmail ? now : null, createdBy: null, diff --git a/apps/sim/lib/credential-groups/credentials.ts b/apps/sim/lib/credential-groups/credentials.ts index bbe6a0762ff..9ae0a404526 100644 --- a/apps/sim/lib/credential-groups/credentials.ts +++ b/apps/sim/lib/credential-groups/credentials.ts @@ -487,6 +487,7 @@ export async function loadScopedAccountsCredentialListContext( const [row] = await db .select({ credentialGroupId: credentialGroup.id, + publicId: credentialGroup.publicId, workspaceId: credentialGroup.workspaceId, organizationId: credentialGroup.organizationId, name: credentialGroup.name, diff --git a/apps/sim/lib/credential-groups/email-mask.ts b/apps/sim/lib/credential-groups/email-mask.ts new file mode 100644 index 00000000000..c15d84a7d2a --- /dev/null +++ b/apps/sim/lib/credential-groups/email-mask.ts @@ -0,0 +1,6 @@ +/** Masks an address as `b***@example.com` so a forwarded link never reveals who it was for. */ +export function maskEnrollmentEmail(email: string): string { + const at = email.lastIndexOf('@') + if (at < 1) return '***' + return `${email[0]}***${email.slice(at)}` +} diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 9432ae4420d..4732ff80622 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -10,25 +10,10 @@ import { user, workspace, } from '@sim/db/schema' -import { sha256Hex } from '@sim/security/hash' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { normalizeEmail, truncate } from '@sim/utils/string' -import { - and, - asc, - count, - desc, - eq, - gt, - inArray, - isNotNull, - isNull, - lt, - or, - type SQL, - sql, -} from 'drizzle-orm' +import { and, asc, count, desc, eq, inArray, isNull, lt, or, type SQL, sql } from 'drizzle-orm' import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' import { getCredentialGroupInvitationSubject } from '@/components/emails/subjects' import { searchFilter } from '@/lib/api/list-query' @@ -41,6 +26,15 @@ import { import { resourceScopeCondition } from '@/lib/core/resource-scope.server' import { getBaseUrl } from '@/lib/core/utils/urls' import { moreUsableAccount } from '@/lib/credential-groups/account-rules' +import { + adoptLegacyInvitationLink, + createUnissuedInvitationTokenHash, + hashInvitationToken, + INVITATION_TTL_MS, + insertEnrollmentLink, + liveEnrollmentLinkCondition, + revokeCredentialGroupEnrollmentLinks, +} from '@/lib/credential-groups/links' import type { ManagedMcpConnectorId } from '@/lib/credential-groups/managed-mcp-connectors' import { getManagedMcpConnector } from '@/lib/credential-groups/managed-mcp-connectors' import { requireOrganizationAccountsSetup } from '@/lib/credential-groups/organization-setup' @@ -66,9 +60,6 @@ import { sendEmail } from '@/lib/messaging/email/mailer' import { getFromEmailAddress } from '@/lib/messaging/email/utils' import { isSearchProviderEnabled } from '@/lib/sim-search/live/provider-rollout' -const INVITATION_TTL_MS = 7 * 24 * 60 * 60 * 1000 -/** How long a `self` or `connect` link lives: it is opened in the sitting it was minted for. */ -const SESSION_LINK_TTL_MS = 60 * 60 * 1000 const DELIVERY_CONCURRENCY = 5 const MAX_ENROLLMENT_PAGE_SIZE = 100 const CONNECTION_SUMMARIES_PER_ENROLLMENT = (CREDENTIAL_GROUP_PROVIDER_IDS.length + 1) * 3 @@ -100,23 +91,12 @@ interface InvitationContext { /** What issuing an invitation does to an enrollment an admin revoked. */ export type RevokedEnrollmentPolicy = 'reactivate' | 'reject' -type EnrollmentLinkPurpose = (typeof credentialGroupEnrollmentLink.$inferInsert)['purpose'] - interface SendInvitationOptions { expectedEnrollmentId?: string revokedEnrollment: RevokedEnrollmentPolicy searchConnection?: { optionId: string; providerName: string } } -interface IssueInvitationOptions extends SendInvitationOptions { - /** - * `email` is an administrator's (re)invitation and restarts the invitation lifecycle; - * `self` only adds a link, leaving an existing enrollment's issuer, timestamps and status as - * they are. - */ - purpose: Extract -} - interface IssuedInvitation { enrollment: EnrollmentRow invitationLink: string @@ -279,66 +259,6 @@ function decodeCredentialGroupEnrollmentCursor(cursor: string): CredentialGroupE } } -function hashInvitationToken(token: string): string { - return sha256Hex(token) -} - -const UNISSUED_INVITATION_PREFIX = 'unissued:' - -/** - * A value for the legacy `invitation_token_hash` column of an enrollment created without an - * emailed link (by self-enrollment or a workflow's connection request). It contains a character - * no hex digest does, so no token ever hashes to it: the legacy branch of - * {@link liveEnrollmentLinkCondition} never matches it and link adoption skips it. It is unique - * and 64 characters long, as the column requires. - */ -export function createUnissuedInvitationTokenHash(): string { - return `${UNISSUED_INVITATION_PREFIX}${sha256Hex(generateId()).slice(UNISSUED_INVITATION_PREFIX.length)}` -} - -function isUnissuedInvitationTokenHash(value: string): boolean { - return value.startsWith(UNISSUED_INVITATION_PREFIX) -} - -/** - * Matches the enrollment row that `tokenHash` is a live link into: an unrevoked, unexpired link. - * Only an emailed link outlives its expiry, and only once the enrollment is bound to a user (from - * then on the signed-in user is the authority, not the email's age); `self` and `connect` links - * are minted for one sitting and always expire. A hash with no link row falls back to the - * enrollment's legacy column, an emailed invitation the pre-link app still writes during a - * deploy or rollback. - */ -export function liveEnrollmentLinkCondition(tokenHash: string, now = new Date()): SQL { - const link = credentialGroupEnrollmentLink - const bound = isNotNull(credentialGroupEnrollment.userId) - return sql`(exists (select 1 from ${link} where ${and( - eq(link.enrollmentId, credentialGroupEnrollment.id), - eq(link.tokenHash, tokenHash), - isNull(link.revokedAt), - or(and(bound, eq(link.purpose, 'email')), gt(link.expiresAt, now)) - )}) or (${and( - eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), - or(bound, gt(credentialGroupEnrollment.invitationExpiresAt, now)) - )} and not exists (select 1 from ${link} where ${eq(link.tokenHash, tokenHash)})))` -} - -/** Revokes every link into an enrollment; callers hold its lifecycle lock. */ -export async function revokeCredentialGroupEnrollmentLinks( - tx: DbTransaction, - enrollmentId: string, - now = new Date() -): Promise { - await tx - .update(credentialGroupEnrollmentLink) - .set({ revokedAt: now }) - .where( - and( - eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId), - isNull(credentialGroupEnrollmentLink.revokedAt) - ) - ) -} - function metadataString(metadata: object | null, key: string): string | null { const value = metadata ? (metadata as Record)[key] : undefined return typeof value === 'string' && value.length > 0 ? value : null @@ -582,27 +502,48 @@ async function getInvitationContext( } } +function invitationLinkFor(token: string): string { + return `${getBaseUrl()}/credential-groups/enroll/${token}` +} + /** - * Gives the invitation in an enrollment's legacy column a link row when it has none, so that - * overwriting the column does not kill a link the released app emailed during a deploy. A revoked - * enrollment's adopted link is revoked with it. + * Locks the invitation target and reads its enrollment, if any, under the enrollment's lifecycle + * lock as well. */ -async function adoptLegacyInvitationLink(tx: DbTransaction, current: EnrollmentRow, now: Date) { - if (isUnissuedInvitationTokenHash(current.invitationTokenHash)) return - await tx - .insert(credentialGroupEnrollmentLink) - .values({ - id: generateId(), - enrollmentId: current.id, - tokenHash: current.invitationTokenHash, - purpose: 'email', - expiresAt: current.invitationExpiresAt, - revokedAt: current.status === 'revoked' || current.revokedAt ? now : null, - createdAt: current.invitedAt, - }) - .onConflictDoNothing({ target: credentialGroupEnrollmentLink.tokenHash }) +async function lockInvitationEnrollment( + tx: DbTransaction, + groupId: string, + email: string +): Promise { + await lockCredentialGroupInvitationTarget(tx, groupId, email) + const byTarget = and( + eq(credentialGroupEnrollment.credentialGroupId, groupId), + eq(credentialGroupEnrollment.email, email) + ) + const [existing] = await tx + .select({ id: credentialGroupEnrollment.id }) + .from(credentialGroupEnrollment) + .where(byTarget) + .limit(1) + if (!existing) return undefined + await lockCredentialGroupEnrollmentLifecycle(tx, existing.id) + const [locked] = await tx + .select() + .from(credentialGroupEnrollment) + .where(and(eq(credentialGroupEnrollment.id, existing.id), byTarget)) + .limit(1) + return locked } +/** + * Emails a fresh invitation link: an administrator's invitation, reinvitation or resend (or an + * automatic invitation a workflow issued). It deliberately restarts the invitation lifecycle on an + * existing enrollment: the issuer, `invitedAt` and `sentAt` move to this send, the status returns + * to `invited` unless the person already made progress, and a workflow's connection-request + * marker and reminder count are cleared, since the enrollment is now the inviter's. Delivery + * bookkeeping depends on that reset ({@link deliveryStillCurrent} compares `invitedAt`). Earlier + * links stay live; only a revocation kills them. + */ async function issueInvitation( context: InvitationContext, /** @@ -614,45 +555,14 @@ async function issueInvitation( */ userId: string | undefined, email: string, - options: IssueInvitationOptions + options: SendInvitationOptions ): Promise { const now = new Date() const token = generateId() - const tokenHash = hashInvitationToken(token) - const expiresAt = new Date( - now.getTime() + (options.purpose === 'email' ? INVITATION_TTL_MS : SESSION_LINK_TTL_MS) - ) + const expiresAt = new Date(now.getTime() + INVITATION_TTL_MS) const issued = await db.transaction(async (tx) => { - await lockCredentialGroupInvitationTarget(tx, context.groupId, email) - const [existing] = await tx - .select() - .from(credentialGroupEnrollment) - .where( - and( - eq(credentialGroupEnrollment.credentialGroupId, context.groupId), - eq(credentialGroupEnrollment.email, email) - ) - ) - .limit(1) - - let current = existing - if (existing) { - await lockCredentialGroupEnrollmentLifecycle(tx, existing.id) - const [locked] = await tx - .select() - .from(credentialGroupEnrollment) - .where( - and( - eq(credentialGroupEnrollment.id, existing.id), - eq(credentialGroupEnrollment.credentialGroupId, context.groupId), - eq(credentialGroupEnrollment.email, email) - ) - ) - .limit(1) - current = locked - } - + const current = await lockInvitationEnrollment(tx, context.groupId, email) if (options.expectedEnrollmentId && current?.id !== options.expectedEnrollmentId) { throw new CredentialGroupEnrollmentError('Enrollment not found', 404) } @@ -662,8 +572,9 @@ async function issueInvitation( if (current) { await adoptLegacyInvitationLink(tx, current, now) /** - * The released app revokes by status alone, so links into an enrollment it revoked may - * still be unrevoked; none of them may survive a reinvitation. + * Status is authoritative for revocation: the released app revokes by status alone, so + * links into an enrollment it revoked may still be unrevoked, and none of them may survive + * a reinvitation. */ if (current.status === 'revoked' || current.revokedAt) await revokeCredentialGroupEnrollmentLinks(tx, current.id, now) @@ -673,7 +584,7 @@ async function issueInvitation( const nextStatus = preservesProgress ? current.status : ('invited' as const) /** The legacy column mirrors the newest emailed link, the one an admin sees expire. */ const invitationValues = { - invitationTokenHash: tokenHash, + invitationTokenHash: hashInvitationToken(token), invitationExpiresAt: expiresAt, status: nextStatus, invitedAt: now, @@ -682,185 +593,83 @@ async function issueInvitation( revokedAt: null, lastDeliveryError: null, createdBy: userId ?? null, + requestedByWorkflowId: null, + connectionRequestReminders: 0, updatedAt: now, } - const [next] = !current + const [next] = current ? await tx + .update(credentialGroupEnrollment) + .set(invitationValues) + .where(eq(credentialGroupEnrollment.id, current.id)) + .returning() + : await tx .insert(credentialGroupEnrollment) .values({ id: generateId(), credentialGroupId: context.groupId, email, ...invitationValues, - /** - * No email was sent: the admin-facing invitation window is the default one, and the - * legacy column names no link, so pruning the session link cannot leave its token - * resolving through the column. - */ - ...(options.purpose === 'email' - ? {} - : { - invitationTokenHash: createUnissuedInvitationTokenHash(), - invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), - }), createdAt: now, }) .returning() - : options.purpose === 'email' - ? await tx - .update(credentialGroupEnrollment) - .set(invitationValues) - .where(eq(credentialGroupEnrollment.id, current.id)) - .returning() - : [current] if (!next) throw new Error('Credential group enrollment write returned no row') - const [link] = await tx - .insert(credentialGroupEnrollmentLink) - .values({ - id: generateId(), - enrollmentId: next.id, - tokenHash, - purpose: options.purpose, - expiresAt, - createdAt: now, - }) - .returning({ id: credentialGroupEnrollmentLink.id }) - if (!link) throw new Error('Credential group enrollment link insert returned no row') - return { enrollment: next, linkId: link.id } + const { linkId } = await insertEnrollmentLink(tx, { + enrollmentId: next.id, + purpose: 'email', + token, + expiresAt, + now, + }) + return { enrollment: next, linkId } }) - return { - ...issued, - invitationLink: `${getBaseUrl()}/credential-groups/enroll/${token}`, - } + return { ...issued, invitationLink: invitationLinkFor(token) } } /** - * Mints a short-lived link focused on one account option for an enrollment the caller already - * matched to the signed-in person. Inserts a link row only: the enrollment's issuer, timestamps, - * status and legacy token column stay as they are. Returns the bearer token, or null when the - * enrollment was revoked or removed before the lifecycle lock was taken. + * Adds a one-hour `self` link for a verified member enrolling themselves. Creates the enrollment + * when there is none; an existing one keeps its issuer, timestamps and status. A revoked + * enrollment is refused, never reactivated. */ -export async function issueCredentialGroupConnectLink( - enrollmentId: string, - optionId: string -): Promise { - const token = generateId() - const now = new Date() +async function issueSelfEnrollmentLink( + groupId: string, + email: string +): Promise<{ enrollment: EnrollmentRow; invitationLink: string }> { return db.transaction(async (tx) => { - await lockCredentialGroupEnrollmentLifecycle(tx, enrollmentId) - const [current] = await tx - .select({ status: credentialGroupEnrollment.status }) - .from(credentialGroupEnrollment) - .where( - and( - eq(credentialGroupEnrollment.id, enrollmentId), - isNull(credentialGroupEnrollment.revokedAt) - ) - ) - .limit(1) - if (!current || current.status === 'revoked') return null - await tx.insert(credentialGroupEnrollmentLink).values({ - id: generateId(), - enrollmentId, - tokenHash: hashInvitationToken(token), - purpose: 'connect', - optionId, - expiresAt: new Date(now.getTime() + SESSION_LINK_TTL_MS), - createdAt: now, + const now = new Date() + const current = await lockInvitationEnrollment(tx, groupId, email) + if (current?.status === 'revoked' || current?.revokedAt) { + throw new CredentialGroupEnrollmentError('Revoked enrollment cannot be resent', 409) + } + const [enrollment] = current + ? [current] + : await tx + .insert(credentialGroupEnrollment) + .values({ + id: generateId(), + credentialGroupId: groupId, + email, + status: 'invited', + /** No invitation was emailed; the legacy column names no link. */ + invitationTokenHash: createUnissuedInvitationTokenHash(), + invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), + invitedAt: now, + createdBy: null, + createdAt: now, + updatedAt: now, + }) + .returning() + if (!enrollment) throw new Error('Credential group enrollment insert returned no row') + const { token } = await insertEnrollmentLink(tx, { + enrollmentId: enrollment.id, + purpose: 'self', + now, }) - return token + return { enrollment, invitationLink: invitationLinkFor(token) } }) } -/** - * The single account option a link is limited to, or null when the link (or a legacy token with - * no link row) may connect any option. - */ -export async function getCredentialGroupEnrollmentLinkOptionId( - invitationTokenHash: string -): Promise { - const [row] = await db - .select({ optionId: credentialGroupEnrollmentLink.optionId }) - .from(credentialGroupEnrollmentLink) - .where(eq(credentialGroupEnrollmentLink.tokenHash, invitationTokenHash)) - .limit(1) - return row?.optionId ?? null -} - -export interface CredentialGroupConnectSubject { - viewer: { email: string; emailVerified: boolean } - group: { - id: string - workspaceId: string | null - organizationId: string | null - status: 'active' | 'disabled' - options: CredentialGroupOptionConfig[] - organizationName: string - } - enrollment: Pick | null -} - -/** - * Loads the group a public connect URL names and the enrollment that belongs to the signed-in - * person: the one bound to them, else the one invited at their email. Null for an unknown - * public ID or user. Authorizes nothing; the connect use case decides what the person may do. - */ -export async function loadCredentialGroupConnectSubject(input: { - publicId: string - userId: string -}): Promise { - const [viewer] = await db - .select({ email: user.email, emailVerified: user.emailVerified }) - .from(user) - .where(eq(user.id, input.userId)) - .limit(1) - if (!viewer) return null - const [group] = await db - .select({ - id: credentialGroup.id, - workspaceId: credentialGroup.workspaceId, - organizationId: credentialGroup.organizationId, - status: credentialGroup.status, - options: credentialGroup.options, - organizationName: organization.name, - workspaceName: workspace.name, - }) - .from(credentialGroup) - .leftJoin(workspace, eq(workspace.id, credentialGroup.workspaceId)) - .leftJoin(organization, eq(organization.id, credentialGroup.organizationId)) - .where(eq(credentialGroup.publicId, input.publicId)) - .limit(1) - if (!group) return null - const enrollments = await db - .select({ - id: credentialGroupEnrollment.id, - email: credentialGroupEnrollment.email, - userId: credentialGroupEnrollment.userId, - status: credentialGroupEnrollment.status, - revokedAt: credentialGroupEnrollment.revokedAt, - }) - .from(credentialGroupEnrollment) - .where( - and( - eq(credentialGroupEnrollment.credentialGroupId, group.id), - or( - eq(credentialGroupEnrollment.userId, input.userId), - eq(credentialGroupEnrollment.email, normalizeEmail(viewer.email)) - ) - ) - ) - .limit(2) - const enrollment = - enrollments.find((candidate) => candidate.userId === input.userId) ?? enrollments[0] ?? null - const { workspaceName, organizationName, ...rest } = group - return { - viewer, - group: { ...rest, organizationName: organizationName ?? workspaceName ?? '' }, - enrollment, - } -} - /** * True while an emailed invitation is still the enrollment's newest one, unrevoked and in the * state it was issued in, so a slower send never records its outcome over a later send's. Only @@ -895,7 +704,7 @@ async function sendInvitation( enrollment: issued, invitationLink, linkId, - } = await issueInvitation(context, userId, email, { ...options, purpose: 'email' }) + } = await issueInvitation(context, userId, email, options) const focusedLink = new URL(invitationLink) if (options.searchConnection) { focusedLink.searchParams.set('optionId', options.searchConnection.optionId) @@ -1233,10 +1042,7 @@ export async function createCredentialGroupSelfEnrollmentLink( ): Promise { const scope = credentialGroupScope(scopeInput) const context = await getInvitationContext(scope, groupId, false) - const issued = await issueInvitation(context, undefined, normalizeEmail(email), { - revokedEnrollment: 'reject', - purpose: 'self', - }) + const issued = await issueSelfEnrollmentLink(context.groupId, normalizeEmail(email)) return { enrollment: toCredentialGroupEnrollment(issued.enrollment), invitationLink: issued.invitationLink, @@ -1739,87 +1545,3 @@ function credentialGroupOAuthContextFromRow( options: row.options, } } - -export interface CredentialGroupEnrollmentLinkRecord { - email: string - userId: string | null - status: CredentialGroupEnrollmentStatus - /** - * Past its expiry, matching {@link liveEnrollmentLinkCondition}: a `self` or `connect` link - * always expires, an emailed one only while the enrollment has no bound user. - */ - expired: boolean - /** The enrollment itself was revoked by an admin. */ - revoked: boolean - /** This link alone was revoked (a disconnect) while the enrollment may still be live. */ - linkRevoked: boolean - groupActive: boolean - organizationName: string - inviterName: string | null -} - -/** - * Reads the enrollment an invitation token names in any state, so the person holding it can be - * told why it stopped working. Resolves the token the way {@link liveEnrollmentLinkCondition} - * does (its link row, else the legacy column when no link row carries the hash) without the - * liveness filter. Grants no authority: live-link callers use - * {@link authenticatePublicCredentialGroupEnrollment}. - */ -export async function findCredentialGroupEnrollmentLinkRecord( - token: string -): Promise { - if (!token.trim() || token.length > 128) return null - const tokenHash = hashInvitationToken(token) - const link = credentialGroupEnrollmentLink - const [row] = await db - .select({ - email: credentialGroupEnrollment.email, - userId: credentialGroupEnrollment.userId, - status: credentialGroupEnrollment.status, - legacyExpiresAt: credentialGroupEnrollment.invitationExpiresAt, - revokedAt: credentialGroupEnrollment.revokedAt, - linkExpiresAt: link.expiresAt, - linkPurpose: link.purpose, - linkRevokedAt: link.revokedAt, - groupStatus: credentialGroup.status, - workspaceId: credentialGroup.workspaceId, - organizationId: credentialGroup.organizationId, - organizationName: organization.name, - workspaceName: workspace.name, - inviterName: user.name, - }) - .from(credentialGroupEnrollment) - .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) - .leftJoin( - link, - and(eq(link.enrollmentId, credentialGroupEnrollment.id), eq(link.tokenHash, tokenHash)) - ) - .leftJoin(workspace, eq(workspace.id, credentialGroup.workspaceId)) - .leftJoin(organization, eq(organization.id, credentialGroup.organizationId)) - .leftJoin(user, eq(user.id, credentialGroupEnrollment.createdBy)) - .where( - or( - isNotNull(link.id), - and( - eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), - sql`not exists (select 1 from ${link} where ${eq(link.tokenHash, tokenHash)})` - ) - ) - ) - .limit(1) - if (!row || !(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(row)))) return null - const expiresAt = row.linkExpiresAt ?? row.legacyExpiresAt - return { - email: row.email, - userId: row.userId, - status: row.status, - expired: - (!row.userId || (row.linkPurpose ?? 'email') !== 'email') && - expiresAt.getTime() <= Date.now(), - revoked: row.status === 'revoked' || row.revokedAt !== null, - linkRevoked: row.linkRevokedAt !== null, - groupActive: row.groupStatus === 'active', - organizationName: row.organizationName ?? row.workspaceName ?? '', - inviterName: row.inviterName, - } -} diff --git a/apps/sim/lib/credential-groups/limits.ts b/apps/sim/lib/credential-groups/limits.ts index 29f917d17aa..35e90ac0b63 100644 --- a/apps/sim/lib/credential-groups/limits.ts +++ b/apps/sim/lib/credential-groups/limits.ts @@ -1,3 +1,4 @@ +export const DAY_MS = 24 * 60 * 60 * 1000 export const CREDENTIAL_GROUP_MCP_SERVER_LIMIT = 50 export const ORGANIZATION_VIEWER_ACCOUNT_LIMIT = 100 export const ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT = 1000 diff --git a/apps/sim/lib/credential-groups/links.ts b/apps/sim/lib/credential-groups/links.ts new file mode 100644 index 00000000000..6ef476d7b78 --- /dev/null +++ b/apps/sim/lib/credential-groups/links.ts @@ -0,0 +1,349 @@ +import { db } from '@sim/db' +import { + type CredentialGroupOptionConfig, + credentialGroup, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + organization, + user, + workspace, +} from '@sim/db/schema' +import { sha256Hex } from '@sim/security/hash' +import { generateId } from '@sim/utils/id' +import { and, eq, gt, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm' +import { alias } from 'drizzle-orm/pg-core' +import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' +import { resourceScopeFromOwner } from '@/lib/core/resource-scope' +import { DAY_MS } from '@/lib/credential-groups/limits' +import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' +import type { DbTransaction } from '@/lib/db/types' + +/** + * Storage for the bearer links into a Credential Group enrollment: each emailed invitation, member + * self-enrollment and connect-page hand-off is one `credential_group_enrollment_link` row, so issuing + * a link never invalidates another. Callers that write hold the enrollment's lifecycle lock. + * + * Link lifetimes: + * - `email`: {@link INVITATION_TTL_MS}, and only while the enrollment is unbound; once a verified + * user is bound, the signed-in user is the authority, not the email's age. + * - `self` and `connect`: {@link SESSION_LINK_TTL_MS}, always. They are minted for the sitting the + * person is in, so a self link from before the link table that the backfill recorded as `email` + * keeps the emailed lifetime instead. + * + * contract-pending(after the enrollment-link expand is fully deployed and no rollback target + * predates it): the enrollment's legacy `invitation_token_hash` column and its `unissued:` values + * go in two steps. First make the column nullable and stop writing it (enrollments created without + * an emailed link then store null instead of {@link createUnissuedInvitationTokenHash}); then drop + * it with its unique index and length check, along with the legacy branch of + * {@link liveEnrollmentLinkCondition}, {@link adoptLegacyInvitationLink}, and the legacy fallback of + * {@link findCredentialGroupEnrollmentLinkRecord}. + */ + +/** How long an emailed invitation, or a workflow-requested enrollment, waits for its person. */ +export const INVITATION_TTL_MS = 7 * DAY_MS +/** How long a `self` or `connect` link lives: it is opened in the sitting it was minted for. */ +const SESSION_LINK_TTL_MS = 60 * 60 * 1000 + +type EnrollmentRow = typeof credentialGroupEnrollment.$inferSelect + +type EnrollmentLinkPurpose = (typeof credentialGroupEnrollmentLink.$inferInsert)['purpose'] + +export function hashInvitationToken(token: string): string { + return sha256Hex(token) +} + +const UNISSUED_INVITATION_PREFIX = 'unissued:' + +/** + * A value for the legacy `invitation_token_hash` column of an enrollment created without an + * emailed link (by self-enrollment or a workflow's connection request). It contains a character + * no hex digest does, so no token ever hashes to it: the legacy branch of + * {@link liveEnrollmentLinkCondition} never matches it and link adoption skips it. It is unique + * and 64 characters long, as the column requires. + */ +export function createUnissuedInvitationTokenHash(): string { + return `${UNISSUED_INVITATION_PREFIX}${sha256Hex(generateId()).slice(UNISSUED_INVITATION_PREFIX.length)}` +} + +function isUnissuedInvitationTokenHash(value: string): boolean { + return value.startsWith(UNISSUED_INVITATION_PREFIX) +} + +/** + * Whether a link is past its expiry: the TypeScript form of the rule + * {@link liveEnrollmentLinkCondition} applies in SQL. An emailed link never expires once its + * enrollment is bound to a user; `self` and `connect` links always do. A legacy column value is an + * emailed link. + */ +function isEnrollmentLinkExpired( + link: { purpose: EnrollmentLinkPurpose; expiresAt: Date }, + bound: boolean, + now = Date.now() +): boolean { + if (bound && link.purpose === 'email') return false + return link.expiresAt.getTime() <= now +} + +/** + * The enrollment a token hash names: its link row's enrollment, else the enrollment whose legacy + * column holds it. Both lookups are uncorrelated and use a unique index, so a query filtering + * `credential_group_enrollment.id` by this value reads one row by primary key. + */ +function enrollmentIdForTokenHash(tokenHash: string): SQL { + const link = credentialGroupEnrollmentLink + const legacy = alias(credentialGroupEnrollment, 'legacy_invitation') + const linked = db + .select({ id: link.enrollmentId }) + .from(link) + .where(eq(link.tokenHash, tokenHash)) + const legacyInvitation = db + .select({ id: legacy.id }) + .from(legacy) + .where(eq(legacy.invitationTokenHash, tokenHash)) + return sql`coalesce((${linked}), (${legacyInvitation}))` +} + +/** + * Matches the enrollment row that `tokenHash` is a live link into: an unrevoked link that has not + * expired under {@link isEnrollmentLinkExpired}. A hash with no link row falls back to the + * enrollment's legacy column, an emailed invitation the pre-link app still writes during a deploy + * or rollback. The pre-link app revokes an enrollment by its status alone, leaving its links + * unrevoked, so every caller also refuses a `revoked` enrollment. + * + * The enrollment is found by primary key first ({@link enrollmentIdForTokenHash}); the liveness + * checks then run against that one row. + */ +export function liveEnrollmentLinkCondition(tokenHash: string, now = new Date()): SQL { + const link = credentialGroupEnrollmentLink + const bound = isNotNull(credentialGroupEnrollment.userId) + return sql`(${credentialGroupEnrollment.id} = ${enrollmentIdForTokenHash(tokenHash)} and (exists (select 1 from ${link} where ${and( + eq(link.tokenHash, tokenHash), + eq(link.enrollmentId, credentialGroupEnrollment.id), + isNull(link.revokedAt), + or(and(bound, eq(link.purpose, 'email')), gt(link.expiresAt, now)) + )}) or (${and( + eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), + or(bound, gt(credentialGroupEnrollment.invitationExpiresAt, now)) + )} and not exists (select 1 from ${link} where ${eq(link.tokenHash, tokenHash)}))))` +} + +/** Revokes every link into an enrollment; callers hold its lifecycle lock. */ +export async function revokeCredentialGroupEnrollmentLinks( + tx: DbTransaction, + enrollmentId: string, + now = new Date() +): Promise { + await tx + .update(credentialGroupEnrollmentLink) + .set({ revokedAt: now }) + .where( + and( + eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId), + isNull(credentialGroupEnrollmentLink.revokedAt) + ) + ) +} + +/** + * Gives the invitation in an enrollment's legacy column a link row when it has none, so that + * overwriting the column does not kill a link the released app emailed during a deploy. A revoked + * enrollment's adopted link is revoked with it. + */ +export async function adoptLegacyInvitationLink( + tx: DbTransaction, + current: EnrollmentRow, + now: Date +): Promise { + if (isUnissuedInvitationTokenHash(current.invitationTokenHash)) return + await tx + .insert(credentialGroupEnrollmentLink) + .values({ + id: generateId(), + enrollmentId: current.id, + tokenHash: current.invitationTokenHash, + purpose: 'email', + expiresAt: current.invitationExpiresAt, + revokedAt: current.status === 'revoked' || current.revokedAt ? now : null, + createdAt: current.invitedAt, + }) + .onConflictDoNothing({ target: credentialGroupEnrollmentLink.tokenHash }) +} + +/** + * Mints a link into an enrollment and returns its bearer token. The caller holds the enrollment's + * lifecycle lock and has checked the enrollment may receive one. + */ +export async function insertEnrollmentLink( + tx: DbTransaction, + input: { + enrollmentId: string + purpose: EnrollmentLinkPurpose + /** Limits the link to one account option; only `connect` links carry one. */ + optionId?: string + now: Date + /** Defaults to the purpose's lifetime. */ + expiresAt?: Date + /** Reuses a token the caller already hashed into the enrollment's legacy column. */ + token?: string + } +): Promise<{ token: string; linkId: string; expiresAt: Date }> { + const token = input.token ?? generateId() + const expiresAt = + input.expiresAt ?? + new Date( + input.now.getTime() + (input.purpose === 'email' ? INVITATION_TTL_MS : SESSION_LINK_TTL_MS) + ) + const [link] = await tx + .insert(credentialGroupEnrollmentLink) + .values({ + id: generateId(), + enrollmentId: input.enrollmentId, + tokenHash: hashInvitationToken(token), + purpose: input.purpose, + optionId: input.optionId ?? null, + expiresAt, + createdAt: input.now, + }) + .returning({ id: credentialGroupEnrollmentLink.id }) + if (!link) throw new Error('Credential group enrollment link insert returned no row') + return { token, linkId: link.id, expiresAt } +} + +/** + * The single account option a link is limited to, or null when the link (or a legacy token with + * no link row) may connect any option. + */ +export async function getCredentialGroupEnrollmentLinkOptionId( + invitationTokenHash: string +): Promise { + const [row] = await db + .select({ optionId: credentialGroupEnrollmentLink.optionId }) + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.tokenHash, invitationTokenHash)) + .limit(1) + return row?.optionId ?? null +} + +const LINK_FOCUS_REASON = 'link_focus' + +/** A link focused on one account option was used to connect a different one. */ +export class CredentialGroupLinkFocusError extends OrchestrationError { + readonly reason = LINK_FOCUS_REASON + + constructor() { + super('forbidden', 'This link only connects the account it was sent for') + this.name = 'CredentialGroupLinkFocusError' + } +} + +/** Whether `error`, or an error it wraps, is a {@link CredentialGroupLinkFocusError}. */ +export function isCredentialGroupLinkFocusError(error: unknown): boolean { + const orchestrationError = asOrchestrationError(error) + return ( + orchestrationError?.code === 'forbidden' && + 'reason' in orchestrationError && + orchestrationError.reason === LINK_FOCUS_REASON + ) +} + +interface CredentialGroupEnrollmentLinkRecord { + email: string + userId: string | null + status: EnrollmentRow['status'] + /** The link's purpose; a legacy column value is an emailed link. */ + purpose: EnrollmentLinkPurpose + /** Past its expiry under {@link isEnrollmentLinkExpired}. */ + expired: boolean + /** The enrollment itself was revoked by an admin. */ + revoked: boolean + /** This link alone was revoked (a disconnect) while the enrollment may still be live. */ + linkRevoked: boolean + groupActive: boolean + organizationName: string + inviterName: string | null + /** For a link focused on one option: that option and the group's public ID, to start over. */ + focus: { + publicId: string + option: Pick + } | null +} + +/** + * Reads the enrollment an invitation token names in any state, so the person holding it can be + * told why it stopped working. Resolves the token the way {@link liveEnrollmentLinkCondition} + * does (its link row, else the legacy column when no link row carries the hash) without the + * liveness filter. Grants no authority: live-link callers authenticate the token instead. + */ +export async function findCredentialGroupEnrollmentLinkRecord( + token: string +): Promise { + if (!token.trim() || token.length > 128) return null + const tokenHash = hashInvitationToken(token) + const link = credentialGroupEnrollmentLink + const [row] = await db + .select({ + email: credentialGroupEnrollment.email, + userId: credentialGroupEnrollment.userId, + status: credentialGroupEnrollment.status, + legacyExpiresAt: credentialGroupEnrollment.invitationExpiresAt, + revokedAt: credentialGroupEnrollment.revokedAt, + linkExpiresAt: link.expiresAt, + linkPurpose: link.purpose, + linkOptionId: link.optionId, + linkRevokedAt: link.revokedAt, + groupStatus: credentialGroup.status, + publicId: credentialGroup.publicId, + options: credentialGroup.options, + workspaceId: credentialGroup.workspaceId, + organizationId: credentialGroup.organizationId, + organizationName: organization.name, + workspaceName: workspace.name, + inviterName: user.name, + }) + .from(credentialGroupEnrollment) + .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) + .leftJoin( + link, + and(eq(link.enrollmentId, credentialGroupEnrollment.id), eq(link.tokenHash, tokenHash)) + ) + .leftJoin(workspace, eq(workspace.id, credentialGroup.workspaceId)) + .leftJoin(organization, eq(organization.id, credentialGroup.organizationId)) + .leftJoin(user, eq(user.id, credentialGroupEnrollment.createdBy)) + .where( + and( + sql`${credentialGroupEnrollment.id} = ${enrollmentIdForTokenHash(tokenHash)}`, + or(isNotNull(link.id), eq(credentialGroupEnrollment.invitationTokenHash, tokenHash)) + ) + ) + .limit(1) + if (!row || !(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(row)))) return null + const purpose = row.linkPurpose ?? 'email' + const focusOption = row.linkOptionId + ? row.options.find((option) => option.id === row.linkOptionId) + : undefined + return { + email: row.email, + userId: row.userId, + status: row.status, + purpose, + expired: isEnrollmentLinkExpired( + { purpose, expiresAt: row.linkExpiresAt ?? row.legacyExpiresAt }, + row.userId !== null + ), + revoked: row.status === 'revoked' || row.revokedAt !== null, + linkRevoked: row.linkRevokedAt !== null, + groupActive: row.groupStatus === 'active', + organizationName: row.organizationName ?? row.workspaceName ?? '', + inviterName: row.inviterName, + focus: focusOption + ? { + publicId: row.publicId, + option: { + id: focusOption.id, + provider: focusOption.provider, + status: focusOption.status, + }, + } + : null, + } +} diff --git a/apps/sim/lib/credential-groups/oauth.ts b/apps/sim/lib/credential-groups/oauth.ts index 841c6828ad7..1a6d85d513c 100644 --- a/apps/sim/lib/credential-groups/oauth.ts +++ b/apps/sim/lib/credential-groups/oauth.ts @@ -15,10 +15,10 @@ import { resourceScopeCondition } from '@/lib/core/resource-scope.server' import { resolveAccountWrite } from '@/lib/credential-groups/account-rules' import { type CredentialGroupOAuthContext, - liveEnrollmentLinkCondition, lockCredentialGroupEnrollmentLifecycle, } from '@/lib/credential-groups/enrollments' import { CREDENTIAL_GROUP_ACCOUNTS_PER_PROVIDER_LIMIT } from '@/lib/credential-groups/limits' +import { liveEnrollmentLinkCondition } from '@/lib/credential-groups/links' import type { CredentialGroupConnectionIntent } from '@/lib/credential-groups/oauth-intent' import { type CredentialGroupOAuthAttempt, diff --git a/apps/sim/lib/credential-groups/provider-adapter.ts b/apps/sim/lib/credential-groups/provider-adapter.ts index 743c908a367..09badad09a0 100644 --- a/apps/sim/lib/credential-groups/provider-adapter.ts +++ b/apps/sim/lib/credential-groups/provider-adapter.ts @@ -1,6 +1,5 @@ import { createHash } from 'node:crypto' import type { CredentialGroupOptionConfig, ManagedOAuthProviderMetadata } from '@sim/db/schema' -import { OrchestrationError } from '@/lib/core/orchestration/types' import type { CredentialGroupOAuthContext } from '@/lib/credential-groups/enrollments' import type { CredentialGroupOAuthFailure } from '@/lib/credential-groups/oauth-completion' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' @@ -95,14 +94,6 @@ export class CredentialGroupOAuthError extends Error { } } -/** A link focused on one account option was used to connect a different one. */ -export class CredentialGroupLinkFocusError extends OrchestrationError { - constructor() { - super('forbidden', 'This link only connects the account it was sent for') - this.name = 'CredentialGroupLinkFocusError' - } -} - export class CredentialGroupInvitationUnavailableError extends CredentialGroupOAuthError { constructor() { super('This account invitation was revoked.', 409) diff --git a/apps/sim/lib/credential-groups/rate-limit.ts b/apps/sim/lib/credential-groups/rate-limit.ts index 3e23755cd93..a6b67aa0284 100644 --- a/apps/sim/lib/credential-groups/rate-limit.ts +++ b/apps/sim/lib/credential-groups/rate-limit.ts @@ -37,6 +37,7 @@ type PublicCredentialGroupRateLimitScope = | 'oauth-start' | 'oauth-callback' | 'complete' + | 'connect-confirm' function rateLimitResponse(retryAfterMs: number | undefined, fallbackMs: number): NextResponse { const retryAfterSeconds = Math.ceil((retryAfterMs ?? fallbackMs) / 1000) @@ -54,7 +55,8 @@ function rateLimitResponse(retryAfterMs: number | undefined, fallbackMs: number) function configForPublicScope(scope: PublicCredentialGroupRateLimitScope): TokenBucketConfig { if (scope === 'metadata') return PUBLIC_ENROLLMENT_METADATA_RATE_LIMIT - if (scope === 'oauth-start' || scope === 'complete') return PUBLIC_OAUTH_START_RATE_LIMIT + if (scope === 'oauth-start' || scope === 'complete' || scope === 'connect-confirm') + return PUBLIC_OAUTH_START_RATE_LIMIT return PUBLIC_OAUTH_CALLBACK_RATE_LIMIT } diff --git a/apps/sim/lib/credentials/managed-mcp.ts b/apps/sim/lib/credentials/managed-mcp.ts index f6293b3d993..9c063a58e59 100644 --- a/apps/sim/lib/credentials/managed-mcp.ts +++ b/apps/sim/lib/credentials/managed-mcp.ts @@ -22,10 +22,8 @@ import { import { decryptSecret, encryptSecret } from '@/lib/core/security/encryption' import { resolveAccountWrite } from '@/lib/credential-groups/account-rules' import type { OrganizationCredentialType } from '@/lib/credential-groups/credential-types' -import { - liveEnrollmentLinkCondition, - lockCredentialGroupEnrollmentLifecycle, -} from '@/lib/credential-groups/enrollments' +import { lockCredentialGroupEnrollmentLifecycle } from '@/lib/credential-groups/enrollments' +import { liveEnrollmentLinkCondition } from '@/lib/credential-groups/links' import { getManagedMcpConnector, managedMcpAccountLimit, diff --git a/packages/db/migrations/0489_credential_group_enrollment_links.sql b/packages/db/migrations/0489_credential_group_enrollment_links.sql index 7d171d4b903..d11b9a103a7 100644 --- a/packages/db/migrations/0489_credential_group_enrollment_links.sql +++ b/packages/db/migrations/0489_credential_group_enrollment_links.sql @@ -3,6 +3,9 @@ -- writing it (mirroring the newest link), so the released app and a rollback keep resolving -- invitations through it. Every statement is idempotent: a replay after an earlier migration's -- embedded COMMIT re-runs this file in autocommit. +-- Contract, in two later migrations: first make invitation_token_hash nullable and stop writing +-- it (enrollments created without an emailed link then store null instead of an 'unissued:' +-- placeholder), then drop it with its unique index and length check. DO $$ BEGIN CREATE TYPE "public"."credential_group_enrollment_link_purpose" AS ENUM('email', 'self', 'connect'); EXCEPTION WHEN duplicate_object THEN NULL; diff --git a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts index a8558d13784..a700269ddd4 100644 --- a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts +++ b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts @@ -17,12 +17,8 @@ export class MockCredentialGroupEnrollmentError extends Error { /** * Controllable mock functions for `@/lib/credential-groups/enrollments`. * - * Every function is a bare `vi.fn()` except `mockLockCredentialGroupEnrollmentLifecycle` and - * `mockRevokeCredentialGroupEnrollmentLinks`, which resolve `undefined`, - * `mockGetCredentialGroupEnrollmentLinkOptionId`, which resolves `null` (an unfocused link), and - * `mockLiveEnrollmentLinkCondition`, which returns a `{ type: 'liveEnrollmentLink', tokenHash }` - * condition node a test can find in a WHERE tree, and `mockCreateUnissuedInvitationTokenHash`, - * which returns a fixed unissued placeholder. + * Every function is a bare `vi.fn()` except `mockLockCredentialGroupEnrollmentLifecycle`, which + * resolves `undefined`. Link storage lives in `@/lib/credential-groups/links`. * * @example * ```ts @@ -36,13 +32,6 @@ export const credentialGroupsEnrollmentsMockFns = { mockLockCredentialGroupEnrollmentLifecycle: vi.fn( async (_executor: unknown, _enrollmentId: string): Promise => {} ), - mockLiveEnrollmentLinkCondition: vi.fn((tokenHash: string) => ({ - type: 'liveEnrollmentLink', - tokenHash, - })), - mockRevokeCredentialGroupEnrollmentLinks: vi.fn( - async (_executor: unknown, _enrollmentId: string, _now?: Date): Promise => {} - ), mockAuthenticatePublicCredentialGroupEnrollment: vi.fn(), mockBindCredentialGroupEnrollmentUser: vi.fn(), mockListCredentialGroupEnrollments: vi.fn(), @@ -59,13 +48,6 @@ export const credentialGroupsEnrollmentsMockFns = { mockGetCredentialGroupOAuthContextForEnrollment: vi.fn(), mockGetAuthorizedCredentialGroupMcpOAuthContext: vi.fn(), mockGetCredentialGroupMcpOAuthContextForEnrollment: vi.fn(), - mockGetCredentialGroupEnrollmentLinkOptionId: vi.fn( - async (_invitationTokenHash: string): Promise => null - ), - mockIssueCredentialGroupConnectLink: vi.fn(), - mockLoadCredentialGroupConnectSubject: vi.fn(), - mockFindCredentialGroupEnrollmentLinkRecord: vi.fn(), - mockCreateUnissuedInvitationTokenHash: vi.fn((): string => `unissued:${'0'.repeat(55)}`), } const fns = credentialGroupsEnrollmentsMockFns @@ -81,8 +63,6 @@ const fns = credentialGroupsEnrollmentsMockFns export const credentialGroupsEnrollmentsMock = { CredentialGroupEnrollmentError: MockCredentialGroupEnrollmentError, lockCredentialGroupEnrollmentLifecycle: fns.mockLockCredentialGroupEnrollmentLifecycle, - liveEnrollmentLinkCondition: fns.mockLiveEnrollmentLinkCondition, - revokeCredentialGroupEnrollmentLinks: fns.mockRevokeCredentialGroupEnrollmentLinks, authenticatePublicCredentialGroupEnrollment: fns.mockAuthenticatePublicCredentialGroupEnrollment, bindCredentialGroupEnrollmentUser: fns.mockBindCredentialGroupEnrollmentUser, listCredentialGroupEnrollments: fns.mockListCredentialGroupEnrollments, @@ -101,9 +81,4 @@ export const credentialGroupsEnrollmentsMock = { getAuthorizedCredentialGroupMcpOAuthContext: fns.mockGetAuthorizedCredentialGroupMcpOAuthContext, getCredentialGroupMcpOAuthContextForEnrollment: fns.mockGetCredentialGroupMcpOAuthContextForEnrollment, - getCredentialGroupEnrollmentLinkOptionId: fns.mockGetCredentialGroupEnrollmentLinkOptionId, - issueCredentialGroupConnectLink: fns.mockIssueCredentialGroupConnectLink, - loadCredentialGroupConnectSubject: fns.mockLoadCredentialGroupConnectSubject, - findCredentialGroupEnrollmentLinkRecord: fns.mockFindCredentialGroupEnrollmentLinkRecord, - createUnissuedInvitationTokenHash: fns.mockCreateUnissuedInvitationTokenHash, } From 17c8484b6038cf1e5d1813b87db6544c89c44a91 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 15:27:12 -0600 Subject: [PATCH 11/26] refactor(credential-groups): prune connect history from its own cron job The connection-request log and expired session links are pruned by an hourly cleanup-credential-group-links job (background task, cron route, Helm, Compose crontab and self-hosting docs), following cleanup-oauth-tokens, instead of from the outbox processor, whose changes are reverted. --- .../docs/platform/enterprise/self-hosted.mdx | 1 + .../platform/self-hosting/background-jobs.mdx | 1 + .../cleanup-credential-group-links/route.ts | 31 +++++++++++++++++++ ...nup-credential-group-links.integration.ts} | 6 ++-- .../cleanup-credential-group-links.ts} | 6 ++-- apps/sim/lib/core/outbox/processor.test.ts | 9 ------ apps/sim/lib/core/outbox/processor.ts | 21 +------------ docker/crontab | 3 ++ helm/sim/values.yaml | 11 +++++++ scripts/check-api-validation-contracts.ts | 1 + 10 files changed, 55 insertions(+), 35 deletions(-) create mode 100644 apps/sim/app/api/cron/cleanup-credential-group-links/route.ts rename apps/sim/{lib/credential-groups/__integration__/retention.integration.ts => background/cleanup-credential-group-links.integration.ts} (95%) rename apps/sim/{lib/credential-groups/retention.ts => background/cleanup-credential-group-links.ts} (95%) diff --git a/apps/docs/content/docs/platform/enterprise/self-hosted.mdx b/apps/docs/content/docs/platform/enterprise/self-hosted.mdx index 9649b2a1141..4aed1fa7a96 100644 --- a/apps/docs/content/docs/platform/enterprise/self-hosted.mdx +++ b/apps/docs/content/docs/platform/enterprise/self-hosted.mdx @@ -214,6 +214,7 @@ Persist the same value as `CRON_SECRET` on the application and its scheduler. Ea | Retention: Chat tasks | `GET /api/cron/cleanup-tasks` | Daily | No | | Retention: file versions | `GET /api/cron/cleanup-file-versions` | Daily | No | | OAuth token cleanup | `GET /api/cron/cleanup-oauth-tokens` | Hourly | Yes | +| Credential Group link cleanup | `GET /api/cron/cleanup-credential-group-links` | Hourly | Yes | | Workspace source staging cleanup | `GET /api/cron/cleanup-source-staging` | Hourly | Yes | | Retention: activity history | `GET /api/cron/cleanup-activity-history` | Daily | Yes | diff --git a/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx b/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx index 783368540bc..4d121822252 100644 --- a/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx +++ b/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx @@ -182,6 +182,7 @@ Create a workflow with a Schedule trigger set to every minute, deploy it, and wa | Table row TTL cleanup | `/api/cron/cleanup-table-row-ttl` | `*/15 * * * *` | Deletes table rows whose TTL column has expired | | Stale execution cleanup | `/api/cron/cleanup-stale-executions` | `*/30 * * * *` | Fails runs whose worker died without finishing — workflow executions, background jobs, table jobs and table runs — so they stop showing as running | | OAuth token cleanup | `/api/cron/cleanup-oauth-tokens` | `0 * * * *` | Deletes access and refresh tokens after the retention tail | +| Credential Group link cleanup | `/api/cron/cleanup-credential-group-links` | `20 * * * *` | Deletes workflow connection-request log rows after two days and connect or self-enrollment links a day after they expire | | Activity history cleanup | `/api/cron/cleanup-activity-history` | `45 4 * * *` | Deletes organization adoption history past its retention: daily member activity, daily Search integration counts and Search MCP call metadata after 400 days | | Workspace source staging cleanup | `/api/cron/cleanup-source-staging` | `30 * * * *` | Deletes binary files staged for a workspace source apply a day after they were last staged | | SCIM reconciliation | `/api/cron/scim-reconcile` | `17 * * * *` | Re-applies directory group mappings | diff --git a/apps/sim/app/api/cron/cleanup-credential-group-links/route.ts b/apps/sim/app/api/cron/cleanup-credential-group-links/route.ts new file mode 100644 index 00000000000..84e193250ec --- /dev/null +++ b/apps/sim/app/api/cron/cleanup-credential-group-links/route.ts @@ -0,0 +1,31 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { type NextRequest, NextResponse } from 'next/server' +import { verifyCronAuth } from '@/lib/auth/internal' +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' +import { runCleanupCredentialGroupLinks } from '@/background/cleanup-credential-group-links' + +export const dynamic = 'force-dynamic' +export const maxDuration = 60 + +const logger = createLogger('CleanupCredentialGroupLinksAPI') + +/** + * Retention sweep for the Credential Group connect flow: the workflow connection-request log + * past the daily cap's window, and connect-page and self-enrollment links a day past expiry. + */ +export const GET = withRouteHandler(async (request: NextRequest) => { + const authError = verifyCronAuth(request, 'Credential group link cleanup') + if (authError) return authError + + try { + const result = await runCleanupCredentialGroupLinks() + return NextResponse.json({ success: true, ...result }) + } catch (error) { + logger.error('Failed to clean up credential group links', { error }) + return NextResponse.json( + { error: getErrorMessage(error, 'Failed to clean up credential group links') }, + { status: 500 } + ) + } +}) diff --git a/apps/sim/lib/credential-groups/__integration__/retention.integration.ts b/apps/sim/background/cleanup-credential-group-links.integration.ts similarity index 95% rename from apps/sim/lib/credential-groups/__integration__/retention.integration.ts rename to apps/sim/background/cleanup-credential-group-links.integration.ts index 99bb33795a5..f5ddbe58ac3 100644 --- a/apps/sim/lib/credential-groups/__integration__/retention.integration.ts +++ b/apps/sim/background/cleanup-credential-group-links.integration.ts @@ -17,7 +17,7 @@ import { sha256Hex } from '@sim/security/hash' import { generateId } from '@sim/utils/id' import { eq, inArray } from 'drizzle-orm' import { afterAll, describe, expect, it } from 'vitest' -import { pruneCredentialGroupConnectHistory } from '@/lib/credential-groups/retention' +import { runCleanupCredentialGroupLinks } from '@/background/cleanup-credential-group-links' const HOUR_MS = 60 * 60 * 1000 const DAY_MS = 24 * HOUR_MS @@ -80,7 +80,7 @@ afterAll(async () => { await db.delete(organization).where(inArray(organization.id, organizationIds)) }) -describe('pruneCredentialGroupConnectHistory', () => { +describe('runCleanupCredentialGroupLinks', () => { it('deletes request log rows past two days and session links a day past expiry, nothing else', async () => { const legacyTokenHash = sha256Hex(generateId()) const { groupId, enrollmentId } = await createEnrollment(legacyTokenHash) @@ -99,7 +99,7 @@ describe('pruneCredentialGroupConnectHistory', () => { legacyTokenHash ) - await pruneCredentialGroupConnectHistory(new Date(now)) + await runCleanupCredentialGroupLinks(new Date(now)) const requests = await db .select({ id: credentialGroupConnectionRequest.id }) diff --git a/apps/sim/lib/credential-groups/retention.ts b/apps/sim/background/cleanup-credential-group-links.ts similarity index 95% rename from apps/sim/lib/credential-groups/retention.ts rename to apps/sim/background/cleanup-credential-group-links.ts index c66104155c8..ace9fe20109 100644 --- a/apps/sim/lib/credential-groups/retention.ts +++ b/apps/sim/background/cleanup-credential-group-links.ts @@ -6,10 +6,10 @@ import { } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { and, asc, eq, inArray, lt, sql } from 'drizzle-orm' +import { DAY_MS } from '@/lib/credential-groups/limits' -const logger = createLogger('CredentialGroupRetention') +const logger = createLogger('CleanupCredentialGroupLinks') -const DAY_MS = 24 * 60 * 60 * 1000 /** The daily cap reads one day of the request log; a second day is slack for clock skew. */ const CONNECTION_REQUEST_RETENTION_MS = 2 * DAY_MS /** Session links expire after an hour; a day past that they only explain an old link. */ @@ -36,7 +36,7 @@ async function drain(deleteBatch: () => Promise): Promise { * too, since deleting its row would let that token resolve through the column instead. Each * batch takes its rows oldest first, skipping rows another run has locked. */ -export async function pruneCredentialGroupConnectHistory( +export async function runCleanupCredentialGroupLinks( now = new Date() ): Promise<{ connectionRequests: number; sessionLinks: number }> { const requestCutoff = new Date(now.getTime() - CONNECTION_REQUEST_RETENTION_MS) diff --git a/apps/sim/lib/core/outbox/processor.test.ts b/apps/sim/lib/core/outbox/processor.test.ts index ab696f286f7..98913f0a8e0 100644 --- a/apps/sim/lib/core/outbox/processor.test.ts +++ b/apps/sim/lib/core/outbox/processor.test.ts @@ -5,13 +5,9 @@ const mocks = vi.hoisted(() => ({ recover: vi.fn(), reap: vi.fn(), prune: vi.fn(), - pruneCredentialGroups: vi.fn(), })) vi.mock('@/lib/core/outbox/service', () => outboxServiceMock) vi.mock('@/lib/core/outbox/retention', () => ({ pruneCompletedOutboxEvents: mocks.prune })) -vi.mock('@/lib/credential-groups/retention', () => ({ - pruneCredentialGroupConnectHistory: mocks.pruneCredentialGroups, -})) vi.mock('@/lib/knowledge/documents/processing-recovery', () => ({ recoverKnowledgeDocumentProcessing: mocks.recover, })) @@ -44,7 +40,6 @@ describe('outbox processor recovery', () => { mocks.recover.mockResolvedValue(2) mocks.reap.mockResolvedValue(3) mocks.prune.mockResolvedValue(4) - mocks.pruneCredentialGroups.mockResolvedValue({ connectionRequests: 0, sessionLinks: 0 }) }) afterEach(() => vi.useRealTimers()) @@ -55,7 +50,6 @@ describe('outbox processor recovery', () => { recoveredDocuments: 0, reapedBackgroundWork: 3, prunedEvents: 4, - prunedCredentialGroupRows: 0, }) }) @@ -66,7 +60,6 @@ describe('outbox processor recovery', () => { recoveredDocuments: 2, reapedBackgroundWork: 0, prunedEvents: 4, - prunedCredentialGroupRows: 0, }) }) @@ -77,7 +70,6 @@ describe('outbox processor recovery', () => { recoveredDocuments: 2, reapedBackgroundWork: 3, prunedEvents: 0, - prunedCredentialGroupRows: 0, }) }) @@ -91,7 +83,6 @@ describe('outbox processor recovery', () => { recoveredDocuments: 0, reapedBackgroundWork: 3, prunedEvents: 4, - prunedCredentialGroupRows: 0, }) expect(mocks.recover).not.toHaveBeenCalled() }) diff --git a/apps/sim/lib/core/outbox/processor.ts b/apps/sim/lib/core/outbox/processor.ts index 99a035e5606..240e78a7502 100644 --- a/apps/sim/lib/core/outbox/processor.ts +++ b/apps/sim/lib/core/outbox/processor.ts @@ -9,7 +9,6 @@ import { OUTBOX_HANDLER_GROUPS } from '@/lib/core/outbox/handlers' import { pruneCompletedOutboxEvents } from '@/lib/core/outbox/retention' import { type ProcessOutboxResult, processOutboxEvents } from '@/lib/core/outbox/service' import { DeadlineExceededError } from '@/lib/core/utils/deadline' -import { pruneCredentialGroupConnectHistory } from '@/lib/credential-groups/retention' import { getConnectorFailureDiagnostic } from '@/lib/knowledge/connectors/error' import { recoverKnowledgeDocumentProcessing } from '@/lib/knowledge/documents/processing-recovery' import { reapStaleBackgroundWork } from '@/ee/workspace-forking/lib/background-work/store' @@ -21,7 +20,6 @@ export interface OutboxProcessorResult { recoveredDocuments: number reapedBackgroundWork: number prunedEvents: number - prunedCredentialGroupRows: number } /** Processes one bounded batch and its recovery work in either the worker or self-hosted cron. */ @@ -65,22 +63,11 @@ export async function runOutboxProcessor(): Promise { logger.error('Completed outbox pruning failed', { error: toError(error).message }) } - let prunedCredentialGroupRows = 0 - try { - const pruned = await pruneCredentialGroupConnectHistory() - prunedCredentialGroupRows = pruned.connectionRequests + pruned.sessionLinks - } catch (error) { - logger.error('Credential group connect history pruning failed', { - error: toError(error).message, - }) - } - const summary = { ...result, reapedBackgroundWork, recoveredDocuments, prunedEvents, - prunedCredentialGroupRows, durationMs: Date.now() - startedAt, } /** Fail the run so a broken handler module stays as visible as the crash its static import caused. */ @@ -90,11 +77,5 @@ export async function runOutboxProcessor(): Promise { throw new Error(message) } logger.info('Outbox processing completed', summary) - return { - result, - reapedBackgroundWork, - recoveredDocuments, - prunedEvents, - prunedCredentialGroupRows, - } + return { result, reapedBackgroundWork, recoveredDocuments, prunedEvents } } diff --git a/docker/crontab b/docker/crontab index 47533fddb9c..fc38796f71c 100644 --- a/docker/crontab +++ b/docker/crontab @@ -68,6 +68,9 @@ SHELL=/bin/sh # Deletes OAuth token rows after the retention tail 0 * * * * curl -fsS -m 120 -o /dev/null -H "Authorization: Bearer $CRON_SECRET" "$SIM_URL/api/cron/cleanup-oauth-tokens" +# Deletes Credential Group connection-request log rows and expired session links +20 * * * * curl -fsS -m 60 -o /dev/null -H "Authorization: Bearer $CRON_SECRET" "$SIM_URL/api/cron/cleanup-credential-group-links" + # Deletes organization adoption history past its retention 45 4 * * * curl -fsS -m 120 -o /dev/null -H "Authorization: Bearer $CRON_SECRET" "$SIM_URL/api/cron/cleanup-activity-history" diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index df1e14a186b..d78f5c66eb8 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -1662,6 +1662,17 @@ cronjobs: successfulJobsHistoryLimit: 3 failedJobsHistoryLimit: 1 + # Deletes the Credential Group connect flow's short-lived rows: the workflow connection + # request log past the daily cap's window, and session links a day past expiry. + cleanupCredentialGroupLinks: + enabled: true + name: cleanup-credential-group-links + schedule: "20 * * * *" + path: "/api/cron/cleanup-credential-group-links" + concurrencyPolicy: Forbid + successfulJobsHistoryLimit: 3 + failedJobsHistoryLimit: 1 + # Deletes organization adoption history past its retention (daily member activity and # Search MCP call metadata after 400 days). cleanupActivityHistory: diff --git a/scripts/check-api-validation-contracts.ts b/scripts/check-api-validation-contracts.ts index 48e19d17146..532b0797e16 100644 --- a/scripts/check-api-validation-contracts.ts +++ b/scripts/check-api-validation-contracts.ts @@ -114,6 +114,7 @@ const INDIRECT_ZOD_ROUTES = new Set([ 'apps/sim/app/api/cron/cleanup-sandbox-images/route.ts', 'apps/sim/app/api/cron/cleanup-session-sandboxes/route.ts', 'apps/sim/app/api/cron/cleanup-oauth-tokens/route.ts', + 'apps/sim/app/api/cron/cleanup-credential-group-links/route.ts', 'apps/sim/app/api/cron/cleanup-activity-history/route.ts', 'apps/sim/app/api/cron/cleanup-source-staging/route.ts', 'apps/sim/app/api/cron/renew-subscriptions/route.ts', From 425db45ceff2e62cae22f949629797a9c09b5aae Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 15:27:14 -0600 Subject: [PATCH 12/26] fix(credential-groups): safer connection request emails and a Slack return for workflows - The email subject names only the organization and integration; the body shows the workflow name with control and formatting characters removed, cut to 60 characters. - The email handler skips an enrollment an admin has since reinvited, records a failed delivery as delivery_failed like an admin invitation, writes only while the enrollment is as the request left it, and never throws after the provider accepted the email, so it is not sent twice. - The Credential block's connection operations take a Return to input (none or Slack) that the connect URL carries as return=slack. - Saving the request policy uses the contract-parsed policy instead of parsing it again. --- apps/sim/blocks/blocks/credential.ts | 16 ++ apps/sim/components/emails/subjects.ts | 13 +- .../executor/handlers/credential/handler.ts | 10 + ...orkflow-connection-requests.integration.ts | 194 +++++++++++++++++- .../organization-connection-requests.ts | 19 +- .../connection-request-email.ts | 87 ++++++-- 6 files changed, 293 insertions(+), 46 deletions(-) diff --git a/apps/sim/blocks/blocks/credential.ts b/apps/sim/blocks/blocks/credential.ts index e8f7a5531e2..29a7dc426b1 100644 --- a/apps/sim/blocks/blocks/credential.ts +++ b/apps/sim/blocks/blocks/credential.ts @@ -163,6 +163,17 @@ export const CredentialBlock: BlockConfig = { ], }, }, + { + id: 'connectReturnTo', + title: 'Return to', + type: 'dropdown', + options: [ + { label: 'Nowhere', id: 'none' }, + { label: 'Slack', id: 'slack' }, + ], + value: () => 'none', + condition: { field: 'operation', value: CONNECTION_OPERATIONS }, + }, { id: 'limit', title: 'Limit', @@ -198,6 +209,11 @@ export const CredentialBlock: BlockConfig = { type: 'json', description: 'Optional organization OAuth provider IDs', }, + connectReturnTo: { + type: 'string', + description: + 'Where connectUrl offers to send the person once connected: none, or slack to open the Slack app', + }, mcpProvider: { type: 'string', description: 'Managed MCP provider ID' }, limit: { type: 'number', description: 'Page size from 1 to 100' }, cursor: { type: 'string', description: 'Previous page nextCursor' }, diff --git a/apps/sim/components/emails/subjects.ts b/apps/sim/components/emails/subjects.ts index 0d44c3db1a5..418f89d08e2 100644 --- a/apps/sim/components/emails/subjects.ts +++ b/apps/sim/components/emails/subjects.ts @@ -133,18 +133,21 @@ export function getOtpSubject(resourceLabel: string): string { } /** - * Names the workspace so an external recipient can identify the request, and the - * inviter when there is one — a workflow-issued invitation has no person to name. + * Names only the organization and the integration. The requesting workflow's name is chosen by + * whoever built the workflow, so it never appears in a subject line, where it could pose as a + * message from someone else; the body shows it, cleaned and shortened. */ -/** Names the requesting workflow and organization; never text a workflow passed at run time. */ export function getCredentialGroupConnectionRequestSubject(input: { - workflowName: string organizationName: string providerName: string }): string { - return `${input.workflowName} in ${input.organizationName} asked you to connect ${input.providerName}` + return `${input.organizationName} asked you to connect ${input.providerName}` } +/** + * Names the workspace so an external recipient can identify the request, and the + * inviter when there is one — a workflow-issued invitation has no person to name. + */ export function getCredentialGroupInvitationSubject( inviterName: string | undefined, workspaceName: string diff --git a/apps/sim/executor/handlers/credential/handler.ts b/apps/sim/executor/handlers/credential/handler.ts index 77b52ceea86..d934472a75d 100644 --- a/apps/sim/executor/handlers/credential/handler.ts +++ b/apps/sim/executor/handlers/credential/handler.ts @@ -56,6 +56,14 @@ function parseOptionalString(value: unknown, label: string): string | undefined return value.trim() } +/** The connect link's return destination: `slack`, or none when blank or `none`. */ +function parseConnectReturnTo(value: unknown): { returnTo?: 'slack' } { + const returnTo = parseOptionalString(value, 'Return to') + if (returnTo === undefined || returnTo === 'none') return {} + if (returnTo === 'slack') return { returnTo } + throw new Error('Return to must be none or slack') +} + function requireString(value: unknown, label: string): string { const parsed = parseOptionalString(value, label) if (!parsed) throw new Error(`${label} is required`) @@ -136,6 +144,7 @@ export class CredentialBlockHandler implements BlockHandler { workspaceId: ctx.workspaceId, email: requireString(inputs.email, 'Email'), providerId: requireString(inputs.organizationProvider, 'Provider'), + ...parseConnectReturnTo(inputs.connectReturnTo), }, }) case 'request_connection': { @@ -145,6 +154,7 @@ export class CredentialBlockHandler implements BlockHandler { workspaceId: ctx.workspaceId, email: requireString(inputs.email, 'Email'), providerId: requireString(inputs.organizationProvider, 'Provider'), + ...parseConnectReturnTo(inputs.connectReturnTo), }, }) return { requested, connectUrl } diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index 7d523a45b7a..b5ea07d8feb 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -11,8 +11,11 @@ * error differing by target; a `+` alias slipping in; reminders beyond the per-enrollment cap or * after 30 days; a revocation racing a reminder still emailing; an admin unable to turn requests * off after their choices went stale; saving either the request policy or Access changing the - * other; a request's placeholder invitation being adopted as a link by a later admin invite; the - * emailed link not opening the requested enrollment on the connect page. + * other; a request's placeholder invitation being adopted as a link by a later admin invite; an + * admin's reinvitation leaving the workflow's reminders running; the emailed link not opening the + * requested enrollment on the connect page; the requesting workflow's name reaching the email + * subject, or reaching the body uncleaned; a failed delivery not showing as Email failed; and an + * email still going out, or its outcome overwriting the enrollment, after an admin reinvited. */ import type { WorkflowExecutionDelegatedPrincipal } from '@sim/auth/principal' import { db } from '@sim/db' @@ -28,6 +31,7 @@ import { outboxEvent, resourcePolicy, user, + workflow, workspace, } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' @@ -36,10 +40,11 @@ import { createSessionPrincipal } from '@sim/testing/factories/principal.factory import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' import { and, eq, inArray, isNotNull, sql } from 'drizzle-orm' -import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { OrchestrationError } from '@/lib/core/orchestration/types' +import { enqueueOutboxEvent, processOutboxEventById } from '@/lib/core/outbox/service' import { CREDENTIAL_GROUP_DELEGATION_AUDIENCE } from '@/lib/credential-groups/application/authorization' -import { resolveCredentialGroupConnectTarget } from '@/lib/credential-groups/application/connect-target' +import { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' import { getOrganizationAccountConnectionStatus, requestOrganizationAccountConnection, @@ -51,7 +56,11 @@ import { } from '@/lib/credential-groups/application/organization-connection-requests' import { buildOrganizationAccountAccessPolicy } from '@/lib/credential-groups/application/workspace-access-policy' import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' -import { CONNECTION_REQUEST_EMAIL_EVENT } from '@/lib/credential-groups/connection-request-event' +import { credentialGroupConnectionRequestOutboxHandlers } from '@/lib/credential-groups/connection-request-email' +import { + CONNECTION_REQUEST_EMAIL_EVENT, + type ConnectionRequestEmailPayload, +} from '@/lib/credential-groups/connection-request-event' import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' import { authenticatePublicCredentialGroupEnrollment, @@ -69,14 +78,34 @@ vi.mock('@/lib/credential-groups/scoped-availability', () => ({ isScopedCredentialGroupsAvailable: async () => true, })) -/** Delivery is outside this suite: the enqueued outbox event is what a request controls. */ +/** + * The mail transport and template renderer are faked: requests are judged by the outbox events + * they enqueue, and the email handler by what it would have sent and how it records the outcome. + */ +const mail = vi.hoisted(() => ({ + sent: [] as Array<{ to: string; subject: string }>, + rendered: [] as Array<{ recipientEmail: string; workflowRequest?: { workflowName: string } }>, + failWith: null as string | null, +})) + vi.mock('@/lib/messaging/email/mailer', () => ({ - sendEmail: async () => ({ success: true, message: 'sent' }), + sendEmail: async (input: { to: string; subject: string }) => { + mail.sent.push({ to: input.to, subject: input.subject }) + return mail.failWith + ? { success: false, message: mail.failWith } + : { success: true, message: 'sent' } + }, })) vi.mock('@/components/emails/credential-groups/render', () => ({ - renderCredentialGroupInvitationEmail: async (input: { invitationLink: string }) => - input.invitationLink, + renderCredentialGroupInvitationEmail: async (input: { + invitationLink: string + recipientEmail: string + workflowRequest?: { workflowName: string } + }) => { + mail.rendered.push(input) + return input.invitationLink + }, })) vi.mock('@/lib/credential-groups/provider-registry', async (importOriginal) => { @@ -680,6 +709,34 @@ describe('connection request emails', () => { expect(await emailEvents(enrollment.id)).toHaveLength(1) }) + it("hands a requested enrollment to the admin who invites it, ending the workflow's reminders", async () => { + const email = address('reminded-then-invited') + await request(orgA, email) + await ageRequests(orgA, email) + await request(orgA, email) + const [requested] = await enrollmentsFor(orgA, email) + if (!requested) throw new Error('Request created no enrollment') + expect(requested.connectionRequestReminders).toBe(1) + + await inviteCredentialGroupEnrollment( + { kind: 'organization', organizationId: orgA.organizationId }, + orgA.groupId, + orgA.adminId, + 'Admin', + email + ) + const [invited] = await enrollmentsFor(orgA, email) + expect(invited).toMatchObject({ + requestedByWorkflowId: null, + connectionRequestReminders: 0, + createdBy: orgA.adminId, + }) + + await ageRequests(orgA, email) + await request(orgA, email) + expect(await emailEvents(requested.id)).toHaveLength(2) + }) + it('sends nothing when a revocation commits while the reminder is being claimed', async () => { const email = address('revoke-race') await request(orgA, email) @@ -713,6 +770,123 @@ describe('connection request emails', () => { }) }) +describe('connection request email delivery', () => { + const namedWorkflowId = generateId() + + beforeAll(async () => { + const now = new Date() + await db.insert(workflow).values({ + id: namedWorkflowId, + userId: ownerId, + workspaceId: orgA.workspaceId, + name: `\u202Eexe.pdf\u0007 Payroll\n\n bot ${'x'.repeat(80)}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + }) + + beforeEach(async () => { + await setRequestPolicy(orgA, OPEN_POLICY) + mail.sent.length = 0 + mail.rendered.length = 0 + mail.failWith = null + }) + + afterEach(() => { + mail.failWith = null + }) + + /** A request that enqueued no email, so the test delivers it explicitly. */ + async function requestedEnrollment(label: string) { + const email = address(label) + await request(orgA, email) + const [enrollment] = await enrollmentsFor(orgA, email) + if (!enrollment) throw new Error('Request created no enrollment') + return { email, enrollmentId: enrollment.id } + } + + async function deliver(enrollmentId: string) { + const eventId = await enqueueOutboxEvent( + db, + CONNECTION_REQUEST_EMAIL_EVENT, + { + enrollmentId, + workspaceId: orgA.workspaceId, + workflowId: namedWorkflowId, + providerName: DRIVE.label, + connectUrl: buildCredentialGroupConnectUrl({ publicId: orgA.publicId, provider: DRIVE_ID }), + }, + { maxAttempts: 3 } + ) + await processOutboxEventById(eventId, credentialGroupConnectionRequestOutboxHandlers) + } + + const enrollmentRow = async (enrollmentId: string) => { + const [row] = await db + .select() + .from(credentialGroupEnrollment) + .where(eq(credentialGroupEnrollment.id, enrollmentId)) + if (!row) throw new Error('Enrollment is missing') + return row + } + + it('keeps the workflow name out of the subject and shows it cleaned and shortened', async () => { + const { email, enrollmentId } = await requestedEnrollment('named-request') + + await deliver(enrollmentId) + + expect(mail.sent).toEqual([ + { to: email, subject: 'Connection requests fixture asked you to connect Google Drive' }, + ]) + const workflowName = mail.rendered.at(-1)?.workflowRequest?.workflowName ?? '' + expect(workflowName.startsWith('exe.pdf Payroll bot xxx')).toBe(true) + expect(workflowName).not.toMatch(/[\u202E\u0007\n]/) + expect(workflowName.length).toBeLessThanOrEqual(61) + }) + + it('records a failed delivery as Email failed, and a later successful one clears it', async () => { + const { enrollmentId } = await requestedEnrollment('bounced-request') + + mail.failWith = 'Mailbox unavailable' + await deliver(enrollmentId) + expect(await enrollmentRow(enrollmentId)).toMatchObject({ + status: 'delivery_failed', + lastDeliveryError: 'Mailbox unavailable', + }) + + mail.failWith = null + await deliver(enrollmentId) + expect(await enrollmentRow(enrollmentId)).toMatchObject({ + status: 'invited', + lastDeliveryError: null, + }) + }) + + it('sends nothing, and records nothing, once an admin has reinvited the person', async () => { + const { email, enrollmentId } = await requestedEnrollment('reinvited-request') + await inviteCredentialGroupEnrollment( + { kind: 'organization', organizationId: orgA.organizationId }, + orgA.groupId, + orgA.adminId, + 'Admin', + email + ) + const invited = await enrollmentRow(enrollmentId) + mail.sent.length = 0 + + mail.failWith = 'Mailbox unavailable' + await deliver(enrollmentId) + + expect(mail.sent).toEqual([]) + expect(await enrollmentRow(enrollmentId)).toMatchObject({ + status: invited.status, + lastDeliveryError: invited.lastDeliveryError, + sentAt: invited.sentAt, + }) + }) +}) + describe('a requested enrollment on the connect page', () => { beforeEach(async () => { await setRequestPolicy(orgA, { ...OPEN_POLICY, sendEmail: true }) @@ -746,7 +920,7 @@ describe('a requested enrollment on the connect page', () => { createdAt: new Date(), updatedAt: new Date(), }) - const target = await resolveCredentialGroupConnectTarget.execute({ + const target = await startCredentialGroupConnect.execute({ principal: createSessionPrincipal({ userId }), input: { publicId: orgA.publicId, provider: DRIVE_ID }, }) diff --git a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts index 67dfec53b24..6acfc9661e5 100644 --- a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts @@ -9,11 +9,7 @@ import { listOrganizationAccountWorkspaceIds, organizationAccountAccessPolicyCodec, } from '@/lib/credential-groups/application/workspace-access-policy' -import { - type ConnectionRequestPolicy, - type ConnectionRequestPolicyInput, - connectionRequestPolicySchema, -} from '@/lib/credential-groups/connection-request-policy' +import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' import { ConnectionRequestPolicyConflictError, loadConnectionRequestPolicy, @@ -129,7 +125,8 @@ export const getOrganizationConnectionRequestPolicy = defineOrganizationAccounts }) /** - * Saves the admin's policy. Turning requests on requires every chosen workspace to be on the + * Saves the admin's policy, as the route contract parsed it (`connectionRequestPolicySchema`: + * normalized lists, and non-empty ones when turned on). Turning requests on requires every chosen workspace to be on the * Access tab and every integration to be active; turning them off never fails on choices that * went stale, which are pruned instead. */ @@ -139,21 +136,15 @@ export const updateOrganizationConnectionRequestPolicy = defineOrganizationAccou input, context, }: { - input: { organizationId: string; revision: number; policy: ConnectionRequestPolicyInput } + input: { organizationId: string; revision: number; policy: ConnectionRequestPolicy } context: OrganizationMembershipContext }) { - const parsed = connectionRequestPolicySchema.safeParse(input.policy) - if (!parsed.success) - throw new OrchestrationError( - 'validation', - parsed.error.issues[0]?.message ?? 'Connection request settings are invalid' - ) const { group, workspaces, providers } = await loadConnectionRequestState( context.organizationId ) const workspaceIds = new Set(workspaces.map((entry) => entry.id)) const providerIds = new Set(providers.map((provider) => provider.id)) - const next = parsed.data + const next = input.policy if (next.enabled) { if (next.providers.some((provider) => !providerIds.has(provider))) throw new OrchestrationError( diff --git a/apps/sim/lib/credential-groups/connection-request-email.ts b/apps/sim/lib/credential-groups/connection-request-email.ts index f916994995b..0e9cdd009f1 100644 --- a/apps/sim/lib/credential-groups/connection-request-email.ts +++ b/apps/sim/lib/credential-groups/connection-request-email.ts @@ -1,9 +1,10 @@ import { db } from '@sim/db' import { credentialGroup, credentialGroupEnrollment, organization, workflow } from '@sim/db/schema' import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' import { isRecordLike } from '@sim/utils/object' -import { truncate } from '@sim/utils/string' -import { and, eq, isNull } from 'drizzle-orm' +import { truncate, truncateAtCodePoint } from '@sim/utils/string' +import { and, eq, inArray, isNotNull, isNull, type SQL } from 'drizzle-orm' import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' import { getCredentialGroupConnectionRequestSubject } from '@/components/emails/subjects' import type { OutboxHandler } from '@/lib/core/outbox/service' @@ -16,6 +17,8 @@ import { getFromEmailAddress } from '@/lib/messaging/email/utils' const logger = createLogger('CredentialGroupConnectionRequestEmail') +const WORKFLOW_NAME_MAX_LENGTH = 60 + function parsePayload(payload: unknown): ConnectionRequestEmailPayload { if ( !isRecordLike(payload) || @@ -35,17 +38,50 @@ function parsePayload(payload: unknown): ConnectionRequestEmailPayload { } } +/** + * The requesting workflow's name as the email body shows it. The name is whatever its builder + * typed, so control and invisible formatting characters (which could reorder or hide text) are + * removed, whitespace is collapsed, and it is cut to {@link WORKFLOW_NAME_MAX_LENGTH} characters. + */ +function connectionRequestWorkflowName(name: string | undefined): string { + const cleaned = (name ?? '') + .replace(/[\p{Cc}\p{Cf}]/gu, '') + .replace(/\s+/g, ' ') + .trim() + return cleaned ? truncateAtCodePoint(cleaned, WORKFLOW_NAME_MAX_LENGTH, '…') : 'A workflow' +} + +/** + * The enrollment as the request left it: still unbound, still the workflow's request (an + * admin's invitation clears that), and not issued again since (a reinvitation moves `invitedAt`). + */ +function stillRequested(enrollmentId: string, invitedAt: Date): SQL | undefined { + return and( + eq(credentialGroupEnrollment.id, enrollmentId), + eq(credentialGroupEnrollment.invitedAt, invitedAt), + inArray(credentialGroupEnrollment.status, ['invited', 'delivery_failed']), + isNull(credentialGroupEnrollment.userId), + isNotNull(credentialGroupEnrollment.requestedByWorkflowId) + ) +} + /** * Sends the email a workflow's connection request enqueued. The enrollment is read again first, - * so a person who was revoked, or who connected, after the request was accepted gets nothing. - * A failed delivery is recorded on the enrollment for admins and retried by the outbox; a - * successful one clears it. + * so a person who was revoked, connected, or reinvited by an admin after the request was accepted + * gets nothing. + * + * A failed delivery marks the enrollment `delivery_failed` with its error, as an admin invitation + * does (People shows "Email failed"), and throws so the outbox retries. Once the provider accepted + * the email the handler never throws: failing to record that would make the outbox send it again. + * Both writes are conditional on the enrollment still being as the request left it, so they never + * overwrite a later admin action. */ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { const payload = parsePayload(rawPayload) const [target] = await db .select({ email: credentialGroupEnrollment.email, + invitedAt: credentialGroupEnrollment.invitedAt, organizationName: organization.name, credentialGroupName: credentialGroup.name, }) @@ -55,8 +91,9 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { .where( and( eq(credentialGroupEnrollment.id, payload.enrollmentId), - eq(credentialGroupEnrollment.status, 'invited'), - isNull(credentialGroupEnrollment.userId) + inArray(credentialGroupEnrollment.status, ['invited', 'delivery_failed']), + isNull(credentialGroupEnrollment.userId), + isNotNull(credentialGroupEnrollment.requestedByWorkflowId) ) ) .limit(1) @@ -66,19 +103,21 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { .from(workflow) .where(and(eq(workflow.id, payload.workflowId), eq(workflow.workspaceId, payload.workspaceId))) .limit(1) - const workflowName = requester?.name ?? 'A workflow' const html = await renderCredentialGroupInvitationEmail({ recipientEmail: target.email, workspaceName: target.organizationName, + ownerKind: 'organization', credentialGroupName: target.credentialGroupName, invitationLink: payload.connectUrl, - workflowRequest: { workflowName, providerName: payload.providerName }, + workflowRequest: { + workflowName: connectionRequestWorkflowName(requester?.name), + providerName: payload.providerName, + }, }) const result = await sendEmail({ to: target.email, subject: getCredentialGroupConnectionRequestSubject({ - workflowName, organizationName: target.organizationName, providerName: payload.providerName, }), @@ -86,17 +125,31 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { from: getFromEmailAddress(), emailType: 'transactional', }) - await db - .update(credentialGroupEnrollment) - .set({ - lastDeliveryError: result.success ? null : truncate(result.message, 500), - updatedAt: new Date(), - }) - .where(eq(credentialGroupEnrollment.id, payload.enrollmentId)) + if (!result.success) { + await db + .update(credentialGroupEnrollment) + .set({ + status: 'delivery_failed', + lastDeliveryError: truncate(result.message, 500), + updatedAt: new Date(), + }) + .where(stillRequested(payload.enrollmentId, target.invitedAt)) logger.warn('Connection request email failed', { enrollmentId: payload.enrollmentId }) throw new Error('Connection request email delivery failed') } + + try { + await db + .update(credentialGroupEnrollment) + .set({ status: 'invited', lastDeliveryError: null, updatedAt: new Date() }) + .where(stillRequested(payload.enrollmentId, target.invitedAt)) + } catch (error) { + logger.error('Failed to record a sent connection request email', { + enrollmentId: payload.enrollmentId, + error: getErrorMessage(error), + }) + } } export const credentialGroupConnectionRequestOutboxHandlers = { From bf78ffdec765f2427a533ecb171316abfc35d5e8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 15:42:20 -0600 Subject: [PATCH 13/26] test(credential-groups): connect flow proofs and merge reconciliation Reconciliation after the core and UI lanes merged: - One helper in return-url.ts turns a stable connect URL's `return` value into a destination: only the keyword `slack` (the Slack app), shared by the connect page and the connect use case; the enroll page keeps accepting the validated URL the server put on its link. - A workflow's repeat request emails with a "Reminder: ..." subject (organization and integration only). The inbox preview no longer shows the workflow name, which appears only in the body. - The Credential block's Return to options read None / Slack; the block docs describe the input. - The organization-accounts query mock covers the personal-accounts and request-policy hooks. - Fix the enroll page's duplicated slackReturnUrl prop left by the merge. - Request Connection's use case returns only { requested, connectUrl }; the enrollment and whether it was created stay inside the module for the audit row. Tests (each shown red against a reverted guard): - 0489 backfill: legacy invitations become one emailed link each, a replay adds nothing, and every token answers as it did through the legacy column. - Connect POST: IP limit, signed-out/unverified, per-person limit, non-ready outcomes, no-store and no-referrer on success, no GET handler. - Request Connection answers revoked, admin-invited and new people identically; the limit test seeds a real revoked enrollment; the one-day window; concurrent repeats send one reminder. - Admin request policy refuses a member, another organization's admin, and a stale revision. - Focused links refuse MCP completion and always read their one option; MCP grants refuse revoked and expired links at real Postgres; racing saves complete the enrollment once. - A revocation holding the lifecycle lock wins over a waiting completion; a bounced invitation still binds its person, a status-revoked one does not. - Retention keeps rows exactly at the cutoff, skips locked rows, and caps batches per run. - Lock-wait helpers wait on the specific holder (pg_blocking_pids), not any lock in the server. - Removed call-order and mock-argument unit tests now covered at the real boundary. --- .../docs/workflows/blocks/credential.mdx | 6 +- .../connect/[publicId]/route.test.ts | 87 +++++++-- .../[publicId]/connect/page.tsx | 13 +- .../credential-groups/enroll/[token]/page.tsx | 9 +- ...anup-credential-group-links.integration.ts | 93 ++++++++- apps/sim/blocks/blocks/credential.ts | 2 +- .../credential-group-invitation-email.tsx | 5 +- apps/sim/components/emails/subjects.ts | 5 +- .../organization-account-providers.test.tsx | 3 - .../executor/handlers/credential/handler.ts | 6 +- .../connect-target.integration.ts | 105 +++++++++-- .../enrollment-link-backfill.integration.ts | 178 ++++++++++++++++++ .../enrollment-links.integration.ts | 94 ++++++++- .../multiple-provider-accounts.integration.ts | 48 ++++- ...orkflow-connection-requests.integration.ts | 138 ++++++++++++-- .../application/connect-target.ts | 15 +- .../application/connection-requests.ts | 31 ++- apps/sim/lib/credential-groups/connect-url.ts | 5 +- .../connection-request-email.ts | 2 + .../connection-request-event.ts | 2 + .../credential-groups/connection-requests.ts | 7 +- .../lib/credential-groups/enrollments.test.ts | 78 -------- apps/sim/lib/credential-groups/return-url.ts | 15 ++ apps/sim/lib/credentials/managed-mcp.test.ts | 18 +- .../organization-accounts-queries.mock.ts | 10 + 25 files changed, 775 insertions(+), 200 deletions(-) create mode 100644 apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts diff --git a/apps/docs/content/docs/workflows/blocks/credential.mdx b/apps/docs/content/docs/workflows/blocks/credential.mdx index 0a4295d4e36..67d5ac1d4fa 100644 --- a/apps/docs/content/docs/workflows/blocks/credential.mdx +++ b/apps/docs/content/docs/workflows/blocks/credential.mdx @@ -53,8 +53,8 @@ Authorized workflows in an allowed workspace can discover active contributions f | --- | --- | --- | | Find Organization Account | **Email**, **Integration** | — | | List Organization Accounts | — | **Email**, **Integrations**, **Limit**, **Cursor** | -| Get Connection Status | **Email**, **Integration** | — | -| Request Connection | **Email**, **Integration** | — | +| Get Connection Status | **Email**, **Integration** | **Return to** | +| Request Connection | **Email**, **Integration** | **Return to** | | Find Organization MCP Connection | **Email**, **MCP provider** | — | | List Organization MCP Connections | — | **Email**, **MCP provider**, **Limit**, **Cursor** | @@ -105,6 +105,8 @@ The status never says whether the person was invited, removed, or never asked. ` When `connected` is false, call **Request Connection** first (or make sure an admin invited the person), then show `connectUrl`. +Set **Return to** to **Slack** when the person starts in Slack: once their account is connected, the page offers a **Return to Slack** button that opens the Slack app. With **None** the page tells them they can close the tab. + **Request Connection** returns `requested` and `connectUrl`. It works only when an admin turns on **Allow workflow requests** under **Workflow connection requests** in **Settings → Credential Groups → Access**, for the workflow's workspace, the person's email domain, and the integration. A request outside those settings, or past the daily limit, fails with an error. Otherwise the result is the same whether the person was already asked, already connected, or removed; a removed person is never re-invited. Use the person's primary address: an address with a `+` alias is refused. The daily limit counts every accepted request across all workspaces, including repeat requests for the same person. When the admin chose to also email the person, Sim emails the link with the workflow's name. It sends up to 3 reminders, each only when a workflow asks again after a day with no request for that person, and none after 30 days. ### Managed MCP diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts index 1e77d88c8c8..94bace40530 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts @@ -1,30 +1,41 @@ /** * The connect page's confirmation POST enrolls the signed-in person, so it must only act on a - * request a page on this origin sent. Failure modes: a cross-site form post, a post from another - * origin whose browser sends no `Sec-Fetch-Site`, and a client that sends neither header, each of - * which must be refused before the person is enrolled; a same-origin post must still go through. + * request a page on this origin sent, by a verified person within their rate limits. Failure + * modes: a cross-site form post, a post from another origin whose browser sends no + * `Sec-Fetch-Site`, a client that sends neither header, an IP over its bucket, a signed-out or + * unverified session, a person over their connect-link limit, and a start that ends anywhere but + * ready. Each must leave the person unenrolled (or send them back to the connect page, which + * explains the outcome); a same-origin post goes through without leaking the minted link through + * a cache or a Referer. No GET handler exists, so a link click or prefetch never confirms. */ import { authMockFns } from '@sim/testing' import { createMockRequest } from '@sim/testing/mocks/request.mock' +import { NextResponse } from 'next/server' import { beforeEach, describe, expect, it, vi } from 'vitest' -const { mockStart } = vi.hoisted(() => ({ mockStart: vi.fn() })) +const { mockStart, mockIpRateLimit, mockUserRateLimited } = vi.hoisted(() => ({ + mockStart: vi.fn(), + mockIpRateLimit: vi.fn(), + mockUserRateLimited: vi.fn(), +})) vi.mock('@/lib/credential-groups/application/connect-target', () => ({ startCredentialGroupConnect: { execute: mockStart }, })) vi.mock('@/lib/credential-groups/rate-limit', () => ({ - enforcePublicCredentialGroupIpRateLimit: async () => null, - isCredentialGroupConnectUserRateLimited: async () => false, + enforcePublicCredentialGroupIpRateLimit: mockIpRateLimit, + isCredentialGroupConnectUserRateLimited: mockUserRateLimited, })) -import { POST } from '@/app/api/credential-groups/connect/[publicId]/route' +import * as connectRoute from '@/app/api/credential-groups/connect/[publicId]/route' + +const CONNECT_PATH = '/credential-groups/public-1/connect?provider=google-drive&return=slack' -function confirm(headers: Record) { - return POST( +function confirm(headers: Record = { 'sec-fetch-site': 'same-origin' }) { + return connectRoute.POST( createMockRequest({ method: 'POST', - url: 'http://localhost:3000/api/credential-groups/connect/public-1?provider=google-drive', + url: 'http://localhost:3000/api/credential-groups/connect/public-1?provider=google-drive&return=slack', headers, }), { params: Promise.resolve({ publicId: 'public-1' }) } @@ -37,6 +48,8 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { user: { id: 'user-1', emailVerified: true }, session: { id: 'session-1' }, }) + mockIpRateLimit.mockResolvedValue(null) + mockUserRateLimited.mockResolvedValue(false) mockStart.mockResolvedValue({ kind: 'ready', invitationToken: 'token-1', optionId: 'drive' }) }) @@ -45,15 +58,63 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { ['a same-site sibling origin', { 'sec-fetch-site': 'same-site' }], ['another origin with no Sec-Fetch-Site', { origin: 'https://attacker.example' }], ['a client sending neither header', {}], - ])('refuses %s', async (_label, headers) => { + ])('refuses %s without enrolling anyone', async (_label, headers) => { const response = await confirm(headers) expect(response.status).toBe(403) expect(response.headers.get('location')).toBeNull() + expect(mockStart).not.toHaveBeenCalled() + }) + + it('refuses an IP over its bucket without enrolling anyone', async () => { + mockIpRateLimit.mockResolvedValueOnce( + NextResponse.json({ error: 'Too many requests' }, { status: 429 }) + ) + const response = await confirm() + expect(response.status).toBe(429) + expect(mockStart).not.toHaveBeenCalled() + }) + + it.each([ + ['a signed-out visitor', null], + [ + 'an unverified session', + { user: { id: 'user-1', emailVerified: false }, session: { id: 'session-1' } }, + ], + ])('sends %s back to the connect page without enrolling them', async (_label, session) => { + authMockFns.mockGetSession.mockResolvedValueOnce(session) + const response = await confirm() + expect(response.status).toBe(303) + expect(response.headers.get('location')).toBe(CONNECT_PATH) + expect(mockStart).not.toHaveBeenCalled() + }) + + it('sends a person over their connect-link limit back without enrolling them', async () => { + mockUserRateLimited.mockResolvedValueOnce(true) + const response = await confirm() + expect(response.headers.get('location')).toBe(CONNECT_PATH) + expect(mockStart).not.toHaveBeenCalled() }) - it('continues a same-origin post to the enrollment page', async () => { - const response = await confirm({ 'sec-fetch-site': 'same-origin' }) + it.each(['not_invited', 'revoked', 'unavailable', 'wrong_account'])( + 'sends a %s outcome back to the connect page to explain it', + async (kind) => { + mockStart.mockResolvedValueOnce({ kind }) + const response = await confirm() + expect(response.status).toBe(303) + expect(response.headers.get('location')).toBe(CONNECT_PATH) + } + ) + + it('confirms enrollment and continues to the focused enrollment page, uncached and unreferred', async () => { + const response = await confirm() expect(response.status).toBe(303) expect(response.headers.get('location')).toMatch(/^\/credential-groups\/enroll\/token-1\?/) + expect(response.headers.get('cache-control')).toBe('no-store') + expect(response.headers.get('referrer-policy')).toBe('no-referrer') + expect(mockStart.mock.calls[0]?.[0]?.input).toMatchObject({ confirmSelfEnrollment: true }) + }) + + it('has no GET handler, so following or prefetching the URL never confirms', () => { + expect('GET' in connectRoute).toBe(false) }) }) diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index d6fc8b082a6..1edc40f7efa 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -16,7 +16,7 @@ import { enforcePublicCredentialGroupIpRateLimit, isCredentialGroupConnectUserRateLimited, } from '@/lib/credential-groups/rate-limit' -import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' +import { resolveCredentialGroupConnectReturnUrl } from '@/lib/credential-groups/return-url' import { AuthHeader } from '@/app/(auth)/components' import { CredentialGroupPageShell, @@ -52,15 +52,6 @@ function getSearchParam( const UNAVAILABLE_MESSAGE = 'This link isn’t available. Ask whoever sent it to check it’s still set up.' -/** - * Where a dead end sends the person back to: `return=slack` is the Slack app, and any other value - * must pass the Slack allowlist. Rendered only as a link the person clicks. - */ -function resolveSlackReturnHref(returnValue: string | undefined): string | undefined { - if (!returnValue) return undefined - return parseCredentialGroupReturnUrl(returnValue === 'slack' ? 'slack://open' : returnValue)?.href -} - /** * The secret-free link a workflow shows when someone has not connected an account yet. Signs the * person in, resolves their own enrollment, and hands off to the enrollment page with a @@ -77,7 +68,7 @@ export default async function CredentialGroupConnectPage({ const provider = getSearchParam(query, 'provider') const optionId = getSearchParam(query, 'optionId') const returnValue = getSearchParam(query, 'return') - const slackReturnHref = resolveSlackReturnHref(returnValue) + const slackReturnHref = resolveCredentialGroupConnectReturnUrl(returnValue) const recovery = slackReturnHref ? { recoveryHref: slackReturnHref, recoveryLabel: 'Return to Slack' } : {} diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index 0e6b66f1b54..fd4396e6db4 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -54,10 +54,11 @@ interface EnrollmentLinkProblemProps { outcome: CredentialGroupEnrollmentLinkOutcome signedInEmail: string callbackUrl: string - /** An allowed Slack destination the link carried, offered beside a way to start over. */ - slackReturnUrl?: string fallbackMessage?: string - /** An allowlisted Slack destination, offered as the way out of a dead end. */ + /** + * An allowlisted Slack destination the link carried: the way out of a dead end, and offered + * beside Start again on an expired connect link. + */ slackReturnUrl?: string } @@ -76,7 +77,6 @@ function EnrollmentLinkProblem({ outcome, signedInEmail, callbackUrl, - slackReturnUrl, fallbackMessage, slackReturnUrl, }: EnrollmentLinkProblemProps) { @@ -243,7 +243,6 @@ export default async function CredentialGroupEnrollmentPage({ } signedInEmail={session.user.email} callbackUrl={callbackUrl} - slackReturnUrl={slackReturnUrl} fallbackMessage={fallbackMessage} slackReturnUrl={slackReturnUrl} /> diff --git a/apps/sim/background/cleanup-credential-group-links.integration.ts b/apps/sim/background/cleanup-credential-group-links.integration.ts index f5ddbe58ac3..b35c87ec69b 100644 --- a/apps/sim/background/cleanup-credential-group-links.integration.ts +++ b/apps/sim/background/cleanup-credential-group-links.integration.ts @@ -3,7 +3,9 @@ * request log row the daily cap still reads being deleted; an expired session link a day past * expiry being kept; an emailed link, which outlives its expiry once bound, being deleted; a * session link the enrollment's legacy invitation column still names being deleted, which would - * let its token resolve through the column with no expiry. + * let its token resolve through the column with no expiry; a row exactly at a cutoff being + * deleted early; a row another run has locked stalling this run; one run draining an unbounded + * backlog instead of capping its batches. */ import { db } from '@sim/db' import { @@ -14,8 +16,9 @@ import { organization, } from '@sim/db/schema' import { sha256Hex } from '@sim/security/hash' +import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' -import { eq, inArray } from 'drizzle-orm' +import { eq, inArray, sql } from 'drizzle-orm' import { afterAll, describe, expect, it } from 'vitest' import { runCleanupCredentialGroupLinks } from '@/background/cleanup-credential-group-links' @@ -114,4 +117,90 @@ describe('runCleanupCredentialGroupLinks', () => { [recentlyExpired, live, oldEmail, namedByLegacyColumn].sort() ) }) + + it('keeps rows exactly at their cutoff and deletes those a millisecond older', async () => { + const { groupId, enrollmentId } = await createEnrollment(sha256Hex(generateId())) + const now = Date.now() + const atRequestCutoff = await insertRequest(groupId, new Date(now - 2 * DAY_MS)) + await insertRequest(groupId, new Date(now - 2 * DAY_MS - 1)) + const atLinkCutoff = await insertLink(enrollmentId, 'connect', new Date(now - DAY_MS)) + await insertLink(enrollmentId, 'connect', new Date(now - DAY_MS - 1)) + + await runCleanupCredentialGroupLinks(new Date(now)) + + const requests = await db + .select({ id: credentialGroupConnectionRequest.id }) + .from(credentialGroupConnectionRequest) + .where(eq(credentialGroupConnectionRequest.credentialGroupId, groupId)) + expect(requests.map((row) => row.id)).toEqual([atRequestCutoff]) + const links = await db + .select({ id: credentialGroupEnrollmentLink.id }) + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId)) + expect(links.map((row) => row.id)).toEqual([atLinkCutoff]) + }) + + it('skips a row another run holds instead of waiting for it', async () => { + const { groupId } = await createEnrollment(sha256Hex(generateId())) + const old = new Date(Date.now() - 3 * DAY_MS) + const held = await insertRequest(groupId, old) + const free = await insertRequest(groupId, old) + + let release = () => {} + const releaseHeld = new Promise((resolve) => { + release = resolve + }) + let markLocked = () => {} + const locked = new Promise((resolve) => { + markLocked = resolve + }) + const holder = db.transaction(async (tx) => { + await tx.execute( + sql`SELECT id FROM ${credentialGroupConnectionRequest} WHERE id = ${held} FOR UPDATE` + ) + markLocked() + await releaseHeld + }) + await locked + const outcome = await Promise.race([ + runCleanupCredentialGroupLinks().then(() => 'finished' as const), + sleep(5_000).then(() => 'blocked' as const), + ]) + release() + await holder + + expect(outcome).toBe('finished') + const remaining = await db + .select({ id: credentialGroupConnectionRequest.id }) + .from(credentialGroupConnectionRequest) + .where(inArray(credentialGroupConnectionRequest.id, [held, free])) + expect(remaining.map((row) => row.id)).toEqual([held]) + }) + + it('deletes at most five batches per run, oldest first, leaving the rest for the next run', async () => { + const { groupId } = await createEnrollment(sha256Hex(generateId())) + const now = Date.now() + const rows = Array.from({ length: 5_001 }, (_, index) => ({ + id: generateId(), + credentialGroupId: groupId, + email: `backlog-${index}@retention.test`, + workspaceId: generateId(), + workflowId: generateId(), + createdAt: new Date(now - 10 * DAY_MS + index * 1_000), + })) + await db.insert(credentialGroupConnectionRequest).values(rows) + const newest = rows.at(-1)?.id + const ours = () => + db + .select({ id: credentialGroupConnectionRequest.id }) + .from(credentialGroupConnectionRequest) + .where(eq(credentialGroupConnectionRequest.credentialGroupId, groupId)) + + const first = await runCleanupCredentialGroupLinks(new Date(now)) + expect(first.connectionRequests).toBe(5_000) + expect((await ours()).map((row) => row.id)).toEqual([newest]) + + await runCleanupCredentialGroupLinks(new Date(now)) + expect(await ours()).toEqual([]) + }) }) diff --git a/apps/sim/blocks/blocks/credential.ts b/apps/sim/blocks/blocks/credential.ts index 9f90cb2f824..03c437142d6 100644 --- a/apps/sim/blocks/blocks/credential.ts +++ b/apps/sim/blocks/blocks/credential.ts @@ -168,7 +168,7 @@ export const CredentialBlock: BlockConfig = { title: 'Return to', type: 'dropdown', options: [ - { label: 'Nowhere', id: 'none' }, + { label: 'None', id: 'none' }, { label: 'Slack', id: 'slack' }, ], value: () => 'none', diff --git a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx index f27efe034f6..c6aa908e613 100644 --- a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx +++ b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx @@ -15,7 +15,8 @@ interface CredentialGroupInvitationEmailProps { searchProviderName?: string /** * Set when a workflow asked for one integration. The link is then the stable connect - * page, which signs the person in instead of expiring, so the footer says so. + * page, which signs the person in instead of expiring, so the footer says so. The workflow + * name, chosen by its builder, appears only in the body, never in the inbox preview. */ workflowRequest?: { workflowName: string; providerName: string } } @@ -35,7 +36,7 @@ export function CredentialGroupInvitationEmail({ { const menu = document.querySelector( 'button[aria-label="Integration actions"]' ) - expect(menu).not.toBeNull() await act(async () => menu?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) ) const reapply = [...document.querySelectorAll('[role="menuitem"]')].find( (node) => node.textContent?.trim() === 'Re-apply app configuration' ) - expect(reapply).toBeDefined() await act(async () => reapply?.click()) expect(mocks.update).not.toHaveBeenCalled() await clickButton('Re-apply') @@ -221,7 +219,6 @@ describe('organization provider configuration UI', () => { ) expect(mocks.add).not.toHaveBeenCalled() expect(mocks.remove).not.toHaveBeenCalled() - expect(toast.success).toHaveBeenCalledWith('App configuration re-applied') }) it('loads existing settings for Configure and preserves a saved secret left blank', async () => { diff --git a/apps/sim/executor/handlers/credential/handler.ts b/apps/sim/executor/handlers/credential/handler.ts index d934472a75d..9a191d8a899 100644 --- a/apps/sim/executor/handlers/credential/handler.ts +++ b/apps/sim/executor/handlers/credential/handler.ts @@ -147,8 +147,8 @@ export class CredentialBlockHandler implements BlockHandler { ...parseConnectReturnTo(inputs.connectReturnTo), }, }) - case 'request_connection': { - const { requested, connectUrl } = await requestOrganizationAccountConnection.execute({ + case 'request_connection': + return requestOrganizationAccountConnection.execute({ principal, input: { workspaceId: ctx.workspaceId, @@ -157,8 +157,6 @@ export class CredentialBlockHandler implements BlockHandler { ...parseConnectReturnTo(inputs.connectReturnTo), }, }) - return { requested, connectUrl } - } case 'find_organization_mcp_connection': case 'list_organization_mcp_connections': { const find = operation === 'find_organization_mcp_connection' diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index 25f894ade49..bd6bd302399 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -40,7 +40,9 @@ import { } from '@/lib/credential-groups/application/connect-target' import { completePublicCredentialGroupEnrollment, + completePublicCredentialGroupMcpOAuth, completePublicCredentialGroupOAuth, + readPublicCredentialGroupEnrollment, startPublicCredentialGroupMcpOAuth, startPublicCredentialGroupOAuth, } from '@/lib/credential-groups/application/public-enrollment' @@ -264,16 +266,20 @@ async function enrollmentOf(groupId: string, email: string) { return row } -/** Resolves once a query waits on an advisory lock, so a test can commit the holder mid-request. */ -async function waitForAdvisoryLockWaiter() { +/** + * Resolves once a backend in this database waits on the transaction holding `blockerPid`, so a + * test can commit the holder mid-request. Scoped to that holder, so another suite's lock waits + * on a shared server never satisfy it. + */ +async function waitForBlockedBy(blockerPid: number) { for (let attempt = 0; attempt < 200; attempt++) { const waiting = await db.execute( - sql`SELECT 1 FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND wait_event = 'advisory'` + sql`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND ${blockerPid}::int = ANY(pg_blocking_pids(pid))` ) if (waiting.length) return await sleep(25) } - throw new Error('The self-enrollment never waited on the invitation lock') + throw new Error('The request never waited on the held transaction') } afterAll(async () => { @@ -320,6 +326,24 @@ describe('startCredentialGroupConnect', () => { }) }) + it('ignores a return URL in the connect link, even an allowlisted Slack one', async () => { + const fixture = await createOrganization() + const person = await createPerson() + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + + for (const returnUrl of ['slack://open', 'https://slack.com/app_redirect?app=A123']) { + const target = await resolveTarget(person.userId, { publicId: fixture.publicId, returnUrl }) + expect(target.kind).toBe('ready') + expect(target).not.toHaveProperty('returnUrl') + } + }) + it('resolves without binding the person or minting a link', async () => { const fixture = await createOrganization() const person = await createPerson() @@ -514,10 +538,12 @@ describe('startCredentialGroupConnect', () => { invitationExpiresAt: new Date(Date.now() + HOUR_MS), invitedAt: new Date(), }) + const [holder] = await tx.execute<{ pid: number }>(sql`SELECT pg_backend_pid() AS pid`) + if (!holder) throw new Error('No backend pid') const pending = runOutsideTransactionContext(() => resolveTarget(teammate.userId, { publicId: fixture.publicId, confirmSelfEnrollment: true }) ) - await runOutsideTransactionContext(waitForAdvisoryLockWaiter) + await runOutsideTransactionContext(() => waitForBlockedBy(holder.pid)) return { pending } }) @@ -613,7 +639,7 @@ describe('startCredentialGroupConnect', () => { }) describe('a focused connect link', () => { - it('refuses to start or complete OAuth for another option, or start an MCP server', async () => { + it('refuses to start or complete OAuth for another option, or start or complete an MCP grant', async () => { const fixture = await createOrganization([ driveOption('drive-work', 'Work Drive'), driveOption('drive-shared', 'Shared Drive'), @@ -653,6 +679,57 @@ describe('a focused connect link', () => { }, }) ).rejects.toBeInstanceOf(CredentialGroupLinkFocusError) + await expect( + completePublicCredentialGroupMcpOAuth.execute({ + principal, + input: { + attempt: { + userId: person.userId, + state: generateId(), + organizationId: fixture.organizationId, + email: principal.email, + enrollmentId: principal.enrollmentId, + credentialGroupId: fixture.groupId, + mcpServerId: generateId(), + oauthConfigVersion: 1, + codeVerifier: 'verifier', + invitationToken: token, + createdAt: Date.now(), + }, + code: 'code', + }, + }) + ).rejects.toBeInstanceOf(CredentialGroupLinkFocusError) + expect((await enrollmentOf(fixture.groupId, person.email)).status).toBe('invited') + }) + + it('shows only its one option, whichever option the page asks for', async () => { + const fixture = await createOrganization([ + driveOption('drive-work', 'Work Drive'), + driveOption('drive-shared', 'Shared Drive'), + ]) + const person = await createPerson() + await inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + person.email + ) + const token = await readyToken(person.userId, { + publicId: fixture.publicId, + optionId: 'drive-work', + }) + const principal = await principalFor(token, person.userId) + + for (const optionId of [undefined, 'drive-shared']) { + const read = await readPublicCredentialGroupEnrollment.execute({ + principal, + input: optionId ? { optionId } : {}, + }) + expect(read.focusOptionId).toBe('drive-work') + expect(read.enrollment.options.map((option) => option.id)).toEqual(['drive-work']) + } }) it('refuses Submit, which a focused link never shows, leaving the enrollment open', async () => { @@ -674,7 +751,7 @@ describe('a focused connect link', () => { expect((await enrollmentOf(fixture.groupId, person.email)).status).toBe('invited') }) - it('completes the enrollment when its connection is saved, firing form_submitted once', async () => { + it('completes the enrollment when its connection is saved, firing form_submitted once even when saves race', async () => { const fixture = await createOrganization() const person = await createPerson() await inviteCredentialGroupEnrollment( @@ -687,12 +764,14 @@ describe('a focused connect link', () => { const token = await readyToken(person.userId, { publicId: fixture.publicId }) const principal = await principalFor(token, person.userId) - for (const code of ['same@drive.test', 'same@drive.test']) { - await completePublicCredentialGroupOAuth.execute({ - principal, - input: { attempt: attemptFor(fixture, principal, token, DRIVE.id), code }, - }) - } + await Promise.allSettled( + ['same@drive.test', 'same@drive.test', 'same@drive.test'].map((code) => + completePublicCredentialGroupOAuth.execute({ + principal, + input: { attempt: attemptFor(fixture, principal, token, DRIVE.id), code }, + }) + ) + ) const enrollment = await enrollmentOf(fixture.groupId, person.email) expect(enrollment.status).toBe('completed') diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts new file mode 100644 index 00000000000..0c805b37f9a --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts @@ -0,0 +1,178 @@ +/** + * The 0489 backfill against real Postgres: invitations the pre-link app wrote (only the legacy + * `invitation_token_hash` column, no link row) each become exactly one emailed link, a replay of + * the statement adds nothing, and every token gets the same answer through the link table as it + * got through the legacy column. The backfill statement is read from the migration file itself. + */ +import { readFile } from 'node:fs/promises' +import { db } from '@sim/db' +import { + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + member, + organization, + user, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq, inArray, sql } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { authenticatePublicCredentialGroupEnrollment } from '@/lib/credential-groups/enrollments' +import { + findCredentialGroupEnrollmentLinkRecord, + hashInvitationToken, +} from '@/lib/credential-groups/links' +import { ensureWorkspaceAccountsGroup } from '@/lib/credential-groups/service' + +vi.mock('@/lib/credential-groups/scoped-availability', () => ({ + isScopedCredentialGroupsAvailable: async () => true, +})) + +const MIGRATION_URL = new URL( + '../../../../../packages/db/migrations/0489_credential_group_enrollment_links.sql', + import.meta.url +) +const DAY_MS = 24 * 60 * 60 * 1000 + +const organizationId = generateId() +const adminId = generateId() +const boundUserId = generateId() +let groupId = '' + +interface LegacyInvitation { + label: string + enrollmentId: string + token: string + revokedByStatus: boolean + expiresAt: Date +} + +const invitations: LegacyInvitation[] = [] + +/** Writes an enrollment the way the pre-link app did: its invitation only in the legacy column. */ +async function seedLegacyInvitation(input: { + label: string + expiresInMs: number + status?: 'invited' | 'revoked' | 'completed' + userId?: string +}): Promise { + const enrollmentId = generateId() + const token = generateId() + const now = Date.now() + const expiresAt = new Date(now + input.expiresInMs) + await db.insert(credentialGroupEnrollment).values({ + id: enrollmentId, + credentialGroupId: groupId, + email: `${enrollmentId}@backfill.test`.toLowerCase(), + userId: input.userId ?? null, + status: input.status ?? 'invited', + invitationTokenHash: hashInvitationToken(token), + invitationExpiresAt: expiresAt, + invitedAt: new Date(now - DAY_MS), + createdBy: adminId, + }) + invitations.push({ + label: input.label, + enrollmentId, + token, + revokedByStatus: input.status === 'revoked', + expiresAt, + }) +} + +async function backfillStatement(): Promise { + const migration = await readFile(MIGRATION_URL, 'utf8') + const statement = migration.split('--> statement-breakpoint').at(-1) + if (!statement?.includes('INSERT INTO "credential_group_enrollment_link"')) + throw new Error('0489 no longer ends with its backfill') + return statement +} + +async function answers(token: string) { + const [identity, record] = await Promise.all([ + authenticatePublicCredentialGroupEnrollment(token), + findCredentialGroupEnrollmentLinkRecord(token), + ]) + return { + live: identity !== null, + expired: record?.expired, + revoked: record?.revoked, + linkRevoked: record?.linkRevoked, + } +} + +beforeAll(async () => { + await db.insert(user).values( + [adminId, boundUserId].map((id) => ({ + id, + name: 'Backfill fixture', + email: `${id}@backfill.test`.toLowerCase(), + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + })) + ) + await db + .insert(organization) + .values({ id: organizationId, name: 'Backfill', slug: organizationId }) + await db + .insert(member) + .values({ id: generateId(), organizationId, userId: adminId, role: 'owner' }) + groupId = (await ensureWorkspaceAccountsGroup({ kind: 'organization', organizationId }, adminId)) + .id + + await seedLegacyInvitation({ label: 'live and unbound', expiresInMs: 3 * DAY_MS }) + await seedLegacyInvitation({ + label: 'revoked by status alone', + expiresInMs: 3 * DAY_MS, + status: 'revoked', + }) + await seedLegacyInvitation({ label: 'expired and unbound', expiresInMs: -DAY_MS }) + await seedLegacyInvitation({ + label: 'expired but bound to its person', + expiresInMs: -DAY_MS, + status: 'completed', + userId: boundUserId, + }) +}) + +afterAll(async () => { + await db.delete(organization).where(eq(organization.id, organizationId)) + await db.delete(user).where(inArray(user.id, [adminId, boundUserId])) +}) + +describe('0489 enrollment link backfill', () => { + it('turns each legacy invitation into one emailed link that answers exactly as before, even when replayed', async () => { + const before = await Promise.all(invitations.map((invitation) => answers(invitation.token))) + expect(before.map((answer) => answer.live)).toEqual([true, false, false, true]) + + const statement = await backfillStatement() + await db.execute(sql.raw(statement)) + await db.execute(sql.raw(statement)) + + const links = await db + .select() + .from(credentialGroupEnrollmentLink) + .where( + inArray( + credentialGroupEnrollmentLink.enrollmentId, + invitations.map((invitation) => invitation.enrollmentId) + ) + ) + for (const invitation of invitations) { + const own = links.filter((link) => link.enrollmentId === invitation.enrollmentId) + expect(own, invitation.label).toHaveLength(1) + expect(own[0], invitation.label).toMatchObject({ + tokenHash: hashInvitationToken(invitation.token), + purpose: 'email', + optionId: null, + expiresAt: invitation.expiresAt, + }) + expect(own[0]?.revokedAt !== null, invitation.label).toBe(invitation.revokedByStatus) + } + + const after = await Promise.all(invitations.map((invitation) => answers(invitation.token))) + expect(after.map(({ linkRevoked, ...rest }) => rest)).toEqual( + before.map(({ linkRevoked, ...rest }) => rest) + ) + }) +}) diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts index 45a5e1d2a68..91172581d27 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts @@ -19,8 +19,9 @@ import { import { explainCaptured } from '@sim/db/testing/explain' import { sha256Hex } from '@sim/security/hash' import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' -import { eq } from 'drizzle-orm' +import { eq, sql } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { disconnectPersonalOrganizationAccount } from '@/lib/credential-groups/application/personal-organization-accounts' import { issueCredentialGroupConnectLink } from '@/lib/credential-groups/connect-subject' @@ -30,6 +31,7 @@ import { completeAuthorizedCredentialGroupEnrollment, getCredentialGroupOAuthContextForEnrollment, inviteCredentialGroupEnrollment, + lockCredentialGroupEnrollmentLifecycle, resendCredentialGroupEnrollment, revokeCredentialGroupEnrollment, } from '@/lib/credential-groups/enrollments' @@ -152,6 +154,33 @@ async function resolves(token: string): Promise { return (await authenticatePublicCredentialGroupEnrollment(token)) !== null } +async function identityOf(token: string) { + const identity = await authenticatePublicCredentialGroupEnrollment(token) + if (!identity) throw new Error('Link did not resolve') + return identity +} + +async function enrollmentRow(enrollmentId: string) { + const [row] = await db + .select() + .from(credentialGroupEnrollment) + .where(eq(credentialGroupEnrollment.id, enrollmentId)) + if (!row) throw new Error('Enrollment is missing') + return row +} + +/** Resolves once a backend in this database waits on the transaction holding `blockerPid`. */ +async function waitForBlockedBy(blockerPid: number) { + for (let attempt = 0; attempt < 200; attempt++) { + const waiting = await db.execute( + sql`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND ${blockerPid}::int = ANY(pg_blocking_pids(pid))` + ) + if (waiting.length) return + await sleep(25) + } + throw new Error('The request never waited on the held transaction') +} + /** Ages every link of an enrollment, and the legacy column, past its expiry. */ async function expire(enrollmentId: string) { const past = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000) @@ -481,4 +510,67 @@ describe('credential group enrollment links', () => { expect(await resolves(resent)).toBe(true) expect(await resolves(self.token)).toBe(true) }) + + it('binds a person whose emailed invitation bounced, but never a revoked one', async () => { + const bounced = await createPerson() + const bouncedInvite = await adminInvite(bounced.email) + await db + .update(credentialGroupEnrollment) + .set({ status: 'delivery_failed', lastDeliveryError: 'mailbox unavailable' }) + .where(eq(credentialGroupEnrollment.id, bouncedInvite.enrollmentId)) + + await bindCredentialGroupEnrollmentUser(await identityOf(bouncedInvite.token), bounced.userId) + expect((await enrollmentRow(bouncedInvite.enrollmentId)).userId).toBe(bounced.userId) + + const revoked = await createPerson() + const revokedInvite = await adminInvite(revoked.email) + const identity = await identityOf(revokedInvite.token) + /** Revoked by status alone, as the released app does, so its link is still unrevoked. */ + await db + .update(credentialGroupEnrollment) + .set({ status: 'revoked' }) + .where(eq(credentialGroupEnrollment.id, revokedInvite.enrollmentId)) + + expect(await resolves(revokedInvite.token)).toBe(false) + await expect(bindCredentialGroupEnrollmentUser(identity, revoked.userId)).rejects.toMatchObject( + { status: 404 } + ) + expect((await enrollmentRow(revokedInvite.enrollmentId)).userId).toBeNull() + }) + + it('refuses to complete an enrollment revoked while the completion waits for its lock', async () => { + const person = await createPerson() + const self = await selfEnroll(person.userId) + const identity = await identityOf(self.token) + + let release = () => {} + const held = new Promise((resolve) => { + release = resolve + }) + let markLocked = (_pid: number) => {} + const locked = new Promise((resolve) => { + markLocked = resolve + }) + const revocation = db.transaction(async (tx) => { + await lockCredentialGroupEnrollmentLifecycle(tx, self.enrollmentId) + await tx + .update(credentialGroupEnrollment) + .set({ status: 'revoked', revokedAt: new Date() }) + .where(eq(credentialGroupEnrollment.id, self.enrollmentId)) + const [holder] = await tx.execute<{ pid: number }>(sql`SELECT pg_backend_pid() AS pid`) + markLocked(holder?.pid ?? -1) + await held + }) + const holderPid = await locked + const completion = completeAuthorizedCredentialGroupEnrollment(identity) + await waitForBlockedBy(holderPid) + release() + await revocation + + await expect(completion).resolves.toBeNull() + expect(await enrollmentRow(self.enrollmentId)).toMatchObject({ + status: 'revoked', + completedAt: null, + }) + }) }) diff --git a/apps/sim/lib/credential-groups/__integration__/multiple-provider-accounts.integration.ts b/apps/sim/lib/credential-groups/__integration__/multiple-provider-accounts.integration.ts index 430e5aef103..d94a701ee5f 100644 --- a/apps/sim/lib/credential-groups/__integration__/multiple-provider-accounts.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/multiple-provider-accounts.integration.ts @@ -8,6 +8,7 @@ import { credential, credentialGroup, credentialGroupEnrollment, + credentialGroupEnrollmentLink, mcpServers, member, organization, @@ -25,7 +26,10 @@ import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth- import { CredentialGroupOAuthError } from '@/lib/credential-groups/provider-adapter' import type { CredentialGroupProvider } from '@/lib/credential-groups/providers' import { listViewerOrganizationAccounts } from '@/lib/credential-groups/viewer-accounts' -import { persistManagedMcpCredential } from '@/lib/credentials/managed-mcp' +import { + ManagedMcpCredentialError, + persistManagedMcpCredential, +} from '@/lib/credentials/managed-mcp' import { decryptManagedOAuthTokenSet } from '@/lib/credentials/managed-oauth' import { resolveSlackSearchMember } from '@/lib/knowledge/application/slack-search/identity' import { mcpService } from '@/lib/mcp/service' @@ -585,10 +589,11 @@ describe('managed MCP accounts', () => { }) const connectMcp = ( identity: ReturnType | null, - connectionIntent?: CredentialGroupOAuthAttempt['connectionIntent'] + connectionIntent?: CredentialGroupOAuthAttempt['connectionIntent'], + token = invitationToken ) => persistManagedMcpCredential({ - invitationTokenHash: sha256Hex(invitationToken), + invitationTokenHash: sha256Hex(token), oauthConfigVersion: 1, enrollmentId, credentialGroupId: groupId, @@ -818,4 +823,41 @@ describe('managed MCP accounts', () => { ]) expect(await mcpRows()).toHaveLength(1) }) + + it.each([ + ['a revoked emailed link', { purpose: 'email', expiresInMs: 3_600_000, revoked: true }], + ['an expired connect link', { purpose: 'connect', expiresInMs: -60_000, revoked: false }], + ['an expired self link', { purpose: 'self', expiresInMs: -60_000, revoked: false }], + ] as const)('refuses to save a grant through %s, saving nothing', async (_label, link) => { + const token = generateId() + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId, + tokenHash: sha256Hex(token), + purpose: link.purpose, + expiresAt: new Date(Date.now() + link.expiresInMs), + revokedAt: link.revoked ? new Date() : null, + }) + + const error = await connectMcp(identityOf('one'), { kind: 'create' }, token).catch( + (caught: unknown) => caught + ) + expect(error).toBeInstanceOf(ManagedMcpCredentialError) + expect(error).toMatchObject({ statusCode: 404 }) + expect(await mcpRows()).toEqual([]) + }) + + it('saves a grant through a live connect link', async () => { + const token = generateId() + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId, + tokenHash: sha256Hex(token), + purpose: 'connect', + expiresAt: new Date(Date.now() + 3_600_000), + }) + await expect(connectMcp(identityOf('one'), { kind: 'create' }, token)).resolves.toMatchObject({ + created: true, + }) + }) }) diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index b5ea07d8feb..fb59d6078e7 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -375,7 +375,7 @@ async function connectPerson(fixture: OrgFixture, email: string) { const emailEvents = (enrollmentId: string) => db - .select({ id: outboxEvent.id }) + .select({ reminder: sql`(${outboxEvent.payload} ->> 'reminder')::boolean` }) .from(outboxEvent) .where( and( @@ -401,16 +401,26 @@ const clearRequestLog = (fixture: OrgFixture) => .delete(credentialGroupConnectionRequest) .where(eq(credentialGroupConnectionRequest.credentialGroupId, fixture.groupId)) -/** Resolves once some query waits on a row lock, so a test can commit the holder mid-request. */ -async function waitForLockedQuery() { +/** + * Resolves once a backend in this database waits on the transaction holding `blockerPid`, so a + * test can commit the holder mid-request. Scoped to that holder, so another suite's lock waits + * on a shared server never satisfy it. + */ +async function waitForBlockedBy(blockerPid: number) { for (let attempt = 0; attempt < 200; attempt++) { const waiting = await db.execute( - sql`SELECT 1 FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query ILIKE '%credential_group_enrollment%'` + sql`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND ${blockerPid}::int = ANY(pg_blocking_pids(pid))` ) if (waiting.length) return await sleep(25) } - throw new Error('The request never waited on the revocation') + throw new Error('The request never waited on the held transaction') +} + +async function backendPid(executor: Pick): Promise { + const [row] = await executor.execute<{ pid: number }>(sql`SELECT pg_backend_pid() AS pid`) + if (!row) throw new Error('No backend pid') + return row.pid } const enrollmentsFor = (fixture: OrgFixture, email: string) => @@ -562,7 +572,7 @@ describe('request_connection', () => { it('creates one unattributed invited enrollment that names the requesting workflow', async () => { const result = await request(orgA, address('new')) - expect({ requested: result.requested, connectUrl: result.connectUrl }).toEqual({ + expect(result).toEqual({ requested: true, connectUrl: `http://localhost:3000/credential-groups/${orgA.publicId}/connect?provider=${DRIVE_ID}`, }) @@ -584,10 +594,10 @@ describe('request_connection', () => { const [before] = await enrollmentsFor(orgA, address('revoked-request')) const revoked = await request(orgA, address('revoked-request')) const fresh = await request(orgA, address('fresh-request')) - expect({ requested: revoked.requested, connectUrl: revoked.connectUrl }).toEqual({ - requested: fresh.requested, - connectUrl: fresh.connectUrl, - }) + await enroll(orgA, address('known-request')) + const known = await request(orgA, address('known-request')) + expect(revoked).toEqual(fresh) + expect(known).toEqual(fresh) const [after] = await enrollmentsFor(orgA, address('revoked-request')) expect(after).toEqual(before) expect(after?.id).toBe(revokedId) @@ -660,12 +670,30 @@ describe('request_connection input and daily limit', () => { expect(await enrollmentsFor(orgC, address('limit-new'))).toEqual([]) }) + it('counts only requests from the last day toward the limit', async () => { + await request(orgC, address('window-1')) + await request(orgC, address('window-2')) + expect((await refusal(request(orgC, address('window-3')))).code).toBe('conflict') + + const ageAll = (ms: number) => + db + .update(credentialGroupConnectionRequest) + .set({ createdAt: new Date(Date.now() - ms) }) + .where(eq(credentialGroupConnectionRequest.credentialGroupId, orgC.groupId)) + await ageAll(DAY_MS - 60_000) + expect((await refusal(request(orgC, address('window-3')))).code).toBe('conflict') + await ageAll(DAY_MS + 60_000) + await expect(request(orgC, address('window-3'))).resolves.toMatchObject({ requested: true }) + expect(await enrollmentsFor(orgC, address('window-3'))).toHaveLength(1) + }) + it('fails the same way at the limit whatever the target', async () => { await enroll(orgC, address('limit-known')) + await enroll(orgC, address('limit-revoked'), { status: 'revoked', revokedAt: new Date() }) await request(orgC, address('limit-filler-1')) await request(orgC, address('limit-filler-2')) const known = await refusal(request(orgC, address('limit-known'))) - const revoked = await refusal(request(orgC, address('revoked-request'))) + const revoked = await refusal(request(orgC, address('limit-revoked'))) const unknown = await refusal(request(orgC, address('limit-unknown'))) for (const error of [known, revoked]) expect({ code: error.code, message: error.message }).toEqual({ @@ -685,7 +713,7 @@ describe('connection request emails', () => { await request(orgA, email) const [enrollment] = await enrollmentsFor(orgA, email) if (!enrollment) throw new Error('Request created no enrollment') - expect(await emailEvents(enrollment.id)).toHaveLength(1) + expect(await emailEvents(enrollment.id)).toEqual([{ reminder: null }]) await request(orgA, email) expect(await emailEvents(enrollment.id)).toHaveLength(1) for (const expected of [2, 3, 4, 4]) { @@ -693,6 +721,7 @@ describe('connection request emails', () => { await request(orgA, email) expect(await emailEvents(enrollment.id)).toHaveLength(expected) } + expect((await emailEvents(enrollment.id)).filter((event) => event.reminder)).toHaveLength(3) }) it('sends no reminder once the enrollment was requested more than 30 days ago', async () => { @@ -737,6 +766,21 @@ describe('connection request emails', () => { expect(await emailEvents(requested.id)).toHaveLength(2) }) + it('sends one reminder when a workflow asks again several times at once', async () => { + const email = address('reminded-at-once') + await request(orgA, email) + const [enrollment] = await enrollmentsFor(orgA, email) + if (!enrollment) throw new Error('Request created no enrollment') + await ageRequests(orgA, email) + + const results = await Promise.allSettled(Array.from({ length: 4 }, () => request(orgA, email))) + + expect(results.every((result) => result.status === 'fulfilled')).toBe(true) + expect(await emailEvents(enrollment.id)).toHaveLength(2) + const [after] = await enrollmentsFor(orgA, email) + expect(after?.connectionRequestReminders).toBe(1) + }) + it('sends nothing when a revocation commits while the reminder is being claimed', async () => { const email = address('revoke-race') await request(orgA, email) @@ -748,8 +792,8 @@ describe('connection request emails', () => { const held = new Promise((resolve) => { release = resolve }) - let markLocked = () => {} - const locked = new Promise((resolve) => { + let markLocked = (_pid: number) => {} + const locked = new Promise((resolve) => { markLocked = resolve }) const revocation = db.transaction(async (tx) => { @@ -757,12 +801,12 @@ describe('connection request emails', () => { .update(credentialGroupEnrollment) .set({ status: 'revoked', revokedAt: new Date() }) .where(eq(credentialGroupEnrollment.id, enrollment.id)) - markLocked() + markLocked(await backendPid(tx)) await held }) - await locked + const holderPid = await locked const reminder = request(orgA, email) - await waitForLockedQuery() + await waitForBlockedBy(holderPid) release() await revocation expect(await reminder).toMatchObject({ requested: true }) @@ -806,7 +850,7 @@ describe('connection request email delivery', () => { return { email, enrollmentId: enrollment.id } } - async function deliver(enrollmentId: string) { + async function deliver(enrollmentId: string, reminder?: boolean) { const eventId = await enqueueOutboxEvent( db, CONNECTION_REQUEST_EMAIL_EVENT, @@ -816,6 +860,7 @@ describe('connection request email delivery', () => { workflowId: namedWorkflowId, providerName: DRIVE.label, connectUrl: buildCredentialGroupConnectUrl({ publicId: orgA.publicId, provider: DRIVE_ID }), + ...(reminder ? { reminder } : {}), }, { maxAttempts: 3 } ) @@ -845,6 +890,19 @@ describe('connection request email delivery', () => { expect(workflowName.length).toBeLessThanOrEqual(61) }) + it('marks a reminder as one in the subject, still naming only the organization and integration', async () => { + const { email, enrollmentId } = await requestedEnrollment('reminder-subject') + + await deliver(enrollmentId, true) + + expect(mail.sent).toEqual([ + { + to: email, + subject: 'Reminder: Connection requests fixture asked you to connect Google Drive', + }, + ]) + }) + it('records a failed delivery as Email failed, and a later successful one clears it', async () => { const { enrollmentId } = await requestedEnrollment('bounced-request') @@ -1018,6 +1076,50 @@ describe('admin connection request settings', () => { expect((await refusal(save(orgC, off.revision, selected(orgC)))).code).toBe('validation') }) + it('refuses a member who is not an admin, and an admin of another organization, changing nothing', async () => { + const memberId = generateId() + await db.insert(user).values({ + id: memberId, + name: 'Member', + email: `member-${memberId}@${domain}`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }) + people.set(memberId, memberId) + await db.insert(member).values({ + id: generateId(), + organizationId: orgC.organizationId, + userId: memberId, + role: 'member', + createdAt: new Date(), + }) + const as = (userId: string) => createSessionPrincipal({ userId, sessionId: generateId() }) + const input = { organizationId: orgC.organizationId, revision: 0, policy: selected(orgC) } + + for (const userId of [memberId, orgA.adminId]) { + await expect( + updateOrganizationConnectionRequestPolicy.execute({ principal: as(userId), input }) + ).rejects.toBeInstanceOf(OrchestrationError) + await expect( + getOrganizationConnectionRequestPolicy.execute({ + principal: as(userId), + input: { organizationId: orgC.organizationId }, + }) + ).rejects.toBeInstanceOf(OrchestrationError) + } + expect(await requestPolicyRow(orgC)).toEqual([]) + }) + + it('refuses a save from a stale revision, keeping the newer policy', async () => { + const first = await save(orgC, 0, selected(orgC)) + await save(orgC, first.revision, { ...selected(orgC), dailyLimit: 7 }) + + const stale = await refusal(save(orgC, first.revision, { ...selected(orgC), dailyLimit: 9 })) + expect(stale.code).toBe('conflict') + expect((await read(orgC)).policy).toMatchObject({ dailyLimit: 7 }) + }) + it('leaves the Access document untouched, and Access saves leave the request policy alone', async () => { const accessBefore = await accessRow(orgC) await save(orgC, 0, selected(orgC)) diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts index dbf84a00550..89378257898 100644 --- a/apps/sim/lib/credential-groups/application/connect-target.ts +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -24,6 +24,7 @@ import { type CredentialGroupProvider, findCredentialGroupProviderFromProviderId, } from '@/lib/credential-groups/providers' +import { resolveCredentialGroupConnectReturnUrl } from '@/lib/credential-groups/return-url' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import { defineAuthorizedCredentialUserUseCase } from '@/lib/credentials/application/authorized-user-use-case' @@ -48,18 +49,6 @@ const credentialGroupConnectOperations = { }), } as const -/** - * The keyword a connect URL's `return` query may carry. Workflows hold no Slack team or app ID, - * so `slack` opens the Slack app through its generic deep link; nothing else read from the URL is - * a return destination, so a crafted link cannot name one. - */ -const SLACK_RETURN_KEYWORD = 'slack' -const SLACK_APP_RETURN_URL = 'slack://open' - -function resolveReturnUrl(raw: string | undefined): string | undefined { - return raw === SLACK_RETURN_KEYWORD ? SLACK_APP_RETURN_URL : undefined -} - interface CredentialGroupConnectInput { publicId: string /** The credential provider ID the workflow asked for (e.g. `google-drive`). */ @@ -316,7 +305,7 @@ export const startCredentialGroupConnect = defineAuthorizedCredentialUserUseCase provider: decision.provider, } : UNAVAILABLE - const returnUrl = resolveReturnUrl(input.returnUrl) + const returnUrl = resolveCredentialGroupConnectReturnUrl(input.returnUrl) return { kind: 'ready', invitationToken: issued.token, diff --git a/apps/sim/lib/credential-groups/application/connection-requests.ts b/apps/sim/lib/credential-groups/application/connection-requests.ts index 902f702fcb2..ed0ae101c41 100644 --- a/apps/sim/lib/credential-groups/application/connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/connection-requests.ts @@ -1,6 +1,6 @@ import { AuditAction, AuditResourceType } from '@sim/audit' import { isValidEmailSyntax, normalizeEmail } from '@sim/utils/string' -import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' +import { type AuthorizingUseCase, defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' import { OrchestrationError } from '@/lib/core/orchestration/types' import { processOutboxEventById } from '@/lib/core/outbox/service' import { runDetached } from '@/lib/core/utils/background' @@ -180,13 +180,8 @@ interface RecordedRequest extends OrganizationAccountConnectionRequestResult { providerId: string } -/** - * Asks a person to connect one integration on a workflow's behalf. Authority is the - * organization admin's connection request policy, checked here rather than through the - * operation's role: an actorless deployed run has no role to check. Policy refusals are the - * workflow author's configuration problem and say so; per-person outcomes all look the same. - */ -export const requestOrganizationAccountConnection = defineAuthorizedWorkspaceUseCase({ +/** Records the request; its result carries the enrollment only for the audit row. */ +const recordOrganizationAccountConnectionRequest = defineAuthorizedWorkspaceUseCase({ operation: credentialGroupOperations.requestConnection, resolveContext: async ({ input }: { input: OrganizationAccountConnectionInput }) => { const context = await resolveOrganizationAccountsWorkspaceContext(input.workspaceId) @@ -257,3 +252,23 @@ export const requestOrganizationAccountConnection = defineAuthorizedWorkspaceUse }, }), }) + +/** + * Asks a person to connect one integration on a workflow's behalf. Authority is the + * organization admin's connection request policy, checked here rather than through the + * operation's role: an actorless deployed run has no role to check. Policy refusals are the + * workflow author's configuration problem and say so; per-person outcomes all look the same, + * so the result is only the public shape: which enrollment was used, or whether one was + * created, never leaves this module. + */ +export const requestOrganizationAccountConnection: AuthorizingUseCase< + typeof credentialGroupOperations.requestConnection, + OrganizationAccountConnectionInput, + OrganizationAccountConnectionRequestResult +> = { + ...recordOrganizationAccountConnectionRequest, + async execute(args) { + const { requested, connectUrl } = await recordOrganizationAccountConnectionRequest.execute(args) + return { requested, connectUrl } + }, +} diff --git a/apps/sim/lib/credential-groups/connect-url.ts b/apps/sim/lib/credential-groups/connect-url.ts index d17041cc705..df42f57431d 100644 --- a/apps/sim/lib/credential-groups/connect-url.ts +++ b/apps/sim/lib/credential-groups/connect-url.ts @@ -1,10 +1,11 @@ import { getBaseUrl } from '@/lib/core/utils/urls' +import type { CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD } from '@/lib/credential-groups/return-url' interface CredentialGroupConnectPathInput { publicId: string provider: string optionId?: string - /** The raw `return` query value: the keyword `slack` or an allowlisted Slack URL. */ + /** The raw `return` query value; the connect page honours only the keyword `slack`. */ returnValue?: string } @@ -32,7 +33,7 @@ export function buildCredentialGroupConnectUrl({ }: { publicId: string provider: string - returnKey?: 'slack' + returnKey?: typeof CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD }): string { return `${getBaseUrl()}${buildCredentialGroupConnectPath({ publicId, provider, returnValue: returnKey })}` } diff --git a/apps/sim/lib/credential-groups/connection-request-email.ts b/apps/sim/lib/credential-groups/connection-request-email.ts index 0e9cdd009f1..e214cf55447 100644 --- a/apps/sim/lib/credential-groups/connection-request-email.ts +++ b/apps/sim/lib/credential-groups/connection-request-email.ts @@ -35,6 +35,7 @@ function parsePayload(payload: unknown): ConnectionRequestEmailPayload { workflowId: payload.workflowId, providerName: payload.providerName, connectUrl: payload.connectUrl, + reminder: payload.reminder === true, } } @@ -120,6 +121,7 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { subject: getCredentialGroupConnectionRequestSubject({ organizationName: target.organizationName, providerName: payload.providerName, + reminder: payload.reminder, }), html, from: getFromEmailAddress(), diff --git a/apps/sim/lib/credential-groups/connection-request-event.ts b/apps/sim/lib/credential-groups/connection-request-event.ts index 8033c20b1f6..701ad2e97c3 100644 --- a/apps/sim/lib/credential-groups/connection-request-event.ts +++ b/apps/sim/lib/credential-groups/connection-request-event.ts @@ -8,4 +8,6 @@ export interface ConnectionRequestEmailPayload { workflowId: string providerName: string connectUrl: string + /** A repeat request for an enrollment already asked for; its subject reads as a reminder. */ + reminder?: boolean } diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index cff1635b9c8..899a8a9ce4d 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -264,7 +264,7 @@ export async function recordCredentialGroupConnectionRequest(input: { createdAt: now, }) - const enqueueEmail = (enrollmentId: string) => + const enqueueEmail = (enrollmentId: string, reminder: boolean) => enqueueOutboxEvent( tx, CONNECTION_REQUEST_EMAIL_EVENT, @@ -274,6 +274,7 @@ export async function recordCredentialGroupConnectionRequest(input: { workflowId: input.workflowId, providerName: input.providerName, connectUrl: input.connectUrl, + ...(reminder ? { reminder } : {}), }, { maxAttempts: 3 } ) @@ -308,7 +309,7 @@ export async function recordCredentialGroupConnectionRequest(input: { return { enrollmentId: existing.id, created: false, - emailEventId: reminded ? await enqueueEmail(existing.id) : null, + emailEventId: reminded ? await enqueueEmail(existing.id, true) : null, } } @@ -332,7 +333,7 @@ export async function recordCredentialGroupConnectionRequest(input: { return { enrollmentId, created: true, - emailEventId: input.sendEmail ? await enqueueEmail(enrollmentId) : null, + emailEventId: input.sendEmail ? await enqueueEmail(enrollmentId, false) : null, } }) } diff --git a/apps/sim/lib/credential-groups/enrollments.test.ts b/apps/sim/lib/credential-groups/enrollments.test.ts index 8822c073c79..62bb92720d1 100644 --- a/apps/sim/lib/credential-groups/enrollments.test.ts +++ b/apps/sim/lib/credential-groups/enrollments.test.ts @@ -39,7 +39,6 @@ vi.mock('@/lib/credential-groups/availability', () => ({ vi.mock('@/lib/credential-groups/provider-registry', () => credentialGroupsProvidersMock) -import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' import { bindCredentialGroupEnrollmentUser, createCredentialGroupSelfEnrollmentLink, @@ -372,23 +371,6 @@ describe('verified self enrollment', () => { options: [], } - it('permits a token enrollment in an empty canonical group without sending email', async () => { - dbChainMockFns.limit.mockResolvedValueOnce([group]).mockResolvedValueOnce([]) - dbChainMockFns.returning - .mockResolvedValueOnce([ENROLLMENT]) - .mockResolvedValueOnce([{ id: 'link-1' }]) - const result = await createCredentialGroupSelfEnrollmentLink( - 'workspace-1', - 'group-1', - ENROLLMENT.email - ) - expect(result.enrollment.id).toBe(ENROLLMENT.id) - expect(sendEmail).not.toHaveBeenCalled() - expect(dbChainMockFns.values).toHaveBeenCalledWith( - expect.objectContaining({ createdBy: null, email: ENROLLMENT.email }) - ) - }) - it('refuses a disabled group for self enrollment', async () => { dbChainMockFns.limit.mockResolvedValueOnce([{ ...group, groupStatus: 'disabled' }]) await expect( @@ -439,49 +421,6 @@ describe('resendCredentialGroupEnrollment', () => { expect(dbChainMockFns.insert).not.toHaveBeenCalled() expect(sendEmail).not.toHaveBeenCalled() }) - - it('rotates the invitation without hiding credentials from a completed enrollment', async () => { - dbChainMockFns.limit - .mockResolvedValueOnce([ - { - workspaceId: 'workspace-1', - workspaceName: 'Workspace', - groupId: 'group-1', - groupName: 'Group', - groupStatus: 'active', - options: [{ id: 'option-1', status: 'active' }], - }, - ]) - .mockResolvedValueOnce([{ enrollment: ENROLLMENT }]) - .mockResolvedValueOnce([ENROLLMENT]) - .mockResolvedValueOnce([ENROLLMENT]) - dbChainMockFns.returning - .mockResolvedValueOnce([ENROLLMENT]) - .mockResolvedValueOnce([{ id: 'link-1' }]) - .mockResolvedValueOnce([{ ...ENROLLMENT, sentAt: new Date() }]) - vi.mocked(sendEmail).mockResolvedValueOnce({ success: true, message: 'sent' }) - - const result = await resendCredentialGroupEnrollment( - 'workspace-1', - 'group-1', - ENROLLMENT.id, - 'user-1', - 'Inviter', - { optionId: 'option-1', providerName: 'Gmail' } - ) - - expect(renderCredentialGroupInvitationEmail).toHaveBeenCalledWith( - expect.objectContaining({ - searchProviderName: 'Gmail', - invitationLink: expect.stringMatching(/\?optionId=option-1&returnTo=search$/), - }) - ) - expect(result.status).toBe('completed') - expect(dbChainMockFns.set).toHaveBeenNthCalledWith( - 1, - expect.objectContaining({ status: 'completed', completedAt: ENROLLMENT.completedAt }) - ) - }) }) describe('deleteCredentialGroupEnrollment', () => { @@ -529,23 +468,6 @@ describe('enrollment context for session-authorized or consumed-attempt OAuth', beforeEach(() => { resetDbChainMock() }) - it('resolves pinned identity without looking up an invitation bearer', async () => { - queueTableRows(schemaMock.credentialGroupEnrollment, [row]) - expect(await getCredentialGroupOAuthContextForEnrollment(identity, 'option-1')).toMatchObject({ - enrollmentId: identity.enrollmentId, - workspaceId: identity.workspaceId, - email: identity.email, - option: { id: 'option-1' }, - }) - expect(eq).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.id, identity.enrollmentId) - expect(eq).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.email, identity.email) - expect(eq).toHaveBeenCalledWith(schemaMock.credentialGroup.id, identity.credentialGroupId) - expect(eq).toHaveBeenCalledWith(schemaMock.credentialGroup.workspaceId, identity.workspaceId) - expect(eq).not.toHaveBeenCalledWith( - schemaMock.credentialGroupEnrollment.invitationTokenHash, - expect.anything() - ) - }) it.each([ { groupStatus: 'disabled' }, { enrollment: { ...row.enrollment, status: 'revoked' } }, diff --git a/apps/sim/lib/credential-groups/return-url.ts b/apps/sim/lib/credential-groups/return-url.ts index 3aa344844af..5debc292427 100644 --- a/apps/sim/lib/credential-groups/return-url.ts +++ b/apps/sim/lib/credential-groups/return-url.ts @@ -39,6 +39,21 @@ function isSlackAppRedirect(raw: string): boolean { return seen.has('app') || seen.has('channel') } +/** The keyword a stable connect URL's `return` query may carry, set by the Credential block. */ +export const CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD = 'slack' + +/** + * Where a stable connect URL's `return` query sends the person back to. Workflows hold no Slack + * team or app ID, so only the keyword `slack` is honoured, as the Slack app's generic deep link; + * any URL in that query is ignored, so a crafted connect link cannot name a destination. URLs + * the server itself put on an enrollment link go through {@link parseCredentialGroupReturnUrl}. + */ +export function resolveCredentialGroupConnectReturnUrl( + raw: string | undefined +): string | undefined { + return raw === CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD ? SLACK_OPEN : undefined +} + /** Returns the parsed URL when `raw` is an allowed Slack destination, else `null`. */ export function parseCredentialGroupReturnUrl(raw: string): URL | null { if (raw.length === 0 || raw.length > CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH) return null diff --git a/apps/sim/lib/credentials/managed-mcp.test.ts b/apps/sim/lib/credentials/managed-mcp.test.ts index f4ac9dd8008..b9882fc5d70 100644 --- a/apps/sim/lib/credentials/managed-mcp.test.ts +++ b/apps/sim/lib/credentials/managed-mcp.test.ts @@ -1,9 +1,6 @@ import { dbChainMockFns, queueTableRows, resetDbChainMock, schemaMock } from '@sim/testing' import { billingWorkspaceAccessMock } from '@sim/testing/mocks/billing-workspace-access.mock' -import { - credentialGroupsEnrollmentsMock, - credentialGroupsEnrollmentsMockFns, -} from '@sim/testing/mocks/credential-groups-enrollments.mock' +import { credentialGroupsEnrollmentsMock } from '@sim/testing/mocks/credential-groups-enrollments.mock' import { encryptionMock, encryptionMockFns } from '@sim/testing/mocks/encryption.mock' import { workspaceContextMock } from '@sim/testing/mocks/workspace-context.mock' import { eq } from 'drizzle-orm' @@ -21,10 +18,6 @@ import { saveManagedMcpToolSnapshot, } from '@/lib/credentials/managed-mcp' -const mocks = { - lock: credentialGroupsEnrollmentsMockFns.mockLockCredentialGroupEnrollmentLifecycle, -} - encryptionMockFns.mockEncryptSecret.mockResolvedValue({ encrypted: 'encrypted-token-set' }) const input = { @@ -65,13 +58,6 @@ describe('managed MCP grant persistence', () => { async (row) => { queueTableRows(schemaMock.credentialGroupEnrollment, row ? [row] : []) await expect(persistManagedMcpCredential(input)).rejects.toThrow('no longer available') - expect(mocks.lock).toHaveBeenCalledWith(expect.anything(), input.enrollmentId) - expect(eq).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.email, input.email) - expect(eq).toHaveBeenCalledWith( - schemaMock.credentialGroupEnrollment.credentialGroupId, - input.credentialGroupId - ) - expect(dbChainMockFns.for).toHaveBeenCalledWith('update') expect(dbChainMockFns.insert).not.toHaveBeenCalled() expect(dbChainMockFns.update).not.toHaveBeenCalled() } @@ -87,8 +73,6 @@ describe('managed MCP grant persistence', () => { enrollmentStatus: 'in_progress', connectionId: expect.stringMatching(/^mcp-cg-/), }) - expect(eq).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.userId, 'person-1') - expect(eq).toHaveBeenCalledWith(schemaMock.mcpServers.oauthConfigVersion, 2) expect(dbChainMockFns.values).toHaveBeenCalledWith( expect.objectContaining({ organizationId: 'org-1', diff --git a/packages/testing/src/mocks/organization-accounts-queries.mock.ts b/packages/testing/src/mocks/organization-accounts-queries.mock.ts index dd0fa4f6859..313ae1c30ad 100644 --- a/packages/testing/src/mocks/organization-accounts-queries.mock.ts +++ b/packages/testing/src/mocks/organization-accounts-queries.mock.ts @@ -9,6 +9,7 @@ const mutationHook = () => vi.fn((..._args: unknown[]): unknown => createMutatio * * Query hooks (`useOrganizationAccounts`, `useOrganizationDatabricksSetup`, * `useWorkspaceOrganizationAccounts`, `useOrganizationAccountWorkspaceAccess`, + * `usePersonalOrganizationAccounts`, `useOrganizationConnectionRequestPolicy`, * `useOrganizationAccountPeople`) return a fresh {@link createQueryResultMock} (not-yet-fetched: * `data: undefined`, `isPending: true`). Every mutation hook returns a fresh * {@link createMutationResultMock} (`idle`, no-op `mutate`/`reset`, `mutateAsync` resolves @@ -24,6 +25,7 @@ const mutationHook = () => vi.fn((..._args: unknown[]): unknown => createMutatio */ export const organizationAccountsQueriesMockFns = { mockUseReconnectPersonalOrganizationAccount: mutationHook(), + mockUsePersonalOrganizationAccounts: queryHook(), mockUseDisconnectPersonalOrganizationAccount: mutationHook(), mockUseOrganizationAccounts: queryHook(), mockUseEnsureOrganizationAccounts: mutationHook(), @@ -34,6 +36,8 @@ export const organizationAccountsQueriesMockFns = { mockUseWorkspaceOrganizationAccounts: queryHook(), mockUseOrganizationAccountWorkspaceAccess: queryHook(), mockUseUpdateOrganizationAccountWorkspaceAccess: mutationHook(), + mockUseOrganizationConnectionRequestPolicy: queryHook(), + mockUseUpdateOrganizationConnectionRequestPolicy: mutationHook(), mockUseOrganizationAccountPeople: queryHook(), mockUseInviteOrganizationAccountPeople: mutationHook(), mockUseResendOrganizationAccountInvitation: mutationHook(), @@ -55,6 +59,8 @@ export const organizationAccountsQueriesMock = { refreshConnectedAccounts: vi.fn(async () => undefined), useReconnectPersonalOrganizationAccount: organizationAccountsQueriesMockFns.mockUseReconnectPersonalOrganizationAccount, + usePersonalOrganizationAccounts: + organizationAccountsQueriesMockFns.mockUsePersonalOrganizationAccounts, useDisconnectPersonalOrganizationAccount: organizationAccountsQueriesMockFns.mockUseDisconnectPersonalOrganizationAccount, useOrganizationAccounts: organizationAccountsQueriesMockFns.mockUseOrganizationAccounts, @@ -73,6 +79,10 @@ export const organizationAccountsQueriesMock = { organizationAccountsQueriesMockFns.mockUseOrganizationAccountWorkspaceAccess, useUpdateOrganizationAccountWorkspaceAccess: organizationAccountsQueriesMockFns.mockUseUpdateOrganizationAccountWorkspaceAccess, + useOrganizationConnectionRequestPolicy: + organizationAccountsQueriesMockFns.mockUseOrganizationConnectionRequestPolicy, + useUpdateOrganizationConnectionRequestPolicy: + organizationAccountsQueriesMockFns.mockUseUpdateOrganizationConnectionRequestPolicy, useOrganizationAccountPeople: organizationAccountsQueriesMockFns.mockUseOrganizationAccountPeople, useInviteOrganizationAccountPeople: organizationAccountsQueriesMockFns.mockUseInviteOrganizationAccountPeople, From 9809eae2d32bf8ee894df27eb95131d9dbb06bda Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 15:55:50 -0600 Subject: [PATCH 14/26] refactor(credential-groups): simplify and cleanup pass Connect page runs only the start use case (drops the read-only resolve twin), shared helpers for unissued enrollments, revocation, pending workflow requests and no-store redirects, strict same-origin check moved to lib/core/security, lib throws OrchestrationError directly, cleanup job on the cleanup pool, admin modal validates with the policy schema, duplicate error surfaces removed, comment fixes. --- .../connect/[publicId]/route.test.ts | 2 +- .../connect/[publicId]/route.ts | 34 +++------ .../enroll/[token]/mcp/[mcpServerId]/route.ts | 11 ++- .../enroll/[token]/oauth/[optionId]/route.ts | 40 +++++------ .../credential-groups/enrollment-redirect.ts | 33 ++++----- .../[publicId]/connect/page.tsx | 27 ++----- .../app/credential-groups/complete/page.tsx | 9 ++- .../credential-groups/enroll/[token]/page.tsx | 13 ++-- ...anup-credential-group-links.integration.ts | 3 +- .../cleanup-credential-group-links.ts | 11 +-- .../organization-account-people.tsx | 3 +- .../organization-account-providers.test.tsx | 2 + .../organization-connection-requests.tsx | 26 +++---- .../hooks/queries/organization-accounts.ts | 1 + apps/sim/lib/core/security/same-origin.ts | 15 ++++ .../connect-target.integration.ts | 35 +-------- .../application/connect-target.ts | 64 ++++------------- .../application/connection-requests.ts | 28 +++----- .../application/enrollment-link-outcome.ts | 2 +- .../organization-connection-requests.ts | 67 ++++++++--------- .../lib/credential-groups/connect-subject.ts | 25 +++---- .../connection-request-email.ts | 56 +++++++-------- .../credential-groups/connection-requests.ts | 71 ++++++++++--------- apps/sim/lib/credential-groups/enrollments.ts | 23 ++---- apps/sim/lib/credential-groups/links.ts | 38 +++++++++- apps/sim/lib/credential-groups/oauth.ts | 4 +- packages/db/schema.ts | 2 +- 27 files changed, 272 insertions(+), 373 deletions(-) diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts index 94bace40530..40bea5724f1 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts @@ -8,7 +8,7 @@ * explains the outcome); a same-origin post goes through without leaking the minted link through * a cache or a Referer. No GET handler exists, so a link click or prefetch never confirms. */ -import { authMockFns } from '@sim/testing' +import { authMockFns } from '@sim/testing/mocks/auth.mock' import { createMockRequest } from '@sim/testing/mocks/request.mock' import { NextResponse } from 'next/server' import { beforeEach, describe, expect, it, vi } from 'vitest' diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts index 393d7b17188..3060e5e8f76 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts @@ -3,7 +3,7 @@ import { NextResponse } from 'next/server' import { confirmCredentialGroupConnectContract } from '@/lib/api/contracts/credential-groups' import { parseRequest } from '@/lib/api/server' import { getSession } from '@/lib/auth' -import { isSameOrigin } from '@/lib/core/utils/validation' +import { isSameOriginSessionRequest } from '@/lib/core/security/same-origin' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' import { @@ -14,29 +14,11 @@ import { enforcePublicCredentialGroupIpRateLimit, isCredentialGroupConnectUserRateLimited, } from '@/lib/credential-groups/rate-limit' +import { createNoStoreRedirect } from '@/app/api/credential-groups/enrollment-redirect' export const dynamic = 'force-dynamic' export const runtime = 'nodejs' -function seeOther(location: string): NextResponse { - return new NextResponse(null, { - status: 303, - headers: { Location: location, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' }, - }) -} - -/** - * Whether the POST came from a page on this origin. The browser sets `Sec-Fetch-Site` and - * `Origin` and page script cannot forge either, so a cross-site form or a `same-site` sibling - * subdomain cannot enroll the signed-in person. A client that sends neither is refused. - */ -function isSameOriginPost(request: NextRequest): boolean { - const fetchSite = request.headers.get('sec-fetch-site') - if (fetchSite) return fetchSite === 'same-origin' - const origin = request.headers.get('origin') - return origin !== null && isSameOrigin(origin) -} - /** * The connect page's "Connect" button for an organization member with no enrollment: enrolls * them and continues to the focused enrollment page. Any other outcome goes back to the connect @@ -44,7 +26,7 @@ function isSameOriginPost(request: NextRequest): boolean { */ export const POST = withRouteHandler( async (request: NextRequest, context: { params: Promise<{ publicId: string }> }) => { - if (!isSameOriginPost(request)) + if (!isSameOriginSessionRequest(request)) return NextResponse.json( { error: 'Cross-site request refused' }, { status: 403, headers: { 'Cache-Control': 'no-store' } } @@ -64,8 +46,9 @@ export const POST = withRouteHandler( }) const session = await getSession() - if (!session?.user?.emailVerified) return seeOther(connectPath) - if (await isCredentialGroupConnectUserRateLimited(session.user.id)) return seeOther(connectPath) + if (!session?.user?.emailVerified) return createNoStoreRedirect(connectPath, 303) + if (await isCredentialGroupConnectUserRateLimited(session.user.id)) + return createNoStoreRedirect(connectPath, 303) const target = await startCredentialGroupConnect.execute({ principal: { kind: 'session', userId: session.user.id, sessionId: session.session.id }, @@ -78,8 +61,9 @@ export const POST = withRouteHandler( }, request, }) - return seeOther( - target.kind === 'ready' ? buildCredentialGroupConnectHandoffPath(target) : connectPath + return createNoStoreRedirect( + target.kind === 'ready' ? buildCredentialGroupConnectHandoffPath(target) : connectPath, + 303 ) } ) diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts index b4d61d1a8e7..820bfc18b0b 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts @@ -1,7 +1,6 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import type { NextRequest } from 'next/server' -import { NextResponse } from 'next/server' import { startCredentialGroupMcpOAuthContract } from '@/lib/api/contracts/credential-groups' import { parseRequest } from '@/lib/api/server' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' @@ -13,7 +12,10 @@ import { enforcePublicCredentialGroupOAuthStartIpRateLimit, } from '@/lib/credential-groups/rate-limit' import { makeTimedStep } from '@/lib/mcp/oauth' -import { createCredentialGroupEnrollmentRedirect } from '@/app/api/credential-groups/enrollment-redirect' +import { + createCredentialGroupEnrollmentRedirect, + createNoStoreRedirect, +} from '@/app/api/credential-groups/enrollment-redirect' export const dynamic = 'force-dynamic' export const runtime = 'nodejs' @@ -59,10 +61,7 @@ export const GET = withRouteHandler( request, }) ) - const response = NextResponse.redirect(authorizationUrl) - response.headers.set('Cache-Control', 'no-store') - response.headers.set('Referrer-Policy', 'no-referrer') - return response + return createNoStoreRedirect(authorizationUrl) } catch (error) { if (isCredentialGroupLinkFocusError(error)) return backToEnrollment('other_option') logger.error('Failed to start managed MCP OAuth authorization', { diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts index a564e45884e..e72f15c053f 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts @@ -1,7 +1,6 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import type { NextRequest } from 'next/server' -import { NextResponse } from 'next/server' import { startCredentialGroupOAuthContract } from '@/lib/api/contracts/credential-groups' import { parseRequest } from '@/lib/api/server' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' @@ -13,7 +12,10 @@ import { enforceCredentialGroupEnrollmentOAuthRateLimit, enforcePublicCredentialGroupOAuthStartIpRateLimit, } from '@/lib/credential-groups/rate-limit' -import { createCredentialGroupEnrollmentRedirect } from '@/app/api/credential-groups/enrollment-redirect' +import { + createCredentialGroupEnrollmentRedirect, + createNoStoreRedirect, +} from '@/app/api/credential-groups/enrollment-redirect' export const dynamic = 'force-dynamic' export const runtime = 'nodejs' @@ -36,20 +38,16 @@ export const GET = withRouteHandler( ...(returnTo ? { optionId, returnTo } : {}), ...(returnUrl ? { return: returnUrl } : {}), } - if (limited) { - return createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth: 'rate_limited' }) - } + const backToEnrollment = (oauth: string) => + createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth }) + if (limited) return backToEnrollment('rate_limited') const principal = await authenticateCredentialGroupEnrollment(token) - if (!principal) { - return createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth: 'unavailable' }) - } + if (!principal) return backToEnrollment('unavailable') const enrollmentLimited = await enforceCredentialGroupEnrollmentOAuthRateLimit( principal.enrollmentId ) - if (enrollmentLimited) { - return createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth: 'rate_limited' }) - } + if (enrollmentLimited) return backToEnrollment('rate_limited') try { const { authorizationUrl } = await startPublicCredentialGroupOAuth.execute({ @@ -62,23 +60,17 @@ export const GET = withRouteHandler( }, request, }) - const response = NextResponse.redirect(authorizationUrl) - response.headers.set('Cache-Control', 'no-store') - response.headers.set('Referrer-Policy', 'no-referrer') - return response + return createNoStoreRedirect(authorizationUrl) } catch (error) { - if (isCredentialGroupLinkFocusError(error)) - return createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth: 'other_option' }) + if (isCredentialGroupLinkFocusError(error)) return backToEnrollment('other_option') logger.error('Failed to start managed OAuth authorization', { error: getErrorMessage(error), }) - return createCredentialGroupEnrollmentRedirect(token, { - ...focus, - oauth: - error instanceof CredentialGroupOAuthError && error.statusCode === 409 - ? 'configuration_changed' - : 'unavailable', - }) + return backToEnrollment( + error instanceof CredentialGroupOAuthError && error.statusCode === 409 + ? 'configuration_changed' + : 'unavailable' + ) } } ) diff --git a/apps/sim/app/api/credential-groups/enrollment-redirect.ts b/apps/sim/app/api/credential-groups/enrollment-redirect.ts index b4abdb74db0..049fba195a6 100644 --- a/apps/sim/app/api/credential-groups/enrollment-redirect.ts +++ b/apps/sim/app/api/credential-groups/enrollment-redirect.ts @@ -1,24 +1,25 @@ import { NextResponse } from 'next/server' import type { CredentialGroupOAuthFailure } from '@/lib/credential-groups/oauth-completion' -const NO_STORE_REDIRECT_HEADERS = { - 'Cache-Control': 'no-store', - 'Referrer-Policy': 'no-referrer', -} as const +/** + * A redirect that is never cached and sends no referrer, so an enrollment token or an OAuth + * authorization URL in either location never leaks onward. + */ +export function createNoStoreRedirect(location: string, status: 303 | 307 = 307): NextResponse { + return new NextResponse(null, { + status, + headers: { Location: location, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' }, + }) +} export function createCredentialGroupEnrollmentRedirect( token: string, params: Record ): NextResponse { const query = new URLSearchParams(params).toString() - const location = `/credential-groups/enroll/${encodeURIComponent(token)}${query ? `?${query}` : ''}` - return new NextResponse(null, { - status: 307, - headers: { - Location: location, - ...NO_STORE_REDIRECT_HEADERS, - }, - }) + return createNoStoreRedirect( + `/credential-groups/enroll/${encodeURIComponent(token)}${query ? `?${query}` : ''}` + ) } interface CredentialGroupCompletionRedirectOptions { @@ -45,11 +46,5 @@ export function createCredentialGroupCompletionRedirect({ if (completionId) query.set('completionId', completionId) if (organizationId) query.set('organizationId', organizationId) if (completionReturnId) query.set('returnId', completionReturnId) - return new NextResponse(null, { - status: 303, - headers: { - Location: `/credential-groups/complete${query.size ? `?${query}` : ''}`, - ...NO_STORE_REDIRECT_HEADERS, - }, - }) + return createNoStoreRedirect(`/credential-groups/complete${query.size ? `?${query}` : ''}`, 303) } diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index 1edc40f7efa..78c067293d5 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -3,10 +3,7 @@ import type { Metadata } from 'next' import { headers } from 'next/headers' import { redirect } from 'next/navigation' import { getSession } from '@/lib/auth' -import { - resolveCredentialGroupConnectTarget, - startCredentialGroupConnect, -} from '@/lib/credential-groups/application/connect-target' +import { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' import { buildCredentialGroupConnectHandoffPath, buildCredentialGroupConnectPath, @@ -78,10 +75,10 @@ export default async function CredentialGroupConnectPage({ 'metadata' ) if (limited) return - if (!publicId || publicId.length > 128 || !provider || provider.length > 128) - return ( - - ) + const unavailable = ( + + ) + if (!publicId || publicId.length > 128 || !provider || provider.length > 128) return unavailable const callbackUrl = buildCredentialGroupConnectPath({ publicId, provider, optionId, returnValue }) @@ -110,11 +107,7 @@ export default async function CredentialGroupConnectPage({ ...(optionId ? { optionId } : {}), ...(returnValue ? { returnUrl: returnValue } : {}), } - const resolved = await resolveCredentialGroupConnectTarget.execute({ principal, input }) - const target = - resolved.kind === 'connect' - ? await startCredentialGroupConnect.execute({ principal, input }) - : resolved + const target = await startCredentialGroupConnect.execute({ principal, input }) switch (target.kind) { case 'ready': @@ -186,12 +179,6 @@ export default async function CredentialGroupConnectPage({ ) } case 'unavailable': - return ( - - ) + return unavailable } } diff --git a/apps/sim/app/credential-groups/complete/page.tsx b/apps/sim/app/credential-groups/complete/page.tsx index 219adbe252b..a77be880964 100644 --- a/apps/sim/app/credential-groups/complete/page.tsx +++ b/apps/sim/app/credential-groups/complete/page.tsx @@ -26,12 +26,11 @@ export const dynamic = 'force-dynamic' export default async function CredentialGroupCompletePage({ searchParams, }: CredentialGroupCompletePageProps) { - const session = await getSession() + const query = await searchParams + /** Only a stored Slack return is bound to the viewer, so only then is the session read. */ + const session = query.returnId ? await getSession() : null const { failure, completionId, integrationsHref, slackReturnHref } = - await resolveCredentialGroupCompletionView({ - searchParams: await searchParams, - userId: session?.user.id, - }) + await resolveCredentialGroupCompletionView({ searchParams: query, userId: session?.user.id }) const error = failure ? CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure] : undefined /** * Rendered only as links the person clicks: no automatic hop to an external scheme. After a diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index fd4396e6db4..b0deb6ca17e 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -25,7 +25,10 @@ import { CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES } from '@/lib/credential-groups import { CredentialGroupProviderConfigurationError } from '@/lib/credential-groups/provider-adapter' import { getCredentialGroupProviderService } from '@/lib/credential-groups/providers' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' -import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' +import { + CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD, + parseCredentialGroupReturnUrl, +} from '@/lib/credential-groups/return-url' import { APP_ENTRY_PATH, organizationRoutes } from '@/lib/navigation/paths' import { AuthHeader } from '@/app/(auth)/components' import { OAuthConnectLink } from '@/app/credential-groups/enroll/[token]/oauth-reconnect-link' @@ -83,10 +86,6 @@ function EnrollmentLinkProblem({ const recovery = slackReturnUrl ? { recoveryHref: slackReturnUrl, recoveryLabel: 'Return to Slack' } : {} - const organizationName = - 'organizationName' in outcome && outcome.organizationName - ? outcome.organizationName - : 'Your organization' switch (outcome.kind) { case 'wrong_account': return ( @@ -110,7 +109,7 @@ function EnrollmentLinkProblem({ ) @@ -125,7 +124,7 @@ function EnrollmentLinkProblem({ diff --git a/apps/sim/background/cleanup-credential-group-links.integration.ts b/apps/sim/background/cleanup-credential-group-links.integration.ts index b35c87ec69b..68a4200eb31 100644 --- a/apps/sim/background/cleanup-credential-group-links.integration.ts +++ b/apps/sim/background/cleanup-credential-group-links.integration.ts @@ -7,7 +7,7 @@ * deleted early; a row another run has locked stalling this run; one run draining an unbounded * backlog instead of capping its batches. */ -import { db } from '@sim/db' +import { db, dbFor } from '@sim/db' import { credentialGroup, credentialGroupConnectionRequest, @@ -81,6 +81,7 @@ async function insertRequest(groupId: string, createdAt: Date) { afterAll(async () => { await db.delete(organization).where(inArray(organization.id, organizationIds)) + await Promise.all([db.$client.end(), dbFor('cleanup').$client.end()]) }) describe('runCleanupCredentialGroupLinks', () => { diff --git a/apps/sim/background/cleanup-credential-group-links.ts b/apps/sim/background/cleanup-credential-group-links.ts index ace9fe20109..1c976b05451 100644 --- a/apps/sim/background/cleanup-credential-group-links.ts +++ b/apps/sim/background/cleanup-credential-group-links.ts @@ -1,4 +1,4 @@ -import { db } from '@sim/db' +import { dbFor } from '@sim/db' import { credentialGroupConnectionRequest, credentialGroupEnrollment, @@ -9,6 +9,7 @@ import { and, asc, eq, inArray, lt, sql } from 'drizzle-orm' import { DAY_MS } from '@/lib/credential-groups/limits' const logger = createLogger('CleanupCredentialGroupLinks') +const cleanupDb = dbFor('cleanup') /** The daily cap reads one day of the request log; a second day is slack for clock skew. */ const CONNECTION_REQUEST_RETENTION_MS = 2 * DAY_MS @@ -45,12 +46,12 @@ export async function runCleanupCredentialGroupLinks( const link = credentialGroupEnrollmentLink const connectionRequests = await drain(async () => { - const removed = await db + const removed = await cleanupDb .delete(request) .where( inArray( request.id, - db + cleanupDb .select({ id: request.id }) .from(request) .where(lt(request.createdAt, requestCutoff)) @@ -64,12 +65,12 @@ export async function runCleanupCredentialGroupLinks( }) const sessionLinks = await drain(async () => { - const removed = await db + const removed = await cleanupDb .delete(link) .where( inArray( link.id, - db + cleanupDb .select({ id: link.id }) .from(link) .where( diff --git a/apps/sim/ee/credential-groups/components/organization-account-people.tsx b/apps/sim/ee/credential-groups/components/organization-account-people.tsx index 8d35091c8fb..3dc5d658730 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-people.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-people.tsx @@ -65,7 +65,7 @@ export function OrganizationAccountPeople({ organizationId }: OrganizationAccoun const people = useOrganizationAccountPeople(organizationId, search) const [inviteOpen, setInviteOpen] = useState(false) const [revokingPerson, setRevokingPerson] = useState<{ id: string; email: string } | null>(null) - const error = resend.error ?? revoke.error + const error = resend.error const pending = resend.isPending || revoke.isPending const enrollments = people.data?.pages.flatMap((page) => page.enrollments) ?? [] return ( @@ -191,7 +191,6 @@ export function OrganizationAccountPeople({ organizationId }: OrganizationAccoun label: 'Revoke', pendingLabel: 'Revoking…', pending: revoke.isPending, - variant: 'destructive', onClick: () => revoke.mutate( { organizationId, enrollmentId: revokingPerson.id }, diff --git a/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx b/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx index 72e0e8221dc..931f8a73738 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-providers.test.tsx @@ -178,12 +178,14 @@ describe('organization provider configuration UI', () => { const menu = document.querySelector( 'button[aria-label="Integration actions"]' ) + expect(menu).not.toBeNull() await act(async () => menu?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) ) const reapply = [...document.querySelectorAll('[role="menuitem"]')].find( (node) => node.textContent?.trim() === 'Re-apply app configuration' ) + expect(reapply).toBeDefined() await act(async () => reapply?.click()) expect(mocks.update).not.toHaveBeenCalled() await clickButton('Re-apply') diff --git a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx index ebb40f4ae54..d112f259c73 100644 --- a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx +++ b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx @@ -18,6 +18,7 @@ import type { OrganizationConnectionRequestPolicyState } from '@/lib/api/contrac import { CONNECTION_REQUEST_DAILY_LIMIT_DEFAULT, CONNECTION_REQUEST_DAILY_LIMIT_MAX, + connectionRequestPolicySchema, FREE_MAIL_DOMAINS, normalizeConnectionRequestList, } from '@/lib/credential-groups/connection-request-policy' @@ -81,7 +82,8 @@ export function OrganizationConnectionRequests({ setEditing(false) toast.success('Connection requests updated') } catch (error) { - toast.error(getErrorMessage(error, 'Could not update connection requests')) + /** The open modal shows the error itself; only the header switch needs a toast. */ + if (!editing) toast.error(getErrorMessage(error, 'Could not update connection requests')) } } @@ -164,8 +166,16 @@ function ConnectionRequestPolicyModal({ const limit = Number(dailyLimit) const limitValid = Number.isInteger(limit) && limit >= 1 && limit <= CONNECTION_REQUEST_DAILY_LIMIT_MAX - const workspacesValid = workspaces.mode === 'all' || workspaces.workspaceIds.length > 0 - const valid = emailDomains.length > 0 && providers.length > 0 && limitValid && workspacesValid + const draft: Policy = { + enabled: initial?.enabled ?? true, + workspaces, + emailDomains, + providers, + dailyLimit: limit, + sendEmail, + } + /** Held to the rules of an enabled policy either way, so a saved draft can be turned on. */ + const valid = connectionRequestPolicySchema.safeParse({ ...draft, enabled: true }).success return ( - onSave({ - enabled: initial?.enabled ?? true, - workspaces, - emailDomains, - providers, - dailyLimit: limit, - sendEmail, - }), + onClick: () => onSave(draft), }} /> diff --git a/apps/sim/hooks/queries/organization-accounts.ts b/apps/sim/hooks/queries/organization-accounts.ts index 7a49ef21c42..be5aa9ced32 100644 --- a/apps/sim/hooks/queries/organization-accounts.ts +++ b/apps/sim/hooks/queries/organization-accounts.ts @@ -371,6 +371,7 @@ export function useUpdateOrganizationConnectionRequestPolicy() { params: { id: organizationId }, body, }), + /** Also after a refused save, so a stale-revision conflict picks up the current revision. */ onSettled: (_data, _error, { organizationId }) => queryClient.invalidateQueries({ queryKey: organizationAccountsKeys.connectionRequests(organizationId), diff --git a/apps/sim/lib/core/security/same-origin.ts b/apps/sim/lib/core/security/same-origin.ts index 1fb605ef297..1f26bc8478f 100644 --- a/apps/sim/lib/core/security/same-origin.ts +++ b/apps/sim/lib/core/security/same-origin.ts @@ -1,4 +1,5 @@ import type { NextRequest } from 'next/server' +import { isSameOrigin } from '@/lib/core/utils/validation' /** * Returns true when a request is provably cross-site — a browser fetch driven @@ -21,3 +22,17 @@ import type { NextRequest } from 'next/server' export function isCrossSiteSessionRequest(req: NextRequest): boolean { return req.headers.get('sec-fetch-site') === 'cross-site' } + +/** + * The strict counterpart of {@link isCrossSiteSessionRequest}, for a session form POST that + * enrolls or grants something: true only when the browser reports the request came from a page + * on this origin. `Sec-Fetch-Site` and `Origin` are browser-set and page script cannot forge + * either, so a cross-site form or a `same-site` sibling subdomain is refused, and so is a client + * that sends neither. + */ +export function isSameOriginSessionRequest(req: NextRequest): boolean { + const fetchSite = req.headers.get('sec-fetch-site') + if (fetchSite) return fetchSite === 'same-origin' + const origin = req.headers.get('origin') + return origin !== null && isSameOrigin(origin) +} diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index bd6bd302399..9fc28fbaf37 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -34,10 +34,7 @@ import { generateId } from '@sim/utils/id' import { and, eq, inArray, sql } from 'drizzle-orm' import { afterAll, describe, expect, it, vi } from 'vitest' import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' -import { - resolveCredentialGroupConnectTarget, - startCredentialGroupConnect, -} from '@/lib/credential-groups/application/connect-target' +import { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' import { completePublicCredentialGroupEnrollment, completePublicCredentialGroupMcpOAuth, @@ -344,36 +341,6 @@ describe('startCredentialGroupConnect', () => { } }) - it('resolves without binding the person or minting a link', async () => { - const fixture = await createOrganization() - const person = await createPerson() - const enrollment = await inviteCredentialGroupEnrollment( - fixture.scope, - fixture.groupId, - fixture.adminId, - 'Admin', - person.email - ) - - await expect( - resolveCredentialGroupConnectTarget.execute({ - principal: createSessionPrincipal({ userId: person.userId }), - input: { publicId: fixture.publicId, provider: DRIVE_PROVIDER_ID }, - }) - ).resolves.toEqual({ - kind: 'connect', - organizationName: 'Acme', - provider: 'google-drive', - optionId: DRIVE.id, - }) - expect((await enrollmentOf(fixture.groupId, person.email)).userId).toBeNull() - const links = await db - .select() - .from(credentialGroupEnrollmentLink) - .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollment.id)) - expect(links.every((link) => link.purpose !== 'connect')).toBe(true) - }) - it('refuses an enrollment bound to another user as the wrong account', async () => { const fixture = await createOrganization() const person = await createPerson() diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts index 89378257898..9314e614f22 100644 --- a/apps/sim/lib/credential-groups/application/connect-target.ts +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -16,6 +16,7 @@ import { loadCredentialGroupConnectSubject, } from '@/lib/credential-groups/connect-subject' import { maskEnrollmentEmail } from '@/lib/credential-groups/email-mask' +import { isEnrollmentRevoked } from '@/lib/credential-groups/links' import { OrganizationAccountsSetupRequiredError, requireOrganizationAccountsSetup, @@ -30,18 +31,11 @@ import { defineAuthorizedCredentialUserUseCase } from '@/lib/credentials/applica const credentialGroupConnectOperations = { /** + * A member's self-enrollment is held to the Integrations capability by the same check the + * member self-enroll path uses. * permission-group-exempt: the person connecting may be outside the organization; authority is * their own verified email or bound enrollment, never a workspace role. */ - resolve: defineOperation({ - id: 'credential_groups.connect.resolve', - principalKinds: ['session'], - capability: 'none', - }), - /** - * permission-group-exempt: as for `resolve`; a member's self-enrollment is held to the - * Integrations capability by the same check the member self-enroll path uses. - */ start: defineOperation({ id: 'credential_groups.connect.start', principalKinds: ['session'], @@ -66,7 +60,12 @@ interface StartCredentialGroupConnectInput extends CredentialGroupConnectInput { confirmSelfEnrollment?: boolean } -/** A refusal the connect page explains; the same for {@link resolveCredentialGroupConnectTarget} and the start. */ +/** + * A refusal the connect page explains. Every refusal that would reveal whether a group exists, is + * enabled, or offers the provider is the same `unavailable`; the organization is only named once + * the group is known to be active and to offer the provider, since the link holder got the URL + * from that organization. + */ type CredentialGroupConnectRefusal = | { kind: 'unavailable' } | { kind: 'not_invited'; organizationName: string; provider: CredentialGroupProvider } @@ -86,23 +85,6 @@ interface ConfirmSelfEnrollment { optionId: string } -/** - * What the connect page does for the signed-in person. Every refusal that would reveal whether a - * group exists, is enabled, or offers the provider is the same `unavailable`; the organization is - * only named once the group is known to be active and to offer the provider, since the link holder - * got the URL from that organization. `connect` means the person may connect now, which - * {@link startCredentialGroupConnect} does. - */ -type CredentialGroupConnectTarget = - | CredentialGroupConnectRefusal - | ConfirmSelfEnrollment - | { - kind: 'connect' - organizationName: string - provider: CredentialGroupProvider - optionId: string - } - /** What starting a connection did: minted the person's focused link, or why it did not. */ type CredentialGroupConnectStart = | CredentialGroupConnectRefusal @@ -200,7 +182,7 @@ async function decideConnectTarget( organizationName, maskedEmail: maskEnrollmentEmail(enrollment.email), } - if (enrollment && (enrollment.status === 'revoked' || enrollment.revokedAt)) + if (enrollment && isEnrollmentRevoked(enrollment)) return { kind: 'revoked', organizationName, provider } if (!enrollment) { if (!group.organizationId || !(await canSelfEnroll(principal, group.organizationId, group.id))) @@ -243,29 +225,9 @@ async function decideConnectTarget( } /** - * Tells the connect page what the signed-in person may do with a secret-free connect URL, without - * changing anything: a page load, link unfurler, or prefetch that only resolves leaves no trace. - */ -export const resolveCredentialGroupConnectTarget = defineAuthorizedCredentialUserUseCase({ - operation: credentialGroupConnectOperations.resolve, - async execute({ - principal, - input, - }: { - principal: SessionPrincipal - input: CredentialGroupConnectInput - }): Promise { - const decision = await decideConnectTarget(principal, input) - if (decision.kind === 'confirm_self_enrollment') - return omit(decision, ['credentialGroupId', 'organizationId']) - if (decision.kind === 'connect') return omit(decision, ['credentialGroupId', 'enrollment']) - return decision - }, -}) - -/** - * Mints the signed-in person's one-hour link focused on the single matching account option, after - * deciding again what they may do. In one transaction it enrolls a member who confirmed + * Mints the signed-in person's one-hour link focused on the single matching account option, once + * {@link decideConnectTarget} allows it; every refusal and the self-enrollment confirmation come + * back unchanged and write nothing. In one transaction it enrolls a member who confirmed * self-enrollment, binds the person to an enrollment invited at their email, and inserts the link, * so a revocation either lands first (and the person is told the connection is no longer needed) * or kills the new link. Creating or binding an enrollment is audited; minting a link for one diff --git a/apps/sim/lib/credential-groups/application/connection-requests.ts b/apps/sim/lib/credential-groups/application/connection-requests.ts index ed0ae101c41..c9862f08edc 100644 --- a/apps/sim/lib/credential-groups/application/connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/connection-requests.ts @@ -25,7 +25,6 @@ import { connectionRequestRefusal, } from '@/lib/credential-groups/connection-request-policy' import { - ConnectionRequestDailyLimitError, loadConnectionRequestPolicy, loadOrganizationAccountConnectionStatus, type OrganizationAccountConnectionStatus, @@ -211,23 +210,16 @@ const recordOrganizationAccountConnectionRequest = defineAuthorizedWorkspaceUseC provider: input.providerId, returnKey: input.returnTo, }) - let recorded - try { - recorded = await recordCredentialGroupConnectionRequest({ - credentialGroupId: context.credentialGroupId, - email, - workspaceId: context.workspaceId, - workflowId, - providerName: label, - connectUrl, - dailyLimit: policy.dailyLimit, - sendEmail: policy.sendEmail, - }) - } catch (error) { - if (error instanceof ConnectionRequestDailyLimitError) - throw new OrchestrationError('conflict', error.message) - throw error - } + const recorded = await recordCredentialGroupConnectionRequest({ + credentialGroupId: context.credentialGroupId, + email, + workspaceId: context.workspaceId, + workflowId, + providerName: label, + connectUrl, + dailyLimit: policy.dailyLimit, + sendEmail: policy.sendEmail, + }) if (recorded.emailEventId) deliverSoon(recorded.emailEventId) return { requested: true, diff --git a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts index f4d2ea73aea..1f1c157e078 100644 --- a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts +++ b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts @@ -49,7 +49,7 @@ export type CredentialGroupEnrollmentLinkOutcome = /** * Explains a link that failed to open, for the page that shows the person what to do next. Reads * only, and only about the enrollment the link names. A `delivery_failed` enrollment is not an - * outcome: it no longer keeps a live link from opening, so a link that failed is explained by + * outcome: it does not keep a live link from opening, so a link that failed is explained by * what did stop it. */ export const explainCredentialGroupEnrollmentLink = defineAuthorizedCredentialUserUseCase({ diff --git a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts index 6acfc9661e5..4459429e456 100644 --- a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts @@ -11,7 +11,6 @@ import { } from '@/lib/credential-groups/application/workspace-access-policy' import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' import { - ConnectionRequestPolicyConflictError, loadConnectionRequestPolicy, writeConnectionRequestPolicy, } from '@/lib/credential-groups/connection-requests' @@ -50,15 +49,12 @@ async function loadConnectionRequestState(organizationId: string) { }) if (!group) throw new OrchestrationError('not_found', 'Organization connected accounts are not configured') - const [access, stored] = await Promise.all([ - requireResourcePolicy({ - organizationId, - resourceType: 'credential_group', - resourceId: group.credentialGroupId, - codec: organizationAccountAccessPolicyCodec, - }), - loadConnectionRequestPolicy(group.credentialGroupId), - ]) + const access = await requireResourcePolicy({ + organizationId, + resourceType: 'credential_group', + resourceId: group.credentialGroupId, + codec: organizationAccountAccessPolicyCodec, + }) const accessWorkspaceIds = listOrganizationAccountWorkspaceIds(access.document) const workspaces = accessWorkspaceIds.length ? await db @@ -78,7 +74,13 @@ async function loadConnectionRequestState(organizationId: string) { ? [{ id: getCredentialGroupProviderId(option.provider), label: option.label }] : [] ) - return { group, stored, workspaces, providers } + return { + group, + workspaces, + providers, + workspaceIds: new Set(workspaces.map((entry) => entry.id)), + providerIds: new Set(providers.map((provider) => provider.id)), + } } /** @@ -106,18 +108,13 @@ function pruneConnectionRequestPolicy( export const getOrganizationConnectionRequestPolicy = defineOrganizationAccountsUseCase({ operation: organizationConnectionRequestOperations.read, async execute({ context }) { - const { stored, workspaces, providers } = await loadConnectionRequestState( - context.organizationId - ) + const { group, workspaces, providers, workspaceIds, providerIds } = + await loadConnectionRequestState(context.organizationId) + const stored = await loadConnectionRequestPolicy(group.credentialGroupId) return { revision: stored.revision, policy: - stored.policy && - pruneConnectionRequestPolicy( - stored.policy, - new Set(workspaces.map((entry) => entry.id)), - new Set(providers.map((provider) => provider.id)) - ), + stored.policy && pruneConnectionRequestPolicy(stored.policy, workspaceIds, providerIds), workspaces, providers, } @@ -126,9 +123,9 @@ export const getOrganizationConnectionRequestPolicy = defineOrganizationAccounts /** * Saves the admin's policy, as the route contract parsed it (`connectionRequestPolicySchema`: - * normalized lists, and non-empty ones when turned on). Turning requests on requires every chosen workspace to be on the - * Access tab and every integration to be active; turning them off never fails on choices that - * went stale, which are pruned instead. + * normalized lists, and non-empty ones when turned on). Turning requests on requires every + * chosen workspace to be on the Access tab and every integration to be active; turning them off + * never fails on choices that went stale, which are pruned instead. */ export const updateOrganizationConnectionRequestPolicy = defineOrganizationAccountsUseCase({ operation: organizationConnectionRequestOperations.update, @@ -139,11 +136,9 @@ export const updateOrganizationConnectionRequestPolicy = defineOrganizationAccou input: { organizationId: string; revision: number; policy: ConnectionRequestPolicy } context: OrganizationMembershipContext }) { - const { group, workspaces, providers } = await loadConnectionRequestState( + const { group, workspaceIds, providerIds } = await loadConnectionRequestState( context.organizationId ) - const workspaceIds = new Set(workspaces.map((entry) => entry.id)) - const providerIds = new Set(providers.map((provider) => provider.id)) const next = input.policy if (next.enabled) { if (next.providers.some((provider) => !providerIds.has(provider))) @@ -163,19 +158,13 @@ export const updateOrganizationConnectionRequestPolicy = defineOrganizationAccou const policy = next.enabled ? next : pruneConnectionRequestPolicy(next, workspaceIds, providerIds) - try { - const revision = await writeConnectionRequestPolicy({ - credentialGroupId: group.credentialGroupId, - expectedRevision: input.revision, - policy, - actorUserId: context.userId, - }) - return { credentialGroupId: group.credentialGroupId, name: group.name, revision, policy } - } catch (error) { - if (error instanceof ConnectionRequestPolicyConflictError) - throw new OrchestrationError('conflict', error.message) - throw error - } + const revision = await writeConnectionRequestPolicy({ + credentialGroupId: group.credentialGroupId, + expectedRevision: input.revision, + policy, + actorUserId: context.userId, + }) + return { credentialGroupId: group.credentialGroupId, name: group.name, revision, policy } }, projectAudit: (result) => ({ resourceId: result.credentialGroupId, diff --git a/apps/sim/lib/credential-groups/connect-subject.ts b/apps/sim/lib/credential-groups/connect-subject.ts index 0e084f5ef02..a2b10c0efba 100644 --- a/apps/sim/lib/credential-groups/connect-subject.ts +++ b/apps/sim/lib/credential-groups/connect-subject.ts @@ -7,7 +7,6 @@ import { user, workspace, } from '@sim/db/schema' -import { generateId } from '@sim/utils/id' import { normalizeEmail } from '@sim/utils/string' import { and, eq, or } from 'drizzle-orm' import { @@ -15,9 +14,9 @@ import { lockCredentialGroupInvitationTarget, } from '@/lib/credential-groups/enrollments' import { - createUnissuedInvitationTokenHash, - INVITATION_TTL_MS, insertEnrollmentLink, + isEnrollmentRevoked, + unissuedEnrollmentValues, } from '@/lib/credential-groups/links' /** @@ -165,21 +164,14 @@ export async function issueCredentialGroupConnectLink(input: { if (existing) { enrollmentId = existing.id } else { - enrollmentId = generateId() - created = true - await tx.insert(credentialGroupEnrollment).values({ - id: enrollmentId, + const values = unissuedEnrollmentValues({ credentialGroupId: input.credentialGroupId, email: viewerEmail, - status: 'invited', - /** No invitation was emailed; the legacy column names no link. */ - invitationTokenHash: createUnissuedInvitationTokenHash(), - invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), - invitedAt: now, - createdBy: null, - createdAt: now, - updatedAt: now, + now, }) + enrollmentId = values.id + created = true + await tx.insert(credentialGroupEnrollment).values(values) } } else { enrollmentId = input.target.enrollmentId @@ -208,8 +200,7 @@ export async function issueCredentialGroupConnectLink(input: { .limit(1) .for('update', { of: credentialGroupEnrollment }) if (!current) return { issued: false, reason: 'unavailable' } - if (current.status === 'revoked' || current.revokedAt) - return { issued: false, reason: 'revoked' } + if (isEnrollmentRevoked(current)) return { issued: false, reason: 'revoked' } if (current.groupStatus !== 'active') return { issued: false, reason: 'unavailable' } if (current.userId ? current.userId !== input.userId : current.email !== viewerEmail) return { issued: false, reason: 'unavailable' } diff --git a/apps/sim/lib/credential-groups/connection-request-email.ts b/apps/sim/lib/credential-groups/connection-request-email.ts index e214cf55447..c1bed4c7da9 100644 --- a/apps/sim/lib/credential-groups/connection-request-email.ts +++ b/apps/sim/lib/credential-groups/connection-request-email.ts @@ -4,7 +4,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { isRecordLike } from '@sim/utils/object' import { truncate, truncateAtCodePoint } from '@sim/utils/string' -import { and, eq, inArray, isNotNull, isNull, type SQL } from 'drizzle-orm' +import { and, eq, type SQL } from 'drizzle-orm' import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' import { getCredentialGroupConnectionRequestSubject } from '@/components/emails/subjects' import type { OutboxHandler } from '@/lib/core/outbox/service' @@ -12,6 +12,7 @@ import { CONNECTION_REQUEST_EMAIL_EVENT, type ConnectionRequestEmailPayload, } from '@/lib/credential-groups/connection-request-event' +import { pendingWorkflowRequestCondition } from '@/lib/credential-groups/connection-requests' import { sendEmail } from '@/lib/messaging/email/mailer' import { getFromEmailAddress } from '@/lib/messaging/email/utils' @@ -58,11 +59,8 @@ function connectionRequestWorkflowName(name: string | undefined): string { */ function stillRequested(enrollmentId: string, invitedAt: Date): SQL | undefined { return and( - eq(credentialGroupEnrollment.id, enrollmentId), - eq(credentialGroupEnrollment.invitedAt, invitedAt), - inArray(credentialGroupEnrollment.status, ['invited', 'delivery_failed']), - isNull(credentialGroupEnrollment.userId), - isNotNull(credentialGroupEnrollment.requestedByWorkflowId) + pendingWorkflowRequestCondition(enrollmentId), + eq(credentialGroupEnrollment.invitedAt, invitedAt) ) } @@ -79,31 +77,31 @@ function stillRequested(enrollmentId: string, invitedAt: Date): SQL | undefined */ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { const payload = parsePayload(rawPayload) - const [target] = await db - .select({ - email: credentialGroupEnrollment.email, - invitedAt: credentialGroupEnrollment.invitedAt, - organizationName: organization.name, - credentialGroupName: credentialGroup.name, - }) - .from(credentialGroupEnrollment) - .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) - .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) - .where( - and( - eq(credentialGroupEnrollment.id, payload.enrollmentId), - inArray(credentialGroupEnrollment.status, ['invited', 'delivery_failed']), - isNull(credentialGroupEnrollment.userId), - isNotNull(credentialGroupEnrollment.requestedByWorkflowId) + const [[target], [requester]] = await Promise.all([ + db + .select({ + email: credentialGroupEnrollment.email, + invitedAt: credentialGroupEnrollment.invitedAt, + organizationName: organization.name, + credentialGroupName: credentialGroup.name, + }) + .from(credentialGroupEnrollment) + .innerJoin( + credentialGroup, + eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId) + ) + .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) + .where(pendingWorkflowRequestCondition(payload.enrollmentId)) + .limit(1), + db + .select({ name: workflow.name }) + .from(workflow) + .where( + and(eq(workflow.id, payload.workflowId), eq(workflow.workspaceId, payload.workspaceId)) ) - ) - .limit(1) + .limit(1), + ]) if (!target) return - const [requester] = await db - .select({ name: workflow.name }) - .from(workflow) - .where(and(eq(workflow.id, payload.workflowId), eq(workflow.workspaceId, payload.workspaceId))) - .limit(1) const html = await renderCredentialGroupInvitationEmail({ recipientEmail: target.email, diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index 899a8a9ce4d..da70947c812 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -6,7 +6,8 @@ import { credentialGroupEnrollment, } from '@sim/db/schema' import { generateId } from '@sim/utils/id' -import { and, count, eq, gt, inArray, isNotNull, isNull, lt, sql } from 'drizzle-orm' +import { and, count, eq, gt, inArray, isNotNull, isNull, lt, type SQL, sql } from 'drizzle-orm' +import { OrchestrationError } from '@/lib/core/orchestration/types' import { enqueueOutboxEvent } from '@/lib/core/outbox/service' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' import { resourceScopeCondition } from '@/lib/core/resource-scope.server' @@ -24,7 +25,7 @@ import { } from '@/lib/credential-groups/credentials' import { lockCredentialGroupInvitationTarget } from '@/lib/credential-groups/enrollments' import { DAY_MS } from '@/lib/credential-groups/limits' -import { createUnissuedInvitationTokenHash, INVITATION_TTL_MS } from '@/lib/credential-groups/links' +import { unissuedEnrollmentValues } from '@/lib/credential-groups/links' import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' /** Reminders a workflow-requested enrollment may receive after its first email. */ @@ -32,16 +33,22 @@ const CONNECTION_REQUEST_MAX_REMINDERS = 3 /** No reminder goes out for an enrollment requested longer ago than this. */ const CONNECTION_REQUEST_REMINDER_WINDOW_MS = 30 * DAY_MS +/** + * An enrollment that is still a workflow's open request: unbound, never revoked, and not taken + * over by an admin's invitation (which clears `requestedByWorkflowId`). + */ +export function pendingWorkflowRequestCondition(enrollmentId: string): SQL | undefined { + return and( + eq(credentialGroupEnrollment.id, enrollmentId), + inArray(credentialGroupEnrollment.status, ['invited', 'delivery_failed']), + isNull(credentialGroupEnrollment.userId), + isNotNull(credentialGroupEnrollment.requestedByWorkflowId) + ) +} + /** What a workflow may learn about one person and integration. Nothing finer is exposed. */ export type OrganizationAccountConnectionStatus = 'connected' | 'not_connected' | 'needs_reconnect' -export class ConnectionRequestDailyLimitError extends Error { - constructor() { - super('This organization reached its daily limit for workflow connection requests') - this.name = 'ConnectionRequestDailyLimitError' - } -} - /** * Collapses a person's enrollment and credentials for one integration into a workflow-safe * status. `connected` uses the same live-account query as Find Organization Account, so the @@ -118,13 +125,6 @@ export async function loadConnectionRequestPolicy( return { revision: row.revision, policy: storedConnectionRequestPolicySchema.parse(row.policy) } } -export class ConnectionRequestPolicyConflictError extends Error { - constructor() { - super('Connection request settings changed. Reload before saving again.') - this.name = 'ConnectionRequestPolicyConflictError' - } -} - /** * Saves the policy when the stored revision still equals `expectedRevision` (`0` for the first * save), returning the new revision. @@ -166,7 +166,11 @@ export async function writeConnectionRequestPolicy(input: { ) .returning({ revision: credentialGroupConnectionRequestPolicy.revision }) const [row] = written - if (!row) throw new ConnectionRequestPolicyConflictError() + if (!row) + throw new OrchestrationError( + 'conflict', + 'Connection request settings changed. Reload before saving again.' + ) return row.revision } @@ -190,8 +194,9 @@ interface RecordedConnectionRequest { * Only an absent enrollment is created. An existing one keeps its status and attribution: a * revoked person stays revoked, an admin's invitation stays the admin's, and a connected person * stays connected. The only write to an existing row is a reminder on an unbound, still-invited - * enrollment a workflow created (including one whose last email failed): when nobody asked for this address in the last day, the - * enrollment was requested within the last 30 days, and it has had fewer than + * enrollment a workflow created (including one whose last email failed): when nobody asked for + * this address in the last day, the enrollment was requested within + * {@link CONNECTION_REQUEST_REMINDER_WINDOW_MS}, and it has had fewer than * {@link CONNECTION_REQUEST_MAX_REMINDERS} reminders. That update re-checks the row's state, so a * revocation committed meanwhile sends nothing. * @@ -226,7 +231,11 @@ export async function recordCredentialGroupConnectionRequest(input: { gt(credentialGroupConnectionRequest.createdAt, dayAgo) ) ) - if ((recent?.total ?? 0) >= input.dailyLimit) throw new ConnectionRequestDailyLimitError() + if ((recent?.total ?? 0) >= input.dailyLimit) + throw new OrchestrationError( + 'conflict', + 'This organization reached its daily limit for workflow connection requests' + ) await lockCredentialGroupInvitationTarget(tx, input.credentialGroupId, input.email) const [[askedToday], [existing]] = await Promise.all([ @@ -291,10 +300,7 @@ export async function recordCredentialGroupConnectionRequest(input: { }) .where( and( - eq(credentialGroupEnrollment.id, existing.id), - inArray(credentialGroupEnrollment.status, ['invited', 'delivery_failed']), - isNull(credentialGroupEnrollment.userId), - isNotNull(credentialGroupEnrollment.requestedByWorkflowId), + pendingWorkflowRequestCondition(existing.id), lt( credentialGroupEnrollment.connectionRequestReminders, CONNECTION_REQUEST_MAX_REMINDERS @@ -313,23 +319,18 @@ export async function recordCredentialGroupConnectionRequest(input: { } } - const enrollmentId = generateId() - await tx.insert(credentialGroupEnrollment).values({ - id: enrollmentId, + const values = unissuedEnrollmentValues({ credentialGroupId: input.credentialGroupId, email: input.email, - status: 'invited', + now, + }) + await tx.insert(credentialGroupEnrollment).values({ + ...values, /** No invitation link is issued: the person signs in on the connect page instead. */ - invitationTokenHash: createUnissuedInvitationTokenHash(), - /** The admin invitation lifetime, so an unbound requested enrollment ages out alike. */ - invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), - invitedAt: now, sentAt: input.sendEmail ? now : null, - createdBy: null, requestedByWorkflowId: input.workflowId, - createdAt: now, - updatedAt: now, }) + const enrollmentId = values.id return { enrollmentId, created: true, diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 4732ff80622..bf31aa05759 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -28,12 +28,13 @@ import { getBaseUrl } from '@/lib/core/utils/urls' import { moreUsableAccount } from '@/lib/credential-groups/account-rules' import { adoptLegacyInvitationLink, - createUnissuedInvitationTokenHash, hashInvitationToken, INVITATION_TTL_MS, insertEnrollmentLink, + isEnrollmentRevoked, liveEnrollmentLinkCondition, revokeCredentialGroupEnrollmentLinks, + unissuedEnrollmentValues, } from '@/lib/credential-groups/links' import type { ManagedMcpConnectorId } from '@/lib/credential-groups/managed-mcp-connectors' import { getManagedMcpConnector } from '@/lib/credential-groups/managed-mcp-connectors' @@ -289,7 +290,7 @@ async function loadLiveEnrollmentRow(scope: SQL | undefined) { .limit(1) if (!row || row.groupStatus !== 'active') return null - if (row.enrollment.status === 'revoked' || row.enrollment.revokedAt) return null + if (isEnrollmentRevoked(row.enrollment)) return null const ownerScope = resourceScopeFromOwner(row) if (!(await isScopedCredentialGroupsAvailable(ownerScope))) return null @@ -576,7 +577,7 @@ async function issueInvitation( * links into an enrollment it revoked may still be unrevoked, and none of them may survive * a reinvitation. */ - if (current.status === 'revoked' || current.revokedAt) + if (isEnrollmentRevoked(current)) await revokeCredentialGroupEnrollmentLinks(tx, current.id, now) } @@ -639,26 +640,14 @@ async function issueSelfEnrollmentLink( return db.transaction(async (tx) => { const now = new Date() const current = await lockInvitationEnrollment(tx, groupId, email) - if (current?.status === 'revoked' || current?.revokedAt) { + if (current && isEnrollmentRevoked(current)) { throw new CredentialGroupEnrollmentError('Revoked enrollment cannot be resent', 409) } const [enrollment] = current ? [current] : await tx .insert(credentialGroupEnrollment) - .values({ - id: generateId(), - credentialGroupId: groupId, - email, - status: 'invited', - /** No invitation was emailed; the legacy column names no link. */ - invitationTokenHash: createUnissuedInvitationTokenHash(), - invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), - invitedAt: now, - createdBy: null, - createdAt: now, - updatedAt: now, - }) + .values(unissuedEnrollmentValues({ credentialGroupId: groupId, email, now })) .returning() if (!enrollment) throw new Error('Credential group enrollment insert returned no row') const { token } = await insertEnrollmentLink(tx, { diff --git a/apps/sim/lib/credential-groups/links.ts b/apps/sim/lib/credential-groups/links.ts index 6ef476d7b78..9dedc605ddc 100644 --- a/apps/sim/lib/credential-groups/links.ts +++ b/apps/sim/lib/credential-groups/links.ts @@ -69,6 +69,40 @@ function isUnissuedInvitationTokenHash(value: string): boolean { return value.startsWith(UNISSUED_INVITATION_PREFIX) } +/** + * Insert values for an enrollment created without an emailed link (member self-enrollment, the + * connect page, or a workflow's connection request). It waits for its person as long as an + * emailed invitation would, so an unbound enrollment ages out alike. + */ +export function unissuedEnrollmentValues(input: { + credentialGroupId: string + email: string + now: Date +}) { + return { + id: generateId(), + credentialGroupId: input.credentialGroupId, + email: input.email, + status: 'invited', + invitationTokenHash: createUnissuedInvitationTokenHash(), + invitationExpiresAt: new Date(input.now.getTime() + INVITATION_TTL_MS), + invitedAt: input.now, + createdBy: null, + createdAt: input.now, + updatedAt: input.now, + } satisfies typeof credentialGroupEnrollment.$inferInsert +} + +/** + * Whether an admin revoked the enrollment. Status is authoritative while an app that revokes by + * status alone may still be deployed, so either marker counts. + */ +export function isEnrollmentRevoked( + enrollment: Pick +): boolean { + return enrollment.status === 'revoked' || enrollment.revokedAt !== null +} + /** * Whether a link is past its expiry: the TypeScript form of the rule * {@link liveEnrollmentLinkCondition} applies in SQL. An emailed link never expires once its @@ -163,7 +197,7 @@ export async function adoptLegacyInvitationLink( tokenHash: current.invitationTokenHash, purpose: 'email', expiresAt: current.invitationExpiresAt, - revokedAt: current.status === 'revoked' || current.revokedAt ? now : null, + revokedAt: isEnrollmentRevoked(current) ? now : null, createdAt: current.invitedAt, }) .onConflictDoNothing({ target: credentialGroupEnrollmentLink.tokenHash }) @@ -330,7 +364,7 @@ export async function findCredentialGroupEnrollmentLinkRecord( { purpose, expiresAt: row.linkExpiresAt ?? row.legacyExpiresAt }, row.userId !== null ), - revoked: row.status === 'revoked' || row.revokedAt !== null, + revoked: isEnrollmentRevoked(row), linkRevoked: row.linkRevokedAt !== null, groupActive: row.groupStatus === 'active', organizationName: row.organizationName ?? row.workspaceName ?? '', diff --git a/apps/sim/lib/credential-groups/oauth.ts b/apps/sim/lib/credential-groups/oauth.ts index 1a6d85d513c..26ed05208dc 100644 --- a/apps/sim/lib/credential-groups/oauth.ts +++ b/apps/sim/lib/credential-groups/oauth.ts @@ -18,7 +18,7 @@ import { lockCredentialGroupEnrollmentLifecycle, } from '@/lib/credential-groups/enrollments' import { CREDENTIAL_GROUP_ACCOUNTS_PER_PROVIDER_LIMIT } from '@/lib/credential-groups/limits' -import { liveEnrollmentLinkCondition } from '@/lib/credential-groups/links' +import { isEnrollmentRevoked, liveEnrollmentLinkCondition } from '@/lib/credential-groups/links' import type { CredentialGroupConnectionIntent } from '@/lib/credential-groups/oauth-intent' import { type CredentialGroupOAuthAttempt, @@ -190,7 +190,7 @@ async function persistGrant( ) ) .limit(1) - if (!enrollment || enrollment.status === 'revoked' || enrollment.revokedAt) { + if (!enrollment || isEnrollmentRevoked(enrollment)) { throw new CredentialGroupInvitationUnavailableError() } diff --git a/packages/db/schema.ts b/packages/db/schema.ts index 663c8cd455d..28f2860f463 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7429,7 +7429,7 @@ export const credentialGroupEnrollment = pgTable( revokedAt: timestamp('revoked_at'), lastDeliveryError: text('last_delivery_error'), createdBy: text('created_by').references(() => user.id, { onDelete: 'set null' }), - /** Set when a workflow's connection request created the row; admin invitations leave it null. */ + /** Set when a workflow's connection request created the row; an admin invitation clears it. */ requestedByWorkflowId: text('requested_by_workflow_id'), /** Reminder emails sent for a workflow-requested enrollment after its first invitation. */ connectionRequestReminders: integer('connection_request_reminders').notNull().default(0), From fd9b1e0a8f7ab696b3a66b17d9f651e66744a762 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 16:17:06 -0600 Subject: [PATCH 15/26] feat(credential-groups): lane E connect states, people statuses, policy UX, docs - Connect page: presentational states in link-states (ConnectConfirm, DifferentEmail, NotInvited with Switch account, RequestExpired, VerifyEmail, ChooseConnectOption) and a shared action row that pairs Return to Slack with "You can close this tab." - Enroll page: a focused connect link opened by someone already connected shows "{Integration} connected"; Slack returns use the shared action row - People: Invited/Requested/Expired/Email failed/Not connected/Connected/Needs reconnect/ Revoked, Requested by workflow marker, reminder while any active option lacks a connection, Re-invite on revoked rows - Workflow requests policy: close modal and toast on revision conflict, header switch opens the editor when the saved policy cannot be enabled, Not in effect badge, inline domain errors, labelled toggle, loading skeleton, All allowed workspaces - Contracts: requestedByWorkflow/emailed on People rows, inEffect on the policy read - Docs: when Sim emails, lower-cased event email, listen for added and reconnected, member-only status links, Find returns the first match, editor runs are real, policy is the only request gate, Return to Slack opens the app --- .../docs/platform/connected-accounts.mdx | 19 +- .../docs/workflows/blocks/credential.mdx | 20 +- .../[publicId]/connect/page.tsx | 104 ++++---- .../app/credential-groups/complete/page.tsx | 17 +- .../credential-groups/enroll/[token]/page.tsx | 73 ++++-- .../sim/app/credential-groups/link-states.tsx | 237 +++++++++++++++++- .../organization-account-people.tsx | 140 +++++++---- .../organization-account-providers.tsx | 5 +- .../organization-connection-requests.tsx | 92 ++++--- .../lib/api/contracts/credential-groups.ts | 4 + .../api/contracts/organization-accounts.ts | 2 + 11 files changed, 527 insertions(+), 186 deletions(-) diff --git a/apps/docs/content/docs/platform/connected-accounts.mdx b/apps/docs/content/docs/platform/connected-accounts.mdx index 819f6408127..27145b429e5 100644 --- a/apps/docs/content/docs/platform/connected-accounts.mdx +++ b/apps/docs/content/docs/platform/connected-accounts.mdx @@ -29,7 +29,7 @@ Open the organization's **Settings → Credential Groups**. If no pool exists, s ### 1. Add integrations -In **Integrations**, select **Add integration**, search the catalog, and complete any required setup. Use **Configure** to change an added provider's settings, **Copy connect link** in its menu to share a link people open to connect it, or **Remove** in its menu to remove it. +In **Integrations**, select **Add integration**, search the catalog, and complete any required setup. Use **Configure** to change an added provider's settings, **Copy connect link** in its menu to share a link people open to connect it, or **Remove** in its menu to remove it. A copied link works for organization members and for people you or a workflow asked to connect; anyone else is told no connection was requested. | Provider | Required organization setup | | --- | --- | @@ -62,7 +62,22 @@ On first use, the invitation email must match the signed-in user's verified Sim The verified Sim user who starts authorization must complete it. The provider account may have a different email; its contribution belongs to the bound Sim user. Managed MCP connections use that person's authorization too. Search separately checks current provider identity and source-specific access requirements. -Use **Send reminder** in a person's menu when they need the invitation again. **Revoke** stops the organization from using their contributions. They cannot undo an administrator's revocation by reconnecting themselves. +Each person shows one status: + +| Status | Meaning | +| --- | --- | +| **Invited** | Sim emailed a request the person has not accepted yet | +| **Requested** | A workflow asked, but Sim did not email the person | +| **Expired** | The request went unaccepted for 7 days; send a reminder to renew it | +| **Email failed** | Sim could not deliver the request email | +| **Not connected** | The person accepted but has no connected account | +| **Connected** | At least one account is connected | +| **Needs reconnect** | An account stopped working and must be reconnected | +| **Revoked** | An admin revoked the person | + +People asked by a workflow are also marked **Requested by workflow**. + +Use **Send reminder** in a person's menu while any integration they were asked for is not connected; it also renews an expired request. A reminder for a workflow's request stays attributed to the workflow. **Revoke** stops the organization from using their contributions. They cannot undo an administrator's revocation by reconnecting themselves; use **Re-invite** to ask them again. ### 3. Grant workspace access diff --git a/apps/docs/content/docs/workflows/blocks/credential.mdx b/apps/docs/content/docs/workflows/blocks/credential.mdx index 67d5ac1d4fa..497d8fa139a 100644 --- a/apps/docs/content/docs/workflows/blocks/credential.mdx +++ b/apps/docs/content/docs/workflows/blocks/credential.mdx @@ -26,11 +26,11 @@ A credential ID is a reference, not a token. The downstream block resolves and a | --- | --- | | **Select Credential** | Return one workspace OAuth credential reference. | | **List Credentials** | Return workspace OAuth credential references, optionally filtered by integrations. | -| **Find Organization Account** | Find exactly one active OAuth contribution by invitation email and integration. | +| **Find Organization Account** | Find the first active OAuth contribution matching an invitation email and integration. | | **List Organization Accounts** | Page through active OAuth contributions, optionally filtered by email and integrations. | | **Get Connection Status** | Report whether a person has connected an integration, with a link they can open to connect it. | | **Request Connection** | Ask a person to connect an integration, when an organization admin allows workflow requests. | -| **Find Organization MCP Connection** | Find exactly one active managed MCP connection by invitation email and MCP provider. | +| **Find Organization MCP Connection** | Find the first active managed MCP connection matching an invitation email and MCP provider. | | **List Organization MCP Connections** | Page through active managed MCP connections, optionally filtered by email and provider. | These operations do not select secrets or service accounts. Function can read a returned ID string, but does not automatically resolve it to a token. @@ -62,7 +62,7 @@ Authorized workflows in an allowed workspace can discover active contributions f List **Limit** defaults to 100 and accepts 1–100. **Cursor** accepts the previous page's `nextCursor` with the same filters. The block does not fetch all pages automatically. -Find fails unless exactly one active connection matches. List returns empty results when none match. Disconnected accounts, revoked invitations, and accounts needing reconnection are excluded; multiple accounts contributed by one person stay separate. +Find returns the first active connection that matches and fails when none do; use List when a person may have contributed more than one account. List returns empty results when none match. Disconnected accounts, revoked invitations, and accounts needing reconnection are excluded; multiple accounts contributed by one person stay separate. ## Outputs @@ -103,11 +103,17 @@ For example, name the block **Account**, choose Find Organization Account, set E The status never says whether the person was invited, removed, or never asked. `connectUrl` carries no secret: the page checks that the signed-in person is the one with that email before anything is connected, so it is safe to post, for example as a Slack button. -When `connected` is false, call **Request Connection** first (or make sure an admin invited the person), then show `connectUrl`. +A `connectUrl` from Get Connection Status alone works only for members of your organization. Anyone else must be asked first, by **Request Connection** or by an admin in **People**; otherwise the page tells them no connection was requested. So when `connected` is false, call **Request Connection** first, then show `connectUrl`. -Set **Return to** to **Slack** when the person starts in Slack: once their account is connected, the page offers a **Return to Slack** button that opens the Slack app. With **None** the page tells them they can close the tab. +Set **Return to** to **Slack** when the person starts in Slack: once their account is connected, the page offers a **Return to Slack** button. It opens the Slack app, so someone using Slack in a browser instead closes the tab, and the page says so. With **None** the page tells them they can close the tab. -**Request Connection** returns `requested` and `connectUrl`. It works only when an admin turns on **Allow workflow requests** under **Workflow connection requests** in **Settings → Credential Groups → Access**, for the workflow's workspace, the person's email domain, and the integration. A request outside those settings, or past the daily limit, fails with an error. Otherwise the result is the same whether the person was already asked, already connected, or removed; a removed person is never re-invited. Use the person's primary address: an address with a `+` alias is refused. The daily limit counts every accepted request across all workspaces, including repeat requests for the same person. When the admin chose to also email the person, Sim emails the link with the workflow's name. It sends up to 3 reminders, each only when a workflow asks again after a day with no request for that person, and none after 30 days. +**Request Connection** returns `requested` and `connectUrl`. It works only when an admin turns on **Allow workflow requests** under **Workflow connection requests** in **Settings → Credential Groups → Access**, for the workflow's workspace, the person's email domain, and the integration. That setting is the only gate: any run of the workflow can request a connection, including a manual run by a workspace member with read access. A request outside those settings, or past the daily limit, fails with an error. Otherwise the result is the same whether the person was already asked, already connected, or removed; a removed person is never re-invited. Use the person's primary address: an address with a `+` alias is refused. + +The daily limit counts each new person asked per day, across all workspaces; asking again for someone already asked that day does not count. A request the person has not accepted expires after 7 days; asking again renews it. + +Sim emails the person only when the admin turned on **Also email the person**. The email carries the link and the workflow's name. Sim sends up to 3 reminders, each only when a workflow asks again after a day with no request for that person, and none after 30 days. Runs from the workflow editor are real: they send real emails and count toward the daily limit. + +To continue once the person connects, deploy a workflow listening for both **Credential Added** and **Credential Reconnected**: someone who connected before and was then disconnected comes back as a reconnection. ### Managed MCP @@ -149,7 +155,7 @@ Switch the block to trigger mode, select an **Event**, and deploy in an allowed | Credential Reconnected | Existing contribution reconnected | | Account Connections Submitted | Connection form submitted | -Events include `event`, `timestamp`, `email`, `enrollmentId`, `enrollmentStatus`, `credentialGroupId`, and `credentialGroupName`. Added/reconnected events also include account details such as `credentialId`, `provider`, and `displayName`; `mcpServerId` identifies shared MCP configuration and is null for OAuth accounts. +Events include `event`, `timestamp`, `email` (lower-cased), `enrollmentId`, `enrollmentStatus`, `credentialGroupId`, and `credentialGroupName`. Added/reconnected events also include account details such as `credentialId`, `provider`, and `displayName`; `mcpServerId` identifies shared MCP configuration and is null for OAuth accounts. Every deployed workflow selecting that event in an allowed workspace can receive it. Removing workspace access stops later delivery. Replace legacy Credential Group blocks with Credential; they are not automatically converted. diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index 78c067293d5..9b384a6cfaa 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -1,4 +1,3 @@ -import { AuthButton as Chip, AuthLinkButton as ChipLink } from '@sim/auth-ui' import type { Metadata } from 'next' import { headers } from 'next/headers' import { redirect } from 'next/navigation' @@ -14,10 +13,12 @@ import { isCredentialGroupConnectUserRateLimited, } from '@/lib/credential-groups/rate-limit' import { resolveCredentialGroupConnectReturnUrl } from '@/lib/credential-groups/return-url' -import { AuthHeader } from '@/app/(auth)/components' import { - CredentialGroupPageShell, + ChooseConnectOption, + ConnectConfirm, + NotInvited, UnavailableInvitation, + VerifyEmail, WrongAccount, } from '@/app/credential-groups/link-states' @@ -66,9 +67,6 @@ export default async function CredentialGroupConnectPage({ const optionId = getSearchParam(query, 'optionId') const returnValue = getSearchParam(query, 'return') const slackReturnHref = resolveCredentialGroupConnectReturnUrl(returnValue) - const recovery = slackReturnHref - ? { recoveryHref: slackReturnHref, recoveryLabel: 'Return to Slack' } - : {} const limited = await enforcePublicCredentialGroupIpRateLimit( { headers: await headers() }, @@ -76,7 +74,11 @@ export default async function CredentialGroupConnectPage({ ) if (limited) return const unavailable = ( - + ) if (!publicId || publicId.length > 128 || !provider || provider.length > 128) return unavailable @@ -85,14 +87,7 @@ export default async function CredentialGroupConnectPage({ const session = await getSession() if (!session?.user) redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) if (!session.user.emailVerified) - return ( - - ) + return if (await isCredentialGroupConnectUserRateLimited(session.user.id)) return @@ -117,67 +112,56 @@ export default async function CredentialGroupConnectPage({ ) case 'confirm_self_enrollment': { - const integration = getCredentialGroupProviderService(target.provider).name const confirmQuery = new URLSearchParams({ provider, optionId: target.optionId }) if (returnValue) confirmQuery.set('return', returnValue) return ( - - - - - Connect {integration} - - - + ) } - case 'not_invited': { - const integration = getCredentialGroupProviderService(target.provider).name + case 'not_invited': return ( - ) - } case 'revoked': return ( - + ) - case 'choose_option': { - const integration = getCredentialGroupProviderService(target.provider).name + case 'choose_option': return ( - - -
- {target.options.map((option) => ( - - {option.label} - - ))} -
-
+ ({ + ...option, + href: buildCredentialGroupConnectPath({ + publicId, + provider, + optionId: option.id, + returnValue, + }), + }))} + slackHref={slackReturnHref} + /> ) - } case 'unavailable': return unavailable } diff --git a/apps/sim/app/credential-groups/complete/page.tsx b/apps/sim/app/credential-groups/complete/page.tsx index a77be880964..8443f9dfe44 100644 --- a/apps/sim/app/credential-groups/complete/page.tsx +++ b/apps/sim/app/credential-groups/complete/page.tsx @@ -6,6 +6,7 @@ import { APP_ENTRY_PATH } from '@/lib/navigation/paths' import { AuthHeader, AuthShell } from '@/app/(auth)/components' import { CredentialGroupCompletionHandoff } from '@/app/credential-groups/complete/completion-handoff' import { resolveCredentialGroupCompletionView } from '@/app/credential-groups/complete/completion-view' +import { CredentialGroupLinkActions } from '@/app/credential-groups/link-states' interface CredentialGroupCompletePageProps { searchParams: Promise> @@ -45,11 +46,6 @@ export default async function CredentialGroupCompletePage({ {integrationsHref ? (error ? 'Try again' : 'Return to Integrations') : 'Open Sim'}
) : null - const slackLink = slackReturnHref ? ( - - Return to Slack - - ) : null return ( {completionId && ( @@ -70,11 +66,14 @@ export default async function CredentialGroupCompletePage({ : 'Your accounts are ready to use. You can close this tab.') } /> - {(appLink || slackLink) && ( -
+ {(appLink || slackReturnHref) && ( + {appLink} - {slackLink} -
+ )}
) diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index b0deb6ca17e..79640ea2ec0 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -34,6 +34,7 @@ import { AuthHeader } from '@/app/(auth)/components' import { OAuthConnectLink } from '@/app/credential-groups/enroll/[token]/oauth-reconnect-link' import { CredentialGroupOAuthToast } from '@/app/credential-groups/enroll/[token]/oauth-toast' import { + CredentialGroupLinkActions, CredentialGroupPageShell as PageShell, UnavailableInvitation, WrongAccount, @@ -83,9 +84,6 @@ function EnrollmentLinkProblem({ fallbackMessage, slackReturnUrl, }: EnrollmentLinkProblemProps) { - const recovery = slackReturnUrl - ? { recoveryHref: slackReturnUrl, recoveryLabel: 'Return to Slack' } - : {} switch (outcome.kind) { case 'wrong_account': return ( @@ -93,6 +91,7 @@ function EnrollmentLinkProblem({ token={token} description={`You’re signed in as ${signedInEmail}. This link is for ${outcome.maskedEmail}.`} callbackUrl={callbackUrl} + slackHref={slackReturnUrl} /> ) case 'revoked': @@ -101,7 +100,7 @@ function EnrollmentLinkProblem({ token={token} title='Connection no longer needed' message={null} - {...recovery} + slackHref={slackReturnUrl} /> ) case 'paused': @@ -110,7 +109,7 @@ function EnrollmentLinkProblem({ token={token} title='Connections paused' message={`${outcome.organizationName || 'Your organization'} isn’t collecting account connections right now.`} - {...recovery} + slackHref={slackReturnUrl} /> ) case 'reopen': @@ -119,8 +118,7 @@ function EnrollmentLinkProblem({
-
- {slackReturnUrl && Return to Slack} + Start again -
+
) @@ -140,13 +138,15 @@ function EnrollmentLinkProblem({ token={token} title={outcome.reason === 'expired' ? 'Link expired' : 'Link no longer active'} message={needsNewLinkCopy(outcome)} - {...recovery} + slackHref={slackReturnUrl} /> ) case 'unavailable': - return + return ( + + ) case 'unknown': - return + return } } @@ -154,12 +154,14 @@ interface UnavailableSearchConnectionProps { token: string returnHref: string returnLabel: string + slackHref?: string } function UnavailableSearchConnection({ token, returnHref, returnLabel, + slackHref, }: UnavailableSearchConnectionProps) { return ( @@ -168,9 +170,13 @@ function UnavailableSearchConnection({ title='Connection unavailable' description='Ask an admin to check this source’s connected account settings, then start a new connection.' /> -
- {returnLabel} -
+ + {!slackHref && {returnLabel}} +
) } @@ -303,6 +309,7 @@ export default async function CredentialGroupEnrollmentPage({ token={token} returnHref={returnHref} returnLabel={returnLabel} + slackHref={slackReturnUrl} /> ) @@ -326,12 +333,18 @@ export default async function CredentialGroupEnrollmentPage({ token={token} returnHref={returnHref} returnLabel={returnLabel} + slackHref={slackReturnUrl} /> ) const visibleOptions = focusedOption ? [focusedOption] : activeOptions + const focusedAccounts = + focusedOption?.connections.filter((connection) => connection.status !== 'revoked') ?? [] + // A connect link opened by someone already connected reads as done, not as a fresh ask. const focusedConnected = - focusedOption?.connections.some((connection) => connection.status === 'connected') && - (returnToSearch || connectedOptionId === focusedOption.id) + focusedOption !== undefined && + focusedAccounts.length > 0 && + focusedAccounts.every((connection) => connection.status === 'connected') && + (returnToSearch || focusedReturnTo === 'connect' || connectedOptionId === focusedOption.id) const connectedOption = connectedOptionId ? activeOptions.find((option) => option.id === connectedOptionId) : undefined @@ -451,21 +464,29 @@ export default async function CredentialGroupEnrollmentPage({
{focused ? ( -
- - {returnLabel} - -
+ + {!slackReturnUrl && ( + + {returnLabel} + + )} + ) : (
- {slackReturnUrl && Return to Slack} - - {enrollment.status === 'completed' ? 'Submitted' : 'Submit'} - + + + {enrollment.status === 'completed' ? 'Submitted' : 'Submit'} + +
)}
diff --git a/apps/sim/app/credential-groups/link-states.tsx b/apps/sim/app/credential-groups/link-states.tsx index 375e5974c79..df0d4abf308 100644 --- a/apps/sim/app/credential-groups/link-states.tsx +++ b/apps/sim/app/credential-groups/link-states.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from 'react' -import { AuthLinkButton as ChipLink } from '@sim/auth-ui' +import { AuthButton as Chip, AuthLinkButton as ChipLink, cn } from '@sim/auth-ui' import { APP_ENTRY_PATH } from '@/lib/navigation/paths' import { AuthHeader, AuthShell as LogoShell, SupportFooter } from '@/app/(auth)/components' import { SourceCompletion } from '@/app/desktop/connect/source-completion' @@ -18,6 +18,50 @@ export function CredentialGroupPageShell({ children }: CredentialGroupPageShellP ) } +interface CredentialGroupLinkActionsProps { + /** Where "Return to Slack" goes; omitted when the person did not come from Slack. */ + slackHref?: string + /** Makes "Return to Slack" the primary action, for a page with nothing left to do. */ + slackPrimary?: boolean + align?: 'center' | 'end' + className?: string + children?: ReactNode +} + +/** + * The action row of a connect page. "Return to Slack" opens the Slack app, which does nothing + * for someone using Slack in a browser, so it always comes with "You can close this tab." + */ +export function CredentialGroupLinkActions({ + slackHref, + slackPrimary = false, + align = 'center', + className, + children, +}: CredentialGroupLinkActionsProps) { + return ( +
+
+ {slackHref && ( + + Return to Slack + + )} + {children} +
+ {slackHref && ( +

You can close this tab.

+ )} +
+ ) +} + interface UnavailableInvitationProps { /** The enrollment token, when the page was opened from one, so a desktop handoff can finish. */ token?: string @@ -27,6 +71,8 @@ interface UnavailableInvitationProps { message?: string | null recoveryHref?: string recoveryLabel?: string + /** Offered instead of the recovery link when the person came from Slack. */ + slackHref?: string } /** A terminal state with a title, one line of copy, and one way out. */ @@ -37,6 +83,7 @@ export function UnavailableInvitation({ message, recoveryHref = APP_ENTRY_PATH, recoveryLabel = 'Open Sim', + slackHref, }: UnavailableInvitationProps) { return ( @@ -53,32 +100,202 @@ export function UnavailableInvitation({ : 'Sign in with the account this invitation was sent to. If the link has expired, ask an organization admin for a new invitation.')) } /> -
- {recoveryLabel} -
+ + {!slackHref && {recoveryLabel}} +
) } -interface WrongAccountProps { +interface SwitchAccountStateProps { token?: string + title: string description: string /** Where to come back to after signing in as someone else. */ callbackUrl: string + slackHref?: string } -/** The signed-in person is not the one this link is for; offers to switch accounts. */ -export function WrongAccount({ token, description, callbackUrl }: WrongAccountProps) { +function SwitchAccountState({ + token, + title, + description, + callbackUrl, + slackHref, +}: SwitchAccountStateProps) { return ( {token && }
- -
+ + -
+
) } + +interface WrongAccountProps { + token?: string + description: string + /** Where to come back to after signing in as someone else. */ + callbackUrl: string + slackHref?: string +} + +/** The signed-in person is not the one this link is for; offers to switch accounts. */ +export function WrongAccount(props: WrongAccountProps) { + return +} + +interface DifferentEmailProps { + viewerEmail: string + callbackUrl: string + slackHref?: string +} + +/** + * The link was made for someone else's email. The intended address is never shown: anyone + * holding the link could otherwise read it. + */ +export function DifferentEmail({ viewerEmail, callbackUrl, slackHref }: DifferentEmailProps) { + return ( + + ) +} + +interface NotInvitedProps { + integration: string + organizationName: string + viewerEmail: string + callbackUrl: string + slackHref?: string +} + +/** The signed-in person was never asked to connect; they may be signed in as someone else. */ +export function NotInvited({ + integration, + organizationName, + viewerEmail, + callbackUrl, + slackHref, +}: NotInvitedProps) { + return ( + + ) +} + +interface RequestExpiredProps { + organizationName: string + slackHref?: string +} + +/** A request nobody accepted in time; only an admin or the workflow asking again renews it. */ +export function RequestExpired({ organizationName, slackHref }: RequestExpiredProps) { + return ( + + ) +} + +interface VerifyEmailProps { + verifyHref: string +} + +export function VerifyEmail({ verifyHref }: VerifyEmailProps) { + return ( + + ) +} + +interface ConnectConfirmProps { + integration: string + organizationName: string + /** The same-origin POST that starts the connection; the page itself never writes. */ + action: string + slackHref?: string +} + +/** + * One button that starts the connection. A POST rather than a link, so unfurlers and + * prefetchers, which only follow GETs, never enroll anyone or mint a link. + */ +export function ConnectConfirm({ + integration, + organizationName, + action, + slackHref, +}: ConnectConfirmProps) { + return ( + + +
+ + + Connect {integration} + + +
+
+ ) +} + +interface ChooseConnectOptionProps { + integration: string + organizationName: string + options: Array<{ id: string; label: string; href: string }> + slackHref?: string +} + +/** The organization collects more than one account for the integration; the person picks one. */ +export function ChooseConnectOption({ + integration, + organizationName, + options, + slackHref, +}: ChooseConnectOptionProps) { + return ( + + +
+ {options.map((option) => ( + + {option.label} + + ))} +
+ {slackHref && ( + + )} +
+ ) +} diff --git a/apps/sim/ee/credential-groups/components/organization-account-people.tsx b/apps/sim/ee/credential-groups/components/organization-account-people.tsx index 3dc5d658730..26fdf3a542c 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-people.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-people.tsx @@ -3,7 +3,10 @@ import { useState } from 'react' import { Avatar, Badge, Chip, ChipConfirmModal, ChipModalError, toast } from '@sim/emcn' import { Plus } from '@sim/emcn/icons' -import type { CredentialGroupEnrollmentDetail } from '@/lib/api/contracts/credential-groups' +import type { + CredentialGroup, + CredentialGroupEnrollmentDetail, +} from '@/lib/api/contracts/credential-groups' import { SEARCH_DEBOUNCE_MS } from '@/lib/url-state' import { RowActionsMenu } from '@/app/workspace/[workspaceId]/settings/components/row-actions-menu' import { @@ -18,7 +21,9 @@ import { import { OrganizationAccountInviteModal } from '@/ee/credential-groups/components/organization-account-invite-modal' import { OrganizationPersonConnections } from '@/ee/credential-groups/components/organization-person-connections' import { + useInviteOrganizationAccountPeople, useOrganizationAccountPeople, + useOrganizationAccounts, useResendOrganizationAccountInvitation, useRevokeOrganizationAccountEnrollment, } from '@/hooks/queries/organization-accounts' @@ -34,18 +39,22 @@ const PERSON_STATUS_BADGES = { delivery_failed: { label: 'Email failed', variant: 'red' }, needs_reconnect: { label: 'Needs reconnect', variant: 'amber' }, connected: { label: 'Connected', variant: 'green' }, + not_connected: { label: 'Not connected', variant: 'gray' }, expired: { label: 'Expired', variant: 'orange' }, + requested: { label: 'Requested', variant: 'blue' }, invited: { label: 'Invited', variant: 'blue' }, } as const +type PersonStatus = keyof typeof PERSON_STATUS_BADGES + /** * Collapses an enrollment and its connections into the one status an admin - * acts on. A broken connection outranks a working one so it is never hidden, - * and an expired invitation only matters while no account is connected. + * acts on. A broken connection outranks a working one so it is never hidden. + * A request nobody has accepted yet is Expired once past its expiry (the same + * `expired` the connect page refuses on), Requested when Sim never emailed it, + * and Invited otherwise; once accepted, it is Not connected until an account is. */ -function getPersonStatus( - person: CredentialGroupEnrollmentDetail -): keyof typeof PERSON_STATUS_BADGES { +function getPersonStatus(person: CredentialGroupEnrollmentDetail): PersonStatus { if (person.status === 'revoked') return 'revoked' if (person.status === 'delivery_failed') return 'delivery_failed' const connections = [...person.connections, ...person.mcpConnections] @@ -53,24 +62,49 @@ function getPersonStatus( return 'needs_reconnect' } if (connections.some((connection) => connection.status === 'active')) return 'connected' - if (person.expired && person.status === 'invited') return 'expired' - return 'invited' + if (person.status !== 'invited') return 'not_connected' + if (person.expired) return 'expired' + return person.emailed ? 'invited' : 'requested' +} + +/** Whether some account the group collects is still missing for this person. */ +function lacksConnection( + person: CredentialGroupEnrollmentDetail, + group: Pick | null | undefined +): boolean { + if (!group) return true + const connected = new Set( + person.connections + .filter((connection) => connection.status === 'active') + .map((connection) => connection.provider) + ) + const connectedServers = new Set( + person.mcpConnections + .filter((connection) => connection.status === 'active') + .map((connection) => connection.mcpServerId) + ) + return ( + group.options.some((option) => option.status === 'active' && !connected.has(option.provider)) || + group.mcpServers.some((server) => server.enabled && !connectedServers.has(server.id)) + ) } export function OrganizationAccountPeople({ organizationId }: OrganizationAccountPeopleProps) { const resend = useResendOrganizationAccountInvitation() + const reinvite = useInviteOrganizationAccountPeople() const revoke = useRevokeOrganizationAccountEnrollment() + const group = useOrganizationAccounts(organizationId).data?.credentialGroup const [peopleSearch, setPeopleSearch] = useOrganizationAccountPeopleSearch() const search = useDebounce(peopleSearch.trim(), SEARCH_DEBOUNCE_MS) const people = useOrganizationAccountPeople(organizationId, search) const [inviteOpen, setInviteOpen] = useState(false) const [revokingPerson, setRevokingPerson] = useState<{ id: string; email: string } | null>(null) - const error = resend.error - const pending = resend.isPending || revoke.isPending + const error = resend.error ?? reinvite.error + const pending = resend.isPending || reinvite.isPending || revoke.isPending const enrollments = people.data?.pages.flatMap((page) => page.enrollments) ?? [] return ( { const personStatus = getPersonStatus(person) const status = PERSON_STATUS_BADGES[personStatus] - const revoked = personStatus === 'revoked' + const remindable = + personStatus === 'needs_reconnect' || lacksConnection(person, group) return ( } badge={ - - {status.label} - + <> + {person.requestedByWorkflow && ( + + Requested by workflow + + )} + + {status.label} + + } trailing={ - revoked ? undefined : ( - - resend.mutate( - { organizationId, enrollmentId: person.id }, - { onSuccess: () => toast.success('Reminder sent') } - ), + + reinvite.mutate( + { organizationId, emails: [person.email] }, + { onSuccess: () => toast.success('Invitation sent') } + ), + }, + ] + : [ + ...(remindable + ? [ + { + label: 'Send reminder', + disabled: pending, + onSelect: () => + resend.mutate( + { organizationId, enrollmentId: person.id }, + { onSuccess: () => toast.success('Reminder sent') } + ), + }, + ] + : []), + { + label: 'Revoke', + destructive: true, + disabled: pending, + onSelect: () => { + revoke.reset() + setRevokingPerson({ id: person.id, email: person.email }) }, - ]), - { - label: 'Revoke', - destructive: true, - disabled: pending, - onSelect: () => { - revoke.reset() - setRevokingPerson({ id: person.id, email: person.email }) - }, - }, - ]} - /> - ) + }, + ] + } + /> } /> ) diff --git a/apps/sim/ee/credential-groups/components/organization-account-providers.tsx b/apps/sim/ee/credential-groups/components/organization-account-providers.tsx index eadfbb6f0a8..f143a64c9f0 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-providers.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-providers.tsx @@ -62,7 +62,10 @@ function copyConnectLink(publicId: string, provider: CredentialGroupProvider) { void writeTextToClipboard( buildCredentialGroupConnectUrl({ publicId, provider: getCredentialGroupProviderId(provider) }) ).then( - () => toast.success('Link copied'), + () => + toast.success('Link copied', { + description: 'Works for organization members and people you’ve asked to connect.', + }), () => toast.error('Could not copy the link') ) } diff --git a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx index d112f259c73..802a9c1ee9d 100644 --- a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx +++ b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx @@ -1,7 +1,8 @@ 'use client' -import { useState } from 'react' +import { useId, useState } from 'react' import { + Badge, Chip, ChipDropdown, ChipModal, @@ -10,10 +11,13 @@ import { ChipModalField, ChipModalFooter, ChipModalHeader, + Label, + Skeleton, Switch, toast, } from '@sim/emcn' import { getErrorMessage } from '@sim/utils/errors' +import { isApiClientError } from '@/lib/api/client/errors' import type { OrganizationConnectionRequestPolicyState } from '@/lib/api/contracts/organization-accounts' import { CONNECTION_REQUEST_DAILY_LIMIT_DEFAULT, @@ -21,6 +25,7 @@ import { connectionRequestPolicySchema, FREE_MAIL_DOMAINS, normalizeConnectionRequestList, + storedConnectionRequestPolicySchema, } from '@/lib/credential-groups/connection-request-policy' import { SettingsQueryErrorState } from '@/app/workspace/[workspaceId]/settings/components/settings-empty-state' import { SettingsResourceRow } from '@/app/workspace/[workspaceId]/settings/components/settings-resource-row' @@ -32,15 +37,20 @@ import { type Policy = NonNullable const ALL_WORKSPACES = 'all' +const ALL_WORKSPACES_LABEL = 'All allowed workspaces' const SECTION_LABEL = 'Workflow connection requests' const TOGGLE_LABEL = 'Allow workflow requests' +/** Whether the policy could be turned on as it stands, or still needs the admin to fill it in. */ +const canEnable = (policy: Policy) => + connectionRequestPolicySchema.safeParse({ ...policy, enabled: true }).success + const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? '' : 's'}` function summarize(policy: Policy): string { return [ policy.workspaces.mode === 'all' - ? 'All workspaces' + ? ALL_WORKSPACES_LABEL : plural(policy.workspaces.workspaceIds.length, 'workspace'), policy.emailDomains.join(', '), plural(policy.providers.length, 'integration'), @@ -60,6 +70,7 @@ export function OrganizationConnectionRequests({ const state = useOrganizationConnectionRequestPolicy(organizationId) const update = useUpdateOrganizationConnectionRequestPolicy() const [editing, setEditing] = useState(false) + const toggleId = useId() if (state.error) return ( @@ -73,8 +84,18 @@ export function OrganizationConnectionRequests({ /> ) - if (!state.data) return null - const { policy, revision } = state.data + if (!state.data) + return ( + + + + ) + const { policy, revision, inEffect } = state.data + + const openEditor = () => { + update.reset() + setEditing(true) + } const save = async (next: Policy) => { try { @@ -82,7 +103,13 @@ export function OrganizationConnectionRequests({ setEditing(false) toast.success('Connection requests updated') } catch (error) { - /** The open modal shows the error itself; only the header switch needs a toast. */ + if (editing && isApiClientError(error) && error.status === 409) { + setEditing(false) + update.reset() + toast.error('Someone else changed these settings. Reopen to review.') + return + } + // The open modal shows other errors itself; only the header switch needs a toast. if (!editing) toast.error(getErrorMessage(error, 'Could not update connection requests')) } } @@ -90,31 +117,31 @@ export function OrganizationConnectionRequests({ return ( {TOGGLE_LABEL}} description={policy ? summarize(policy) : undefined} + badge={ + policy?.enabled && !inEffect ? ( + + Not in effect + + ) : undefined + } trailing={
{policy && ( - { - update.reset() - setEditing(true) - }} - > + Edit )} { - if (policy) void save({ ...policy, enabled: checked }) - else if (checked) { - update.reset() - setEditing(true) - } + if (!checked) { + if (policy) void save({ ...policy, enabled: false }) + } else if (policy && canEnable(policy)) void save({ ...policy, enabled: true }) + else openEditor() }} />
@@ -159,9 +186,11 @@ function ConnectionRequestPolicyModal({ ) const [sendEmail, setSendEmail] = useState(initial?.sendEmail ?? true) - const emailDomains = normalizeConnectionRequestList( - domains.split(',').map((domain) => domain.trim().replace(/^@/, '')) - ) + const enteredDomains = domains.split(',').map((domain) => domain.trim().replace(/^@/, '')) + const emailDomains = normalizeConnectionRequestList(enteredDomains) + const domainsError = + storedConnectionRequestPolicySchema.shape.emailDomains.safeParse(enteredDomains).error + ?.issues[0]?.message const freeMailDomains = emailDomains.filter((domain) => FREE_MAIL_DOMAINS.has(domain)) const limit = Number(dailyLimit) const limitValid = @@ -174,8 +203,8 @@ function ConnectionRequestPolicyModal({ dailyLimit: limit, sendEmail, } - /** Held to the rules of an enabled policy either way, so a saved draft can be turned on. */ - const valid = connectionRequestPolicySchema.safeParse({ ...draft, enabled: true }).success + // Held to the rules of an enabled policy either way, so a saved draft can be turned on. + const valid = canEnable(draft) return ( ({ value: workspace.id, label: workspace.name, @@ -234,11 +263,18 @@ function ConnectionRequestPolicyModal({ hint={ freeMailDomains.length ? `Anyone with a ${freeMailDomains.join(', ')} address could be asked` - : "Exact domains only; subdomains aren't included" + : "Comma-separated. Exact domains only; subdomains aren't included" } + error={domainsError} disabled={disabled} /> - + {(aria) => ( Date: Thu, 3 Dec 2026 16:43:28 -0600 Subject: [PATCH 16/26] refactor(credential-groups): one link expiry rule, revoked check, and request lifecycle - liveEnrollmentLinkCondition refuses a revoked enrollment itself; caller copies removed - unexpiredLinkCondition is the single expiry rule for lookups, link explanations and retention; a bound person's emailed link stops expiring only while the legacy column names it, so the pre-link app's disconnect ends it - enrollment-lifecycle holds the pure row rules (unissued values, revoked, request expiry); findOrCreateUnissuedEnrollment is the one locked find-or-create for link-less enrollments - an unbound enrollment is a request that expires at invitation_expires_at; People's expired flag uses the same predicate - email verification that a deployment cannot enforce counts as verified for enrollments - retention drains are isolated from each other's failures - 0490 adds requested_provider_id and puts the enrollment columns first --- ...anup-credential-group-links.integration.ts | 8 +- .../cleanup-credential-group-links.ts | 44 +++-- .../enrollment-link-outcome.integration.ts | 16 +- .../enrollment-links.integration.ts | 34 ++++ .../application/enrollment-auth.ts | 10 +- .../personal-organization-accounts.ts | 12 +- .../credential-groups/completion-return.ts | 71 -------- apps/sim/lib/credential-groups/credentials.ts | 3 +- .../credential-groups/enrollment-lifecycle.ts | 83 ++++++++++ .../lib/credential-groups/enrollments.test.ts | 17 +- apps/sim/lib/credential-groups/enrollments.ts | 136 +++++++++++---- apps/sim/lib/credential-groups/links.ts | 156 ++++++------------ apps/sim/lib/credential-groups/oauth.test.ts | 41 +---- apps/sim/lib/credential-groups/oauth.ts | 20 +-- .../lib/credential-groups/return-url.test.ts | 73 -------- apps/sim/lib/credential-groups/return-url.ts | 64 ------- .../credential-groups/self-enrollment.test.ts | 3 + .../lib/credential-groups/self-enrollment.ts | 3 +- .../lib/credential-groups/verified-email.ts | 11 ++ apps/sim/lib/credentials/managed-mcp.test.ts | 3 - apps/sim/lib/credentials/managed-mcp.ts | 5 - .../0490_credential_group_connect.sql | 12 +- .../db/migrations/meta/0490_snapshot.json | 6 + packages/db/schema.ts | 7 +- .../credential-groups-enrollments.mock.ts | 8 + .../src/mocks/schema-tables.generated.ts | 1 + scripts/check-unused-exports.baseline.json | 1 - 27 files changed, 407 insertions(+), 441 deletions(-) delete mode 100644 apps/sim/lib/credential-groups/completion-return.ts create mode 100644 apps/sim/lib/credential-groups/enrollment-lifecycle.ts delete mode 100644 apps/sim/lib/credential-groups/return-url.test.ts delete mode 100644 apps/sim/lib/credential-groups/return-url.ts create mode 100644 apps/sim/lib/credential-groups/verified-email.ts diff --git a/apps/sim/background/cleanup-credential-group-links.integration.ts b/apps/sim/background/cleanup-credential-group-links.integration.ts index 68a4200eb31..62fa670e1be 100644 --- a/apps/sim/background/cleanup-credential-group-links.integration.ts +++ b/apps/sim/background/cleanup-credential-group-links.integration.ts @@ -119,13 +119,13 @@ describe('runCleanupCredentialGroupLinks', () => { ) }) - it('keeps rows exactly at their cutoff and deletes those a millisecond older', async () => { + it('keeps a request exactly at its cutoff and a link not yet expired at its cutoff', async () => { const { groupId, enrollmentId } = await createEnrollment(sha256Hex(generateId())) const now = Date.now() const atRequestCutoff = await insertRequest(groupId, new Date(now - 2 * DAY_MS)) await insertRequest(groupId, new Date(now - 2 * DAY_MS - 1)) - const atLinkCutoff = await insertLink(enrollmentId, 'connect', new Date(now - DAY_MS)) - await insertLink(enrollmentId, 'connect', new Date(now - DAY_MS - 1)) + const pastLinkCutoff = await insertLink(enrollmentId, 'connect', new Date(now - DAY_MS + 1)) + await insertLink(enrollmentId, 'connect', new Date(now - DAY_MS)) await runCleanupCredentialGroupLinks(new Date(now)) @@ -138,7 +138,7 @@ describe('runCleanupCredentialGroupLinks', () => { .select({ id: credentialGroupEnrollmentLink.id }) .from(credentialGroupEnrollmentLink) .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId)) - expect(links.map((row) => row.id)).toEqual([atLinkCutoff]) + expect(links.map((row) => row.id)).toEqual([pastLinkCutoff]) }) it('skips a row another run holds instead of waiting for it', async () => { diff --git a/apps/sim/background/cleanup-credential-group-links.ts b/apps/sim/background/cleanup-credential-group-links.ts index 1c976b05451..a464d0dd776 100644 --- a/apps/sim/background/cleanup-credential-group-links.ts +++ b/apps/sim/background/cleanup-credential-group-links.ts @@ -5,8 +5,10 @@ import { credentialGroupEnrollmentLink, } from '@sim/db/schema' import { createLogger } from '@sim/logger' -import { and, asc, eq, inArray, lt, sql } from 'drizzle-orm' +import { getErrorMessage } from '@sim/utils/errors' +import { and, asc, eq, inArray, lt, ne, not } from 'drizzle-orm' import { DAY_MS } from '@/lib/credential-groups/limits' +import { unexpiredLinkCondition } from '@/lib/credential-groups/links' const logger = createLogger('CleanupCredentialGroupLinks') const cleanupDb = dbFor('cleanup') @@ -19,13 +21,24 @@ const CREDENTIAL_GROUP_PRUNE_BATCH_SIZE = 1_000 /** Batches per table per run; a larger backlog drains over the next runs. */ const MAX_BATCHES_PER_TABLE = 5 -/** Runs a bounded batch delete until one comes up short or the batch cap is reached. */ -async function drain(deleteBatch: () => Promise): Promise { +/** + * Runs a bounded batch delete until one comes up short or the batch cap is reached. A failure is + * logged and ends only this drain, so one table's trouble never stops the other's retention. + */ +async function drain(table: string, deleteBatch: () => Promise): Promise { let deleted = 0 - for (let batch = 0; batch < MAX_BATCHES_PER_TABLE; batch += 1) { - const count = await deleteBatch() - deleted += count - if (count < CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) break + try { + for (let batch = 0; batch < MAX_BATCHES_PER_TABLE; batch += 1) { + const count = await deleteBatch() + deleted += count + if (count < CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) break + } + } catch (error) { + logger.error('Credential group retention drain failed', { + table, + deleted, + error: getErrorMessage(error), + }) } return deleted } @@ -45,7 +58,7 @@ export async function runCleanupCredentialGroupLinks( const request = credentialGroupConnectionRequest const link = credentialGroupEnrollmentLink - const connectionRequests = await drain(async () => { + const connectionRequests = await drain('connection_requests', async () => { const removed = await cleanupDb .delete(request) .where( @@ -64,7 +77,7 @@ export async function runCleanupCredentialGroupLinks( return removed.length }) - const sessionLinks = await drain(async () => { + const sessionLinks = await drain('session_links', async () => { const removed = await cleanupDb .delete(link) .where( @@ -73,19 +86,20 @@ export async function runCleanupCredentialGroupLinks( cleanupDb .select({ id: link.id }) .from(link) + .innerJoin( + credentialGroupEnrollment, + eq(credentialGroupEnrollment.id, link.enrollmentId) + ) .where( and( inArray(link.purpose, ['self', 'connect']), - lt(link.expiresAt, linkCutoff), - sql`not exists (select 1 from ${credentialGroupEnrollment} where ${and( - eq(credentialGroupEnrollment.id, link.enrollmentId), - eq(credentialGroupEnrollment.invitationTokenHash, link.tokenHash) - )})` + not(unexpiredLinkCondition(linkCutoff)), + ne(credentialGroupEnrollment.invitationTokenHash, link.tokenHash) ) ) .orderBy(asc(link.expiresAt)) .limit(CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) - .for('update', { skipLocked: true }) + .for('update', { of: link, skipLocked: true }) ) ) .returning({ id: link.id }) diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts index 437488319e6..f9ee3699a10 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts @@ -271,10 +271,20 @@ describe('explainCredentialGroupEnrollmentLink', () => { }) }) - it('never calls an expired emailed link of a bound person expired', async () => { + it("never calls a bound person's newest emailed link expired, only an older one", async () => { const enrollmentToken = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) - const token = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) - await expect(explain(token, invitee)).resolves.toEqual({ kind: 'unavailable' }) + const older = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) + const newest = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) + await db + .update(credentialGroupEnrollment) + .set({ invitationTokenHash: sha256Hex(newest) }) + .where(eq(credentialGroupEnrollment.invitationTokenHash, sha256Hex(enrollmentToken))) + + await expect(explain(newest, invitee)).resolves.toEqual({ kind: 'unavailable' }) + await expect(explain(older, invitee)).resolves.toMatchObject({ + kind: 'needs_new_link', + reason: 'expired', + }) }) it('calls an expired connect link of a bound person expired', async () => { diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts index 91172581d27..a7008fbbd40 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts @@ -428,6 +428,40 @@ describe('credential group enrollment links', () => { expect(await resolves(self.token)).toBe(false) }) + it('refuses every link into an enrollment the pre-link app revoked, even to bind or complete', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + const identity = await identityOf(emailed.token) + /** The released app revokes the enrollment row only; its links stay unrevoked. */ + await db + .update(credentialGroupEnrollment) + .set({ status: 'revoked' }) + .where(eq(credentialGroupEnrollment.id, emailed.enrollmentId)) + + expect(await resolves(emailed.token)).toBe(false) + await expect(bindCredentialGroupEnrollmentUser(identity, person.userId)).rejects.toThrow( + 'Invitation is invalid or expired' + ) + await expect(completeAuthorizedCredentialGroupEnrollment(identity)).resolves.toBeNull() + expect((await enrollmentRow(emailed.enrollmentId)).userId).toBeNull() + }) + + it("ends a bound person's emailed link when the pre-link app's disconnect rewrites the legacy column", async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + await bindCredentialGroupEnrollmentUser(await identityOf(emailed.token), person.userId) + await expire(emailed.enrollmentId) + expect(await resolves(emailed.token)).toBe(true) + + /** The released app's disconnect writes a fresh hash to the column and leaves links alone. */ + await db + .update(credentialGroupEnrollment) + .set({ invitationTokenHash: sha256Hex(generateId()) }) + .where(eq(credentialGroupEnrollment.id, emailed.enrollmentId)) + + expect(await resolves(emailed.token)).toBe(false) + }) + it('keeps an invitation the pre-link app emailed during a deploy working after a resend', async () => { const person = await createPerson() const emailed = await adminInvite(person.email) diff --git a/apps/sim/lib/credential-groups/application/enrollment-auth.ts b/apps/sim/lib/credential-groups/application/enrollment-auth.ts index 9b7fed6f1b0..5375373152f 100644 --- a/apps/sim/lib/credential-groups/application/enrollment-auth.ts +++ b/apps/sim/lib/credential-groups/application/enrollment-auth.ts @@ -5,6 +5,7 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' import { authenticatePublicCredentialGroupEnrollment } from '@/lib/credential-groups/enrollments' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' +import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' /** Exchanges a valid invitation bearer for its bounded external enrollment principal. */ export async function authenticateCredentialGroupEnrollment( @@ -12,7 +13,7 @@ export async function authenticateCredentialGroupEnrollment( ): Promise { if (!invitationToken.trim() || invitationToken.length > 128) return null const session = await getSession() - if (!session?.user?.id || !session.user.emailVerified) return null + if (!session?.user?.id || !isCredentialGroupEmailVerified(session.user)) return null const identity = await authenticatePublicCredentialGroupEnrollment(invitationToken) if (!identity) return null if (identity.userId && identity.userId !== session.user.id) return null @@ -41,7 +42,12 @@ export async function credentialGroupOAuthAttemptPrincipal( > ): Promise { const session = await getSession() - if (!attempt.userId || !session?.user?.emailVerified || session.user.id !== attempt.userId) { + if ( + !attempt.userId || + !session?.user || + !isCredentialGroupEmailVerified(session.user) || + session.user.id !== attempt.userId + ) { throw new OrchestrationError( 'forbidden', 'Complete authorization using the same signed-in account that started it' diff --git a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts index 57ebb8e081d..27a190e2dd5 100644 --- a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts +++ b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts @@ -13,12 +13,10 @@ import { defineOperation } from '@/lib/core/application' import { runWithOutboundOrganization } from '@/lib/core/network/context.server' import { OrchestrationError } from '@/lib/core/orchestration/types' import { sameResourceScopeCondition } from '@/lib/core/resource-scope.server' +import { createUnissuedInvitationTokenHash } from '@/lib/credential-groups/enrollment-lifecycle' import { createCredentialGroupOAuthStartUrl } from '@/lib/credential-groups/enrollment-links' import { lockCredentialGroupEnrollmentLifecycle } from '@/lib/credential-groups/enrollments' -import { - createUnissuedInvitationTokenHash, - revokeCredentialGroupEnrollmentLinks, -} from '@/lib/credential-groups/links' +import { revokeCredentialGroupEnrollmentLinks } from '@/lib/credential-groups/links' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import { createViewerCredentialGroupEnrollment } from '@/lib/credential-groups/self-enrollment' import { @@ -157,7 +155,7 @@ export const reconnectPersonalOrganizationAccount = defineAuthorizedCredentialUs userId: principal.userId, credentialGroupId: account.groupId, completionId: input.oauthCompletionId, - returnTo: 'integrations' as const, + origin: 'integrations' as const, } return runWithOutboundOrganization(account.organizationId, () => { if (account.type === 'managed_oauth' && account.optionId) { @@ -185,7 +183,7 @@ export const reconnectPersonalOrganizationAccount = defineAuthorizedCredentialUs const url = new URL(invitationLink) if (account.optionId) { url.searchParams.set('optionId', account.optionId) - url.searchParams.set('returnTo', 'accounts') + url.searchParams.set('origin', 'accounts') } return { invitationLink: url.toString(), @@ -194,7 +192,7 @@ export const reconnectPersonalOrganizationAccount = defineAuthorizedCredentialUs authorizationUrl: createCredentialGroupOAuthStartUrl({ invitationLink, optionId: account.optionId, - returnTo: 'accounts', + origin: 'accounts', }), } : {}), diff --git a/apps/sim/lib/credential-groups/completion-return.ts b/apps/sim/lib/credential-groups/completion-return.ts deleted file mode 100644 index aa3cc9470ff..00000000000 --- a/apps/sim/lib/credential-groups/completion-return.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { createLogger } from '@sim/logger' -import { sha256Hex } from '@sim/security/hash' -import { getErrorMessage } from '@sim/utils/errors' -import { generateId, isValidUuid } from '@sim/utils/id' -import { getRedisClient } from '@/lib/core/config/redis' -import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' - -/** - * Server-held "Return to Slack" destinations for the completion page. A connect flow that ends on - * `/credential-groups/complete` stores its validated return URL here, bound to the signed-in - * person, and passes only the opaque ID in the redirect; the page never reads a destination from - * its own query, so a crafted completion link cannot show a return button. - */ - -const logger = createLogger('CredentialGroupCompletionReturn') - -const COMPLETION_RETURN_TTL_MS = 30 * 60 * 1000 - -interface StoredCompletionReturn { - userId: string - returnUrl: string -} - -function completionReturnKey(returnId: string): string { - return `credential-group:completion-return:${sha256Hex(returnId)}` -} - -/** - * Stores where `userId` may return to once their connection finishes. Returns the opaque ID for - * the completion redirect, or undefined when there is no allowed destination to keep or it could - * not be stored. - */ -export async function createCredentialGroupCompletionReturn(input: { - userId: string - returnUrl: string | undefined -}): Promise { - const returnUrl = input.returnUrl ? parseCredentialGroupReturnUrl(input.returnUrl)?.href : null - if (!returnUrl || !input.userId) return undefined - const returnId = generateId() - const stored: StoredCompletionReturn = { userId: input.userId, returnUrl } - try { - await getRedisClient().set( - completionReturnKey(returnId), - JSON.stringify(stored), - 'PX', - COMPLETION_RETURN_TTL_MS - ) - return returnId - } catch (error) { - /** The connection already finished; losing the return button must not fail it. */ - logger.warn('Failed to store credential group completion return', { - error: getErrorMessage(error), - }) - return undefined - } -} - -/** The destination stored under `returnId` for `userId`, or undefined for anyone else. */ -export async function readCredentialGroupCompletionReturn(input: { - returnId: string | undefined - userId: string | undefined -}): Promise { - if (!input.returnId || !isValidUuid(input.returnId) || !input.userId) return undefined - const raw = await getRedisClient().get(completionReturnKey(input.returnId)) - if (!raw) return undefined - const stored: unknown = JSON.parse(raw) - if (!stored || typeof stored !== 'object') return undefined - const { userId, returnUrl } = stored as Partial - if (userId !== input.userId || typeof returnUrl !== 'string') return undefined - return parseCredentialGroupReturnUrl(returnUrl)?.href -} diff --git a/apps/sim/lib/credential-groups/credentials.ts b/apps/sim/lib/credential-groups/credentials.ts index 9ae0a404526..b1bea32b7fb 100644 --- a/apps/sim/lib/credential-groups/credentials.ts +++ b/apps/sim/lib/credential-groups/credentials.ts @@ -16,6 +16,7 @@ import { isCredentialGroupProvider, } from '@/lib/credential-groups/providers' import type { CredentialGroupEnrollmentStatus } from '@/lib/credential-groups/types' +import { isEmailVerificationEffectivelyEnabled } from '@/lib/messaging/email/verification' export const MAX_CREDENTIAL_GROUP_CREDENTIAL_PAGE_SIZE = 100 @@ -139,7 +140,7 @@ export async function loadCredentialGroupEnrollmentAccess( .where( and( eq(user.id, userId), - eq(user.emailVerified, true), + isEmailVerificationEffectivelyEnabled() ? eq(user.emailVerified, true) : undefined, eq(credentialGroupEnrollment.credentialGroupId, credentialGroupId), inArray(credentialGroupEnrollment.status, [...LIVE_ENROLLMENT_STATUSES]) ) diff --git a/apps/sim/lib/credential-groups/enrollment-lifecycle.ts b/apps/sim/lib/credential-groups/enrollment-lifecycle.ts new file mode 100644 index 00000000000..cba0a3b6bcd --- /dev/null +++ b/apps/sim/lib/credential-groups/enrollment-lifecycle.ts @@ -0,0 +1,83 @@ +import type { credentialGroupEnrollment } from '@sim/db/schema' +import { sha256Hex } from '@sim/security/hash' +import { generateId } from '@sim/utils/id' +import { DAY_MS } from '@/lib/credential-groups/limits' + +/** + * Pure rules about one enrollment row: how long an unbound request waits for its person, when it + * counts as revoked or expired, and the values a link-less enrollment is created with. + */ + +type EnrollmentRow = typeof credentialGroupEnrollment.$inferSelect + +/** + * How long an unbound enrollment (an admin's invitation or a workflow's request) waits for its + * person, and how long an emailed link lives. A reminder or a repeat request renews it. + */ +export const INVITATION_TTL_MS = 7 * DAY_MS + +const UNISSUED_INVITATION_PREFIX = 'unissued:' + +/** + * A value for the legacy `invitation_token_hash` column of an enrollment created without an + * emailed link. It contains a character no hex digest does, so no token ever hashes to it: the + * legacy branch of the link lookup never matches it and link adoption skips it. It is unique and + * 64 characters long, as the column requires. + */ +export function createUnissuedInvitationTokenHash(): string { + return `${UNISSUED_INVITATION_PREFIX}${sha256Hex(generateId()).slice(UNISSUED_INVITATION_PREFIX.length)}` +} + +export function isUnissuedInvitationTokenHash(value: string): boolean { + return value.startsWith(UNISSUED_INVITATION_PREFIX) +} + +/** + * Insert values for an enrollment created without an emailed link (member self-enrollment, the + * connect page, or a workflow's connection request). It waits for its person as long as an + * emailed invitation would. + */ +export function unissuedEnrollmentValues(input: { + credentialGroupId: string + email: string + now: Date +}) { + return { + id: generateId(), + credentialGroupId: input.credentialGroupId, + email: input.email, + status: 'invited', + invitationTokenHash: createUnissuedInvitationTokenHash(), + invitationExpiresAt: new Date(input.now.getTime() + INVITATION_TTL_MS), + invitedAt: input.now, + createdBy: null, + createdAt: input.now, + updatedAt: input.now, + } satisfies typeof credentialGroupEnrollment.$inferInsert +} + +/** + * Whether an admin revoked the enrollment. Status is authoritative while an app that revokes by + * status alone may still be deployed, so either marker counts. + */ +export function isEnrollmentRevoked( + enrollment: Pick +): boolean { + return enrollment.status === 'revoked' || enrollment.revokedAt !== null +} + +/** + * Whether an enrollment is a request nobody answered in time: unbound, not revoked, and past + * `invitation_expires_at`. A bound enrollment never expires. The connect page refuses an expired + * request and People labels it Expired, both through this one rule. + */ +export function isEnrollmentRequestExpired( + enrollment: Pick, + now = new Date() +): boolean { + return ( + enrollment.userId === null && + !isEnrollmentRevoked(enrollment) && + enrollment.invitationExpiresAt.getTime() <= now.getTime() + ) +} diff --git a/apps/sim/lib/credential-groups/enrollments.test.ts b/apps/sim/lib/credential-groups/enrollments.test.ts index 62bb92720d1..31027029853 100644 --- a/apps/sim/lib/credential-groups/enrollments.test.ts +++ b/apps/sim/lib/credential-groups/enrollments.test.ts @@ -23,6 +23,9 @@ const { adapter } = vi.hoisted(() => ({ }, })) +vi.mock('@/lib/messaging/email/verification', () => ({ + isEmailVerificationEffectivelyEnabled: () => true, +})) vi.mock('@/components/emails/credential-groups/render', () => ({ renderCredentialGroupInvitationEmail: vi.fn(), })) @@ -602,7 +605,7 @@ describe('verified immutable enrollment identity binding', () => { }) it('binds an invitation once to its verified recipient', async () => { queueTableRows(schemaMock.credentialGroupEnrollment, [ - { enrollment: { ...ENROLLMENT, userId: null }, email: ENROLLMENT.email, verified: true }, + { enrollment: { ...ENROLLMENT, userId: null }, email: ENROLLMENT.email, emailVerified: true }, ]) await bindCredentialGroupEnrollmentUser(identity, 'recipient') expect(dbChainMockFns.set).toHaveBeenCalledWith( @@ -615,11 +618,11 @@ describe('verified immutable enrollment identity binding', () => { ) }) it.each([ - { email: 'someone-else@example.com', verified: true }, - { email: ENROLLMENT.email, verified: false }, - ])('rejects a different or unverified recipient', async ({ email, verified }) => { + { email: 'someone-else@example.com', emailVerified: true }, + { email: ENROLLMENT.email, emailVerified: false }, + ])('rejects a different or unverified recipient', async ({ email, emailVerified }) => { queueTableRows(schemaMock.credentialGroupEnrollment, [ - { enrollment: { ...ENROLLMENT, userId: null }, email, verified }, + { enrollment: { ...ENROLLMENT, userId: null }, email, emailVerified }, ]) await expect(bindCredentialGroupEnrollmentUser(identity, 'recipient')).rejects.toThrow( 'verified email' @@ -631,7 +634,7 @@ describe('verified immutable enrollment identity binding', () => { { enrollment: { ...ENROLLMENT, userId: 'recipient' }, email: 'new@example.com', - verified: true, + emailVerified: true, }, ]) await expect(bindCredentialGroupEnrollmentUser(identity, 'recipient')).resolves.toBeUndefined() @@ -642,7 +645,7 @@ describe('verified immutable enrollment identity binding', () => { { enrollment: { ...ENROLLMENT, userId: 'recipient' }, email: ENROLLMENT.email, - verified: true, + emailVerified: true, }, ]) await expect(bindCredentialGroupEnrollmentUser(identity, 'new-user')).rejects.toThrow( diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index bf31aa05759..742004654b3 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -13,7 +13,20 @@ import { import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { normalizeEmail, truncate } from '@sim/utils/string' -import { and, asc, count, desc, eq, inArray, isNull, lt, or, type SQL, sql } from 'drizzle-orm' +import { + and, + asc, + count, + countDistinct, + desc, + eq, + inArray, + isNull, + lt, + or, + type SQL, + sql, +} from 'drizzle-orm' import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' import { getCredentialGroupInvitationSubject } from '@/components/emails/subjects' import { searchFilter } from '@/lib/api/list-query' @@ -26,15 +39,18 @@ import { import { resourceScopeCondition } from '@/lib/core/resource-scope.server' import { getBaseUrl } from '@/lib/core/utils/urls' import { moreUsableAccount } from '@/lib/credential-groups/account-rules' +import { + INVITATION_TTL_MS, + isEnrollmentRequestExpired, + isEnrollmentRevoked, + unissuedEnrollmentValues, +} from '@/lib/credential-groups/enrollment-lifecycle' import { adoptLegacyInvitationLink, hashInvitationToken, - INVITATION_TTL_MS, insertEnrollmentLink, - isEnrollmentRevoked, liveEnrollmentLinkCondition, revokeCredentialGroupEnrollmentLinks, - unissuedEnrollmentValues, } from '@/lib/credential-groups/links' import type { ManagedMcpConnectorId } from '@/lib/credential-groups/managed-mcp-connectors' import { getManagedMcpConnector } from '@/lib/credential-groups/managed-mcp-connectors' @@ -55,6 +71,7 @@ import type { CredentialGroupEnrollmentRecord, InviteCredentialGroupEnrollmentsInput, } from '@/lib/credential-groups/types' +import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' import type { DbTransaction } from '@/lib/db/types' import { sendEmail } from '@/lib/messaging/email/mailer' @@ -368,7 +385,7 @@ export async function bindCredentialGroupEnrollmentUser( .select({ enrollment: credentialGroupEnrollment, email: user.email, - verified: user.emailVerified, + emailVerified: user.emailVerified, }) .from(credentialGroupEnrollment) .innerJoin( @@ -388,11 +405,11 @@ export async function bindCredentialGroupEnrollmentUser( ) .limit(1) .for('update', { of: credentialGroupEnrollment }) - if (!row || row.enrollment.revokedAt || row.enrollment.status === 'revoked') { + if (!row) { throw new CredentialGroupEnrollmentError('Invitation is invalid or expired', 404) } if ( - !row.verified || + !isCredentialGroupEmailVerified(row) || (row.enrollment.userId ? row.enrollment.userId !== userId : normalizeEmail(row.email) !== identity.email) @@ -416,7 +433,7 @@ export async function bindCredentialGroupEnrollmentUser( }) } -function toCredentialGroupEnrollment(row: EnrollmentRow): CredentialGroupEnrollmentRecord { +export function toCredentialGroupEnrollment(row: EnrollmentRow): CredentialGroupEnrollmentRecord { return { id: row.id, credentialGroupId: row.credentialGroupId, @@ -427,7 +444,7 @@ function toCredentialGroupEnrollment(row: EnrollmentRow): CredentialGroupEnrollm sentAt: row.sentAt?.toISOString() ?? null, completedAt: row.completedAt?.toISOString() ?? null, revokedAt: row.revokedAt?.toISOString() ?? null, - expired: row.invitationExpiresAt.getTime() <= Date.now(), + expired: isEnrollmentRequestExpired(row), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), } @@ -536,6 +553,40 @@ async function lockInvitationEnrollment( return locked } +/** + * The enrollment for an address, created without an emailed link when there is none. Returned + * under the invitation-target and lifecycle locks, so the caller decides on it, binds it, or mints + * a link into it without racing an invitation or a revocation. A revoked enrollment is returned + * as it is, never reactivated. A workflow's request records which workflow and integration asked. + */ +export async function findOrCreateUnissuedEnrollment( + tx: DbTransaction, + input: { + credentialGroupId: string + email: string + now: Date + request?: { workflowId: string; providerId: string } + } +): Promise<{ row: EnrollmentRow; created: boolean }> { + const existing = await lockInvitationEnrollment(tx, input.credentialGroupId, input.email) + if (existing) return { row: existing, created: false } + const [row] = await tx + .insert(credentialGroupEnrollment) + .values({ + ...unissuedEnrollmentValues(input), + ...(input.request + ? { + requestedByWorkflowId: input.request.workflowId, + requestedProviderId: input.request.providerId, + } + : {}), + }) + .returning() + if (!row) throw new Error('Credential group enrollment insert returned no row') + await lockCredentialGroupEnrollmentLifecycle(tx, row.id) + return { row, created: true } +} + /** * Emails a fresh invitation link: an administrator's invitation, reinvitation or resend (or an * automatic invitation a workflow issued). It deliberately restarts the invitation lifecycle on an @@ -572,18 +623,16 @@ async function issueInvitation( } if (current) { await adoptLegacyInvitationLink(tx, current, now) - /** - * Status is authoritative for revocation: the released app revokes by status alone, so - * links into an enrollment it revoked may still be unrevoked, and none of them may survive - * a reinvitation. - */ + // The released app revokes by status alone, so its revoked enrollment's links may still be + // unrevoked; none of them may survive a reinvitation. if (isEnrollmentRevoked(current)) await revokeCredentialGroupEnrollmentLinks(tx, current.id, now) } const preservesProgress = current?.status === 'in_progress' || current?.status === 'completed' const nextStatus = preservesProgress ? current.status : ('invited' as const) - /** The legacy column mirrors the newest emailed link, the one an admin sees expire. */ + // The legacy column mirrors the newest emailed link; a bound person's emailed link stays + // live only while it is that one. const invitationValues = { invitationTokenHash: hashInvitationToken(token), invitationExpiresAt: expiresAt, @@ -639,17 +688,14 @@ async function issueSelfEnrollmentLink( ): Promise<{ enrollment: EnrollmentRow; invitationLink: string }> { return db.transaction(async (tx) => { const now = new Date() - const current = await lockInvitationEnrollment(tx, groupId, email) - if (current && isEnrollmentRevoked(current)) { + const { row: enrollment } = await findOrCreateUnissuedEnrollment(tx, { + credentialGroupId: groupId, + email, + now, + }) + if (isEnrollmentRevoked(enrollment)) { throw new CredentialGroupEnrollmentError('Revoked enrollment cannot be resent', 409) } - const [enrollment] = current - ? [current] - : await tx - .insert(credentialGroupEnrollment) - .values(unissuedEnrollmentValues({ credentialGroupId: groupId, email, now })) - .returning() - if (!enrollment) throw new Error('Credential group enrollment insert returned no row') const { token } = await insertEnrollmentLink(tx, { enrollmentId: enrollment.id, purpose: 'self', @@ -697,14 +743,14 @@ async function sendInvitation( const focusedLink = new URL(invitationLink) if (options.searchConnection) { focusedLink.searchParams.set('optionId', options.searchConnection.optionId) - focusedLink.searchParams.set('returnTo', 'search') + focusedLink.searchParams.set('origin', 'search') } const html = await renderCredentialGroupInvitationEmail({ recipientEmail: email, inviterName, - workspaceName: context.workspaceName, - ownerKind: context.organizationId ? 'organization' : 'workspace', - credentialGroupName: context.groupName, + owner: context.organizationId + ? { kind: 'organization', name: context.workspaceName } + : { kind: 'workspace', name: context.workspaceName, credentialGroupName: context.groupName }, invitationLink: focusedLink.toString(), ...(options.searchConnection ? { searchProviderName: options.searchConnection.providerName } @@ -938,6 +984,8 @@ export async function listCredentialGroupEnrollments( return { enrollments: pageRows.map(({ enrollment }) => ({ ...toCredentialGroupEnrollment(enrollment), + requestedByWorkflow: enrollment.requestedByWorkflowId !== null, + emailed: enrollment.sentAt !== null, connections: connectionsByEnrollment.get(enrollment.id) ?? [], mcpConnections: mcpConnectionsByEnrollment.get(enrollment.id) ?? [], })), @@ -1331,6 +1379,36 @@ async function buildPublicCredentialGroupEnrollment( } } +/** + * Whether a connection made through a focused link finishes the enrollment on its own: a + * workflow's request asked for that one integration, and anyone else is done once every active + * account option has a live connection. Otherwise the enrollment stays open for its other options. + */ +export async function isFocusedConnectionComplete( + identity: PublicCredentialGroupEnrollmentIdentity +): Promise { + const row = await resolveAuthorizedPublicEnrollmentRow(identity) + if (!row) return false + if (row.enrollment.requestedByWorkflowId !== null) return true + const activeOptionIds = row.options + .filter((option) => option.status === 'active') + .map((option) => option.id) + if (activeOptionIds.length === 0) return false + const [connected] = await db + .select({ options: countDistinct(credential.credentialGroupOptionId) }) + .from(credential) + .where( + and( + eq(credential.type, 'managed_oauth'), + eq(credential.credentialGroupEnrollmentId, row.enrollment.id), + inArray(credential.credentialGroupOptionId, activeOptionIds), + eq(credential.managedOauthStatus, 'active'), + isNull(credential.revokedAt) + ) + ) + return (connected?.options ?? 0) === activeOptionIds.length +} + /** Finalizes an enrollment after the recipient finishes their optional account selections. */ export async function completeAuthorizedCredentialGroupEnrollment( identity: PublicCredentialGroupEnrollmentIdentity @@ -1357,7 +1435,7 @@ async function completeResolvedCredentialGroupEnrollment( ) ) .limit(1) - if (!current || current.status === 'revoked') return null + if (!current) return null const [group] = await tx .select({ diff --git a/apps/sim/lib/credential-groups/links.ts b/apps/sim/lib/credential-groups/links.ts index 9dedc605ddc..d7343eeda86 100644 --- a/apps/sim/lib/credential-groups/links.ts +++ b/apps/sim/lib/credential-groups/links.ts @@ -10,11 +10,15 @@ import { } from '@sim/db/schema' import { sha256Hex } from '@sim/security/hash' import { generateId } from '@sim/utils/id' -import { and, eq, gt, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm' +import { and, eq, gt, isNotNull, isNull, ne, or, type SQL, sql } from 'drizzle-orm' import { alias } from 'drizzle-orm/pg-core' import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' -import { DAY_MS } from '@/lib/credential-groups/limits' +import { + INVITATION_TTL_MS, + isEnrollmentRevoked, + isUnissuedInvitationTokenHash, +} from '@/lib/credential-groups/enrollment-lifecycle' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import type { DbTransaction } from '@/lib/db/types' @@ -23,24 +27,22 @@ import type { DbTransaction } from '@/lib/db/types' * self-enrollment and connect-page hand-off is one `credential_group_enrollment_link` row, so issuing * a link never invalidates another. Callers that write hold the enrollment's lifecycle lock. * - * Link lifetimes: - * - `email`: {@link INVITATION_TTL_MS}, and only while the enrollment is unbound; once a verified - * user is bound, the signed-in user is the authority, not the email's age. + * Link lifetimes, decided by {@link unexpiredLinkCondition} alone: + * - `email`: {@link INVITATION_TTL_MS}. Once a verified user is bound, the newest emailed link (the + * one the enrollment's legacy column mirrors) stops expiring: the signed-in user is the authority, + * not the email's age. The pre-link app's disconnect rewrites that column, so it also ends that. * - `self` and `connect`: {@link SESSION_LINK_TTL_MS}, always. They are minted for the sitting the - * person is in, so a self link from before the link table that the backfill recorded as `email` - * keeps the emailed lifetime instead. + * person is in. * * contract-pending(after the enrollment-link expand is fully deployed and no rollback target * predates it): the enrollment's legacy `invitation_token_hash` column and its `unissued:` values - * go in two steps. First make the column nullable and stop writing it (enrollments created without - * an emailed link then store null instead of {@link createUnissuedInvitationTokenHash}); then drop - * it with its unique index and length check, along with the legacy branch of - * {@link liveEnrollmentLinkCondition}, {@link adoptLegacyInvitationLink}, and the legacy fallback of - * {@link findCredentialGroupEnrollmentLinkRecord}. + * go in two steps. First make the column nullable and stop writing it; then drop it with its + * unique index and length check, along with {@link legacyInvitationUnexpiredCondition}, + * {@link adoptLegacyInvitationLink}, and the legacy fallback of + * {@link findCredentialGroupEnrollmentLinkRecord}. Bound emailed links then need their own marker + * in place of the column comparison in {@link unexpiredLinkCondition}. */ -/** How long an emailed invitation, or a workflow-requested enrollment, waits for its person. */ -export const INVITATION_TTL_MS = 7 * DAY_MS /** How long a `self` or `connect` link lives: it is opened in the sitting it was minted for. */ const SESSION_LINK_TTL_MS = 60 * 60 * 1000 @@ -52,70 +54,28 @@ export function hashInvitationToken(token: string): string { return sha256Hex(token) } -const UNISSUED_INVITATION_PREFIX = 'unissued:' - -/** - * A value for the legacy `invitation_token_hash` column of an enrollment created without an - * emailed link (by self-enrollment or a workflow's connection request). It contains a character - * no hex digest does, so no token ever hashes to it: the legacy branch of - * {@link liveEnrollmentLinkCondition} never matches it and link adoption skips it. It is unique - * and 64 characters long, as the column requires. - */ -export function createUnissuedInvitationTokenHash(): string { - return `${UNISSUED_INVITATION_PREFIX}${sha256Hex(generateId()).slice(UNISSUED_INVITATION_PREFIX.length)}` -} - -function isUnissuedInvitationTokenHash(value: string): boolean { - return value.startsWith(UNISSUED_INVITATION_PREFIX) -} - -/** - * Insert values for an enrollment created without an emailed link (member self-enrollment, the - * connect page, or a workflow's connection request). It waits for its person as long as an - * emailed invitation would, so an unbound enrollment ages out alike. - */ -export function unissuedEnrollmentValues(input: { - credentialGroupId: string - email: string - now: Date -}) { - return { - id: generateId(), - credentialGroupId: input.credentialGroupId, - email: input.email, - status: 'invited', - invitationTokenHash: createUnissuedInvitationTokenHash(), - invitationExpiresAt: new Date(input.now.getTime() + INVITATION_TTL_MS), - invitedAt: input.now, - createdBy: null, - createdAt: input.now, - updatedAt: input.now, - } satisfies typeof credentialGroupEnrollment.$inferInsert -} - /** - * Whether an admin revoked the enrollment. Status is authoritative while an app that revokes by - * status alone may still be deployed, so either marker counts. + * Whether a `credential_group_enrollment_link` row is unexpired at `now`, against its enrollment + * row in the same query. The one expiry rule for links: lookups, the explanation of a dead link, + * and retention all use it. */ -export function isEnrollmentRevoked( - enrollment: Pick -): boolean { - return enrollment.status === 'revoked' || enrollment.revokedAt !== null +export function unexpiredLinkCondition(now: Date): SQL { + const link = credentialGroupEnrollmentLink + const enrollment = credentialGroupEnrollment + return sql`(${or( + and( + isNotNull(enrollment.userId), + eq(link.purpose, 'email'), + eq(link.tokenHash, enrollment.invitationTokenHash) + ), + gt(link.expiresAt, now) + )})` } -/** - * Whether a link is past its expiry: the TypeScript form of the rule - * {@link liveEnrollmentLinkCondition} applies in SQL. An emailed link never expires once its - * enrollment is bound to a user; `self` and `connect` links always do. A legacy column value is an - * emailed link. - */ -function isEnrollmentLinkExpired( - link: { purpose: EnrollmentLinkPurpose; expiresAt: Date }, - bound: boolean, - now = Date.now() -): boolean { - if (bound && link.purpose === 'email') return false - return link.expiresAt.getTime() <= now +/** Whether an invitation known only by the enrollment's legacy column is unexpired at `now`. */ +function legacyInvitationUnexpiredCondition(now: Date): SQL { + const enrollment = credentialGroupEnrollment + return sql`(${or(isNotNull(enrollment.userId), gt(enrollment.invitationExpiresAt, now))})` } /** @@ -138,26 +98,30 @@ function enrollmentIdForTokenHash(tokenHash: string): SQL { } /** - * Matches the enrollment row that `tokenHash` is a live link into: an unrevoked link that has not - * expired under {@link isEnrollmentLinkExpired}. A hash with no link row falls back to the - * enrollment's legacy column, an emailed invitation the pre-link app still writes during a deploy - * or rollback. The pre-link app revokes an enrollment by its status alone, leaving its links - * unrevoked, so every caller also refuses a `revoked` enrollment. + * Matches the enrollment row that `tokenHash` is a live link into: an enrollment nobody revoked, + * and an unrevoked link that {@link unexpiredLinkCondition} keeps. A hash with no link row falls + * back to the enrollment's legacy column, an emailed invitation the pre-link app still writes + * during a deploy or rollback. The pre-link app revokes an enrollment by its status alone, leaving + * its links unrevoked, so the enrollment's status is checked here too. * * The enrollment is found by primary key first ({@link enrollmentIdForTokenHash}); the liveness * checks then run against that one row. */ export function liveEnrollmentLinkCondition(tokenHash: string, now = new Date()): SQL { const link = credentialGroupEnrollmentLink - const bound = isNotNull(credentialGroupEnrollment.userId) - return sql`(${credentialGroupEnrollment.id} = ${enrollmentIdForTokenHash(tokenHash)} and (exists (select 1 from ${link} where ${and( + const enrollment = credentialGroupEnrollment + return sql`(${and( + sql`${enrollment.id} = ${enrollmentIdForTokenHash(tokenHash)}`, + ne(enrollment.status, 'revoked'), + isNull(enrollment.revokedAt) + )} and (exists (select 1 from ${link} where ${and( eq(link.tokenHash, tokenHash), - eq(link.enrollmentId, credentialGroupEnrollment.id), + eq(link.enrollmentId, enrollment.id), isNull(link.revokedAt), - or(and(bound, eq(link.purpose, 'email')), gt(link.expiresAt, now)) + unexpiredLinkCondition(now) )}) or (${and( - eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), - or(bound, gt(credentialGroupEnrollment.invitationExpiresAt, now)) + eq(enrollment.invitationTokenHash, tokenHash), + legacyInvitationUnexpiredCondition(now) )} and not exists (select 1 from ${link} where ${eq(link.tokenHash, tokenHash)}))))` } @@ -258,12 +222,8 @@ export async function getCredentialGroupEnrollmentLinkOptionId( return row?.optionId ?? null } -const LINK_FOCUS_REASON = 'link_focus' - /** A link focused on one account option was used to connect a different one. */ export class CredentialGroupLinkFocusError extends OrchestrationError { - readonly reason = LINK_FOCUS_REASON - constructor() { super('forbidden', 'This link only connects the account it was sent for') this.name = 'CredentialGroupLinkFocusError' @@ -272,12 +232,7 @@ export class CredentialGroupLinkFocusError extends OrchestrationError { /** Whether `error`, or an error it wraps, is a {@link CredentialGroupLinkFocusError}. */ export function isCredentialGroupLinkFocusError(error: unknown): boolean { - const orchestrationError = asOrchestrationError(error) - return ( - orchestrationError?.code === 'forbidden' && - 'reason' in orchestrationError && - orchestrationError.reason === LINK_FOCUS_REASON - ) + return asOrchestrationError(error) instanceof CredentialGroupLinkFocusError } interface CredentialGroupEnrollmentLinkRecord { @@ -286,7 +241,7 @@ interface CredentialGroupEnrollmentLinkRecord { status: EnrollmentRow['status'] /** The link's purpose; a legacy column value is an emailed link. */ purpose: EnrollmentLinkPurpose - /** Past its expiry under {@link isEnrollmentLinkExpired}. */ + /** Past its expiry under {@link unexpiredLinkCondition}. */ expired: boolean /** The enrollment itself was revoked by an admin. */ revoked: boolean @@ -314,14 +269,14 @@ export async function findCredentialGroupEnrollmentLinkRecord( if (!token.trim() || token.length > 128) return null const tokenHash = hashInvitationToken(token) const link = credentialGroupEnrollmentLink + const now = new Date() const [row] = await db .select({ email: credentialGroupEnrollment.email, userId: credentialGroupEnrollment.userId, status: credentialGroupEnrollment.status, - legacyExpiresAt: credentialGroupEnrollment.invitationExpiresAt, revokedAt: credentialGroupEnrollment.revokedAt, - linkExpiresAt: link.expiresAt, + expired: sql`not (case when ${link.id} is null then ${legacyInvitationUnexpiredCondition(now)} else ${unexpiredLinkCondition(now)} end)`, linkPurpose: link.purpose, linkOptionId: link.optionId, linkRevokedAt: link.revokedAt, @@ -360,10 +315,7 @@ export async function findCredentialGroupEnrollmentLinkRecord( userId: row.userId, status: row.status, purpose, - expired: isEnrollmentLinkExpired( - { purpose, expiresAt: row.linkExpiresAt ?? row.legacyExpiresAt }, - row.userId !== null - ), + expired: row.expired, revoked: isEnrollmentRevoked(row), linkRevoked: row.linkRevokedAt !== null, groupActive: row.groupStatus === 'active', diff --git a/apps/sim/lib/credential-groups/oauth.test.ts b/apps/sim/lib/credential-groups/oauth.test.ts index a008244d970..357a426b59e 100644 --- a/apps/sim/lib/credential-groups/oauth.test.ts +++ b/apps/sim/lib/credential-groups/oauth.test.ts @@ -124,7 +124,7 @@ describe('credential group OAuth persistence', () => { createAttempt.mockResolvedValue({ state: 'state', nonce: 'nonce' }) await expect( startCredentialGroupOAuth(CONTEXT, 'invitation', { - returnTo: 'search', + origin: 'search', completionRedirect: true, completionId: '550e8400-e29b-41d4-a716-446655440000', }) @@ -138,7 +138,7 @@ describe('credential group OAuth persistence', () => { authorizationAppId: POLICY.authorizationAppId, scopeVersion: POLICY.scopeVersion, requiredScopes: POLICY.requiredScopes, - returnTo: 'search', + origin: 'search', completionRedirect: true, completionId: '550e8400-e29b-41d4-a716-446655440000', invitationToken: 'invitation', @@ -151,39 +151,6 @@ describe('credential group OAuth persistence', () => { expect(dbChainMockFns.update).not.toHaveBeenCalled() }) - it('does not reactivate a credential after its enrollment is revoked', async () => { - dbChainMockFns.limit.mockResolvedValueOnce([{ status: 'revoked' }]) - - await expect( - completeCredentialGroupOAuth( - CONTEXT, - { - state: 'state-1', - userId: 'person-1', - provider: 'gmail', - nonceHash: 'nonce-hash', - workspaceId: CONTEXT.workspaceId, - email: CONTEXT.email, - enrollmentId: CONTEXT.enrollmentId, - credentialGroupId: CONTEXT.credentialGroupId, - optionId: CONTEXT.option.id, - authorizationAppId: POLICY.authorizationAppId, - scopeVersion: POLICY.scopeVersion, - requiredScopes: POLICY.requiredScopes, - redirectUri: 'https://sim.ai/api/auth/oauth2/callback/google-email', - codeVerifier: 'verifier', - invitationToken: 'invitation-token', - createdAt: Date.now(), - }, - 'authorization-code' - ) - ).rejects.toBeInstanceOf(CredentialGroupInvitationUnavailableError) - - expect(dbChainMockFns.execute).toHaveBeenCalledTimes(2) - expect(dbChainMockFns.update).not.toHaveBeenCalled() - expect(dbChainMockFns.insert).not.toHaveBeenCalled() - }) - it('persists a different-email provider account under the enrolled Sim user', async () => { dbChainMockFns.limit.mockResolvedValueOnce([{ status: 'invited' }]) queueTableRows(schemaMock.credentialGroup, [GROUP]) @@ -462,8 +429,8 @@ describe('credential group OAuth persistence', () => { expect(dbChainMockFns.update).not.toHaveBeenCalled() expect(dbChainMockFns.insert).not.toHaveBeenCalled() }) - it('refuses a retained revocation timestamp and locks the original email/group identity', async () => { - dbChainMockFns.limit.mockResolvedValueOnce([{ status: 'in_progress', revokedAt: new Date() }]) + it('refuses an enrollment the live-link lookup no longer finds, by its original email and group', async () => { + dbChainMockFns.limit.mockResolvedValueOnce([]) await expect( completeCredentialGroupOAuth( CONTEXT, diff --git a/apps/sim/lib/credential-groups/oauth.ts b/apps/sim/lib/credential-groups/oauth.ts index 26ed05208dc..265824221d7 100644 --- a/apps/sim/lib/credential-groups/oauth.ts +++ b/apps/sim/lib/credential-groups/oauth.ts @@ -13,16 +13,17 @@ import { } from '@/lib/core/resource-scope' import { resourceScopeCondition } from '@/lib/core/resource-scope.server' import { resolveAccountWrite } from '@/lib/credential-groups/account-rules' +import type { ConnectReturnDestination } from '@/lib/credential-groups/connect-return' import { type CredentialGroupOAuthContext, lockCredentialGroupEnrollmentLifecycle, } from '@/lib/credential-groups/enrollments' import { CREDENTIAL_GROUP_ACCOUNTS_PER_PROVIDER_LIMIT } from '@/lib/credential-groups/limits' -import { isEnrollmentRevoked, liveEnrollmentLinkCondition } from '@/lib/credential-groups/links' +import { liveEnrollmentLinkCondition } from '@/lib/credential-groups/links' import type { CredentialGroupConnectionIntent } from '@/lib/credential-groups/oauth-intent' import { type CredentialGroupOAuthAttempt, - type CredentialGroupOAuthReturnTo, + type CredentialGroupOAuthOrigin, createCredentialGroupOAuthAttempt, } from '@/lib/credential-groups/oauth-state' import type { @@ -123,8 +124,8 @@ export async function startCredentialGroupOAuth( completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: CredentialGroupOAuthReturnTo - returnUrl?: string + origin?: CredentialGroupOAuthOrigin + returnTo?: ConnectReturnDestination } = {} ): Promise { if (!context.credentialOwnerId) throw new CredentialGroupInvitationUnavailableError() @@ -147,8 +148,8 @@ export async function startCredentialGroupOAuth( completionRedirect: options.completionRedirect, completionId: options.completionId, connectionIntent: options.connectionIntent, + origin: options.origin, returnTo: options.returnTo, - returnUrl: options.returnUrl, invitationToken, }) return await prepared.buildAuthorizationUrl({ state, nonce }) @@ -175,10 +176,7 @@ async function persistGrant( `credential-group-oauth:${context.enrollmentId}:${context.option.id}` ) const [enrollment] = await tx - .select({ - status: credentialGroupEnrollment.status, - revokedAt: credentialGroupEnrollment.revokedAt, - }) + .select({ status: credentialGroupEnrollment.status }) .from(credentialGroupEnrollment) .where( and( @@ -190,7 +188,7 @@ async function persistGrant( ) ) .limit(1) - if (!enrollment || isEnrollmentRevoked(enrollment)) { + if (!enrollment) { throw new CredentialGroupInvitationUnavailableError() } @@ -414,7 +412,7 @@ export async function completeCredentialGroupOAuth( attempt.connectionIntent && attempt.completionId && attempt.organizationId && - attempt.returnTo !== 'integrations' + attempt.origin !== 'integrations' ) { await recordSearchConnectionCompletion({ organizationId: attempt.organizationId, diff --git a/apps/sim/lib/credential-groups/return-url.test.ts b/apps/sim/lib/credential-groups/return-url.test.ts deleted file mode 100644 index dca6a26ce7e..00000000000 --- a/apps/sim/lib/credential-groups/return-url.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' - -describe('parseCredentialGroupReturnUrl', () => { - it.each([ - 'https://slack.com/app_redirect?app=A123&team=T123', - 'https://slack.com/app_redirect?channel=C123&team=T123', - 'https://slack.com/app_redirect?app=A123', - 'slack://app?team=T123&id=A123', - 'slack://open', - ])('accepts the Slack destination %s', (raw) => { - expect(parseCredentialGroupReturnUrl(raw)?.href).toBe(raw) - }) - - it.each([ - ['another host', 'https://example.com/app_redirect?app=A1'], - ['a lookalike suffix', 'https://slack.com.evil.com/app_redirect'], - ['a lookalike prefix', 'https://evilslack.com/'], - ['a lookalike subdomain suffix', 'https://acme.slack.com.evil.com/'], - ['userinfo before the host', 'https://slack.com@evil.com/'], - ['userinfo naming Slack', 'https://user@acme.slack.com/'], - ['userinfo with a password', 'https://a:b@acme.slack.com/'], - ['an explicit port', 'https://slack.com:8443/app_redirect'], - ['the default port spelled out', 'https://acme.slack.com:443/'], - ['plain http', 'http://slack.com/app_redirect?app=A1'], - ['a javascript URL', 'javascript:alert(1)//slack.com'], - ['a data URL', 'data:text/html,'], - ['a protocol-relative URL', '//slack.com/app_redirect'], - ['a relative path', '/app_redirect'], - ['an uppercase scheme', 'HTTPS://slack.com/app_redirect'], - ['a leading space', ' https://slack.com/app_redirect'], - ['a trailing newline', 'https://slack.com/app_redirect\n'], - ['an embedded tab', 'https://sla\tck.com/app_redirect'], - ['a NUL byte', 'https://slack.com/app_redirect\u0000'], - ['a backslash authority', 'https://evil.com\\@slack.com/'], - ['backslashes for slashes', 'https:\\\\slack.com/app_redirect'], - ['a percent-encoded dot in the host', 'https://slack%2ecom/app_redirect'], - ['a percent-encoded host suffix', 'https://evil.com%2f.slack.com/'], - ['a non-ASCII homoglyph host', 'https://slаck.com/app_redirect'], - ['a punycode host', 'https://xn--slck-7cd.com/app_redirect'], - ['a trailing-dot host', 'https://slack.com./app_redirect'], - ['an empty subdomain label', 'https://.slack.com/'], - ['another slack.com path', 'https://slack.com/oauth/v2/authorize?client_id=1'], - ['an app_redirect prefix path', 'https://slack.com/app_redirect/../signin'], - ['an IP host', 'https://127.0.0.1/'], - ['an unlisted slack scheme action', 'slack://user?team=T123&id=U123'], - ['a slack scheme with a path', 'slack://app/../../etc?team=T1'], - ['a slack scheme with userinfo', 'slack://evil@app?team=T1'], - ['a slack scheme with a port', 'slack://app:1?team=T1'], - ['a slack scheme lookalike action', 'slack://application?team=T1'], - ['a slack-like scheme', 'slacks://app?team=T1'], - ['a Slack workspace page', 'https://acme.slack.com/archives/C123/p1700000000000100'], - ['an enterprise Slack host', 'https://acme.enterprise.slack.com/'], - ['the Slack web client', 'https://app.slack.com/client/T123/D456'], - ['an app_redirect with no query', 'https://slack.com/app_redirect'], - ['an app_redirect with only a team', 'https://slack.com/app_redirect?team=T123'], - ['an app_redirect with another parameter', 'https://slack.com/app_redirect?app=A1&next=x'], - ['an app_redirect with a repeated parameter', 'https://slack.com/app_redirect?app=A1&app=A2'], - ['an app_redirect with an encoded value', 'https://slack.com/app_redirect?app=A%31'], - ['an app_redirect with a fragment', 'https://slack.com/app_redirect?app=A1#x'], - ['an app_redirect with an empty value', 'https://slack.com/app_redirect?app='], - ['a slack open link with a query', 'slack://open?team=T123'], - ['a slack channel link', 'slack://channel?team=T123&id=C123'], - ['a slack app link with its parameters swapped', 'slack://app?id=A123&team=T123'], - ['a slack app link with an extra parameter', 'slack://app?team=T123&id=A123&x=1'], - ['a slack app link with a lowercase ID', 'slack://app?team=t123&id=A123'], - ['a slack app link with a non-app ID', 'slack://app?team=T123&id=U123'], - ['an overlong URL', `https://slack.com/app_redirect?app=${'A'.repeat(2048)}`], - ['an empty string', ''], - ])('rejects %s', (_label, raw) => { - expect(parseCredentialGroupReturnUrl(raw)).toBeNull() - }) -}) diff --git a/apps/sim/lib/credential-groups/return-url.ts b/apps/sim/lib/credential-groups/return-url.ts deleted file mode 100644 index 5debc292427..00000000000 --- a/apps/sim/lib/credential-groups/return-url.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * The closed allowlist of places a connect flow may send someone back to once their account is - * connected. Only three Slack shapes are allowed: - * - `https://slack.com/app_redirect?…` with only `app`, `team` and `channel` query parameters - * - `slack://open` with no query - * - `slack://app?team=T…&id=A…` with exactly those two parameters - * - * The raw string is matched before it is parsed, so parser normalization (percent-decoding, - * backslash folding, default-port stripping, IDNA) can never turn a rejected spelling into an - * accepted one. The result is only ever rendered as a link the person clicks, never followed by - * an automatic redirect. - */ - -const CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH = 2048 - -/** - * The longest `return` query value a route accepts at all. Anything over - * {@link CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH} is then ignored rather than refused, so an - * oversized value never turns a connect link into an error page. - */ -export const CREDENTIAL_GROUP_RETURN_QUERY_MAX_LENGTH = 8192 - -const SLACK_ID = '[A-Z0-9]{1,32}' -const SLACK_APP_REDIRECT = /^https:\/\/slack\.com\/app_redirect\?(?[A-Za-z0-9=&]+)$/ -const SLACK_APP_REDIRECT_PARAMS = new Set(['app', 'team', 'channel']) -const SLACK_APP_REDIRECT_PARAM = new RegExp(`^(?[a-z]+)=${SLACK_ID}$`) -const SLACK_OPEN = 'slack://open' -const SLACK_APP = new RegExp(`^slack://app\\?team=T${SLACK_ID}&id=A${SLACK_ID}$`) - -function isSlackAppRedirect(raw: string): boolean { - const query = SLACK_APP_REDIRECT.exec(raw)?.groups?.query - if (!query) return false - const seen = new Set() - for (const pair of query.split('&')) { - const key = SLACK_APP_REDIRECT_PARAM.exec(pair)?.groups?.key - if (!key || !SLACK_APP_REDIRECT_PARAMS.has(key) || seen.has(key)) return false - seen.add(key) - } - return seen.has('app') || seen.has('channel') -} - -/** The keyword a stable connect URL's `return` query may carry, set by the Credential block. */ -export const CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD = 'slack' - -/** - * Where a stable connect URL's `return` query sends the person back to. Workflows hold no Slack - * team or app ID, so only the keyword `slack` is honoured, as the Slack app's generic deep link; - * any URL in that query is ignored, so a crafted connect link cannot name a destination. URLs - * the server itself put on an enrollment link go through {@link parseCredentialGroupReturnUrl}. - */ -export function resolveCredentialGroupConnectReturnUrl( - raw: string | undefined -): string | undefined { - return raw === CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD ? SLACK_OPEN : undefined -} - -/** Returns the parsed URL when `raw` is an allowed Slack destination, else `null`. */ -export function parseCredentialGroupReturnUrl(raw: string): URL | null { - if (raw.length === 0 || raw.length > CREDENTIAL_GROUP_RETURN_URL_MAX_LENGTH) return null - if (raw !== SLACK_OPEN && !SLACK_APP.test(raw) && !isSlackAppRedirect(raw)) return null - if (!URL.canParse(raw)) return null - const url = new URL(raw) - return url.href === raw ? url : null -} diff --git a/apps/sim/lib/credential-groups/self-enrollment.test.ts b/apps/sim/lib/credential-groups/self-enrollment.test.ts index b98556ab2b6..a68424e339d 100644 --- a/apps/sim/lib/credential-groups/self-enrollment.test.ts +++ b/apps/sim/lib/credential-groups/self-enrollment.test.ts @@ -5,6 +5,9 @@ import { } from '@sim/testing/mocks/credential-groups-enrollments.mock' import { beforeEach, describe, expect, it, vi } from 'vitest' +vi.mock('@/lib/messaging/email/verification', () => ({ + isEmailVerificationEffectivelyEnabled: () => true, +})) vi.mock('@/lib/credential-groups/enrollments', () => credentialGroupsEnrollmentsMock) import { CredentialGroupEnrollmentError } from '@/lib/credential-groups/enrollments' diff --git a/apps/sim/lib/credential-groups/self-enrollment.ts b/apps/sim/lib/credential-groups/self-enrollment.ts index 14e7b4bea61..691fca2870c 100644 --- a/apps/sim/lib/credential-groups/self-enrollment.ts +++ b/apps/sim/lib/credential-groups/self-enrollment.ts @@ -10,6 +10,7 @@ import { CredentialGroupEnrollmentError, createCredentialGroupSelfEnrollmentLink, } from '@/lib/credential-groups/enrollments' +import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' /** Enrolls a verified workspace member without reviving access revoked by an administrator. */ export async function createViewerCredentialGroupEnrollment(input: { @@ -24,7 +25,7 @@ export async function createViewerCredentialGroupEnrollment(input: { .where(eq(user.id, input.userId)) .limit(1) if (!viewer) throw new OrchestrationError('not_found', 'User not found') - if (!viewer.emailVerified) { + if (!isCredentialGroupEmailVerified(viewer)) { throw new OrchestrationError( 'validation', 'Verify your email address before connecting an account' diff --git a/apps/sim/lib/credential-groups/verified-email.ts b/apps/sim/lib/credential-groups/verified-email.ts new file mode 100644 index 00000000000..eaa91c594bf --- /dev/null +++ b/apps/sim/lib/credential-groups/verified-email.ts @@ -0,0 +1,11 @@ +import { isEmailVerificationEffectivelyEnabled } from '@/lib/messaging/email/verification' + +/** + * Whether a Sim user's email counts as verified for claiming an enrollment at that address. A + * deployment that cannot verify email (verification off, or no mail provider) has no verified + * addresses at all, so there its users' addresses are taken as given, as sign-up and organization + * invitations already do. + */ +export function isCredentialGroupEmailVerified(user: { emailVerified: boolean }): boolean { + return user.emailVerified || !isEmailVerificationEffectivelyEnabled() +} diff --git a/apps/sim/lib/credentials/managed-mcp.test.ts b/apps/sim/lib/credentials/managed-mcp.test.ts index b9882fc5d70..a889b75c5fb 100644 --- a/apps/sim/lib/credentials/managed-mcp.test.ts +++ b/apps/sim/lib/credentials/managed-mcp.test.ts @@ -35,7 +35,6 @@ const input = { } const source = { enrollmentStatus: 'in_progress', - enrollmentRevokedAt: null, credentialGroupId: input.credentialGroupId, groupStatus: 'active', linkedCredentialGroupId: input.credentialGroupId, @@ -49,8 +48,6 @@ describe('managed MCP grant persistence', () => { it.each([ null, - { ...source, enrollmentRevokedAt: new Date() }, - { ...source, enrollmentStatus: 'revoked' }, { ...source, groupStatus: 'disabled' }, { ...source, linkedCredentialGroupId: 'another-group' }, ])( diff --git a/apps/sim/lib/credentials/managed-mcp.ts b/apps/sim/lib/credentials/managed-mcp.ts index 9c063a58e59..5cf4f126498 100644 --- a/apps/sim/lib/credentials/managed-mcp.ts +++ b/apps/sim/lib/credentials/managed-mcp.ts @@ -354,7 +354,6 @@ export async function persistManagedMcpCredential(params: { const [source] = await tx .select({ enrollmentStatus: credentialGroupEnrollment.status, - enrollmentRevokedAt: credentialGroupEnrollment.revokedAt, credentialGroupId: credentialGroupEnrollment.credentialGroupId, groupStatus: credentialGroup.status, linkedCredentialGroupId: mcpServers.credentialGroupId, @@ -387,10 +386,6 @@ export async function persistManagedMcpCredential(params: { !source || !source.managedConnectorId || source.groupStatus !== 'active' || - source.enrollmentRevokedAt || - !['invited', 'delivery_failed', 'in_progress', 'completed'].includes( - source.enrollmentStatus - ) || source.linkedCredentialGroupId !== source.credentialGroupId ) { throw new ManagedMcpCredentialError('Managed MCP connection is no longer available', 404) diff --git a/packages/db/migrations/0490_credential_group_connect.sql b/packages/db/migrations/0490_credential_group_connect.sql index 4a1e0a0d6b7..be3443637b1 100644 --- a/packages/db/migrations/0490_credential_group_connect.sql +++ b/packages/db/migrations/0490_credential_group_connect.sql @@ -6,6 +6,12 @@ -- Contract, in two later migrations: first make invitation_token_hash nullable and stop writing -- it (enrollments created without an emailed link then store null instead of an 'unissued:' -- placeholder), then drop it with its unique index and length check. +-- +-- Expand first: two enrollment columns for workflow connection requests (the requesting workflow and +-- integration) and its reminder count. Nullable or defaulted, so the released app is unaffected. +ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "requested_by_workflow_id" text;--> statement-breakpoint +ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "requested_provider_id" text;--> statement-breakpoint +ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "connection_request_reminders" integer DEFAULT 0 NOT NULL;--> statement-breakpoint DO $$ BEGIN CREATE TYPE "public"."credential_group_enrollment_link_purpose" AS ENUM('email', 'self', 'connect'); EXCEPTION WHEN duplicate_object THEN NULL; @@ -42,8 +48,8 @@ SELECT FROM "credential_group_enrollment" e ON CONFLICT ("token_hash") DO NOTHING; --> statement-breakpoint --- Expand: workflow connection requests. A request log the daily cap counts, the admin's request --- policy, and two enrollment columns (the requesting workflow and its reminder count). Every +-- Expand: workflow connection requests. A request log the daily cap counts and the admin's request +-- policy (the enrollment columns are added at the top of this file). Every -- statement is idempotent: a replay after an earlier migration's embedded COMMIT re-runs this -- file in autocommit. CREATE TABLE IF NOT EXISTS "credential_group_connection_request" ( @@ -66,8 +72,6 @@ CREATE TABLE IF NOT EXISTS "credential_group_connection_request_policy" ( CONSTRAINT "credential_group_connection_request_policy_revision_check" CHECK ("credential_group_connection_request_policy"."revision" >= 1) ); --> statement-breakpoint -ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "requested_by_workflow_id" text;--> statement-breakpoint -ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "connection_request_reminders" integer DEFAULT 0 NOT NULL;--> statement-breakpoint DO $$ BEGIN ALTER TABLE "credential_group_connection_request" ADD CONSTRAINT "credential_group_connection_request_credential_group_id_credential_group_id_fk" FOREIGN KEY ("credential_group_id") REFERENCES "public"."credential_group"("id") ON DELETE cascade ON UPDATE no action; EXCEPTION WHEN duplicate_object THEN NULL; diff --git a/packages/db/migrations/meta/0490_snapshot.json b/packages/db/migrations/meta/0490_snapshot.json index 0be7b288789..b8a2825b624 100644 --- a/packages/db/migrations/meta/0490_snapshot.json +++ b/packages/db/migrations/meta/0490_snapshot.json @@ -5766,6 +5766,12 @@ "primaryKey": false, "notNull": false }, + "requested_provider_id": { + "name": "requested_provider_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "connection_request_reminders": { "name": "connection_request_reminders", "type": "integer", diff --git a/packages/db/schema.ts b/packages/db/schema.ts index e739767b732..c8e40a06d46 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7459,7 +7459,10 @@ export const credentialGroupEnrollment = pgTable( * invitation resolves through the link table. */ invitationTokenHash: text('invitation_token_hash').notNull(), - /** Latest expiry among the enrollment's links; reporting only. */ + /** + * When an unbound enrollment stops waiting for its person. An admin's invitation or reminder, + * or a workflow's request or reminder, renews it; a bound enrollment never expires. + */ invitationExpiresAt: timestamp('invitation_expires_at').notNull(), invitedAt: timestamp('invited_at').notNull(), sentAt: timestamp('sent_at'), @@ -7469,6 +7472,8 @@ export const credentialGroupEnrollment = pgTable( createdBy: text('created_by').references(() => user.id, { onDelete: 'set null' }), /** Set when a workflow's connection request created the row; an admin invitation clears it. */ requestedByWorkflowId: text('requested_by_workflow_id'), + /** The credential provider the workflow last asked for, so a reminder asks for it again. */ + requestedProviderId: text('requested_provider_id'), /** Reminder emails sent for a workflow-requested enrollment after its first invitation. */ connectionRequestReminders: integer('connection_request_reminders').notNull().default(0), createdAt: timestamp('created_at').notNull().defaultNow(), diff --git a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts index a700269ddd4..815432f9c74 100644 --- a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts +++ b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts @@ -32,6 +32,10 @@ export const credentialGroupsEnrollmentsMockFns = { mockLockCredentialGroupEnrollmentLifecycle: vi.fn( async (_executor: unknown, _enrollmentId: string): Promise => {} ), + mockLockCredentialGroupInvitationTarget: vi.fn(), + mockFindOrCreateUnissuedEnrollment: vi.fn(), + mockToCredentialGroupEnrollment: vi.fn(), + mockIsFocusedConnectionComplete: vi.fn(), mockAuthenticatePublicCredentialGroupEnrollment: vi.fn(), mockBindCredentialGroupEnrollmentUser: vi.fn(), mockListCredentialGroupEnrollments: vi.fn(), @@ -63,6 +67,10 @@ const fns = credentialGroupsEnrollmentsMockFns export const credentialGroupsEnrollmentsMock = { CredentialGroupEnrollmentError: MockCredentialGroupEnrollmentError, lockCredentialGroupEnrollmentLifecycle: fns.mockLockCredentialGroupEnrollmentLifecycle, + lockCredentialGroupInvitationTarget: fns.mockLockCredentialGroupInvitationTarget, + findOrCreateUnissuedEnrollment: fns.mockFindOrCreateUnissuedEnrollment, + toCredentialGroupEnrollment: fns.mockToCredentialGroupEnrollment, + isFocusedConnectionComplete: fns.mockIsFocusedConnectionComplete, authenticatePublicCredentialGroupEnrollment: fns.mockAuthenticatePublicCredentialGroupEnrollment, bindCredentialGroupEnrollmentUser: fns.mockBindCredentialGroupEnrollmentUser, listCredentialGroupEnrollments: fns.mockListCredentialGroupEnrollments, diff --git a/packages/testing/src/mocks/schema-tables.generated.ts b/packages/testing/src/mocks/schema-tables.generated.ts index 35c73d657d6..35ecd2d7630 100644 --- a/packages/testing/src/mocks/schema-tables.generated.ts +++ b/packages/testing/src/mocks/schema-tables.generated.ts @@ -1888,6 +1888,7 @@ export const GENERATED_SCHEMA_TABLES = { 'lastDeliveryError', 'createdBy', 'requestedByWorkflowId', + 'requestedProviderId', 'connectionRequestReminders', 'createdAt', 'updatedAt', diff --git a/scripts/check-unused-exports.baseline.json b/scripts/check-unused-exports.baseline.json index b7d1083eca3..225f5768c15 100644 --- a/scripts/check-unused-exports.baseline.json +++ b/scripts/check-unused-exports.baseline.json @@ -1283,7 +1283,6 @@ "apps/sim/lib/api/contracts/copilot.ts#validateCopilotApiKeyUsageExceededSchema", "apps/sim/lib/api/contracts/copilot.ts#validateCopilotByokBodySchema", "apps/sim/lib/api/contracts/credential-groups.ts#CreateCredentialGroupMcpConnectorBody", - "apps/sim/lib/api/contracts/credential-groups.ts#CredentialGroup", "apps/sim/lib/api/contracts/credential-groups.ts#CredentialGroupAccessPolicy", "apps/sim/lib/api/contracts/credential-groups.ts#CredentialGroupAccessResponse", "apps/sim/lib/api/contracts/credential-groups.ts#CredentialGroupEnrollment", From 0b1e70f12f22f07ed292b1632a45f4efe71a5ed7 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 16:43:57 -0600 Subject: [PATCH 17/26] feat(credential-groups): read-only connect page, start POST, and one return destination - openCredentialGroupConnect (GET page) only reads; startCredentialGroupConnect (same-origin POST) enrolls or binds and mints the focused link in one transaction, then goes straight to the provider's OAuth start; refusals, limits and outages return to the page, never JSON - outcomes: ready_to_connect, confirm_self_enrollment, wrong_account, different_email, not_invited, expired, revoked, choose_option, unavailable, verify_email - connect URLs built for one person carry a for= request handle (keyed hash of group and email); a mismatch says so without revealing the address and never self-enrolls - page and POST share one session gate; a limiter outage is told apart from a real limit - ConnectReturnDestination ('slack') travels block input, return=slack, OAuth attempt and completion redirect, resolved to slack://open only where rendered; the Redis completion return store and URL allowlist are gone; the in-app return enum is renamed origin - OAuth attempts live 30 minutes (state v6, MCP v5); an expired attempt still offers the way back to Slack - signed-in OAuth starts are bounded by their enrollment, not the shared IP bucket - a focused connection completes the enrollment only when every active option is connected or a workflow requested it - reconnecting the wrong account tells an invitee which account to choose --- .../connect/[publicId]/route.test.ts | 74 ++-- .../connect/[publicId]/route.ts | 65 ++- .../enroll/[token]/complete/route.ts | 10 +- .../enroll/[token]/mcp/[mcpServerId]/route.ts | 18 +- .../[token]/oauth/[optionId]/route.test.ts | 33 +- .../enroll/[token]/oauth/[optionId]/route.ts | 19 +- .../credential-groups/enrollment-redirect.ts | 13 +- .../credential-groups/oauth-callback.test.ts | 20 +- .../api/credential-groups/oauth-callback.ts | 22 +- .../oauth/[provider]/callback/route.test.ts | 8 +- .../app/api/mcp/oauth/callback/route.test.ts | 2 +- apps/sim/app/api/mcp/oauth/callback/route.ts | 4 +- .../[id]/connected-accounts/connect/route.ts | 2 +- .../[publicId]/connect/page.tsx | 168 ++++--- .../complete/completion-view.ts | 44 +- .../app/credential-groups/complete/page.tsx | 15 +- .../enroll/[token]/page.test.tsx | 10 +- .../credential-groups/enroll/[token]/page.tsx | 113 ++--- .../lib/api/contracts/credential-groups.ts | 27 +- .../connect-target.integration.ts | 418 ++++++++++-------- ...ganization-account-outbound.integration.ts | 4 +- .../slack-return.integration.ts | 111 ++--- .../application/connect-target.ts | 248 ++++++----- .../application/organization-access.test.ts | 4 +- .../application/organization-accounts.ts | 10 +- .../personal-organization-accounts.test.ts | 4 +- .../application/public-enrollment.test.ts | 4 +- .../application/public-enrollment.ts | 36 +- .../connect-request-handle.ts | 31 ++ .../lib/credential-groups/connect-return.ts | 26 ++ .../lib/credential-groups/connect-session.ts | 31 ++ .../lib/credential-groups/connect-subject.ts | 74 ++-- apps/sim/lib/credential-groups/connect-url.ts | 42 +- .../enrollment-links.test.ts | 8 +- .../lib/credential-groups/enrollment-links.ts | 4 +- .../credential-groups/mcp-oauth-state.test.ts | 4 +- .../lib/credential-groups/mcp-oauth-state.ts | 14 +- apps/sim/lib/credential-groups/mcp-oauth.ts | 2 +- .../lib/credential-groups/oauth-state.test.ts | 10 +- apps/sim/lib/credential-groups/oauth-state.ts | 77 ++-- apps/sim/lib/credential-groups/rate-limit.ts | 40 +- .../self-enrollment-oauth.ts | 8 +- .../knowledge/application/connector-access.ts | 2 +- .../application/github-setup.test.ts | 2 +- .../lib/knowledge/application/github-setup.ts | 4 +- 45 files changed, 1037 insertions(+), 848 deletions(-) create mode 100644 apps/sim/lib/credential-groups/connect-request-handle.ts create mode 100644 apps/sim/lib/credential-groups/connect-return.ts create mode 100644 apps/sim/lib/credential-groups/connect-session.ts diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts index 40bea5724f1..83b67ac4b65 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts @@ -1,30 +1,31 @@ /** - * The connect page's confirmation POST enrolls the signed-in person, so it must only act on a - * request a page on this origin sent, by a verified person within their rate limits. Failure - * modes: a cross-site form post, a post from another origin whose browser sends no - * `Sec-Fetch-Site`, a client that sends neither header, an IP over its bucket, a signed-out or - * unverified session, a person over their connect-link limit, and a start that ends anywhere but - * ready. Each must leave the person unenrolled (or send them back to the connect page, which - * explains the outcome); a same-origin post goes through without leaking the minted link through - * a cache or a Referer. No GET handler exists, so a link click or prefetch never confirms. + * The connect page's Connect POST enrolls or binds the signed-in person and mints their link, so + * it must only act on a request a page on this origin sent, by a verified person within their + * rate limit. Failure modes: a cross-site form post, a post from another origin whose browser + * sends no `Sec-Fetch-Site`, a client that sends neither header, a signed-out or unverified + * session, a person over their limit, a limiter outage, and a start that ends anywhere but + * started. Each leaves the person untouched and goes back to the connect page (with `error` for a + * limit or an outage), never to raw JSON; a started connection goes straight to the provider's + * OAuth start without leaking the minted link through a cache or a Referer. No GET handler exists, + * so a link click or prefetch never starts anything. */ import { authMockFns } from '@sim/testing/mocks/auth.mock' import { createMockRequest } from '@sim/testing/mocks/request.mock' -import { NextResponse } from 'next/server' import { beforeEach, describe, expect, it, vi } from 'vitest' -const { mockStart, mockIpRateLimit, mockUserRateLimited } = vi.hoisted(() => ({ +const { mockStart, mockUserRateLimit } = vi.hoisted(() => ({ mockStart: vi.fn(), - mockIpRateLimit: vi.fn(), - mockUserRateLimited: vi.fn(), + mockUserRateLimit: vi.fn(), })) vi.mock('@/lib/credential-groups/application/connect-target', () => ({ startCredentialGroupConnect: { execute: mockStart }, })) +vi.mock('@/lib/messaging/email/verification', () => ({ + isEmailVerificationEffectivelyEnabled: () => true, +})) vi.mock('@/lib/credential-groups/rate-limit', () => ({ - enforcePublicCredentialGroupIpRateLimit: mockIpRateLimit, - isCredentialGroupConnectUserRateLimited: mockUserRateLimited, + checkCredentialGroupConnectUserRateLimit: mockUserRateLimit, })) import * as connectRoute from '@/app/api/credential-groups/connect/[publicId]/route' @@ -48,9 +49,8 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { user: { id: 'user-1', emailVerified: true }, session: { id: 'session-1' }, }) - mockIpRateLimit.mockResolvedValue(null) - mockUserRateLimited.mockResolvedValue(false) - mockStart.mockResolvedValue({ kind: 'ready', invitationToken: 'token-1', optionId: 'drive' }) + mockUserRateLimit.mockResolvedValue('allowed') + mockStart.mockResolvedValue({ kind: 'started', invitationToken: 'token-1', optionId: 'drive' }) }) it.each([ @@ -60,17 +60,8 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { ['a client sending neither header', {}], ])('refuses %s without enrolling anyone', async (_label, headers) => { const response = await confirm(headers) - expect(response.status).toBe(403) - expect(response.headers.get('location')).toBeNull() - expect(mockStart).not.toHaveBeenCalled() - }) - - it('refuses an IP over its bucket without enrolling anyone', async () => { - mockIpRateLimit.mockResolvedValueOnce( - NextResponse.json({ error: 'Too many requests' }, { status: 429 }) - ) - const response = await confirm() - expect(response.status).toBe(429) + expect(response.status).toBe(303) + expect(response.headers.get('location')).toBe(CONNECT_PATH) expect(mockStart).not.toHaveBeenCalled() }) @@ -88,14 +79,20 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { expect(mockStart).not.toHaveBeenCalled() }) - it('sends a person over their connect-link limit back without enrolling them', async () => { - mockUserRateLimited.mockResolvedValueOnce(true) - const response = await confirm() - expect(response.headers.get('location')).toBe(CONNECT_PATH) - expect(mockStart).not.toHaveBeenCalled() - }) + it.each([ + ['over their limit', 'limited', 'rate_limited'], + ['during a limiter outage', 'unavailable', 'try_again'], + ])( + 'sends a person %s back with the reason, without enrolling them', + async (_label, limit, error) => { + mockUserRateLimit.mockResolvedValueOnce(limit) + const response = await confirm() + expect(response.headers.get('location')).toBe(`${CONNECT_PATH}&error=${error}`) + expect(mockStart).not.toHaveBeenCalled() + } + ) - it.each(['not_invited', 'revoked', 'unavailable', 'wrong_account'])( + it.each(['not_invited', 'revoked', 'expired', 'different_email', 'unavailable', 'wrong_account'])( 'sends a %s outcome back to the connect page to explain it', async (kind) => { mockStart.mockResolvedValueOnce({ kind }) @@ -105,13 +102,14 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { } ) - it('confirms enrollment and continues to the focused enrollment page, uncached and unreferred', async () => { + it('goes straight to the OAuth start for the started option, uncached and unreferred', async () => { const response = await confirm() expect(response.status).toBe(303) - expect(response.headers.get('location')).toMatch(/^\/credential-groups\/enroll\/token-1\?/) + expect(response.headers.get('location')).toBe( + '/api/credential-groups/enroll/token-1/oauth/drive?origin=connect&return=slack' + ) expect(response.headers.get('cache-control')).toBe('no-store') expect(response.headers.get('referrer-policy')).toBe('no-referrer') - expect(mockStart.mock.calls[0]?.[0]?.input).toMatchObject({ confirmSelfEnrollment: true }) }) it('has no GET handler, so following or prefetching the URL never confirms', () => { diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts index 3060e5e8f76..eaf8dc8b064 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts @@ -1,68 +1,61 @@ import type { NextRequest } from 'next/server' -import { NextResponse } from 'next/server' -import { confirmCredentialGroupConnectContract } from '@/lib/api/contracts/credential-groups' +import { startCredentialGroupConnectContract } from '@/lib/api/contracts/credential-groups' import { parseRequest } from '@/lib/api/server' -import { getSession } from '@/lib/auth' import { isSameOriginSessionRequest } from '@/lib/core/security/same-origin' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' +import { resolveCredentialGroupConnectSession } from '@/lib/credential-groups/connect-session' import { - buildCredentialGroupConnectHandoffPath, + buildCredentialGroupConnectOAuthStartPath, buildCredentialGroupConnectPath, } from '@/lib/credential-groups/connect-url' -import { - enforcePublicCredentialGroupIpRateLimit, - isCredentialGroupConnectUserRateLimited, -} from '@/lib/credential-groups/rate-limit' import { createNoStoreRedirect } from '@/app/api/credential-groups/enrollment-redirect' export const dynamic = 'force-dynamic' export const runtime = 'nodejs' /** - * The connect page's "Connect" button for an organization member with no enrollment: enrolls - * them and continues to the focused enrollment page. Any other outcome goes back to the connect - * page, which explains it, so this route never renders a state of its own. + * The connect page's Connect button. Enrolls or binds the person and mints their focused link in + * one transaction, then goes straight to the provider's OAuth start for that option. Anything + * else goes back to the connect page (a refusal it explains itself, or `error` for a limit or an + * outage), so this route never renders a state of its own. */ export const POST = withRouteHandler( async (request: NextRequest, context: { params: Promise<{ publicId: string }> }) => { - if (!isSameOriginSessionRequest(request)) - return NextResponse.json( - { error: 'Cross-site request refused' }, - { status: 403, headers: { 'Cache-Control': 'no-store' } } - ) - const limited = await enforcePublicCredentialGroupIpRateLimit(request, 'connect-confirm') - if (limited) return limited - - const parsed = await parseRequest(confirmCredentialGroupConnectContract, request, context) + const parsed = await parseRequest(startCredentialGroupConnectContract, request, context) if (!parsed.success) return parsed.response const { publicId } = parsed.data.params - const { provider, optionId, return: returnValue } = parsed.data.query - const connectPath = buildCredentialGroupConnectPath({ - publicId, - provider, - optionId, - returnValue, - }) + const { provider, optionId, for: requestHandle, return: returnTo } = parsed.data.query + const backToConnect = (error?: 'rate_limited' | 'try_again') => { + const path = buildCredentialGroupConnectPath({ + publicId, + provider, + optionId, + requestHandle, + returnTo, + }) + return createNoStoreRedirect(error ? `${path}&error=${error}` : path, 303) + } + if (!isSameOriginSessionRequest(request)) return backToConnect() - const session = await getSession() - if (!session?.user?.emailVerified) return createNoStoreRedirect(connectPath, 303) - if (await isCredentialGroupConnectUserRateLimited(session.user.id)) - return createNoStoreRedirect(connectPath, 303) + const session = await resolveCredentialGroupConnectSession() + if (session.kind === 'rate_limited' || session.kind === 'try_again') + return backToConnect(session.kind) + if (session.kind !== 'signed_in') return backToConnect() - const target = await startCredentialGroupConnect.execute({ - principal: { kind: 'session', userId: session.user.id, sessionId: session.session.id }, + const started = await startCredentialGroupConnect.execute({ + principal: session.principal, input: { publicId, provider, ...(optionId ? { optionId } : {}), - ...(returnValue ? { returnUrl: returnValue } : {}), - confirmSelfEnrollment: true, + ...(requestHandle ? { requestHandle } : {}), }, request, }) + if (started.kind !== 'started') return backToConnect() return createNoStoreRedirect( - target.kind === 'ready' ? buildCredentialGroupConnectHandoffPath(target) : connectPath, + buildCredentialGroupConnectOAuthStartPath({ ...started, returnTo }), 303 ) } diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts index d54ae38ac6f..ee41221d4cf 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/complete/route.ts @@ -23,16 +23,16 @@ export const POST = withRouteHandler( const parsed = await parseRequest(completeCredentialGroupEnrollmentContract, request, context) if (!parsed.success) return parsed.response const { token } = parsed.data.params - const { return: returnUrl } = parsed.data.query + const { return: returnTo } = parsed.data.query const backToEnrollment = (oauth: 'unavailable' | 'other_option') => createCredentialGroupEnrollmentRedirect(token, { oauth, - ...(returnUrl ? { return: returnUrl } : {}), + ...(returnTo ? { return: returnTo } : {}), }) const principal = await authenticateCredentialGroupEnrollment(token) if (!principal) return backToEnrollment('unavailable') const completion = await completePublicCredentialGroupEnrollment - .execute({ principal, input: returnUrl ? { returnUrl } : {}, request }) + .execute({ principal, input: {}, request }) .catch((error: unknown) => { if (isCredentialGroupLinkFocusError(error)) return 'focused' as const if (asOrchestrationError(error)?.code === 'not_found') return null @@ -40,8 +40,6 @@ export const POST = withRouteHandler( }) if (completion === 'focused') return backToEnrollment('other_option') if (!completion || completion.completed === null) return backToEnrollment('unavailable') - return createCredentialGroupCompletionRedirect({ - completionReturnId: completion.completionReturnId, - }) + return createCredentialGroupCompletionRedirect({ returnTo }) } ) diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts index 820bfc18b0b..1971643e383 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts @@ -29,22 +29,22 @@ export const GET = withRouteHandler( request: NextRequest, context: { params: Promise<{ token: string; mcpServerId: string }> } ) => { - const limited = await enforcePublicCredentialGroupOAuthStartIpRateLimit(request) const parsed = await parseRequest(startCredentialGroupMcpOAuthContract, request, context) - if (!parsed.success) return limited ?? parsed.response + if (!parsed.success) return parsed.response const { token, mcpServerId } = parsed.data.params - const { returnTo, return: returnUrl } = parsed.data.query - /** Passed back as given, like the OAuth start route: the enrollment page keeps only allowed ones. */ + const { origin, return: returnTo } = parsed.data.query + // Passed back as given, like the OAuth start route, so the enrollment page keeps its focus. const focus: Record = { - ...(returnTo ? { returnTo } : {}), - ...(returnUrl ? { return: returnUrl } : {}), + ...(origin ? { origin } : {}), + ...(returnTo ? { return: returnTo } : {}), } const backToEnrollment = (oauth: string) => createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth }) - if (limited) return backToEnrollment('rate_limited') - const principal = await authenticateCredentialGroupEnrollment(token) - if (!principal) return backToEnrollment('unavailable') + if (!principal) { + const limited = await enforcePublicCredentialGroupOAuthStartIpRateLimit(request) + return backToEnrollment(limited ? 'rate_limited' : 'unavailable') + } const enrollmentLimited = await enforceCredentialGroupEnrollmentOAuthRateLimit( principal.enrollmentId ) diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.test.ts b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.test.ts index f7411cc723e..0cda855336f 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.test.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.test.ts @@ -53,16 +53,16 @@ describe('credential group OAuth start route', () => { it.each(['search', 'accounts'] as const)( 'forwards only a closed return context to the authorized operation: %s', - async (returnTo) => { - await GET(request(`?returnTo=${returnTo}`), context) + async (origin) => { + await GET(request(`?origin=${origin}`), context) expect(mocks.startOAuth).toHaveBeenCalledWith( expect.objectContaining({ principal, - input: { invitationToken: 'invitation-token', optionId: 'option-1', returnTo }, + input: { invitationToken: 'invitation-token', optionId: 'option-1', origin }, }) ) mocks.startOAuth.mockClear() - const response = await GET(request('?returnTo=https://external.test'), context) + const response = await GET(request('?origin=https://external.test'), context) expect(response.status).toBe(400) expect(mocks.startOAuth).not.toHaveBeenCalled() } @@ -71,28 +71,40 @@ describe('credential group OAuth start route', () => { it.each(['ip', 'enrollment', 'unavailable', 'configuration'])( 'preserves exact Search focus after %s failure', async (failure) => { - if (failure === 'ip') + if (failure === 'ip') { + mocks.authenticate.mockResolvedValue(null) mocks.ipRateLimit.mockResolvedValue(NextResponse.json({}, { status: 429 })) + } if (failure === 'enrollment') mocks.enrollmentRateLimit.mockResolvedValue(NextResponse.json({}, { status: 429 })) if (failure === 'unavailable') mocks.authenticate.mockResolvedValue(null) if (failure === 'configuration') mocks.startOAuth.mockRejectedValue(new Error('Unavailable configuration')) - const response = await GET(request('?returnTo=search'), context) + const response = await GET(request('?origin=search'), context) const location = new URL(response.headers.get('location')!, 'http://localhost') expect(location.pathname).toBe('/credential-groups/enroll/invitation-token') expect(location.searchParams.get('optionId')).toBe('option-1') - expect(location.searchParams.get('returnTo')).toBe('search') + expect(location.searchParams.get('origin')).toBe('search') expect(location.searchParams.get('oauth')).toBe( failure === 'ip' || failure === 'enrollment' ? 'rate_limited' : 'unavailable' ) } ) - it('returns a rate-limited OAuth start to its enrollment page before token lookup', async () => { - mocks.ipRateLimit.mockResolvedValue( - NextResponse.json({ error: 'Too many requests' }, { status: 429 }) + it('holds a signed-in start to its enrollment budget, not the shared IP bucket', async () => { + mocks.ipRateLimit.mockResolvedValue(NextResponse.json({}, { status: 429 })) + + const response = await GET(request(), context) + + expect(response.headers.get('location')).toBe( + 'https://accounts.google.com/o/oauth2/v2/auth?state=state-1' ) + expect(mocks.ipRateLimit).not.toHaveBeenCalled() + }) + + it('returns an unauthenticated start over its IP bucket to its enrollment page', async () => { + mocks.authenticate.mockResolvedValue(null) + mocks.ipRateLimit.mockResolvedValue(NextResponse.json({}, { status: 429 })) const response = await GET(request(), context) @@ -100,6 +112,5 @@ describe('credential group OAuth start route', () => { expect(response.headers.get('location')).toBe( '/credential-groups/enroll/invitation-token?oauth=rate_limited' ) - expect(mocks.authenticate).not.toHaveBeenCalled() }) }) diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts index e72f15c053f..72fcfba06b9 100644 --- a/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts +++ b/apps/sim/app/api/credential-groups/enroll/[token]/oauth/[optionId]/route.ts @@ -27,22 +27,21 @@ export const GET = withRouteHandler( request: NextRequest, context: { params: Promise<{ token: string; optionId: string }> } ) => { - const limited = await enforcePublicCredentialGroupOAuthStartIpRateLimit(request) - const parsed = await parseRequest(startCredentialGroupOAuthContract, request, context) - if (!parsed.success) return limited ?? parsed.response + if (!parsed.success) return parsed.response const { token, optionId } = parsed.data.params - const { returnTo, return: returnUrl } = parsed.data.query - /** Passed through as given: the use case and the enrollment page each keep only an allowed one. */ + const { origin, return: returnTo } = parsed.data.query const focus: Record = { - ...(returnTo ? { optionId, returnTo } : {}), - ...(returnUrl ? { return: returnUrl } : {}), + ...(origin ? { optionId, origin } : {}), + ...(returnTo ? { return: returnTo } : {}), } const backToEnrollment = (oauth: string) => createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth }) - if (limited) return backToEnrollment('rate_limited') const principal = await authenticateCredentialGroupEnrollment(token) - if (!principal) return backToEnrollment('unavailable') + if (!principal) { + const limited = await enforcePublicCredentialGroupOAuthStartIpRateLimit(request) + return backToEnrollment(limited ? 'rate_limited' : 'unavailable') + } const enrollmentLimited = await enforceCredentialGroupEnrollmentOAuthRateLimit( principal.enrollmentId @@ -55,8 +54,8 @@ export const GET = withRouteHandler( input: { invitationToken: token, optionId, + ...(origin ? { origin } : {}), ...(returnTo ? { returnTo } : {}), - ...(returnUrl ? { returnUrl } : {}), }, request, }) diff --git a/apps/sim/app/api/credential-groups/enrollment-redirect.ts b/apps/sim/app/api/credential-groups/enrollment-redirect.ts index 049fba195a6..0e63405075e 100644 --- a/apps/sim/app/api/credential-groups/enrollment-redirect.ts +++ b/apps/sim/app/api/credential-groups/enrollment-redirect.ts @@ -1,4 +1,5 @@ import { NextResponse } from 'next/server' +import type { ConnectReturnDestination } from '@/lib/credential-groups/connect-return' import type { CredentialGroupOAuthFailure } from '@/lib/credential-groups/oauth-completion' /** @@ -27,24 +28,20 @@ interface CredentialGroupCompletionRedirectOptions { completionId?: string /** Set when the connection started from the organization's Integrations page. */ organizationId?: string - /** The opaque ID of a Slack return destination the server stored for the person. */ - completionReturnId?: string + returnTo?: ConnectReturnDestination } -/** - * Sends the person to the completion page. A Slack return travels only as `completionReturnId`, - * the opaque ID of a destination the server stored for them, never as a URL in the query. - */ +/** Sends the person to the completion page. */ export function createCredentialGroupCompletionRedirect({ oauth, completionId, organizationId, - completionReturnId, + returnTo, }: CredentialGroupCompletionRedirectOptions = {}): NextResponse { const query = new URLSearchParams() if (oauth) query.set('oauth', oauth) if (completionId) query.set('completionId', completionId) if (organizationId) query.set('organizationId', organizationId) - if (completionReturnId) query.set('returnId', completionReturnId) + if (returnTo) query.set('return', returnTo) return createNoStoreRedirect(`/credential-groups/complete${query.size ? `?${query}` : ''}`, 303) } diff --git a/apps/sim/app/api/credential-groups/oauth-callback.test.ts b/apps/sim/app/api/credential-groups/oauth-callback.test.ts index dc25b3bafd9..7ca38325bac 100644 --- a/apps/sim/app/api/credential-groups/oauth-callback.test.ts +++ b/apps/sim/app/api/credential-groups/oauth-callback.test.ts @@ -45,7 +45,7 @@ const attempt = { provider: 'github-repositories', invitationToken: 'invitation-token', optionId: 'option-1', - returnTo: 'search', + origin: 'search', } as const function completeCallback() { @@ -104,7 +104,7 @@ describe('GitHub managed OAuth failure presentation', () => { } else { expect(location.pathname).toBe('/credential-groups/enroll/invitation-token') expect(location.searchParams.get('optionId')).toBe(attempt.optionId) - expect(location.searchParams.get('returnTo')).toBe('search') + expect(location.searchParams.get('origin')).toBe('search') } expect(logError).toHaveBeenCalledExactlyOnceWith('Managed OAuth authorization failed', { provider: 'github-repositories', @@ -175,7 +175,7 @@ describe('GitHub installation setup OAuth return target', () => { async (stage) => { mocks.consumeAttempt.mockResolvedValue({ ...attempt, - returnTo: 'github-installation', + origin: 'github-installation', organizationId: 'organization', completionId, }) @@ -200,7 +200,7 @@ describe('GitHub installation setup OAuth return target', () => { it('resumes only the server-owned setup after the guarded OAuth completion', async () => { mocks.consumeAttempt.mockResolvedValue({ ...attempt, - returnTo: 'github-installation', + origin: 'github-installation', organizationId: 'organization', completionId, completionRedirect: true, @@ -218,7 +218,7 @@ describe('GitHub installation setup OAuth return target', () => { it('returns classified OAuth failure to setup status without accepting a client redirect URL', async () => { mocks.consumeAttempt.mockResolvedValue({ ...attempt, - returnTo: 'github-installation', + origin: 'github-installation', organizationId: 'organization', completionId, completionRedirect: true, @@ -245,7 +245,7 @@ describe('Integrations OAuth completion', () => { async (error) => { mocks.consumeAttempt.mockResolvedValueOnce({ ...attempt, - returnTo: 'integrations', + origin: 'integrations', organizationId: 'organization-1', completionRedirect: true, completionId, @@ -270,7 +270,7 @@ describe('Integrations OAuth completion', () => { }) describe('Slack return destination', () => { - const forgedReturn = 'https://slack.com/app_redirect?app=AFORGED' + const forgedReturn = 'https://evil.example' function callbackWithForgedReturn() { return handleCredentialGroupOAuthCallback({ @@ -290,14 +290,14 @@ describe('Slack return destination', () => { it.each([ { stored: undefined, expected: null }, - { stored: 'slack://open', expected: 'slack://open' }, + { stored: 'slack', expected: 'slack' }, ])( 'returns to $expected from the stored attempt, ignoring the callback query', async ({ stored, expected }) => { mocks.consumeAttempt.mockResolvedValueOnce({ ...attempt, - returnTo: 'connect', - ...(stored ? { returnUrl: stored } : {}), + origin: 'connect', + ...(stored ? { returnTo: stored } : {}), }) const response = await callbackWithForgedReturn() const destination = new URL(response.headers.get('location') ?? '', 'https://sim.test') diff --git a/apps/sim/app/api/credential-groups/oauth-callback.ts b/apps/sim/app/api/credential-groups/oauth-callback.ts index d3eacbd1cb0..cd80f6e2fb0 100644 --- a/apps/sim/app/api/credential-groups/oauth-callback.ts +++ b/apps/sim/app/api/credential-groups/oauth-callback.ts @@ -7,7 +7,6 @@ import { internalSessionAuth } from '@/lib/api/server/routes' import { asOrchestrationError, statusForOrchestrationError } from '@/lib/core/orchestration/types' import { credentialGroupOAuthAttemptPrincipal } from '@/lib/credential-groups/application/enrollment-auth' import { completePublicCredentialGroupOAuth } from '@/lib/credential-groups/application/public-enrollment' -import { createCredentialGroupCompletionReturn } from '@/lib/credential-groups/completion-return' import { CredentialGroupOAuthStateVersionError } from '@/lib/credential-groups/oauth-attempt-version' import type { CredentialGroupOAuthFailure } from '@/lib/credential-groups/oauth-completion' import { consumeCredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' @@ -65,13 +64,15 @@ export async function handleCredentialGroupOAuthCallback({ }) return createCredentialGroupCompletionRedirect({ oauth: 'unavailable' }) } + if (attempt && 'expired' in attempt) + return createCredentialGroupCompletionRedirect({ oauth: 'expired', returnTo: attempt.returnTo }) if (!attempt || attempt.provider !== provider) { return createCredentialGroupCompletionRedirect({ oauth: limited ? 'rate_limited' : 'expired' }) } - /** The return destination comes only from server-held attempt state, never the callback query. */ + // Origin and return destination come only from server-held attempt state, never the query. const focus: Record = { - ...(attempt.returnTo ? { optionId: attempt.optionId, returnTo: attempt.returnTo } : {}), - ...(attempt.returnUrl ? { return: attempt.returnUrl } : {}), + ...(attempt.origin ? { optionId: attempt.optionId, origin: attempt.origin } : {}), + ...(attempt.returnTo ? { return: attempt.returnTo } : {}), } const setupRedirect = (oauth?: CredentialGroupOAuthFailure) => new NextResponse(null, { @@ -86,20 +87,17 @@ export async function handleCredentialGroupOAuthCallback({ }, }) const installationSetup = - attempt.returnTo === 'github-installation' && attempt.organizationId && attempt.completionId + attempt.origin === 'github-installation' && attempt.organizationId && attempt.completionId const returnOrganizationId = - attempt.returnTo === 'integrations' ? attempt.organizationId : undefined - const completionRedirect = async (oauth?: CredentialGroupOAuthFailure) => + attempt.origin === 'integrations' ? attempt.organizationId : undefined + const completionRedirect = (oauth?: CredentialGroupOAuthFailure) => createCredentialGroupCompletionRedirect({ oauth, completionId: attempt.completionId, organizationId: returnOrganizationId, - completionReturnId: await createCredentialGroupCompletionReturn({ - userId: attempt.userId, - returnUrl: attempt.returnUrl, - }), + returnTo: attempt.returnTo, }) - const failureRedirect = async (oauth: CredentialGroupOAuthFailure) => + const failureRedirect = (oauth: CredentialGroupOAuthFailure) => installationSetup ? setupRedirect(oauth) : attempt.completionRedirect diff --git a/apps/sim/app/api/credential-groups/oauth/[provider]/callback/route.test.ts b/apps/sim/app/api/credential-groups/oauth/[provider]/callback/route.test.ts index da968943b82..bac3c3cf38e 100644 --- a/apps/sim/app/api/credential-groups/oauth/[provider]/callback/route.test.ts +++ b/apps/sim/app/api/credential-groups/oauth/[provider]/callback/route.test.ts @@ -82,18 +82,18 @@ describe('credential group OAuth callback', () => { [new CredentialGroupOAuthError('Changed settings', 409), 'configuration_changed'], [new Error('Provider failed'), 'failed'], ])('retains Search focus after a rejected provider exchange: %s', async (error, status) => { - mocks.consumeAttempt.mockResolvedValue({ ...attempt, returnTo: 'search' }) + mocks.consumeAttempt.mockResolvedValue({ ...attempt, origin: 'search' }) mocks.completeOAuth.mockRejectedValueOnce(error) const response = await GET(request('state=state-1&code=code-1'), context) expect(response.headers.get('location')).toBe( - `/credential-groups/enroll/invitation-token?optionId=option-1&returnTo=search&oauth=${status}` + `/credential-groups/enroll/invitation-token?optionId=option-1&origin=search&oauth=${status}` ) }) it.each(['denied', 'rate_limited'])( 'retains Search focus without exchanging after %s', async (status) => { - mocks.consumeAttempt.mockResolvedValue({ ...attempt, returnTo: 'search' }) + mocks.consumeAttempt.mockResolvedValue({ ...attempt, origin: 'search' }) if (status === 'rate_limited') mocks.rateLimit.mockResolvedValue(NextResponse.json({}, { status: 429 })) const response = await GET( @@ -103,7 +103,7 @@ describe('credential group OAuth callback', () => { context ) expect(response.headers.get('location')).toBe( - `/credential-groups/enroll/invitation-token?optionId=option-1&returnTo=search&oauth=${status}` + `/credential-groups/enroll/invitation-token?optionId=option-1&origin=search&oauth=${status}` ) expect(mocks.completeOAuth).not.toHaveBeenCalled() } diff --git a/apps/sim/app/api/mcp/oauth/callback/route.test.ts b/apps/sim/app/api/mcp/oauth/callback/route.test.ts index f3f9a7c3a6c..7a06970cf33 100644 --- a/apps/sim/app/api/mcp/oauth/callback/route.test.ts +++ b/apps/sim/app/api/mcp/oauth/callback/route.test.ts @@ -113,7 +113,7 @@ describe('MCP OAuth callback route', () => { invitationToken: 'invitation-token', mcpServerId: 'server-1', completionId, - returnTo: 'integrations', + origin: 'integrations', }) const response = await GET( new NextRequest( diff --git a/apps/sim/app/api/mcp/oauth/callback/route.ts b/apps/sim/app/api/mcp/oauth/callback/route.ts index 259e74f3335..ff8b06f3f11 100644 --- a/apps/sim/app/api/mcp/oauth/callback/route.ts +++ b/apps/sim/app/api/mcp/oauth/callback/route.ts @@ -115,7 +115,7 @@ async function completeManagedMcpCallback(params: { ? createCredentialGroupCompletionRedirect({ oauth, completionId: attempt.completionId, - organizationId: attempt.returnTo === 'integrations' ? attempt.organizationId : undefined, + organizationId: attempt.origin === 'integrations' ? attempt.organizationId : undefined, }) : createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { oauth }) if (params.error) { @@ -155,7 +155,7 @@ async function completeManagedMcpCallback(params: { if (attempt.completionId) return createCredentialGroupCompletionRedirect({ completionId: attempt.completionId, - organizationId: attempt.returnTo === 'integrations' ? attempt.organizationId : undefined, + organizationId: attempt.origin === 'integrations' ? attempt.organizationId : undefined, }) return createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { mcp: 'connected', diff --git a/apps/sim/app/api/organizations/[id]/connected-accounts/connect/route.ts b/apps/sim/app/api/organizations/[id]/connected-accounts/connect/route.ts index 51aa2a4a346..e34d132954a 100644 --- a/apps/sim/app/api/organizations/[id]/connected-accounts/connect/route.ts +++ b/apps/sim/app/api/organizations/[id]/connected-accounts/connect/route.ts @@ -21,7 +21,7 @@ export const POST = defineInternalJsonRoute({ mapInput: ({ params, body }) => ({ organizationId: params.id, ...body, - ...(body.oauthCompletionId ? { returnTo: 'integrations' as const } : {}), + ...(body.oauthCompletionId ? { origin: 'integrations' as const } : {}), }), useCase: startOrganizationAccountConnection, }) diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index 9b384a6cfaa..fd30dba9ec0 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -1,22 +1,21 @@ import type { Metadata } from 'next' import { headers } from 'next/headers' import { redirect } from 'next/navigation' -import { getSession } from '@/lib/auth' -import { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' +import { openCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' import { - buildCredentialGroupConnectHandoffPath, - buildCredentialGroupConnectPath, -} from '@/lib/credential-groups/connect-url' + connectReturnHref, + parseConnectReturnDestination, +} from '@/lib/credential-groups/connect-return' +import { resolveCredentialGroupConnectSession } from '@/lib/credential-groups/connect-session' +import { buildCredentialGroupConnectPath } from '@/lib/credential-groups/connect-url' import { getCredentialGroupProviderService } from '@/lib/credential-groups/providers' -import { - enforcePublicCredentialGroupIpRateLimit, - isCredentialGroupConnectUserRateLimited, -} from '@/lib/credential-groups/rate-limit' -import { resolveCredentialGroupConnectReturnUrl } from '@/lib/credential-groups/return-url' +import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' import { ChooseConnectOption, ConnectConfirm, + DifferentEmail, NotInvited, + RequestExpired, UnavailableInvitation, VerifyEmail, WrongAccount, @@ -27,7 +26,7 @@ export const metadata: Metadata = { robots: { index: false, follow: false }, } -/** Every visit mints a fresh link for whoever is signed in, so nothing here may be cached. */ +/** Each visit is decided for whoever is signed in, so nothing here may be cached. */ export const dynamic = 'force-dynamic' export const revalidate = 0 @@ -49,13 +48,13 @@ function getSearchParam( const UNAVAILABLE_MESSAGE = 'This link isn’t available. Ask whoever sent it to check it’s still set up.' +const TRY_AGAIN_MESSAGE = 'Something went wrong. Try again in a moment.' /** * The secret-free link a workflow shows when someone has not connected an account yet. Signs the - * person in, resolves their own enrollment, and hands off to the enrollment page with a - * short-lived link focused on the one account asked for. Link unfurlers and prefetchers are never - * signed in, so they stop at the login redirect and mint nothing. An organization member with no - * enrollment confirms with a button whose POST enrolls them; this GET never creates one. + * person in and shows what the link will do for them; it writes nothing. Its one Connect button + * POSTs to the start route, which enrolls or binds the person, mints their focused link, and goes + * on to the provider. Link unfurlers and prefetchers only GET, so they never enroll anyone. */ export default async function CredentialGroupConnectPage({ params, @@ -65,101 +64,132 @@ export default async function CredentialGroupConnectPage({ const query = await searchParams const provider = getSearchParam(query, 'provider') const optionId = getSearchParam(query, 'optionId') - const returnValue = getSearchParam(query, 'return') - const slackReturnHref = resolveCredentialGroupConnectReturnUrl(returnValue) + const requestHandle = getSearchParam(query, 'for') + const returnTo = parseConnectReturnDestination(getSearchParam(query, 'return')) + const slackHref = returnTo ? connectReturnHref(returnTo) : undefined + const startError = getSearchParam(query, 'error') const limited = await enforcePublicCredentialGroupIpRateLimit( { headers: await headers() }, 'metadata' ) - if (limited) return + if (limited) return const unavailable = ( ) if (!publicId || publicId.length > 128 || !provider || provider.length > 128) return unavailable - const callbackUrl = buildCredentialGroupConnectPath({ publicId, provider, optionId, returnValue }) - - const session = await getSession() - if (!session?.user) redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) - if (!session.user.emailVerified) - return - if (await isCredentialGroupConnectUserRateLimited(session.user.id)) - return + const linkPath = (overrides: { optionId?: string } = {}) => + buildCredentialGroupConnectPath({ + publicId, + provider, + optionId, + requestHandle, + returnTo, + ...overrides, + }) + const callbackUrl = linkPath() + const tryAgain = ( + + ) - const principal = { - kind: 'session' as const, - userId: session.user.id, - sessionId: session.session.id, + const session = await resolveCredentialGroupConnectSession() + switch (session.kind) { + case 'sign_in': + return redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) + case 'verify_email': + return + case 'rate_limited': + return + case 'try_again': + return tryAgain } - const input = { - publicId, - provider, - ...(optionId ? { optionId } : {}), - ...(returnValue ? { returnUrl: returnValue } : {}), - } - const target = await startCredentialGroupConnect.execute({ principal, input }) + if (startError === 'rate_limited') + return + if (startError === 'try_again') return tryAgain - switch (target.kind) { - case 'ready': - return redirect(buildCredentialGroupConnectHandoffPath(target)) - case 'wrong_account': + const outcome = await openCredentialGroupConnect.execute({ + principal: session.principal, + input: { + publicId, + provider, + ...(optionId ? { optionId } : {}), + ...(requestHandle ? { requestHandle } : {}), + }, + }) + switch (outcome.kind) { + case 'ready_to_connect': + case 'confirm_self_enrollment': { + const startQuery = new URLSearchParams({ provider, optionId: outcome.optionId }) + if (requestHandle) startQuery.set('for', requestHandle) + if (returnTo) startQuery.set('return', returnTo) return ( - + ) + } + case 'verify_email': + return + case 'different_email': + return ( + ) - case 'confirm_self_enrollment': { - const confirmQuery = new URLSearchParams({ provider, optionId: target.optionId }) - if (returnValue) confirmQuery.set('return', returnValue) + case 'wrong_account': return ( - ) - } case 'not_invited': return ( ) + case 'expired': + return case 'revoked': return ( ) case 'choose_option': return ( ({ + integration={getCredentialGroupProviderService(outcome.provider).name} + organizationName={outcome.organizationName} + options={outcome.options.map((option) => ({ ...option, - href: buildCredentialGroupConnectPath({ - publicId, - provider, - optionId: option.id, - returnValue, - }), + href: linkPath({ optionId: option.id }), }))} - slackHref={slackReturnHref} + slackHref={slackHref} /> ) case 'unavailable': diff --git a/apps/sim/app/credential-groups/complete/completion-view.ts b/apps/sim/app/credential-groups/complete/completion-view.ts index 1a975b861cd..82809aedbed 100644 --- a/apps/sim/app/credential-groups/complete/completion-view.ts +++ b/apps/sim/app/credential-groups/complete/completion-view.ts @@ -1,6 +1,10 @@ import { isValidUuid } from '@sim/utils/id' -import { readCredentialGroupCompletionReturn } from '@/lib/credential-groups/completion-return' import { + connectReturnHref, + parseConnectReturnDestination, +} from '@/lib/credential-groups/connect-return' +import { + CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES, type CredentialGroupOAuthFailure, isCredentialGroupOAuthFailure, } from '@/lib/credential-groups/oauth-completion' @@ -10,11 +14,13 @@ type CompletionSearchParams = Record export interface CredentialGroupCompletionView { failure?: CredentialGroupOAuthFailure + /** What the page says about {@link failure}. */ + error?: string /** The opener tab's correlation ID, for the cross-tab completion handoff. */ completionId?: string /** Back to the organization's Integrations page, for a connection started there. */ integrationsHref?: string - /** A "Return to Slack" destination, only ever from server-held state bound to the viewer. */ + /** "Return to Slack", for a connection a Slack workflow asked for. */ slackReturnHref?: string } @@ -23,32 +29,32 @@ function single(value: string | string[] | undefined): string | undefined { } /** - * Resolves what the completion page shows from its query and the signed-in viewer. A Slack - * destination comes only from `returnId`, an opaque ID the server stored for this viewer; a - * `return` URL in the query is never read. + * Resolves what the completion page shows from its query. `return` names only a fixed + * destination, so a forged one can at most offer to open Slack. */ -export async function resolveCredentialGroupCompletionView({ - searchParams, - userId, -}: { +export function resolveCredentialGroupCompletionView( searchParams: CompletionSearchParams - userId: string | undefined -}): Promise { +): CredentialGroupCompletionView { const oauth = searchParams.oauth const completionId = single(searchParams.completionId) const organizationId = single(searchParams.organizationId) - const slackReturnHref = await readCredentialGroupCompletionReturn({ - returnId: single(searchParams.returnId), - userId, - }) + const returnTo = parseConnectReturnDestination(single(searchParams.return)) + const failure = + oauth === undefined ? undefined : isCredentialGroupOAuthFailure(oauth) ? oauth : 'failed' return { - ...(oauth === undefined - ? {} - : { failure: isCredentialGroupOAuthFailure(oauth) ? oauth : 'failed' }), + ...(failure + ? { + failure, + error: + failure === 'expired' && returnTo === 'slack' + ? 'This connection attempt expired. Go back to Slack and tap Connect again.' + : CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure], + } + : {}), ...(completionId && isValidUuid(completionId) ? { completionId } : {}), ...(organizationId && organizationId.length <= 128 ? { integrationsHref: organizationRoutes(encodeURIComponent(organizationId)).integrations } : {}), - ...(slackReturnHref ? { slackReturnHref } : {}), + ...(returnTo ? { slackReturnHref: connectReturnHref(returnTo) } : {}), } } diff --git a/apps/sim/app/credential-groups/complete/page.tsx b/apps/sim/app/credential-groups/complete/page.tsx index 8443f9dfe44..71be4b682fd 100644 --- a/apps/sim/app/credential-groups/complete/page.tsx +++ b/apps/sim/app/credential-groups/complete/page.tsx @@ -1,7 +1,5 @@ import { AuthLinkButton as ChipLink } from '@sim/auth-ui' import type { Metadata } from 'next' -import { getSession } from '@/lib/auth' -import { CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES } from '@/lib/credential-groups/oauth-completion' import { APP_ENTRY_PATH } from '@/lib/navigation/paths' import { AuthHeader, AuthShell } from '@/app/(auth)/components' import { CredentialGroupCompletionHandoff } from '@/app/credential-groups/complete/completion-handoff' @@ -28,15 +26,10 @@ export default async function CredentialGroupCompletePage({ searchParams, }: CredentialGroupCompletePageProps) { const query = await searchParams - /** Only a stored Slack return is bound to the viewer, so only then is the session read. */ - const session = query.returnId ? await getSession() : null - const { failure, completionId, integrationsHref, slackReturnHref } = - await resolveCredentialGroupCompletionView({ searchParams: query, userId: session?.user.id }) - const error = failure ? CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure] : undefined - /** - * Rendered only as links the person clicks: no automatic hop to an external scheme. After a - * failure, Integrations is where the connection started, so it is the way to try again. - */ + const { failure, error, completionId, integrationsHref, slackReturnHref } = + resolveCredentialGroupCompletionView(query) + // Rendered only as links the person clicks: no automatic hop to an external scheme. After a + // failure, Integrations is where the connection started, so it is the way to try again. const appLink = error || integrationsHref ? ( { describe('focused Search enrollment', () => { it('shows only the exact requested option and derives the return workspace from the principal', async () => { - await render({ returnTo: 'search', optionId: 'site-two', workspaceId: 'other-workspace' }) + await render({ origin: 'search', optionId: 'site-two', workspaceId: 'other-workspace' }) expect(document.querySelector('h1')?.textContent).toBe('Connect your Confluence account') expect(document.body.textContent).toContain('Second Confluence site') expect(document.body.textContent).not.toContain('First Confluence site') expect(document.body.textContent).not.toContain('Slack') expect(document.body.textContent).not.toContain('Unrelated MCP') expect(oauthLinks().map((link) => link.getAttribute('href'))).toEqual([ - '/api/credential-groups/enroll/invitation/oauth/site-two?returnTo=search', + '/api/credential-groups/enroll/invitation/oauth/site-two?origin=search', ]) expect(document.querySelector('form')).toBeNull() expect( @@ -159,7 +159,7 @@ describe('focused Search enrollment', () => { async (optionId) => { enrollment.options[1]!.status = 'disabled' await render({ - returnTo: 'search', + origin: 'search', optionId: Array.isArray(optionId) ? [...optionId] : optionId, }) expect(document.body.textContent).toContain('Ask an admin') @@ -171,7 +171,7 @@ describe('focused Search enrollment', () => { it('does not treat a success query marker as a connected account', async () => { await render({ - returnTo: 'search', + origin: 'search', optionId: 'site-two', connected: 'site-two', mcp: 'connected', @@ -184,7 +184,7 @@ describe('focused Search enrollment', () => { it('does not resolve enrollment metadata or trust a return workspace after authentication fails', async () => { mocks.authenticate.mockResolvedValue(null) - await render({ returnTo: 'search', optionId: 'site-two', workspaceId: 'other-workspace' }) + await render({ origin: 'search', optionId: 'site-two', workspaceId: 'other-workspace' }) expect(document.body.textContent).toContain('Invitation unavailable') expect(mocks.read).not.toHaveBeenCalled() expect(document.querySelector('a')?.getAttribute('href')).toBe('/home') diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index 79640ea2ec0..e03950c28b5 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -18,6 +18,11 @@ import { explainCredentialGroupEnrollmentLink, } from '@/lib/credential-groups/application/enrollment-link-outcome' import { readPublicCredentialGroupEnrollment } from '@/lib/credential-groups/application/public-enrollment' +import { + type ConnectReturnDestination, + connectReturnHref, + parseConnectReturnDestination, +} from '@/lib/credential-groups/connect-return' import { buildCredentialGroupConnectPath } from '@/lib/credential-groups/connect-url' import { CredentialGroupEnrollmentError } from '@/lib/credential-groups/enrollments' import { getManagedMcpConnectorIcon } from '@/lib/credential-groups/managed-mcp-connector-icons' @@ -25,10 +30,7 @@ import { CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES } from '@/lib/credential-groups import { CredentialGroupProviderConfigurationError } from '@/lib/credential-groups/provider-adapter' import { getCredentialGroupProviderService } from '@/lib/credential-groups/providers' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' -import { - CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD, - parseCredentialGroupReturnUrl, -} from '@/lib/credential-groups/return-url' +import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' import { APP_ENTRY_PATH, organizationRoutes } from '@/lib/navigation/paths' import { AuthHeader } from '@/app/(auth)/components' import { OAuthConnectLink } from '@/app/credential-groups/enroll/[token]/oauth-reconnect-link' @@ -59,11 +61,8 @@ interface EnrollmentLinkProblemProps { signedInEmail: string callbackUrl: string fallbackMessage?: string - /** - * An allowlisted Slack destination the link carried: the way out of a dead end, and offered - * beside Start again on an expired connect link. - */ - slackReturnUrl?: string + /** Where the link offers to return: the way out of a dead end, and kept on Start again. */ + returnTo?: ConnectReturnDestination } function needsNewLinkCopy( @@ -82,8 +81,9 @@ function EnrollmentLinkProblem({ signedInEmail, callbackUrl, fallbackMessage, - slackReturnUrl, + returnTo, }: EnrollmentLinkProblemProps) { + const slackHref = returnTo ? connectReturnHref(returnTo) : undefined switch (outcome.kind) { case 'wrong_account': return ( @@ -91,7 +91,7 @@ function EnrollmentLinkProblem({ token={token} description={`You’re signed in as ${signedInEmail}. This link is for ${outcome.maskedEmail}.`} callbackUrl={callbackUrl} - slackHref={slackReturnUrl} + slackHref={slackHref} /> ) case 'revoked': @@ -100,7 +100,7 @@ function EnrollmentLinkProblem({ token={token} title='Connection no longer needed' message={null} - slackHref={slackReturnUrl} + slackHref={slackHref} /> ) case 'paused': @@ -109,7 +109,7 @@ function EnrollmentLinkProblem({ token={token} title='Connections paused' message={`${outcome.organizationName || 'Your organization'} isn’t collecting account connections right now.`} - slackHref={slackReturnUrl} + slackHref={slackHref} /> ) case 'reopen': @@ -118,11 +118,11 @@ function EnrollmentLinkProblem({
- + @@ -138,15 +138,13 @@ function EnrollmentLinkProblem({ token={token} title={outcome.reason === 'expired' ? 'Link expired' : 'Link no longer active'} message={needsNewLinkCopy(outcome)} - slackHref={slackReturnUrl} + slackHref={slackHref} /> ) case 'unavailable': - return ( - - ) + return case 'unknown': - return + return } } @@ -213,22 +211,21 @@ export default async function CredentialGroupEnrollmentPage({ if (!token || token.length > 128) return const resolvedSearchParams = await searchParams - const rawReturnUrl = getSearchParam(resolvedSearchParams, 'return') - const slackReturnUrl = rawReturnUrl - ? parseCredentialGroupReturnUrl(rawReturnUrl)?.href - : undefined + const rawReturn = getSearchParam(resolvedSearchParams, 'return') + const returnTo = parseConnectReturnDestination(rawReturn) + const slackHref = returnTo ? connectReturnHref(returnTo) : undefined const callback = new URLSearchParams() - for (const key of ['returnTo', 'optionId']) { + for (const key of ['origin', 'optionId']) { const value = getSearchParam(resolvedSearchParams, key) if (value) callback.set(key, value) } - if (slackReturnUrl) callback.set('return', slackReturnUrl) + if (returnTo) callback.set('return', returnTo) const callbackUrl = `/credential-groups/enroll/${encodeURIComponent(token)}${callback.size ? `?${callback}` : ''}` const session = await getSession() if (!session?.user) { redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) } - if (!session.user.emailVerified) + if (!isCredentialGroupEmailVerified(session.user)) return ( ) const principal = await authenticateCredentialGroupEnrollment(token) if (!principal) return explainLinkProblem() - const returnTo = getSearchParam(resolvedSearchParams, 'returnTo') - const returnToSearch = returnTo === 'search' - const requestedReturnTo = - returnTo === 'search' || returnTo === 'accounts' || returnTo === 'connect' - ? returnTo - : undefined + const origin = getSearchParam(resolvedSearchParams, 'origin') + const originIsSearch = origin === 'search' + const requestedOrigin = + origin === 'search' || origin === 'accounts' || origin === 'connect' ? origin : undefined const requestedOptionId = resolvedSearchParams.optionId const requestedFocusOptionId = typeof requestedOptionId === 'string' && requestedOptionId.length <= 128 @@ -268,13 +263,13 @@ export default async function CredentialGroupEnrollmentPage({ const enrollmentResult = await readPublicCredentialGroupEnrollment .execute({ principal, - input: requestedReturnTo ? { optionId: requestedFocusOptionId } : {}, + input: requestedOrigin ? { optionId: requestedFocusOptionId } : {}, }) .catch((error: unknown) => { if (error instanceof CredentialGroupEnrollmentError) return { enrollment: null, enrollmentError: error.message } if (asOrchestrationError(error)?.code === 'not_found') return null - if (requestedReturnTo && error instanceof CredentialGroupProviderConfigurationError) + if (requestedOrigin && error instanceof CredentialGroupProviderConfigurationError) return { enrollment: null } throw error }) @@ -282,17 +277,16 @@ export default async function CredentialGroupEnrollmentPage({ if ('enrollmentError' in enrollmentResult) return explainLinkProblem(enrollmentResult.enrollmentError) const { enrollment } = enrollmentResult - /** A link limited to one option is focused on it whatever the query says; the server enforces it. */ + // A link limited to one option is focused on it whatever the query says; the server enforces it. const linkOptionId = 'focusOptionId' in enrollmentResult ? enrollmentResult.focusOptionId : null - const focusedReturnTo = linkOptionId ? (requestedReturnTo ?? 'connect') : requestedReturnTo - const focused = focusedReturnTo !== undefined + const focusedOrigin = linkOptionId ? (requestedOrigin ?? 'connect') : requestedOrigin + const focused = focusedOrigin !== undefined const focusedOptionId = linkOptionId ?? requestedFocusOptionId const canReturnToSearch = - returnToSearch && + originIsSearch && ('canSearch' in enrollmentResult ? enrollmentResult.canSearch : !principal.organizationId) - const returnHref = - slackReturnUrl ?? (canReturnToSearch ? sourceReturnPath(principal) : APP_ENTRY_PATH) - const returnLabel = slackReturnUrl + const returnHref = slackHref ?? (canReturnToSearch ? sourceReturnPath(principal) : APP_ENTRY_PATH) + const returnLabel = slackHref ? 'Return to Slack' : canReturnToSearch ? principal.organizationId @@ -300,8 +294,8 @@ export default async function CredentialGroupEnrollmentPage({ : 'Open knowledge bases' : 'Open Sim' const oauthStartQuery = new URLSearchParams() - if (focusedReturnTo) oauthStartQuery.set('returnTo', focusedReturnTo) - if (slackReturnUrl) oauthStartQuery.set('return', slackReturnUrl) + if (focusedOrigin) oauthStartQuery.set('origin', focusedOrigin) + if (returnTo) oauthStartQuery.set('return', returnTo) const oauthStartSuffix = oauthStartQuery.size ? `?${oauthStartQuery}` : '' if (!enrollment) return ( @@ -309,7 +303,7 @@ export default async function CredentialGroupEnrollmentPage({ token={token} returnHref={returnHref} returnLabel={returnLabel} - slackHref={slackReturnUrl} + slackHref={slackHref} /> ) @@ -319,21 +313,28 @@ export default async function CredentialGroupEnrollmentPage({ getSearchParam(resolvedSearchParams, 'mcp') === 'connected' ? getSearchParam(resolvedSearchParams, 'mcpServerId') : undefined - const oauthMessage = - oauthStatus && Object.hasOwn(OAUTH_MESSAGES, oauthStatus) - ? OAUTH_MESSAGES[oauthStatus as keyof typeof OAUTH_MESSAGES] - : null const activeOptions = enrollment.options.filter((option) => option.status === 'active') const focusedOption = focused ? activeOptions.find((option) => option.id === focusedOptionId) : undefined + // An invitee reconnecting the wrong account is told which one to pick at the provider. + const mismatchedAccountEmail = + oauthStatus === 'account_mismatch' + ? focusedOption?.connections.find((connection) => connection.status !== 'revoked')?.email + : undefined + const oauthMessage = + mismatchedAccountEmail && focusedOption + ? `Choose ${mismatchedAccountEmail} when ${getCredentialGroupProviderService(focusedOption.provider).name} asks.` + : oauthStatus && Object.hasOwn(OAUTH_MESSAGES, oauthStatus) + ? OAUTH_MESSAGES[oauthStatus as keyof typeof OAUTH_MESSAGES] + : null if (focused && !focusedOption) return ( ) const visibleOptions = focusedOption ? [focusedOption] : activeOptions @@ -344,7 +345,7 @@ export default async function CredentialGroupEnrollmentPage({ focusedOption !== undefined && focusedAccounts.length > 0 && focusedAccounts.every((connection) => connection.status === 'connected') && - (returnToSearch || focusedReturnTo === 'connect' || connectedOptionId === focusedOption.id) + (originIsSearch || focusedOrigin === 'connect' || connectedOptionId === focusedOption.id) const connectedOption = connectedOptionId ? activeOptions.find((option) => option.id === connectedOptionId) : undefined @@ -465,12 +466,12 @@ export default async function CredentialGroupEnrollmentPage({ {focused ? ( - {!slackReturnUrl && ( + {!slackHref && ( {returnLabel} @@ -478,11 +479,11 @@ export default async function CredentialGroupEnrollmentPage({ ) : (
- + {enrollment.status === 'completed' ? 'Submitted' : 'Submit'} diff --git a/apps/sim/lib/api/contracts/credential-groups.ts b/apps/sim/lib/api/contracts/credential-groups.ts index a374c84a08f..68eeeee699d 100644 --- a/apps/sim/lib/api/contracts/credential-groups.ts +++ b/apps/sim/lib/api/contracts/credential-groups.ts @@ -5,6 +5,7 @@ import { workspaceIdSchema, } from '@/lib/api/contracts/primitives' import { defineRouteContract } from '@/lib/api/contracts/types' +import { CONNECT_RETURN_DESTINATIONS } from '@/lib/credential-groups/connect-return' import { CREDENTIAL_GROUP_MCP_SERVER_LIMIT, CREDENTIAL_GROUP_WORKFLOW_ACCESS_LIMIT, @@ -16,7 +17,6 @@ import { CREDENTIAL_GROUP_PROVIDER_IDS, CREDENTIAL_GROUP_STANDARD_OAUTH_PROVIDER_IDS, } from '@/lib/credential-groups/providers' -import { CREDENTIAL_GROUP_RETURN_QUERY_MAX_LENGTH } from '@/lib/credential-groups/return-url' export const credentialGroupProviderSchema = z.enum(CREDENTIAL_GROUP_PROVIDER_IDS) export const credentialGroupStatusSchema = z.enum(['active', 'disabled']) @@ -576,21 +576,18 @@ export const slackCredentialGroupConfigurationCallbackContract = defineRouteCont }) /** - * A Slack destination to offer once the person is done. The use case keeps it only when it passes - * the return allowlist; an invalid or oversized value is ignored, never refused. + * Where to offer to send the person once they are done. Any other value is ignored, never refused, + * so a mangled link still connects. */ -const credentialGroupReturnQuerySchema = z - .string() - .max(CREDENTIAL_GROUP_RETURN_QUERY_MAX_LENGTH) - .optional() +const connectReturnQuerySchema = z.enum(CONNECT_RETURN_DESTINATIONS).optional().catch(undefined) const completeCredentialGroupEnrollmentQuerySchema = z.object({ - return: credentialGroupReturnQuerySchema, + return: connectReturnQuerySchema, }) export const startCredentialGroupOAuthQuerySchema = z.object({ - returnTo: z.enum(['search', 'accounts', 'connect']).optional(), - return: credentialGroupReturnQuerySchema, + origin: z.enum(['search', 'accounts', 'connect']).optional(), + return: connectReturnQuerySchema, }) export type StartCredentialGroupOAuthQuery = z.output @@ -611,17 +608,19 @@ export const startCredentialGroupMcpOAuthContract = defineRouteContract({ }) /** - * The connect page's confirmation, the only request that enrolls an organization member who has - * no enrollment yet. A form POST, so a cross-site navigation (sent with Lax cookies) cannot make it. + * The connect page's Connect button, the only request that enrolls, binds, or mints a link for + * the connect URL. A same-origin form POST, so a cross-site navigation or a link unfurler cannot + * make it. */ -export const confirmCredentialGroupConnectContract = defineRouteContract({ +export const startCredentialGroupConnectContract = defineRouteContract({ method: 'POST', path: '/api/credential-groups/connect/[publicId]', params: z.object({ publicId: z.string().min(1).max(128) }), query: z.object({ provider: z.string().min(1).max(128), optionId: z.string().min(1).max(128).optional(), - return: credentialGroupReturnQuerySchema, + for: z.string().min(1).max(64).optional(), + return: connectReturnQuerySchema, }), response: { mode: 'redirect' }, }) diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index 9fc28fbaf37..a6227869bb0 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -1,17 +1,18 @@ /** - * The secret-free connect URL against real Postgres: who it opens for, what it mints (resolving - * alone mints and binds nothing), and how the focused link it mints is held to its one account - * option. Failure modes: an invited person - * (minted link scoped to the option, one hour, enrollment fields untouched), an enrollment bound - * to someone else, an unverified session, a revoked enrollment, a stranger, an organization member - * with no enrollment (enrolled only on the confirmation, never on the page load), a member the - * Integrations permission group or an unfinished setup keeps from self-enrolling, a revocation - * landing while a member self-enrolls, a disabled group or unknown provider (indistinguishable - * from an unknown public ID), a provider with two options, a workflow-requested enrollment with no - * live link, a focused link used for another option, an MCP server or Submit, and the saved - * connection completing the enrollment exactly once. Only email delivery, the provider code - * exchange, the workflow trigger fan-out, and the Enterprise entitlement that turns permission - * groups on are faked. + * The secret-free connect URL against real Postgres, through its two operations: opening it (the + * page, which reads only) and starting it (the Connect POST, which enrolls or binds and mints the + * focused link in one transaction). Failure modes: an invited person (minted link scoped to the + * option, one hour, enrollment fields untouched but the binding), a page load that would write, an + * enrollment bound to someone else, an unverified session (and a deployment that cannot verify + * email), a link made for another address, a revoked enrollment, an expired request (and a bound + * one, which never expires), a stranger, an organization member with no enrollment (enrolled only + * by the start), a member the Integrations permission group or an unfinished setup keeps from + * self-enrolling, a revocation landing while a member self-enrolls, a disabled group or unknown + * provider (indistinguishable from an unknown public ID), a provider with two options, a focused + * link used for another option, an MCP server or Submit, and the saved connection completing the + * enrollment exactly when the request is done. Only email delivery, the provider code exchange, + * the workflow trigger fan-out, and the Enterprise entitlement that turns permission groups on are + * faked. */ import type { CredentialGroupEnrollmentPrincipal } from '@sim/auth/principal' import { db, runOutsideTransactionContext } from '@sim/db' @@ -34,7 +35,10 @@ import { generateId } from '@sim/utils/id' import { and, eq, inArray, sql } from 'drizzle-orm' import { afterAll, describe, expect, it, vi } from 'vitest' import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' -import { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' +import { + openCredentialGroupConnect, + startCredentialGroupConnect, +} from '@/lib/credential-groups/application/connect-target' import { completePublicCredentialGroupEnrollment, completePublicCredentialGroupMcpOAuth, @@ -43,9 +47,11 @@ import { startPublicCredentialGroupMcpOAuth, startPublicCredentialGroupOAuth, } from '@/lib/credential-groups/application/public-enrollment' +import { connectRequestHandle } from '@/lib/credential-groups/connect-request-handle' import { authenticatePublicCredentialGroupEnrollment, inviteCredentialGroupEnrollment, + listCredentialGroupEnrollments, lockCredentialGroupInvitationTarget, revokeCredentialGroupEnrollment, } from '@/lib/credential-groups/enrollments' @@ -57,6 +63,11 @@ import { ensureWorkspaceAccountsGroup } from '@/lib/credential-groups/service' const POLICY = { authorizationAppId: 'fixture-app', requiredScopes: ['read'], scopeVersion: 1 } const triggerEvents: Array<{ event: string; enrollmentId: string }> = [] +const emailVerification = vi.hoisted(() => ({ enforced: true })) + +vi.mock('@/lib/messaging/email/verification', () => ({ + isEmailVerificationEffectivelyEnabled: () => emailVerification.enforced, +})) vi.mock('@/lib/credential-groups/scoped-availability', () => ({ isScopedCredentialGroupsAvailable: async () => true, @@ -187,31 +198,49 @@ async function enrollmentsIn(groupId: string) { .where(eq(credentialGroupEnrollment.credentialGroupId, groupId)) } -function resolveTarget( - userId: string, - input: { - publicId: string - provider?: string - optionId?: string - returnUrl?: string - confirmSelfEnrollment?: boolean - } -) { +type ConnectInput = { + publicId: string + provider?: string + optionId?: string + requestHandle?: string +} + +function openTarget(userId: string, input: ConnectInput) { + return openCredentialGroupConnect.execute({ + principal: createSessionPrincipal({ userId }), + input: { provider: DRIVE_PROVIDER_ID, ...input }, + }) +} + +function startTarget(userId: string, input: ConnectInput) { return startCredentialGroupConnect.execute({ principal: createSessionPrincipal({ userId }), input: { provider: DRIVE_PROVIDER_ID, ...input }, }) } -async function readyToken( - userId: string, - input: { publicId: string; optionId?: string } -): Promise { - const target = await resolveTarget(userId, input) - if (target.kind !== 'ready') throw new Error(`Expected ready, got ${target.kind}`) +async function readyToken(userId: string, input: ConnectInput): Promise { + const target = await startTarget(userId, input) + if (target.kind !== 'started') throw new Error(`Expected started, got ${target.kind}`) return target.invitationToken } +async function connectLinksIn(groupId: string) { + return db + .select({ id: credentialGroupEnrollmentLink.id }) + .from(credentialGroupEnrollmentLink) + .innerJoin( + credentialGroupEnrollment, + eq(credentialGroupEnrollment.id, credentialGroupEnrollmentLink.enrollmentId) + ) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, groupId), + eq(credentialGroupEnrollmentLink.purpose, 'connect') + ) + ) +} + async function principalFor( token: string, userId: string @@ -258,8 +287,13 @@ async function enrollmentOf(groupId: string, email: string) { const [row] = await db .select() .from(credentialGroupEnrollment) - .where(eq(credentialGroupEnrollment.credentialGroupId, groupId)) - if (!row || row.email !== email) throw new Error('Enrollment not found') + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, groupId), + eq(credentialGroupEnrollment.email, email) + ) + ) + if (!row) throw new Error('Enrollment not found') return row } @@ -285,36 +319,57 @@ afterAll(async () => { await db.delete(user).where(inArray(user.id, userIds)) }) -describe('startCredentialGroupConnect', () => { - it('mints a one-hour connect link scoped to the option and binds the invited person', async () => { +async function invite(fixture: Fixture, email: string) { + return inviteCredentialGroupEnrollment( + fixture.scope, + fixture.groupId, + fixture.adminId, + 'Admin', + email + ) +} + +describe('the connect URL', () => { + it('opens without writing anything, then starts by binding and minting a one-hour focused link', async () => { const fixture = await createOrganization() const person = await createPerson() - await inviteCredentialGroupEnrollment( - fixture.scope, - fixture.groupId, - fixture.adminId, - 'Admin', - person.email - ) + const teammate = await createPerson() + await addMember(fixture, teammate.userId) + await invite(fixture, person.email) const before = await enrollmentOf(fixture.groupId, person.email) - const target = await resolveTarget(person.userId, { - publicId: fixture.publicId, - returnUrl: 'slack', + await expect(openTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'ready_to_connect', + organizationName: 'Acme', + provider: 'google-drive', + optionId: DRIVE.id, + }) + await expect(openTarget(teammate.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'confirm_self_enrollment', + organizationName: 'Acme', + provider: 'google-drive', + optionId: DRIVE.id, }) + expect(await enrollmentsIn(fixture.groupId)).toEqual([before]) + expect(await connectLinksIn(fixture.groupId)).toHaveLength(0) - expect(target).toMatchObject({ kind: 'ready', optionId: DRIVE.id, returnUrl: 'slack://open' }) - if (target.kind !== 'ready') return + const started = await startTarget(person.userId, { publicId: fixture.publicId }) + + expect(started).toEqual({ + kind: 'started', + invitationToken: expect.any(String), + optionId: DRIVE.id, + }) + if (started.kind !== 'started') return const [link] = await db .select() .from(credentialGroupEnrollmentLink) - .where(eq(credentialGroupEnrollmentLink.tokenHash, sha256Hex(target.invitationToken))) + .where(eq(credentialGroupEnrollmentLink.tokenHash, sha256Hex(started.invitationToken))) expect(link).toMatchObject({ purpose: 'connect', optionId: DRIVE.id, revokedAt: null }) const ttl = (link?.expiresAt.getTime() ?? 0) - Date.now() expect(ttl).toBeGreaterThan(HOUR_MS - 60_000) expect(ttl).toBeLessThanOrEqual(HOUR_MS) - const after = await enrollmentOf(fixture.groupId, person.email) - expect(after).toMatchObject({ + expect(await enrollmentOf(fixture.groupId, person.email)).toMatchObject({ userId: person.userId, status: before.status, createdBy: before.createdBy, @@ -323,126 +378,138 @@ describe('startCredentialGroupConnect', () => { }) }) - it('ignores a return URL in the connect link, even an allowlisted Slack one', async () => { - const fixture = await createOrganization() - const person = await createPerson() - await inviteCredentialGroupEnrollment( - fixture.scope, - fixture.groupId, - fixture.adminId, - 'Admin', - person.email - ) - - for (const returnUrl of ['slack://open', 'https://slack.com/app_redirect?app=A123']) { - const target = await resolveTarget(person.userId, { publicId: fixture.publicId, returnUrl }) - expect(target.kind).toBe('ready') - expect(target).not.toHaveProperty('returnUrl') - } - }) - it('refuses an enrollment bound to another user as the wrong account', async () => { const fixture = await createOrganization() const person = await createPerson() const other = await createPerson() - await inviteCredentialGroupEnrollment( - fixture.scope, - fixture.groupId, - fixture.adminId, - 'Admin', - person.email - ) + await invite(fixture, person.email) await db .update(credentialGroupEnrollment) .set({ userId: other.userId }) .where(eq(credentialGroupEnrollment.credentialGroupId, fixture.groupId)) - await expect(resolveTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + const expected = { kind: 'wrong_account', organizationName: 'Acme', maskedEmail: `${person.email[0]}***@connect.test`, - }) + } + await expect(openTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual( + expected + ) + await expect(startTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual( + expected + ) }) - it('refuses an unverified session', async () => { + it('asks an unverified person to verify, unless the deployment cannot verify email', async () => { const fixture = await createOrganization() const person = await createPerson(false) - await inviteCredentialGroupEnrollment( - fixture.scope, - fixture.groupId, - fixture.adminId, - 'Admin', - person.email - ) + await invite(fixture, person.email) + + await expect(openTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'verify_email', + }) + await expect(startTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'verify_email', + }) + expect((await enrollmentOf(fixture.groupId, person.email)).userId).toBeNull() + + emailVerification.enforced = false + try { + await expect(readyToken(person.userId, { publicId: fixture.publicId })).resolves.toEqual( + expect.any(String) + ) + } finally { + emailVerification.enforced = true + } + expect((await enrollmentOf(fixture.groupId, person.email)).userId).toBe(person.userId) + }) + + it('tells someone holding a link made for another address only that, and never enrolls them', async () => { + const fixture = await createOrganization() + const teammate = await createPerson() + await addMember(fixture, teammate.userId) + const otherHandle = connectRequestHandle(fixture.groupId, 'someone-else@connect.test') + const ownHandle = connectRequestHandle(fixture.groupId, teammate.email) + + for (const connect of [openTarget, startTarget]) + await expect( + connect(teammate.userId, { publicId: fixture.publicId, requestHandle: otherHandle }) + ).resolves.toEqual({ kind: 'different_email' }) + expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) await expect( - resolveTarget(person.userId, { publicId: fixture.publicId }) - ).rejects.toMatchObject({ code: 'forbidden' }) - const enrollment = await enrollmentOf(fixture.groupId, person.email) - expect(enrollment.userId).toBeNull() + openTarget(teammate.userId, { publicId: fixture.publicId, requestHandle: ownHandle }) + ).resolves.toMatchObject({ kind: 'confirm_self_enrollment' }) }) it('tells a revoked person the connection is no longer needed and mints nothing', async () => { const fixture = await createOrganization() const person = await createPerson() - const enrollment = await inviteCredentialGroupEnrollment( - fixture.scope, - fixture.groupId, - fixture.adminId, - 'Admin', - person.email - ) + const enrollment = await invite(fixture, person.email) await revokeCredentialGroupEnrollment(fixture.scope, fixture.groupId, enrollment.id) - await expect(resolveTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + await expect(startTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ kind: 'revoked', organizationName: 'Acme', provider: 'google-drive', }) - const links = await db - .select() - .from(credentialGroupEnrollmentLink) - .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollment.id)) - expect(links.every((link) => link.purpose !== 'connect')).toBe(true) + expect(await connectLinksIn(fixture.groupId)).toHaveLength(0) + }) + + it('refuses a request nobody answered in time, but never a bound enrollment', async () => { + const fixture = await createOrganization() + const person = await createPerson() + const bound = await createPerson() + await invite(fixture, person.email) + await invite(fixture, bound.email) + await readyToken(bound.userId, { publicId: fixture.publicId }) + await db + .update(credentialGroupEnrollment) + .set({ invitationExpiresAt: new Date(Date.now() - HOUR_MS) }) + .where(eq(credentialGroupEnrollment.credentialGroupId, fixture.groupId)) + + const expired = { kind: 'expired', organizationName: 'Acme', provider: 'google-drive' } + await expect(openTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual( + expired + ) + await expect(startTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual( + expired + ) + expect((await enrollmentOf(fixture.groupId, person.email)).userId).toBeNull() + await expect(readyToken(bound.userId, { publicId: fixture.publicId })).resolves.toEqual( + expect.any(String) + ) + const { enrollments } = await listCredentialGroupEnrollments(fixture.scope, fixture.groupId, 10) + expect( + Object.fromEntries(enrollments.map((enrollment) => [enrollment.email, enrollment.expired])) + ).toEqual({ [person.email]: true, [bound.email]: false }) }) it('tells someone with no enrollment outside the organization they were not asked', async () => { const fixture = await createOrganization() const stranger = await createPerson() - await expect(resolveTarget(stranger.userId, { publicId: fixture.publicId })).resolves.toEqual({ + await expect(startTarget(stranger.userId, { publicId: fixture.publicId })).resolves.toEqual({ kind: 'not_invited', organizationName: 'Acme', provider: 'google-drive', }) - const enrollments = await db - .select() - .from(credentialGroupEnrollment) - .where(eq(credentialGroupEnrollment.credentialGroupId, fixture.groupId)) - expect(enrollments).toHaveLength(0) + expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) }) - it('asks a member with no enrollment to confirm, enrolling them only on the confirmation', async () => { + it('enrolls a member with no enrollment only when they start', async () => { const fixture = await createOrganization() const teammate = await createPerson() await addMember(fixture, teammate.userId) - await expect(resolveTarget(teammate.userId, { publicId: fixture.publicId })).resolves.toEqual({ - kind: 'confirm_self_enrollment', - organizationName: 'Acme', - provider: 'google-drive', - optionId: DRIVE.id, - }) + await openTarget(teammate.userId, { publicId: fixture.publicId }) expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) - const target = await resolveTarget(teammate.userId, { - publicId: fixture.publicId, - confirmSelfEnrollment: true, - }) - - expect(target).toMatchObject({ kind: 'ready', optionId: DRIVE.id }) - const enrollment = await enrollmentOf(fixture.groupId, teammate.email) - expect(enrollment.userId).toBe(teammate.userId) + await expect( + startTarget(teammate.userId, { publicId: fixture.publicId }) + ).resolves.toMatchObject({ kind: 'started', optionId: DRIVE.id }) + expect((await enrollmentOf(fixture.groupId, teammate.email)).userId).toBe(teammate.userId) }) it('refuses self-enrollment to a member the Integrations permission group restricts', async () => { @@ -458,10 +525,8 @@ describe('startCredentialGroupConnect', () => { isDefault: true, }) - for (const confirmSelfEnrollment of [false, true]) - await expect( - resolveTarget(teammate.userId, { publicId: fixture.publicId, confirmSelfEnrollment }) - ).resolves.toEqual({ + for (const connect of [openTarget, startTarget]) + await expect(connect(teammate.userId, { publicId: fixture.publicId })).resolves.toEqual({ kind: 'not_invited', organizationName: 'Acme', provider: 'google-drive', @@ -482,9 +547,11 @@ describe('startCredentialGroupConnect', () => { ) ) - await expect( - resolveTarget(teammate.userId, { publicId: fixture.publicId, confirmSelfEnrollment: true }) - ).resolves.toEqual({ kind: 'not_invited', organizationName: 'Acme', provider: 'google-drive' }) + await expect(startTarget(teammate.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'not_invited', + organizationName: 'Acme', + provider: 'google-drive', + }) expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) }) @@ -508,7 +575,7 @@ describe('startCredentialGroupConnect', () => { const [holder] = await tx.execute<{ pid: number }>(sql`SELECT pg_backend_pid() AS pid`) if (!holder) throw new Error('No backend pid') const pending = runOutsideTransactionContext(() => - resolveTarget(teammate.userId, { publicId: fixture.publicId, confirmSelfEnrollment: true }) + startTarget(teammate.userId, { publicId: fixture.publicId }) ) await runOutsideTransactionContext(() => waitForBlockedBy(holder.pid)) return { pending } @@ -519,40 +586,30 @@ describe('startCredentialGroupConnect', () => { organizationName: 'Acme', provider: 'google-drive', }) + expect(await connectLinksIn(fixture.groupId)).toHaveLength(0) }) it('answers a disabled group, an unoffered provider and an unknown ID identically', async () => { const fixture = await createOrganization() const disabled = await createOrganization() const person = await createPerson() - await inviteCredentialGroupEnrollment( - disabled.scope, - disabled.groupId, - disabled.adminId, - 'Admin', - person.email - ) + await invite(disabled, person.email) await db .update(credentialGroup) .set({ status: 'disabled' }) .where(eq(credentialGroup.id, disabled.groupId)) - const unknown = await resolveTarget(person.userId, { publicId: generateId() }) + const unknown = await startTarget(person.userId, { publicId: generateId() }) expect(unknown).toEqual({ kind: 'unavailable' }) - await expect(resolveTarget(person.userId, { publicId: disabled.publicId })).resolves.toEqual( + await expect(startTarget(person.userId, { publicId: disabled.publicId })).resolves.toEqual( unknown ) - const disabledEnrollment = await enrollmentOf(disabled.groupId, person.email) - const mintedForDisabled = await db - .select() - .from(credentialGroupEnrollmentLink) - .where(eq(credentialGroupEnrollmentLink.enrollmentId, disabledEnrollment.id)) - expect(mintedForDisabled.every((link) => link.purpose !== 'connect')).toBe(true) + expect(await connectLinksIn(disabled.groupId)).toHaveLength(0) await expect( - resolveTarget(person.userId, { publicId: fixture.publicId, provider: 'slack' }) + startTarget(person.userId, { publicId: fixture.publicId, provider: 'slack' }) ).resolves.toEqual(unknown) await expect( - resolveTarget(person.userId, { publicId: fixture.publicId, provider: 'not-a-provider' }) + startTarget(person.userId, { publicId: fixture.publicId, provider: 'not-a-provider' }) ).resolves.toEqual(unknown) }) @@ -562,15 +619,9 @@ describe('startCredentialGroupConnect', () => { driveOption('drive-shared', 'Shared Drive'), ]) const person = await createPerson() - await inviteCredentialGroupEnrollment( - fixture.scope, - fixture.groupId, - fixture.adminId, - 'Admin', - person.email - ) + await invite(fixture, person.email) - await expect(resolveTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + await expect(openTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ kind: 'choose_option', organizationName: 'Acme', provider: 'google-drive', @@ -580,28 +631,8 @@ describe('startCredentialGroupConnect', () => { ], }) await expect( - resolveTarget(person.userId, { publicId: fixture.publicId, optionId: 'drive-shared' }) - ).resolves.toMatchObject({ kind: 'ready', optionId: 'drive-shared' }) - }) - - it('opens a workflow-requested enrollment whose only invitation is long expired', async () => { - const fixture = await createOrganization() - const person = await createPerson() - await db.insert(credentialGroupEnrollment).values({ - id: generateId(), - credentialGroupId: fixture.groupId, - email: person.email, - status: 'invited', - invitationTokenHash: sha256Hex(generateId()), - invitationExpiresAt: new Date(Date.now() - 30 * 24 * HOUR_MS), - invitedAt: new Date(), - }) - - const token = await readyToken(person.userId, { publicId: fixture.publicId }) - - await expect(authenticatePublicCredentialGroupEnrollment(token)).resolves.toMatchObject({ - userId: person.userId, - }) + startTarget(person.userId, { publicId: fixture.publicId, optionId: 'drive-shared' }) + ).resolves.toMatchObject({ kind: 'started', optionId: 'drive-shared' }) }) }) @@ -749,6 +780,39 @@ describe('a focused connect link', () => { ).toHaveLength(1) }) + it("keeps an admin's request open while other options lack a connection, but finishes a workflow's", async () => { + const fixture = await createOrganization([ + driveOption('drive-work', 'Work Drive'), + driveOption('drive-shared', 'Shared Drive'), + ]) + const invited = await createPerson() + const requested = await createPerson() + await invite(fixture, invited.email) + await invite(fixture, requested.email) + await db + .update(credentialGroupEnrollment) + .set({ requestedByWorkflowId: 'workflow-1' }) + .where(eq(credentialGroupEnrollment.email, requested.email)) + + for (const person of [invited, requested]) { + const token = await readyToken(person.userId, { + publicId: fixture.publicId, + optionId: 'drive-work', + }) + const principal = await principalFor(token, person.userId) + await completePublicCredentialGroupOAuth.execute({ + principal, + input: { + attempt: attemptFor(fixture, principal, token, 'drive-work'), + code: `${person.userId}@drive.test`, + }, + }) + } + + expect((await enrollmentOf(fixture.groupId, invited.email)).status).toBe('in_progress') + expect((await enrollmentOf(fixture.groupId, requested.email)).status).toBe('completed') + }) + it('leaves an enrollment connected through an unfocused link for Submit', async () => { const fixture = await createOrganization() const person = await createPerson() diff --git a/apps/sim/lib/credential-groups/__integration__/organization-account-outbound.integration.ts b/apps/sim/lib/credential-groups/__integration__/organization-account-outbound.integration.ts index 503a432e2ff..160c99260bb 100644 --- a/apps/sim/lib/credential-groups/__integration__/organization-account-outbound.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/organization-account-outbound.integration.ts @@ -190,7 +190,7 @@ function connect( organizationId, mcpServerId, oauthCompletionId: generateId(), - returnTo: 'integrations', + origin: 'integrations', }, }) } @@ -218,7 +218,7 @@ async function verifyAuthorization(start: typeof connect | typeof reconnect) { organizationId: directOrg, userId: owner, mcpServerId: servers.get(directOrg), - returnTo: 'integrations', + origin: 'integrations', }) expect(authorization.searchParams.get('code_challenge')).toBe( createHash('sha256').update(attempt!.codeVerifier).digest('base64url') diff --git a/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts b/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts index 1ff2079724f..18ad7d61960 100644 --- a/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts @@ -1,86 +1,67 @@ /** - * The "Return to Slack" destination against real Redis: it survives the OAuth attempt round trip, - * and the completion page shows it only from a destination the server stored for the signed-in - * viewer, never from a `return` URL in its own query. + * The "Return to Slack" destination against real Redis. Failure modes: the destination lost on + * the OAuth attempt round trip, lost when the person took too long at the provider (the callback + * must still offer the way back), and a crafted completion link naming somewhere else. */ import { generateId } from '@sim/utils/id' -import { describe, expect, it } from 'vitest' -import { createCredentialGroupCompletionReturn } from '@/lib/credential-groups/completion-return' +import { describe, expect, it, vi } from 'vitest' import { + type CredentialGroupOAuthAttempt, consumeCredentialGroupOAuthAttempt, createCredentialGroupOAuthAttempt, } from '@/lib/credential-groups/oauth-state' import { resolveCredentialGroupCompletionView } from '@/app/credential-groups/complete/completion-view' -const SLACK_APP = 'slack://app?team=T123&id=A123' -const FORGED = 'https://slack.com/app_redirect?app=AFORGED' +function startAttempt() { + return createCredentialGroupOAuthAttempt({ + provider: 'google-drive', + organizationId: generateId(), + userId: generateId(), + email: 'person@example.com', + enrollmentId: generateId(), + credentialGroupId: generateId(), + optionId: 'option-drive', + authorizationAppId: 'google:app', + scopeVersion: 1, + requiredScopes: ['openid'], + redirectUri: 'https://sim.test/api/auth/oauth2/callback/google-drive', + invitationToken: generateId(), + origin: 'connect', + returnTo: 'slack', + }) +} describe('Slack return destination', () => { it('survives the OAuth attempt create and consume round trip', async () => { - const { state } = await createCredentialGroupOAuthAttempt({ - provider: 'google-drive', - organizationId: generateId(), - userId: generateId(), - email: 'person@example.com', - enrollmentId: generateId(), - credentialGroupId: generateId(), - optionId: 'option-drive', - authorizationAppId: 'google:app', - scopeVersion: 1, - requiredScopes: ['openid'], - redirectUri: 'https://sim.test/api/auth/oauth2/callback/google-drive', - invitationToken: generateId(), - returnTo: 'connect', - returnUrl: SLACK_APP, - }) + const { state } = await startAttempt() await expect(consumeCredentialGroupOAuthAttempt(state)).resolves.toMatchObject({ - returnTo: 'connect', - returnUrl: SLACK_APP, - }) + origin: 'connect', + returnTo: 'slack', + } satisfies Partial) }) - it('shows no return button for a crafted completion link', async () => { - const view = await resolveCredentialGroupCompletionView({ - searchParams: { return: FORGED }, - userId: generateId(), - }) - - expect(view.slackReturnHref).toBeUndefined() + it('is still known when the person took too long at the provider', async () => { + const { state } = await startAttempt() + vi.useFakeTimers({ now: Date.now() + 31 * 60 * 1000, toFake: ['Date'] }) + try { + await expect(consumeCredentialGroupOAuthAttempt(state)).resolves.toEqual({ + expired: true, + returnTo: 'slack', + }) + } finally { + vi.useRealTimers() + } }) - it('shows the destination the server stored for the viewer, and only to them', async () => { - const viewer = generateId() - const returnId = await createCredentialGroupCompletionReturn({ - userId: viewer, - returnUrl: SLACK_APP, - }) - if (!returnId) throw new Error('Completion return was not stored') - - const own = await resolveCredentialGroupCompletionView({ - searchParams: { returnId, return: FORGED }, - userId: viewer, - }) - const someoneElse = await resolveCredentialGroupCompletionView({ - searchParams: { returnId }, - userId: generateId(), + it('offers only the Slack app, and tells an expired attempt to go back to Slack', () => { + expect( + resolveCredentialGroupCompletionView({ return: 'https://evil.example' }).slackReturnHref + ).toBeUndefined() + expect(resolveCredentialGroupCompletionView({ oauth: 'expired', return: 'slack' })).toEqual({ + failure: 'expired', + error: 'This connection attempt expired. Go back to Slack and tap Connect again.', + slackReturnHref: 'slack://open', }) - const signedOut = await resolveCredentialGroupCompletionView({ - searchParams: { returnId }, - userId: undefined, - }) - - expect(own.slackReturnHref).toBe(SLACK_APP) - expect(someoneElse.slackReturnHref).toBeUndefined() - expect(signedOut.slackReturnHref).toBeUndefined() - }) - - it('stores nothing for a destination outside the allowlist', async () => { - await expect( - createCredentialGroupCompletionReturn({ - userId: generateId(), - returnUrl: 'https://evil.example/app_redirect?app=A1', - }) - ).resolves.toBeUndefined() }) }) diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts index 9314e614f22..e615a2c9218 100644 --- a/apps/sim/lib/credential-groups/application/connect-target.ts +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -1,22 +1,24 @@ import { AuditAction, AuditResourceType } from '@sim/audit' import type { SessionPrincipal } from '@sim/auth/principal' -import { omit } from '@sim/utils/object' -import { defineOperation } from '@/lib/core/application' +import { defineOperation, type OperationUseCase } from '@/lib/core/application' import { ForbiddenOperationError } from '@/lib/core/application/forbidden' import { authorizeOrganizationOperation, OrganizationMembershipNotFoundError, } from '@/lib/core/application/organization-authorization' -import { OrchestrationError } from '@/lib/core/orchestration/types' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' import { organizationAccountOperations } from '@/lib/credential-groups/application/organization-accounts' +import { connectRequestHandleMatches } from '@/lib/credential-groups/connect-request-handle' import { type CredentialGroupConnectLinkTarget, issueCredentialGroupConnectLink, loadCredentialGroupConnectSubject, } from '@/lib/credential-groups/connect-subject' import { maskEnrollmentEmail } from '@/lib/credential-groups/email-mask' -import { isEnrollmentRevoked } from '@/lib/credential-groups/links' +import { + isEnrollmentRequestExpired, + isEnrollmentRevoked, +} from '@/lib/credential-groups/enrollment-lifecycle' import { OrganizationAccountsSetupRequiredError, requireOrganizationAccountsSetup, @@ -25,17 +27,25 @@ import { type CredentialGroupProvider, findCredentialGroupProviderFromProviderId, } from '@/lib/credential-groups/providers' -import { resolveCredentialGroupConnectReturnUrl } from '@/lib/credential-groups/return-url' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' +import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' import { defineAuthorizedCredentialUserUseCase } from '@/lib/credentials/application/authorized-user-use-case' +/** + * Opening and starting a connect URL. A member's self-enrollment is held to the Integrations + * capability by the check the member self-enroll path uses. + */ const credentialGroupConnectOperations = { /** - * A member's self-enrollment is held to the Integrations capability by the same check the - * member self-enroll path uses. * permission-group-exempt: the person connecting may be outside the organization; authority is * their own verified email or bound enrollment, never a workspace role. */ + open: defineOperation({ + id: 'credential_groups.connect.open', + principalKinds: ['session'], + capability: 'none', + }), + /** permission-group-exempt: as `open`, the person's own verified email or bound enrollment. */ start: defineOperation({ id: 'credential_groups.connect.start', principalKinds: ['session'], @@ -48,29 +58,25 @@ interface CredentialGroupConnectInput { /** The credential provider ID the workflow asked for (e.g. `google-drive`). */ provider: string optionId?: string - /** Raw `return` query value; only the keyword `slack` is honored. */ - returnUrl?: string -} - -interface StartCredentialGroupConnectInput extends CredentialGroupConnectInput { - /** - * Set only by the confirmation POST. Without it an organization member with no enrollment is - * asked to confirm instead of enrolled, so a cross-site navigation enrolls nobody. - */ - confirmSelfEnrollment?: boolean + /** The connect URL's `for` handle, when it was built for one person's email. */ + requestHandle?: string } /** - * A refusal the connect page explains. Every refusal that would reveal whether a group exists, is - * enabled, or offers the provider is the same `unavailable`; the organization is only named once - * the group is known to be active and to offer the provider, since the link holder got the URL - * from that organization. + * Why the connect page cannot start a connection for the signed-in person. Every refusal that + * would reveal whether a group exists, is enabled, or offers the provider is the same + * `unavailable`; the organization is only named once the group is known to be active and to + * offer the provider, since the link holder got the URL from that organization. The address a + * person-specific link was made for is never revealed. */ type CredentialGroupConnectRefusal = | { kind: 'unavailable' } + | { kind: 'verify_email' } + | { kind: 'different_email' } | { kind: 'not_invited'; organizationName: string; provider: CredentialGroupProvider } | { kind: 'wrong_account'; organizationName: string; maskedEmail: string } | { kind: 'revoked'; organizationName: string; provider: CredentialGroupProvider } + | { kind: 'expired'; organizationName: string; provider: CredentialGroupProvider } | { kind: 'choose_option' organizationName: string @@ -78,40 +84,23 @@ type CredentialGroupConnectRefusal = options: Array<{ id: string; label: string }> } -interface ConfirmSelfEnrollment { - kind: 'confirm_self_enrollment' +interface ConnectOffer { + /** + * `ready_to_connect`: the person holds an enrollment, which the POST binds. + * `confirm_self_enrollment`: an organization member with none, whom the POST enrolls. + */ + kind: 'ready_to_connect' | 'confirm_self_enrollment' organizationName: string provider: CredentialGroupProvider optionId: string } -/** What starting a connection did: minted the person's focused link, or why it did not. */ -type CredentialGroupConnectStart = - | CredentialGroupConnectRefusal - | ConfirmSelfEnrollment - | { - kind: 'ready' - invitationToken: string - optionId: string - returnUrl?: string - /** For the audit record; the page never shows these. */ - credentialGroupId: string - enrollmentId: string - created: boolean - bound: boolean - } +/** What the connect page shows a signed-in person. */ +export type CredentialGroupConnectOutcome = CredentialGroupConnectRefusal | ConnectOffer type ConnectDecision = | CredentialGroupConnectRefusal - | (ConfirmSelfEnrollment & { credentialGroupId: string; organizationId: string }) - | { - kind: 'connect' - organizationName: string - provider: CredentialGroupProvider - optionId: string - credentialGroupId: string - enrollment: { id: string; bound: boolean } - } + | (ConnectOffer & { credentialGroupId: string; target: CredentialGroupConnectLinkTarget }) const UNAVAILABLE = { kind: 'unavailable' } as const @@ -142,14 +131,23 @@ async function canSelfEnroll( } } +/** Binding an invited person needs the organization's setup, as the invitation page does. */ +async function hasOrganizationSetup(organizationId: string, credentialGroupId: string) { + try { + await requireOrganizationAccountsSetup(organizationId, credentialGroupId) + return true + } catch (error) { + if (error instanceof OrganizationAccountsSetupRequiredError) return false + throw error + } +} + /** - * Decides what the signed-in person may do with a connect URL. Reads only. The session is the - * authority, not an earlier invitation: an unbound enrollment whose emailed link (or legacy - * invitation column) expired, or that a workflow requested with no link at all, is still - * connectable by the person at its email, because the link minted for it carries its own expiry. - * An organization member with no enrollment who passes the member self-enroll checks is asked to - * confirm; anyone else must already hold an enrollment bound to them or invited at their verified - * email. + * Decides what the signed-in person may do with a connect URL. Reads only. The person must + * already hold an enrollment, bound to them or requested at their verified email and not yet + * expired, or be an organization member who passes the member self-enroll checks. A link made for + * another address (its `for` handle does not match the viewer) is refused before anything about + * the viewer's own enrollment is said, and never offers self-enrollment. */ async function decideConnectTarget( principal: SessionPrincipal, @@ -159,10 +157,9 @@ async function decideConnectTarget( publicId: input.publicId, userId: principal.userId, }) - if (subject && !subject.viewer.emailVerified) - throw new OrchestrationError('forbidden', 'Verify your email address before connecting') + if (subject && !isCredentialGroupEmailVerified(subject.viewer)) return { kind: 'verify_email' } if (!subject || subject.group.status !== 'active') return UNAVAILABLE - const { group, enrollment } = subject + const { group, enrollment, viewer } = subject const provider = findCredentialGroupProviderFromProviderId(input.provider) if (!provider) return UNAVAILABLE if (!(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(group)))) return UNAVAILABLE @@ -176,6 +173,11 @@ async function decideConnectTarget( if (!option) return UNAVAILABLE const { organizationName } = group + if ( + input.requestHandle !== undefined && + !connectRequestHandleMatches(input.requestHandle, group.id, viewer.email) + ) + return { kind: 'different_email' } if (enrollment?.userId && enrollment.userId !== principal.userId) return { kind: 'wrong_account', @@ -184,17 +186,17 @@ async function decideConnectTarget( } if (enrollment && isEnrollmentRevoked(enrollment)) return { kind: 'revoked', organizationName, provider } + if (enrollment && isEnrollmentRequestExpired(enrollment)) + return { kind: 'expired', organizationName, provider } if (!enrollment) { if (!group.organizationId || !(await canSelfEnroll(principal, group.organizationId, group.id))) return { kind: 'not_invited', organizationName, provider } - } else if (!enrollment.userId && group.organizationId) { - /** Binding an invited person needs the organization's setup, as the invitation page does. */ - try { - await requireOrganizationAccountsSetup(group.organizationId, group.id) - } catch (error) { - if (error instanceof OrganizationAccountsSetupRequiredError) return UNAVAILABLE - throw error - } + } else if ( + !enrollment.userId && + group.organizationId && + !(await hasOrganizationSetup(group.organizationId, group.id)) + ) { + return UNAVAILABLE } if (options.length > 1) return { @@ -203,76 +205,83 @@ async function decideConnectTarget( provider, options: options.map(({ id, label }) => ({ id, label })), } - if (!enrollment) { - if (!group.organizationId) return UNAVAILABLE - return { - kind: 'confirm_self_enrollment', - organizationName, - provider, - optionId: option.id, - credentialGroupId: group.id, - organizationId: group.organizationId, - } - } return { - kind: 'connect', + kind: enrollment ? 'ready_to_connect' : 'confirm_self_enrollment', organizationName, provider, optionId: option.id, credentialGroupId: group.id, - enrollment: { id: enrollment.id, bound: Boolean(enrollment.userId) }, + target: enrollment + ? { kind: 'enrollment', enrollmentId: enrollment.id } + : { kind: 'self_enrollment' }, } } -/** - * Mints the signed-in person's one-hour link focused on the single matching account option, once - * {@link decideConnectTarget} allows it; every refusal and the self-enrollment confirmation come - * back unchanged and write nothing. In one transaction it enrolls a member who confirmed - * self-enrollment, binds the person to an enrollment invited at their email, and inserts the link, - * so a revocation either lands first (and the person is told the connection is no longer needed) - * or kills the new link. Creating or binding an enrollment is audited; minting a link for one - * already bound is not, since the person can repeat it freely. - */ -export const startCredentialGroupConnect = defineAuthorizedCredentialUserUseCase({ +function isOffer(decision: ConnectDecision): decision is Extract { + return decision.kind === 'ready_to_connect' || decision.kind === 'confirm_self_enrollment' +} + +/** Shows the person what the connect URL will do for them. Reads only: no enrollment, link, or audit. */ +export const openCredentialGroupConnect = defineAuthorizedCredentialUserUseCase({ + operation: credentialGroupConnectOperations.open, + async execute({ + principal, + input, + }: { + principal: SessionPrincipal + input: CredentialGroupConnectInput + }): Promise { + const decision = await decideConnectTarget(principal, input) + if (!isOffer(decision)) return decision + const { kind, organizationName, provider, optionId } = decision + return { kind, organizationName, provider, optionId } + }, +}) + +/** What starting a connection did: minted the person's focused link, or why it did not. */ +type CredentialGroupConnectStart = + | CredentialGroupConnectRefusal + | { kind: 'started'; invitationToken: string; optionId: string } + +interface StartedConnect { + kind: 'started' + invitationToken: string + optionId: string + credentialGroupId: string + enrollmentId: string + created: boolean + bound: boolean +} + +const recordCredentialGroupConnectStart = defineAuthorizedCredentialUserUseCase({ operation: credentialGroupConnectOperations.start, async execute({ principal, input, }: { principal: SessionPrincipal - input: StartCredentialGroupConnectInput - }): Promise { + input: CredentialGroupConnectInput + }): Promise { const decision = await decideConnectTarget(principal, input) - let target: CredentialGroupConnectLinkTarget - if (decision.kind === 'connect') { - target = { kind: 'enrollment', enrollmentId: decision.enrollment.id } - } else if (decision.kind === 'confirm_self_enrollment') { - if (!input.confirmSelfEnrollment) - return omit(decision, ['credentialGroupId', 'organizationId']) - target = { kind: 'self_enrollment' } - } else { - return decision - } + if (!isOffer(decision)) return decision const issued = await issueCredentialGroupConnectLink({ credentialGroupId: decision.credentialGroupId, userId: principal.userId, optionId: decision.optionId, - target, + target: decision.target, }) if (!issued.issued) - return issued.reason === 'revoked' - ? { - kind: 'revoked', + return issued.reason === 'unavailable' + ? UNAVAILABLE + : { + kind: issued.reason, organizationName: decision.organizationName, provider: decision.provider, } - : UNAVAILABLE - const returnUrl = resolveCredentialGroupConnectReturnUrl(input.returnUrl) return { - kind: 'ready', + kind: 'started', invitationToken: issued.token, optionId: decision.optionId, - ...(returnUrl ? { returnUrl } : {}), credentialGroupId: decision.credentialGroupId, enrollmentId: issued.enrollmentId, created: issued.created, @@ -280,7 +289,7 @@ export const startCredentialGroupConnect = defineAuthorizedCredentialUserUseCase } }, projectAudit: ({ result }) => - result.kind === 'ready' && (result.created || result.bound) + result.kind === 'started' && (result.created || result.bound) ? { workspaceId: null, action: AuditAction.CREDENTIAL_GROUP_UPDATED, @@ -298,3 +307,24 @@ export const startCredentialGroupConnect = defineAuthorizedCredentialUserUseCase } : [], }) + +/** + * Starts the connection the connect page offered, from its same-origin POST. In one transaction + * it enrolls a member enrolling themselves, binds the person to an enrollment requested at their + * email, and mints a one-hour link focused on the one option, so a revocation either lands first + * (and the person is told) or kills the new link. Creating or binding an enrollment is audited; + * minting a link for one already bound is not, since the person can repeat it freely. The result + * carries only what the caller needs to continue. + */ +export const startCredentialGroupConnect: OperationUseCase< + typeof credentialGroupConnectOperations.start, + CredentialGroupConnectInput, + CredentialGroupConnectStart +> = { + ...recordCredentialGroupConnectStart, + async execute(args) { + const result = await recordCredentialGroupConnectStart.execute(args) + if (result.kind !== 'started') return result + return { kind: 'started', invitationToken: result.invitationToken, optionId: result.optionId } + }, +} diff --git a/apps/sim/lib/credential-groups/application/organization-access.test.ts b/apps/sim/lib/credential-groups/application/organization-access.test.ts index c3f72b4821f..2933cf2da48 100644 --- a/apps/sim/lib/credential-groups/application/organization-access.test.ts +++ b/apps/sim/lib/credential-groups/application/organization-access.test.ts @@ -218,9 +218,9 @@ describe('organization workspace sharing administration', () => { }) ).resolves.toEqual({ invitationLink: - 'https://sim.test/credential-groups/enroll/fixture-token?optionId=option-1&returnTo=search', + 'https://sim.test/credential-groups/enroll/fixture-token?optionId=option-1&origin=search', authorizationUrl: - 'https://sim.test/api/credential-groups/enroll/fixture-token/oauth/option-1?returnTo=search', + 'https://sim.test/api/credential-groups/enroll/fixture-token/oauth/option-1?origin=search', }) }) diff --git a/apps/sim/lib/credential-groups/application/organization-accounts.ts b/apps/sim/lib/credential-groups/application/organization-accounts.ts index 707c82e62d3..d32450a2874 100644 --- a/apps/sim/lib/credential-groups/application/organization-accounts.ts +++ b/apps/sim/lib/credential-groups/application/organization-accounts.ts @@ -283,7 +283,7 @@ export const startOrganizationAccountConnection = defineOrganizationAccountsUseC }: { input: OrganizationAccountsInput & StartOrganizationAccountConnectionBody & { - returnTo?: 'integrations' + origin?: 'integrations' connectionIntent?: CredentialGroupConnectionIntent } context: OrganizationMembershipContext @@ -301,7 +301,7 @@ export const startOrganizationAccountConnection = defineOrganizationAccountsUseC credentialGroupId: group.id, mcpServerId: input.mcpServerId, completionId: input.oauthCompletionId, - returnTo: input.returnTo, + origin: input.origin, connectionIntent: input.connectionIntent ?? { kind: 'create' }, }) } @@ -327,7 +327,7 @@ export const startOrganizationAccountConnection = defineOrganizationAccountsUseC credentialGroupId: group.id, optionId: input.optionId, completionId: input.oauthCompletionId, - returnTo: input.returnTo, + origin: input.origin, connectionIntent: input.connectionIntent ?? { kind: 'create' }, }) } @@ -338,13 +338,13 @@ export const startOrganizationAccountConnection = defineOrganizationAccountsUseC }) const url = new URL(invitationLink) url.searchParams.set('optionId', input.optionId) - url.searchParams.set('returnTo', 'search') + url.searchParams.set('origin', 'search') return { invitationLink: url.toString(), authorizationUrl: createCredentialGroupOAuthStartUrl({ invitationLink, optionId: input.optionId, - returnTo: 'search', + origin: 'search', }), } }, diff --git a/apps/sim/lib/credential-groups/application/personal-organization-accounts.test.ts b/apps/sim/lib/credential-groups/application/personal-organization-accounts.test.ts index 7743b931744..98cfaf3c4c0 100644 --- a/apps/sim/lib/credential-groups/application/personal-organization-accounts.test.ts +++ b/apps/sim/lib/credential-groups/application/personal-organization-accounts.test.ts @@ -88,9 +88,9 @@ describe('personal organization contributions', () => { const result = await reconnectPersonalOrganizationAccount.execute({ principal, input }) const url = new URL(result.invitationLink) expect(url.searchParams.get('optionId')).toBe('gmail-option') - expect(url.searchParams.get('returnTo')).toBe('accounts') + expect(url.searchParams.get('origin')).toBe('accounts') expect(result.authorizationUrl).toBe( - 'https://sim.test/api/credential-groups/enroll/fixture-token/oauth/gmail-option?returnTo=accounts' + 'https://sim.test/api/credential-groups/enroll/fixture-token/oauth/gmail-option?origin=accounts' ) expect(dbChainMockFns.from).not.toHaveBeenCalledWith(schemaMock.member) }) diff --git a/apps/sim/lib/credential-groups/application/public-enrollment.test.ts b/apps/sim/lib/credential-groups/application/public-enrollment.test.ts index bebf1240f53..dae8b64090e 100644 --- a/apps/sim/lib/credential-groups/application/public-enrollment.test.ts +++ b/apps/sim/lib/credential-groups/application/public-enrollment.test.ts @@ -227,13 +227,13 @@ describe('public Credential Group enrollment application operations', () => { it('keeps the Search return context with the exact authorized OAuth option', async () => { await startPublicCredentialGroupOAuth.execute({ principal, - input: { invitationToken, optionId: 'option-1', returnTo: 'search' }, + input: { invitationToken, optionId: 'option-1', origin: 'search' }, }) expect(mocks.getOAuthContext).toHaveBeenCalledWith(identity, 'option-1') expect(mocks.startOAuth).toHaveBeenCalledWith( expect.objectContaining({ option: { id: 'option-1', provider: 'gmail' } }), invitationToken, - { returnTo: 'search' } + { origin: 'search' } ) expect(mocks.completeEnrollment).not.toHaveBeenCalled() }) diff --git a/apps/sim/lib/credential-groups/application/public-enrollment.ts b/apps/sim/lib/credential-groups/application/public-enrollment.ts index 1f991103ade..631b5a0989c 100644 --- a/apps/sim/lib/credential-groups/application/public-enrollment.ts +++ b/apps/sim/lib/credential-groups/application/public-enrollment.ts @@ -10,7 +10,7 @@ import { sameResourceScope, } from '@/lib/core/resource-scope' import { credentialGroupEnrollmentOperations } from '@/lib/credential-groups/application/enrollment-operations' -import { createCredentialGroupCompletionReturn } from '@/lib/credential-groups/completion-return' +import type { ConnectReturnDestination } from '@/lib/credential-groups/connect-return' import { bindCredentialGroupEnrollmentUser, completeAuthorizedCredentialGroupEnrollment, @@ -19,6 +19,7 @@ import { getAuthorizedPublicCredentialGroupEnrollment, getCredentialGroupMcpOAuthContextForEnrollment, getCredentialGroupOAuthContextForEnrollment, + isFocusedConnectionComplete, type PublicCredentialGroupEnrollmentIdentity, } from '@/lib/credential-groups/enrollments' import { @@ -36,7 +37,6 @@ import { } from '@/lib/credential-groups/oauth' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' import { CredentialGroupInvitationUnavailableError } from '@/lib/credential-groups/provider-adapter' -import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' import { fireCredentialGroupTrigger } from '@/lib/credential-groups/trigger' import { isKnowledgeMemberAccessAvailable } from '@/lib/knowledge/access/availability' import { getOrganizationSettingsAccess } from '@/lib/organizations/settings-access' @@ -188,11 +188,6 @@ export const readPublicCredentialGroupEnrollment = defineAuthorizedCredentialGro } ) -interface CompletePublicCredentialGroupEnrollmentInput { - /** Raw `return` query value; kept for the completion page only when it is an allowed Slack destination. */ - returnUrl?: string -} - export const completePublicCredentialGroupEnrollment = defineAuthorizedCredentialGroupEnrollmentUseCase({ operation: credentialGroupEnrollmentOperations.complete, @@ -200,19 +195,14 @@ export const completePublicCredentialGroupEnrollment = principal, }: { principal: CredentialGroupEnrollmentPrincipal - input: CompletePublicCredentialGroupEnrollmentInput + input: Record }) => resolvePublicEnrollmentContext(principal), /** A focused link completes itself when its connection is saved; it has no Submit. */ - async execute({ context, principal, input, linkOptionId }) { + async execute({ context, linkOptionId }) { if (linkOptionId) throw new CredentialGroupLinkFocusError() - const completed = await completeEnrollment(context, context.enrollment.credentialGroupName) - const completionReturnId = completed - ? await createCredentialGroupCompletionReturn({ - userId: principal.userId, - returnUrl: input.returnUrl, - }) - : undefined - return { completed, ...(completionReturnId ? { completionReturnId } : {}) } + return { + completed: await completeEnrollment(context, context.enrollment.credentialGroupName), + } }, }) @@ -242,9 +232,8 @@ async function completeEnrollment( interface PublicCredentialGroupOAuthInput { invitationToken: string optionId: string - returnTo?: 'search' | 'accounts' | 'connect' - /** Raw `return` query value; kept only when it is an allowed Slack destination. */ - returnUrl?: string + origin?: 'search' | 'accounts' | 'connect' + returnTo?: ConnectReturnDestination } interface PublicCredentialGroupOAuthContext extends PublicCredentialGroupEnrollmentIdentity { @@ -275,10 +264,8 @@ export const startPublicCredentialGroupOAuth = defineAuthorizedCredentialGroupEn requireInvitationToken(principal, input.invitationToken) return { authorizationUrl: await startCredentialGroupOAuth(context.oauth, input.invitationToken, { + origin: input.origin, returnTo: input.returnTo, - returnUrl: input.returnUrl - ? parseCredentialGroupReturnUrl(input.returnUrl)?.href - : undefined, }), } }, @@ -355,7 +342,8 @@ export const completePublicCredentialGroupOAuth = defineAuthorizedCredentialGrou displayName: completion.displayName, }, }) - if (linkOptionId) await completeEnrollment(context, context.oauth.credentialGroupName) + if (linkOptionId && (await isFocusedConnectionComplete(context))) + await completeEnrollment(context, context.oauth.credentialGroupName) return { connectedOptionId: context.oauth.option.id } }, }) diff --git a/apps/sim/lib/credential-groups/connect-request-handle.ts b/apps/sim/lib/credential-groups/connect-request-handle.ts new file mode 100644 index 00000000000..ef7ff0e4960 --- /dev/null +++ b/apps/sim/lib/credential-groups/connect-request-handle.ts @@ -0,0 +1,31 @@ +import { safeCompare } from '@sim/security/compare' +import { hmacSha256Base64 } from '@sim/security/hmac' +import { normalizeEmail } from '@sim/utils/string' +import { env } from '@/lib/core/config/env' + +const REQUEST_HANDLE_LENGTH = 22 + +/** + * The `for` value of a connect URL built for one person: a keyed hash of the group and their + * address. The connect page recomputes it for the signed-in viewer, so it can tell "this link was + * sent to someone else" without the link revealing the address, and never offers self-enrollment + * to the wrong person. 22 base64url characters keep 132 bits. + */ +export function connectRequestHandle(credentialGroupId: string, email: string): string { + return hmacSha256Base64( + `credential-group-connect:${credentialGroupId}:${normalizeEmail(email)}`, + env.BETTER_AUTH_SECRET + ) + .replace(/\+/g, '-') + .replace(/\//g, '_') + .slice(0, REQUEST_HANDLE_LENGTH) +} + +/** Whether a connect URL's `for` value names `email`. */ +export function connectRequestHandleMatches( + handle: string, + credentialGroupId: string, + email: string +): boolean { + return safeCompare(handle, connectRequestHandle(credentialGroupId, email)) +} diff --git a/apps/sim/lib/credential-groups/connect-return.ts b/apps/sim/lib/credential-groups/connect-return.ts new file mode 100644 index 00000000000..2a2e9725f5e --- /dev/null +++ b/apps/sim/lib/credential-groups/connect-return.ts @@ -0,0 +1,26 @@ +/** + * Where a connect flow offers to send the person once their account is connected. The workflow + * picks it (Credential block `returnTo`), the connect URL carries it as `return=slack`, the OAuth + * attempt keeps it, and the page that finishes renders it. Only this closed set exists, so a forged + * `return` value can at most open the Slack app. + */ +export const CONNECT_RETURN_DESTINATIONS = ['slack'] as const + +export type ConnectReturnDestination = (typeof CONNECT_RETURN_DESTINATIONS)[number] + +export function parseConnectReturnDestination( + value: unknown +): ConnectReturnDestination | undefined { + return CONNECT_RETURN_DESTINATIONS.find((destination) => destination === value) +} + +/** + * The link a destination opens. Resolved only where a page renders it: Slack's generic deep link, + * since a workflow holds no Slack team or app ID. + */ +export function connectReturnHref(destination: ConnectReturnDestination): string { + switch (destination) { + case 'slack': + return 'slack://open' + } +} diff --git a/apps/sim/lib/credential-groups/connect-session.ts b/apps/sim/lib/credential-groups/connect-session.ts new file mode 100644 index 00000000000..d790050f62a --- /dev/null +++ b/apps/sim/lib/credential-groups/connect-session.ts @@ -0,0 +1,31 @@ +import type { SessionPrincipal } from '@sim/auth/principal' +import { getSession } from '@/lib/auth' +import { checkCredentialGroupConnectUserRateLimit } from '@/lib/credential-groups/rate-limit' +import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' + +/** + * Who is opening a connect URL, as the page and its POST both need it before any use case runs: + * signed in, with a verified email, and within their per-person budget. + */ +export type CredentialGroupConnectSession = + | { kind: 'sign_in' } + | { kind: 'verify_email' } + /** Over the per-person budget. */ + | { kind: 'rate_limited' } + /** The limiter could not be reached; refused, but not blamed on the person. */ + | { kind: 'try_again' } + | { kind: 'signed_in'; principal: SessionPrincipal; email: string } + +export async function resolveCredentialGroupConnectSession(): Promise { + const session = await getSession() + if (!session?.user) return { kind: 'sign_in' } + if (!isCredentialGroupEmailVerified(session.user)) return { kind: 'verify_email' } + const limit = await checkCredentialGroupConnectUserRateLimit(session.user.id) + if (limit === 'limited') return { kind: 'rate_limited' } + if (limit === 'unavailable') return { kind: 'try_again' } + return { + kind: 'signed_in', + principal: { kind: 'session', userId: session.user.id, sessionId: session.session.id }, + email: session.user.email, + } +} diff --git a/apps/sim/lib/credential-groups/connect-subject.ts b/apps/sim/lib/credential-groups/connect-subject.ts index a2b10c0efba..063d156d6c1 100644 --- a/apps/sim/lib/credential-groups/connect-subject.ts +++ b/apps/sim/lib/credential-groups/connect-subject.ts @@ -10,14 +10,15 @@ import { import { normalizeEmail } from '@sim/utils/string' import { and, eq, or } from 'drizzle-orm' import { + isEnrollmentRequestExpired, + isEnrollmentRevoked, +} from '@/lib/credential-groups/enrollment-lifecycle' +import { + findOrCreateUnissuedEnrollment, lockCredentialGroupEnrollmentLifecycle, - lockCredentialGroupInvitationTarget, } from '@/lib/credential-groups/enrollments' -import { - insertEnrollmentLink, - isEnrollmentRevoked, - unissuedEnrollmentValues, -} from '@/lib/credential-groups/links' +import { insertEnrollmentLink } from '@/lib/credential-groups/links' +import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' /** * Reads and writes for the secret-free connect URL. The decision of what a signed-in person may @@ -37,7 +38,10 @@ interface CredentialGroupConnectSubject { options: CredentialGroupOptionConfig[] organizationName: string } - enrollment: Pick | null + enrollment: Pick< + EnrollmentRow, + 'id' | 'email' | 'userId' | 'status' | 'revokedAt' | 'invitationExpiresAt' + > | null } /** @@ -78,6 +82,7 @@ export async function loadCredentialGroupConnectSubject(input: { userId: credentialGroupEnrollment.userId, status: credentialGroupEnrollment.status, revokedAt: credentialGroupEnrollment.revokedAt, + invitationExpiresAt: credentialGroupEnrollment.invitationExpiresAt, }) .from(credentialGroupEnrollment) .where( @@ -102,9 +107,9 @@ export async function loadCredentialGroupConnectSubject(input: { /** Who the connect link is for and which enrollment it opens. */ export type CredentialGroupConnectLinkTarget = - /** An enrollment the person already holds: bound to them, or invited at their email. */ + /** An enrollment the person already holds: bound to them, or requested at their email. */ | { kind: 'enrollment'; enrollmentId: string } - /** An organization member with no enrollment, who confirmed enrolling themselves. */ + /** An organization member with no enrollment, who asked to connect. */ | { kind: 'self_enrollment' } type IssuedCredentialGroupConnectLink = @@ -117,19 +122,19 @@ type IssuedCredentialGroupConnectLink = /** The person was bound to the enrollment by this link. */ bound: boolean } - | { issued: false; reason: 'revoked' | 'unavailable' } + | { issued: false; reason: 'revoked' | 'expired' | 'unavailable' } /** * Mints a short-lived link focused on one account option and, in the same transaction, creates - * the member's enrollment when they confirmed self-enrollment and binds the signed-in person to an + * the member's enrollment when they enroll themselves and binds the signed-in person to an * unbound one. The enrollment's lifecycle lock serializes it with revocation, so a revocation that * commits first is reported as `revoked` and a later one kills the new link. Inserts a link row * only: an existing enrollment's issuer, timestamps, status and legacy token column stay as they * are. * * The caller has already decided the person may connect; this re-checks, under the lock, only what - * may have changed since: revocation, the group still being active, the binding, and that the - * person's verified email still matches an unbound enrollment. + * may have changed since: revocation, expiry, the group still being active, the binding, and that + * the person's verified email still matches an unbound enrollment. */ export async function issueCredentialGroupConnectLink(input: { credentialGroupId: string @@ -144,46 +149,31 @@ export async function issueCredentialGroupConnectLink(input: { .from(user) .where(eq(user.id, input.userId)) .limit(1) - if (!viewer?.emailVerified) return { issued: false, reason: 'unavailable' } + if (!viewer || !isCredentialGroupEmailVerified(viewer)) + return { issued: false, reason: 'unavailable' } const viewerEmail = normalizeEmail(viewer.email) - let enrollmentId: string + let enrollmentId = input.target.kind === 'enrollment' ? input.target.enrollmentId : null let created = false - if (input.target.kind === 'self_enrollment') { - await lockCredentialGroupInvitationTarget(tx, input.credentialGroupId, viewerEmail) - const [existing] = await tx - .select({ id: credentialGroupEnrollment.id }) - .from(credentialGroupEnrollment) - .where( - and( - eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId), - eq(credentialGroupEnrollment.email, viewerEmail) - ) - ) - .limit(1) - if (existing) { - enrollmentId = existing.id - } else { - const values = unissuedEnrollmentValues({ - credentialGroupId: input.credentialGroupId, - email: viewerEmail, - now, - }) - enrollmentId = values.id - created = true - await tx.insert(credentialGroupEnrollment).values(values) - } + if (enrollmentId === null) { + const enrollment = await findOrCreateUnissuedEnrollment(tx, { + credentialGroupId: input.credentialGroupId, + email: viewerEmail, + now, + }) + enrollmentId = enrollment.row.id + created = enrollment.created } else { - enrollmentId = input.target.enrollmentId + await lockCredentialGroupEnrollmentLifecycle(tx, enrollmentId) } - await lockCredentialGroupEnrollmentLifecycle(tx, enrollmentId) const [current] = await tx .select({ email: credentialGroupEnrollment.email, userId: credentialGroupEnrollment.userId, status: credentialGroupEnrollment.status, revokedAt: credentialGroupEnrollment.revokedAt, + invitationExpiresAt: credentialGroupEnrollment.invitationExpiresAt, groupStatus: credentialGroup.status, }) .from(credentialGroupEnrollment) @@ -198,9 +188,9 @@ export async function issueCredentialGroupConnectLink(input: { ) ) .limit(1) - .for('update', { of: credentialGroupEnrollment }) if (!current) return { issued: false, reason: 'unavailable' } if (isEnrollmentRevoked(current)) return { issued: false, reason: 'revoked' } + if (isEnrollmentRequestExpired(current, now)) return { issued: false, reason: 'expired' } if (current.groupStatus !== 'active') return { issued: false, reason: 'unavailable' } if (current.userId ? current.userId !== input.userId : current.email !== viewerEmail) return { issued: false, reason: 'unavailable' } diff --git a/apps/sim/lib/credential-groups/connect-url.ts b/apps/sim/lib/credential-groups/connect-url.ts index df42f57431d..658c529cf85 100644 --- a/apps/sim/lib/credential-groups/connect-url.ts +++ b/apps/sim/lib/credential-groups/connect-url.ts @@ -1,12 +1,13 @@ import { getBaseUrl } from '@/lib/core/utils/urls' -import type { CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD } from '@/lib/credential-groups/return-url' +import type { ConnectReturnDestination } from '@/lib/credential-groups/connect-return' interface CredentialGroupConnectPathInput { publicId: string provider: string optionId?: string - /** The raw `return` query value; the connect page honours only the keyword `slack`. */ - returnValue?: string + returnTo?: ConnectReturnDestination + /** The `for` request handle of a link built for one person's email. */ + requestHandle?: string } /** The connect page's path and query, relative to the app origin. */ @@ -14,11 +15,13 @@ export function buildCredentialGroupConnectPath({ publicId, provider, optionId, - returnValue, + returnTo, + requestHandle, }: CredentialGroupConnectPathInput): string { const query = new URLSearchParams({ provider }) if (optionId) query.set('optionId', optionId) - if (returnValue) query.set('return', returnValue) + if (requestHandle) query.set('for', requestHandle) + if (returnTo) query.set('return', returnTo) return `/credential-groups/${encodeURIComponent(publicId)}/connect?${query}` } @@ -26,25 +29,22 @@ export function buildCredentialGroupConnectPath({ * The stable, secret-free link a person opens to connect one integration for a Credential Group. * Safe to show anywhere: the page it opens verifies who is signed in before minting anything. */ -export function buildCredentialGroupConnectUrl({ - publicId, - provider, - returnKey, -}: { - publicId: string - provider: string - returnKey?: typeof CREDENTIAL_GROUP_SLACK_RETURN_KEYWORD -}): string { - return `${getBaseUrl()}${buildCredentialGroupConnectPath({ publicId, provider, returnValue: returnKey })}` +export function buildCredentialGroupConnectUrl( + input: Omit +): string { + return `${getBaseUrl()}${buildCredentialGroupConnectPath(input)}` } -/** Where a resolved connect link continues: the enrollment page, focused on its one option. */ -export function buildCredentialGroupConnectHandoffPath(target: { +/** + * Where a started connection goes: the OAuth start for its one option, through the focused link + * just minted for it, so the person lands at the provider without another click. + */ +export function buildCredentialGroupConnectOAuthStartPath(target: { invitationToken: string optionId: string - returnUrl?: string + returnTo?: ConnectReturnDestination }): string { - const query = new URLSearchParams({ optionId: target.optionId, returnTo: 'connect' }) - if (target.returnUrl) query.set('return', target.returnUrl) - return `/credential-groups/enroll/${encodeURIComponent(target.invitationToken)}?${query}` + const query = new URLSearchParams({ origin: 'connect' }) + if (target.returnTo) query.set('return', target.returnTo) + return `/api/credential-groups/enroll/${encodeURIComponent(target.invitationToken)}/oauth/${encodeURIComponent(target.optionId)}?${query}` } diff --git a/apps/sim/lib/credential-groups/enrollment-links.test.ts b/apps/sim/lib/credential-groups/enrollment-links.test.ts index aa3c5639b6a..b462fca1535 100644 --- a/apps/sim/lib/credential-groups/enrollment-links.test.ts +++ b/apps/sim/lib/credential-groups/enrollment-links.test.ts @@ -8,16 +8,16 @@ describe('credential group OAuth start links', () => { const optionId = 'option/with ?+%' const url = new URL( createCredentialGroupOAuthStartUrl({ - invitationLink: `${origin}/credential-groups/enroll/${encodeURIComponent(token)}?optionId=old&returnTo=accounts#old`, + invitationLink: `${origin}/credential-groups/enroll/${encodeURIComponent(token)}?optionId=old&origin=accounts#old`, optionId, - returnTo: 'search', + origin: 'search', }) ) expect(url.origin).toBe(origin) expect(url.pathname).toBe( `/api/credential-groups/enroll/${encodeURIComponent(token)}/oauth/${encodeURIComponent(optionId)}` ) - expect(url.search).toBe('?returnTo=search') + expect(url.search).toBe('?origin=search') expect(url.hash).toBe('') }) @@ -28,7 +28,7 @@ describe('credential group OAuth start links', () => { createCredentialGroupOAuthStartUrl({ invitationLink: `https://sim.test${path}`, optionId: 'option-1', - returnTo: 'search', + origin: 'search', }) ).toThrow('Invalid credential group enrollment link') } diff --git a/apps/sim/lib/credential-groups/enrollment-links.ts b/apps/sim/lib/credential-groups/enrollment-links.ts index 7010a375336..0a1234b34c3 100644 --- a/apps/sim/lib/credential-groups/enrollment-links.ts +++ b/apps/sim/lib/credential-groups/enrollment-links.ts @@ -2,7 +2,7 @@ export function createCredentialGroupOAuthStartUrl(input: { invitationLink: string optionId: string - returnTo: 'search' | 'accounts' + origin: 'search' | 'accounts' }): string { const invitation = new URL(input.invitationLink) const token = invitation.pathname.match(/^\/credential-groups\/enroll\/([^/]+)$/)?.[1] @@ -11,7 +11,7 @@ export function createCredentialGroupOAuthStartUrl(input: { `/api/credential-groups/enroll/${encodeURIComponent(decodeURIComponent(token))}/oauth/${encodeURIComponent(input.optionId)}`, invitation.origin ) - url.searchParams.set('returnTo', input.returnTo) + url.searchParams.set('origin', input.origin) return url.toString() } diff --git a/apps/sim/lib/credential-groups/mcp-oauth-state.test.ts b/apps/sim/lib/credential-groups/mcp-oauth-state.test.ts index 96499c6a490..42e85ef5d30 100644 --- a/apps/sim/lib/credential-groups/mcp-oauth-state.test.ts +++ b/apps/sim/lib/credential-groups/mcp-oauth-state.test.ts @@ -98,11 +98,11 @@ describe('Credential Group MCP OAuth state', () => { ...ATTEMPT, state: 'mcp_cg_direct', completionId, - returnTo: 'integrations', + origin: 'integrations', }) await expect(consumeCredentialGroupMcpOAuthAttempt('mcp_cg_direct')).resolves.toMatchObject({ completionId, - returnTo: 'integrations', + origin: 'integrations', }) await expect(consumeCredentialGroupMcpOAuthAttempt('mcp_cg_direct')).resolves.toBeNull() }) diff --git a/apps/sim/lib/credential-groups/mcp-oauth-state.ts b/apps/sim/lib/credential-groups/mcp-oauth-state.ts index 63e36d9ccea..e545e618f72 100644 --- a/apps/sim/lib/credential-groups/mcp-oauth-state.ts +++ b/apps/sim/lib/credential-groups/mcp-oauth-state.ts @@ -10,7 +10,7 @@ import { } from '@/lib/credential-groups/oauth-intent' const MCP_OAUTH_ATTEMPT_TTL_MS = 10 * 60 * 1000 -const MCP_OAUTH_ATTEMPT_VERSION = 4 as const +const MCP_OAUTH_ATTEMPT_VERSION = 5 as const const MCP_OAUTH_STATE_PREFIX = 'mcp_cg_' const CONSUME_SCRIPT = ` @@ -34,7 +34,7 @@ return #keys interface StoredCredentialGroupMcpOAuthAttempt { completionId?: string connectionIntent?: CredentialGroupConnectionIntent - returnTo?: 'integrations' + origin?: 'integrations' oauthConfigVersion: number configurationFingerprint?: string userId: string @@ -53,7 +53,7 @@ interface StoredCredentialGroupMcpOAuthAttempt { export interface CredentialGroupMcpOAuthAttempt { completionId?: string connectionIntent?: CredentialGroupConnectionIntent - returnTo?: 'integrations' + origin?: 'integrations' oauthConfigVersion: number configurationFingerprint?: string userId: string @@ -90,7 +90,7 @@ function isStoredAttempt(value: unknown): value is StoredCredentialGroupMcpOAuth /^[a-f0-9]{64}$/.test(candidate.configurationFingerprint))) && (candidate.completionId === undefined || (typeof candidate.completionId === 'string' && isValidUuid(candidate.completionId))) && - (candidate.returnTo === undefined || candidate.returnTo === 'integrations') && + (candidate.origin === undefined || candidate.origin === 'integrations') && (candidate.connectionIntent === undefined || credentialGroupConnectionIntentSchema.safeParse(candidate.connectionIntent).success) && typeof candidate.userId === 'string' && @@ -120,7 +120,7 @@ export function isCredentialGroupMcpOAuthState(state: string): boolean { export async function createCredentialGroupMcpOAuthAttempt(params: { completionId?: string connectionIntent?: CredentialGroupConnectionIntent - returnTo?: 'integrations' + origin?: 'integrations' oauthConfigVersion: number configurationFingerprint?: string userId: string @@ -149,7 +149,7 @@ export async function createCredentialGroupMcpOAuthAttempt(params: { version: MCP_OAUTH_ATTEMPT_VERSION, completionId: params.completionId, connectionIntent: params.connectionIntent, - returnTo: params.returnTo, + origin: params.origin, oauthConfigVersion: params.oauthConfigVersion, configurationFingerprint: params.configurationFingerprint, userId: params.userId, @@ -194,7 +194,7 @@ export async function consumeCredentialGroupMcpOAuthAttempt( state, completionId: parsed.completionId, connectionIntent: parsed.connectionIntent, - returnTo: parsed.returnTo, + origin: parsed.origin, oauthConfigVersion: parsed.oauthConfigVersion, configurationFingerprint: parsed.configurationFingerprint, userId: parsed.userId, diff --git a/apps/sim/lib/credential-groups/mcp-oauth.ts b/apps/sim/lib/credential-groups/mcp-oauth.ts index 48b55b549d4..b8c267c7927 100644 --- a/apps/sim/lib/credential-groups/mcp-oauth.ts +++ b/apps/sim/lib/credential-groups/mcp-oauth.ts @@ -41,7 +41,7 @@ export async function startCredentialGroupMcpOAuth( invitationToken: string, completion: { completionId?: string - returnTo?: 'integrations' + origin?: 'integrations' connectionIntent?: CredentialGroupConnectionIntent } = {} ): Promise { diff --git a/apps/sim/lib/credential-groups/oauth-state.test.ts b/apps/sim/lib/credential-groups/oauth-state.test.ts index 40f3077c6f0..d55136cdddc 100644 --- a/apps/sim/lib/credential-groups/oauth-state.test.ts +++ b/apps/sim/lib/credential-groups/oauth-state.test.ts @@ -103,10 +103,10 @@ describe('credential group OAuth state', () => { requiredScopes: ['openid'], redirectUri: 'https://sim.ai/callback', invitationToken: 'invitation', - returnTo: 'search', + origin: 'search', }) const [key, raw] = [...values.entries()][0] - values.set(key, JSON.stringify({ ...JSON.parse(raw), returnTo: 'https://external.test' })) + values.set(key, JSON.stringify({ ...JSON.parse(raw), origin: 'https://external.test' })) await expect(consumeCredentialGroupOAuthAttempt(created.state)).rejects.toThrow('malformed') await expect(consumeCredentialGroupOAuthAttempt(created.state)).resolves.toBeNull() }) @@ -151,7 +151,7 @@ describe('organization enrollment OAuth state', () => { requiredScopes: ['openid', 'email'], redirectUri: 'https://sim.ai/api/auth/oauth2/callback/google-email', invitationToken: 'invitation-token', - returnTo: 'search' as const, + origin: 'search' as const, } beforeEach(() => { values.clear() @@ -160,13 +160,13 @@ describe('organization enrollment OAuth state', () => { it('round trips explicit organization ownership and preserves the setup return destination', async () => { const { state } = await createCredentialGroupOAuthAttempt(input) const raw = JSON.parse([...values.values()][0]!) - expect(raw.version).toBe(5) + expect(raw.version).toBe(6) expect(raw.organizationId).toBe('org-1') expect(raw.workspaceId).toBeUndefined() const attempt = await consumeCredentialGroupOAuthAttempt(state) expect(attempt).toMatchObject({ organizationId: 'org-1', - returnTo: 'search', + origin: 'search', optionId: 'option-1', }) expect(attempt?.workspaceId).toBeUndefined() diff --git a/apps/sim/lib/credential-groups/oauth-state.ts b/apps/sim/lib/credential-groups/oauth-state.ts index cf626556b4d..e4d58a5d02f 100644 --- a/apps/sim/lib/credential-groups/oauth-state.ts +++ b/apps/sim/lib/credential-groups/oauth-state.ts @@ -4,6 +4,10 @@ import { generateId, isValidUuid } from '@sim/utils/id' import { getRedisClient } from '@/lib/core/config/redis' import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' import { decryptSecret, encryptSecret } from '@/lib/core/security/encryption' +import { + type ConnectReturnDestination, + parseConnectReturnDestination, +} from '@/lib/credential-groups/connect-return' import { assertCredentialGroupOAuthAttemptVersion } from '@/lib/credential-groups/oauth-attempt-version' import { type CredentialGroupConnectionIntent, @@ -13,18 +17,23 @@ import { type CredentialGroupProvider, isCredentialGroupProvider, } from '@/lib/credential-groups/providers' -import { parseCredentialGroupReturnUrl } from '@/lib/credential-groups/return-url' /** Where a managed-enrollment OAuth attempt lands once the provider sends the person back. */ -export type CredentialGroupOAuthReturnTo = +export type CredentialGroupOAuthOrigin = | 'search' | 'accounts' | 'connect' | 'integrations' | 'github-installation' -const OAUTH_ATTEMPT_TTL_MS = 10 * 60 * 1000 -const OAUTH_ATTEMPT_VERSION = 5 as const +/** How long a person has at the provider before the attempt expires. */ +const OAUTH_ATTEMPT_TTL_MS = 30 * 60 * 1000 +/** + * How long an expired attempt is kept, only so its callback can still say where the person came + * from (and offer Return to Slack) instead of a bare "expired". + */ +const EXPIRED_OAUTH_ATTEMPT_RETENTION_MS = 30 * 60 * 1000 +const OAUTH_ATTEMPT_VERSION = 6 as const const OAUTH_ATTEMPT_STATE_PREFIX = 'cg_' const CONSUME_SCRIPT = ` @@ -53,8 +62,8 @@ interface StoredCredentialGroupOAuthAttempt { completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: CredentialGroupOAuthReturnTo - returnUrl?: string + origin?: CredentialGroupOAuthOrigin + returnTo?: ConnectReturnDestination nonceHash: string encryptedCodeVerifier?: string encryptedInvitationToken: string @@ -79,8 +88,8 @@ export interface CredentialGroupOAuthAttempt { completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: CredentialGroupOAuthReturnTo - returnUrl?: string + origin?: CredentialGroupOAuthOrigin + returnTo?: ConnectReturnDestination codeVerifier?: string invitationToken: string createdAt: number @@ -102,8 +111,8 @@ interface CreateCredentialGroupOAuthAttemptParams { completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: CredentialGroupOAuthReturnTo - returnUrl?: string + origin?: CredentialGroupOAuthOrigin + returnTo?: ConnectReturnDestination codeVerifier?: string invitationToken: string } @@ -149,18 +158,17 @@ function isStoredAttempt(value: unknown): value is StoredCredentialGroupOAuthAtt isValidUuid(candidate.completionId))) && (candidate.connectionIntent === undefined || credentialGroupConnectionIntentSchema.safeParse(candidate.connectionIntent).success) && - (candidate.returnTo === undefined || - candidate.returnTo === 'search' || - candidate.returnTo === 'accounts' || - candidate.returnTo === 'connect' || - candidate.returnTo === 'integrations' || - (candidate.returnTo === 'github-installation' && + (candidate.origin === undefined || + candidate.origin === 'search' || + candidate.origin === 'accounts' || + candidate.origin === 'connect' || + candidate.origin === 'integrations' || + (candidate.origin === 'github-installation' && candidate.provider === 'github-repositories' && typeof candidate.organizationId === 'string' && typeof candidate.completionId === 'string')) && - (candidate.returnUrl === undefined || - (typeof candidate.returnUrl === 'string' && - parseCredentialGroupReturnUrl(candidate.returnUrl) !== null)) && + (candidate.returnTo === undefined || + parseConnectReturnDestination(candidate.returnTo) !== undefined) && typeof candidate.nonceHash === 'string' && (candidate.encryptedCodeVerifier === undefined || typeof candidate.encryptedCodeVerifier === 'string') && @@ -180,19 +188,12 @@ export async function createCredentialGroupOAuthAttempt( throw new Error('OAuth completion requires a valid correlation ID and completion redirect') } if ( - params.returnTo === 'github-installation' && + params.origin === 'github-installation' && (params.provider !== 'github-repositories' || !params.organizationId || !params.completionId) ) { throw new Error('GitHub installation OAuth requires an organization-bound setup attempt') } if (params.connectionIntent) credentialGroupConnectionIntentSchema.parse(params.connectionIntent) - const returnUrl = - params.returnUrl === undefined - ? undefined - : parseCredentialGroupReturnUrl(params.returnUrl)?.href - if (params.returnUrl !== undefined && !returnUrl) { - throw new Error('Credential group OAuth return URL is not an allowed destination') - } const redis = getRedisClient() const state = `${OAUTH_ATTEMPT_STATE_PREFIX}${generateId()}` const nonce = generateId() @@ -216,8 +217,8 @@ export async function createCredentialGroupOAuthAttempt( ...(params.completionRedirect ? { completionRedirect: true } : {}), ...(params.connectionIntent ? { connectionIntent: params.connectionIntent } : {}), ...(params.completionId ? { completionId: params.completionId } : {}), + ...(params.origin ? { origin: params.origin } : {}), ...(params.returnTo ? { returnTo: params.returnTo } : {}), - ...(returnUrl ? { returnUrl } : {}), nonceHash: sha256Hex(nonce), ...(encryptedCodeVerifier ? { encryptedCodeVerifier: encryptedCodeVerifier.encrypted } : {}), encryptedInvitationToken: encryptedInvitationToken.encrypted, @@ -227,7 +228,7 @@ export async function createCredentialGroupOAuthAttempt( attemptKey(state), JSON.stringify(attempt), 'PX', - OAUTH_ATTEMPT_TTL_MS, + OAUTH_ATTEMPT_TTL_MS + EXPIRED_OAUTH_ATTEMPT_RETENTION_MS, 'NX' ) if (stored !== 'OK') throw new Error('Credential group OAuth state collision') @@ -239,10 +240,19 @@ export function isCredentialGroupOAuthState(state: string): boolean { return state.startsWith(OAUTH_ATTEMPT_STATE_PREFIX) } -/** Atomically burns state before the single-use authorization code is exchanged. */ +/** An attempt the person took too long to finish; only where they came from is kept. */ +export interface ExpiredCredentialGroupOAuthAttempt { + expired: true + returnTo?: ConnectReturnDestination +} + +/** + * Atomically burns state before the single-use authorization code is exchanged. Null for state + * that never existed or is long gone. + */ export async function consumeCredentialGroupOAuthAttempt( state: string -): Promise { +): Promise { const redis = getRedisClient() const raw = await redis.eval(CONSUME_SCRIPT, 1, attemptKey(state)) if (raw === null) return null @@ -251,7 +261,8 @@ export async function consumeCredentialGroupOAuthAttempt( const parsed: unknown = JSON.parse(raw) assertCredentialGroupOAuthAttemptVersion(parsed, OAUTH_ATTEMPT_VERSION) if (!isStoredAttempt(parsed)) throw new Error('Credential group OAuth state is malformed') - if (Date.now() - parsed.createdAt > OAUTH_ATTEMPT_TTL_MS) return null + if (Date.now() - parsed.createdAt > OAUTH_ATTEMPT_TTL_MS) + return { expired: true, ...(parsed.returnTo ? { returnTo: parsed.returnTo } : {}) } const [codeVerifier, invitationToken] = await Promise.all([ parsed.encryptedCodeVerifier ? decryptSecret(parsed.encryptedCodeVerifier) : undefined, @@ -274,8 +285,8 @@ export async function consumeCredentialGroupOAuthAttempt( ...(parsed.completionRedirect ? { completionRedirect: true } : {}), ...(parsed.connectionIntent ? { connectionIntent: parsed.connectionIntent } : {}), ...(parsed.completionId ? { completionId: parsed.completionId } : {}), + ...(parsed.origin ? { origin: parsed.origin } : {}), ...(parsed.returnTo ? { returnTo: parsed.returnTo } : {}), - ...(parsed.returnUrl ? { returnUrl: parsed.returnUrl } : {}), ...(codeVerifier ? { codeVerifier: codeVerifier.decrypted } : {}), invitationToken: invitationToken.decrypted, createdAt: parsed.createdAt, diff --git a/apps/sim/lib/credential-groups/rate-limit.ts b/apps/sim/lib/credential-groups/rate-limit.ts index a6b67aa0284..840844a1174 100644 --- a/apps/sim/lib/credential-groups/rate-limit.ts +++ b/apps/sim/lib/credential-groups/rate-limit.ts @@ -1,7 +1,10 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' import { NextResponse } from 'next/server' import { RateLimitError, RateLimiter, type TokenBucketConfig } from '@/lib/core/rate-limiter' import { getClientIp } from '@/lib/core/utils/request' +const logger = createLogger('CredentialGroupRateLimit') const rateLimiter = new RateLimiter() const CREDENTIAL_GROUP_INVITATION_RATE_LIMIT = { @@ -37,7 +40,6 @@ type PublicCredentialGroupRateLimitScope = | 'oauth-start' | 'oauth-callback' | 'complete' - | 'connect-confirm' function rateLimitResponse(retryAfterMs: number | undefined, fallbackMs: number): NextResponse { const retryAfterSeconds = Math.ceil((retryAfterMs ?? fallbackMs) / 1000) @@ -55,8 +57,7 @@ function rateLimitResponse(retryAfterMs: number | undefined, fallbackMs: number) function configForPublicScope(scope: PublicCredentialGroupRateLimitScope): TokenBucketConfig { if (scope === 'metadata') return PUBLIC_ENROLLMENT_METADATA_RATE_LIMIT - if (scope === 'oauth-start' || scope === 'complete' || scope === 'connect-confirm') - return PUBLIC_OAUTH_START_RATE_LIMIT + if (scope === 'oauth-start' || scope === 'complete') return PUBLIC_OAUTH_START_RATE_LIMIT return PUBLIC_OAUTH_CALLBACK_RATE_LIMIT } @@ -89,8 +90,9 @@ export async function enforcePublicCredentialGroupIpRateLimit( } /** - * Applies the OAuth-start IP bucket when resolvable and otherwise defers to the - * mandatory per-enrollment OAuth budget applied after invitation authentication. + * Applies the OAuth-start IP bucket when resolvable and otherwise defers. Only a start that did + * not authenticate uses it: a signed-in start is bounded by its enrollment's OAuth budget instead, + * so people behind one office or carrier address do not share a bucket. */ export async function enforcePublicCredentialGroupOAuthStartIpRateLimit(request: { headers: { get(name: string): string | null } @@ -118,14 +120,26 @@ const CONNECT_LINK_USER_RATE_LIMIT: TokenBucketConfig = { refillIntervalMs: 15 * 60_000, } -/** Bounds how many connect links one signed-in person can mint, wherever they open them from. */ -export async function isCredentialGroupConnectUserRateLimited(userId: string): Promise { - const result = await rateLimiter.checkRateLimitDirect( - `credential-group-connect:user:${userId}`, - CONNECT_LINK_USER_RATE_LIMIT, - { failClosed: true } - ) - return !result.allowed +/** + * Bounds how many times one signed-in person can open or start connect links, wherever they open + * them from. Fails closed, but tells an outage of the limiter (`unavailable`) apart from a person + * who really is over the limit (`limited`), so neither is told the other. + */ +export async function checkCredentialGroupConnectUserRateLimit( + userId: string +): Promise<'allowed' | 'limited' | 'unavailable'> { + try { + const result = await rateLimiter.checkRateLimitDirectOrThrow( + `credential-group-connect:user:${userId}`, + CONNECT_LINK_USER_RATE_LIMIT + ) + return result.allowed ? 'allowed' : 'limited' + } catch (error) { + logger.error('Credential group connect rate limit unavailable', { + error: getErrorMessage(error), + }) + return 'unavailable' + } } export class CredentialGroupInvitationRateLimitError extends RateLimitError { diff --git a/apps/sim/lib/credential-groups/self-enrollment-oauth.ts b/apps/sim/lib/credential-groups/self-enrollment-oauth.ts index 19b491a5148..b6620623fc8 100644 --- a/apps/sim/lib/credential-groups/self-enrollment-oauth.ts +++ b/apps/sim/lib/credential-groups/self-enrollment-oauth.ts @@ -16,7 +16,7 @@ export async function startViewerCredentialGroupOAuth(input: { credentialGroupId: string optionId: string completionId: string - returnTo?: 'integrations' + origin?: 'integrations' connectionIntent?: CredentialGroupConnectionIntent }): Promise<{ invitationLink: string; authorizationUrl: string }> { const { enrollment, invitationLink } = await createViewerCredentialGroupEnrollment(input) @@ -37,7 +37,7 @@ export async function startViewerCredentialGroupOAuth(input: { throw new OrchestrationError('forbidden', 'This account connection is no longer available') const authorizationUrl = await startCredentialGroupOAuth(oauth, token, { completionRedirect: true, - returnTo: input.returnTo ?? 'search', + origin: input.origin ?? 'search', completionId: input.completionId, connectionIntent: input.connectionIntent, }) @@ -51,7 +51,7 @@ export async function startViewerCredentialGroupMcpOAuth(input: { credentialGroupId: string mcpServerId: string completionId: string - returnTo?: 'integrations' + origin?: 'integrations' connectionIntent?: CredentialGroupConnectionIntent }): Promise<{ invitationLink: string; authorizationUrl: string }> { const { enrollment, invitationLink } = await createViewerCredentialGroupEnrollment(input) @@ -71,7 +71,7 @@ export async function startViewerCredentialGroupMcpOAuth(input: { throw new OrchestrationError('forbidden', 'This account connection is no longer available') const authorizationUrl = await startCredentialGroupMcpOAuth(oauth, token, { completionId: input.completionId, - returnTo: input.returnTo, + origin: input.origin, connectionIntent: input.connectionIntent, }) return { invitationLink, authorizationUrl } diff --git a/apps/sim/lib/knowledge/application/connector-access.ts b/apps/sim/lib/knowledge/application/connector-access.ts index 13ab39ccb0b..61354910145 100644 --- a/apps/sim/lib/knowledge/application/connector-access.ts +++ b/apps/sim/lib/knowledge/application/connector-access.ts @@ -118,7 +118,7 @@ export const startKnowledgeConnectorMemberEnrollment = defineAuthorizedKnowledge if (!context.knowledgeBase.isSearchIndex) return invitationLink const url = new URL(invitationLink) url.searchParams.set('optionId', optionId) - url.searchParams.set('returnTo', 'search') + url.searchParams.set('origin', 'search') return url.toString() } if (connector.accessMode === 'admin') { diff --git a/apps/sim/lib/knowledge/application/github-setup.test.ts b/apps/sim/lib/knowledge/application/github-setup.test.ts index dc55e9fb8fa..a0d4494c4ac 100644 --- a/apps/sim/lib/knowledge/application/github-setup.test.ts +++ b/apps/sim/lib/knowledge/application/github-setup.test.ts @@ -194,7 +194,7 @@ const oauthAttempt = { redirectUri: 'https://sim.example/api/auth/oauth2/callback/github-repositories', completionRedirect: true, completionId: input.setupId, - returnTo: 'github-installation' as const, + origin: 'github-installation' as const, invitationToken: 'fixture-invitation', createdAt: 0, } diff --git a/apps/sim/lib/knowledge/application/github-setup.ts b/apps/sim/lib/knowledge/application/github-setup.ts index 9b2c39e3f9e..60df3ead8cf 100644 --- a/apps/sim/lib/knowledge/application/github-setup.ts +++ b/apps/sim/lib/knowledge/application/github-setup.ts @@ -267,7 +267,7 @@ async function authorizeReader(attempt: GitHubSetupAttempt) { const url = await startCredentialGroupOAuth(context, token, { completionRedirect: true, completionId: attempt.setupId, - returnTo: 'github-installation', + origin: 'github-installation', connectionIntent: existing ? { kind: 'reconnect', credentialId: existing.id } : { kind: 'create' }, @@ -494,7 +494,7 @@ export const completeGitHubSetupReaderOAuth = defineAuthorizedKnowledgeUseCase({ const { attempt } = input if ( attempt.provider !== 'github-repositories' || - attempt.returnTo !== 'github-installation' || + attempt.origin !== 'github-installation' || !attempt.organizationId || !attempt.completionId || attempt.userId !== principal.userId From 17fa43d698e5e19530622bba7735201abefc47bb Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 16:43:58 -0600 Subject: [PATCH 18/26] feat(credential-groups): workflow request cap, reminders, policy effect, and block copy - the daily cap counts distinct addresses; asking again today is unlogged and uncapped - a workflow request, its reminder, and an admin reminder renew an unanswered request - an admin's Send reminder on a workflow's open request re-sends that workflow's request for its integration and keeps the attribution - request emails use the outbox's default attempts and record sentAt only on delivery - the policy read reports inEffect; saving rejects an integration no chosen workspace may use; conflict copy and a wider free-mail list - org invitations no longer name the group; the workflow email asks the person to sign in or create a Sim account with their address - the block input is returnTo; the dropdown hides ORGANIZATION_OPERATIONS from the block; handler copy says Integration and asks for the primary email --- .../components/dropdown/dropdown.tsx | 9 +- apps/sim/blocks/blocks/credential.ts | 7 +- .../credential-group-invitation-email.tsx | 42 +-- .../emails/credential-groups/render.ts | 9 +- .../executor/handlers/credential/handler.ts | 41 ++- apps/sim/lib/credential-groups/README.md | 24 +- ...orkflow-connection-requests.integration.ts | 157 +++++++-- .../application/connection-requests.ts | 51 ++- .../organization-account-management.ts | 42 ++- .../organization-connection-requests.ts | 77 ++++- .../connection-request-email.ts | 65 ++-- .../connection-request-event.ts | 6 +- .../connection-request-policy.ts | 18 +- .../credential-groups/connection-requests.ts | 306 +++++++++++------- 14 files changed, 576 insertions(+), 278 deletions(-) diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/dropdown/dropdown.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/dropdown/dropdown.tsx index f81cb1b7721..055b1f62e46 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/dropdown/dropdown.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/dropdown/dropdown.tsx @@ -16,6 +16,7 @@ import { getWorkflowSearchLabelHighlight } from '@/app/workspace/[workspaceId]/w import { useFetchedOptions } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-fetched-options' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' import { useActiveSearchTarget } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/providers/active-search-target-provider' +import { ORGANIZATION_OPERATIONS } from '@/blocks/blocks/credential' import { getBlock } from '@/blocks/registry' import type { SubBlockConfig } from '@/blocks/types' import { ResponseBlockHandler } from '@/executor/handlers/response/handler' @@ -313,13 +314,7 @@ export const Dropdown = memo(function Dropdown({ opt.hidden || hiddenCredentialOptions.has(opt.id) || deniedOperationIds.has(opt.id) || - (hideOrganizationOperations && - [ - 'find_organization_account', - 'list_organization_accounts', - 'find_organization_mcp_connection', - 'list_organization_mcp_connections', - ].includes(opt.id)), + (hideOrganizationOperations && ORGANIZATION_OPERATIONS.includes(opt.id)), } }) }, [ diff --git a/apps/sim/blocks/blocks/credential.ts b/apps/sim/blocks/blocks/credential.ts index 03c437142d6..d233b7d7a85 100644 --- a/apps/sim/blocks/blocks/credential.ts +++ b/apps/sim/blocks/blocks/credential.ts @@ -4,7 +4,8 @@ import type { BlockConfig } from '@/blocks/types' import { getTrigger } from '@/triggers' const CONNECTION_OPERATIONS = ['get_connection_status', 'request_connection'] -const ORGANIZATION_OPERATIONS = [ +/** Operations that read the organization's Credential Group; hidden where the workspace cannot. */ +export const ORGANIZATION_OPERATIONS = [ 'find_organization_account', ...CONNECTION_OPERATIONS, 'list_organization_accounts', @@ -164,7 +165,7 @@ export const CredentialBlock: BlockConfig = { }, }, { - id: 'connectReturnTo', + id: 'returnTo', title: 'Return to', type: 'dropdown', options: [ @@ -209,7 +210,7 @@ export const CredentialBlock: BlockConfig = { type: 'json', description: 'Optional organization OAuth provider IDs', }, - connectReturnTo: { + returnTo: { type: 'string', description: 'Where connectUrl offers to send the person once connected: none, or slack to open the Slack app', diff --git a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx index c6aa908e613..9266bf2ada9 100644 --- a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx +++ b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx @@ -2,15 +2,19 @@ import { Link, Text } from '@react-email/components' import { baseStyles } from '@/components/emails/_styles' import { EmailLayout } from '@/components/emails/components' +export type CredentialGroupInvitationOwner = + | { kind: 'organization'; name: string } + | { kind: 'workspace'; name: string; credentialGroupName: string } + interface CredentialGroupInvitationEmailProps { recipientEmail: string /** Absent when a workflow issued the invitation: there is no person to name. */ inviterName?: string - /** The organization or workspace name, per {@link ownerKind}. */ - workspaceName: string - /** Whether the Credential Group belongs to an organization or a single workspace. */ - ownerKind: 'organization' | 'workspace' - credentialGroupName: string + /** + * Who collects the accounts. An organization has one Credential Group, so only a workspace + * group is named. + */ + owner: CredentialGroupInvitationOwner invitationLink: string searchProviderName?: string /** @@ -24,22 +28,21 @@ interface CredentialGroupInvitationEmailProps { export function CredentialGroupInvitationEmail({ recipientEmail, inviterName, - workspaceName, - ownerKind, - credentialGroupName, + owner, invitationLink, searchProviderName, workflowRequest, }: CredentialGroupInvitationEmailProps) { const providerName = searchProviderName ?? workflowRequest?.providerName + const ownerName = owner.name return ( @@ -47,8 +50,8 @@ export function CredentialGroupInvitationEmail({ {workflowRequest ? ( <> - {workflowRequest.workflowName} in {workspaceName}{' '} - asked you to connect {workflowRequest.providerName}. + {workflowRequest.workflowName} in {ownerName} asked + you to connect {workflowRequest.providerName}. ) : ( <> @@ -64,17 +67,18 @@ export function CredentialGroupInvitationEmail({ {searchProviderName ? ( <> to connect your {searchProviderName} account for Search in{' '} - {workspaceName}. + {ownerName}. ) : ( <> - to connect accounts for {credentialGroupName} in{' '} - {ownerKind === 'workspace' ? ( + to connect accounts for{' '} + {owner.kind === 'workspace' ? ( <> - the {workspaceName} workspace + {owner.credentialGroupName} in the {ownerName}{' '} + workspace ) : ( - {workspaceName} + {ownerName} )}{' '} on Sim. @@ -98,7 +102,7 @@ export function CredentialGroupInvitationEmail({ {workflowRequest - ? `Sign in to Sim as ${recipientEmail} to continue. Sim will send you to ${workflowRequest.providerName} to sign in and will never ask for your ${workflowRequest.providerName} password. If you did not expect this request, you can ignore it.` + ? `Sign in or create a Sim account with ${recipientEmail} to continue. Sim will send you to ${workflowRequest.providerName} to sign in and will never ask for your ${workflowRequest.providerName} password. If you did not expect this request, you can ignore it.` : 'This private link expires in 7 days. Sim will send you to each provider to sign in and will never ask for your provider password. If you did not expect this invitation, you can ignore it.'} diff --git a/apps/sim/components/emails/credential-groups/render.ts b/apps/sim/components/emails/credential-groups/render.ts index e8b5aa403c5..cf12ffd9c2c 100644 --- a/apps/sim/components/emails/credential-groups/render.ts +++ b/apps/sim/components/emails/credential-groups/render.ts @@ -1,12 +1,13 @@ import { render } from '@react-email/render' -import { CredentialGroupInvitationEmail } from '@/components/emails/credential-groups/credential-group-invitation-email' +import { + CredentialGroupInvitationEmail, + type CredentialGroupInvitationOwner, +} from '@/components/emails/credential-groups/credential-group-invitation-email' export async function renderCredentialGroupInvitationEmail(params: { recipientEmail: string inviterName?: string - workspaceName: string - ownerKind: 'organization' | 'workspace' - credentialGroupName: string + owner: CredentialGroupInvitationOwner invitationLink: string searchProviderName?: string workflowRequest?: { workflowName: string; providerName: string } diff --git a/apps/sim/executor/handlers/credential/handler.ts b/apps/sim/executor/handlers/credential/handler.ts index 9a191d8a899..88f81f518cd 100644 --- a/apps/sim/executor/handlers/credential/handler.ts +++ b/apps/sim/executor/handlers/credential/handler.ts @@ -6,6 +6,10 @@ import { } from '@/lib/credential-groups/application/connection-requests' import { listCredentialGroupCredentials } from '@/lib/credential-groups/application/list-credentials' import { listCredentialGroupMcpConnections } from '@/lib/credential-groups/application/list-mcp-connections' +import { + type ConnectReturnDestination, + parseConnectReturnDestination, +} from '@/lib/credential-groups/connect-return' import { MAX_CREDENTIAL_GROUP_CREDENTIAL_PAGE_SIZE } from '@/lib/credential-groups/credentials' import { resolveWorkflowCredentials } from '@/lib/credentials/application/resolve-workflow-credentials' import { createExecutorPrincipalFromExecutionContext } from '@/lib/internal/principals/executor' @@ -56,12 +60,23 @@ function parseOptionalString(value: unknown, label: string): string | undefined return value.trim() } -/** The connect link's return destination: `slack`, or none when blank or `none`. */ -function parseConnectReturnTo(value: unknown): { returnTo?: 'slack' } { - const returnTo = parseOptionalString(value, 'Return to') - if (returnTo === undefined || returnTo === 'none') return {} - if (returnTo === 'slack') return { returnTo } - throw new Error('Return to must be none or slack') +/** The connect link's return destination, or none when blank or `none`. */ +function parseConnectReturnTo(value: unknown): { returnTo?: ConnectReturnDestination } { + const raw = parseOptionalString(value, 'Return to') + if (raw === undefined || raw === 'none') return {} + const returnTo = parseConnectReturnDestination(raw) + if (!returnTo) throw new Error('Return to must be none or slack') + return { returnTo } +} + +/** The person's address as Slack reports it (`users.info` → `profile.email`), not an alias. */ +const CONNECTION_EMAIL_REQUIRED = + "Email is required. Use the person's primary email, for example profile.email from Slack users.info" + +function requireConnectionEmail(value: unknown): string { + const email = parseOptionalString(value, 'Email') + if (!email) throw new Error(CONNECTION_EMAIL_REQUIRED) + return email } function requireString(value: unknown, label: string): string { @@ -121,7 +136,7 @@ export class CredentialBlockHandler implements BlockHandler { ? requireString(inputs.email, 'Email') : parseOptionalString(inputs.email, 'Email'), credentialProviderIds: find - ? [requireString(inputs.organizationProvider, 'Provider')] + ? [requireString(inputs.organizationProvider, 'Integration')] : parseStringList(inputs.organizationProviders, 'Providers'), limit: find ? 1 : parseLimit(inputs.limit), cursor: find ? undefined : parseOptionalString(inputs.cursor, 'Cursor'), @@ -142,9 +157,9 @@ export class CredentialBlockHandler implements BlockHandler { principal, input: { workspaceId: ctx.workspaceId, - email: requireString(inputs.email, 'Email'), - providerId: requireString(inputs.organizationProvider, 'Provider'), - ...parseConnectReturnTo(inputs.connectReturnTo), + email: requireConnectionEmail(inputs.email), + providerId: requireString(inputs.organizationProvider, 'Integration'), + ...parseConnectReturnTo(inputs.returnTo), }, }) case 'request_connection': @@ -152,9 +167,9 @@ export class CredentialBlockHandler implements BlockHandler { principal, input: { workspaceId: ctx.workspaceId, - email: requireString(inputs.email, 'Email'), - providerId: requireString(inputs.organizationProvider, 'Provider'), - ...parseConnectReturnTo(inputs.connectReturnTo), + email: requireConnectionEmail(inputs.email), + providerId: requireString(inputs.organizationProvider, 'Integration'), + ...parseConnectReturnTo(inputs.returnTo), }, }) case 'find_organization_mcp_connection': diff --git a/apps/sim/lib/credential-groups/README.md b/apps/sim/lib/credential-groups/README.md index 69a972d95a8..9594c142efd 100644 --- a/apps/sim/lib/credential-groups/README.md +++ b/apps/sim/lib/credential-groups/README.md @@ -4,7 +4,7 @@ An organization has at most one account pool. Owners and admins manage it in **O Credential Groups remains available whenever its organization feature is enabled, independently of Search. Search administrators use **Settings → Sources**; members use **Integrations**. The live Sources page has no credential-pool setup or People tabs. These surfaces reuse current grants without changing credential-group API access or stored workspace policies. -**Credential Groups → People → Request connections** sends manual email invitations. Each person shows one status (Invited, Expired, Email failed, Connected, Needs reconnect, or Revoked) and has **Send reminder** (until their enrollment is completed) and **Revoke** in their actions menu. If no org credential group exists, the page offers **Set up Credential Groups** first. Search source creation does not replace required provider app configuration. +**Credential Groups → People → Request connections** sends manual email invitations. Each person shows one status (Invited, Requested, Expired, Email failed, Not connected, Connected, Needs reconnect, or Revoked) and has **Send reminder** and **Revoke** in their actions menu; a revoked person has **Re-invite**, which is the ordinary invitation. **Send reminder** on a workflow's open request emails that workflow's request for its integration again and keeps it the workflow's; on anyone else it is the admin's invitation again. If no org credential group exists, the page offers **Set up Credential Groups** first. Search source creation does not replace required provider app configuration. ## Permissions @@ -72,24 +72,36 @@ Every bearer link into an enrollment is a row in `credential_group_enrollment_li | Purpose | Issued by | Lifetime | | --- | --- | --- | -| `email` | An admin's invitation or resend, or an automatic invitation | 7 days while the enrollment is unbound; no expiry once a verified user is bound | +| `email` | An admin's invitation or resend, or an automatic invitation | 7 days; once a verified user is bound, the newest emailed link (the one the legacy column mirrors) no longer expires | | `self` | A member enrolling themselves from Integrations | 1 hour, always | -| `connect` | The connect page, for one account option | 1 hour, always; an expired one sends the person back to the connect page to start again | +| `connect` | The connect page's Connect button, for one account option | 1 hour, always; an expired one sends the person back to the connect page to start again | -The 0490 migration's backfill recorded every existing invitation, including self-enrollment tokens issued before links existed, as `email`, so those keep the emailed lifetime. The hourly `cleanup-credential-group-links` cron job deletes `self` and `connect` links a day after they expire, and the workflow connection-request log after two days. +The 0490 migration's backfill recorded every existing invitation, including self-enrollment tokens issued before links existed, as `email`, so those keep the emailed lifetime. One rule, `unexpiredLinkCondition`, decides every link's expiry, for lookups, explanations and retention alike. The hourly `cleanup-credential-group-links` cron job deletes `self` and `connect` links a day after they expire, and the workflow connection-request log after two days. An emailed reinvitation deliberately restarts the invitation: the issuer, invited and sent times move to the new send, a workflow's request marker and reminder count are cleared, and the status returns to Invited unless the person already made progress. Earlier links stay live. -Status is authoritative for revocation. The pre-link app revokes an enrollment by setting its status alone, so during a deploy or rollback its links can stay unrevoked; every link check also refuses a `revoked` enrollment, and a reinvitation revokes such links. The pre-link app's disconnect rewrites only the legacy column, so the same bound person's emailed links stay live through it; the contract migration below revokes links whose enrollment's legacy column no longer names any link. +Status is authoritative for revocation. The pre-link app revokes an enrollment by setting its status alone, so during a deploy or rollback its links can stay unrevoked; every link check also refuses a `revoked` enrollment, and a reinvitation revokes such links. The pre-link app's disconnect rewrites only the legacy column; a bound person's emailed link stays unexpired only while that column names it, so that disconnect ends it too. Contract phase (after the link expand is fully deployed and no rollback target predates it): 1. Make `credential_group_enrollment.invitation_token_hash` nullable and stop writing it. Enrollments created without an emailed link store null instead of an `unissued:` value. Revoke live links into enrollments whose legacy column matches no link row. 2. Drop the column with its unique index and length check, and remove the legacy branch of `liveEnrollmentLinkCondition`, `adoptLegacyInvitationLink`, and the legacy fallback of `findCredentialGroupEnrollmentLinkRecord`. +## Connect URL + +A workflow's `connectUrl` is `/credential-groups//connect?provider=`, plus `for=` when it was built for one person (a keyed hash of the group and their address) and `return=slack` when the workflow asked to send the person back to Slack. It carries no secret. Opening it only reads (`openCredentialGroupConnect`); its one Connect button is a same-origin POST (`startCredentialGroupConnect`) that, in one transaction, enrolls a member enrolling themselves, binds the person to the enrollment requested at their verified address, and mints a one-hour `connect` link, then goes straight to the provider. A link whose `for` names someone else says so without revealing the address and never offers self-enrollment. + +An unbound enrollment is a request that waits seven days (`invitation_expires_at`); after that the connect page refuses it as expired and People shows Expired, both through `isEnrollmentRequestExpired`. A workflow asking again, a workflow reminder, and an admin's reminder or invitation renew it. A bound enrollment never expires. A connection made through a connect link completes the enrollment when the request is done: a workflow's request after its one integration, anyone else once every active option is connected. + +`return=slack` is the only return destination (`ConnectReturnDestination`). It travels through the OAuth attempt and is rendered as "Return to Slack" (`slack://open`) with "You can close this tab." A forged one can at most open the Slack app. + +On a deployment that cannot verify email (verification off, or no mail provider), a signed-in user's address is taken as verified for claiming an enrollment. + +The daily request limit counts distinct addresses per group per day; asking again for an address already asked today is neither logged nor counted. + ## Rollout -OAuth attempt state changes at this release boundary (OAuth v5 and managed MCP v3). Older attempts lack a verified Sim user binding; older MCP attempts also lack the configuration version. They are deliberately rejected before token exchange, with an explicit instruction to reopen the invitation and connect again. Existing saved credentials are not invalidated by the state version change. Mixed application versions cannot complete each other's in-flight attempts: pause enrollment starts, allow the ten-minute state lifetime to drain, replace the application instances together, and only then reopen enrollment. Do not run enrollment OAuth across mixed versions or roll back with active attempts. +OAuth attempt state changes at this release boundary (OAuth v6 and managed MCP v5). Older attempts lack a verified Sim user binding; older MCP attempts also lack the configuration version. They are deliberately rejected before token exchange, with an explicit instruction to reopen the invitation and connect again. Existing saved credentials are not invalidated by the state version change. Mixed application versions cannot complete each other's in-flight attempts: pause enrollment starts, allow the thirty-minute state lifetime to drain, replace the application instances together, and only then reopen enrollment. Do not run enrollment OAuth across mixed versions or roll back with active attempts. 1. Apply `0328_organization_connected_accounts.sql` before deploying code that reads the new columns. It expands ownership columns and checks, adds stable enrollment identity and MCP configuration versions, and builds indexes concurrently. No grants, enrollments, or Search data are moved or deleted. Constraints are added `NOT VALID` to avoid scanning existing tables while holding the DDL lock; validate them separately after auditing existing rows. 2. Inventory existing groups and their Search dependencies before enabling the feature. The queries below read IDs/counts only. Review archived/deleted sources too because a reset must account for retained documents and cleanup work. diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index fb59d6078e7..09839519e5b 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -50,11 +50,13 @@ import { requestOrganizationAccountConnection, } from '@/lib/credential-groups/application/connection-requests' import { updateOrganizationAccountWorkspaceAccess } from '@/lib/credential-groups/application/organization-access' +import { resendOrganizationAccountInvitation } from '@/lib/credential-groups/application/organization-account-management' import { getOrganizationConnectionRequestPolicy, updateOrganizationConnectionRequestPolicy, } from '@/lib/credential-groups/application/organization-connection-requests' import { buildOrganizationAccountAccessPolicy } from '@/lib/credential-groups/application/workspace-access-policy' +import { connectRequestHandle } from '@/lib/credential-groups/connect-request-handle' import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' import { credentialGroupConnectionRequestOutboxHandlers } from '@/lib/credential-groups/connection-request-email' import { @@ -465,17 +467,23 @@ afterAll(async () => { await db.delete(user).where(inArray(user.id, [ownerId, ...people.values()])) }) -describe('get_connection_status', () => { - const connectUrl = () => - `http://localhost:3000/credential-groups/${orgA.publicId}/connect?provider=${DRIVE_ID}` +/** The connect URL a workflow gets for one person: the stable page, with that person's handle. */ +function personConnectUrl(fixture: OrgFixture, email: string) { + return buildCredentialGroupConnectUrl({ + publicId: fixture.publicId, + provider: DRIVE_ID, + requestHandle: connectRequestHandle(fixture.groupId, email), + }) +} +describe('get_connection_status', () => { it('reports a connected person with the credential Find Organization Account returns', async () => { const { credentialId } = await connectPerson(orgA, address('connected')) expect(await status(orgA, address('connected'))).toEqual({ status: 'connected', connected: true, credentialId, - connectUrl: connectUrl(), + connectUrl: personConnectUrl(orgA, address('connected')), }) }) @@ -489,7 +497,7 @@ describe('get_connection_status', () => { status: 'needs_reconnect', connected: false, credentialId: null, - connectUrl: connectUrl(), + connectUrl: personConnectUrl(orgA, address('stale')), }) }) @@ -503,17 +511,12 @@ describe('get_connection_status', () => { .set({ status: 'revoked', revokedAt: new Date() }) .where(eq(credentialGroupEnrollment.id, revoked.enrollmentId)) - const answers = await Promise.all( - ['invited', 'failed', 'expired', 'revoked', 'nobody'].map((label) => - status(orgA, address(label)) - ) - ) - for (const answer of answers) - expect(answer).toEqual({ + for (const label of ['invited', 'failed', 'expired', 'revoked', 'nobody']) + expect(await status(orgA, address(label))).toEqual({ status: 'not_connected', connected: false, credentialId: null, - connectUrl: connectUrl(), + connectUrl: personConnectUrl(orgA, address(label)), }) }) @@ -574,7 +577,7 @@ describe('request_connection', () => { const result = await request(orgA, address('new')) expect(result).toEqual({ requested: true, - connectUrl: `http://localhost:3000/credential-groups/${orgA.publicId}/connect?provider=${DRIVE_ID}`, + connectUrl: personConnectUrl(orgA, address('new')), }) expect(await enrollmentsFor(orgA, address('new'))).toEqual([ expect.objectContaining({ @@ -596,20 +599,60 @@ describe('request_connection', () => { const fresh = await request(orgA, address('fresh-request')) await enroll(orgA, address('known-request')) const known = await request(orgA, address('known-request')) - expect(revoked).toEqual(fresh) - expect(known).toEqual(fresh) + expect(revoked).toEqual({ + requested: true, + connectUrl: personConnectUrl(orgA, address('revoked-request')), + }) + expect(fresh).toEqual({ + requested: true, + connectUrl: personConnectUrl(orgA, address('fresh-request')), + }) + expect(known).toEqual({ + requested: true, + connectUrl: personConnectUrl(orgA, address('known-request')), + }) const [after] = await enrollmentsFor(orgA, address('revoked-request')) expect(after).toEqual(before) expect(after?.id).toBe(revokedId) }) - it('leaves an admin invitation attributed to the admin', async () => { - await enroll(orgA, address('admin-invited')) + it('leaves an admin invitation attributed to the admin, renewing only its wait', async () => { + await enroll(orgA, address('admin-invited'), { + invitationExpiresAt: new Date(Date.now() - DAY_MS), + }) const [before] = await enrollmentsFor(orgA, address('admin-invited')) await request(orgA, address('admin-invited')) const [after] = await enrollmentsFor(orgA, address('admin-invited')) - expect(after).toEqual(before) + expect(after).toEqual({ + ...before, + invitationExpiresAt: expect.any(Date), + updatedAt: expect.any(Date), + }) expect(after).toMatchObject({ createdBy: ownerId, requestedByWorkflowId: null }) + expect(after?.invitationExpiresAt.getTime()).toBeGreaterThan(Date.now() + 6 * DAY_MS) + }) + + it('renews a request nobody answered, but never a bound or revoked enrollment', async () => { + await request(orgA, address('renewed')) + await enroll(orgA, address('renew-revoked'), { status: 'revoked', revokedAt: new Date() }) + const past = new Date(Date.now() - DAY_MS) + await db + .update(credentialGroupEnrollment) + .set({ invitationExpiresAt: past }) + .where( + and( + eq(credentialGroupEnrollment.credentialGroupId, orgA.groupId), + inArray(credentialGroupEnrollment.email, [address('renewed'), address('renew-revoked')]) + ) + ) + + await request(orgA, address('renewed')) + await request(orgA, address('renew-revoked')) + + const [renewed] = await enrollmentsFor(orgA, address('renewed')) + const [revoked] = await enrollmentsFor(orgA, address('renew-revoked')) + expect(renewed?.invitationExpiresAt.getTime()).toBeGreaterThan(Date.now() + 6 * DAY_MS) + expect(revoked?.invitationExpiresAt).toEqual(past) }) it('creates a single enrollment when the same person is requested concurrently', async () => { @@ -662,12 +705,21 @@ describe('request_connection input and daily limit', () => { ).toEqual([]) }) - it('counts requests for an address that already has an enrollment', async () => { + it('counts distinct addresses: asking again for one already asked today is free and unlogged', async () => { await enroll(orgC, address('limit-existing')) + for (let attempt = 0; attempt < 3; attempt++) await request(orgC, address('limit-existing')) + await request(orgC, address('limit-new')) await request(orgC, address('limit-existing')) - await request(orgC, address('limit-existing')) - expect((await refusal(request(orgC, address('limit-new')))).code).toBe('conflict') - expect(await enrollmentsFor(orgC, address('limit-new'))).toEqual([]) + + expect((await refusal(request(orgC, address('limit-third')))).code).toBe('conflict') + expect(await enrollmentsFor(orgC, address('limit-third'))).toEqual([]) + const logged = await db + .select({ email: credentialGroupConnectionRequest.email }) + .from(credentialGroupConnectionRequest) + .where(eq(credentialGroupConnectionRequest.credentialGroupId, orgC.groupId)) + expect(logged.map((row) => row.email).sort()).toEqual( + [address('limit-existing'), address('limit-new')].sort() + ) }) it('counts only requests from the last day toward the limit', async () => { @@ -766,6 +818,40 @@ describe('connection request emails', () => { expect(await emailEvents(requested.id)).toHaveLength(2) }) + it("reminds a workflow's request when an admin sends a reminder, keeping it the workflow's", async () => { + const email = address('admin-reminded') + await request(orgA, email) + const [requested] = await enrollmentsFor(orgA, email) + if (!requested) throw new Error('Request created no enrollment') + await db + .update(credentialGroupEnrollment) + .set({ invitationExpiresAt: new Date(Date.now() - DAY_MS) }) + .where(eq(credentialGroupEnrollment.id, requested.id)) + + await resendOrganizationAccountInvitation.execute({ + principal: createSessionPrincipal({ userId: orgA.adminId, sessionId: generateId() }), + input: { organizationId: orgA.organizationId, enrollmentId: requested.id }, + }) + + const events = await emailEvents(requested.id) + expect(events).toHaveLength(2) + expect(events).toEqual(expect.arrayContaining([{ reminder: null }, { reminder: true }])) + const [after] = await enrollmentsFor(orgA, email) + expect(after).toMatchObject({ + requestedByWorkflowId: workflowId, + requestedProviderId: DRIVE_ID, + createdBy: null, + invitedAt: requested.invitedAt, + invitationTokenHash: requested.invitationTokenHash, + }) + expect(after?.invitationExpiresAt.getTime()).toBeGreaterThan(Date.now() + 6 * DAY_MS) + const links = await db + .select({ id: credentialGroupEnrollmentLink.id }) + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, requested.id)) + expect(links).toEqual([]) + }) + it('sends one reminder when a workflow asks again several times at once', async () => { const email = address('reminded-at-once') await request(orgA, email) @@ -856,13 +942,11 @@ describe('connection request email delivery', () => { CONNECTION_REQUEST_EMAIL_EVENT, { enrollmentId, - workspaceId: orgA.workspaceId, workflowId: namedWorkflowId, providerName: DRIVE.label, connectUrl: buildCredentialGroupConnectUrl({ publicId: orgA.publicId, provider: DRIVE_ID }), ...(reminder ? { reminder } : {}), - }, - { maxAttempts: 3 } + } ) await processOutboxEventById(eventId, credentialGroupConnectionRequestOutboxHandlers) } @@ -903,14 +987,16 @@ describe('connection request email delivery', () => { ]) }) - it('records a failed delivery as Email failed, and a later successful one clears it', async () => { + it('records a failed delivery as Email failed and not emailed, and a later success as emailed', async () => { const { enrollmentId } = await requestedEnrollment('bounced-request') + expect((await enrollmentRow(enrollmentId)).sentAt).toBeNull() mail.failWith = 'Mailbox unavailable' await deliver(enrollmentId) expect(await enrollmentRow(enrollmentId)).toMatchObject({ status: 'delivery_failed', lastDeliveryError: 'Mailbox unavailable', + sentAt: null, }) mail.failWith = null @@ -918,6 +1004,7 @@ describe('connection request email delivery', () => { expect(await enrollmentRow(enrollmentId)).toMatchObject({ status: 'invited', lastDeliveryError: null, + sentAt: expect.any(Date), }) }) @@ -964,9 +1051,7 @@ describe('a requested enrollment on the connect page', () => { sql`${outboxEvent.payload} ->> 'enrollmentId' = ${enrollment.id}` ) ) - expect(event?.payload).toMatchObject({ - connectUrl: buildCredentialGroupConnectUrl({ publicId: orgA.publicId, provider: DRIVE_ID }), - }) + expect(event?.payload).toMatchObject({ connectUrl: personConnectUrl(orgA, email) }) const userId = generateId() people.set(email, userId) @@ -980,11 +1065,15 @@ describe('a requested enrollment on the connect page', () => { }) const target = await startCredentialGroupConnect.execute({ principal: createSessionPrincipal({ userId }), - input: { publicId: orgA.publicId, provider: DRIVE_ID }, + input: { + publicId: orgA.publicId, + provider: DRIVE_ID, + requestHandle: connectRequestHandle(orgA.groupId, email), + }, }) - expect(target).toMatchObject({ kind: 'ready', optionId: DRIVE.id }) - if (target.kind !== 'ready') return + expect(target).toMatchObject({ kind: 'started', optionId: DRIVE.id }) + if (target.kind !== 'started') return await expect( authenticatePublicCredentialGroupEnrollment(target.invitationToken) ).resolves.toMatchObject({ enrollmentId: enrollment.id, userId }) @@ -1064,10 +1153,12 @@ describe('admin connection request settings', () => { it('lets an admin turn requests off after a selected workspace left the Access tab', async () => { const saved = await save(orgC, 0, selected(orgC)) + expect((await read(orgC)).inEffect).toBe(true) await setAccess(orgC, [orgC.outsideWorkspaceId]) const state = await read(orgC) expect(state.policy?.workspaces).toEqual({ mode: 'selected', workspaceIds: [] }) + expect(state.inEffect).toBe(false) const off = await save(orgC, saved.revision, { ...selected(orgC), enabled: false }) expect(off.policy).toMatchObject({ enabled: false, diff --git a/apps/sim/lib/credential-groups/application/connection-requests.ts b/apps/sim/lib/credential-groups/application/connection-requests.ts index c9862f08edc..40a2437c62f 100644 --- a/apps/sim/lib/credential-groups/application/connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/connection-requests.ts @@ -2,8 +2,6 @@ import { AuditAction, AuditResourceType } from '@sim/audit' import { isValidEmailSyntax, normalizeEmail } from '@sim/utils/string' import { type AuthorizingUseCase, defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' import { OrchestrationError } from '@/lib/core/orchestration/types' -import { processOutboxEventById } from '@/lib/core/outbox/service' -import { runDetached } from '@/lib/core/utils/background' import { credentialGroupDelegationPolicy, requireCredentialGroupWorkflowActor, @@ -19,12 +17,15 @@ import { type OrganizationAccountAccessPolicy, organizationAccountPolicyAllowsWorkspace, } from '@/lib/credential-groups/application/workspace-access-policy' +import { connectRequestHandle } from '@/lib/credential-groups/connect-request-handle' +import type { ConnectReturnDestination } from '@/lib/credential-groups/connect-return' import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' import { CONNECTION_REQUESTS_OFF, connectionRequestRefusal, } from '@/lib/credential-groups/connection-request-policy' import { + deliverConnectionRequestEmailSoon, loadConnectionRequestPolicy, loadOrganizationAccountConnectionStatus, type OrganizationAccountConnectionStatus, @@ -40,11 +41,8 @@ export interface OrganizationAccountConnectionInput { email: string /** Credential provider ID, as Find Organization Account takes it. */ providerId: string - /** - * Where the connect page offers to send the person once connected. Only `slack`, the Slack - * app's generic deep link, can be asked for; a workflow never supplies a URL. - */ - returnTo?: 'slack' + /** Where the connect page offers to send the person once connected; never a URL. */ + returnTo?: ConnectReturnDestination } export interface OrganizationAccountConnectionStatusResult { @@ -81,16 +79,6 @@ function requireRequestableEmail(value: string): string { return email } -/** Sends the enqueued email now, off the request path; the outbox worker retries it otherwise. */ -function deliverSoon(eventId: string) { - runDetached('credential-group-connection-request-email', async () => { - const { credentialGroupConnectionRequestOutboxHandlers } = await import( - '@/lib/credential-groups/connection-request-email' - ) - await processOutboxEventById(eventId, credentialGroupConnectionRequestOutboxHandlers) - }) -} - /** * Resolves the group options collecting this provider that the executing workspace may use, * with the same errors List Organization Accounts gives for an inactive or disallowed provider. @@ -130,6 +118,20 @@ function requireAllowedProviderOptions( return { options: allowed, label: first.label } } +/** The connect URL for one person: its `for` handle tells the page whom it was made for. */ +function personConnectUrl( + context: OrganizationAccountsWorkspaceContext, + email: string, + input: OrganizationAccountConnectionInput +): string { + return buildCredentialGroupConnectUrl({ + publicId: context.publicId, + provider: input.providerId, + returnTo: input.returnTo, + requestHandle: connectRequestHandle(context.credentialGroupId, email), + }) +} + function requireWorkspacePolicy(context: OrganizationAccountsWorkspaceContext) { const policy = context.workspaceAccessPolicy if (!policy) throw new Error('Connection lookups require workspace policy authorization') @@ -163,11 +165,7 @@ export const getOrganizationAccountConnectionStatus = defineAuthorizedWorkspaceU status, connected: status === 'connected', credentialId, - connectUrl: buildCredentialGroupConnectUrl({ - publicId: context.publicId, - provider: input.providerId, - returnKey: input.returnTo, - }), + connectUrl: personConnectUrl(context, email, input), } }, }) @@ -205,22 +203,19 @@ const recordOrganizationAccountConnectionRequest = defineAuthorizedWorkspaceUseC if (refusal) throw new OrchestrationError('forbidden', refusal) const { label } = requireAllowedProviderOptions(context, accessPolicy, input.providerId) - const connectUrl = buildCredentialGroupConnectUrl({ - publicId: context.publicId, - provider: input.providerId, - returnKey: input.returnTo, - }) + const connectUrl = personConnectUrl(context, email, input) const recorded = await recordCredentialGroupConnectionRequest({ credentialGroupId: context.credentialGroupId, email, workspaceId: context.workspaceId, workflowId, + providerId: input.providerId, providerName: label, connectUrl, dailyLimit: policy.dailyLimit, sendEmail: policy.sendEmail, }) - if (recorded.emailEventId) deliverSoon(recorded.emailEventId) + if (recorded.emailEventId) deliverConnectionRequestEmailSoon(recorded.emailEventId) return { requested: true, connectUrl, diff --git a/apps/sim/lib/credential-groups/application/organization-account-management.ts b/apps/sim/lib/credential-groups/application/organization-account-management.ts index cb3ea051659..bbe3816f627 100644 --- a/apps/sim/lib/credential-groups/application/organization-account-management.ts +++ b/apps/sim/lib/credential-groups/application/organization-account-management.ts @@ -3,6 +3,12 @@ import { defineOrganizationOperation } from '@/lib/core/application/organization import { OrchestrationError } from '@/lib/core/orchestration/types' import { defineOrganizationAccountsUseCase } from '@/lib/credential-groups/application/organization-accounts' import { validateCredentialGroupInvitationEmails } from '@/lib/credential-groups/application/validation' +import { connectRequestHandle } from '@/lib/credential-groups/connect-request-handle' +import { buildCredentialGroupConnectUrl } from '@/lib/credential-groups/connect-url' +import { + deliverConnectionRequestEmailSoon, + remindWorkflowConnectionRequest, +} from '@/lib/credential-groups/connection-requests' import { loadScopedAccountsCredentialListContext } from '@/lib/credential-groups/credentials' import { inviteCredentialGroupEnrollments, @@ -10,6 +16,7 @@ import { loadCredentialGroupInviterIdentity, resendCredentialGroupEnrollment, revokeCredentialGroupEnrollment, + toCredentialGroupEnrollment, } from '@/lib/credential-groups/enrollments' import { getCredentialGroupIndexingConnector } from '@/lib/credential-groups/indexing' import type { ManagedMcpConnectorId } from '@/lib/credential-groups/managed-mcp-connectors' @@ -19,7 +26,10 @@ import { deleteManagedMcpConnector, } from '@/lib/credential-groups/managed-mcp-service' import { clearCredentialGroupMcpOAuthAttempts } from '@/lib/credential-groups/mcp-oauth-state' -import { isCredentialGroupProvider } from '@/lib/credential-groups/providers' +import { + getCredentialGroupProviderId, + isCredentialGroupProvider, +} from '@/lib/credential-groups/providers' import { evictMcpServerConnections } from '@/lib/mcp/connection-pool' export const organizationAccountManagementOperations = { @@ -187,6 +197,11 @@ export const inviteOrganizationAccountPeople = defineOrganizationAccountsUseCase projectAudit: groupAudit, }) +/** + * "Send reminder" on a person. A workflow's open request is reminded as the workflow's request + * for the integration it asked for, keeping its attribution; anyone else gets the admin's + * invitation again. + */ export const resendOrganizationAccountInvitation = defineOrganizationAccountsUseCase({ operation: organizationAccountManagementOperations.resend, async execute({ @@ -194,6 +209,31 @@ export const resendOrganizationAccountInvitation = defineOrganizationAccountsUse context, }: OrganizationExecution) { const { scope, group } = await requireGroup(context.organizationId) + const reminded = await remindWorkflowConnectionRequest({ + credentialGroupId: group.credentialGroupId, + enrollmentId: input.enrollmentId, + providerNameFor: (providerId) => + group.options.find( + (option) => + option.status === 'active' && + isCredentialGroupProvider(option.provider) && + getCredentialGroupProviderId(option.provider) === providerId + )?.label ?? null, + connectUrlFor: ({ providerId, email }) => + buildCredentialGroupConnectUrl({ + publicId: group.publicId, + provider: providerId, + requestHandle: connectRequestHandle(group.credentialGroupId, email), + }), + }) + if (reminded) { + deliverConnectionRequestEmailSoon(reminded.emailEventId) + return { + credentialGroupEnrollment: toCredentialGroupEnrollment(reminded.enrollment), + credentialGroupId: group.credentialGroupId, + description: 'Reminded a person of a workflow connection request', + } + } const enrollment = await resendCredentialGroupEnrollment( scope, group.credentialGroupId, diff --git a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts index 4459429e456..c579787f97c 100644 --- a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts @@ -8,6 +8,7 @@ import { defineOrganizationAccountsUseCase } from '@/lib/credential-groups/appli import { listOrganizationAccountWorkspaceIds, organizationAccountAccessPolicyCodec, + organizationAccountPolicyAllowsWorkspace, } from '@/lib/credential-groups/application/workspace-access-policy' import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' import { @@ -69,20 +70,57 @@ async function loadConnectionRequestState(organizationId: string) { ) .orderBy(asc(workspace.name), asc(workspace.id)) : [] - const providers = group.options.flatMap((option) => + const activeProviders = group.options.flatMap((option) => option.status === 'active' && isCredentialGroupProvider(option.provider) - ? [{ id: getCredentialGroupProviderId(option.provider), label: option.label }] + ? [{ id: getCredentialGroupProviderId(option.provider), label: option.label, option }] : [] ) return { group, workspaces, - providers, + providers: activeProviders.map(({ id, label }) => ({ id, label })), workspaceIds: new Set(workspaces.map((entry) => entry.id)), - providerIds: new Set(providers.map((provider) => provider.id)), + providerIds: new Set(activeProviders.map((provider) => provider.id)), + /** Whether the Access tab lets a workspace use an integration, by provider ID. */ + accessAllows: (workspaceId: string, providerId: string) => + activeProviders.some( + ({ id, option }) => + id === providerId && + isCredentialGroupProvider(option.provider) && + organizationAccountPolicyAllowsWorkspace( + access.document, + workspaceId, + `oauth:${option.provider}` + ) + ), } } +/** The workspaces a policy lets request: its selection, or every workspace on the Access tab. */ +function policyWorkspaceIds( + policy: ConnectionRequestPolicy, + workspaceIds: ReadonlySet +): string[] { + return policy.workspaces.mode === 'all' ? [...workspaceIds] : policy.workspaces.workspaceIds +} + +/** + * Whether a request could pass the policy at all: it is on, names a domain, and some chosen + * workspace may use some chosen integration on the Access tab. + */ +function isConnectionRequestPolicyInEffect( + policy: ConnectionRequestPolicy | null, + state: Pick +): boolean { + if (!policy?.enabled || !policy.emailDomains.length) return false + const workspaceIds = policyWorkspaceIds(policy, state.workspaceIds) + return policy.providers.some((providerId) => + workspaceIds.some((workspaceId) => state.accessAllows(workspaceId, providerId)) + ) +} + +type ConnectionRequestState = Awaited> + /** * Drops workspaces no longer on the Access tab and integrations no longer active. Requests from * those are refused anyway; pruning keeps the admin from seeing or re-saving stale choices. @@ -108,15 +146,17 @@ function pruneConnectionRequestPolicy( export const getOrganizationConnectionRequestPolicy = defineOrganizationAccountsUseCase({ operation: organizationConnectionRequestOperations.read, async execute({ context }) { - const { group, workspaces, providers, workspaceIds, providerIds } = - await loadConnectionRequestState(context.organizationId) - const stored = await loadConnectionRequestPolicy(group.credentialGroupId) + const state = await loadConnectionRequestState(context.organizationId) + const stored = await loadConnectionRequestPolicy(state.group.credentialGroupId) + const policy = + stored.policy && + pruneConnectionRequestPolicy(stored.policy, state.workspaceIds, state.providerIds) return { revision: stored.revision, - policy: - stored.policy && pruneConnectionRequestPolicy(stored.policy, workspaceIds, providerIds), - workspaces, - providers, + policy, + inEffect: isConnectionRequestPolicyInEffect(policy, state), + workspaces: state.workspaces, + providers: state.providers, } }, }) @@ -136,9 +176,8 @@ export const updateOrganizationConnectionRequestPolicy = defineOrganizationAccou input: { organizationId: string; revision: number; policy: ConnectionRequestPolicy } context: OrganizationMembershipContext }) { - const { group, workspaceIds, providerIds } = await loadConnectionRequestState( - context.organizationId - ) + const state = await loadConnectionRequestState(context.organizationId) + const { group, workspaceIds, providerIds } = state const next = input.policy if (next.enabled) { if (next.providers.some((provider) => !providerIds.has(provider))) @@ -154,6 +193,16 @@ export const updateOrganizationConnectionRequestPolicy = defineOrganizationAccou 'validation', 'Every workspace must already be allowed on the Access tab' ) + const chosenWorkspaceIds = policyWorkspaceIds(next, workspaceIds) + const unusable = next.providers.find( + (providerId) => + !chosenWorkspaceIds.some((workspaceId) => state.accessAllows(workspaceId, providerId)) + ) + if (unusable) + throw new OrchestrationError( + 'validation', + `${state.providers.find((provider) => provider.id === unusable)?.label ?? unusable} is not allowed in any chosen workspace on the Access tab` + ) } const policy = next.enabled ? next diff --git a/apps/sim/lib/credential-groups/connection-request-email.ts b/apps/sim/lib/credential-groups/connection-request-email.ts index c1bed4c7da9..ac4eed53a28 100644 --- a/apps/sim/lib/credential-groups/connection-request-email.ts +++ b/apps/sim/lib/credential-groups/connection-request-email.ts @@ -1,5 +1,11 @@ import { db } from '@sim/db' -import { credentialGroup, credentialGroupEnrollment, organization, workflow } from '@sim/db/schema' +import { + credentialGroup, + credentialGroupEnrollment, + organization, + workflow, + workspace, +} from '@sim/db/schema' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { isRecordLike } from '@sim/utils/object' @@ -24,7 +30,6 @@ function parsePayload(payload: unknown): ConnectionRequestEmailPayload { if ( !isRecordLike(payload) || typeof payload.enrollmentId !== 'string' || - typeof payload.workspaceId !== 'string' || typeof payload.workflowId !== 'string' || typeof payload.providerName !== 'string' || typeof payload.connectUrl !== 'string' @@ -32,7 +37,6 @@ function parsePayload(payload: unknown): ConnectionRequestEmailPayload { throw new Error('Invalid connection request email payload') return { enrollmentId: payload.enrollmentId, - workspaceId: payload.workspaceId, workflowId: payload.workflowId, providerName: payload.providerName, connectUrl: payload.connectUrl, @@ -77,37 +81,31 @@ function stillRequested(enrollmentId: string, invitedAt: Date): SQL | undefined */ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { const payload = parsePayload(rawPayload) - const [[target], [requester]] = await Promise.all([ - db - .select({ - email: credentialGroupEnrollment.email, - invitedAt: credentialGroupEnrollment.invitedAt, - organizationName: organization.name, - credentialGroupName: credentialGroup.name, - }) - .from(credentialGroupEnrollment) - .innerJoin( - credentialGroup, - eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId) - ) - .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) - .where(pendingWorkflowRequestCondition(payload.enrollmentId)) - .limit(1), - db - .select({ name: workflow.name }) - .from(workflow) - .where( - and(eq(workflow.id, payload.workflowId), eq(workflow.workspaceId, payload.workspaceId)) - ) - .limit(1), - ]) + const [target] = await db + .select({ + email: credentialGroupEnrollment.email, + invitedAt: credentialGroupEnrollment.invitedAt, + organizationId: organization.id, + organizationName: organization.name, + }) + .from(credentialGroupEnrollment) + .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) + .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) + .where(pendingWorkflowRequestCondition(payload.enrollmentId)) + .limit(1) if (!target) return + const [requester] = await db + .select({ name: workflow.name }) + .from(workflow) + .innerJoin(workspace, eq(workspace.id, workflow.workspaceId)) + .where( + and(eq(workflow.id, payload.workflowId), eq(workspace.organizationId, target.organizationId)) + ) + .limit(1) const html = await renderCredentialGroupInvitationEmail({ recipientEmail: target.email, - workspaceName: target.organizationName, - ownerKind: 'organization', - credentialGroupName: target.credentialGroupName, + owner: { kind: 'organization', name: target.organizationName }, invitationLink: payload.connectUrl, workflowRequest: { workflowName: connectionRequestWorkflowName(requester?.name), @@ -142,7 +140,12 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { try { await db .update(credentialGroupEnrollment) - .set({ status: 'invited', lastDeliveryError: null, updatedAt: new Date() }) + .set({ + status: 'invited', + sentAt: new Date(), + lastDeliveryError: null, + updatedAt: new Date(), + }) .where(stillRequested(payload.enrollmentId, target.invitedAt)) } catch (error) { logger.error('Failed to record a sent connection request email', { diff --git a/apps/sim/lib/credential-groups/connection-request-event.ts b/apps/sim/lib/credential-groups/connection-request-event.ts index 701ad2e97c3..6e934c4ed69 100644 --- a/apps/sim/lib/credential-groups/connection-request-event.ts +++ b/apps/sim/lib/credential-groups/connection-request-event.ts @@ -3,8 +3,10 @@ export const CONNECTION_REQUEST_EMAIL_EVENT = 'credential-group.connection-reque export interface ConnectionRequestEmailPayload { enrollmentId: string - workspaceId: string - /** The requesting workflow; the email names it, read from the workflow record when sent. */ + /** + * The requesting workflow; the email names it, read when sent from the workflow record in the + * group's organization. + */ workflowId: string providerName: string connectUrl: string diff --git a/apps/sim/lib/credential-groups/connection-request-policy.ts b/apps/sim/lib/credential-groups/connection-request-policy.ts index 3a422a6b344..9bda526a0f7 100644 --- a/apps/sim/lib/credential-groups/connection-request-policy.ts +++ b/apps/sim/lib/credential-groups/connection-request-policy.ts @@ -11,12 +11,26 @@ export const CONNECTION_REQUEST_PROVIDER_LIMIT = 100 * so the admin settings warn when one is entered. */ export const FREE_MAIL_DOMAINS: ReadonlySet = new Set([ + '163.com', + 'aol.com', 'gmail.com', - 'outlook.com', + 'gmx.com', + 'gmx.de', + 'googlemail.com', 'hotmail.com', - 'yahoo.com', 'icloud.com', + 'live.com', + 'mail.com', + 'me.com', + 'msn.com', + 'outlook.com', 'proton.me', + 'protonmail.com', + 'qq.com', + 'yahoo.com', + 'yandex.com', + 'yandex.ru', + 'zoho.com', ]) const EMAIL_DOMAIN_PATTERN = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/ diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index da70947c812..3d20b6e3d43 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -6,11 +6,23 @@ import { credentialGroupEnrollment, } from '@sim/db/schema' import { generateId } from '@sim/utils/id' -import { and, count, eq, gt, inArray, isNotNull, isNull, lt, type SQL, sql } from 'drizzle-orm' +import { + and, + countDistinct, + eq, + gt, + inArray, + isNotNull, + isNull, + lt, + type SQL, + sql, +} from 'drizzle-orm' import { OrchestrationError } from '@/lib/core/orchestration/types' -import { enqueueOutboxEvent } from '@/lib/core/outbox/service' +import { enqueueOutboxEvent, processOutboxEventById } from '@/lib/core/outbox/service' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' import { resourceScopeCondition } from '@/lib/core/resource-scope.server' +import { runDetached } from '@/lib/core/utils/background' import { CONNECTION_REQUEST_EMAIL_EVENT, type ConnectionRequestEmailPayload, @@ -23,16 +35,25 @@ import { LIVE_ENROLLMENT_STATUSES, listCredentialGroupCredentialReferences, } from '@/lib/credential-groups/credentials' -import { lockCredentialGroupInvitationTarget } from '@/lib/credential-groups/enrollments' +import { + INVITATION_TTL_MS, + isEnrollmentRevoked, +} from '@/lib/credential-groups/enrollment-lifecycle' +import { + findOrCreateUnissuedEnrollment, + lockCredentialGroupEnrollmentLifecycle, +} from '@/lib/credential-groups/enrollments' import { DAY_MS } from '@/lib/credential-groups/limits' -import { unissuedEnrollmentValues } from '@/lib/credential-groups/links' import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' +import type { DbTransaction } from '@/lib/db/types' /** Reminders a workflow-requested enrollment may receive after its first email. */ const CONNECTION_REQUEST_MAX_REMINDERS = 3 /** No reminder goes out for an enrollment requested longer ago than this. */ const CONNECTION_REQUEST_REMINDER_WINDOW_MS = 30 * DAY_MS +type EnrollmentRow = typeof credentialGroupEnrollment.$inferSelect + /** * An enrollment that is still a workflow's open request: unbound, never revoked, and not taken * over by an admin's invitation (which clears `requestedByWorkflowId`). @@ -169,7 +190,7 @@ export async function writeConnectionRequestPolicy(input: { if (!row) throw new OrchestrationError( 'conflict', - 'Connection request settings changed. Reload before saving again.' + 'Someone else changed these settings. Review and save again.' ) return row.revision } @@ -182,23 +203,52 @@ interface RecordedConnectionRequest { emailEventId: string | null } +/** Starts a new wait for an unbound enrollment nobody revoked; any other enrollment is left alone. */ +async function renewEnrollmentRequest( + tx: DbTransaction, + enrollment: EnrollmentRow, + now: Date, + requestedProviderId?: string +): Promise { + if (enrollment.userId !== null || isEnrollmentRevoked(enrollment)) return + await tx + .update(credentialGroupEnrollment) + .set({ + invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), + ...(requestedProviderId && enrollment.requestedByWorkflowId !== null + ? { requestedProviderId } + : {}), + updatedAt: now, + }) + .where(eq(credentialGroupEnrollment.id, enrollment.id)) +} + +function enqueueConnectionRequestEmail( + tx: DbTransaction, + payload: ConnectionRequestEmailPayload +): Promise { + return enqueueOutboxEvent( + tx, + CONNECTION_REQUEST_EMAIL_EVENT, + payload + ) +} + /** * Records one workflow's request that a person connect an account, in one transaction. * - * The group lock serializes the daily cap, which counts every accepted request in the request - * log, before the address is looked up: whatever the person's state, a request past the cap - * fails the same way, and a request under it is logged and counted the same way. The per-email - * invitation lock is the one admin invitations take, so a request never races an invite for the - * same address. + * The daily cap counts distinct addresses asked per group per day, under the group lock. A repeat + * request for an address already asked today is neither logged nor capped, so retries and loops + * over the same person cost nothing. The per-email invitation lock is the one admin invitations + * take, so a request never races an invite for the same address. * * Only an absent enrollment is created. An existing one keeps its status and attribution: a * revoked person stays revoked, an admin's invitation stays the admin's, and a connected person - * stays connected. The only write to an existing row is a reminder on an unbound, still-invited - * enrollment a workflow created (including one whose last email failed): when nobody asked for - * this address in the last day, the enrollment was requested within - * {@link CONNECTION_REQUEST_REMINDER_WINDOW_MS}, and it has had fewer than - * {@link CONNECTION_REQUEST_MAX_REMINDERS} reminders. That update re-checks the row's state, so a - * revocation committed meanwhile sends nothing. + * stays connected. An unbound one is renewed (it waits {@link INVITATION_TTL_MS} again). A + * reminder goes out only for an unbound, still-invited enrollment a workflow created (including one + * whose last email failed): when nobody asked for this address in the last day, the enrollment was + * requested within {@link CONNECTION_REQUEST_REMINDER_WINDOW_MS}, and it has had fewer than + * {@link CONNECTION_REQUEST_MAX_REMINDERS} reminders. * * Emails are enqueued on the outbox in the same transaction, so nothing here waits on rendering * or delivery. Log rows are only read inside the cap's one-day window and are pruned after two @@ -209,6 +259,7 @@ export async function recordCredentialGroupConnectionRequest(input: { email: string workspaceId: string workflowId: string + providerId: string providerName: string connectUrl: string dailyLimit: number @@ -217,124 +268,149 @@ export async function recordCredentialGroupConnectionRequest(input: { return db.transaction(async (tx) => { const now = new Date() const dayAgo = new Date(now.getTime() - DAY_MS) + const log = credentialGroupConnectionRequest await acquireAdvisoryXactLock( tx, 'credential_group_connection_request', `credential-group-connection-request:${input.credentialGroupId}` ) - const [recent] = await tx - .select({ total: count() }) - .from(credentialGroupConnectionRequest) + const [askedToday] = await tx + .select({ id: log.id }) + .from(log) .where( and( - eq(credentialGroupConnectionRequest.credentialGroupId, input.credentialGroupId), - gt(credentialGroupConnectionRequest.createdAt, dayAgo) + eq(log.credentialGroupId, input.credentialGroupId), + eq(log.email, input.email), + gt(log.createdAt, dayAgo) ) ) - if ((recent?.total ?? 0) >= input.dailyLimit) - throw new OrchestrationError( - 'conflict', - 'This organization reached its daily limit for workflow connection requests' - ) - - await lockCredentialGroupInvitationTarget(tx, input.credentialGroupId, input.email) - const [[askedToday], [existing]] = await Promise.all([ - tx - .select({ id: credentialGroupConnectionRequest.id }) - .from(credentialGroupConnectionRequest) - .where( - and( - eq(credentialGroupConnectionRequest.credentialGroupId, input.credentialGroupId), - eq(credentialGroupConnectionRequest.email, input.email), - gt(credentialGroupConnectionRequest.createdAt, dayAgo) - ) + .limit(1) + if (!askedToday) { + const [today] = await tx + .select({ emails: countDistinct(log.email) }) + .from(log) + .where(and(eq(log.credentialGroupId, input.credentialGroupId), gt(log.createdAt, dayAgo))) + if ((today?.emails ?? 0) >= input.dailyLimit) + throw new OrchestrationError( + 'conflict', + 'This organization reached its daily limit for workflow connection requests' ) - .limit(1), - tx - .select({ - id: credentialGroupEnrollment.id, - requestedByWorkflowId: credentialGroupEnrollment.requestedByWorkflowId, - }) - .from(credentialGroupEnrollment) - .where( - and( - eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId), - eq(credentialGroupEnrollment.email, input.email) - ) - ) - .limit(1), - ]) - await tx.insert(credentialGroupConnectionRequest).values({ - id: generateId(), + await tx.insert(log).values({ + id: generateId(), + credentialGroupId: input.credentialGroupId, + email: input.email, + workspaceId: input.workspaceId, + workflowId: input.workflowId, + createdAt: now, + }) + } + + const { row, created } = await findOrCreateUnissuedEnrollment(tx, { credentialGroupId: input.credentialGroupId, email: input.email, - workspaceId: input.workspaceId, + now, + request: { workflowId: input.workflowId, providerId: input.providerId }, + }) + const email = (reminder: boolean) => ({ + enrollmentId: row.id, workflowId: input.workflowId, - createdAt: now, + providerName: input.providerName, + connectUrl: input.connectUrl, + ...(reminder ? { reminder } : {}), }) + if (created) + return { + enrollmentId: row.id, + created, + emailEventId: input.sendEmail + ? await enqueueConnectionRequestEmail(tx, email(false)) + : null, + } - const enqueueEmail = (enrollmentId: string, reminder: boolean) => - enqueueOutboxEvent( - tx, - CONNECTION_REQUEST_EMAIL_EVENT, - { - enrollmentId, - workspaceId: input.workspaceId, - workflowId: input.workflowId, - providerName: input.providerName, - connectUrl: input.connectUrl, - ...(reminder ? { reminder } : {}), - }, - { maxAttempts: 3 } - ) - - if (existing) { - if (!input.sendEmail || askedToday || existing.requestedByWorkflowId === null) - return { enrollmentId: existing.id, created: false, emailEventId: null } - const [reminded] = await tx - .update(credentialGroupEnrollment) - .set({ - sentAt: now, - connectionRequestReminders: sql`${credentialGroupEnrollment.connectionRequestReminders} + 1`, - updatedAt: now, - }) - .where( - and( - pendingWorkflowRequestCondition(existing.id), - lt( - credentialGroupEnrollment.connectionRequestReminders, - CONNECTION_REQUEST_MAX_REMINDERS - ), - gt( - credentialGroupEnrollment.createdAt, - new Date(now.getTime() - CONNECTION_REQUEST_REMINDER_WINDOW_MS) - ) + await renewEnrollmentRequest(tx, row, now, input.providerId) + if (!input.sendEmail || askedToday || row.requestedByWorkflowId === null) + return { enrollmentId: row.id, created, emailEventId: null } + const [reminded] = await tx + .update(credentialGroupEnrollment) + .set({ + connectionRequestReminders: sql`${credentialGroupEnrollment.connectionRequestReminders} + 1`, + updatedAt: now, + }) + .where( + and( + pendingWorkflowRequestCondition(row.id), + lt( + credentialGroupEnrollment.connectionRequestReminders, + CONNECTION_REQUEST_MAX_REMINDERS + ), + gt( + credentialGroupEnrollment.createdAt, + new Date(now.getTime() - CONNECTION_REQUEST_REMINDER_WINDOW_MS) ) ) - .returning({ id: credentialGroupEnrollment.id }) - return { - enrollmentId: existing.id, - created: false, - emailEventId: reminded ? await enqueueEmail(existing.id, true) : null, - } + ) + .returning({ id: credentialGroupEnrollment.id }) + return { + enrollmentId: row.id, + created, + emailEventId: reminded ? await enqueueConnectionRequestEmail(tx, email(true)) : null, } + }) +} - const values = unissuedEnrollmentValues({ - credentialGroupId: input.credentialGroupId, - email: input.email, - now, - }) - await tx.insert(credentialGroupEnrollment).values({ - ...values, - /** No invitation link is issued: the person signs in on the connect page instead. */ - sentAt: input.sendEmail ? now : null, - requestedByWorkflowId: input.workflowId, +/** + * An admin's "Send reminder" on a workflow's open request: emails the workflow's request for the + * integration it asked for again and renews the wait, keeping the workflow's attribution (an + * admin invitation would take the enrollment over). Returns null, writing nothing, when the + * enrollment is no longer a workflow's open request or its integration is no longer active; the + * admin's reminder is then an ordinary reinvitation. + */ +export async function remindWorkflowConnectionRequest(input: { + credentialGroupId: string + enrollmentId: string + connectUrlFor: (enrollment: { providerId: string; email: string }) => string + providerNameFor: (providerId: string) => string | null +}): Promise<{ enrollment: EnrollmentRow; emailEventId: string } | null> { + return db.transaction(async (tx) => { + const now = new Date() + await lockCredentialGroupEnrollmentLifecycle(tx, input.enrollmentId) + const [row] = await tx + .select() + .from(credentialGroupEnrollment) + .where( + and( + pendingWorkflowRequestCondition(input.enrollmentId), + eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId) + ) + ) + .limit(1) + const workflowId = row?.requestedByWorkflowId + const providerId = row?.requestedProviderId + const providerName = providerId ? input.providerNameFor(providerId) : null + if (!row || !workflowId || !providerId || !providerName) return null + const [renewed] = await tx + .update(credentialGroupEnrollment) + .set({ invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), updatedAt: now }) + .where(eq(credentialGroupEnrollment.id, row.id)) + .returning() + if (!renewed) throw new Error('Credential group enrollment update returned no row') + const emailEventId = await enqueueConnectionRequestEmail(tx, { + enrollmentId: row.id, + workflowId, + providerName, + connectUrl: input.connectUrlFor({ providerId, email: row.email }), + reminder: true, }) - const enrollmentId = values.id - return { - enrollmentId, - created: true, - emailEventId: input.sendEmail ? await enqueueEmail(enrollmentId, false) : null, - } + return { enrollment: renewed, emailEventId } + }) +} + +/** Sends an enqueued request email now, off the request path; the outbox worker retries it otherwise. */ +export function deliverConnectionRequestEmailSoon(eventId: string): void { + runDetached('credential-group-connection-request-email', async () => { + const { credentialGroupConnectionRequestOutboxHandlers } = await import( + '@/lib/credential-groups/connection-request-email' + ) + await processOutboxEventById(eventId, credentialGroupConnectionRequestOutboxHandlers) }) } From 9c4f7cbcbdda9482215359ed5d7d5c72b54efb34 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 16:49:20 -0600 Subject: [PATCH 19/26] fix(credential-groups): renew a member's expired request from the connect page - an organization member who passes the self-enroll checks (membership, Integrations capability, setup) and whose own unbound request expired is offered the confirm step instead of the expired dead end; non-members still see expired - the start POST renews that enrollment (invitation_expires_at) and binds it in the same transaction that mints the focused link, instead of creating another enrollment - a request-handle mismatch is still refused first and never renews --- .../connect-target.integration.ts | 31 +++++++++++++++++- .../application/connect-target.ts | 32 ++++++++++++------- .../lib/credential-groups/connect-subject.ts | 25 ++++++++++++--- 3 files changed, 71 insertions(+), 17 deletions(-) diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index a6227869bb0..a0db905ad91 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -5,7 +5,7 @@ * option, one hour, enrollment fields untouched but the binding), a page load that would write, an * enrollment bound to someone else, an unverified session (and a deployment that cannot verify * email), a link made for another address, a revoked enrollment, an expired request (and a bound - * one, which never expires), a stranger, an organization member with no enrollment (enrolled only + * one, which never expires, and a member's own expired request, renewed by the start), a stranger, an organization member with no enrollment (enrolled only * by the start), a member the Integrations permission group or an unfinished setup keeps from * self-enrolling, a revocation landing while a member self-enrolls, a disabled group or unknown * provider (indistinguishable from an unknown public ID), a provider with two options, a focused @@ -486,6 +486,35 @@ describe('the connect URL', () => { ).toEqual({ [person.email]: true, [bound.email]: false }) }) + it('offers a member their expired request as self-enrollment and renews it when they start', async () => { + const fixture = await createOrganization() + const teammate = await createPerson() + await addMember(fixture, teammate.userId) + await invite(fixture, teammate.email) + await db + .update(credentialGroupEnrollment) + .set({ invitationExpiresAt: new Date(Date.now() - HOUR_MS) }) + .where(eq(credentialGroupEnrollment.credentialGroupId, fixture.groupId)) + const before = await enrollmentOf(fixture.groupId, teammate.email) + + await expect(openTarget(teammate.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'confirm_self_enrollment', + organizationName: 'Acme', + provider: 'google-drive', + optionId: DRIVE.id, + }) + expect(await enrollmentsIn(fixture.groupId)).toEqual([before]) + + await expect( + startTarget(teammate.userId, { publicId: fixture.publicId }) + ).resolves.toMatchObject({ kind: 'started', optionId: DRIVE.id }) + const enrollments = await enrollmentsIn(fixture.groupId) + expect(enrollments).toHaveLength(1) + expect(enrollments[0]).toMatchObject({ id: before.id, userId: teammate.userId }) + expect(enrollments[0]?.invitationExpiresAt.getTime()).toBeGreaterThan(Date.now()) + expect(await connectLinksIn(fixture.groupId)).toHaveLength(1) + }) + it('tells someone with no enrollment outside the organization they were not asked', async () => { const fixture = await createOrganization() const stranger = await createPerson() diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts index e615a2c9218..96827c31549 100644 --- a/apps/sim/lib/credential-groups/application/connect-target.ts +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -87,7 +87,8 @@ type CredentialGroupConnectRefusal = interface ConnectOffer { /** * `ready_to_connect`: the person holds an enrollment, which the POST binds. - * `confirm_self_enrollment`: an organization member with none, whom the POST enrolls. + * `confirm_self_enrollment`: an organization member with none, whom the POST enrolls, or whose + * own request expired, which the POST renews. */ kind: 'ready_to_connect' | 'confirm_self_enrollment' organizationName: string @@ -145,7 +146,8 @@ async function hasOrganizationSetup(organizationId: string, credentialGroupId: s /** * Decides what the signed-in person may do with a connect URL. Reads only. The person must * already hold an enrollment, bound to them or requested at their verified email and not yet - * expired, or be an organization member who passes the member self-enroll checks. A link made for + * expired, or be an organization member who passes the member self-enroll checks; such a member's + * expired request is offered as self-enrollment and renewed, while anyone else sees `expired`. A link made for * another address (its `for` handle does not match the viewer) is refused before anything about * the viewer's own enrollment is said, and never offers self-enrollment. */ @@ -186,11 +188,12 @@ async function decideConnectTarget( } if (enrollment && isEnrollmentRevoked(enrollment)) return { kind: 'revoked', organizationName, provider } - if (enrollment && isEnrollmentRequestExpired(enrollment)) - return { kind: 'expired', organizationName, provider } - if (!enrollment) { + const expired = enrollment !== null && isEnrollmentRequestExpired(enrollment) + if (expired || !enrollment) { if (!group.organizationId || !(await canSelfEnroll(principal, group.organizationId, group.id))) - return { kind: 'not_invited', organizationName, provider } + return expired + ? { kind: 'expired', organizationName, provider } + : { kind: 'not_invited', organizationName, provider } } else if ( !enrollment.userId && group.organizationId && @@ -206,14 +209,16 @@ async function decideConnectTarget( options: options.map(({ id, label }) => ({ id, label })), } return { - kind: enrollment ? 'ready_to_connect' : 'confirm_self_enrollment', + kind: enrollment && !expired ? 'ready_to_connect' : 'confirm_self_enrollment', organizationName, provider, optionId: option.id, credentialGroupId: group.id, - target: enrollment - ? { kind: 'enrollment', enrollmentId: enrollment.id } - : { kind: 'self_enrollment' }, + target: !enrollment + ? { kind: 'self_enrollment' } + : expired + ? { kind: 'renew_expired_enrollment', enrollmentId: enrollment.id } + : { kind: 'enrollment', enrollmentId: enrollment.id }, } } @@ -251,6 +256,7 @@ interface StartedConnect { enrollmentId: string created: boolean bound: boolean + renewed: boolean } const recordCredentialGroupConnectStart = defineAuthorizedCredentialUserUseCase({ @@ -286,6 +292,7 @@ const recordCredentialGroupConnectStart = defineAuthorizedCredentialUserUseCase( enrollmentId: issued.enrollmentId, created: issued.created, bound: issued.bound, + renewed: issued.renewed, } }, projectAudit: ({ result }) => @@ -297,12 +304,15 @@ const recordCredentialGroupConnectStart = defineAuthorizedCredentialUserUseCase( resourceId: result.credentialGroupId, description: result.created ? 'Enrolled themselves to connect an account' - : 'Accepted a request to connect an account', + : result.renewed + ? 'Renewed an expired request to connect an account' + : 'Accepted a request to connect an account', metadata: { enrollmentId: result.enrollmentId, optionId: result.optionId, created: result.created, bound: result.bound, + renewed: result.renewed, }, } : [], diff --git a/apps/sim/lib/credential-groups/connect-subject.ts b/apps/sim/lib/credential-groups/connect-subject.ts index 063d156d6c1..5d4295c87d1 100644 --- a/apps/sim/lib/credential-groups/connect-subject.ts +++ b/apps/sim/lib/credential-groups/connect-subject.ts @@ -10,6 +10,7 @@ import { import { normalizeEmail } from '@sim/utils/string' import { and, eq, or } from 'drizzle-orm' import { + INVITATION_TTL_MS, isEnrollmentRequestExpired, isEnrollmentRevoked, } from '@/lib/credential-groups/enrollment-lifecycle' @@ -109,6 +110,11 @@ export async function loadCredentialGroupConnectSubject(input: { export type CredentialGroupConnectLinkTarget = /** An enrollment the person already holds: bound to them, or requested at their email. */ | { kind: 'enrollment'; enrollmentId: string } + /** + * An organization member's own request that expired unanswered: as a member may enroll + * themselves, the link renews it instead of creating another. + */ + | { kind: 'renew_expired_enrollment'; enrollmentId: string } /** An organization member with no enrollment, who asked to connect. */ | { kind: 'self_enrollment' } @@ -121,13 +127,15 @@ type IssuedCredentialGroupConnectLink = created: boolean /** The person was bound to the enrollment by this link. */ bound: boolean + /** An expired request was renewed for this link. */ + renewed: boolean } | { issued: false; reason: 'revoked' | 'expired' | 'unavailable' } /** * Mints a short-lived link focused on one account option and, in the same transaction, creates * the member's enrollment when they enroll themselves and binds the signed-in person to an - * unbound one. The enrollment's lifecycle lock serializes it with revocation, so a revocation that + * unbound one, renewing an expired request a member may answer. The enrollment's lifecycle lock serializes it with revocation, so a revocation that * commits first is reported as `revoked` and a later one kills the new link. Inserts a link row * only: an existing enrollment's issuer, timestamps, status and legacy token column stay as they * are. @@ -153,7 +161,7 @@ export async function issueCredentialGroupConnectLink(input: { return { issued: false, reason: 'unavailable' } const viewerEmail = normalizeEmail(viewer.email) - let enrollmentId = input.target.kind === 'enrollment' ? input.target.enrollmentId : null + let enrollmentId = input.target.kind === 'self_enrollment' ? null : input.target.enrollmentId let created = false if (enrollmentId === null) { const enrollment = await findOrCreateUnissuedEnrollment(tx, { @@ -190,7 +198,10 @@ export async function issueCredentialGroupConnectLink(input: { .limit(1) if (!current) return { issued: false, reason: 'unavailable' } if (isEnrollmentRevoked(current)) return { issued: false, reason: 'revoked' } - if (isEnrollmentRequestExpired(current, now)) return { issued: false, reason: 'expired' } + const renewed = + input.target.kind === 'renew_expired_enrollment' && isEnrollmentRequestExpired(current, now) + if (!renewed && isEnrollmentRequestExpired(current, now)) + return { issued: false, reason: 'expired' } if (current.groupStatus !== 'active') return { issued: false, reason: 'unavailable' } if (current.userId ? current.userId !== input.userId : current.email !== viewerEmail) return { issued: false, reason: 'unavailable' } @@ -199,7 +210,11 @@ export async function issueCredentialGroupConnectLink(input: { if (bound) await tx .update(credentialGroupEnrollment) - .set({ userId: input.userId, updatedAt: now }) + .set({ + userId: input.userId, + ...(renewed ? { invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS) } : {}), + updatedAt: now, + }) .where(eq(credentialGroupEnrollment.id, enrollmentId)) const { token } = await insertEnrollmentLink(tx, { enrollmentId, @@ -207,6 +222,6 @@ export async function issueCredentialGroupConnectLink(input: { optionId: input.optionId, now, }) - return { issued: true, token, enrollmentId, created, bound } + return { issued: true, token, enrollmentId, created, bound, renewed } }) } From a86fb2bef5531e0066d3feab41df368e8fc41335 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 17:02:34 -0600 Subject: [PATCH 20/26] refactor(credential-groups): make the link table the only invitation token authority The 0490 backfill still turns each existing invitation_token_hash into one emailed link. After that, nothing reads or writes the enrollment column: - drop the legacy-column branch of liveEnrollmentLinkCondition, the token lookup fallback, and adoptLegacyInvitationLink - stop mirroring the newest emailed link into the column; a bound person's emailed links simply do not expire (self and connect links always do) - drop the unissued: placeholder helpers and the cleanup job's column check - revoked is status === 'revoked' alone; a reinvitation no longer re-revokes links a revocation already revoked - 0490 makes invitation_token_hash nullable; schema.ts marks it unused and scheduled for removal by its own contract migration - remove tests of old-app behavior; fixtures seed link rows instead of the column; README states current behavior only --- ...anup-credential-group-links.integration.ts | 35 ++--- .../cleanup-credential-group-links.ts | 9 +- .../tool-permissions.integration.ts | 13 +- apps/sim/lib/credential-groups/README.md | 11 +- .../connect-target.integration.ts | 1 - .../enrollment-link-backfill.integration.ts | 57 ++++--- .../enrollment-link-outcome.integration.ts | 69 +++++---- .../enrollment-links.integration.ts | 143 +++++------------- .../hubspot-mcp.integration.ts | 10 +- .../multiple-provider-accounts.integration.ts | 24 ++- ...orkflow-connection-requests.integration.ts | 21 ++- .../personal-organization-accounts.test.ts | 4 +- .../personal-organization-accounts.ts | 5 - .../lib/credential-groups/connect-subject.ts | 12 +- .../credential-groups/enrollment-lifecycle.ts | 31 +--- .../lib/credential-groups/enrollments.test.ts | 17 +-- apps/sim/lib/credential-groups/enrollments.ts | 21 +-- apps/sim/lib/credential-groups/links.ts | 117 +++----------- apps/sim/lib/credential-groups/oauth.test.ts | 2 +- .../credentials/managed-oauth.integration.ts | 9 +- .../0490_credential_group_connect.sql | 31 ++-- .../db/migrations/meta/0490_snapshot.json | 2 +- packages/db/schema.ts | 10 +- 23 files changed, 235 insertions(+), 419 deletions(-) diff --git a/apps/sim/background/cleanup-credential-group-links.integration.ts b/apps/sim/background/cleanup-credential-group-links.integration.ts index 62fa670e1be..b0f7ed8e048 100644 --- a/apps/sim/background/cleanup-credential-group-links.integration.ts +++ b/apps/sim/background/cleanup-credential-group-links.integration.ts @@ -1,11 +1,9 @@ /** * Retention of the connect flow's short-lived rows against real PostgreSQL. Failure modes: a * request log row the daily cap still reads being deleted; an expired session link a day past - * expiry being kept; an emailed link, which outlives its expiry once bound, being deleted; a - * session link the enrollment's legacy invitation column still names being deleted, which would - * let its token resolve through the column with no expiry; a row exactly at a cutoff being - * deleted early; a row another run has locked stalling this run; one run draining an unbounded - * backlog instead of capping its batches. + * expiry being kept; an emailed link, which outlives its expiry once bound, being deleted; a row + * exactly at a cutoff being deleted early; a row another run has locked stalling this run; one + * run draining an unbounded backlog instead of capping its batches. */ import { db, dbFor } from '@sim/db' import { @@ -26,7 +24,7 @@ const HOUR_MS = 60 * 60 * 1000 const DAY_MS = 24 * HOUR_MS const organizationIds: string[] = [] -async function createEnrollment(legacyTokenHash: string) { +async function createEnrollment() { const organizationId = generateId() organizationIds.push(organizationId) await db @@ -46,7 +44,6 @@ async function createEnrollment(legacyTokenHash: string) { credentialGroupId: groupId, email: `${enrollmentId}@retention.test`, status: 'invited', - invitationTokenHash: legacyTokenHash, invitationExpiresAt: new Date(Date.now() + 7 * DAY_MS), invitedAt: new Date(), }) @@ -56,13 +53,12 @@ async function createEnrollment(legacyTokenHash: string) { async function insertLink( enrollmentId: string, purpose: 'email' | 'self' | 'connect', - expiresAt: Date, - tokenHash = sha256Hex(generateId()) + expiresAt: Date ) { const id = generateId() await db .insert(credentialGroupEnrollmentLink) - .values({ id, enrollmentId, tokenHash, purpose, expiresAt }) + .values({ id, enrollmentId, tokenHash: sha256Hex(generateId()), purpose, expiresAt }) return id } @@ -86,8 +82,7 @@ afterAll(async () => { describe('runCleanupCredentialGroupLinks', () => { it('deletes request log rows past two days and session links a day past expiry, nothing else', async () => { - const legacyTokenHash = sha256Hex(generateId()) - const { groupId, enrollmentId } = await createEnrollment(legacyTokenHash) + const { groupId, enrollmentId } = await createEnrollment() const now = Date.now() await insertRequest(groupId, new Date(now - 2 * DAY_MS - HOUR_MS)) const recentRequest = await insertRequest(groupId, new Date(now - DAY_MS - HOUR_MS)) @@ -96,12 +91,6 @@ describe('runCleanupCredentialGroupLinks', () => { const recentlyExpired = await insertLink(enrollmentId, 'connect', new Date(now - HOUR_MS)) const live = await insertLink(enrollmentId, 'connect', new Date(now + HOUR_MS)) const oldEmail = await insertLink(enrollmentId, 'email', new Date(now - 30 * DAY_MS)) - const namedByLegacyColumn = await insertLink( - enrollmentId, - 'self', - new Date(now - 30 * DAY_MS), - legacyTokenHash - ) await runCleanupCredentialGroupLinks(new Date(now)) @@ -114,13 +103,11 @@ describe('runCleanupCredentialGroupLinks', () => { .select({ id: credentialGroupEnrollmentLink.id }) .from(credentialGroupEnrollmentLink) .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId)) - expect(links.map((row) => row.id).sort()).toEqual( - [recentlyExpired, live, oldEmail, namedByLegacyColumn].sort() - ) + expect(links.map((row) => row.id).sort()).toEqual([recentlyExpired, live, oldEmail].sort()) }) it('keeps a request exactly at its cutoff and a link not yet expired at its cutoff', async () => { - const { groupId, enrollmentId } = await createEnrollment(sha256Hex(generateId())) + const { groupId, enrollmentId } = await createEnrollment() const now = Date.now() const atRequestCutoff = await insertRequest(groupId, new Date(now - 2 * DAY_MS)) await insertRequest(groupId, new Date(now - 2 * DAY_MS - 1)) @@ -142,7 +129,7 @@ describe('runCleanupCredentialGroupLinks', () => { }) it('skips a row another run holds instead of waiting for it', async () => { - const { groupId } = await createEnrollment(sha256Hex(generateId())) + const { groupId } = await createEnrollment() const old = new Date(Date.now() - 3 * DAY_MS) const held = await insertRequest(groupId, old) const free = await insertRequest(groupId, old) @@ -179,7 +166,7 @@ describe('runCleanupCredentialGroupLinks', () => { }) it('deletes at most five batches per run, oldest first, leaving the rest for the next run', async () => { - const { groupId } = await createEnrollment(sha256Hex(generateId())) + const { groupId } = await createEnrollment() const now = Date.now() const rows = Array.from({ length: 5_001 }, (_, index) => ({ id: generateId(), diff --git a/apps/sim/background/cleanup-credential-group-links.ts b/apps/sim/background/cleanup-credential-group-links.ts index a464d0dd776..00505ec738d 100644 --- a/apps/sim/background/cleanup-credential-group-links.ts +++ b/apps/sim/background/cleanup-credential-group-links.ts @@ -6,7 +6,7 @@ import { } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' -import { and, asc, eq, inArray, lt, ne, not } from 'drizzle-orm' +import { and, asc, eq, inArray, lt, not } from 'drizzle-orm' import { DAY_MS } from '@/lib/credential-groups/limits' import { unexpiredLinkCondition } from '@/lib/credential-groups/links' @@ -46,9 +46,7 @@ async function drain(table: string, deleteBatch: () => Promise): Promise /** * Deletes workflow connection request log rows older than two days, and `self` and `connect` * links that expired more than a day ago. Emailed links are kept: once bound, they outlive their - * expiry. A session link whose hash an enrollment's legacy invitation column still names is kept - * too, since deleting its row would let that token resolve through the column instead. Each - * batch takes its rows oldest first, skipping rows another run has locked. + * expiry. Each batch takes its rows oldest first, skipping rows another run has locked. */ export async function runCleanupCredentialGroupLinks( now = new Date() @@ -93,8 +91,7 @@ export async function runCleanupCredentialGroupLinks( .where( and( inArray(link.purpose, ['self', 'connect']), - not(unexpiredLinkCondition(linkCutoff)), - ne(credentialGroupEnrollment.invitationTokenHash, link.tokenHash) + not(unexpiredLinkCondition(linkCutoff)) ) ) .orderBy(asc(link.expiresAt)) diff --git a/apps/sim/lib/assistant-actions/tool-permissions.integration.ts b/apps/sim/lib/assistant-actions/tool-permissions.integration.ts index be98871d842..941bc2f2bb2 100644 --- a/apps/sim/lib/assistant-actions/tool-permissions.integration.ts +++ b/apps/sim/lib/assistant-actions/tool-permissions.integration.ts @@ -16,6 +16,7 @@ import { credential, credentialGroup, credentialGroupEnrollment, + credentialGroupEnrollmentLink, member, organization, organizationSearchIntegration, @@ -265,7 +266,6 @@ beforeAll(async () => { credentialGroupId: groupId, email: `${userId}@example.test`, status: 'completed' as const, - invitationTokenHash: id.replaceAll('-', '').repeat(2), invitationExpiresAt: new Date(Date.now() + 60_000), invitedAt: new Date(), })) @@ -1255,10 +1255,13 @@ describe('Managed account identity across Assistant approvals', () => { revokedAt: null, }) .where(eq(credential.id, selectedCredentialId)) - await db - .update(credentialGroupEnrollment) - .set({ invitationTokenHash: sha256Hex(invitationToken) }) - .where(eq(credentialGroupEnrollment.id, enrollmentId)) + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId, + tokenHash: sha256Hex(invitationToken), + purpose: 'email', + expiresAt: new Date(Date.now() + 60_000), + }) if (scenario.mode === 'new') { await db.update(credentialGroup).set({ options }).where(eq(credentialGroup.id, groupId)) } diff --git a/apps/sim/lib/credential-groups/README.md b/apps/sim/lib/credential-groups/README.md index 9594c142efd..f6e5a60b4b3 100644 --- a/apps/sim/lib/credential-groups/README.md +++ b/apps/sim/lib/credential-groups/README.md @@ -72,7 +72,7 @@ Every bearer link into an enrollment is a row in `credential_group_enrollment_li | Purpose | Issued by | Lifetime | | --- | --- | --- | -| `email` | An admin's invitation or resend, or an automatic invitation | 7 days; once a verified user is bound, the newest emailed link (the one the legacy column mirrors) no longer expires | +| `email` | An admin's invitation or resend, or an automatic invitation | 7 days while the enrollment is unbound; once a verified user is bound, emailed links no longer expire | | `self` | A member enrolling themselves from Integrations | 1 hour, always | | `connect` | The connect page's Connect button, for one account option | 1 hour, always; an expired one sends the person back to the connect page to start again | @@ -80,12 +80,7 @@ The 0490 migration's backfill recorded every existing invitation, including self An emailed reinvitation deliberately restarts the invitation: the issuer, invited and sent times move to the new send, a workflow's request marker and reminder count are cleared, and the status returns to Invited unless the person already made progress. Earlier links stay live. -Status is authoritative for revocation. The pre-link app revokes an enrollment by setting its status alone, so during a deploy or rollback its links can stay unrevoked; every link check also refuses a `revoked` enrollment, and a reinvitation revokes such links. The pre-link app's disconnect rewrites only the legacy column; a bound person's emailed link stays unexpired only while that column names it, so that disconnect ends it too. - -Contract phase (after the link expand is fully deployed and no rollback target predates it): - -1. Make `credential_group_enrollment.invitation_token_hash` nullable and stop writing it. Enrollments created without an emailed link store null instead of an `unissued:` value. Revoke live links into enrollments whose legacy column matches no link row. -2. Drop the column with its unique index and length check, and remove the legacy branch of `liveEnrollmentLinkCondition`, `adoptLegacyInvitationLink`, and the legacy fallback of `findCredentialGroupEnrollmentLinkRecord`. +Revoking an enrollment sets its status to `revoked` and revokes all of its links; every link check refuses a `revoked` enrollment. ## Connect URL @@ -101,7 +96,7 @@ The daily request limit counts distinct addresses per group per day; asking agai ## Rollout -OAuth attempt state changes at this release boundary (OAuth v6 and managed MCP v5). Older attempts lack a verified Sim user binding; older MCP attempts also lack the configuration version. They are deliberately rejected before token exchange, with an explicit instruction to reopen the invitation and connect again. Existing saved credentials are not invalidated by the state version change. Mixed application versions cannot complete each other's in-flight attempts: pause enrollment starts, allow the thirty-minute state lifetime to drain, replace the application instances together, and only then reopen enrollment. Do not run enrollment OAuth across mixed versions or roll back with active attempts. +OAuth attempt state is versioned (OAuth v6, managed MCP v5) and lives thirty minutes. An attempt of any other version is rejected before token exchange, with an instruction to reopen the invitation and connect again; saved credentials are unaffected. 1. Apply `0328_organization_connected_accounts.sql` before deploying code that reads the new columns. It expands ownership columns and checks, adds stable enrollment identity and MCP configuration versions, and builds indexes concurrently. No grants, enrollments, or Search data are moved or deleted. Constraints are added `NOT VALID` to avoid scanning existing tables while holding the DDL lock; validate them separately after auditing existing rows. 2. Inventory existing groups and their Search dependencies before enabling the feature. The queries below read IDs/counts only. Review archived/deleted sources too because a reset must account for retained documents and cleanup work. diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index a0db905ad91..6e7d551780a 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -597,7 +597,6 @@ describe('the connect URL', () => { email: teammate.email, status: 'revoked', revokedAt: new Date(), - invitationTokenHash: sha256Hex(generateId()), invitationExpiresAt: new Date(Date.now() + HOUR_MS), invitedAt: new Date(), }) diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts index aacaa6acf5e..0f1ef1b6124 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts @@ -1,8 +1,9 @@ /** - * The 0490 link backfill against real Postgres: invitations the pre-link app wrote (only the legacy - * `invitation_token_hash` column, no link row) each become exactly one emailed link, a replay of - * the statement adds nothing, and every token gets the same answer through the link table as it - * got through the legacy column. The backfill statement is read from the migration file itself. + * The 0490 link backfill against real Postgres: invitations written before links existed (only the + * enrollment's `invitation_token_hash` column, no link row) each become exactly one emailed link + * carrying the enrollment's expiry and revocation, an enrollment without a hash gets none, a replay + * of the statement adds nothing, and every token then answers as its invitation did. The backfill + * statement is read from the migration file itself. */ import { readFile } from 'node:fs/promises' import { db } from '@sim/db' @@ -38,7 +39,7 @@ const adminId = generateId() const boundUserId = generateId() let groupId = '' -interface LegacyInvitation { +interface SeededInvitation { label: string enrollmentId: string token: string @@ -46,10 +47,11 @@ interface LegacyInvitation { expiresAt: Date } -const invitations: LegacyInvitation[] = [] +const invitations: SeededInvitation[] = [] +const hashlessEnrollmentId = generateId() -/** Writes an enrollment the way the pre-link app did: its invitation only in the legacy column. */ -async function seedLegacyInvitation(input: { +/** Writes an enrollment as it was before links existed: its invitation only in the column. */ +async function seedColumnInvitation(input: { label: string expiresInMs: number status?: 'invited' | 'revoked' | 'completed' @@ -122,19 +124,26 @@ beforeAll(async () => { groupId = (await ensureWorkspaceAccountsGroup({ kind: 'organization', organizationId }, adminId)) .id - await seedLegacyInvitation({ label: 'live and unbound', expiresInMs: 3 * DAY_MS }) - await seedLegacyInvitation({ + await seedColumnInvitation({ label: 'live and unbound', expiresInMs: 3 * DAY_MS }) + await seedColumnInvitation({ label: 'revoked by status alone', expiresInMs: 3 * DAY_MS, status: 'revoked', }) - await seedLegacyInvitation({ label: 'expired and unbound', expiresInMs: -DAY_MS }) - await seedLegacyInvitation({ + await seedColumnInvitation({ label: 'expired and unbound', expiresInMs: -DAY_MS }) + await seedColumnInvitation({ label: 'expired but bound to its person', expiresInMs: -DAY_MS, status: 'completed', userId: boundUserId, }) + await db.insert(credentialGroupEnrollment).values({ + id: hashlessEnrollmentId, + credentialGroupId: groupId, + email: `${hashlessEnrollmentId}@backfill.test`.toLowerCase(), + invitationExpiresAt: new Date(Date.now() + DAY_MS), + invitedAt: new Date(), + }) }) afterAll(async () => { @@ -143,10 +152,7 @@ afterAll(async () => { }) describe('0490 enrollment link backfill', () => { - it('turns each legacy invitation into one emailed link that answers exactly as before, even when replayed', async () => { - const before = await Promise.all(invitations.map((invitation) => answers(invitation.token))) - expect(before.map((answer) => answer.live)).toEqual([true, false, false, true]) - + it('turns each invitation into one emailed link that answers as the invitation did, even when replayed', async () => { const statement = await backfillStatement() await db.execute(sql.raw(statement)) await db.execute(sql.raw(statement)) @@ -155,10 +161,10 @@ describe('0490 enrollment link backfill', () => { .select() .from(credentialGroupEnrollmentLink) .where( - inArray( - credentialGroupEnrollmentLink.enrollmentId, - invitations.map((invitation) => invitation.enrollmentId) - ) + inArray(credentialGroupEnrollmentLink.enrollmentId, [ + ...invitations.map((invitation) => invitation.enrollmentId), + hashlessEnrollmentId, + ]) ) for (const invitation of invitations) { const own = links.filter((link) => link.enrollmentId === invitation.enrollmentId) @@ -172,9 +178,14 @@ describe('0490 enrollment link backfill', () => { expect(own[0]?.revokedAt !== null, invitation.label).toBe(invitation.revokedByStatus) } + expect(links.some((link) => link.enrollmentId === hashlessEnrollmentId)).toBe(false) + const after = await Promise.all(invitations.map((invitation) => answers(invitation.token))) - expect(after.map(({ linkRevoked, ...rest }) => rest)).toEqual( - before.map(({ linkRevoked, ...rest }) => rest) - ) + expect(after).toEqual([ + { live: true, expired: false, revoked: false, linkRevoked: false }, + { live: false, expired: false, revoked: true, linkRevoked: true }, + { live: false, expired: true, revoked: false, linkRevoked: false }, + { live: true, expired: false, revoked: false, linkRevoked: false }, + ]) }) }) diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts index f9ee3699a10..21f7e6df8c0 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts @@ -18,7 +18,7 @@ import { import { sha256Hex } from '@sim/security/hash' import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' import { generateId } from '@sim/utils/id' -import { eq, inArray } from 'drizzle-orm' +import { inArray } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { explainCredentialGroupEnrollmentLink } from '@/lib/credential-groups/application/enrollment-link-outcome' @@ -57,10 +57,12 @@ function explain(invitationToken: string, user: { id: string }) { } const organizationIds: string[] = [] +const enrollmentIdByToken = new Map() /** - * Each enrollment gets its own organization and group: an organization holds one group, and a - * group one enrollment per email and user. + * Seeds an enrollment with one emailed link, as an invitation writes it (a revocation revokes the + * link too), and returns that link's token. Each enrollment gets its own organization and group: + * an organization holds one group, and a group one enrollment per email and user. */ async function seedEnrollment( values: Partial & { email: string }, @@ -85,16 +87,32 @@ async function seedEnrollment( options: group.options ?? [], status: groupStatus, }) - await db.insert(credentialGroupEnrollment).values({ + const [enrollment] = await db + .insert(credentialGroupEnrollment) + .values({ + id: generateId(), + credentialGroupId: groupId, + status: 'invited', + invitationExpiresAt: new Date(Date.now() + DAY_MS), + invitedAt: new Date(), + createdBy: inviterId, + ...values, + }) + .returning({ + id: credentialGroupEnrollment.id, + expiresAt: credentialGroupEnrollment.invitationExpiresAt, + revokedAt: credentialGroupEnrollment.revokedAt, + }) + if (!enrollment) throw new Error('Seeded enrollment not written') + await db.insert(credentialGroupEnrollmentLink).values({ id: generateId(), - credentialGroupId: groupId, - status: 'invited', - invitationTokenHash: sha256Hex(token), - invitationExpiresAt: new Date(Date.now() + DAY_MS), - invitedAt: new Date(), - createdBy: inviterId, - ...values, + enrollmentId: enrollment.id, + tokenHash: sha256Hex(token), + purpose: 'email', + expiresAt: enrollment.expiresAt, + revokedAt: enrollment.revokedAt, }) + enrollmentIdByToken.set(token, enrollment.id) return token } @@ -103,15 +121,12 @@ async function seedLink( enrollmentToken: string, values: Partial = {} ): Promise { - const [enrollment] = await db - .select({ id: credentialGroupEnrollment.id }) - .from(credentialGroupEnrollment) - .where(eq(credentialGroupEnrollment.invitationTokenHash, sha256Hex(enrollmentToken))) - if (!enrollment) throw new Error('Seeded enrollment not found') + const enrollmentId = enrollmentIdByToken.get(enrollmentToken) + if (!enrollmentId) throw new Error('Seeded enrollment not found') const token = generateId() await db.insert(credentialGroupEnrollmentLink).values({ id: generateId(), - enrollmentId: enrollment.id, + enrollmentId, tokenHash: sha256Hex(token), purpose: 'email', expiresAt: new Date(Date.now() + DAY_MS), @@ -172,7 +187,7 @@ describe('explainCredentialGroupEnrollmentLink', () => { const token = await seedEnrollment({ email: inviteeEmail, userId: inviteeId, - status: 'completed', + status: 'revoked', revokedAt: new Date(), }) await expect(explain(token, invitee)).resolves.toEqual({ @@ -271,20 +286,10 @@ describe('explainCredentialGroupEnrollmentLink', () => { }) }) - it("never calls a bound person's newest emailed link expired, only an older one", async () => { + it("never calls a bound person's emailed link expired", async () => { const enrollmentToken = await seedEnrollment({ email: inviteeEmail, userId: inviteeId }) - const older = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) - const newest = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) - await db - .update(credentialGroupEnrollment) - .set({ invitationTokenHash: sha256Hex(newest) }) - .where(eq(credentialGroupEnrollment.invitationTokenHash, sha256Hex(enrollmentToken))) - - await expect(explain(newest, invitee)).resolves.toEqual({ kind: 'unavailable' }) - await expect(explain(older, invitee)).resolves.toMatchObject({ - kind: 'needs_new_link', - reason: 'expired', - }) + const token = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) + await expect(explain(token, invitee)).resolves.toEqual({ kind: 'unavailable' }) }) it('calls an expired connect link of a bound person expired', async () => { @@ -299,7 +304,7 @@ describe('explainCredentialGroupEnrollmentLink', () => { }) }) - it('reports an unbound link expired by its own expiry, not the legacy column', async () => { + it('reports an unbound link expired by its own expiry', async () => { const enrollmentToken = await seedEnrollment({ email: inviteeEmail }) const token = await seedLink(enrollmentToken, { expiresAt: new Date(Date.now() - DAY_MS) }) await expect(explain(token, invitee)).resolves.toMatchObject({ diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts index a7008fbbd40..e29114034f1 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts @@ -1,10 +1,9 @@ /** * Enrollment links against real Postgres: issuing a link never invalidates another, an emailed * link's expiry binds only an unbound enrollment while self and connect links always expire, and - * disconnect or revocation (by this app or the released one) kills every link. A token is resolved - * through indexes, never a scan of every enrollment. Only the email - * transport and the provider code exchange are faked; the emailed link is read from what would - * have been sent. + * disconnect or revocation kills every link. A token is resolved through indexes, never a scan of + * every enrollment. Only the email transport and the provider code exchange are faked; the + * emailed link is read from what would have been sent. */ import { db } from '@sim/db' import { @@ -17,7 +16,6 @@ import { user, } from '@sim/db/schema' import { explainCaptured } from '@sim/db/testing/explain' -import { sha256Hex } from '@sim/security/hash' import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' @@ -181,7 +179,7 @@ async function waitForBlockedBy(blockerPid: number) { throw new Error('The request never waited on the held transaction') } -/** Ages every link of an enrollment, and the legacy column, past its expiry. */ +/** Ages every link of an enrollment, and the enrollment's request, past its expiry. */ async function expire(enrollmentId: string) { const past = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000) await db @@ -265,32 +263,22 @@ afterAll(async () => { }) describe('credential group enrollment links', () => { - it.each([ - ['a link row', false], - ['an invitation in the legacy column', true], - ])( - 'finds the enrollment %s names by an index lookup, never by scanning enrollments', - async (_label, legacy) => { - const person = await createPerson() - const emailed = await adminInvite(person.email) - if (legacy) - await db - .delete(credentialGroupEnrollmentLink) - .where(eq(credentialGroupEnrollmentLink.enrollmentId, emailed.enrollmentId)) - - const plan = await explainCaptured( - db, - async () => expect(await resolves(emailed.token)).toBe(true), - { gucs: { enable_seqscan: 'off' } } - ) - - const enrollmentScans = plan.filter( - (node) => node['Relation Name'] === 'credential_group_enrollment' - ) - expect(enrollmentScans.length).toBeGreaterThan(0) - for (const scan of enrollmentScans) expect(scan['Index Cond']).toBeDefined() - } - ) + it('finds the enrollment a link names by an index lookup, never by scanning enrollments', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + + const plan = await explainCaptured( + db, + async () => expect(await resolves(emailed.token)).toBe(true), + { gucs: { enable_seqscan: 'off' } } + ) + + const enrollmentScans = plan.filter( + (node) => node['Relation Name'] === 'credential_group_enrollment' + ) + expect(enrollmentScans.length).toBeGreaterThan(0) + for (const scan of enrollmentScans) expect(scan['Index Cond']).toBeDefined() + }) it('keeps an emailed link working after the person connects themselves', async () => { const person = await createPerson() @@ -346,6 +334,18 @@ describe('credential group enrollment links', () => { await expect(bindCredentialGroupEnrollmentUser(later, person.userId)).resolves.toBeUndefined() }) + it('keeps every emailed link of a bound person live past its expiry', async () => { + const person = await createPerson() + const emailed = await adminInvite(person.email) + const resent = await resend(emailed.enrollmentId, person.email) + await bindCredentialGroupEnrollmentUser(await identityOf(resent), person.userId) + + await expire(emailed.enrollmentId) + + expect(await resolves(emailed.token)).toBe(true) + expect(await resolves(resent)).toBe(true) + }) + it('expires self and connect links even once the enrollment is bound', async () => { const person = await createPerson() const self = await selfEnroll(person.userId) @@ -410,29 +410,11 @@ describe('credential group enrollment links', () => { expect(await resolves(self.token)).toBe(false) }) - it('kills links into an enrollment the pre-link app revoked when it is reinvited', async () => { - const person = await createPerson() - const emailed = await adminInvite(person.email) - const self = await selfEnroll(person.userId) - /** The released app revokes the enrollment row only; its links stay unrevoked. */ - await db - .update(credentialGroupEnrollment) - .set({ status: 'revoked', revokedAt: new Date() }) - .where(eq(credentialGroupEnrollment.id, emailed.enrollmentId)) - - const reinvited = await adminInvite(person.email) - - expect(reinvited.enrollmentId).toBe(emailed.enrollmentId) - expect(await resolves(reinvited.token)).toBe(true) - expect(await resolves(emailed.token)).toBe(false) - expect(await resolves(self.token)).toBe(false) - }) - - it('refuses every link into an enrollment the pre-link app revoked, even to bind or complete', async () => { + it('refuses every link into a revoked enrollment, even to bind or complete', async () => { const person = await createPerson() const emailed = await adminInvite(person.email) const identity = await identityOf(emailed.token) - /** The released app revokes the enrollment row only; its links stay unrevoked. */ + /** The status alone decides revocation, so the links are left unrevoked here. */ await db .update(credentialGroupEnrollment) .set({ status: 'revoked' }) @@ -446,41 +428,6 @@ describe('credential group enrollment links', () => { expect((await enrollmentRow(emailed.enrollmentId)).userId).toBeNull() }) - it("ends a bound person's emailed link when the pre-link app's disconnect rewrites the legacy column", async () => { - const person = await createPerson() - const emailed = await adminInvite(person.email) - await bindCredentialGroupEnrollmentUser(await identityOf(emailed.token), person.userId) - await expire(emailed.enrollmentId) - expect(await resolves(emailed.token)).toBe(true) - - /** The released app's disconnect writes a fresh hash to the column and leaves links alone. */ - await db - .update(credentialGroupEnrollment) - .set({ invitationTokenHash: sha256Hex(generateId()) }) - .where(eq(credentialGroupEnrollment.id, emailed.enrollmentId)) - - expect(await resolves(emailed.token)).toBe(false) - }) - - it('keeps an invitation the pre-link app emailed during a deploy working after a resend', async () => { - const person = await createPerson() - const emailed = await adminInvite(person.email) - const legacyToken = generateId() - await db - .update(credentialGroupEnrollment) - .set({ - invitationTokenHash: sha256Hex(legacyToken), - invitationExpiresAt: new Date(Date.now() + 60_000), - }) - .where(eq(credentialGroupEnrollment.id, emailed.enrollmentId)) - - const resent = await resend(emailed.enrollmentId, person.email) - - expect(await resolves(legacyToken)).toBe(true) - expect(await resolves(resent)).toBe(true) - expect(await resolves(emailed.token)).toBe(true) - }) - it('never lets a slower, older send record its failure over a newer send', async () => { const person = await createPerson() const { enrollmentId } = await adminInvite(person.email) @@ -511,26 +458,6 @@ describe('credential group enrollment links', () => { expect(row?.sentAt).not.toBeNull() }) - it('resolves an invitation the pre-link app wrote during a deploy', async () => { - const person = await createPerson() - const token = generateId() - const enrollmentId = generateId() - await db.insert(credentialGroupEnrollment).values({ - id: enrollmentId, - credentialGroupId: groupId, - email: person.email, - status: 'invited', - invitationTokenHash: sha256Hex(token), - invitationExpiresAt: new Date(Date.now() + 60_000), - invitedAt: new Date(), - createdBy: adminId, - }) - - expect(await resolves(token)).toBe(true) - await expire(enrollmentId) - expect(await resolves(token)).toBe(false) - }) - it('keeps both links when a resend races the person connecting themselves', async () => { const person = await createPerson() const emailed = await adminInvite(person.email) @@ -559,7 +486,7 @@ describe('credential group enrollment links', () => { const revoked = await createPerson() const revokedInvite = await adminInvite(revoked.email) const identity = await identityOf(revokedInvite.token) - /** Revoked by status alone, as the released app does, so its link is still unrevoked. */ + /** The status alone decides revocation, so its link is left unrevoked here. */ await db .update(credentialGroupEnrollment) .set({ status: 'revoked' }) diff --git a/apps/sim/lib/credential-groups/__integration__/hubspot-mcp.integration.ts b/apps/sim/lib/credential-groups/__integration__/hubspot-mcp.integration.ts index 15044b94970..3fe35210fd1 100644 --- a/apps/sim/lib/credential-groups/__integration__/hubspot-mcp.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/hubspot-mcp.integration.ts @@ -4,6 +4,7 @@ import { db } from '@sim/db' import { credential, credentialGroupEnrollment, + credentialGroupEnrollmentLink, mcpServers, member, organization, @@ -120,7 +121,6 @@ describe.each(SHARED_CLIENTS)('$name shared member connector', (connector) => { userId: owner, email: `${owner}@fixture.test`, status: 'completed', - invitationTokenHash: sha256Hex(generateId()), invitationExpiresAt: new Date(Date.now() + 60_000), invitedAt: new Date(), }) @@ -478,10 +478,16 @@ describe.each(SHARED_CLIENTS)('$name shared member connector', (connector) => { userId: owner, email, status: 'in_progress', - invitationTokenHash: sha256Hex(token), invitationExpiresAt: new Date(Date.now() + 60_000), invitedAt: new Date(), }) + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId, + tokenHash: sha256Hex(token), + purpose: 'email', + expiresAt: new Date(Date.now() + 60_000), + }) const principal = { kind: 'credential_group_enrollment' as const, userId: owner, diff --git a/apps/sim/lib/credential-groups/__integration__/multiple-provider-accounts.integration.ts b/apps/sim/lib/credential-groups/__integration__/multiple-provider-accounts.integration.ts index d94a701ee5f..40e365c26bb 100644 --- a/apps/sim/lib/credential-groups/__integration__/multiple-provider-accounts.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/multiple-provider-accounts.integration.ts @@ -167,17 +167,29 @@ const rows = () => .from(credential) .where(eq(credential.organizationId, organizationId)) -/** Mirrors the disconnect operation, which also invalidates the outstanding invitation token. */ +/** Mints a fresh link into the enrollment and makes its token the outstanding one. */ +async function issueLink() { + invitationToken = generateId() + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId, + tokenHash: sha256Hex(invitationToken), + purpose: 'email', + expiresAt: new Date(Date.now() + 3_600_000), + }) +} + +/** Mirrors the disconnect operation, which also revokes every outstanding link. */ async function disconnect(id: string) { await db .update(credential) .set({ managedOauthStatus: 'revoked', revokedAt: new Date() }) .where(eq(credential.id, id)) - invitationToken = generateId() await db - .update(credentialGroupEnrollment) - .set({ invitationTokenHash: sha256Hex(invitationToken) }) - .where(eq(credentialGroupEnrollment.id, enrollmentId)) + .update(credentialGroupEnrollmentLink) + .set({ revokedAt: new Date() }) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId)) + await issueLink() } beforeAll(async () => { @@ -228,11 +240,11 @@ beforeAll(async () => { userId, email, status: 'completed', - invitationTokenHash: sha256Hex(invitationToken), invitationExpiresAt: new Date(Date.now() + 3_600_000), invitedAt: new Date(), createdBy: userId, }) + await issueLink() }) beforeEach(async () => { diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index 09839519e5b..69040070995 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -306,7 +306,6 @@ async function enroll( credentialGroupId: fixture.groupId, email, status: 'invited', - invitationTokenHash: sha256Hex(generateId()), invitationExpiresAt: new Date(Date.now() + 3_600_000), invitedAt: new Date(), createdBy: ownerId, @@ -335,10 +334,13 @@ async function connectPerson(fixture: OrgFixture, email: string) { createdAt: new Date(), }) const invitationToken = generateId() - const enrollmentId = await enroll(fixture, email, { - userId, - status: 'completed', - invitationTokenHash: sha256Hex(invitationToken), + const enrollmentId = await enroll(fixture, email, { userId, status: 'completed' }) + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId, + tokenHash: sha256Hex(invitationToken), + purpose: 'email', + expiresAt: new Date(Date.now() + 3_600_000), }) const context: CredentialGroupOAuthContext = { enrollmentId, @@ -842,7 +844,6 @@ describe('connection request emails', () => { requestedProviderId: DRIVE_ID, createdBy: null, invitedAt: requested.invitedAt, - invitationTokenHash: requested.invitationTokenHash, }) expect(after?.invitationExpiresAt.getTime()).toBeGreaterThan(Date.now() + 6 * DAY_MS) const links = await db @@ -1093,15 +1094,11 @@ describe('a requested enrollment on the connect page', () => { email ) - const [invited] = await enrollmentsFor(orgA, email) const links = await db - .select({ - tokenHash: credentialGroupEnrollmentLink.tokenHash, - purpose: credentialGroupEnrollmentLink.purpose, - }) + .select({ purpose: credentialGroupEnrollmentLink.purpose }) .from(credentialGroupEnrollmentLink) .where(eq(credentialGroupEnrollmentLink.enrollmentId, requested.id)) - expect(links).toEqual([{ tokenHash: invited?.invitationTokenHash, purpose: 'email' }]) + expect(links).toEqual([{ purpose: 'email' }]) }) }) diff --git a/apps/sim/lib/credential-groups/application/personal-organization-accounts.test.ts b/apps/sim/lib/credential-groups/application/personal-organization-accounts.test.ts index 98cfaf3c4c0..d5aaecf4919 100644 --- a/apps/sim/lib/credential-groups/application/personal-organization-accounts.test.ts +++ b/apps/sim/lib/credential-groups/application/personal-organization-accounts.test.ts @@ -121,9 +121,7 @@ describe('personal organization contributions', () => { expect(dbChainMockFns.set).toHaveBeenCalledWith( expect.objectContaining({ managedOauthStatus: 'revoked', revokedAt: expect.any(Date) }) ) - expect(dbChainMockFns.set).toHaveBeenCalledWith( - expect.objectContaining({ invitationTokenHash: expect.any(String) }) - ) + expect(dbChainMockFns.update).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollmentLink) expect(mocks.evict).toHaveBeenCalledWith('mcp-cg-person', expect.any(String)) expect(mocks.available).not.toHaveBeenCalled() }) diff --git a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts index 27a190e2dd5..b22a73f8405 100644 --- a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts +++ b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts @@ -13,7 +13,6 @@ import { defineOperation } from '@/lib/core/application' import { runWithOutboundOrganization } from '@/lib/core/network/context.server' import { OrchestrationError } from '@/lib/core/orchestration/types' import { sameResourceScopeCondition } from '@/lib/core/resource-scope.server' -import { createUnissuedInvitationTokenHash } from '@/lib/credential-groups/enrollment-lifecycle' import { createCredentialGroupOAuthStartUrl } from '@/lib/credential-groups/enrollment-links' import { lockCredentialGroupEnrollmentLifecycle } from '@/lib/credential-groups/enrollments' import { revokeCredentialGroupEnrollmentLinks } from '@/lib/credential-groups/links' @@ -222,10 +221,6 @@ export const disconnectPersonalOrganizationAccount = defineAuthorizedCredentialU .set({ managedOauthStatus: 'revoked', revokedAt: now, updatedAt: now }) .where(eq(credential.id, current.credentialId)) await revokeCredentialGroupEnrollmentLinks(tx, current.enrollmentId, now) - await tx - .update(credentialGroupEnrollment) - .set({ invitationTokenHash: createUnissuedInvitationTokenHash(), updatedAt: now }) - .where(eq(credentialGroupEnrollment.id, current.enrollmentId)) }) return { success: true as const, diff --git a/apps/sim/lib/credential-groups/connect-subject.ts b/apps/sim/lib/credential-groups/connect-subject.ts index 5d4295c87d1..ac89769ef5a 100644 --- a/apps/sim/lib/credential-groups/connect-subject.ts +++ b/apps/sim/lib/credential-groups/connect-subject.ts @@ -41,7 +41,7 @@ interface CredentialGroupConnectSubject { } enrollment: Pick< EnrollmentRow, - 'id' | 'email' | 'userId' | 'status' | 'revokedAt' | 'invitationExpiresAt' + 'id' | 'email' | 'userId' | 'status' | 'invitationExpiresAt' > | null } @@ -82,7 +82,6 @@ export async function loadCredentialGroupConnectSubject(input: { email: credentialGroupEnrollment.email, userId: credentialGroupEnrollment.userId, status: credentialGroupEnrollment.status, - revokedAt: credentialGroupEnrollment.revokedAt, invitationExpiresAt: credentialGroupEnrollment.invitationExpiresAt, }) .from(credentialGroupEnrollment) @@ -135,10 +134,10 @@ type IssuedCredentialGroupConnectLink = /** * Mints a short-lived link focused on one account option and, in the same transaction, creates * the member's enrollment when they enroll themselves and binds the signed-in person to an - * unbound one, renewing an expired request a member may answer. The enrollment's lifecycle lock serializes it with revocation, so a revocation that - * commits first is reported as `revoked` and a later one kills the new link. Inserts a link row - * only: an existing enrollment's issuer, timestamps, status and legacy token column stay as they - * are. + * unbound one, renewing an expired request a member may answer. The enrollment's lifecycle lock + * serializes it with revocation, so a revocation that commits first is reported as `revoked` and + * a later one kills the new link. Inserts a link row only: an existing enrollment's issuer, + * timestamps and status stay as they are. * * The caller has already decided the person may connect; this re-checks, under the lock, only what * may have changed since: revocation, expiry, the group still being active, the binding, and that @@ -180,7 +179,6 @@ export async function issueCredentialGroupConnectLink(input: { email: credentialGroupEnrollment.email, userId: credentialGroupEnrollment.userId, status: credentialGroupEnrollment.status, - revokedAt: credentialGroupEnrollment.revokedAt, invitationExpiresAt: credentialGroupEnrollment.invitationExpiresAt, groupStatus: credentialGroup.status, }) diff --git a/apps/sim/lib/credential-groups/enrollment-lifecycle.ts b/apps/sim/lib/credential-groups/enrollment-lifecycle.ts index cba0a3b6bcd..17ce0a61125 100644 --- a/apps/sim/lib/credential-groups/enrollment-lifecycle.ts +++ b/apps/sim/lib/credential-groups/enrollment-lifecycle.ts @@ -1,5 +1,4 @@ import type { credentialGroupEnrollment } from '@sim/db/schema' -import { sha256Hex } from '@sim/security/hash' import { generateId } from '@sim/utils/id' import { DAY_MS } from '@/lib/credential-groups/limits' @@ -16,22 +15,6 @@ type EnrollmentRow = typeof credentialGroupEnrollment.$inferSelect */ export const INVITATION_TTL_MS = 7 * DAY_MS -const UNISSUED_INVITATION_PREFIX = 'unissued:' - -/** - * A value for the legacy `invitation_token_hash` column of an enrollment created without an - * emailed link. It contains a character no hex digest does, so no token ever hashes to it: the - * legacy branch of the link lookup never matches it and link adoption skips it. It is unique and - * 64 characters long, as the column requires. - */ -export function createUnissuedInvitationTokenHash(): string { - return `${UNISSUED_INVITATION_PREFIX}${sha256Hex(generateId()).slice(UNISSUED_INVITATION_PREFIX.length)}` -} - -export function isUnissuedInvitationTokenHash(value: string): boolean { - return value.startsWith(UNISSUED_INVITATION_PREFIX) -} - /** * Insert values for an enrollment created without an emailed link (member self-enrollment, the * connect page, or a workflow's connection request). It waits for its person as long as an @@ -47,7 +30,6 @@ export function unissuedEnrollmentValues(input: { credentialGroupId: input.credentialGroupId, email: input.email, status: 'invited', - invitationTokenHash: createUnissuedInvitationTokenHash(), invitationExpiresAt: new Date(input.now.getTime() + INVITATION_TTL_MS), invitedAt: input.now, createdBy: null, @@ -56,14 +38,9 @@ export function unissuedEnrollmentValues(input: { } satisfies typeof credentialGroupEnrollment.$inferInsert } -/** - * Whether an admin revoked the enrollment. Status is authoritative while an app that revokes by - * status alone may still be deployed, so either marker counts. - */ -export function isEnrollmentRevoked( - enrollment: Pick -): boolean { - return enrollment.status === 'revoked' || enrollment.revokedAt !== null +/** Whether an admin revoked the enrollment; a revocation sets the status (and `revoked_at`). */ +export function isEnrollmentRevoked(enrollment: Pick): boolean { + return enrollment.status === 'revoked' } /** @@ -72,7 +49,7 @@ export function isEnrollmentRevoked( * request and People labels it Expired, both through this one rule. */ export function isEnrollmentRequestExpired( - enrollment: Pick, + enrollment: Pick, now = new Date() ): boolean { return ( diff --git a/apps/sim/lib/credential-groups/enrollments.test.ts b/apps/sim/lib/credential-groups/enrollments.test.ts index 31027029853..4f93c956d35 100644 --- a/apps/sim/lib/credential-groups/enrollments.test.ts +++ b/apps/sim/lib/credential-groups/enrollments.test.ts @@ -83,12 +83,13 @@ afterEach(() => { vi.useRealTimers() }) +const TOKEN_HASH = 'a'.repeat(64) + const ENROLLMENT = { id: 'enrollment-1', credentialGroupId: 'group-1', email: 'alex@example.com', status: 'completed' as const, - invitationTokenHash: 'a'.repeat(64), invitationExpiresAt: new Date('2026-08-18T12:00:00.000Z'), invitedAt: new Date('2026-08-11T12:00:00.000Z'), sentAt: new Date('2026-08-11T12:00:01.000Z'), @@ -106,7 +107,7 @@ describe('focused public enrollment projection', () => { credentialGroupId: 'group-1', enrollmentId: ENROLLMENT.id, email: ENROLLMENT.email, - invitationTokenHash: ENROLLMENT.invitationTokenHash, + invitationTokenHash: TOKEN_HASH, } const options = [ { id: 'first', provider: 'gmail', label: 'First account', status: 'active', required: false }, @@ -457,7 +458,6 @@ describe('enrollment context for session-authorized or consumed-attempt OAuth', enrollment: { ...ENROLLMENT, userId: 'person-1', - invitationTokenHash: 'rotated-hash', invitationExpiresAt: new Date(0), }, groupId: 'group-1', @@ -474,7 +474,6 @@ describe('enrollment context for session-authorized or consumed-attempt OAuth', it.each([ { groupStatus: 'disabled' }, { enrollment: { ...row.enrollment, status: 'revoked' } }, - { enrollment: { ...row.enrollment, revokedAt: NOW } }, { options: [] }, { options: [{ id: 'option-1', provider: 'gmail', status: 'disabled' }] }, ])('refuses an enrollment or option that is no longer live', async (change) => { @@ -509,13 +508,13 @@ describe('enrollment context for session-authorized or consumed-attempt OAuth', expect(eq).toHaveBeenCalledWith(schemaMock.mcpServers.authType, 'oauth') expect(isNull).toHaveBeenCalledWith(schemaMock.mcpServers.deletedAt) expect(eq).not.toHaveBeenCalledWith( - schemaMock.credentialGroupEnrollment.invitationTokenHash, + schemaMock.credentialGroupEnrollmentLink.tokenHash, expect.anything() ) }) it('denies a consumed MCP attempt after the enrollment is revoked or its linked server is unavailable', async () => { queueTableRows(schemaMock.credentialGroupEnrollment, [ - { ...row, enrollment: { ...row.enrollment, revokedAt: new Date() } }, + { ...row, enrollment: { ...row.enrollment, status: 'revoked' } }, ]) expect( await getCredentialGroupMcpOAuthContextForEnrollment(identity, 'mcp-server-1') @@ -535,7 +534,7 @@ describe('organization enrollment bound identity', () => { credentialGroupId: 'group-1', enrollmentId: ENROLLMENT.id, email: ENROLLMENT.email, - invitationTokenHash: ENROLLMENT.invitationTokenHash, + invitationTokenHash: TOKEN_HASH, } const row = { enrollment: { ...ENROLLMENT, userId: 'person-1' }, @@ -598,7 +597,7 @@ describe('verified immutable enrollment identity binding', () => { credentialGroupId: 'group-1', enrollmentId: ENROLLMENT.id, email: ENROLLMENT.email, - invitationTokenHash: ENROLLMENT.invitationTokenHash, + invitationTokenHash: TOKEN_HASH, } beforeEach(() => { resetDbChainMock() @@ -613,7 +612,7 @@ describe('verified immutable enrollment identity binding', () => { ) expect(isNull).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.userId) expect(eq).toHaveBeenCalledWith( - schemaMock.credentialGroupEnrollment.invitationTokenHash, + schemaMock.credentialGroupEnrollmentLink.tokenHash, identity.invitationTokenHash ) }) diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 742004654b3..26a45da9035 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -46,7 +46,6 @@ import { unissuedEnrollmentValues, } from '@/lib/credential-groups/enrollment-lifecycle' import { - adoptLegacyInvitationLink, hashInvitationToken, insertEnrollmentLink, liveEnrollmentLinkCondition, @@ -610,10 +609,9 @@ async function issueInvitation( options: SendInvitationOptions ): Promise { const now = new Date() - const token = generateId() const expiresAt = new Date(now.getTime() + INVITATION_TTL_MS) - const issued = await db.transaction(async (tx) => { + return db.transaction(async (tx) => { const current = await lockInvitationEnrollment(tx, context.groupId, email) if (options.expectedEnrollmentId && current?.id !== options.expectedEnrollmentId) { throw new CredentialGroupEnrollmentError('Enrollment not found', 404) @@ -621,20 +619,10 @@ async function issueInvitation( if (current?.status === 'revoked' && options.revokedEnrollment === 'reject') { throw new CredentialGroupEnrollmentError('Revoked enrollment cannot be resent', 409) } - if (current) { - await adoptLegacyInvitationLink(tx, current, now) - // The released app revokes by status alone, so its revoked enrollment's links may still be - // unrevoked; none of them may survive a reinvitation. - if (isEnrollmentRevoked(current)) - await revokeCredentialGroupEnrollmentLinks(tx, current.id, now) - } const preservesProgress = current?.status === 'in_progress' || current?.status === 'completed' const nextStatus = preservesProgress ? current.status : ('invited' as const) - // The legacy column mirrors the newest emailed link; a bound person's emailed link stays - // live only while it is that one. const invitationValues = { - invitationTokenHash: hashInvitationToken(token), invitationExpiresAt: expiresAt, status: nextStatus, invitedAt: now, @@ -664,17 +652,14 @@ async function issueInvitation( }) .returning() if (!next) throw new Error('Credential group enrollment write returned no row') - const { linkId } = await insertEnrollmentLink(tx, { + const { token, linkId } = await insertEnrollmentLink(tx, { enrollmentId: next.id, purpose: 'email', - token, expiresAt, now, }) - return { enrollment: next, linkId } + return { enrollment: next, linkId, invitationLink: invitationLinkFor(token) } }) - - return { ...issued, invitationLink: invitationLinkFor(token) } } /** diff --git a/apps/sim/lib/credential-groups/links.ts b/apps/sim/lib/credential-groups/links.ts index d7343eeda86..734bf987182 100644 --- a/apps/sim/lib/credential-groups/links.ts +++ b/apps/sim/lib/credential-groups/links.ts @@ -11,13 +11,11 @@ import { import { sha256Hex } from '@sim/security/hash' import { generateId } from '@sim/utils/id' import { and, eq, gt, isNotNull, isNull, ne, or, type SQL, sql } from 'drizzle-orm' -import { alias } from 'drizzle-orm/pg-core' import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' import { INVITATION_TTL_MS, isEnrollmentRevoked, - isUnissuedInvitationTokenHash, } from '@/lib/credential-groups/enrollment-lifecycle' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import type { DbTransaction } from '@/lib/db/types' @@ -28,19 +26,10 @@ import type { DbTransaction } from '@/lib/db/types' * a link never invalidates another. Callers that write hold the enrollment's lifecycle lock. * * Link lifetimes, decided by {@link unexpiredLinkCondition} alone: - * - `email`: {@link INVITATION_TTL_MS}. Once a verified user is bound, the newest emailed link (the - * one the enrollment's legacy column mirrors) stops expiring: the signed-in user is the authority, - * not the email's age. The pre-link app's disconnect rewrites that column, so it also ends that. + * - `email`: {@link INVITATION_TTL_MS} while the enrollment is unbound. Once a verified user is + * bound, emailed links stop expiring: the signed-in user is the authority, not the email's age. * - `self` and `connect`: {@link SESSION_LINK_TTL_MS}, always. They are minted for the sitting the * person is in. - * - * contract-pending(after the enrollment-link expand is fully deployed and no rollback target - * predates it): the enrollment's legacy `invitation_token_hash` column and its `unissued:` values - * go in two steps. First make the column nullable and stop writing it; then drop it with its - * unique index and length check, along with {@link legacyInvitationUnexpiredCondition}, - * {@link adoptLegacyInvitationLink}, and the legacy fallback of - * {@link findCredentialGroupEnrollmentLinkRecord}. Bound emailed links then need their own marker - * in place of the column comparison in {@link unexpiredLinkCondition}. */ /** How long a `self` or `connect` link lives: it is opened in the sitting it was minted for. */ @@ -63,46 +52,23 @@ export function unexpiredLinkCondition(now: Date): SQL { const link = credentialGroupEnrollmentLink const enrollment = credentialGroupEnrollment return sql`(${or( - and( - isNotNull(enrollment.userId), - eq(link.purpose, 'email'), - eq(link.tokenHash, enrollment.invitationTokenHash) - ), + and(isNotNull(enrollment.userId), eq(link.purpose, 'email')), gt(link.expiresAt, now) )})` } -/** Whether an invitation known only by the enrollment's legacy column is unexpired at `now`. */ -function legacyInvitationUnexpiredCondition(now: Date): SQL { - const enrollment = credentialGroupEnrollment - return sql`(${or(isNotNull(enrollment.userId), gt(enrollment.invitationExpiresAt, now))})` -} - /** - * The enrollment a token hash names: its link row's enrollment, else the enrollment whose legacy - * column holds it. Both lookups are uncorrelated and use a unique index, so a query filtering - * `credential_group_enrollment.id` by this value reads one row by primary key. + * The enrollment a token hash names. The lookup is uncorrelated and uses the unique token index, + * so a query filtering `credential_group_enrollment.id` by this value reads one row by primary key. */ function enrollmentIdForTokenHash(tokenHash: string): SQL { const link = credentialGroupEnrollmentLink - const legacy = alias(credentialGroupEnrollment, 'legacy_invitation') - const linked = db - .select({ id: link.enrollmentId }) - .from(link) - .where(eq(link.tokenHash, tokenHash)) - const legacyInvitation = db - .select({ id: legacy.id }) - .from(legacy) - .where(eq(legacy.invitationTokenHash, tokenHash)) - return sql`coalesce((${linked}), (${legacyInvitation}))` + return sql`(${db.select({ id: link.enrollmentId }).from(link).where(eq(link.tokenHash, tokenHash))})` } /** * Matches the enrollment row that `tokenHash` is a live link into: an enrollment nobody revoked, - * and an unrevoked link that {@link unexpiredLinkCondition} keeps. A hash with no link row falls - * back to the enrollment's legacy column, an emailed invitation the pre-link app still writes - * during a deploy or rollback. The pre-link app revokes an enrollment by its status alone, leaving - * its links unrevoked, so the enrollment's status is checked here too. + * and an unrevoked link that {@link unexpiredLinkCondition} keeps. * * The enrollment is found by primary key first ({@link enrollmentIdForTokenHash}); the liveness * checks then run against that one row. @@ -112,17 +78,13 @@ export function liveEnrollmentLinkCondition(tokenHash: string, now = new Date()) const enrollment = credentialGroupEnrollment return sql`(${and( sql`${enrollment.id} = ${enrollmentIdForTokenHash(tokenHash)}`, - ne(enrollment.status, 'revoked'), - isNull(enrollment.revokedAt) - )} and (exists (select 1 from ${link} where ${and( + ne(enrollment.status, 'revoked') + )} and exists (select 1 from ${link} where ${and( eq(link.tokenHash, tokenHash), eq(link.enrollmentId, enrollment.id), isNull(link.revokedAt), unexpiredLinkCondition(now) - )}) or (${and( - eq(enrollment.invitationTokenHash, tokenHash), - legacyInvitationUnexpiredCondition(now) - )} and not exists (select 1 from ${link} where ${eq(link.tokenHash, tokenHash)}))))` + )}))` } /** Revokes every link into an enrollment; callers hold its lifecycle lock. */ @@ -142,31 +104,6 @@ export async function revokeCredentialGroupEnrollmentLinks( ) } -/** - * Gives the invitation in an enrollment's legacy column a link row when it has none, so that - * overwriting the column does not kill a link the released app emailed during a deploy. A revoked - * enrollment's adopted link is revoked with it. - */ -export async function adoptLegacyInvitationLink( - tx: DbTransaction, - current: EnrollmentRow, - now: Date -): Promise { - if (isUnissuedInvitationTokenHash(current.invitationTokenHash)) return - await tx - .insert(credentialGroupEnrollmentLink) - .values({ - id: generateId(), - enrollmentId: current.id, - tokenHash: current.invitationTokenHash, - purpose: 'email', - expiresAt: current.invitationExpiresAt, - revokedAt: isEnrollmentRevoked(current) ? now : null, - createdAt: current.invitedAt, - }) - .onConflictDoNothing({ target: credentialGroupEnrollmentLink.tokenHash }) -} - /** * Mints a link into an enrollment and returns its bearer token. The caller holds the enrollment's * lifecycle lock and has checked the enrollment may receive one. @@ -181,11 +118,9 @@ export async function insertEnrollmentLink( now: Date /** Defaults to the purpose's lifetime. */ expiresAt?: Date - /** Reuses a token the caller already hashed into the enrollment's legacy column. */ - token?: string } ): Promise<{ token: string; linkId: string; expiresAt: Date }> { - const token = input.token ?? generateId() + const token = generateId() const expiresAt = input.expiresAt ?? new Date( @@ -207,17 +142,14 @@ export async function insertEnrollmentLink( return { token, linkId: link.id, expiresAt } } -/** - * The single account option a link is limited to, or null when the link (or a legacy token with - * no link row) may connect any option. - */ +/** The single account option a link is limited to, or null when it may connect any option. */ export async function getCredentialGroupEnrollmentLinkOptionId( - invitationTokenHash: string + tokenHash: string ): Promise { const [row] = await db .select({ optionId: credentialGroupEnrollmentLink.optionId }) .from(credentialGroupEnrollmentLink) - .where(eq(credentialGroupEnrollmentLink.tokenHash, invitationTokenHash)) + .where(eq(credentialGroupEnrollmentLink.tokenHash, tokenHash)) .limit(1) return row?.optionId ?? null } @@ -239,7 +171,7 @@ interface CredentialGroupEnrollmentLinkRecord { email: string userId: string | null status: EnrollmentRow['status'] - /** The link's purpose; a legacy column value is an emailed link. */ + /** The link's purpose. */ purpose: EnrollmentLinkPurpose /** Past its expiry under {@link unexpiredLinkCondition}. */ expired: boolean @@ -260,8 +192,8 @@ interface CredentialGroupEnrollmentLinkRecord { /** * Reads the enrollment an invitation token names in any state, so the person holding it can be * told why it stopped working. Resolves the token the way {@link liveEnrollmentLinkCondition} - * does (its link row, else the legacy column when no link row carries the hash) without the - * liveness filter. Grants no authority: live-link callers authenticate the token instead. + * does, without the liveness filter. Grants no authority: live-link callers authenticate the + * token instead. */ export async function findCredentialGroupEnrollmentLinkRecord( token: string @@ -275,8 +207,7 @@ export async function findCredentialGroupEnrollmentLinkRecord( email: credentialGroupEnrollment.email, userId: credentialGroupEnrollment.userId, status: credentialGroupEnrollment.status, - revokedAt: credentialGroupEnrollment.revokedAt, - expired: sql`not (case when ${link.id} is null then ${legacyInvitationUnexpiredCondition(now)} else ${unexpiredLinkCondition(now)} end)`, + expired: sql`not ${unexpiredLinkCondition(now)}`, linkPurpose: link.purpose, linkOptionId: link.optionId, linkRevokedAt: link.revokedAt, @@ -291,22 +222,16 @@ export async function findCredentialGroupEnrollmentLinkRecord( }) .from(credentialGroupEnrollment) .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) - .leftJoin( + .innerJoin( link, and(eq(link.enrollmentId, credentialGroupEnrollment.id), eq(link.tokenHash, tokenHash)) ) .leftJoin(workspace, eq(workspace.id, credentialGroup.workspaceId)) .leftJoin(organization, eq(organization.id, credentialGroup.organizationId)) .leftJoin(user, eq(user.id, credentialGroupEnrollment.createdBy)) - .where( - and( - sql`${credentialGroupEnrollment.id} = ${enrollmentIdForTokenHash(tokenHash)}`, - or(isNotNull(link.id), eq(credentialGroupEnrollment.invitationTokenHash, tokenHash)) - ) - ) + .where(sql`${credentialGroupEnrollment.id} = ${enrollmentIdForTokenHash(tokenHash)}`) .limit(1) if (!row || !(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(row)))) return null - const purpose = row.linkPurpose ?? 'email' const focusOption = row.linkOptionId ? row.options.find((option) => option.id === row.linkOptionId) : undefined @@ -314,7 +239,7 @@ export async function findCredentialGroupEnrollmentLinkRecord( email: row.email, userId: row.userId, status: row.status, - purpose, + purpose: row.linkPurpose, expired: row.expired, revoked: isEnrollmentRevoked(row), linkRevoked: row.linkRevokedAt !== null, diff --git a/apps/sim/lib/credential-groups/oauth.test.ts b/apps/sim/lib/credential-groups/oauth.test.ts index 357a426b59e..f4972226b89 100644 --- a/apps/sim/lib/credential-groups/oauth.test.ts +++ b/apps/sim/lib/credential-groups/oauth.test.ts @@ -255,7 +255,7 @@ describe('credential group OAuth persistence', () => { connectedCredentialId: 'credential-1', }) expect(eq).toHaveBeenCalledWith( - schemaMock.credentialGroupEnrollment.invitationTokenHash, + schemaMock.credentialGroupEnrollmentLink.tokenHash, expect.any(String) ) } diff --git a/apps/sim/lib/credentials/managed-oauth.integration.ts b/apps/sim/lib/credentials/managed-oauth.integration.ts index c388ac04517..9e4c6619550 100644 --- a/apps/sim/lib/credentials/managed-oauth.integration.ts +++ b/apps/sim/lib/credentials/managed-oauth.integration.ts @@ -3,6 +3,7 @@ import { credential, credentialGroup, credentialGroupEnrollment, + credentialGroupEnrollmentLink, organization, user, } from '@sim/db/schema' @@ -100,11 +101,17 @@ beforeAll(async () => { userId, email: `${userId}@example.test`, status: 'completed', - invitationTokenHash: sha256Hex(invitationToken), invitationExpiresAt: new Date(Date.now() + 3_600_000), invitedAt: new Date(), createdBy: userId, }) + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId, + tokenHash: sha256Hex(invitationToken), + purpose: 'email', + expiresAt: new Date(Date.now() + 3_600_000), + }) }) beforeEach(async () => { diff --git a/packages/db/migrations/0490_credential_group_connect.sql b/packages/db/migrations/0490_credential_group_connect.sql index be3443637b1..e1fca5fece6 100644 --- a/packages/db/migrations/0490_credential_group_connect.sql +++ b/packages/db/migrations/0490_credential_group_connect.sql @@ -1,14 +1,10 @@ --- Expand: invitation bearer links move to their own table so issuing one never invalidates --- another. credential_group_enrollment.invitation_token_hash stays NOT NULL and the app keeps --- writing it (mirroring the newest link), so the released app and a rollback keep resolving --- invitations through it. Every statement is idempotent: a replay after an earlier migration's --- embedded COMMIT re-runs this file in autocommit. --- Contract, in two later migrations: first make invitation_token_hash nullable and stop writing --- it (enrollments created without an emailed link then store null instead of an 'unissued:' --- placeholder), then drop it with its unique index and length check. +-- Invitation bearer links move to their own table so issuing one never invalidates another. +-- credential_group_enrollment.invitation_token_hash becomes nullable: the app no longer reads or +-- writes it, and a later contract migration drops it. Every statement is idempotent: a replay +-- after an earlier migration's embedded COMMIT re-runs this file in autocommit. -- --- Expand first: two enrollment columns for workflow connection requests (the requesting workflow and --- integration) and its reminder count. Nullable or defaulted, so the released app is unaffected. +-- Two enrollment columns for workflow connection requests (the requesting workflow and +-- integration) and its reminder count. ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "requested_by_workflow_id" text;--> statement-breakpoint ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "requested_provider_id" text;--> statement-breakpoint ALTER TABLE "credential_group_enrollment" ADD COLUMN IF NOT EXISTS "connection_request_reminders" integer DEFAULT 0 NOT NULL;--> statement-breakpoint @@ -32,10 +28,9 @@ CREATE TABLE IF NOT EXISTS "credential_group_enrollment_link" ( CREATE UNIQUE INDEX IF NOT EXISTS "credential_group_enrollment_link_token_hash_unique" ON "credential_group_enrollment_link" USING btree ("token_hash");--> statement-breakpoint CREATE INDEX IF NOT EXISTS "credential_group_enrollment_link_enrollment_id_idx" ON "credential_group_enrollment_link" USING btree ("enrollment_id");--> statement-breakpoint CREATE INDEX IF NOT EXISTS "credential_group_enrollment_link_session_expires_at_idx" ON "credential_group_enrollment_link" USING btree ("expires_at") WHERE "credential_group_enrollment_link"."purpose" in ('self', 'connect');--> statement-breakpoint --- Backfill: each existing enrollment's current invitation becomes its first link. One row per --- enrollment (a small table), and ON CONFLICT on the unique token hash makes a replay a no-op. --- Rows the released app writes after this runs carry no link and resolve through the legacy --- branch of liveEnrollmentLinkCondition until they are reissued. +-- Backfill: each existing enrollment's current invitation becomes its first link, revoked when +-- the enrollment is. One row per enrollment (a small table), and ON CONFLICT on the unique token +-- hash makes a replay a no-op. INSERT INTO "credential_group_enrollment_link" ("id", "enrollment_id", "token_hash", "purpose", "expires_at", "revoked_at", "created_at") SELECT gen_random_uuid()::text, @@ -46,12 +41,12 @@ SELECT COALESCE(e."revoked_at", CASE WHEN e."status" = 'revoked' THEN now() END), e."invited_at" FROM "credential_group_enrollment" e +WHERE e."invitation_token_hash" IS NOT NULL ON CONFLICT ("token_hash") DO NOTHING; --> statement-breakpoint --- Expand: workflow connection requests. A request log the daily cap counts and the admin's request --- policy (the enrollment columns are added at the top of this file). Every --- statement is idempotent: a replay after an earlier migration's embedded COMMIT re-runs this --- file in autocommit. +ALTER TABLE "credential_group_enrollment" ALTER COLUMN "invitation_token_hash" DROP NOT NULL;--> statement-breakpoint +-- Workflow connection requests: a request log the daily cap counts and the admin's request +-- policy (the enrollment columns are added at the top of this file). CREATE TABLE IF NOT EXISTS "credential_group_connection_request" ( "id" text PRIMARY KEY NOT NULL, "credential_group_id" text NOT NULL, diff --git a/packages/db/migrations/meta/0490_snapshot.json b/packages/db/migrations/meta/0490_snapshot.json index b8a2825b624..387bb4a556b 100644 --- a/packages/db/migrations/meta/0490_snapshot.json +++ b/packages/db/migrations/meta/0490_snapshot.json @@ -5716,7 +5716,7 @@ "name": "invitation_token_hash", "type": "text", "primaryKey": false, - "notNull": true + "notNull": false }, "invitation_expires_at": { "name": "invitation_expires_at", diff --git a/packages/db/schema.ts b/packages/db/schema.ts index c8e40a06d46..b5891f92384 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7452,13 +7452,11 @@ export const credentialGroupEnrollment = pgTable( userId: text('user_id').references(() => user.id, { onDelete: 'cascade' }), status: credentialGroupEnrollmentStatusEnum('status').notNull().default('invited'), /** - * Mirrors the newest `credential_group_enrollment_link` so a rollback to the pre-link app - * still resolves invitations. contract-pending(after the enrollment-link expand is fully - * deployed and no rollback target predates it): retire this column with its unique index, - * length check, and the legacy branch of `liveEnrollmentLinkCondition` — once deployed, every - * invitation resolves through the link table. + * @deprecated Unused: invitation tokens live in `credential_group_enrollment_link`, and the app + * neither reads nor writes this column. Scheduled for removal, with its unique index and + * length check, in its own contract migration. */ - invitationTokenHash: text('invitation_token_hash').notNull(), + invitationTokenHash: text('invitation_token_hash'), /** * When an unbound enrollment stops waiting for its person. An admin's invitation or reminder, * or a workflow's request or reminder, renews it; a bound enrollment never expires. From 26e3896cbb4ffc881cea47f2a9b304b07197bf44 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 17:23:12 -0600 Subject: [PATCH 21/26] fix(credential-groups): harden connect flow, people status, and request cap - Refuse every workflow connection request once the daily cap is reached, repeats included, so the cap reveals nothing about other workspaces. - Re-check membership, Integrations capability and setup inside the link transaction for self-enrollment and expired-request renewal. - Spend the per-person connect budget only on the Connect POST; the page keeps its per-IP limit. - Send malformed and cross-origin Connect POSTs back to the connect page (unavailable / try again) instead of JSON. - Add an already_connected outcome to the connect page so a connected person is not sent through consent again; needs-reauth still connects. - People: expose `bound` (drop `emailed`, derived from sentAt), rework the status order, label "Send email" before any email, surface per-email re-invite failures; policy row explains "Not in effect" and Save shows why it is disabled. - Connect/enroll/complete pages: recovery stays primary beside Return to Slack, "You can close this tab." only once connected, no Open Sim on a focused connect link, Slack return kept on early states, clearer expired copy; one slackHref vocabulary. - Block and refusal copy name the integration; scripts stop writing invitation_token_hash; docs and README match. --- .../docs/workflows/blocks/credential.mdx | 4 +- .../connect/[publicId]/route.test.ts | 37 ++++++-- .../connect/[publicId]/route.ts | 25 +++-- .../[publicId]/connect/page.tsx | 42 ++++++--- .../complete/completion-view.ts | 39 +++++--- .../app/credential-groups/complete/page.tsx | 30 +++--- .../credential-groups/enroll/[token]/page.tsx | 34 ++++--- .../sim/app/credential-groups/link-states.tsx | 71 +++++++++++--- apps/sim/blocks/blocks/credential.ts | 2 +- .../organization-account-people.tsx | 23 +++-- .../organization-connection-requests.tsx | 15 ++- .../lib/api/contracts/credential-groups.ts | 4 +- apps/sim/lib/credential-groups/README.md | 6 +- .../connect-target.integration.ts | 93 +++++++++++++++++-- .../enrollment-links.integration.ts | 4 +- .../slack-return.integration.ts | 4 +- ...orkflow-connection-requests.integration.ts | 31 ++++--- .../application/connect-target.ts | 55 ++++++++--- .../application/connection-requests.ts | 15 ++- .../lib/credential-groups/connect-session.ts | 10 +- .../lib/credential-groups/connect-subject.ts | 61 ++++++++++-- .../connection-request-policy.ts | 10 +- .../credential-groups/connection-requests.ts | 29 +++--- apps/sim/lib/credential-groups/enrollments.ts | 2 +- apps/sim/lib/credential-groups/rate-limit.ts | 7 +- .../scripts/migrate-gitlab-personal-tokens.ts | 2 - .../sim/scripts/test-assistant-actions-e2e.ts | 4 +- 27 files changed, 475 insertions(+), 184 deletions(-) diff --git a/apps/docs/content/docs/workflows/blocks/credential.mdx b/apps/docs/content/docs/workflows/blocks/credential.mdx index 497d8fa139a..7b0143cc273 100644 --- a/apps/docs/content/docs/workflows/blocks/credential.mdx +++ b/apps/docs/content/docs/workflows/blocks/credential.mdx @@ -105,11 +105,11 @@ The status never says whether the person was invited, removed, or never asked. ` A `connectUrl` from Get Connection Status alone works only for members of your organization. Anyone else must be asked first, by **Request Connection** or by an admin in **People**; otherwise the page tells them no connection was requested. So when `connected` is false, call **Request Connection** first, then show `connectUrl`. -Set **Return to** to **Slack** when the person starts in Slack: once their account is connected, the page offers a **Return to Slack** button. It opens the Slack app, so someone using Slack in a browser instead closes the tab, and the page says so. With **None** the page tells them they can close the tab. +Set **Return to** to **Slack** when the person starts in Slack: once their account is connected, the page offers a **Return to Slack** button. It opens the Slack app, so someone using Slack in a browser instead closes the tab, and the page says so. With **None** the page tells them they can close the tab. Someone who opens the link again after connecting is told the account is already connected. **Request Connection** returns `requested` and `connectUrl`. It works only when an admin turns on **Allow workflow requests** under **Workflow connection requests** in **Settings → Credential Groups → Access**, for the workflow's workspace, the person's email domain, and the integration. That setting is the only gate: any run of the workflow can request a connection, including a manual run by a workspace member with read access. A request outside those settings, or past the daily limit, fails with an error. Otherwise the result is the same whether the person was already asked, already connected, or removed; a removed person is never re-invited. Use the person's primary address: an address with a `+` alias is refused. -The daily limit counts each new person asked per day, across all workspaces; asking again for someone already asked that day does not count. A request the person has not accepted expires after 7 days; asking again renews it. +The daily limit counts each new person asked per day, across all workspaces; below the limit, asking again for someone already asked that day does not count. Once the limit is reached, every request fails, including one for someone already asked that day. A request the person has not accepted expires after 7 days; asking again renews it. Sim emails the person only when the admin turned on **Also email the person**. The email carries the link and the workflow's name. Sim sends up to 3 reminders, each only when a workflow asks again after a day with no request for that person, and none after 30 days. Runs from the workflow editor are real: they send real emails and count toward the daily limit. diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts index 83b67ac4b65..e73e836b762 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts @@ -2,12 +2,13 @@ * The connect page's Connect POST enrolls or binds the signed-in person and mints their link, so * it must only act on a request a page on this origin sent, by a verified person within their * rate limit. Failure modes: a cross-site form post, a post from another origin whose browser - * sends no `Sec-Fetch-Site`, a client that sends neither header, a signed-out or unverified - * session, a person over their limit, a limiter outage, and a start that ends anywhere but - * started. Each leaves the person untouched and goes back to the connect page (with `error` for a - * limit or an outage), never to raw JSON; a started connection goes straight to the provider's - * OAuth start without leaking the minted link through a cache or a Referer. No GET handler exists, - * so a link click or prefetch never starts anything. + * sends no `Sec-Fetch-Site`, a client that sends neither header, a malformed query, a signed-out + * or unverified session, a person over their limit, a limiter outage, and a start that ends + * anywhere but started. Each leaves the person untouched and goes back to the connect page (with + * `error` for a malformed or cross-origin request, a limit or an outage), never to raw JSON; a + * started connection goes straight to the provider's OAuth start without leaking the minted link + * through a cache or a Referer. No GET handler exists, so a link click or prefetch never starts + * anything. */ import { authMockFns } from '@sim/testing/mocks/auth.mock' import { createMockRequest } from '@sim/testing/mocks/request.mock' @@ -32,11 +33,14 @@ import * as connectRoute from '@/app/api/credential-groups/connect/[publicId]/ro const CONNECT_PATH = '/credential-groups/public-1/connect?provider=google-drive&return=slack' -function confirm(headers: Record = { 'sec-fetch-site': 'same-origin' }) { +function confirm( + headers: Record = { 'sec-fetch-site': 'same-origin' }, + query = 'provider=google-drive&return=slack' +) { return connectRoute.POST( createMockRequest({ method: 'POST', - url: 'http://localhost:3000/api/credential-groups/connect/public-1?provider=google-drive&return=slack', + url: `http://localhost:3000/api/credential-groups/connect/public-1?${query}`, headers, }), { params: Promise.resolve({ publicId: 'public-1' }) } @@ -58,10 +62,23 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { ['a same-site sibling origin', { 'sec-fetch-site': 'same-site' }], ['another origin with no Sec-Fetch-Site', { origin: 'https://attacker.example' }], ['a client sending neither header', {}], - ])('refuses %s without enrolling anyone', async (_label, headers) => { + ])('sends %s back to try again, without enrolling anyone', async (_label, headers) => { const response = await confirm(headers) expect(response.status).toBe(303) - expect(response.headers.get('location')).toBe(CONNECT_PATH) + expect(response.headers.get('location')).toBe(`${CONNECT_PATH}&error=try_again`) + expect(mockStart).not.toHaveBeenCalled() + }) + + it.each([ + ['no provider', 'return=slack'], + ['an oversized option', `provider=google-drive&optionId=${'x'.repeat(200)}&return=slack`], + ])('sends a request with %s back as unavailable, never as JSON', async (_label, query) => { + const response = await confirm(undefined, query) + expect(response.status).toBe(303) + expect(response.headers.get('location')).toBe( + '/credential-groups/public-1/connect?error=unavailable&return=slack' + ) + expect(mockUserRateLimit).not.toHaveBeenCalled() expect(mockStart).not.toHaveBeenCalled() }) diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts index eaf8dc8b064..a5cf8736412 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts @@ -4,11 +4,13 @@ import { parseRequest } from '@/lib/api/server' import { isSameOriginSessionRequest } from '@/lib/core/security/same-origin' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' +import { parseConnectReturnDestination } from '@/lib/credential-groups/connect-return' import { resolveCredentialGroupConnectSession } from '@/lib/credential-groups/connect-session' import { buildCredentialGroupConnectOAuthStartPath, buildCredentialGroupConnectPath, } from '@/lib/credential-groups/connect-url' +import { checkCredentialGroupConnectUserRateLimit } from '@/lib/credential-groups/rate-limit' import { createNoStoreRedirect } from '@/app/api/credential-groups/enrollment-redirect' export const dynamic = 'force-dynamic' @@ -17,13 +19,23 @@ export const runtime = 'nodejs' /** * The connect page's Connect button. Enrolls or binds the person and mints their focused link in * one transaction, then goes straight to the provider's OAuth start for that option. Anything - * else goes back to the connect page (a refusal it explains itself, or `error` for a limit or an - * outage), so this route never renders a state of its own. + * else goes back to the connect page (a refusal it explains itself, or `error` for a malformed + * request, a request from another origin, a limit or an outage), so this route never renders a + * state of its own. Only this write spends the person's connect budget. */ export const POST = withRouteHandler( async (request: NextRequest, context: { params: Promise<{ publicId: string }> }) => { const parsed = await parseRequest(startCredentialGroupConnectContract, request, context) - if (!parsed.success) return parsed.response + if (!parsed.success) { + const { publicId } = await context.params + const query = new URLSearchParams({ error: 'unavailable' }) + const returnTo = parseConnectReturnDestination(request.nextUrl.searchParams.get('return')) + if (returnTo) query.set('return', returnTo) + return createNoStoreRedirect( + `/credential-groups/${encodeURIComponent(publicId)}/connect?${query}`, + 303 + ) + } const { publicId } = parsed.data.params const { provider, optionId, for: requestHandle, return: returnTo } = parsed.data.query const backToConnect = (error?: 'rate_limited' | 'try_again') => { @@ -36,12 +48,13 @@ export const POST = withRouteHandler( }) return createNoStoreRedirect(error ? `${path}&error=${error}` : path, 303) } - if (!isSameOriginSessionRequest(request)) return backToConnect() + if (!isSameOriginSessionRequest(request)) return backToConnect('try_again') const session = await resolveCredentialGroupConnectSession() - if (session.kind === 'rate_limited' || session.kind === 'try_again') - return backToConnect(session.kind) if (session.kind !== 'signed_in') return backToConnect() + const limit = await checkCredentialGroupConnectUserRateLimit(session.principal.userId) + if (limit === 'limited') return backToConnect('rate_limited') + if (limit === 'unavailable') return backToConnect('try_again') const started = await startCredentialGroupConnect.execute({ principal: session.principal, diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index fd30dba9ec0..0e665137143 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -11,6 +11,7 @@ import { buildCredentialGroupConnectPath } from '@/lib/credential-groups/connect import { getCredentialGroupProviderService } from '@/lib/credential-groups/providers' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' import { + AlreadyConnected, ChooseConnectOption, ConnectConfirm, DifferentEmail, @@ -52,9 +53,10 @@ const TRY_AGAIN_MESSAGE = 'Something went wrong. Try again in a moment.' /** * The secret-free link a workflow shows when someone has not connected an account yet. Signs the - * person in and shows what the link will do for them; it writes nothing. Its one Connect button - * POSTs to the start route, which enrolls or binds the person, mints their focused link, and goes - * on to the provider. Link unfurlers and prefetchers only GET, so they never enroll anyone. + * person in and shows what the link will do for them, or that their account is already + * connected; it writes nothing. Its one Connect button POSTs to the start route, which enrolls or + * binds the person, mints their focused link, and goes on to the provider. Link unfurlers and + * prefetchers only GET, so they never enroll anyone. */ export default async function CredentialGroupConnectPage({ params, @@ -81,7 +83,14 @@ export default async function CredentialGroupConnectPage({ slackHref={slackHref} /> ) - if (!publicId || publicId.length > 128 || !provider || provider.length > 128) return unavailable + if ( + startError === 'unavailable' || + !publicId || + publicId.length > 128 || + !provider || + provider.length > 128 + ) + return unavailable const linkPath = (overrides: { optionId?: string } = {}) => buildCredentialGroupConnectPath({ @@ -97,8 +106,13 @@ export default async function CredentialGroupConnectPage({ + ) + const verifyEmail = ( + ) @@ -108,11 +122,7 @@ export default async function CredentialGroupConnectPage({ case 'sign_in': return redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) case 'verify_email': - return - case 'rate_limited': - return - case 'try_again': - return tryAgain + return verifyEmail } if (startError === 'rate_limited') return @@ -142,8 +152,16 @@ export default async function CredentialGroupConnectPage({ /> ) } + case 'already_connected': + return ( + + ) case 'verify_email': - return + return verifyEmail case 'different_email': return ( - {integrationsHref ? (error ? 'Try again' : 'Return to Integrations') : 'Open Sim'} - - ) : null + // failure, Integrations is where the connection started, so it is the way to try again; with + // nowhere to retry, Open Sim is offered unless Slack is where the person came from. + const appLink = integrationsHref ? ( + + {error ? 'Try again' : 'Return to Integrations'} + + ) : error && !slackHref ? ( + Open Sim + ) : null return ( {completionId && ( @@ -52,17 +51,18 @@ export default async function CredentialGroupCompletePage({ title={error ? 'Account not connected' : 'Accounts connected'} description={ error ?? - (slackReturnHref + (slackHref ? 'Return to Slack to continue.' : integrationsHref ? 'Returning to Integrations.' : 'Your accounts are ready to use. You can close this tab.') } /> - {(appLink || slackReturnHref) && ( + {(appLink || slackHref) && ( {appLink} diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index e03950c28b5..af21660c98f 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -117,7 +117,10 @@ function EnrollmentLinkProblem({
- + + if (limited) return - if (!token || token.length > 128) return - const resolvedSearchParams = await searchParams - const rawReturn = getSearchParam(resolvedSearchParams, 'return') - const returnTo = parseConnectReturnDestination(rawReturn) - const slackHref = returnTo ? connectReturnHref(returnTo) : undefined + if (!token || token.length > 128) + return const callback = new URLSearchParams() for (const key of ['origin', 'optionId']) { const value = getSearchParam(resolvedSearchParams, key) @@ -230,8 +233,11 @@ export default async function CredentialGroupEnrollmentPage({ ) const explainLinkProblem = async (fallbackMessage?: string) => ( @@ -346,6 +352,8 @@ export default async function CredentialGroupEnrollmentPage({ focusedAccounts.length > 0 && focusedAccounts.every((connection) => connection.status === 'connected') && (originIsSearch || focusedOrigin === 'connect' || connectedOptionId === focusedOption.id) + // A connect link opened outside Slack has nowhere to send the person back: they close the tab. + const fromConnectWithoutReturn = focusedOrigin === 'connect' && !slackHref const connectedOption = connectedOptionId ? activeOptions.find((option) => option.id === connectedOptionId) : undefined @@ -393,7 +401,9 @@ export default async function CredentialGroupEnrollmentPage({ } description={ focused - ? `${focusedConnected ? 'Your account is connected for' : 'Connect your account for'} ${enrollment.workspaceName}.` + ? focusedConnected + ? `Your account is connected for ${enrollment.workspaceName}.${fromConnectWithoutReturn ? ' You can close this tab.' : ''}` + : `Connect your account for ${enrollment.workspaceName}.` : `${enrollment.inviterName ? `${enrollment.inviterName} invited you` : 'You have been invited'} to connect accounts for ${enrollment.workspaceName}.` } /> @@ -467,11 +477,11 @@ export default async function CredentialGroupEnrollmentPage({ {focused ? ( - {!slackHref && ( + {!slackHref && focusedOrigin !== 'connect' && ( {returnLabel} diff --git a/apps/sim/app/credential-groups/link-states.tsx b/apps/sim/app/credential-groups/link-states.tsx index df0d4abf308..35c04dd2056 100644 --- a/apps/sim/app/credential-groups/link-states.tsx +++ b/apps/sim/app/credential-groups/link-states.tsx @@ -23,6 +23,8 @@ interface CredentialGroupLinkActionsProps { slackHref?: string /** Makes "Return to Slack" the primary action, for a page with nothing left to do. */ slackPrimary?: boolean + /** The account is connected: "Return to Slack" is primary and the tab may be closed. */ + connected?: boolean align?: 'center' | 'end' className?: string children?: ReactNode @@ -30,11 +32,13 @@ interface CredentialGroupLinkActionsProps { /** * The action row of a connect page. "Return to Slack" opens the Slack app, which does nothing - * for someone using Slack in a browser, so it always comes with "You can close this tab." + * for someone using Slack in a browser, so once the account is connected it comes with "You can + * close this tab." */ export function CredentialGroupLinkActions({ slackHref, slackPrimary = false, + connected = false, align = 'center', className, children, @@ -49,13 +53,13 @@ export function CredentialGroupLinkActions({ >
{slackHref && ( - + Return to Slack )} {children}
- {slackHref && ( + {slackHref && connected && (

You can close this tab.

)}
@@ -69,20 +73,19 @@ interface UnavailableInvitationProps { rateLimited?: boolean /** The line under the title; `null` when the title says it all. */ message?: string | null - recoveryHref?: string - recoveryLabel?: string - /** Offered instead of the recovery link when the person came from Slack. */ + /** A way forward (Try again, Verify email), shown as the primary action. */ + recovery?: { href: string; label: string } + /** Return to Slack: secondary to a recovery, else the way out in place of Open Sim. */ slackHref?: string } -/** A terminal state with a title, one line of copy, and one way out. */ +/** A state with a title, one line of copy, and a way forward or out. */ export function UnavailableInvitation({ token, title, rateLimited = false, message, - recoveryHref = APP_ENTRY_PATH, - recoveryLabel = 'Open Sim', + recovery, slackHref, }: UnavailableInvitationProps) { return ( @@ -100,8 +103,18 @@ export function UnavailableInvitation({ : 'Sign in with the account this invitation was sent to. If the link has expired, ask an organization admin for a new invitation.')) } /> - - {!slackHref && {recoveryLabel}} + + {recovery ? ( + + {recovery.label} + + ) : ( + !slackHref && Open Sim + )}
@@ -214,20 +227,50 @@ export function RequestExpired({ organizationName, slackHref }: RequestExpiredPr } interface VerifyEmailProps { + token?: string verifyHref: string + slackHref?: string } -export function VerifyEmail({ verifyHref }: VerifyEmailProps) { +export function VerifyEmail({ token, verifyHref, slackHref }: VerifyEmailProps) { return ( ) } +interface AlreadyConnectedProps { + integration: string + organizationName: string + slackHref?: string +} + +/** The person's account for this integration is already connected; nothing is asked of them. */ +export function AlreadyConnected({ + integration, + organizationName, + slackHref, +}: AlreadyConnectedProps) { + return ( + +
+ + {slackHref && ( + + )} +
+
+ ) +} + interface ConnectConfirmProps { integration: string organizationName: string diff --git a/apps/sim/blocks/blocks/credential.ts b/apps/sim/blocks/blocks/credential.ts index d233b7d7a85..827f7ec8c92 100644 --- a/apps/sim/blocks/blocks/credential.ts +++ b/apps/sim/blocks/blocks/credential.ts @@ -260,7 +260,7 @@ export const CredentialBlock: BlockConfig = { }, requested: { type: 'boolean', - description: 'Always true once the request is accepted, whatever the person has done before', + description: 'Always true when the request succeeds, whatever the person has done before', condition: { field: 'operation', value: 'request_connection' }, }, displayName: { diff --git a/apps/sim/ee/credential-groups/components/organization-account-people.tsx b/apps/sim/ee/credential-groups/components/organization-account-people.tsx index 26fdf3a542c..23baaec89e0 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-people.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-people.tsx @@ -50,9 +50,10 @@ type PersonStatus = keyof typeof PERSON_STATUS_BADGES /** * Collapses an enrollment and its connections into the one status an admin * acts on. A broken connection outranks a working one so it is never hidden. - * A request nobody has accepted yet is Expired once past its expiry (the same - * `expired` the connect page refuses on), Requested when Sim never emailed it, - * and Invited otherwise; once accepted, it is Not connected until an account is. + * Once the person accepted (the enrollment is bound or has progressed), it is + * Not connected until an account is. A request nobody accepted is Expired past + * its expiry (the same `expired` the connect page refuses on), Invited once Sim + * emailed it, Requested when only a workflow asked, and Not connected otherwise. */ function getPersonStatus(person: CredentialGroupEnrollmentDetail): PersonStatus { if (person.status === 'revoked') return 'revoked' @@ -62,9 +63,12 @@ function getPersonStatus(person: CredentialGroupEnrollmentDetail): PersonStatus return 'needs_reconnect' } if (connections.some((connection) => connection.status === 'active')) return 'connected' - if (person.status !== 'invited') return 'not_connected' + if (person.status === 'in_progress' || person.status === 'completed' || person.bound) { + return 'not_connected' + } if (person.expired) return 'expired' - return person.emailed ? 'invited' : 'requested' + if (person.sentAt) return 'invited' + return person.requestedByWorkflow ? 'requested' : 'not_connected' } /** Whether some account the group collects is still missing for this person. */ @@ -174,7 +178,12 @@ export function OrganizationAccountPeople({ organizationId }: OrganizationAccoun onSelect: () => reinvite.mutate( { organizationId, emails: [person.email] }, - { onSuccess: () => toast.success('Invitation sent') } + { + onSuccess: ({ results: [result] }) => { + if (result && !result.success) toast.error(result.error) + else toast.success('Invitation sent') + }, + } ), }, ] @@ -182,7 +191,7 @@ export function OrganizationAccountPeople({ organizationId }: OrganizationAccoun ...(remindable ? [ { - label: 'Send reminder', + label: person.sentAt ? 'Send reminder' : 'Send email', disabled: pending, onSelect: () => resend.mutate( diff --git a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx index 802a9c1ee9d..b5d0778355e 100644 --- a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx +++ b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx @@ -118,7 +118,13 @@ export function OrganizationConnectionRequests({ {TOGGLE_LABEL}} - description={policy ? summarize(policy) : undefined} + description={ + policy + ? policy.enabled && !inEffect + ? `${summarize(policy)} · No chosen workspace can use a chosen integration on Access` + : summarize(policy) + : undefined + } badge={ policy?.enabled && !inEffect ? ( @@ -204,7 +210,9 @@ function ConnectionRequestPolicyModal({ sendEmail, } // Held to the rules of an enabled policy either way, so a saved draft can be turned on. - const valid = canEnable(draft) + const invalidReason = limitValid + ? connectionRequestPolicySchema.safeParse({ ...draft, enabled: true }).error?.issues[0]?.message + : 'Enter a valid daily limit' return ( onSave(draft), }} /> diff --git a/apps/sim/lib/api/contracts/credential-groups.ts b/apps/sim/lib/api/contracts/credential-groups.ts index 68eeeee699d..8106a6f55c2 100644 --- a/apps/sim/lib/api/contracts/credential-groups.ts +++ b/apps/sim/lib/api/contracts/credential-groups.ts @@ -139,8 +139,8 @@ export const credentialGroupEnrollmentMcpConnectionSchema = z.object({ export const credentialGroupEnrollmentDetailSchema = credentialGroupEnrollmentSchema.extend({ /** A workflow asked this person to connect, rather than an admin. */ requestedByWorkflow: z.boolean(), - /** Sim emailed this person a request at least once. */ - emailed: z.boolean(), + /** The person accepted: the enrollment is bound to their Sim account. */ + bound: z.boolean(), connections: z .array(credentialGroupEnrollmentConnectionSchema) .max((CREDENTIAL_GROUP_PROVIDER_IDS.length + 1) * 3), diff --git a/apps/sim/lib/credential-groups/README.md b/apps/sim/lib/credential-groups/README.md index f6e5a60b4b3..d4bc197070d 100644 --- a/apps/sim/lib/credential-groups/README.md +++ b/apps/sim/lib/credential-groups/README.md @@ -84,15 +84,15 @@ Revoking an enrollment sets its status to `revoked` and revokes all of its links ## Connect URL -A workflow's `connectUrl` is `/credential-groups//connect?provider=`, plus `for=` when it was built for one person (a keyed hash of the group and their address) and `return=slack` when the workflow asked to send the person back to Slack. It carries no secret. Opening it only reads (`openCredentialGroupConnect`); its one Connect button is a same-origin POST (`startCredentialGroupConnect`) that, in one transaction, enrolls a member enrolling themselves, binds the person to the enrollment requested at their verified address, and mints a one-hour `connect` link, then goes straight to the provider. A link whose `for` names someone else says so without revealing the address and never offers self-enrollment. +A workflow's `connectUrl` is `/credential-groups//connect?provider=`, plus `for=` when it was built for one person (a keyed hash of the group and their address) and `return=slack` when the workflow asked to send the person back to Slack. It carries no secret. Opening it only reads (`openCredentialGroupConnect`); its one Connect button is a same-origin POST (`startCredentialGroupConnect`) that, in one transaction, enrolls a member enrolling themselves, binds the person to the enrollment requested at their verified address, and mints a one-hour `connect` link, then goes straight to the provider. A link whose `for` names someone else says so without revealing the address and never offers self-enrollment. A person whose enrollment already holds an active account for the option is told it is already connected instead of being sent through consent again; an account that needs reconnecting is offered the Connect button. Opening the page is rate limited per IP; only the POST spends the person's own connect budget. The POST re-checks a self-enrolling member's membership, Integrations capability and setup inside its transaction. An unbound enrollment is a request that waits seven days (`invitation_expires_at`); after that the connect page refuses it as expired and People shows Expired, both through `isEnrollmentRequestExpired`. A workflow asking again, a workflow reminder, and an admin's reminder or invitation renew it. A bound enrollment never expires. A connection made through a connect link completes the enrollment when the request is done: a workflow's request after its one integration, anyone else once every active option is connected. -`return=slack` is the only return destination (`ConnectReturnDestination`). It travels through the OAuth attempt and is rendered as "Return to Slack" (`slack://open`) with "You can close this tab." A forged one can at most open the Slack app. +`return=slack` is the only return destination (`ConnectReturnDestination`). It travels through the OAuth attempt and is rendered as "Return to Slack" (`slack://open`), with "You can close this tab." once the account is connected. A forged one can at most open the Slack app. On a deployment that cannot verify email (verification off, or no mail provider), a signed-in user's address is taken as verified for claiming an enrollment. -The daily request limit counts distinct addresses per group per day; asking again for an address already asked today is neither logged nor counted. +The daily request limit counts distinct addresses per group per day; below it, asking again for an address already asked today is neither logged nor counted. Once it is reached every request is refused with the same error, a repeat included, so the result says nothing about what other workspaces asked. ## Rollout diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index 6e7d551780a..d684d1b0035 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -5,14 +5,16 @@ * option, one hour, enrollment fields untouched but the binding), a page load that would write, an * enrollment bound to someone else, an unverified session (and a deployment that cannot verify * email), a link made for another address, a revoked enrollment, an expired request (and a bound - * one, which never expires, and a member's own expired request, renewed by the start), a stranger, an organization member with no enrollment (enrolled only - * by the start), a member the Integrations permission group or an unfinished setup keeps from - * self-enrolling, a revocation landing while a member self-enrolls, a disabled group or unknown - * provider (indistinguishable from an unknown public ID), a provider with two options, a focused - * link used for another option, an MCP server or Submit, and the saved connection completing the - * enrollment exactly when the request is done. Only email delivery, the provider code exchange, - * the workflow trigger fan-out, and the Enterprise entitlement that turns permission groups on are - * faked. + * one, which never expires, and a member's own expired request, renewed by the start), a stranger, + * an organization member with no enrollment (enrolled only by the start), a member the + * Integrations permission group or an unfinished setup keeps from self-enrolling, a revocation + * landing while a member self-enrolls, a member removed from the organization between the page's + * checks and the start's transaction, a disabled group or unknown provider (indistinguishable from + * an unknown public ID), a provider with two options, a focused link used for another option, an + * MCP server or Submit, the saved connection completing the enrollment exactly when the request is + * done, and a link opened again after connecting running the provider's consent again (unless the + * account needs reconnecting). Only email delivery, the provider code exchange, the workflow + * trigger fan-out, and the Enterprise entitlement that turns permission groups on are faked. */ import type { CredentialGroupEnrollmentPrincipal } from '@sim/auth/principal' import { db, runOutsideTransactionContext } from '@sim/db' @@ -482,8 +484,13 @@ describe('the connect URL', () => { ) const { enrollments } = await listCredentialGroupEnrollments(fixture.scope, fixture.groupId, 10) expect( - Object.fromEntries(enrollments.map((enrollment) => [enrollment.email, enrollment.expired])) - ).toEqual({ [person.email]: true, [bound.email]: false }) + Object.fromEntries( + enrollments.map(({ email, expired, bound }) => [email, { expired, bound }]) + ) + ).toEqual({ + [person.email]: { expired: true, bound: false }, + [bound.email]: { expired: false, bound: true }, + }) }) it('offers a member their expired request as self-enrollment and renews it when they start', async () => { @@ -617,6 +624,41 @@ describe('the connect URL', () => { expect(await connectLinksIn(fixture.groupId)).toHaveLength(0) }) + it('refuses to enroll or renew for a member removed from the organization while they start', async () => { + const fixture = await createOrganization() + const joiner = await createPerson() + const renewer = await createPerson() + await addMember(fixture, joiner.userId) + await addMember(fixture, renewer.userId) + await invite(fixture, renewer.email) + await db + .update(credentialGroupEnrollment) + .set({ invitationExpiresAt: new Date(Date.now() - HOUR_MS) }) + .where(eq(credentialGroupEnrollment.email, renewer.email)) + const expired = await enrollmentOf(fixture.groupId, renewer.email) + + for (const person of [joiner, renewer]) { + const { pending } = await db.transaction(async (tx) => { + await tx + .delete(member) + .where( + and(eq(member.organizationId, fixture.organizationId), eq(member.userId, person.userId)) + ) + const [holder] = await tx.execute<{ pid: number }>(sql`SELECT pg_backend_pid() AS pid`) + if (!holder) throw new Error('No backend pid') + const pending = runOutsideTransactionContext(() => + startTarget(person.userId, { publicId: fixture.publicId }) + ) + await runOutsideTransactionContext(() => waitForBlockedBy(holder.pid)) + return { pending } + }) + await expect(pending).resolves.toEqual({ kind: 'unavailable' }) + } + + expect(await enrollmentsIn(fixture.groupId)).toEqual([expired]) + expect(await connectLinksIn(fixture.groupId)).toHaveLength(0) + }) + it('answers a disabled group, an unoffered provider and an unknown ID identically', async () => { const fixture = await createOrganization() const disabled = await createOrganization() @@ -808,6 +850,37 @@ describe('a focused connect link', () => { ).toHaveLength(1) }) + it('tells a connected person so on a second open, but offers a reconnect once the account needs one', async () => { + const fixture = await createOrganization() + const person = await createPerson() + await invite(fixture, person.email) + const token = await readyToken(person.userId, { publicId: fixture.publicId }) + const principal = await principalFor(token, person.userId) + await completePublicCredentialGroupOAuth.execute({ + principal, + input: { attempt: attemptFor(fixture, principal, token, DRIVE.id), code: 'live@drive.test' }, + }) + const linksBefore = await connectLinksIn(fixture.groupId) + + await expect(openTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'already_connected', + organizationName: 'Acme', + provider: 'google-drive', + }) + expect(await connectLinksIn(fixture.groupId)).toEqual(linksBefore) + + await db + .update(credential) + .set({ managedOauthStatus: 'needs_reauth' }) + .where(eq(credential.organizationId, fixture.organizationId)) + await expect(openTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'ready_to_connect', + organizationName: 'Acme', + provider: 'google-drive', + optionId: DRIVE.id, + }) + }) + it("keeps an admin's request open while other options lack a connection, but finishes a workflow's", async () => { const fixture = await createOrganization([ driveOption('drive-work', 'Work Drive'), diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts index e29114034f1..c345151d90a 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts @@ -414,7 +414,7 @@ describe('credential group enrollment links', () => { const person = await createPerson() const emailed = await adminInvite(person.email) const identity = await identityOf(emailed.token) - /** The status alone decides revocation, so the links are left unrevoked here. */ + // The status alone decides revocation, so the links are left unrevoked here. await db .update(credentialGroupEnrollment) .set({ status: 'revoked' }) @@ -486,7 +486,7 @@ describe('credential group enrollment links', () => { const revoked = await createPerson() const revokedInvite = await adminInvite(revoked.email) const identity = await identityOf(revokedInvite.token) - /** The status alone decides revocation, so its link is left unrevoked here. */ + // The status alone decides revocation, so its link is left unrevoked here. await db .update(credentialGroupEnrollment) .set({ status: 'revoked' }) diff --git a/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts b/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts index 18ad7d61960..10386961504 100644 --- a/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts @@ -56,12 +56,12 @@ describe('Slack return destination', () => { it('offers only the Slack app, and tells an expired attempt to go back to Slack', () => { expect( - resolveCredentialGroupCompletionView({ return: 'https://evil.example' }).slackReturnHref + resolveCredentialGroupCompletionView({ return: 'https://evil.example' }).slackHref ).toBeUndefined() expect(resolveCredentialGroupCompletionView({ oauth: 'expired', return: 'slack' })).toEqual({ failure: 'expired', error: 'This connection attempt expired. Go back to Slack and tap Connect again.', - slackReturnHref: 'slack://open', + slackHref: 'slack://open', }) }) }) diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index 69040070995..c89d8f4d717 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -5,17 +5,18 @@ * * Failure modes: a workflow learning more than connected / not_connected / needs_reconnect; a * workspace outside the Access allowlist reading status; another organization's accounts leaking - * in; a request without (or outside) the admin policy succeeding; a request reactivating a - * revoked person or re-attributing an admin invitation; concurrent requests creating two rows; - * the daily cap being exceeded, or skipped for an address that already has an enrollment; the cap - * error differing by target; a `+` alias slipping in; reminders beyond the per-enrollment cap or - * after 30 days; a revocation racing a reminder still emailing; an admin unable to turn requests - * off after their choices went stale; saving either the request policy or Access changing the - * other; a request's placeholder invitation being adopted as a link by a later admin invite; an - * admin's reinvitation leaving the workflow's reminders running; the emailed link not opening the - * requested enrollment on the connect page; the requesting workflow's name reaching the email - * subject, or reaching the body uncleaned; a failed delivery not showing as Email failed; and an - * email still going out, or its outcome overwriting the enrollment, after an admin reinvited. + * in; a request without (or outside) the admin policy succeeding; a request reactivating a revoked + * person or re-attributing an admin invitation; concurrent requests creating two rows; the daily + * cap being exceeded, or skipped for an address that already has an enrollment; the cap error + * differing by target, or a repeat for an address asked today passing once the cap is hit; a `+` + * alias slipping in; reminders beyond the per-enrollment cap or after 30 days; a revocation racing + * a reminder still emailing; an admin unable to turn requests off after their choices went stale; + * saving either the request policy or Access changing the other; a request's placeholder + * invitation being adopted as a link by a later admin invite; an admin's reinvitation leaving the + * workflow's reminders running; the emailed link not opening the requested enrollment on the + * connect page; the requesting workflow's name reaching the email subject, or reaching the body + * uncleaned; a failed delivery not showing as Email failed; and an email still going out, or its + * outcome overwriting the enrollment, after an admin reinvited. */ import type { WorkflowExecutionDelegatedPrincipal } from '@sim/auth/principal' import { db } from '@sim/db' @@ -707,11 +708,10 @@ describe('request_connection input and daily limit', () => { ).toEqual([]) }) - it('counts distinct addresses: asking again for one already asked today is free and unlogged', async () => { + it('counts distinct addresses: below the limit, asking again for one already asked today is free and unlogged', async () => { await enroll(orgC, address('limit-existing')) for (let attempt = 0; attempt < 3; attempt++) await request(orgC, address('limit-existing')) await request(orgC, address('limit-new')) - await request(orgC, address('limit-existing')) expect((await refusal(request(orgC, address('limit-third')))).code).toBe('conflict') expect(await enrollmentsFor(orgC, address('limit-third'))).toEqual([]) @@ -741,15 +741,16 @@ describe('request_connection input and daily limit', () => { expect(await enrollmentsFor(orgC, address('window-3'))).toHaveLength(1) }) - it('fails the same way at the limit whatever the target', async () => { + it('fails the same way at the limit whatever the target, an address asked today included', async () => { await enroll(orgC, address('limit-known')) await enroll(orgC, address('limit-revoked'), { status: 'revoked', revokedAt: new Date() }) await request(orgC, address('limit-filler-1')) await request(orgC, address('limit-filler-2')) const known = await refusal(request(orgC, address('limit-known'))) const revoked = await refusal(request(orgC, address('limit-revoked'))) + const askedToday = await refusal(request(orgC, address('limit-filler-1'))) const unknown = await refusal(request(orgC, address('limit-unknown'))) - for (const error of [known, revoked]) + for (const error of [known, revoked, askedToday]) expect({ code: error.code, message: error.message }).toEqual({ code: unknown.code, message: unknown.message, diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts index 96827c31549..4edd76cf477 100644 --- a/apps/sim/lib/credential-groups/application/connect-target.ts +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -11,6 +11,7 @@ import { organizationAccountOperations } from '@/lib/credential-groups/applicati import { connectRequestHandleMatches } from '@/lib/credential-groups/connect-request-handle' import { type CredentialGroupConnectLinkTarget, + hasLiveConnectConnection, issueCredentialGroupConnectLink, loadCredentialGroupConnectSubject, } from '@/lib/credential-groups/connect-subject' @@ -30,6 +31,7 @@ import { import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' import { defineAuthorizedCredentialUserUseCase } from '@/lib/credentials/application/authorized-user-use-case' +import type { DbTransaction } from '@/lib/db/types' /** * Opening and starting a connect URL. A member's self-enrollment is held to the Integrations @@ -96,8 +98,18 @@ interface ConnectOffer { optionId: string } +/** The person's enrollment already holds a live connection for the option; nothing to start. */ +interface AlreadyConnected { + kind: 'already_connected' + organizationName: string + provider: CredentialGroupProvider +} + /** What the connect page shows a signed-in person. */ -export type CredentialGroupConnectOutcome = CredentialGroupConnectRefusal | ConnectOffer +export type CredentialGroupConnectOutcome = + | CredentialGroupConnectRefusal + | ConnectOffer + | AlreadyConnected type ConnectDecision = | CredentialGroupConnectRefusal @@ -108,18 +120,23 @@ const UNAVAILABLE = { kind: 'unavailable' } as const /** * Whether the member may enroll themselves, under the same checks as the member self-enroll path * (`organization_accounts.connect`): membership, the Integrations permission-group capability, - * and an organization whose Connected accounts setup is complete. + * and an organization whose Connected accounts setup is complete. Given a transaction, it reads + * through it and holds the membership row until it ends, so a removal cannot commit in between. */ async function canSelfEnroll( principal: SessionPrincipal, organizationId: string, - credentialGroupId: string + credentialGroupId: string, + tx?: DbTransaction ): Promise { try { - await authorizeOrganizationOperation(principal, organizationAccountOperations.connect, { - organizationId, - }) - await requireOrganizationAccountsSetup(organizationId, credentialGroupId) + await authorizeOrganizationOperation( + principal, + organizationAccountOperations.connect, + { organizationId }, + tx ? { executor: tx, forShare: true } : {} + ) + await requireOrganizationAccountsSetup(organizationId, credentialGroupId, tx) return true } catch (error) { if ( @@ -201,6 +218,9 @@ async function decideConnectTarget( ) { return UNAVAILABLE } + const { organizationId } = group + const mayEnroll = (tx: DbTransaction) => + organizationId ? canSelfEnroll(principal, organizationId, group.id, tx) : Promise.resolve(false) if (options.length > 1) return { kind: 'choose_option', @@ -215,9 +235,9 @@ async function decideConnectTarget( optionId: option.id, credentialGroupId: group.id, target: !enrollment - ? { kind: 'self_enrollment' } + ? { kind: 'self_enrollment', mayEnroll } : expired - ? { kind: 'renew_expired_enrollment', enrollmentId: enrollment.id } + ? { kind: 'renew_expired_enrollment', enrollmentId: enrollment.id, mayEnroll } : { kind: 'enrollment', enrollmentId: enrollment.id }, } } @@ -226,7 +246,11 @@ function isOffer(decision: ConnectDecision): decision is Extract { const decision = await decideConnectTarget(principal, input) if (!isOffer(decision)) return decision - const { kind, organizationName, provider, optionId } = decision + const { kind, organizationName, provider, optionId, target } = decision + if ( + target.kind === 'enrollment' && + (await hasLiveConnectConnection({ + enrollmentId: target.enrollmentId, + optionId, + userId: principal.userId, + })) + ) + return { kind: 'already_connected', organizationName, provider } return { kind, organizationName, provider, optionId } }, }) diff --git a/apps/sim/lib/credential-groups/application/connection-requests.ts b/apps/sim/lib/credential-groups/application/connection-requests.ts index 40a2437c62f..e648c7b2202 100644 --- a/apps/sim/lib/credential-groups/application/connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/connection-requests.ts @@ -32,7 +32,9 @@ import { recordCredentialGroupConnectionRequest, } from '@/lib/credential-groups/connection-requests' import { + findCredentialGroupProviderFromProviderId, getCredentialGroupProviderId, + getCredentialGroupProviderService, isCredentialGroupProvider, } from '@/lib/credential-groups/providers' @@ -79,9 +81,15 @@ function requireRequestableEmail(value: string): string { return email } +/** The integration's name for an error message; the raw ID when no integration has it. */ +function integrationLabel(providerId: string): string { + const provider = findCredentialGroupProviderFromProviderId(providerId) + return provider ? getCredentialGroupProviderService(provider).name : providerId +} + /** * Resolves the group options collecting this provider that the executing workspace may use, - * with the same errors List Organization Accounts gives for an inactive or disallowed provider. + * refusing an inactive or disallowed integration by name. */ function requireAllowedProviderOptions( context: OrganizationAccountsWorkspaceContext, @@ -101,7 +109,7 @@ function requireAllowedProviderOptions( if (!first) throw new OrchestrationError( 'validation', - `Credential provider is not active in this group: ${providerId}` + `The ${integrationLabel(providerId)} integration is not active in this credential group` ) const allowed = options.filter((option) => organizationAccountPolicyAllowsWorkspace( @@ -113,7 +121,7 @@ function requireAllowedProviderOptions( if (!allowed.length) throw new OrchestrationError( 'forbidden', - 'This workspace is not allowed to use the requested credential provider' + `This workspace is not allowed to use the ${integrationLabel(providerId)} integration` ) return { options: allowed, label: first.label } } @@ -199,6 +207,7 @@ const recordOrganizationAccountConnectionRequest = defineAuthorizedWorkspaceUseC workspaceId: context.workspaceId, email, providerId: input.providerId, + integration: integrationLabel(input.providerId), }) if (refusal) throw new OrchestrationError('forbidden', refusal) const { label } = requireAllowedProviderOptions(context, accessPolicy, input.providerId) diff --git a/apps/sim/lib/credential-groups/connect-session.ts b/apps/sim/lib/credential-groups/connect-session.ts index d790050f62a..9babb61347f 100644 --- a/apps/sim/lib/credential-groups/connect-session.ts +++ b/apps/sim/lib/credential-groups/connect-session.ts @@ -1,28 +1,20 @@ import type { SessionPrincipal } from '@sim/auth/principal' import { getSession } from '@/lib/auth' -import { checkCredentialGroupConnectUserRateLimit } from '@/lib/credential-groups/rate-limit' import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' /** * Who is opening a connect URL, as the page and its POST both need it before any use case runs: - * signed in, with a verified email, and within their per-person budget. + * signed in, with a verified email. */ export type CredentialGroupConnectSession = | { kind: 'sign_in' } | { kind: 'verify_email' } - /** Over the per-person budget. */ - | { kind: 'rate_limited' } - /** The limiter could not be reached; refused, but not blamed on the person. */ - | { kind: 'try_again' } | { kind: 'signed_in'; principal: SessionPrincipal; email: string } export async function resolveCredentialGroupConnectSession(): Promise { const session = await getSession() if (!session?.user) return { kind: 'sign_in' } if (!isCredentialGroupEmailVerified(session.user)) return { kind: 'verify_email' } - const limit = await checkCredentialGroupConnectUserRateLimit(session.user.id) - if (limit === 'limited') return { kind: 'rate_limited' } - if (limit === 'unavailable') return { kind: 'try_again' } return { kind: 'signed_in', principal: { kind: 'session', userId: session.user.id, sessionId: session.session.id }, diff --git a/apps/sim/lib/credential-groups/connect-subject.ts b/apps/sim/lib/credential-groups/connect-subject.ts index ac89769ef5a..f41fd3c5828 100644 --- a/apps/sim/lib/credential-groups/connect-subject.ts +++ b/apps/sim/lib/credential-groups/connect-subject.ts @@ -1,6 +1,7 @@ import { db } from '@sim/db' import { type CredentialGroupOptionConfig, + credential, credentialGroup, credentialGroupEnrollment, organization, @@ -8,7 +9,8 @@ import { workspace, } from '@sim/db/schema' import { normalizeEmail } from '@sim/utils/string' -import { and, eq, or } from 'drizzle-orm' +import { and, eq, inArray, or } from 'drizzle-orm' +import { LIVE_ENROLLMENT_STATUSES } from '@/lib/credential-groups/credentials' import { INVITATION_TTL_MS, isEnrollmentRequestExpired, @@ -20,6 +22,7 @@ import { } from '@/lib/credential-groups/enrollments' import { insertEnrollmentLink } from '@/lib/credential-groups/links' import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' +import type { DbTransaction } from '@/lib/db/types' /** * Reads and writes for the secret-free connect URL. The decision of what a signed-in person may @@ -105,6 +108,44 @@ export async function loadCredentialGroupConnectSubject(input: { } } +/** + * Whether the person's own enrollment already holds a live connection for the option: an active + * managed account they connected, on an enrollment bound to them that is still live. An account + * the provider stopped honoring is not live, so the person is offered a reconnect instead. + */ +export async function hasLiveConnectConnection(input: { + enrollmentId: string + optionId: string + userId: string +}): Promise { + const [row] = await db + .select({ id: credential.id }) + .from(credential) + .innerJoin( + credentialGroupEnrollment, + eq(credentialGroupEnrollment.id, credential.credentialGroupEnrollmentId) + ) + .where( + and( + eq(credentialGroupEnrollment.id, input.enrollmentId), + eq(credentialGroupEnrollment.userId, input.userId), + inArray(credentialGroupEnrollment.status, [...LIVE_ENROLLMENT_STATUSES]), + eq(credential.credentialGroupOptionId, input.optionId), + eq(credential.createdBy, input.userId), + eq(credential.type, 'managed_oauth'), + eq(credential.managedOauthStatus, 'active') + ) + ) + .limit(1) + return row !== undefined +} + +/** + * Re-checks, inside the link's transaction, that the person may still enroll themselves (the + * member self-enroll checks), holding what it read until the transaction ends. + */ +type MayEnrollThemselves = (tx: DbTransaction) => Promise + /** Who the connect link is for and which enrollment it opens. */ export type CredentialGroupConnectLinkTarget = /** An enrollment the person already holds: bound to them, or requested at their email. */ @@ -113,9 +154,9 @@ export type CredentialGroupConnectLinkTarget = * An organization member's own request that expired unanswered: as a member may enroll * themselves, the link renews it instead of creating another. */ - | { kind: 'renew_expired_enrollment'; enrollmentId: string } + | { kind: 'renew_expired_enrollment'; enrollmentId: string; mayEnroll: MayEnrollThemselves } /** An organization member with no enrollment, who asked to connect. */ - | { kind: 'self_enrollment' } + | { kind: 'self_enrollment'; mayEnroll: MayEnrollThemselves } type IssuedCredentialGroupConnectLink = | { @@ -140,8 +181,9 @@ type IssuedCredentialGroupConnectLink = * timestamps and status stay as they are. * * The caller has already decided the person may connect; this re-checks, under the lock, only what - * may have changed since: revocation, expiry, the group still being active, the binding, and that - * the person's verified email still matches an unbound enrollment. + * may have changed since: revocation, expiry, the group still being active, the binding, that the + * person's verified email still matches an unbound enrollment, and, for a member enrolling + * themselves or renewing their expired request, that they still pass the member self-enroll checks. */ export async function issueCredentialGroupConnectLink(input: { credentialGroupId: string @@ -160,9 +202,12 @@ export async function issueCredentialGroupConnectLink(input: { return { issued: false, reason: 'unavailable' } const viewerEmail = normalizeEmail(viewer.email) - let enrollmentId = input.target.kind === 'self_enrollment' ? null : input.target.enrollmentId + const { target } = input + let enrollmentId = target.kind === 'self_enrollment' ? null : target.enrollmentId let created = false if (enrollmentId === null) { + if (target.kind === 'self_enrollment' && !(await target.mayEnroll(tx))) + return { issued: false, reason: 'unavailable' } const enrollment = await findOrCreateUnissuedEnrollment(tx, { credentialGroupId: input.credentialGroupId, email: viewerEmail, @@ -172,6 +217,8 @@ export async function issueCredentialGroupConnectLink(input: { created = enrollment.created } else { await lockCredentialGroupEnrollmentLifecycle(tx, enrollmentId) + if (target.kind === 'renew_expired_enrollment' && !(await target.mayEnroll(tx))) + return { issued: false, reason: 'unavailable' } } const [current] = await tx @@ -197,7 +244,7 @@ export async function issueCredentialGroupConnectLink(input: { if (!current) return { issued: false, reason: 'unavailable' } if (isEnrollmentRevoked(current)) return { issued: false, reason: 'revoked' } const renewed = - input.target.kind === 'renew_expired_enrollment' && isEnrollmentRequestExpired(current, now) + target.kind === 'renew_expired_enrollment' && isEnrollmentRequestExpired(current, now) if (!renewed && isEnrollmentRequestExpired(current, now)) return { issued: false, reason: 'expired' } if (current.groupStatus !== 'active') return { issued: false, reason: 'unavailable' } diff --git a/apps/sim/lib/credential-groups/connection-request-policy.ts b/apps/sim/lib/credential-groups/connection-request-policy.ts index 9bda526a0f7..27d9916e5bc 100644 --- a/apps/sim/lib/credential-groups/connection-request-policy.ts +++ b/apps/sim/lib/credential-groups/connection-request-policy.ts @@ -113,7 +113,13 @@ export const CONNECTION_REQUESTS_OFF: ConnectionRequestPolicy = { */ export function connectionRequestRefusal( policy: ConnectionRequestPolicy, - request: { workspaceId: string; email: string; providerId: string } + request: { + workspaceId: string + email: string + providerId: string + /** The integration's name, as the refusal shows it. */ + integration: string + } ): string | null { if (!policy.enabled) return 'Workflow connection requests are turned off for this organization' if ( @@ -125,6 +131,6 @@ export function connectionRequestRefusal( if (!policy.emailDomains.includes(domain)) return `Connection requests are not allowed for ${domain} addresses` if (!policy.providers.includes(request.providerId)) - return `Connection requests are not allowed for ${request.providerId}` + return `Connection requests are not allowed for the ${request.integration} integration` return null } diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index 3d20b6e3d43..d42f5e97a52 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -237,9 +237,11 @@ function enqueueConnectionRequestEmail( /** * Records one workflow's request that a person connect an account, in one transaction. * - * The daily cap counts distinct addresses asked per group per day, under the group lock. A repeat - * request for an address already asked today is neither logged nor capped, so retries and loops - * over the same person cost nothing. The per-email invitation lock is the one admin invitations + * The daily cap counts distinct addresses asked per group per day, under the group lock. Once it + * is reached every request is refused with the same error, a repeat for an address asked today + * included, so whether a request succeeds never reveals what other workspaces asked. Below the + * cap a repeat for an address already asked today is not logged, so retries and loops over the + * same person cost no slot. The per-email invitation lock is the one admin invitations * take, so a request never races an invite for the same address. * * Only an absent enrollment is created. An existing one keeps its status and attribution: a @@ -274,6 +276,15 @@ export async function recordCredentialGroupConnectionRequest(input: { 'credential_group_connection_request', `credential-group-connection-request:${input.credentialGroupId}` ) + const [today] = await tx + .select({ emails: countDistinct(log.email) }) + .from(log) + .where(and(eq(log.credentialGroupId, input.credentialGroupId), gt(log.createdAt, dayAgo))) + if ((today?.emails ?? 0) >= input.dailyLimit) + throw new OrchestrationError( + 'conflict', + 'This organization reached its daily limit for workflow connection requests' + ) const [askedToday] = await tx .select({ id: log.id }) .from(log) @@ -285,16 +296,7 @@ export async function recordCredentialGroupConnectionRequest(input: { ) ) .limit(1) - if (!askedToday) { - const [today] = await tx - .select({ emails: countDistinct(log.email) }) - .from(log) - .where(and(eq(log.credentialGroupId, input.credentialGroupId), gt(log.createdAt, dayAgo))) - if ((today?.emails ?? 0) >= input.dailyLimit) - throw new OrchestrationError( - 'conflict', - 'This organization reached its daily limit for workflow connection requests' - ) + if (!askedToday) await tx.insert(log).values({ id: generateId(), credentialGroupId: input.credentialGroupId, @@ -303,7 +305,6 @@ export async function recordCredentialGroupConnectionRequest(input: { workflowId: input.workflowId, createdAt: now, }) - } const { row, created } = await findOrCreateUnissuedEnrollment(tx, { credentialGroupId: input.credentialGroupId, diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 26a45da9035..3fed2b04cd6 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -970,7 +970,7 @@ export async function listCredentialGroupEnrollments( enrollments: pageRows.map(({ enrollment }) => ({ ...toCredentialGroupEnrollment(enrollment), requestedByWorkflow: enrollment.requestedByWorkflowId !== null, - emailed: enrollment.sentAt !== null, + bound: enrollment.userId !== null, connections: connectionsByEnrollment.get(enrollment.id) ?? [], mcpConnections: mcpConnectionsByEnrollment.get(enrollment.id) ?? [], })), diff --git a/apps/sim/lib/credential-groups/rate-limit.ts b/apps/sim/lib/credential-groups/rate-limit.ts index 840844a1174..e6fe5b51c73 100644 --- a/apps/sim/lib/credential-groups/rate-limit.ts +++ b/apps/sim/lib/credential-groups/rate-limit.ts @@ -121,9 +121,10 @@ const CONNECT_LINK_USER_RATE_LIMIT: TokenBucketConfig = { } /** - * Bounds how many times one signed-in person can open or start connect links, wherever they open - * them from. Fails closed, but tells an outage of the limiter (`unavailable`) apart from a person - * who really is over the limit (`limited`), so neither is told the other. + * Bounds how many connections one signed-in person can start from connect links (the POST that + * enrolls and mints a link), wherever they open them from. Opening the page is bounded per IP. + * Fails closed, but tells an outage of the limiter (`unavailable`) apart from a person who really + * is over the limit (`limited`), so neither is told the other. */ export async function checkCredentialGroupConnectUserRateLimit( userId: string diff --git a/apps/sim/scripts/migrate-gitlab-personal-tokens.ts b/apps/sim/scripts/migrate-gitlab-personal-tokens.ts index cd90bb0d45a..0c4fb2cb751 100644 --- a/apps/sim/scripts/migrate-gitlab-personal-tokens.ts +++ b/apps/sim/scripts/migrate-gitlab-personal-tokens.ts @@ -16,7 +16,6 @@ import { workspace, } from '@sim/db/schema' import { createLogger } from '@sim/logger' -import { sha256Hex } from '@sim/security/hash' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { normalizeEmail } from '@sim/utils/string' @@ -232,7 +231,6 @@ async function migrateToken( userId: owner.id, email: normalizeEmail(owner.email), status: 'in_progress', - invitationTokenHash: sha256Hex(generateId()), invitationExpiresAt: now, invitedAt: now, }) diff --git a/apps/sim/scripts/test-assistant-actions-e2e.ts b/apps/sim/scripts/test-assistant-actions-e2e.ts index 35570e5637f..3a90a48596a 100644 --- a/apps/sim/scripts/test-assistant-actions-e2e.ts +++ b/apps/sim/scripts/test-assistant-actions-e2e.ts @@ -261,8 +261,8 @@ try { values (${groupId}, ${organizationId}, ${generateId()}, 'Personal Jira', ${tx.json([{ id: 'jira', provider: 'jira' }, { id: 'jira-team', provider: 'jira' }, { id: 'salesforce', provider: 'salesforce' }, ...catalogAccounts.map((account) => ({ id: account.option, provider: account.option }))].map(({ id, provider }) => ({ id, provider, label: id, authorizationAppId: 'fixture', requiredScopes: [], scopeVersion: 1, required: false, status: 'active' })))})` await tx`insert into resource_policy (id, organization_id, resource_type, resource_id, document, created_by, updated_by) values (${generateId()}, ${organizationId}, 'credential_group', ${groupId}, ${tx.json({ version: 2, resource: { type: 'credential_group', id: groupId }, statements: [] })}, ${userId}, ${userId})` - await tx`insert into credential_group_enrollment (id, credential_group_id, user_id, email, status, invitation_token_hash, invitation_expires_at, invited_at) - values (${enrollmentId}, ${groupId}, ${userId}, ${email}, 'completed', ${enrollmentId.replaceAll('-', '').repeat(2)}, now() + interval '1 day', now())` + await tx`insert into credential_group_enrollment (id, credential_group_id, user_id, email, status, invitation_expires_at, invited_at) + values (${enrollmentId}, ${groupId}, ${userId}, ${email}, 'completed', now() + interval '1 day', now())` for (const [id, provider] of [ [codaServerId, 'coda'], [firefliesServerId, 'fireflies'], From 55c9b1f3586f91306e9e6d666d13d86eae218515 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 17:26:29 -0600 Subject: [PATCH 22/26] fix(credential-groups): type the enrollment detail's bound and workflow fields --- .../sim/lib/assistant-actions/tool-permissions.integration.ts | 3 ++- apps/sim/lib/credential-groups/types.ts | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/assistant-actions/tool-permissions.integration.ts b/apps/sim/lib/assistant-actions/tool-permissions.integration.ts index 941bc2f2bb2..5544f384871 100644 --- a/apps/sim/lib/assistant-actions/tool-permissions.integration.ts +++ b/apps/sim/lib/assistant-actions/tool-permissions.integration.ts @@ -1326,7 +1326,8 @@ describe('Managed account identity across Assistant approvals', () => { const state = new URL(authorizationUrl).searchParams.get('state') if (!state) throw new Error('Fixture authorization did not return state') const attempt = await consumeCredentialGroupOAuthAttempt(state) - if (!attempt) throw new Error('Fixture authorization state was unavailable') + if (!attempt || 'expired' in attempt) + throw new Error('Fixture authorization state was unavailable') expect(await consumeCredentialGroupOAuthAttempt(state)).toBeNull() const completion = completeCredentialGroupOAuth(context, attempt, 'fixture-code') diff --git a/apps/sim/lib/credential-groups/types.ts b/apps/sim/lib/credential-groups/types.ts index 95ab79485fc..06fca0c9582 100644 --- a/apps/sim/lib/credential-groups/types.ts +++ b/apps/sim/lib/credential-groups/types.ts @@ -100,6 +100,10 @@ export interface CredentialGroupEnrollmentMcpConnection { } export interface CredentialGroupEnrollmentDetail extends CredentialGroupEnrollmentRecord { + /** A workflow asked for this connection rather than an admin. */ + requestedByWorkflow: boolean + /** The person accepted: the enrollment is bound to their Sim account. */ + bound: boolean connections: CredentialGroupEnrollmentConnection[] mcpConnections: CredentialGroupEnrollmentMcpConnection[] } From 243c9476eb849589a9688a30fcabd22972182ca5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 17:40:10 -0600 Subject: [PATCH 23/26] fix(credential-groups): narrow expired OAuth attempts in tests, bump chart for the cleanup cron --- .../organization-account-workspace-access.test.tsx | 1 + apps/sim/lib/credential-groups/oauth-state.test.ts | 6 ++++-- helm/sim/Chart.yaml | 2 +- scripts/check-test-types.baseline.json | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/apps/sim/ee/credential-groups/components/organization-account-workspace-access.test.tsx b/apps/sim/ee/credential-groups/components/organization-account-workspace-access.test.tsx index f42933048c8..1ccd93b85d5 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-workspace-access.test.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-workspace-access.test.tsx @@ -34,6 +34,7 @@ vi.mock('@sim/emcn', () => ({ ), ChipTag: ({ children }: { children: ReactNode }) => {children}, + Skeleton: () =>
, toast: { error: hoisted.toastError, success: hoisted.toastSuccess }, })) vi.mock('@sim/emcn/icons', () => emcnIconsMock) diff --git a/apps/sim/lib/credential-groups/oauth-state.test.ts b/apps/sim/lib/credential-groups/oauth-state.test.ts index d55136cdddc..302543fd7a0 100644 --- a/apps/sim/lib/credential-groups/oauth-state.test.ts +++ b/apps/sim/lib/credential-groups/oauth-state.test.ts @@ -85,7 +85,8 @@ describe('credential group OAuth state', () => { completionRedirect: true, completionId: '550e8400-e29b-41d4-a716-446655440000', }) - expect(credentialGroupOAuthNonceMatches(created.nonce, consumed?.nonceHash ?? '')).toBe(true) + if (!consumed || 'expired' in consumed) throw new Error('Expected a live OAuth attempt') + expect(credentialGroupOAuthNonceMatches(created.nonce, consumed.nonceHash)).toBe(true) await expect(consumeCredentialGroupOAuthAttempt(created.state)).resolves.toBeNull() }) @@ -169,7 +170,8 @@ describe('organization enrollment OAuth state', () => { origin: 'search', optionId: 'option-1', }) - expect(attempt?.workspaceId).toBeUndefined() + if (!attempt || 'expired' in attempt) throw new Error('Expected a live OAuth attempt') + expect(attempt.workspaceId).toBeUndefined() await expect(consumeCredentialGroupOAuthAttempt(state)).resolves.toBeNull() }) it('rejects dual ownership before persisting an OAuth attempt', async () => { diff --git a/helm/sim/Chart.yaml b/helm/sim/Chart.yaml index 4691a3bf82e..1401e875ab1 100644 --- a/helm/sim/Chart.yaml +++ b/helm/sim/Chart.yaml @@ -2,7 +2,7 @@ apiVersion: v2 name: sim description: A Helm chart for Sim - the open-source AI workspace where teams build, deploy, and manage AI agents type: application -version: 1.18.0 +version: 1.19.0 appVersion: "v0.8.26" kubeVersion: ">=1.25.0-0" home: https://sim.ai diff --git a/scripts/check-test-types.baseline.json b/scripts/check-test-types.baseline.json index bff66d12dad..8a15daa3166 100644 --- a/scripts/check-test-types.baseline.json +++ b/scripts/check-test-types.baseline.json @@ -1122,7 +1122,7 @@ "TS2739": 1 }, "apps/sim/lib/credential-groups/oauth.test.ts": { - "TS2345": 9 + "TS2345": 8 }, "apps/sim/lib/credential-groups/organization-account-options.test.ts": { "TS18048": 1 From 4e1ab6956d88e06b98f083be92800b656dc5626f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 17:57:37 -0600 Subject: [PATCH 24/26] fix(credential-groups): address connect-flow review findings - Dry run: answer a Credential block's request_connection whole, like other blocks that write outside the tool seam, so no enrollment or email is made. - A workflow's open request records the latest workflow and integration together, so a reminder names the workflow that asked for it. - A focused connection finishes a workflow's request only when the requested integration is connected (or every option is). - Connect page: unknown, disabled and unoffered groups answer unavailable before the verify-email step. - Explain answers unknown to a viewer whose email is unverified. - Connect link refusals roll back, so a refused self-enrollment leaves no row. - Policy editor opened from the switch saves the policy enabled. - Request log and session link retention share an inclusive cutoff. - Workflow names collapse whitespace before control characters are removed; invitation email says the 7 days apply before the person accepts. - Integration tests: release held locks in finally, assert in_progress, and clean up the delivery suite's outbox events. --- ...anup-credential-group-links.integration.ts | 17 +- .../cleanup-credential-group-links.ts | 12 +- .../credential-group-invitation-email.tsx | 2 +- .../organization-connection-requests.tsx | 26 ++- apps/sim/executor/execution/block-executor.ts | 1 + apps/sim/executor/execution/types.ts | 2 + .../connect-target.integration.ts | 96 +++++++-- .../enrollment-link-outcome.integration.ts | 30 ++- .../enrollment-links.integration.ts | 9 +- ...orkflow-connection-requests.integration.ts | 72 +++++-- .../application/connect-target.ts | 2 +- .../application/enrollment-link-outcome.ts | 13 +- .../lib/credential-groups/connect-subject.ts | 192 ++++++++++-------- .../connection-request-email.ts | 7 +- .../credential-groups/connection-requests.ts | 25 ++- apps/sim/lib/credential-groups/enrollments.ts | 64 +++--- .../application/dry-run.integration.ts | 26 ++- .../sim/lib/workflows/dry-run/side-effects.ts | 34 +++- packages/db/schema.ts | 7 +- 19 files changed, 432 insertions(+), 205 deletions(-) diff --git a/apps/sim/background/cleanup-credential-group-links.integration.ts b/apps/sim/background/cleanup-credential-group-links.integration.ts index b0f7ed8e048..61808f6f432 100644 --- a/apps/sim/background/cleanup-credential-group-links.integration.ts +++ b/apps/sim/background/cleanup-credential-group-links.integration.ts @@ -2,8 +2,9 @@ * Retention of the connect flow's short-lived rows against real PostgreSQL. Failure modes: a * request log row the daily cap still reads being deleted; an expired session link a day past * expiry being kept; an emailed link, which outlives its expiry once bound, being deleted; a row - * exactly at a cutoff being deleted early; a row another run has locked stalling this run; one - * run draining an unbounded backlog instead of capping its batches. + * just inside a cutoff being deleted early, or the two tables treating a row exactly at their + * cutoff differently; a row another run has locked stalling this run; one run draining an + * unbounded backlog instead of capping its batches. */ import { db, dbFor } from '@sim/db' import { @@ -106,12 +107,12 @@ describe('runCleanupCredentialGroupLinks', () => { expect(links.map((row) => row.id).sort()).toEqual([recentlyExpired, live, oldEmail].sort()) }) - it('keeps a request exactly at its cutoff and a link not yet expired at its cutoff', async () => { + it('deletes a request and a link exactly at their cutoffs, keeping ones just inside', async () => { const { groupId, enrollmentId } = await createEnrollment() const now = Date.now() - const atRequestCutoff = await insertRequest(groupId, new Date(now - 2 * DAY_MS)) - await insertRequest(groupId, new Date(now - 2 * DAY_MS - 1)) - const pastLinkCutoff = await insertLink(enrollmentId, 'connect', new Date(now - DAY_MS + 1)) + const insideRequestCutoff = await insertRequest(groupId, new Date(now - 2 * DAY_MS + 1)) + await insertRequest(groupId, new Date(now - 2 * DAY_MS)) + const insideLinkCutoff = await insertLink(enrollmentId, 'connect', new Date(now - DAY_MS + 1)) await insertLink(enrollmentId, 'connect', new Date(now - DAY_MS)) await runCleanupCredentialGroupLinks(new Date(now)) @@ -120,12 +121,12 @@ describe('runCleanupCredentialGroupLinks', () => { .select({ id: credentialGroupConnectionRequest.id }) .from(credentialGroupConnectionRequest) .where(eq(credentialGroupConnectionRequest.credentialGroupId, groupId)) - expect(requests.map((row) => row.id)).toEqual([atRequestCutoff]) + expect(requests.map((row) => row.id)).toEqual([insideRequestCutoff]) const links = await db .select({ id: credentialGroupEnrollmentLink.id }) .from(credentialGroupEnrollmentLink) .where(eq(credentialGroupEnrollmentLink.enrollmentId, enrollmentId)) - expect(links.map((row) => row.id)).toEqual([pastLinkCutoff]) + expect(links.map((row) => row.id)).toEqual([insideLinkCutoff]) }) it('skips a row another run holds instead of waiting for it', async () => { diff --git a/apps/sim/background/cleanup-credential-group-links.ts b/apps/sim/background/cleanup-credential-group-links.ts index 00505ec738d..b0476f7286b 100644 --- a/apps/sim/background/cleanup-credential-group-links.ts +++ b/apps/sim/background/cleanup-credential-group-links.ts @@ -6,7 +6,7 @@ import { } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' -import { and, asc, eq, inArray, lt, not } from 'drizzle-orm' +import { and, asc, eq, inArray, lte, not } from 'drizzle-orm' import { DAY_MS } from '@/lib/credential-groups/limits' import { unexpiredLinkCondition } from '@/lib/credential-groups/links' @@ -44,9 +44,11 @@ async function drain(table: string, deleteBatch: () => Promise): Promise } /** - * Deletes workflow connection request log rows older than two days, and `self` and `connect` - * links that expired more than a day ago. Emailed links are kept: once bound, they outlive their - * expiry. Each batch takes its rows oldest first, skipping rows another run has locked. + * Deletes workflow connection request log rows two or more days old, and `self` and `connect` + * links that expired a day or more ago. A row exactly at either cutoff is deleted, matching how + * {@link unexpiredLinkCondition} treats a link at its expiry. Emailed links are kept: once bound, + * they outlive their expiry. Each batch takes its rows oldest first, skipping rows another run has + * locked. */ export async function runCleanupCredentialGroupLinks( now = new Date() @@ -65,7 +67,7 @@ export async function runCleanupCredentialGroupLinks( cleanupDb .select({ id: request.id }) .from(request) - .where(lt(request.createdAt, requestCutoff)) + .where(lte(request.createdAt, requestCutoff)) .orderBy(asc(request.createdAt)) .limit(CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) .for('update', { skipLocked: true }) diff --git a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx index 9266bf2ada9..55832fed1bb 100644 --- a/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx +++ b/apps/sim/components/emails/credential-groups/credential-group-invitation-email.tsx @@ -103,7 +103,7 @@ export function CredentialGroupInvitationEmail({ {workflowRequest ? `Sign in or create a Sim account with ${recipientEmail} to continue. Sim will send you to ${workflowRequest.providerName} to sign in and will never ask for your ${workflowRequest.providerName} password. If you did not expect this request, you can ignore it.` - : 'This private link expires in 7 days. Sim will send you to each provider to sign in and will never ask for your provider password. If you did not expect this invitation, you can ignore it.'} + : 'If you do not accept within 7 days, this private link expires. Sim will send you to each provider to sign in and will never ask for your provider password. If you did not expect this invitation, you can ignore it.'} ) diff --git a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx index b5d0778355e..207f9486064 100644 --- a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx +++ b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx @@ -69,7 +69,8 @@ export function OrganizationConnectionRequests({ }: OrganizationConnectionRequestsProps) { const state = useOrganizationConnectionRequestPolicy(organizationId) const update = useUpdateOrganizationConnectionRequestPolicy() - const [editing, setEditing] = useState(false) + /** The open editor and whether its Save leaves requests on, or null when it is closed. */ + const [editor, setEditor] = useState<{ enabled: boolean } | null>(null) const toggleId = useId() if (state.error) @@ -92,19 +93,20 @@ export function OrganizationConnectionRequests({ ) const { policy, revision, inEffect } = state.data - const openEditor = () => { + const openEditor = (enabled: boolean) => { update.reset() - setEditing(true) + setEditor({ enabled }) } + const editing = editor !== null const save = async (next: Policy) => { try { await update.mutateAsync({ organizationId, revision, policy: next }) - setEditing(false) + setEditor(null) toast.success('Connection requests updated') } catch (error) { if (editing && isApiClientError(error) && error.status === 409) { - setEditing(false) + setEditor(null) update.reset() toast.error('Someone else changed these settings. Reopen to review.') return @@ -135,7 +137,7 @@ export function OrganizationConnectionRequests({ trailing={
{policy && ( - + openEditor(policy.enabled)}> Edit )} @@ -147,18 +149,19 @@ export function OrganizationConnectionRequests({ if (!checked) { if (policy) void save({ ...policy, enabled: false }) } else if (policy && canEnable(policy)) void save({ ...policy, enabled: true }) - else openEditor() + else openEditor(true) }} />
} /> - {editing && ( + {editor && ( setEditing(false)} + onClose={() => setEditor(null)} onSave={(next) => void save(next)} /> )} @@ -168,6 +171,8 @@ export function OrganizationConnectionRequests({ interface ConnectionRequestPolicyModalProps { state: OrganizationConnectionRequestPolicyState + /** Whether Save leaves requests on: the stored value from Edit, on when the switch opened it. */ + enabled: boolean disabled: boolean error?: string onClose: () => void @@ -176,6 +181,7 @@ interface ConnectionRequestPolicyModalProps { function ConnectionRequestPolicyModal({ state, + enabled, disabled, error, onClose, @@ -202,7 +208,7 @@ function ConnectionRequestPolicyModal({ const limitValid = Number.isInteger(limit) && limit >= 1 && limit <= CONNECTION_REQUEST_DAILY_LIMIT_MAX const draft: Policy = { - enabled: initial?.enabled ?? true, + enabled, workspaces, emailDomains, providers, diff --git a/apps/sim/executor/execution/block-executor.ts b/apps/sim/executor/execution/block-executor.ts index 1da91d6239a..40dd6111574 100644 --- a/apps/sim/executor/execution/block-executor.ts +++ b/apps/sim/executor/execution/block-executor.ts @@ -293,6 +293,7 @@ export class BlockExecutor { blockId: mockedBlockId, blockName: block.metadata?.name ?? mockedBlockId, blockType: block.metadata?.id ?? '', + operation: typeof resolvedInputs.operation === 'string' ? resolvedInputs.operation : null, } const answeredBy = site && sideEffects?.answersBlock(site) ? sideEffects : undefined try { diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index b8f3858065d..5d2e31a06d1 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -351,6 +351,8 @@ export interface SideEffectBlockSite extends SideEffectSite { blockId: string blockName: string blockType: string + /** The block's resolved `operation` input; null for a block without one. */ + operation: string | null } /** The MCP server and tool an MCP block's operation names. */ diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index d684d1b0035..e4898d6590b 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -8,11 +8,12 @@ * one, which never expires, and a member's own expired request, renewed by the start), a stranger, * an organization member with no enrollment (enrolled only by the start), a member the * Integrations permission group or an unfinished setup keeps from self-enrolling, a revocation - * landing while a member self-enrolls, a member removed from the organization between the page's + * landing while a member self-enrolls, a group disabled after the page decided (the refused + * self-enrollment leaving no row), a member removed from the organization between the page's * checks and the start's transaction, a disabled group or unknown provider (indistinguishable from - * an unknown public ID), a provider with two options, a focused link used for another option, an + * an unknown public ID, verified email or not), a provider with two options, a focused link used for another option, an * MCP server or Submit, the saved connection completing the enrollment exactly when the request is - * done, and a link opened again after connecting running the provider's consent again (unless the + * done (a workflow's only once the integration it asked for is connected), and a link opened again after connecting running the provider's consent again (unless the * account needs reconnecting). Only email delivery, the provider code exchange, the workflow * trigger fan-out, and the Enterprise entitlement that turns permission groups on are faked. */ @@ -50,6 +51,7 @@ import { startPublicCredentialGroupOAuth, } from '@/lib/credential-groups/application/public-enrollment' import { connectRequestHandle } from '@/lib/credential-groups/connect-request-handle' +import { issueCredentialGroupConnectLink } from '@/lib/credential-groups/connect-subject' import { authenticatePublicCredentialGroupEnrollment, inviteCredentialGroupEnrollment, @@ -659,28 +661,50 @@ describe('the connect URL', () => { expect(await connectLinksIn(fixture.groupId)).toHaveLength(0) }) - it('answers a disabled group, an unoffered provider and an unknown ID identically', async () => { + it('leaves no enrollment behind when the group is disabled before a member self-enrolls', async () => { + const fixture = await createOrganization() + const teammate = await createPerson() + await addMember(fixture, teammate.userId) + await db + .update(credentialGroup) + .set({ status: 'disabled' }) + .where(eq(credentialGroup.id, fixture.groupId)) + + await expect( + issueCredentialGroupConnectLink({ + credentialGroupId: fixture.groupId, + userId: teammate.userId, + optionId: DRIVE.id, + target: { kind: 'self_enrollment', mayEnroll: async () => true }, + }) + ).resolves.toEqual({ issued: false, reason: 'unavailable' }) + expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) + }) + + it('answers a disabled group, an unoffered provider and an unknown ID identically, verified or not', async () => { const fixture = await createOrganization() const disabled = await createOrganization() - const person = await createPerson() - await invite(disabled, person.email) + const verified = await createPerson() + const unverified = await createPerson(false) + await invite(disabled, verified.email) + await invite(disabled, unverified.email) await db .update(credentialGroup) .set({ status: 'disabled' }) .where(eq(credentialGroup.id, disabled.groupId)) - const unknown = await startTarget(person.userId, { publicId: generateId() }) - expect(unknown).toEqual({ kind: 'unavailable' }) - await expect(startTarget(person.userId, { publicId: disabled.publicId })).resolves.toEqual( - unknown - ) + for (const person of [verified, unverified]) { + for (const input of [ + { publicId: generateId() }, + { publicId: disabled.publicId }, + { publicId: fixture.publicId, provider: 'slack' }, + { publicId: fixture.publicId, provider: 'not-a-provider' }, + ]) { + await expect(openTarget(person.userId, input)).resolves.toEqual({ kind: 'unavailable' }) + await expect(startTarget(person.userId, input)).resolves.toEqual({ kind: 'unavailable' }) + } + } expect(await connectLinksIn(disabled.groupId)).toHaveLength(0) - await expect( - startTarget(person.userId, { publicId: fixture.publicId, provider: 'slack' }) - ).resolves.toEqual(unknown) - await expect( - startTarget(person.userId, { publicId: fixture.publicId, provider: 'not-a-provider' }) - ).resolves.toEqual(unknown) }) it('asks which account to connect when the provider has two options', async () => { @@ -892,7 +916,7 @@ describe('a focused connect link', () => { await invite(fixture, requested.email) await db .update(credentialGroupEnrollment) - .set({ requestedByWorkflowId: 'workflow-1' }) + .set({ requestedByWorkflowId: 'workflow-1', requestedProviderId: DRIVE_PROVIDER_ID }) .where(eq(credentialGroupEnrollment.email, requested.email)) for (const person of [invited, requested]) { @@ -914,6 +938,40 @@ describe('a focused connect link', () => { expect((await enrollmentOf(fixture.groupId, requested.email)).status).toBe('completed') }) + it("keeps a workflow's request open when the focused connection is for another integration", async () => { + const fixture = await createOrganization([ + driveOption('drive-work', 'Work Drive'), + driveOption('drive-shared', 'Shared Drive'), + ]) + const person = await createPerson() + await invite(fixture, person.email) + await db + .update(credentialGroupEnrollment) + .set({ requestedByWorkflowId: 'workflow-1', requestedProviderId: 'google-calendar' }) + .where(eq(credentialGroupEnrollment.email, person.email)) + const token = await readyToken(person.userId, { + publicId: fixture.publicId, + optionId: 'drive-work', + }) + const principal = await principalFor(token, person.userId) + + await completePublicCredentialGroupOAuth.execute({ + principal, + input: { + attempt: attemptFor(fixture, principal, token, 'drive-work'), + code: `${person.userId}@drive.test`, + }, + }) + + const enrollment = await enrollmentOf(fixture.groupId, person.email) + expect(enrollment.status).toBe('in_progress') + expect( + triggerEvents.some( + (event) => event.enrollmentId === enrollment.id && event.event === 'form_submitted' + ) + ).toBe(false) + }) + it('leaves an enrollment connected through an unfocused link for Submit', async () => { const fixture = await createOrganization() const person = await createPerson() @@ -945,7 +1003,7 @@ describe('a focused connect link', () => { }) const after = await enrollmentOf(fixture.groupId, person.email) - expect(after.status).not.toBe('completed') + expect(after.status).toBe('in_progress') expect( triggerEvents.some( (event) => event.enrollmentId === enrollment.id && event.event === 'form_submitted' diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts index 21f7e6df8c0..2aa4e503539 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts @@ -1,7 +1,8 @@ /** * What a signed-in person is told when an invitation link does not open, against real Postgres so * the token lookup, the joins that name the organization and inviter, and the identity check run - * on stored rows. Failure modes: an unknown token, a forwarded link opened by someone else (who + * on stored rows. Failure modes: an unknown token, a viewer whose email is unverified claiming the + * enrollment at that address, a forwarded link opened by someone else (who * must learn nothing but a masked address, whatever state the enrollment is in), a revoked * enrollment, a disabled group, a failed delivery (which no longer stops a live link, so is never * the explanation), an expired link, an expired connect-page link (sent back to start again), and @@ -26,13 +27,19 @@ vi.mock('@/lib/credential-groups/scoped-availability', () => ({ isScopedCredentialGroupsAvailable: async () => true, })) +vi.mock('@/lib/messaging/email/verification', () => ({ + isEmailVerificationEffectivelyEnabled: () => true, +})) + const inviterId = generateId() const inviteeId = generateId() const strangerId = generateId() const shouterId = generateId() +const unverifiedId = generateId() const inviteeEmail = `invitee-${inviteeId}@example.test` const strangerEmail = `stranger-${strangerId}@example.test` const shouterEmail = `SHOUTER-${shouterId}@EXAMPLE.TEST` +const unverifiedEmail = `unverified-${unverifiedId}@example.test` const invitee = { id: inviteeId } const stranger = { id: strangerId } const DAY_MS = 24 * 60 * 60 * 1000 @@ -145,12 +152,22 @@ beforeAll(async () => { { id: shouterId, name: 'Shouter', email: shouterEmail }, ].map((row) => ({ ...row, emailVerified: true, createdAt: now, updatedAt: now })) ) + await db.insert(user).values({ + id: unverifiedId, + name: 'Unverified', + email: unverifiedEmail, + emailVerified: false, + createdAt: now, + updatedAt: now, + }) }) afterAll(async () => { await db.delete(credentialGroup).where(inArray(credentialGroup.organizationId, organizationIds)) await db.delete(organization).where(inArray(organization.id, organizationIds)) - await db.delete(user).where(inArray(user.id, [inviterId, inviteeId, strangerId, shouterId])) + await db + .delete(user) + .where(inArray(user.id, [inviterId, inviteeId, strangerId, shouterId, unverifiedId])) }) describe('explainCredentialGroupEnrollmentLink', () => { @@ -158,6 +175,15 @@ describe('explainCredentialGroupEnrollmentLink', () => { await expect(explain(generateId(), invitee)).resolves.toEqual({ kind: 'unknown' }) }) + it('tells a person whose email is unverified nothing about the enrollment at that address', async () => { + const token = await seedEnrollment({ + email: unverifiedEmail, + status: 'revoked', + revokedAt: new Date(), + }) + await expect(explain(token, { id: unverifiedId })).resolves.toEqual({ kind: 'unknown' }) + }) + it('tells the invitee an expired unbound link needs reissuing by its inviter', async () => { const token = await seedEnrollment({ email: inviteeEmail, diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts index c345151d90a..2801b564bbe 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts @@ -524,9 +524,12 @@ describe('credential group enrollment links', () => { }) const holderPid = await locked const completion = completeAuthorizedCredentialGroupEnrollment(identity) - await waitForBlockedBy(holderPid) - release() - await revocation + try { + await waitForBlockedBy(holderPid) + } finally { + release() + await revocation + } await expect(completion).resolves.toBeNull() expect(await enrollmentRow(self.enrollmentId)).toMatchObject({ diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index c89d8f4d717..a8af0def75a 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -6,7 +6,8 @@ * Failure modes: a workflow learning more than connected / not_connected / needs_reconnect; a * workspace outside the Access allowlist reading status; another organization's accounts leaking * in; a request without (or outside) the admin policy succeeding; a request reactivating a revoked - * person or re-attributing an admin invitation; concurrent requests creating two rows; the daily + * person or re-attributing an admin invitation; a later workflow's request leaving the earlier + * workflow named for the integration it asked for; concurrent requests creating two rows; the daily * cap being exceeded, or skipped for an address that already has an enrollment; the cap error * differing by target, or a repeat for an address asked today passing once the cap is hit; a `+` * alias slipping in; reminders beyond the per-enrollment cap or after 30 days; a revocation racing @@ -161,11 +162,15 @@ interface OrgFixture { const ownerId = generateId() const workflowId = generateId() +/** The workflow whose name the email delivery suite renders. */ +const namedWorkflowId = generateId() const domain = `${generateId().slice(0, 12).toLowerCase()}.test` const people = new Map() let orgA: OrgFixture let orgB: OrgFixture let orgC: OrgFixture +/** Organizations a single test creates for itself, removed with the shared ones. */ +const ownOrganizationIds: string[] = [] const DAY_MS = 24 * 60 * 60 * 1000 const address = (label: string) => `${label}@${domain}` @@ -251,7 +256,10 @@ const OPEN_POLICY: ConnectionRequestPolicy = { } /** An actorless deployed run: no subject, so no role check stands between it and the policy. */ -function deployedRun(workspaceId: string): WorkflowExecutionDelegatedPrincipal { +function deployedRun( + workspaceId: string, + runWorkflowId = workflowId +): WorkflowExecutionDelegatedPrincipal { const issuedAt = new Date(Date.now() - 1000) return { kind: 'delegated', @@ -263,9 +271,13 @@ function deployedRun(workspaceId: string): WorkflowExecutionDelegatedPrincipal { expiresAt: new Date(issuedAt.getTime() + 60_000), delegationContext: { kind: 'workflow_execution', - workflowId, - principal: { kind: 'system', serviceId: 'schedule', workspaceId, workflowId }, - currentWorkflow: { workflowId, mode: 'deployment', deploymentVersionId: generateId() }, + workflowId: runWorkflowId, + principal: { kind: 'system', serviceId: 'schedule', workspaceId, workflowId: runWorkflowId }, + currentWorkflow: { + workflowId: runWorkflowId, + mode: 'deployment', + deploymentVersionId: generateId(), + }, }, } } @@ -280,10 +292,11 @@ const request = ( fixture: OrgFixture, email: string, workspaceId = fixture.workspaceId, - providerId = DRIVE_ID + providerId = DRIVE_ID, + runWorkflowId = workflowId ) => requestOrganizationAccountConnection.execute({ - principal: deployedRun(workspaceId), + principal: deployedRun(workspaceId, runWorkflowId), input: { workspaceId, email, providerId }, }) @@ -459,12 +472,13 @@ afterAll(async () => { .where( and( eq(outboxEvent.eventType, CONNECTION_REQUEST_EMAIL_EVENT), - sql`${outboxEvent.payload} ->> 'workflowId' = ${workflowId}` + inArray(sql`${outboxEvent.payload} ->> 'workflowId'`, [workflowId, namedWorkflowId]) ) ) - const organizations = [orgA, orgB, orgC].flatMap((fixture) => - fixture ? [fixture.organizationId] : [] - ) + const organizations = [ + ...[orgA, orgB, orgC].flatMap((fixture) => (fixture ? [fixture.organizationId] : [])), + ...ownOrganizationIds, + ] await deleteWorkspaceFixture(db, inArray(workspace.organizationId, organizations)) await db.delete(organization).where(inArray(organization.id, organizations)) await db.delete(user).where(inArray(user.id, [ownerId, ...people.values()])) @@ -854,6 +868,29 @@ describe('connection request emails', () => { expect(links).toEqual([]) }) + it('records the latest workflow and integration together when another workflow asks', async () => { + const fixture = await createOrg() + ownOrganizationIds.push(fixture.organizationId) + const calendar = { ...DRIVE, id: 'option-calendar', provider: 'google-calendar' as const } + const calendarId = getCredentialGroupProviderId('google-calendar') + await db + .update(credentialGroup) + .set({ options: [DRIVE, calendar] }) + .where(eq(credentialGroup.id, fixture.groupId)) + await setRequestPolicy(fixture, { ...OPEN_POLICY, providers: [DRIVE_ID, calendarId] }) + const email = address('second-workflow') + const secondWorkflowId = generateId() + + await request(fixture, email) + await request(fixture, email, fixture.workspaceId, calendarId, secondWorkflowId) + + const [after] = await enrollmentsFor(fixture, email) + expect(after).toMatchObject({ + requestedByWorkflowId: secondWorkflowId, + requestedProviderId: calendarId, + }) + }) + it('sends one reminder when a workflow asks again several times at once', async () => { const email = address('reminded-at-once') await request(orgA, email) @@ -894,24 +931,25 @@ describe('connection request emails', () => { }) const holderPid = await locked const reminder = request(orgA, email) - await waitForBlockedBy(holderPid) - release() - await revocation + try { + await waitForBlockedBy(holderPid) + } finally { + release() + await revocation + } expect(await reminder).toMatchObject({ requested: true }) expect(await emailEvents(enrollment.id)).toHaveLength(1) }) }) describe('connection request email delivery', () => { - const namedWorkflowId = generateId() - beforeAll(async () => { const now = new Date() await db.insert(workflow).values({ id: namedWorkflowId, userId: ownerId, workspaceId: orgA.workspaceId, - name: `\u202Eexe.pdf\u0007 Payroll\n\n bot ${'x'.repeat(80)}`, + name: `\u202Eexe.pdf\u0007 Payroll\nbot ${'x'.repeat(80)}`, lastSynced: now, createdAt: now, updatedAt: now, diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts index 4edd76cf477..e96721b6999 100644 --- a/apps/sim/lib/credential-groups/application/connect-target.ts +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -176,7 +176,6 @@ async function decideConnectTarget( publicId: input.publicId, userId: principal.userId, }) - if (subject && !isCredentialGroupEmailVerified(subject.viewer)) return { kind: 'verify_email' } if (!subject || subject.group.status !== 'active') return UNAVAILABLE const { group, enrollment, viewer } = subject const provider = findCredentialGroupProviderFromProviderId(input.provider) @@ -190,6 +189,7 @@ async function decideConnectTarget( ) const [option] = options if (!option) return UNAVAILABLE + if (!isCredentialGroupEmailVerified(viewer)) return { kind: 'verify_email' } const { organizationName } = group if ( diff --git a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts index 1f1c157e078..8e5eceff3b3 100644 --- a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts +++ b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts @@ -2,12 +2,13 @@ import type { SessionPrincipal } from '@sim/auth/principal' import { normalizeEmail } from '@sim/utils/string' import { defineOperation } from '@/lib/core/application' import { maskEnrollmentEmail } from '@/lib/credential-groups/email-mask' -import { loadCredentialGroupInviterIdentity } from '@/lib/credential-groups/enrollments' +import { loadCredentialGroupViewer } from '@/lib/credential-groups/enrollments' import { findCredentialGroupEnrollmentLinkRecord } from '@/lib/credential-groups/links' import { getCredentialGroupProviderId, isCredentialGroupProvider, } from '@/lib/credential-groups/providers' +import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' import { defineAuthorizedCredentialUserUseCase } from '@/lib/credentials/application/authorized-user-use-case' const credentialGroupEnrollmentLinkOperations = { @@ -23,9 +24,9 @@ const credentialGroupEnrollmentLinkOperations = { } as const /** - * Why an invitation link did not open for a signed-in, verified person. Enrollment details are - * only described to the person the enrollment belongs to; anyone else holding the link learns - * just a masked form of the address it was sent to. `reopen` is an expired connect-page link: + * Why an invitation link did not open for a signed-in, verified person; anyone unverified learns + * only `unknown`. Enrollment details are only described to the person the enrollment belongs to; + * anyone else holding the link learns just a masked form of the address it was sent to. `reopen` is an expired connect-page link: * the person starts again from the connect URL, which mints a fresh one. */ export type CredentialGroupEnrollmentLinkOutcome = @@ -63,9 +64,9 @@ export const explainCredentialGroupEnrollmentLink = defineAuthorizedCredentialUs }): Promise { const [record, viewer] = await Promise.all([ findCredentialGroupEnrollmentLinkRecord(input.invitationToken), - loadCredentialGroupInviterIdentity(principal.userId), + loadCredentialGroupViewer(principal.userId), ]) - if (!record || !viewer) return { kind: 'unknown' } + if (!record || !viewer || !isCredentialGroupEmailVerified(viewer)) return { kind: 'unknown' } const belongsToUser = record.userId ? record.userId === principal.userId diff --git a/apps/sim/lib/credential-groups/connect-subject.ts b/apps/sim/lib/credential-groups/connect-subject.ts index f41fd3c5828..4fde05703a6 100644 --- a/apps/sim/lib/credential-groups/connect-subject.ts +++ b/apps/sim/lib/credential-groups/connect-subject.ts @@ -18,6 +18,7 @@ import { } from '@/lib/credential-groups/enrollment-lifecycle' import { findOrCreateUnissuedEnrollment, + loadCredentialGroupViewer, lockCredentialGroupEnrollmentLifecycle, } from '@/lib/credential-groups/enrollments' import { insertEnrollmentLink } from '@/lib/credential-groups/links' @@ -57,11 +58,7 @@ export async function loadCredentialGroupConnectSubject(input: { publicId: string userId: string }): Promise { - const [viewer] = await db - .select({ email: user.email, emailVerified: user.emailVerified }) - .from(user) - .where(eq(user.id, input.userId)) - .limit(1) + const viewer = await loadCredentialGroupViewer(input.userId) if (!viewer) return null const [group] = await db .select({ @@ -170,7 +167,27 @@ type IssuedCredentialGroupConnectLink = /** An expired request was renewed for this link. */ renewed: boolean } - | { issued: false; reason: 'revoked' | 'expired' | 'unavailable' } + | { issued: false; reason: ConnectLinkRefusalReason } + +type ConnectLinkRefusalReason = 'revoked' | 'expired' | 'unavailable' + +interface ConnectLinkInput { + credentialGroupId: string + userId: string + optionId: string + target: CredentialGroupConnectLinkTarget +} + +/** + * A refusal decided inside the link's transaction. Thrown rather than returned so the transaction + * rolls back: a refusal found after the self-enrollment insert leaves no enrollment behind. + */ +class ConnectLinkRefusal extends Error { + constructor(readonly reason: ConnectLinkRefusalReason) { + super(`Connect link refused: ${reason}`) + this.name = 'ConnectLinkRefusal' + } +} /** * Mints a short-lived link focused on one account option and, in the same transaction, creates @@ -178,95 +195,98 @@ type IssuedCredentialGroupConnectLink = * unbound one, renewing an expired request a member may answer. The enrollment's lifecycle lock * serializes it with revocation, so a revocation that commits first is reported as `revoked` and * a later one kills the new link. Inserts a link row only: an existing enrollment's issuer, - * timestamps and status stay as they are. + * timestamps and status stay as they are. A refusal writes nothing. * * The caller has already decided the person may connect; this re-checks, under the lock, only what * may have changed since: revocation, expiry, the group still being active, the binding, that the * person's verified email still matches an unbound enrollment, and, for a member enrolling * themselves or renewing their expired request, that they still pass the member self-enroll checks. */ -export async function issueCredentialGroupConnectLink(input: { - credentialGroupId: string - userId: string - optionId: string - target: CredentialGroupConnectLinkTarget -}): Promise { - return db.transaction(async (tx) => { - const now = new Date() - const [viewer] = await tx - .select({ email: user.email, emailVerified: user.emailVerified }) - .from(user) - .where(eq(user.id, input.userId)) - .limit(1) - if (!viewer || !isCredentialGroupEmailVerified(viewer)) - return { issued: false, reason: 'unavailable' } - const viewerEmail = normalizeEmail(viewer.email) - - const { target } = input - let enrollmentId = target.kind === 'self_enrollment' ? null : target.enrollmentId - let created = false - if (enrollmentId === null) { - if (target.kind === 'self_enrollment' && !(await target.mayEnroll(tx))) - return { issued: false, reason: 'unavailable' } - const enrollment = await findOrCreateUnissuedEnrollment(tx, { - credentialGroupId: input.credentialGroupId, - email: viewerEmail, - now, - }) - enrollmentId = enrollment.row.id - created = enrollment.created - } else { - await lockCredentialGroupEnrollmentLifecycle(tx, enrollmentId) - if (target.kind === 'renew_expired_enrollment' && !(await target.mayEnroll(tx))) - return { issued: false, reason: 'unavailable' } - } +export async function issueCredentialGroupConnectLink( + input: ConnectLinkInput +): Promise { + try { + return await db.transaction(async (tx) => issueConnectLinkInTransaction(tx, input)) + } catch (error) { + if (error instanceof ConnectLinkRefusal) return { issued: false, reason: error.reason } + throw error + } +} - const [current] = await tx - .select({ - email: credentialGroupEnrollment.email, - userId: credentialGroupEnrollment.userId, - status: credentialGroupEnrollment.status, - invitationExpiresAt: credentialGroupEnrollment.invitationExpiresAt, - groupStatus: credentialGroup.status, - }) - .from(credentialGroupEnrollment) - .innerJoin( - credentialGroup, - eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId) - ) - .where( - and( - eq(credentialGroupEnrollment.id, enrollmentId), - eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId) - ) - ) - .limit(1) - if (!current) return { issued: false, reason: 'unavailable' } - if (isEnrollmentRevoked(current)) return { issued: false, reason: 'revoked' } - const renewed = - target.kind === 'renew_expired_enrollment' && isEnrollmentRequestExpired(current, now) - if (!renewed && isEnrollmentRequestExpired(current, now)) - return { issued: false, reason: 'expired' } - if (current.groupStatus !== 'active') return { issued: false, reason: 'unavailable' } - if (current.userId ? current.userId !== input.userId : current.email !== viewerEmail) - return { issued: false, reason: 'unavailable' } +async function issueConnectLinkInTransaction( + tx: DbTransaction, + input: ConnectLinkInput +): Promise> { + const now = new Date() + const [viewer] = await tx + .select({ email: user.email, emailVerified: user.emailVerified }) + .from(user) + .where(eq(user.id, input.userId)) + .limit(1) + if (!viewer || !isCredentialGroupEmailVerified(viewer)) + throw new ConnectLinkRefusal('unavailable') + const viewerEmail = normalizeEmail(viewer.email) - const bound = !current.userId - if (bound) - await tx - .update(credentialGroupEnrollment) - .set({ - userId: input.userId, - ...(renewed ? { invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS) } : {}), - updatedAt: now, - }) - .where(eq(credentialGroupEnrollment.id, enrollmentId)) - const { token } = await insertEnrollmentLink(tx, { - enrollmentId, - purpose: 'connect', - optionId: input.optionId, + const { target } = input + let enrollmentId = target.kind === 'self_enrollment' ? null : target.enrollmentId + let created = false + if (enrollmentId === null) { + if (target.kind === 'self_enrollment' && !(await target.mayEnroll(tx))) + throw new ConnectLinkRefusal('unavailable') + const enrollment = await findOrCreateUnissuedEnrollment(tx, { + credentialGroupId: input.credentialGroupId, + email: viewerEmail, now, }) - return { issued: true, token, enrollmentId, created, bound, renewed } + enrollmentId = enrollment.row.id + created = enrollment.created + } else { + await lockCredentialGroupEnrollmentLifecycle(tx, enrollmentId) + if (target.kind === 'renew_expired_enrollment' && !(await target.mayEnroll(tx))) + throw new ConnectLinkRefusal('unavailable') + } + + const [current] = await tx + .select({ + email: credentialGroupEnrollment.email, + userId: credentialGroupEnrollment.userId, + status: credentialGroupEnrollment.status, + invitationExpiresAt: credentialGroupEnrollment.invitationExpiresAt, + groupStatus: credentialGroup.status, + }) + .from(credentialGroupEnrollment) + .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) + .where( + and( + eq(credentialGroupEnrollment.id, enrollmentId), + eq(credentialGroupEnrollment.credentialGroupId, input.credentialGroupId) + ) + ) + .limit(1) + if (!current) throw new ConnectLinkRefusal('unavailable') + if (isEnrollmentRevoked(current)) throw new ConnectLinkRefusal('revoked') + const renewed = + target.kind === 'renew_expired_enrollment' && isEnrollmentRequestExpired(current, now) + if (!renewed && isEnrollmentRequestExpired(current, now)) throw new ConnectLinkRefusal('expired') + if (current.groupStatus !== 'active') throw new ConnectLinkRefusal('unavailable') + if (current.userId ? current.userId !== input.userId : current.email !== viewerEmail) + throw new ConnectLinkRefusal('unavailable') + + const bound = !current.userId + if (bound) + await tx + .update(credentialGroupEnrollment) + .set({ + userId: input.userId, + ...(renewed ? { invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS) } : {}), + updatedAt: now, + }) + .where(eq(credentialGroupEnrollment.id, enrollmentId)) + const { token } = await insertEnrollmentLink(tx, { + enrollmentId, + purpose: 'connect', + optionId: input.optionId, + now, }) + return { issued: true, token, enrollmentId, created, bound, renewed } } diff --git a/apps/sim/lib/credential-groups/connection-request-email.ts b/apps/sim/lib/credential-groups/connection-request-email.ts index ac4eed53a28..9e78565d2a9 100644 --- a/apps/sim/lib/credential-groups/connection-request-email.ts +++ b/apps/sim/lib/credential-groups/connection-request-email.ts @@ -46,13 +46,14 @@ function parsePayload(payload: unknown): ConnectionRequestEmailPayload { /** * The requesting workflow's name as the email body shows it. The name is whatever its builder - * typed, so control and invisible formatting characters (which could reorder or hide text) are - * removed, whitespace is collapsed, and it is cut to {@link WORKFLOW_NAME_MAX_LENGTH} characters. + * typed, so whitespace (line breaks and tabs included) is collapsed to single spaces, the + * remaining control and invisible formatting characters (which could reorder or hide text) are + * removed, and it is cut to {@link WORKFLOW_NAME_MAX_LENGTH} characters. */ function connectionRequestWorkflowName(name: string | undefined): string { const cleaned = (name ?? '') - .replace(/[\p{Cc}\p{Cf}]/gu, '') .replace(/\s+/g, ' ') + .replace(/[\p{Cc}\p{Cf}]/gu, '') .trim() return cleaned ? truncateAtCodePoint(cleaned, WORKFLOW_NAME_MAX_LENGTH, '…') : 'A workflow' } diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index d42f5e97a52..c5ddd20ddd2 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -203,20 +203,25 @@ interface RecordedConnectionRequest { emailEventId: string | null } -/** Starts a new wait for an unbound enrollment nobody revoked; any other enrollment is left alone. */ +/** + * Starts a new wait for an unbound enrollment nobody revoked; any other enrollment is left alone. + * A workflow's open request then records this, the latest, request: the workflow and the + * integration it asked for change together, so a reminder names the workflow that asked for that + * integration. An admin's invitation keeps its attribution. + */ async function renewEnrollmentRequest( tx: DbTransaction, enrollment: EnrollmentRow, now: Date, - requestedProviderId?: string + request: { workflowId: string; providerId: string } ): Promise { if (enrollment.userId !== null || isEnrollmentRevoked(enrollment)) return await tx .update(credentialGroupEnrollment) .set({ invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), - ...(requestedProviderId && enrollment.requestedByWorkflowId !== null - ? { requestedProviderId } + ...(enrollment.requestedByWorkflowId !== null + ? { requestedByWorkflowId: request.workflowId, requestedProviderId: request.providerId } : {}), updatedAt: now, }) @@ -244,9 +249,10 @@ function enqueueConnectionRequestEmail( * same person cost no slot. The per-email invitation lock is the one admin invitations * take, so a request never races an invite for the same address. * - * Only an absent enrollment is created. An existing one keeps its status and attribution: a - * revoked person stays revoked, an admin's invitation stays the admin's, and a connected person - * stays connected. An unbound one is renewed (it waits {@link INVITATION_TTL_MS} again). A + * Only an absent enrollment is created. An existing one keeps its status: a revoked person stays + * revoked, an admin's invitation stays the admin's, and a connected person stays connected. An + * unbound one is renewed (it waits {@link INVITATION_TTL_MS} again), and a workflow's open request + * then records the latest workflow and integration asked for. A * reminder goes out only for an unbound, still-invited enrollment a workflow created (including one * whose last email failed): when nobody asked for this address in the last day, the enrollment was * requested within {@link CONNECTION_REQUEST_REMINDER_WINDOW_MS}, and it has had fewer than @@ -328,7 +334,10 @@ export async function recordCredentialGroupConnectionRequest(input: { : null, } - await renewEnrollmentRequest(tx, row, now, input.providerId) + await renewEnrollmentRequest(tx, row, now, { + workflowId: input.workflowId, + providerId: input.providerId, + }) if (!input.sendEmail || askedToday || row.requestedByWorkflowId === null) return { enrollmentId: row.id, created, emailEventId: null } const [reminded] = await tx diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 3fed2b04cd6..149dde573af 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -13,20 +13,7 @@ import { import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { normalizeEmail, truncate } from '@sim/utils/string' -import { - and, - asc, - count, - countDistinct, - desc, - eq, - inArray, - isNull, - lt, - or, - type SQL, - sql, -} from 'drizzle-orm' +import { and, asc, count, desc, eq, inArray, isNull, lt, or, type SQL, sql } from 'drizzle-orm' import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' import { getCredentialGroupInvitationSubject } from '@/components/emails/subjects' import { searchFilter } from '@/lib/api/list-query' @@ -59,6 +46,7 @@ import type { CredentialGroupProvider } from '@/lib/credential-groups/providers' import { CREDENTIAL_GROUP_PROVIDER_IDS, getCredentialGroupProviderFromProviderId, + getCredentialGroupProviderId, isCredentialGroupProvider, } from '@/lib/credential-groups/providers' import { credentialGroupScope } from '@/lib/credential-groups/scope' @@ -1022,6 +1010,18 @@ export async function inviteCredentialGroupEnrollments( return { results, sentCount, failedCount: results.length - sentCount } } +/** The signed-in person's address and whether it is verified, or null for an unknown user. */ +export async function loadCredentialGroupViewer( + userId: string +): Promise<{ email: string; emailVerified: boolean } | null> { + const [row] = await db + .select({ email: user.email, emailVerified: user.emailVerified }) + .from(user) + .where(eq(user.id, userId)) + .limit(1) + return row ?? null +} + export async function loadCredentialGroupInviterIdentity( userId: string ): Promise<{ name: string | null; email: string } | null> { @@ -1366,32 +1366,46 @@ async function buildPublicCredentialGroupEnrollment( /** * Whether a connection made through a focused link finishes the enrollment on its own: a - * workflow's request asked for that one integration, and anyone else is done once every active - * account option has a live connection. Otherwise the enrollment stays open for its other options. + * workflow's request is done once the integration it asked for has a live connection, and any + * enrollment is done once every active account option has one. Otherwise the enrollment stays + * open for its other options. */ export async function isFocusedConnectionComplete( identity: PublicCredentialGroupEnrollmentIdentity ): Promise { const row = await resolveAuthorizedPublicEnrollmentRow(identity) if (!row) return false - if (row.enrollment.requestedByWorkflowId !== null) return true - const activeOptionIds = row.options - .filter((option) => option.status === 'active') - .map((option) => option.id) - if (activeOptionIds.length === 0) return false - const [connected] = await db - .select({ options: countDistinct(credential.credentialGroupOptionId) }) + const activeOptions = row.options.filter((option) => option.status === 'active') + if (activeOptions.length === 0) return false + const connected = await db + .selectDistinct({ optionId: credential.credentialGroupOptionId }) .from(credential) .where( and( eq(credential.type, 'managed_oauth'), eq(credential.credentialGroupEnrollmentId, row.enrollment.id), - inArray(credential.credentialGroupOptionId, activeOptionIds), + inArray( + credential.credentialGroupOptionId, + activeOptions.map((option) => option.id) + ), eq(credential.managedOauthStatus, 'active'), isNull(credential.revokedAt) ) ) - return (connected?.options ?? 0) === activeOptionIds.length + const connectedOptionIds = new Set(connected.map((connection) => connection.optionId)) + const requestedProviderId = + row.enrollment.requestedByWorkflowId !== null ? row.enrollment.requestedProviderId : null + if ( + requestedProviderId !== null && + activeOptions.some( + (option) => + connectedOptionIds.has(option.id) && + isCredentialGroupProvider(option.provider) && + getCredentialGroupProviderId(option.provider) === requestedProviderId + ) + ) + return true + return activeOptions.every((option) => connectedOptionIds.has(option.id)) } /** Finalizes an enrollment after the recipient finishes their optional account selections. */ diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index dfbf2e1e246..c5d0e06bfc5 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -6,7 +6,8 @@ * and keeps nothing else: no Agent memory (which its Agents still read), no workspace event, no run * count. An MCP write is authorized before it is answered, and its check leaves the server's health * as it found it. An allowed block writes for real while reads run for real; a child workflow's - * writes, an Agent's included, stay stubbed; custom and Wait blocks are answered whole; code runs + * writes, an Agent's included, stay stubbed; custom and Wait blocks, and a Credential block's + * connection request, are answered whole; code runs * (a Condition's expressions and a While loop's condition included) and its isolate `fetch` writes * are stubbed; a mocked block steers a branch; a failed dry run keeps its side effects and is the source only of * another dry run. A test run is never the source of a run that sends its writes (the v2 use case, @@ -1147,6 +1148,29 @@ describe('a dry run', () => { } }) + it('answers a Credential block’s connection request whole, so nobody is asked to connect', async () => { + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('ask', 'credential', { + operation: 'request_connection', + email: 'person@b.co', + organizationProvider: 'google-drive', + }), + ], + [['start', 'ask']] + ).state + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.stubbed.map((entry) => [entry.block, entry.tool])).toEqual([ + ['ask', null], + ]) + }) + it('runs code for real, listing neither a Function block nor a Condition that sends nothing', async () => { const tableId = await createTable() const gate = condition('gate', ' > 50') diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index 192ba321625..0ac3c25d45d 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -26,8 +26,26 @@ const MAX_RECORDED = 50 /** The tool a stubbed or allowed network request of code is recorded under. */ const CODE_TOOL_ID = 'function_execute' -/** Blocks whose handlers change state outside the tool seam, so a policy answers them whole. */ -const SELF_DIRECTED_BLOCK_TYPES: ReadonlySet = new Set([BlockType.MOTHERSHIP, BlockType.PI]) +type SelfDirectedOperations = 'all' | ReadonlySet + +/** + * Blocks whose handlers change state outside the tool seam, so a policy answers them whole: every + * operation of the block, or only the operations listed (the rest only read). + */ +const SELF_DIRECTED_BLOCKS: ReadonlyMap = new Map< + string, + SelfDirectedOperations +>([ + [BlockType.MOTHERSHIP, 'all'], + [BlockType.PI, 'all'], + [BlockType.CREDENTIAL, new Set(['request_connection'])], +]) + +function actsOutsideToolSeam(block: SideEffectBlockSite): boolean { + const operations = SELF_DIRECTED_BLOCKS.get(block.blockType) + if (operations === undefined) return false + return operations === 'all' || (block.operation !== null && operations.has(block.operation)) +} /** * Blocks that pause the run. A test run is never resumed, so a policy answers them whole and the @@ -206,11 +224,11 @@ class RecordedList { * in the isolate its reads (`isReadRequest`) are sent, unless they would send a placeholder, and any * other request is answered with an empty 200 and recorded like a write, while code in a remote * sandbox, whose network the run cannot see, is listed unchecked. Custom blocks and - * {@link PAUSING_BLOCK_TYPES} are answered whole, as is a block that acts outside the tool seam - * unless it is allowed, and `blockMocks` answers its blocks with fixed outputs. An allowed or - * mocked block is keyed by its workflow and block id, so one of a child applies wherever that - * child runs, at every depth, and an allowed Agent's own tool calls are sent, not a workflow or - * custom block it calls. + * {@link PAUSING_BLOCK_TYPES} are answered whole, as is a block (or a block's operation) that acts + * outside the tool seam unless it is allowed, and `blockMocks` answers its blocks with fixed + * outputs. An allowed or mocked block is keyed by its workflow and block id, so one of a child + * applies wherever that child runs, at every depth, and an allowed Agent's own tool calls are + * sent, not a workflow or custom block it calls. */ export class WriteStubPolicy implements SideEffectPolicy { private readonly stubbed = new RecordedList() @@ -335,7 +353,7 @@ export class WriteStubPolicy implements SideEffectPolicy { if (this.mockOf(block)) return true if (PAUSING_BLOCK_TYPES.has(block.blockType)) return true if (isCustomBlockType(block.blockType)) return true - if (!SELF_DIRECTED_BLOCK_TYPES.has(block.blockType)) return false + if (!actsOutsideToolSeam(block)) return false if (!this.allows(block)) return true this.allowed.add({ ...recordedSite(block), tool: null }, `${block.workflowId}:${block.blockId}`) return false diff --git a/packages/db/schema.ts b/packages/db/schema.ts index b5891f92384..f6e07656849 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7468,9 +7468,12 @@ export const credentialGroupEnrollment = pgTable( revokedAt: timestamp('revoked_at'), lastDeliveryError: text('last_delivery_error'), createdBy: text('created_by').references(() => user.id, { onDelete: 'set null' }), - /** Set when a workflow's connection request created the row; an admin invitation clears it. */ + /** + * Set when a workflow's connection request created the row, then moved to the workflow that + * asked most recently; an admin invitation clears it. + */ requestedByWorkflowId: text('requested_by_workflow_id'), - /** The credential provider the workflow last asked for, so a reminder asks for it again. */ + /** The credential provider that workflow asked for, so a reminder asks for it again. */ requestedProviderId: text('requested_provider_id'), /** Reminder emails sent for a workflow-requested enrollment after its first invitation. */ connectionRequestReminders: integer('connection_request_reminders').notNull().default(0), From 5d63872b41297f81f91cbd928c495093088dcce0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 18:15:31 -0600 Subject: [PATCH 25/26] fix(credential-groups): deliver a request email only while its request is current --- ...orkflow-connection-requests.integration.ts | 22 ++++++++++++++-- .../connection-request-email.ts | 25 +++++++++++++------ .../connection-request-event.ts | 2 ++ .../credential-groups/connection-requests.ts | 2 ++ packages/db/schema.ts | 7 +++--- 5 files changed, 45 insertions(+), 13 deletions(-) diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index a8af0def75a..1138244d611 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -967,10 +967,10 @@ describe('connection request email delivery', () => { mail.failWith = null }) - /** A request that enqueued no email, so the test delivers it explicitly. */ + /** A request by the named workflow that enqueued no email, so the test delivers it explicitly. */ async function requestedEnrollment(label: string) { const email = address(label) - await request(orgA, email) + await request(orgA, email, orgA.workspaceId, DRIVE_ID, namedWorkflowId) const [enrollment] = await enrollmentsFor(orgA, email) if (!enrollment) throw new Error('Request created no enrollment') return { email, enrollmentId: enrollment.id } @@ -983,6 +983,7 @@ describe('connection request email delivery', () => { { enrollmentId, workflowId: namedWorkflowId, + providerId: DRIVE_ID, providerName: DRIVE.label, connectUrl: buildCredentialGroupConnectUrl({ publicId: orgA.publicId, provider: DRIVE_ID }), ...(reminder ? { reminder } : {}), @@ -1048,6 +1049,23 @@ describe('connection request email delivery', () => { }) }) + it('sends nothing, and records nothing, once a later workflow request has replaced this one', async () => { + const { email, enrollmentId } = await requestedEnrollment('superseded-request') + await request(orgA, email, orgA.workspaceId, DRIVE_ID, workflowId) + const replaced = await enrollmentRow(enrollmentId) + expect(replaced.requestedByWorkflowId).toBe(workflowId) + + mail.failWith = 'Mailbox unavailable' + await deliver(enrollmentId) + + expect(mail.sent).toEqual([]) + expect(await enrollmentRow(enrollmentId)).toMatchObject({ + status: replaced.status, + lastDeliveryError: replaced.lastDeliveryError, + sentAt: replaced.sentAt, + }) + }) + it('sends nothing, and records nothing, once an admin has reinvited the person', async () => { const { email, enrollmentId } = await requestedEnrollment('reinvited-request') await inviteCredentialGroupEnrollment( diff --git a/apps/sim/lib/credential-groups/connection-request-email.ts b/apps/sim/lib/credential-groups/connection-request-email.ts index 9e78565d2a9..93b79c10448 100644 --- a/apps/sim/lib/credential-groups/connection-request-email.ts +++ b/apps/sim/lib/credential-groups/connection-request-email.ts @@ -31,6 +31,7 @@ function parsePayload(payload: unknown): ConnectionRequestEmailPayload { !isRecordLike(payload) || typeof payload.enrollmentId !== 'string' || typeof payload.workflowId !== 'string' || + typeof payload.providerId !== 'string' || typeof payload.providerName !== 'string' || typeof payload.connectUrl !== 'string' ) @@ -38,6 +39,7 @@ function parsePayload(payload: unknown): ConnectionRequestEmailPayload { return { enrollmentId: payload.enrollmentId, workflowId: payload.workflowId, + providerId: payload.providerId, providerName: payload.providerName, connectUrl: payload.connectUrl, reminder: payload.reminder === true, @@ -59,16 +61,23 @@ function connectionRequestWorkflowName(name: string | undefined): string { } /** - * The enrollment as the request left it: still unbound, still the workflow's request (an - * admin's invitation clears that), and not issued again since (a reinvitation moves `invitedAt`). + * The enrollment still carries this email's request: unbound, still a workflow request (an admin's + * invitation clears that), and the latest request is the one that enqueued the email (a later + * workflow's request replaces the workflow and integration). */ -function stillRequested(enrollmentId: string, invitedAt: Date): SQL | undefined { +function currentRequest(payload: ConnectionRequestEmailPayload): SQL | undefined { return and( - pendingWorkflowRequestCondition(enrollmentId), - eq(credentialGroupEnrollment.invitedAt, invitedAt) + pendingWorkflowRequestCondition(payload.enrollmentId), + eq(credentialGroupEnrollment.requestedByWorkflowId, payload.workflowId), + eq(credentialGroupEnrollment.requestedProviderId, payload.providerId) ) } +/** {@link currentRequest}, and not issued again since it was read (a reinvitation moves `invitedAt`). */ +function stillRequested(payload: ConnectionRequestEmailPayload, invitedAt: Date): SQL | undefined { + return and(currentRequest(payload), eq(credentialGroupEnrollment.invitedAt, invitedAt)) +} + /** * Sends the email a workflow's connection request enqueued. The enrollment is read again first, * so a person who was revoked, connected, or reinvited by an admin after the request was accepted @@ -92,7 +101,7 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { .from(credentialGroupEnrollment) .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) - .where(pendingWorkflowRequestCondition(payload.enrollmentId)) + .where(currentRequest(payload)) .limit(1) if (!target) return const [requester] = await db @@ -133,7 +142,7 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { lastDeliveryError: truncate(result.message, 500), updatedAt: new Date(), }) - .where(stillRequested(payload.enrollmentId, target.invitedAt)) + .where(stillRequested(payload, target.invitedAt)) logger.warn('Connection request email failed', { enrollmentId: payload.enrollmentId }) throw new Error('Connection request email delivery failed') } @@ -147,7 +156,7 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { lastDeliveryError: null, updatedAt: new Date(), }) - .where(stillRequested(payload.enrollmentId, target.invitedAt)) + .where(stillRequested(payload, target.invitedAt)) } catch (error) { logger.error('Failed to record a sent connection request email', { enrollmentId: payload.enrollmentId, diff --git a/apps/sim/lib/credential-groups/connection-request-event.ts b/apps/sim/lib/credential-groups/connection-request-event.ts index 6e934c4ed69..50b211dfc90 100644 --- a/apps/sim/lib/credential-groups/connection-request-event.ts +++ b/apps/sim/lib/credential-groups/connection-request-event.ts @@ -8,6 +8,8 @@ export interface ConnectionRequestEmailPayload { * group's organization. */ workflowId: string + /** The requested integration; with `workflowId`, identifies the request the email belongs to. */ + providerId: string providerName: string connectUrl: string /** A repeat request for an enrollment already asked for; its subject reads as a reminder. */ diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index c5ddd20ddd2..e46d54f3d8d 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -321,6 +321,7 @@ export async function recordCredentialGroupConnectionRequest(input: { const email = (reminder: boolean) => ({ enrollmentId: row.id, workflowId: input.workflowId, + providerId: input.providerId, providerName: input.providerName, connectUrl: input.connectUrl, ...(reminder ? { reminder } : {}), @@ -407,6 +408,7 @@ export async function remindWorkflowConnectionRequest(input: { const emailEventId = await enqueueConnectionRequestEmail(tx, { enrollmentId: row.id, workflowId, + providerId, providerName, connectUrl: input.connectUrlFor({ providerId, email: row.email }), reminder: true, diff --git a/packages/db/schema.ts b/packages/db/schema.ts index f6e07656849..3da28f95722 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7580,9 +7580,10 @@ export const credentialGroupConnectionRequestPolicy = pgTable( ) /** - * One row per accepted workflow connection request, whatever the person's state, so the daily cap - * counts every request and reminder alike. Rows are never read after the cap's 24-hour window and - * are pruned two days after they were written. + * One row per person a workflow asked about each day, whatever the person's state: a repeat + * request for an address already logged in the last 24 hours writes nothing. The daily cap counts + * these rows, so it counts distinct people per day. Rows are never read after that 24-hour window + * and are pruned two days after they were written. */ export const credentialGroupConnectionRequest = pgTable( 'credential_group_connection_request', From d26f758e4796bec274ac1938a4721dcde9cf6f28 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 18:45:11 -0600 Subject: [PATCH 26/26] chore(ci): retrigger checks after runner infrastructure failures