diff --git a/apps/docs/content/docs/platform/connected-accounts.mdx b/apps/docs/content/docs/platform/connected-accounts.mdx index a756ac26288..27145b429e5 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. 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 **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. +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/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/docs/content/docs/workflows/blocks/credential.mdx b/apps/docs/content/docs/workflows/blocks/credential.mdx index 5a38df40a32..7b0143cc273 100644 --- a/apps/docs/content/docs/workflows/blocks/credential.mdx +++ b/apps/docs/content/docs/workflows/blocks/credential.mdx @@ -25,10 +25,12 @@ 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. | -| **Find Organization MCP Connection** | Find exactly one active managed MCP connection by invitation email and MCP provider. | +| **List Credentials** | Return workspace OAuth credential references, optionally filtered by integrations. | +| **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 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. @@ -39,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] @@ -49,8 +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** | +| Find Organization Account | **Email**, **Integration** | — | +| List Organization Accounts | — | **Email**, **Integrations**, **Limit**, **Cursor** | +| 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** | @@ -58,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 @@ -86,6 +90,31 @@ 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 | +| `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. + +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. 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; 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. + +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 | Field | Meaning | @@ -103,7 +132,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. @@ -126,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/(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 90403bf1a4a..9ca3abef30a 100644 --- a/apps/sim/app/(auth)/login/login-form.tsx +++ b/apps/sim/app/(auth)/login/login-form.tsx @@ -13,7 +13,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, @@ -118,6 +122,10 @@ 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 && + isCredentialGroupConnectCallback(callbackUrl, new URL(getBaseUrl()).origin) const [forgotPasswordOpen, setForgotPasswordOpen] = useState(false) const [forgotPasswordEmail, setForgotPasswordEmail] = useState('') @@ -381,6 +389,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 && showDivider && ( + + )} {showTopSSO && ( @@ -514,19 +545,9 @@ export default function LoginPage({ )} - {showDivider && } - - {showBottomSection && ( - - )} + {!connectFlow && showDivider && } + + {!connectFlow && showBottomSection && socialButtons}
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..e73e836b762 --- /dev/null +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts @@ -0,0 +1,135 @@ +/** + * 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 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' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { mockStart, mockUserRateLimit } = vi.hoisted(() => ({ + mockStart: 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', () => ({ + checkCredentialGroupConnectUserRateLimit: mockUserRateLimit, +})) + +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 = { '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?${query}`, + 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' }, + }) + mockUserRateLimit.mockResolvedValue('allowed') + mockStart.mockResolvedValue({ kind: 'started', 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', {}], + ])('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}&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() + }) + + 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.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', 'expired', 'different_email', '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('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')).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') + }) + + 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/api/credential-groups/connect/[publicId]/route.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts new file mode 100644 index 00000000000..a5cf8736412 --- /dev/null +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts @@ -0,0 +1,75 @@ +import type { NextRequest } from 'next/server' +import { startCredentialGroupConnectContract } from '@/lib/api/contracts/credential-groups' +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' +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 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) { + 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') => { + const path = buildCredentialGroupConnectPath({ + publicId, + provider, + optionId, + requestHandle, + returnTo, + }) + return createNoStoreRedirect(error ? `${path}&error=${error}` : path, 303) + } + if (!isSameOriginSessionRequest(request)) return backToConnect('try_again') + + const session = await resolveCredentialGroupConnectSession() + 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, + input: { + publicId, + provider, + ...(optionId ? { optionId } : {}), + ...(requestHandle ? { requestHandle } : {}), + }, + request, + }) + if (started.kind !== 'started') return backToConnect() + return createNoStoreRedirect( + 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 7c1ffec4029..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 @@ -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 { isCredentialGroupLinkFocusError } from '@/lib/credential-groups/links' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' import { createCredentialGroupCompletionRedirect, @@ -22,23 +23,23 @@ export const POST = withRouteHandler( const parsed = await parseRequest(completeCredentialGroupEnrollmentContract, request, context) if (!parsed.success) return parsed.response const { token } = parsed.data.params + const { return: returnTo } = parsed.data.query + const backToEnrollment = (oauth: 'unavailable' | 'other_option') => + createCredentialGroupEnrollmentRedirect(token, { + oauth, + ...(returnTo ? { return: returnTo } : {}), + }) const principal = await authenticateCredentialGroupEnrollment(token) - if (!principal) { - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'unavailable' }) - } + if (!principal) return backToEnrollment('unavailable') const completion = await completePublicCredentialGroupEnrollment .execute({ principal, input: {}, request }) .catch((error: unknown) => { + if (isCredentialGroupLinkFocusError(error)) return 'focused' as const 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 === 'focused') return backToEnrollment('other_option') + if (!completion || completion.completed === null) return backToEnrollment('unavailable') + 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 2fc0ce969b0..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 @@ -1,18 +1,21 @@ 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' import { authenticateCredentialGroupEnrollment } from '@/lib/credential-groups/application/enrollment-auth' import { startPublicCredentialGroupMcpOAuth } from '@/lib/credential-groups/application/public-enrollment' +import { isCredentialGroupLinkFocusError } from '@/lib/credential-groups/links' import { enforceCredentialGroupEnrollmentOAuthRateLimit, 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' @@ -26,22 +29,26 @@ 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 - if (limited) return createCredentialGroupEnrollmentRedirect(token, { oauth: 'rate_limited' }) - + 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 = { + ...(origin ? { origin } : {}), + ...(returnTo ? { return: returnTo } : {}), + } + const backToEnrollment = (oauth: string) => + createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth }) const principal = await authenticateCredentialGroupEnrollment(token) if (!principal) { - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'unavailable' }) + const limited = await enforcePublicCredentialGroupOAuthStartIpRateLimit(request) + return backToEnrollment(limited ? 'rate_limited' : '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( @@ -54,15 +61,13 @@ 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', { error: getErrorMessage(error), }) - return createCredentialGroupEnrollmentRedirect(token, { oauth: 'unavailable' }) + return backToEnrollment('unavailable') } } ) 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 aa5582d7263..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 @@ -1,18 +1,21 @@ 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' import { authenticateCredentialGroupEnrollment } from '@/lib/credential-groups/application/enrollment-auth' import { startPublicCredentialGroupOAuth } from '@/lib/credential-groups/application/public-enrollment' +import { isCredentialGroupLinkFocusError } from '@/lib/credential-groups/links' import { CredentialGroupOAuthError } from '@/lib/credential-groups/provider-adapter' 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' @@ -24,49 +27,49 @@ 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 } = parsed.data.query - const focus: Record = returnTo ? { optionId, returnTo } : {} - if (limited) { - return createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth: 'rate_limited' }) + const { origin, return: returnTo } = parsed.data.query + const focus: Record = { + ...(origin ? { optionId, origin } : {}), + ...(returnTo ? { return: returnTo } : {}), } + const backToEnrollment = (oauth: string) => + createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth }) const principal = await authenticateCredentialGroupEnrollment(token) if (!principal) { - return createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth: 'unavailable' }) + const limited = await enforcePublicCredentialGroupOAuthStartIpRateLimit(request) + return backToEnrollment(limited ? 'rate_limited' : '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({ principal, - input: { invitationToken: token, optionId, ...(returnTo ? { returnTo } : {}) }, + input: { + invitationToken: token, + optionId, + ...(origin ? { origin } : {}), + ...(returnTo ? { returnTo } : {}), + }, 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 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 7868fb0a087..0e63405075e 100644 --- a/apps/sim/app/api/credential-groups/enrollment-redirect.ts +++ b/apps/sim/app/api/credential-groups/enrollment-redirect.ts @@ -1,40 +1,47 @@ import { NextResponse } from 'next/server' +import type { ConnectReturnDestination } from '@/lib/credential-groups/connect-return' 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}` : ''}` + ) } -export function createCredentialGroupCompletionRedirect( - oauth?: CredentialGroupOAuthFailure, - completionId?: string, +interface CredentialGroupCompletionRedirectOptions { + oauth?: CredentialGroupOAuthFailure + completionId?: string + /** Set when the connection started from the organization's Integrations page. */ organizationId?: string -): NextResponse { + returnTo?: ConnectReturnDestination +} + +/** Sends the person to the completion page. */ +export function createCredentialGroupCompletionRedirect({ + oauth, + completionId, + organizationId, + 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) - return new NextResponse(null, { - status: 303, - headers: { - Location: `/credential-groups/complete${query.size ? `?${query}` : ''}`, - ...NO_STORE_REDIRECT_HEADERS, - }, - }) + 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 1f118b2b028..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, @@ -268,3 +268,41 @@ describe('Integrations OAuth completion', () => { } ) }) + +describe('Slack return destination', () => { + const forgedReturn = 'https://evil.example' + + 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', expected: 'slack' }, + ])( + 'returns to $expected from the stored attempt, ignoring the callback query', + async ({ stored, expected }) => { + mocks.consumeAttempt.mockResolvedValueOnce({ + ...attempt, + origin: 'connect', + ...(stored ? { returnTo: 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 ff5eacf7a5a..cd80f6e2fb0 100644 --- a/apps/sim/app/api/credential-groups/oauth-callback.ts +++ b/apps/sim/app/api/credential-groups/oauth-callback.ts @@ -57,19 +57,23 @@ 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 && 'expired' in attempt) + return createCredentialGroupCompletionRedirect({ oauth: 'expired', returnTo: attempt.returnTo }) if (!attempt || attempt.provider !== provider) { - return createCredentialGroupCompletionRedirect(limited ? 'rate_limited' : 'expired') + return createCredentialGroupCompletionRedirect({ oauth: limited ? 'rate_limited' : 'expired' }) + } + // Origin and return destination come only from server-held attempt state, never the query. + const focus: Record = { + ...(attempt.origin ? { optionId: attempt.optionId, origin: attempt.origin } : {}), + ...(attempt.returnTo ? { return: attempt.returnTo } : {}), } - const focus: Record = attempt.returnTo - ? { optionId: attempt.optionId, returnTo: attempt.returnTo } - : {} const setupRedirect = (oauth?: CredentialGroupOAuthFailure) => new NextResponse(null, { status: 303, @@ -83,14 +87,21 @@ 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 + attempt.origin === 'integrations' ? attempt.organizationId : undefined + const completionRedirect = (oauth?: CredentialGroupOAuthFailure) => + createCredentialGroupCompletionRedirect({ + oauth, + completionId: attempt.completionId, + organizationId: returnOrganizationId, + returnTo: attempt.returnTo, + }) const failureRedirect = (oauth: CredentialGroupOAuthFailure) => installationSetup ? setupRedirect(oauth) : attempt.completionRedirect - ? createCredentialGroupCompletionRedirect(oauth, attempt.completionId, returnOrganizationId) + ? completionRedirect(oauth) : createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { ...focus, oauth }) if (limited) { return failureRedirect('rate_limited') @@ -119,11 +130,7 @@ export async function handleCredentialGroupOAuthCallback({ request, }) return attempt.completionRedirect - ? createCredentialGroupCompletionRedirect( - undefined, - attempt.completionId, - returnOrganizationId - ) + ? completionRedirect() : createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { ...focus, connected: attempt.optionId, 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/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/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.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 7cf3ee76bed..ff8b06f3f11 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.origin === '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.origin === 'integrations' ? attempt.organizationId : undefined, + }) return createCredentialGroupEnrollmentRedirect(attempt.invitationToken, { mcp: 'connected', mcpServerId: result.mcpServerId, 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/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/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx new file mode 100644 index 00000000000..0e665137143 --- /dev/null +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -0,0 +1,216 @@ +import type { Metadata } from 'next' +import { headers } from 'next/headers' +import { redirect } from 'next/navigation' +import { openCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' +import { + 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 } from '@/lib/credential-groups/rate-limit' +import { + AlreadyConnected, + ChooseConnectOption, + ConnectConfirm, + DifferentEmail, + NotInvited, + RequestExpired, + UnavailableInvitation, + VerifyEmail, + WrongAccount, +} from '@/app/credential-groups/link-states' + +export const metadata: Metadata = { + title: 'Connect your account', + robots: { index: false, follow: false }, +} + +/** Each visit is decided 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 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 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, + searchParams, +}: CredentialGroupConnectPageProps) { + const { publicId } = await params + const query = await searchParams + const provider = getSearchParam(query, 'provider') + const optionId = getSearchParam(query, 'optionId') + 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 + const unavailable = ( + + ) + if ( + startError === 'unavailable' || + !publicId || + publicId.length > 128 || + !provider || + provider.length > 128 + ) + return unavailable + + const linkPath = (overrides: { optionId?: string } = {}) => + buildCredentialGroupConnectPath({ + publicId, + provider, + optionId, + requestHandle, + returnTo, + ...overrides, + }) + const callbackUrl = linkPath() + const tryAgain = ( + + ) + const verifyEmail = ( + + ) + + const session = await resolveCredentialGroupConnectSession() + switch (session.kind) { + case 'sign_in': + return redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) + case 'verify_email': + return verifyEmail + } + if (startError === 'rate_limited') + return + if (startError === 'try_again') return tryAgain + + 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 'already_connected': + return ( + + ) + case 'verify_email': + return verifyEmail + case 'different_email': + return ( + + ) + case 'wrong_account': + return ( + + ) + case 'not_invited': + return ( + + ) + case 'expired': + return + case 'revoked': + return ( + + ) + case 'choose_option': + return ( + ({ + ...option, + href: linkPath({ optionId: option.id }), + }))} + slackHref={slackHref} + /> + ) + case 'unavailable': + return unavailable + } +} 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..8b7d54fddcf --- /dev/null +++ b/apps/sim/app/credential-groups/complete/completion-view.ts @@ -0,0 +1,71 @@ +import { isValidUuid } from '@sim/utils/id' +import { + type ConnectReturnDestination, + connectReturnHref, + parseConnectReturnDestination, +} from '@/lib/credential-groups/connect-return' +import { + CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES, + type CredentialGroupOAuthFailure, + isCredentialGroupOAuthFailure, +} from '@/lib/credential-groups/oauth-completion' +import { organizationRoutes } from '@/lib/navigation/paths' + +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 + /** "Return to Slack", for a connection a Slack workflow asked for. */ + slackHref?: string +} + +function single(value: string | string[] | undefined): string | undefined { + return typeof value === 'string' ? value : undefined +} + +/** + * An expired attempt is retried where it started: Slack, Integrations (whose button says Try + * again), or else the link the person was sent. + */ +function failureMessage( + failure: CredentialGroupOAuthFailure, + returnTo: ConnectReturnDestination | undefined, + integrationsHref: string | undefined +): string { + if (failure !== 'expired' || integrationsHref) + return CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure] + return returnTo === 'slack' + ? 'This connection attempt expired. Go back to Slack and tap Connect again.' + : 'This connection attempt expired. Open the link you were sent and connect again.' +} + +/** + * 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 function resolveCredentialGroupCompletionView( + searchParams: CompletionSearchParams +): CredentialGroupCompletionView { + const oauth = searchParams.oauth + const completionId = single(searchParams.completionId) + const organizationId = single(searchParams.organizationId) + const returnTo = parseConnectReturnDestination(single(searchParams.return)) + const failure = + oauth === undefined ? undefined : isCredentialGroupOAuthFailure(oauth) ? oauth : 'failed' + const integrationsHref = + organizationId && organizationId.length <= 128 + ? organizationRoutes(encodeURIComponent(organizationId)).integrations + : undefined + return { + ...(failure ? { failure, error: failureMessage(failure, returnTo, integrationsHref) } : {}), + ...(completionId && isValidUuid(completionId) ? { completionId } : {}), + ...(integrationsHref ? { integrationsHref } : {}), + ...(returnTo ? { slackHref: connectReturnHref(returnTo) } : {}), + } +} diff --git a/apps/sim/app/credential-groups/complete/page.tsx b/apps/sim/app/credential-groups/complete/page.tsx index 773882918e0..c148a5c8ecf 100644 --- a/apps/sim/app/credential-groups/complete/page.tsx +++ b/apps/sim/app/credential-groups/complete/page.tsx @@ -1,60 +1,72 @@ 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 { APP_ENTRY_PATH, organizationRoutes } from '@/lib/navigation/paths' +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' -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<{ - oauth?: string | string[] - completionId?: string | string[] - organizationId?: string | string[] - }> -}) { - const { oauth, completionId, organizationId } = 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 - const error = failure ? CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure] : undefined +}: CredentialGroupCompletePageProps) { + const query = await searchParams + const { failure, error, completionId, integrationsHref, slackHref } = + 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; 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 ( - {typeof completionId === 'string' && isValidUuid(completionId) && ( + {completionId && ( )} - {(error || returnHref) && ( -
- - {returnHref ? 'Return to Integrations' : 'Open Sim'} - -
+ {(appLink || slackHref) && ( + + {appLink} + )}
) 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..19e48c9c4ef 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: { execute: async () => ({ kind: 'unknown' }) }, +})) vi.mock('@/lib/credential-groups/application/public-enrollment', () => ({ readPublicCredentialGroupEnrollment: { execute: mocks.read }, })) @@ -132,14 +135,14 @@ afterEach(() => { 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( @@ -156,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') @@ -168,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', @@ -181,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 130cdbf3e74..af21660c98f 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, @@ -13,17 +13,34 @@ 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 { + 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' import { CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES } from '@/lib/credential-groups/oauth-completion' import { CredentialGroupProviderConfigurationError } from '@/lib/credential-groups/provider-adapter' import { getCredentialGroupProviderService } from '@/lib/credential-groups/providers' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' +import { isCredentialGroupEmailVerified } from '@/lib/credential-groups/verified-email' 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 { + CredentialGroupLinkActions, + CredentialGroupPageShell as PageShell, + UnavailableInvitation, + WrongAccount, +} from '@/app/credential-groups/link-states' import { SourceCompletion } from '@/app/desktop/connect/source-completion' export const metadata: Metadata = { @@ -38,64 +55,114 @@ interface CredentialGroupEnrollmentPageProps { searchParams: Promise> } -interface PageShellProps { - children: ReactNode -} - -function PageShell({ children }: PageShellProps) { - return ( - }> -
{children}
-
- ) +interface EnrollmentLinkProblemProps { + token: string + outcome: CredentialGroupEnrollmentLinkOutcome + signedInEmail: string + callbackUrl: string + fallbackMessage?: string + /** Where the link offers to return: the way out of a dead end, and kept on Start again. */ + returnTo?: ConnectReturnDestination } -interface UnavailableInvitationProps { - token?: string - rateLimited?: boolean - message?: string - recoveryHref?: string - recoveryLabel?: string +function needsNewLinkCopy( + outcome: Extract +): string { + const asker = + outcome.inviterName ?? + (outcome.organizationName ? `an admin at ${outcome.organizationName}` : 'an admin') + return `Ask ${asker} for a new link.` } -function UnavailableInvitation({ +/** Tells a signed-in person why their link did not open; unknown links stay generic. */ +function EnrollmentLinkProblem({ token, - rateLimited = false, - message, - recoveryHref = APP_ENTRY_PATH, - recoveryLabel = 'Open Sim', -}: UnavailableInvitationProps) { - return ( - - {token && } -
- -
- {recoveryLabel} -
-
-
- ) + ) + case 'revoked': + return ( + + ) + case 'paused': + return ( + + ) + case 'reopen': + return ( + + +
+ + + + Start again + + +
+
+ ) + case 'needs_new_link': + return ( + + ) + case 'unavailable': + return + case 'unknown': + return + } } interface UnavailableSearchConnectionProps { token: string returnHref: string returnLabel: string + slackHref?: string } function UnavailableSearchConnection({ token, returnHref, returnLabel, + slackHref, }: UnavailableSearchConnectionProps) { return ( @@ -104,9 +171,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}} +
) } @@ -118,6 +189,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( @@ -133,73 +205,111 @@ export default async function CredentialGroupEnrollmentPage({ searchParams, }: CredentialGroupEnrollmentPageProps) { const { token } = await params + const resolvedSearchParams = await searchParams + const returnTo = parseConnectReturnDestination(getSearchParam(resolvedSearchParams, 'return')) + const slackHref = returnTo ? connectReturnHref(returnTo) : undefined const requestHeaders = await headers() const limited = await enforcePublicCredentialGroupIpRateLimit( { headers: requestHeaders }, 'metadata' ) - if (limited) return + if (limited) return - if (!token || token.length > 128) return - const resolvedSearchParams = await searchParams + if (!token || token.length > 128) + return 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 (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 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 origin = getSearchParam(resolvedSearchParams, 'origin') + const originIsSearch = origin === 'search' + const requestedOrigin = + origin === 'search' || origin === 'accounts' || origin === 'connect' ? origin : 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: 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 (focused && error instanceof CredentialGroupProviderConfigurationError) + if (requestedOrigin && error instanceof CredentialGroupProviderConfigurationError) return { enrollment: null } throw error }) - if (!enrollmentResult) return + if (!enrollmentResult) return explainLinkProblem() if ('enrollmentError' in enrollmentResult) - return + 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 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 = canReturnToSearch ? sourceReturnPath(principal) : APP_ENTRY_PATH - const returnLabel = canReturnToSearch - ? principal.organizationId - ? 'Return to Search' - : 'Open knowledge bases' - : 'Open Sim' + const returnHref = slackHref ?? (canReturnToSearch ? sourceReturnPath(principal) : APP_ENTRY_PATH) + const returnLabel = slackHref + ? 'Return to Slack' + : canReturnToSearch + ? principal.organizationId + ? 'Return to Search' + : 'Open knowledge bases' + : 'Open Sim' + const oauthStartQuery = new URLSearchParams() + if (focusedOrigin) oauthStartQuery.set('origin', focusedOrigin) + if (returnTo) oauthStartQuery.set('return', returnTo) + const oauthStartSuffix = oauthStartQuery.size ? `?${oauthStartQuery}` : '' if (!enrollment) return ( ) @@ -209,26 +319,41 @@ 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 + 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') && + (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 @@ -276,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}.` } /> @@ -312,7 +439,7 @@ export default async function CredentialGroupEnrollmentPage({ (account) => account.status === 'connected' ) ? undefined : ( 0} variant={focused ? 'primary' : undefined} /> @@ -348,20 +475,29 @@ export default async function CredentialGroupEnrollmentPage({ {focused ? ( -
- - {returnLabel} - -
+ + {!slackHref && focusedOrigin !== 'connect' && ( + + {returnLabel} + + )} + ) : (
- - {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 new file mode 100644 index 00000000000..35c04dd2056 --- /dev/null +++ b/apps/sim/app/credential-groups/link-states.tsx @@ -0,0 +1,344 @@ +import type { ReactNode } from 'react' +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' +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 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 + /** The account is connected: "Return to Slack" is primary and the tab may be closed. */ + connected?: 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 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, +}: CredentialGroupLinkActionsProps) { + return ( +
+
+ {slackHref && ( + + Return to Slack + + )} + {children} +
+ {slackHref && connected && ( +

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 + title?: string + rateLimited?: boolean + /** The line under the title; `null` when the title says it all. */ + message?: string | null + /** 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 state with a title, one line of copy, and a way forward or out. */ +export function UnavailableInvitation({ + token, + title, + rateLimited = false, + message, + recovery, + slackHref, +}: UnavailableInvitationProps) { + return ( + + {token && } +
+ + + {recovery ? ( + + {recovery.label} + + ) : ( + !slackHref && Open Sim + )} + +
+
+ ) +} + +interface SwitchAccountStateProps { + token?: string + title: string + description: string + /** Where to come back to after signing in as someone else. */ + callbackUrl: string + slackHref?: string +} + +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 { + token?: string + verifyHref: string + slackHref?: string +} + +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 + /** 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/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/background/cleanup-credential-group-links.integration.ts b/apps/sim/background/cleanup-credential-group-links.integration.ts new file mode 100644 index 00000000000..61808f6f432 --- /dev/null +++ b/apps/sim/background/cleanup-credential-group-links.integration.ts @@ -0,0 +1,195 @@ +/** + * 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 + * 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 { + credentialGroup, + credentialGroupConnectionRequest, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + 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, sql } from 'drizzle-orm' +import { afterAll, describe, expect, it } from 'vitest' +import { runCleanupCredentialGroupLinks } from '@/background/cleanup-credential-group-links' + +const HOUR_MS = 60 * 60 * 1000 +const DAY_MS = 24 * HOUR_MS +const organizationIds: string[] = [] + +async function createEnrollment() { + 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', + 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 +) { + const id = generateId() + await db + .insert(credentialGroupEnrollmentLink) + .values({ id, enrollmentId, tokenHash: sha256Hex(generateId()), 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)) + await Promise.all([db.$client.end(), dbFor('cleanup').$client.end()]) +}) + +describe('runCleanupCredentialGroupLinks', () => { + it('deletes request log rows past two days and session links a day past expiry, nothing else', async () => { + 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)) + 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)) + + 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([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].sort()) + }) + + 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 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)) + + const requests = await db + .select({ id: credentialGroupConnectionRequest.id }) + .from(credentialGroupConnectionRequest) + .where(eq(credentialGroupConnectionRequest.credentialGroupId, groupId)) + 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([insideLinkCutoff]) + }) + + it('skips a row another run holds instead of waiting for it', async () => { + 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) + + 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() + 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/background/cleanup-credential-group-links.ts b/apps/sim/background/cleanup-credential-group-links.ts new file mode 100644 index 00000000000..b0476f7286b --- /dev/null +++ b/apps/sim/background/cleanup-credential-group-links.ts @@ -0,0 +1,111 @@ +import { dbFor } from '@sim/db' +import { + credentialGroupConnectionRequest, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, +} from '@sim/db/schema' +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +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' + +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 +/** 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. 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 + 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 +} + +/** + * 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() +): 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('connection_requests', async () => { + const removed = await cleanupDb + .delete(request) + .where( + inArray( + request.id, + cleanupDb + .select({ id: request.id }) + .from(request) + .where(lte(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('session_links', async () => { + const removed = await cleanupDb + .delete(link) + .where( + inArray( + link.id, + cleanupDb + .select({ id: link.id }) + .from(link) + .innerJoin( + credentialGroupEnrollment, + eq(credentialGroupEnrollment.id, link.enrollmentId) + ) + .where( + and( + inArray(link.purpose, ['self', 'connect']), + not(unexpiredLinkCondition(linkCutoff)) + ) + ) + .orderBy(asc(link.expiresAt)) + .limit(CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) + .for('update', { of: link, 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/apps/sim/blocks/blocks/credential.ts b/apps/sim/blocks/blocks/credential.ts index 290377dece8..827f7ec8c92 100644 --- a/apps/sim/blocks/blocks/credential.ts +++ b/apps/sim/blocks/blocks/credential.ts @@ -3,8 +3,11 @@ import { CREDENTIAL_GROUP_EVENT_TRIGGER_ID } from '@/lib/credential-groups/trigg import type { BlockConfig } from '@/blocks/types' import { getTrigger } from '@/triggers' -const ORGANIZATION_OPERATIONS = [ +const CONNECTION_OPERATIONS = ['get_connection_status', 'request_connection'] +/** 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', 'find_organization_mcp_connection', 'list_organization_mcp_connections', @@ -19,16 +22,19 @@ 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 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. + - "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. `, @@ -47,6 +53,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 +85,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' }, ], @@ -76,7 +94,7 @@ export const CredentialBlock: BlockConfig = { }, { id: 'providerFilter', - title: 'Provider', + title: 'Integrations', type: 'dropdown', selectorKey: 'workspace.credentialProviders', multiSelect: true, @@ -104,17 +122,20 @@ export const CredentialBlock: BlockConfig = { }, { id: 'organizationProvider', - title: 'Provider', + title: 'Integration', type: 'dropdown', selectorKey: 'workspace.credentialGroupProviders', - condition: { field: 'operation', value: 'find_organization_account' }, + condition: { + field: 'operation', + value: ['find_organization_account', ...CONNECTION_OPERATIONS], + }, required: true, }, { id: 'organizationProviders', - title: 'Providers', + title: 'Integrations', type: 'dropdown', - placeholder: 'All allowed providers', + placeholder: 'All allowed integrations', emptyIsValid: true, multiSelect: true, selectorKey: 'workspace.credentialGroupProviders', @@ -132,13 +153,28 @@ 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', - value: ['find_organization_account', 'find_organization_mcp_connection'], + value: [ + 'find_organization_account', + 'find_organization_mcp_connection', + ...CONNECTION_OPERATIONS, + ], }, }, + { + id: 'returnTo', + title: 'Return to', + type: 'dropdown', + options: [ + { label: 'None', id: 'none' }, + { label: 'Slack', id: 'slack' }, + ], + value: () => 'none', + condition: { field: 'operation', value: CONNECTION_OPERATIONS }, + }, { id: 'limit', title: 'Limit', @@ -163,7 +199,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', @@ -173,6 +210,11 @@ export const CredentialBlock: BlockConfig = { type: 'json', description: 'Optional organization OAuth provider IDs', }, + returnTo: { + 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' }, @@ -189,12 +231,38 @@ 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 integration', + condition: { field: 'operation', value: 'get_connection_status' }, + }, + connectUrl: { + type: 'string', + description: + '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: { + type: 'boolean', + description: 'Always true when the request succeeds, 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..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 @@ -2,53 +2,87 @@ 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 - workspaceName: string - 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 + /** + * 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. The workflow + * name, chosen by its builder, appears only in the body, never in the inbox preview. + */ + workflowRequest?: { workflowName: string; providerName: string } } export function CredentialGroupInvitationEmail({ recipientEmail, inviterName, - workspaceName, - credentialGroupName, + owner, invitationLink, searchProviderName, + workflowRequest, }: CredentialGroupInvitationEmailProps) { + const providerName = searchProviderName ?? workflowRequest?.providerName + const ownerName = owner.name return ( Hello, - {inviterName ? ( - <> - {inviterName} invited {recipientEmail} - - ) : ( - <> - {recipientEmail} has been invited - - )}{' '} - {searchProviderName ? ( + {workflowRequest ? ( <> - to connect your {searchProviderName} account for Search in{' '} - {workspaceName}. + {workflowRequest.workflowName} in {ownerName} asked + you to connect {workflowRequest.providerName}. ) : ( <> - 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{' '} + {ownerName}. + + ) : ( + <> + to connect accounts for{' '} + {owner.kind === 'workspace' ? ( + <> + {owner.credentialGroupName} in the {ownerName}{' '} + workspace + + ) : ( + {ownerName} + )}{' '} + on Sim. + + )} )} @@ -60,16 +94,16 @@ 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. + {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.` + : '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/components/emails/credential-groups/render.ts b/apps/sim/components/emails/credential-groups/render.ts index b4f13f238bd..cf12ffd9c2c 100644 --- a/apps/sim/components/emails/credential-groups/render.ts +++ b/apps/sim/components/emails/credential-groups/render.ts @@ -1,13 +1,16 @@ 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 - credentialGroupName: string + owner: CredentialGroupInvitationOwner invitationLink: string searchProviderName?: 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 8bf90722f12..95f7a59889a 100644 --- a/apps/sim/components/emails/subjects.ts +++ b/apps/sim/components/emails/subjects.ts @@ -147,6 +147,21 @@ export function getOtpSubject(resourceLabel: string): string { return `Verification code for ${resourceLabel}` } +/** + * 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. + */ +export function getCredentialGroupConnectionRequestSubject(input: { + organizationName: string + providerName: string + /** A repeat request for a connection the person was already asked for. */ + reminder?: boolean +}): string { + const subject = `${input.organizationName} asked you to connect ${input.providerName}` + return input.reminder ? `Reminder: ${subject}` : subject +} + /** * 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. 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.status === 'in_progress' || person.status === 'completed' || person.bound) { + return 'not_connected' + } + if (person.expired) return 'expired' + if (person.sentAt) return 'invited' + return person.requestedByWorkflow ? 'requested' : 'not_connected' } -export function OrganizationAccountPeople({ - organizationId, - searchConnection, - panel, - enabled = true, - setupFallback, - filters, - requestDisabled = false, -}: OrganizationAccountPeopleProps) { + +/** 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, { - 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 error = resend.error ?? reinvite.error + const pending = resend.isPending || reinvite.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.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 } - : {}), + {enrollments.length === 0 ? ( + + {search ? 'No people match your search' : 'No connection requests yet'} + + ) : ( +
+ {enrollments.map((person) => { + const personStatus = getPersonStatus(person) + const status = PERSON_STATUS_BADGES[personStatus] + const remindable = + personStatus === 'needs_reconnect' || lacksConnection(person, group) + return ( + } + iconVariant='custom' + title={person.email} + description={} + badge={ + <> + {person.requestedByWorkflow && ( + + Requested by workflow + + )} + + {status.label} + + + } + trailing={ + + reinvite.mutate( + { organizationId, emails: [person.email] }, + { + onSuccess: ({ results: [result] }) => { + if (result && !result.success) toast.error(result.error) + else toast.success('Invitation sent') + }, + } + ), + }, + ] + : [ + ...(remindable + ? [ + { + label: person.sentAt ? 'Send reminder' : 'Send email', + 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 }) }, - { 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 }) - }, - }, - ]} - /> - } - /> - ))} -
- )} - {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, + 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..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 @@ -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', @@ -174,7 +175,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 +221,6 @@ describe('organization provider configuration UI', () => { ) expect(mocks.add).not.toHaveBeenCalled() expect(mocks.remove).not.toHaveBeenCalled() - expect(toast.success).toHaveBeenCalledWith('Provider configurations updated') }) 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..f143a64c9f0 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-providers.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-providers.tsx @@ -3,17 +3,20 @@ import { useState } from 'react' import { Chip, + ChipConfirmModal, ChipModal, ChipModalBody, ChipModalError, 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, @@ -22,6 +25,7 @@ import { import { getOrganizationAccountUpdateOptions } from '@/lib/credential-groups/organization-account-options' import { type CredentialGroupProvider, + getCredentialGroupProviderId, getCredentialGroupProviderService, } from '@/lib/credential-groups/providers' import { @@ -50,12 +54,27 @@ 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', { + description: 'Works for organization members and people you’ve asked to connect.', + }), + () => toast.error('Could not copy the link') + ) +} + interface OrganizationAccountProvidersProps { organizationId: string group: NonNullable availableProviders: CredentialGroupProvider[] availableMcpConnectors?: readonly ManagedMcpConnectorId[] - visibleProviders?: readonly CredentialGroupProvider[] } export function OrganizationAccountProviders({ @@ -63,7 +82,6 @@ export function OrganizationAccountProviders({ group, availableProviders, availableMcpConnectors, - visibleProviders, }: OrganizationAccountProvidersProps) { const [searchTerm, setSearchParam] = useQueryState(credentialGroupProviderSearchParam.key, { ...credentialGroupProviderSearchParam.parser, @@ -74,18 +92,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 +153,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 +169,20 @@ 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, + copyLink: + option.status === 'active' + ? () => copyConnectLink(group.publicId, option.provider) + : undefined, + choice: { kind: 'oauth', provider: option.provider } as const, + } + }), ...group.mcpServers .filter((server) => server.managedConnectorId !== 'databricks' || server.enabled) .map((server) => ({ @@ -171,6 +194,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)) @@ -190,12 +214,7 @@ export function OrganizationAccountProviders({ - {options.length > 0 && ( - - Update configurations - - )} +
} disabled={pending} @@ -208,17 +227,26 @@ 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 }) => ( + {visibleRows.map(({ id, name, icon: Icon, configure, copyLink, 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-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/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 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_LABEL + : 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 +} + +/** 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() + /** 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) + return ( + + void state.refetch()} + variant='inline' + /> + + ) + if (!state.data) + return ( + + + + ) + const { policy, revision, inEffect } = state.data + + const openEditor = (enabled: boolean) => { + update.reset() + setEditor({ enabled }) + } + const editing = editor !== null + + const save = async (next: Policy) => { + try { + await update.mutateAsync({ organizationId, revision, policy: next }) + setEditor(null) + toast.success('Connection requests updated') + } catch (error) { + if (editing && isApiClientError(error) && error.status === 409) { + setEditor(null) + 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')) + } + } + + return ( + + {TOGGLE_LABEL}} + description={ + policy + ? policy.enabled && !inEffect + ? `${summarize(policy)} · No chosen workspace can use a chosen integration on Access` + : summarize(policy) + : undefined + } + badge={ + policy?.enabled && !inEffect ? ( + + Not in effect + + ) : undefined + } + trailing={ +
+ {policy && ( + openEditor(policy.enabled)}> + Edit + + )} + { + if (!checked) { + if (policy) void save({ ...policy, enabled: false }) + } else if (policy && canEnable(policy)) void save({ ...policy, enabled: true }) + else openEditor(true) + }} + /> +
+ } + /> + {editor && ( + setEditor(null)} + onSave={(next) => void save(next)} + /> + )} +
+ ) +} + +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 + onSave: (policy: Policy) => void +} + +function ConnectionRequestPolicyModal({ + state, + enabled, + 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 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 = + Number.isInteger(limit) && limit >= 1 && limit <= CONNECTION_REQUEST_DAILY_LIMIT_MAX + const draft: Policy = { + enabled, + 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 invalidReason = limitValid + ? connectionRequestPolicySchema.safeParse({ ...draft, enabled: true }).error?.issues[0]?.message + : 'Enter a valid daily limit' + + return ( + !open && !disabled && onClose()} + > + + {SECTION_LABEL} + + + + {(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(draft), + }} + /> + + ) +} 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..dbc73fe101f 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,14 @@ 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/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/executor/handlers/credential/handler.ts b/apps/sim/executor/handlers/credential/handler.ts index 4bbe708f0c7..88f81f518cd 100644 --- a/apps/sim/executor/handlers/credential/handler.ts +++ b/apps/sim/executor/handlers/credential/handler.ts @@ -1,7 +1,15 @@ 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 { + 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' @@ -52,6 +60,25 @@ function parseOptionalString(value: unknown, label: string): string | undefined return value.trim() } +/** 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 { const parsed = parseOptionalString(value, label) if (!parsed) throw new Error(`${label} is required`) @@ -109,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'), @@ -125,6 +152,26 @@ export class CredentialBlockHandler implements BlockHandler { ) return omit(first, ['accountEmail']) } + case 'get_connection_status': + return getOrganizationAccountConnectionStatus.execute({ + principal, + input: { + workspaceId: ctx.workspaceId, + email: requireConnectionEmail(inputs.email), + providerId: requireString(inputs.organizationProvider, 'Integration'), + ...parseConnectReturnTo(inputs.returnTo), + }, + }) + case 'request_connection': + return requestOrganizationAccountConnection.execute({ + principal, + input: { + workspaceId: ctx.workspaceId, + email: requireConnectionEmail(inputs.email), + providerId: requireString(inputs.organizationProvider, 'Integration'), + ...parseConnectReturnTo(inputs.returnTo), + }, + }) 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..be5aa9ced32 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,36 @@ 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, + }), + /** 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), + }), + }) +} 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..f7077971222 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`: 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, peopleList: (id: string, search?: string, optionId?: string) => [ diff --git a/apps/sim/lib/api/contracts/credential-groups.ts b/apps/sim/lib/api/contracts/credential-groups.ts index 70be7c77dcd..8106a6f55c2 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, @@ -136,6 +137,10 @@ export const credentialGroupEnrollmentMcpConnectionSchema = z.object({ }) export const credentialGroupEnrollmentDetailSchema = credentialGroupEnrollmentSchema.extend({ + /** A workflow asked this person to connect, rather than an admin. */ + requestedByWorkflow: 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), @@ -570,8 +575,19 @@ export const slackCredentialGroupConfigurationCallbackContract = defineRouteCont response: { mode: 'text' }, }) +/** + * 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 connectReturnQuerySchema = z.enum(CONNECT_RETURN_DESTINATIONS).optional().catch(undefined) + +const completeCredentialGroupEnrollmentQuerySchema = z.object({ + return: connectReturnQuerySchema, +}) + export const startCredentialGroupOAuthQuerySchema = z.object({ - returnTo: z.enum(['search', 'accounts']).optional(), + origin: z.enum(['search', 'accounts', 'connect']).optional(), + return: connectReturnQuerySchema, }) export type StartCredentialGroupOAuthQuery = z.output @@ -587,13 +603,33 @@ 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 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 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(), + for: z.string().min(1).max(64).optional(), + return: connectReturnQuerySchema, + }), + response: { mode: 'redirect' }, +}) + 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/api/contracts/organization-accounts.ts b/apps/sim/lib/api/contracts/organization-accounts.ts index 39c0426b337..41ce6289cbf 100644 --- a/apps/sim/lib/api/contracts/organization-accounts.ts +++ b/apps/sim/lib/api/contracts/organization-accounts.ts @@ -16,6 +16,11 @@ 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_PROVIDER_LIMIT, + connectionRequestPolicySchema, + storedConnectionRequestPolicySchema, +} from '@/lib/credential-groups/connection-request-policy' import { ORGANIZATION_CREDENTIAL_TYPES } from '@/lib/credential-groups/credential-types' import { ACCOUNT_SITE_LIMIT, @@ -31,6 +36,7 @@ import { const organizationAccountsParamsSchema = z.object({ id: organizationIdSchema }) const organizationCredentialGroupSchema = credentialGroupSchema.extend({ + publicId: z.string().min(1).max(128), workspaceId: z.null(), organizationId: organizationIdSchema, }) @@ -210,6 +216,54 @@ 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({ + /** `0` while no policy was ever saved, which means requests are off. */ + revision: z.number().int().nonnegative(), + policy: storedConnectionRequestPolicySchema.nullable(), + /** False when a turned-on policy allows nothing that still exists, so no request can pass. */ + inEffect: z.boolean(), + 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), + }), + }, +}) + +export const updateOrganizationConnectionRequestPolicyContract = defineRouteContract({ + method: 'PUT', + path: '/api/organizations/[id]/connected-accounts/workflow-requests', + params: organizationAccountsParamsSchema, + 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: storedConnectionRequestPolicySchema, + }), + }, +}) +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/assistant-actions/tool-permissions.integration.ts b/apps/sim/lib/assistant-actions/tool-permissions.integration.ts index be98871d842..5544f384871 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)) } @@ -1323,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/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/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/README.md b/apps/sim/lib/credential-groups/README.md index a0a5b19e9d1..d4bc197070d 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, 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 @@ -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. @@ -66,9 +66,37 @@ 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; 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 | + +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. + +Revoking an enrollment sets its status to `revoked` and revokes all of its links; every link check refuses a `revoked` enrollment. + +## 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 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." 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; 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 -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 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 new file mode 100644 index 00000000000..e4898d6590b --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -0,0 +1,1013 @@ +/** + * 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, 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 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, 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 (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. + */ +import type { CredentialGroupEnrollmentPrincipal } from '@sim/auth/principal' +import { db, runOutsideTransactionContext } from '@sim/db' +import { + credential, + credentialGroup, + credentialGroupEnrollment, + 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 { and, eq, inArray, sql } from 'drizzle-orm' +import { afterAll, describe, expect, it, vi } from 'vitest' +import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' +import { + openCredentialGroupConnect, + startCredentialGroupConnect, +} from '@/lib/credential-groups/application/connect-target' +import { + completePublicCredentialGroupEnrollment, + completePublicCredentialGroupMcpOAuth, + completePublicCredentialGroupOAuth, + readPublicCredentialGroupEnrollment, + startPublicCredentialGroupMcpOAuth, + 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, + listCredentialGroupEnrollments, + lockCredentialGroupInvitationTarget, + revokeCredentialGroupEnrollment, +} from '@/lib/credential-groups/enrollments' +import { CredentialGroupLinkFocusError } from '@/lib/credential-groups/links' +import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' +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 }> = [] +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, +})) + +/** 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, +})) + +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 } +} + +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)) +} + +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: 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 +): 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( + and( + eq(credentialGroupEnrollment.credentialGroupId, groupId), + eq(credentialGroupEnrollment.email, email) + ) + ) + if (!row) throw new Error('Enrollment not found') + return row +} + +/** + * 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 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') +} + +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)) +}) + +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() + const teammate = await createPerson() + await addMember(fixture, teammate.userId) + await invite(fixture, person.email) + const before = await enrollmentOf(fixture.groupId, person.email) + + 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) + + 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(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) + expect(await enrollmentOf(fixture.groupId, person.email)).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 invite(fixture, person.email) + await db + .update(credentialGroupEnrollment) + .set({ userId: other.userId }) + .where(eq(credentialGroupEnrollment.credentialGroupId, fixture.groupId)) + + 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('asks an unverified person to verify, unless the deployment cannot verify email', async () => { + const fixture = await createOrganization() + const person = await createPerson(false) + 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( + 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 invite(fixture, person.email) + await revokeCredentialGroupEnrollment(fixture.scope, fixture.groupId, enrollment.id) + + await expect(startTarget(person.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'revoked', + organizationName: 'Acme', + provider: 'google-drive', + }) + 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(({ 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 () => { + 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() + + await expect(startTarget(stranger.userId, { publicId: fixture.publicId })).resolves.toEqual({ + kind: 'not_invited', + organizationName: 'Acme', + provider: 'google-drive', + }) + expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) + }) + + 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 openTarget(teammate.userId, { publicId: fixture.publicId }) + expect(await enrollmentsIn(fixture.groupId)).toHaveLength(0) + + 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 () => { + 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 connect of [openTarget, startTarget]) + await expect(connect(teammate.userId, { publicId: fixture.publicId })).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(startTarget(teammate.userId, { publicId: fixture.publicId })).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(), + 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(() => + startTarget(teammate.userId, { publicId: fixture.publicId }) + ) + await runOutsideTransactionContext(() => waitForBlockedBy(holder.pid)) + return { pending } + }) + + await expect(pending).resolves.toEqual({ + kind: 'revoked', + organizationName: 'Acme', + provider: 'google-drive', + }) + 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('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 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)) + + 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) + }) + + 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 invite(fixture, person.email) + + await expect(openTarget(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( + startTarget(person.userId, { publicId: fixture.publicId, optionId: 'drive-shared' }) + ).resolves.toMatchObject({ kind: 'started', optionId: 'drive-shared' }) + }) +}) + +describe('a focused connect link', () => { + 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'), + ]) + 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) + 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 () => { + 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 even when saves race', 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 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') + expect( + triggerEvents.filter( + (event) => event.enrollmentId === enrollment.id && event.event === 'form_submitted' + ) + ).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'), + 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', requestedProviderId: DRIVE_PROVIDER_ID }) + .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("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() + 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).toBe('in_progress') + 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-backfill.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts new file mode 100644 index 00000000000..0f1ef1b6124 --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-backfill.integration.ts @@ -0,0 +1,191 @@ +/** + * 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' +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/0490_credential_group_connect.sql', + import.meta.url +) +const DAY_MS = 24 * 60 * 60 * 1000 + +const organizationId = generateId() +const adminId = generateId() +const boundUserId = generateId() +let groupId = '' + +interface SeededInvitation { + label: string + enrollmentId: string + token: string + revokedByStatus: boolean + expiresAt: Date +} + +const invitations: SeededInvitation[] = [] +const hashlessEnrollmentId = generateId() + +/** 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' + 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 statements = migration + .split('--> statement-breakpoint') + .filter((statement) => statement.includes('INSERT INTO "credential_group_enrollment_link"')) + if (statements.length !== 1 || !statements[0]) + throw new Error('0490 no longer has exactly one link backfill statement') + return statements[0] +} + +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 seedColumnInvitation({ label: 'live and unbound', expiresInMs: 3 * DAY_MS }) + await seedColumnInvitation({ + label: 'revoked by status alone', + expiresInMs: 3 * DAY_MS, + status: 'revoked', + }) + 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 () => { + await db.delete(organization).where(eq(organization.id, organizationId)) + await db.delete(user).where(inArray(user.id, [adminId, boundUserId])) +}) + +describe('0490 enrollment link backfill', () => { + 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)) + + const links = await db + .select() + .from(credentialGroupEnrollmentLink) + .where( + inArray(credentialGroupEnrollmentLink.enrollmentId, [ + ...invitations.map((invitation) => invitation.enrollmentId), + hashlessEnrollmentId, + ]) + ) + 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) + } + + expect(links.some((link) => link.enrollmentId === hashlessEnrollmentId)).toBe(false) + + const after = await Promise.all(invitations.map((invitation) => answers(invitation.token))) + 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 new file mode 100644 index 00000000000..2aa4e503539 --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts @@ -0,0 +1,341 @@ +/** + * 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 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 + * a link revoked (by a disconnect) while its enrollment stays live. + */ +import { db } from '@sim/db' +import { + credentialGroup, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + 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 { 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, +})) + +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 + +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[] = [] +const enrollmentIdByToken = new Map() + +/** + * 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 }, + groupStatus: 'active' | 'disabled' = 'active', + group: { publicId?: string; options?: (typeof credentialGroup.$inferInsert)['options'] } = {} +): 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: group.publicId ?? generateId(), + name: 'Accounts', + options: group.options ?? [], + status: groupStatus, + }) + 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(), + enrollmentId: enrollment.id, + tokenHash: sha256Hex(token), + purpose: 'email', + expiresAt: enrollment.expiresAt, + revokedAt: enrollment.revokedAt, + }) + enrollmentIdByToken.set(token, enrollment.id) + 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 enrollmentId = enrollmentIdByToken.get(enrollmentToken) + if (!enrollmentId) throw new Error('Seeded enrollment not found') + const token = generateId() + await db.insert(credentialGroupEnrollmentLink).values({ + id: generateId(), + enrollmentId, + 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( + [ + { 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 })) + ) + 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, unverifiedId])) +}) + +describe('explainCredentialGroupEnrollmentLink', () => { + it('keeps an unknown token generic', async () => { + 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, + invitationExpiresAt: new Date(Date.now() - DAY_MS), + }) + await expect(explain(token, 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: shouterEmail.toLowerCase(), + status: 'revoked', + revokedAt: new Date(), + }) + 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 () => { + const token = await seedEnrollment({ + email: inviteeEmail, + userId: inviteeId, + status: 'revoked', + revokedAt: new Date(), + }) + 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(explain(token, invitee)).resolves.toEqual({ + kind: 'paused', + organizationName: 'Acme Corp', + }) + }) + + 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: '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', + connect: { publicId, provider: 'google-drive', optionId: DRIVE_OPTION.id }, + }) + }) + + 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(explain(token, 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(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(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(explain(token, invitee)).resolves.toEqual({ + kind: 'needs_new_link', + reason: 'link_revoked', + organizationName: 'Acme Corp', + inviterName: 'Ada Admin', + }) + }) + + it("never calls a bound person's emailed link expired", 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' }) + }) + + 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(explain(token, invitee)).resolves.toMatchObject({ + kind: 'needs_new_link', + reason: 'expired', + }) + }) + + 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({ + 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 new file mode 100644 index 00000000000..2801b564bbe --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-links.integration.ts @@ -0,0 +1,540 @@ +/** + * 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 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 { + credential, + credentialGroup, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + member, + organization, + user, +} from '@sim/db/schema' +import { explainCaptured } from '@sim/db/testing/explain' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { sleep } from '@sim/utils/helpers' +import { generateId } from '@sim/utils/id' +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' +import { + authenticatePublicCredentialGroupEnrollment, + bindCredentialGroupEnrollmentUser, + completeAuthorizedCredentialGroupEnrollment, + getCredentialGroupOAuthContextForEnrollment, + inviteCredentialGroupEnrollment, + lockCredentialGroupEnrollmentLifecycle, + 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() + +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, +})) + +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) + const outcome = pendingDeliveries.get(input.to)?.shift() + return outcome ?? { 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 +} + +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 enrollment's request, 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('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() + 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 emailed link', async () => { + const person = await createPerson() + 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(emailed.enrollmentId) + + 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('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) + 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) + + 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) + 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('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 status alone decides revocation, so the links are left unrevoked here. + 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('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('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) + }) + + 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) + // The status alone decides revocation, so its link is left unrevoked here. + 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) + try { + await waitForBlockedBy(holderPid) + } finally { + 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__/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 430e5aef103..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 @@ -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' @@ -163,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 () => { @@ -224,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 () => { @@ -585,10 +601,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 +835,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__/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 new file mode 100644 index 00000000000..10386961504 --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/slack-return.integration.ts @@ -0,0 +1,67 @@ +/** + * 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, vi } from 'vitest' +import { + type CredentialGroupOAuthAttempt, + consumeCredentialGroupOAuthAttempt, + createCredentialGroupOAuthAttempt, +} from '@/lib/credential-groups/oauth-state' +import { resolveCredentialGroupCompletionView } from '@/app/credential-groups/complete/completion-view' + +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 startAttempt() + + await expect(consumeCredentialGroupOAuthAttempt(state)).resolves.toMatchObject({ + origin: 'connect', + returnTo: 'slack', + } satisfies Partial) + }) + + 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('offers only the Slack app, and tells an expired attempt to go back to Slack', () => { + expect( + 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.', + 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 new file mode 100644 index 00000000000..1138244d611 --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -0,0 +1,1290 @@ +/** + * 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; 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 + * 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' +import { + credential, + credentialGroup, + credentialGroupConnectionRequest, + credentialGroupConnectionRequestPolicy, + credentialGroupEnrollment, + credentialGroupEnrollmentLink, + member, + organization, + outboxEvent, + resourcePolicy, + user, + workflow, + 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 { sleep } from '@sim/utils/helpers' +import { generateId } from '@sim/utils/id' +import { and, eq, inArray, isNotNull, sql } from 'drizzle-orm' +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 { startCredentialGroupConnect } from '@/lib/credential-groups/application/connect-target' +import { + getOrganizationAccountConnectionStatus, + 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 { + 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, + 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' +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, +})) + +/** + * 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 (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 + recipientEmail: string + workflowRequest?: { workflowName: string } + }) => { + mail.rendered.push(input) + return input.invitationLink + }, +})) + +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 + adminId: string +} + +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}` + +async function createOrg(): Promise { + const fixture = { + organizationId: generateId(), + groupId: generateId(), + publicId: generateId(), + workspaceId: generateId(), + outsideWorkspaceId: generateId(), + policyId: generateId(), + adminId: generateId(), + } + await db.insert(organization).values({ + id: fixture.organizationId, + name: 'Connection requests fixture', + 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) => ({ + 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 + .delete(credentialGroupConnectionRequestPolicy) + .where(eq(credentialGroupConnectionRequestPolicy.credentialGroupId, fixture.groupId)) + if (requests) + await db + .insert(credentialGroupConnectionRequestPolicy) + .values({ credentialGroupId: fixture.groupId, policy: requests }) +} + +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, + runWorkflowId = workflowId +): 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: runWorkflowId, + principal: { kind: 'system', serviceId: 'schedule', workspaceId, workflowId: runWorkflowId }, + currentWorkflow: { + workflowId: runWorkflowId, + 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, + runWorkflowId = workflowId +) => + requestOrganizationAccountConnection.execute({ + principal: deployedRun(workspaceId, runWorkflowId), + 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', + 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' }) + 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, + 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 emailEvents = (enrollmentId: string) => + db + .select({ reminder: sql`(${outboxEvent.payload} ->> 'reminder')::boolean` }) + .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 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 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') +} + +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) => + 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() + orgC = await createOrg() +}) + +afterAll(async () => { + await db + .delete(outboxEvent) + .where( + and( + eq(outboxEvent.eventType, CONNECTION_REQUEST_EMAIL_EVENT), + inArray(sql`${outboxEvent.payload} ->> 'workflowId'`, [workflowId, namedWorkflowId]) + ) + ) + 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()])) +}) + +/** 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: personConnectUrl(orgA, address('connected')), + }) + }) + + 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, + connectUrl: personConnectUrl(orgA, address('stale')), + }) + }) + + 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)) + + for (const label of ['invited', 'failed', 'expired', 'revoked', 'nobody']) + expect(await status(orgA, address(label))).toEqual({ + status: 'not_connected', + connected: false, + credentialId: null, + connectUrl: personConnectUrl(orgA, address(label)), + }) + }) + + 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(result).toEqual({ + requested: true, + connectUrl: personConnectUrl(orgA, address('new')), + }) + 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')) + await enroll(orgA, address('known-request')) + const known = await request(orgA, address('known-request')) + 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, 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, + 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 () => { + 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') + }) +}) + +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 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')) + + 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 () => { + 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, 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, askedToday]) + 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)).toEqual([{ reminder: null }]) + 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) + } + 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 () => { + 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("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("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, + }) + 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('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) + 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) + 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 = (_pid: number) => {} + 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 backendPid(tx)) + await held + }) + const holderPid = await locked + const reminder = request(orgA, email) + 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', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(workflow).values({ + id: namedWorkflowId, + userId: ownerId, + workspaceId: orgA.workspaceId, + name: `\u202Eexe.pdf\u0007 Payroll\nbot ${'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 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, 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 } + } + + async function deliver(enrollmentId: string, reminder?: boolean) { + const eventId = await enqueueOutboxEvent( + db, + CONNECTION_REQUEST_EMAIL_EVENT, + { + enrollmentId, + workflowId: namedWorkflowId, + providerId: DRIVE_ID, + providerName: DRIVE.label, + connectUrl: buildCredentialGroupConnectUrl({ publicId: orgA.publicId, provider: DRIVE_ID }), + ...(reminder ? { reminder } : {}), + } + ) + 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('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 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 + await deliver(enrollmentId) + expect(await enrollmentRow(enrollmentId)).toMatchObject({ + status: 'invited', + lastDeliveryError: null, + sentAt: expect.any(Date), + }) + }) + + 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( + { 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 }) + }) + + 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: personConnectUrl(orgA, email) }) + + 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 startCredentialGroupConnect.execute({ + principal: createSessionPrincipal({ userId }), + input: { + publicId: orgA.publicId, + provider: DRIVE_ID, + requestHandle: connectRequestHandle(orgA.groupId, email), + }, + }) + + expect(target).toMatchObject({ kind: 'started', optionId: DRIVE.id }) + if (target.kind !== 'started') 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 links = await db + .select({ purpose: credentialGroupEnrollmentLink.purpose }) + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.enrollmentId, requested.id)) + expect(links).toEqual([{ purpose: 'email' }]) + }) +}) + +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)) + 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, + workspaces: { mode: 'selected', workspaceIds: [] }, + }) + 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)) + 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 2d6b92d3379..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') } 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..e96721b6999 --- /dev/null +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -0,0 +1,373 @@ +import { AuditAction, AuditResourceType } from '@sim/audit' +import type { SessionPrincipal } from '@sim/auth/principal' +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 { 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, + hasLiveConnectConnection, + issueCredentialGroupConnectLink, + loadCredentialGroupConnectSubject, +} from '@/lib/credential-groups/connect-subject' +import { maskEnrollmentEmail } from '@/lib/credential-groups/email-mask' +import { + isEnrollmentRequestExpired, + isEnrollmentRevoked, +} from '@/lib/credential-groups/enrollment-lifecycle' +import { + OrganizationAccountsSetupRequiredError, + requireOrganizationAccountsSetup, +} from '@/lib/credential-groups/organization-setup' +import { + type CredentialGroupProvider, + findCredentialGroupProviderFromProviderId, +} from '@/lib/credential-groups/providers' +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 + * capability by the check the member self-enroll path uses. + */ +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. + */ + 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'], + capability: 'none', + }), +} as const + +interface CredentialGroupConnectInput { + publicId: string + /** The credential provider ID the workflow asked for (e.g. `google-drive`). */ + provider: string + optionId?: string + /** The connect URL's `for` handle, when it was built for one person's email. */ + requestHandle?: string +} + +/** + * 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 + provider: CredentialGroupProvider + options: Array<{ id: string; label: string }> + } + +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, or whose + * own request expired, which the POST renews. + */ + kind: 'ready_to_connect' | 'confirm_self_enrollment' + organizationName: string + provider: CredentialGroupProvider + 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 + | AlreadyConnected + +type ConnectDecision = + | CredentialGroupConnectRefusal + | (ConnectOffer & { credentialGroupId: string; target: CredentialGroupConnectLinkTarget }) + +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. 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, + tx?: DbTransaction +): Promise { + try { + await authorizeOrganizationOperation( + principal, + organizationAccountOperations.connect, + { organizationId }, + tx ? { executor: tx, forShare: true } : {} + ) + await requireOrganizationAccountsSetup(organizationId, credentialGroupId, tx) + return true + } catch (error) { + if ( + error instanceof ForbiddenOperationError || + error instanceof OrganizationMembershipNotFoundError || + error instanceof OrganizationAccountsSetupRequiredError + ) + return false + throw error + } +} + +/** 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 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; 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. + */ +async function decideConnectTarget( + principal: SessionPrincipal, + input: CredentialGroupConnectInput +): Promise { + const subject = await loadCredentialGroupConnectSubject({ + publicId: input.publicId, + userId: principal.userId, + }) + if (!subject || subject.group.status !== 'active') return UNAVAILABLE + const { group, enrollment, viewer } = 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 + if (!isCredentialGroupEmailVerified(viewer)) return { kind: 'verify_email' } + 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', + organizationName, + maskedEmail: maskEnrollmentEmail(enrollment.email), + } + if (enrollment && isEnrollmentRevoked(enrollment)) + return { kind: 'revoked', organizationName, provider } + const expired = enrollment !== null && isEnrollmentRequestExpired(enrollment) + if (expired || !enrollment) { + if (!group.organizationId || !(await canSelfEnroll(principal, group.organizationId, group.id))) + return expired + ? { kind: 'expired', organizationName, provider } + : { kind: 'not_invited', organizationName, provider } + } else if ( + !enrollment.userId && + group.organizationId && + !(await hasOrganizationSetup(group.organizationId, group.id)) + ) { + 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', + organizationName, + provider, + options: options.map(({ id, label }) => ({ id, label })), + } + return { + kind: enrollment && !expired ? 'ready_to_connect' : 'confirm_self_enrollment', + organizationName, + provider, + optionId: option.id, + credentialGroupId: group.id, + target: !enrollment + ? { kind: 'self_enrollment', mayEnroll } + : expired + ? { kind: 'renew_expired_enrollment', enrollmentId: enrollment.id, mayEnroll } + : { kind: 'enrollment', enrollmentId: enrollment.id }, + } +} + +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, or that their account is already + * connected, so a link opened again does not run the provider's consent again. 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, 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 } + }, +}) + +/** 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 + renewed: boolean +} + +const recordCredentialGroupConnectStart = defineAuthorizedCredentialUserUseCase({ + operation: credentialGroupConnectOperations.start, + async execute({ + principal, + input, + }: { + principal: SessionPrincipal + input: CredentialGroupConnectInput + }): Promise { + const decision = await decideConnectTarget(principal, input) + if (!isOffer(decision)) return decision + const issued = await issueCredentialGroupConnectLink({ + credentialGroupId: decision.credentialGroupId, + userId: principal.userId, + optionId: decision.optionId, + target: decision.target, + }) + if (!issued.issued) + return issued.reason === 'unavailable' + ? UNAVAILABLE + : { + kind: issued.reason, + organizationName: decision.organizationName, + provider: decision.provider, + } + return { + kind: 'started', + invitationToken: issued.token, + optionId: decision.optionId, + credentialGroupId: decision.credentialGroupId, + enrollmentId: issued.enrollmentId, + created: issued.created, + bound: issued.bound, + renewed: issued.renewed, + } + }, + projectAudit: ({ result }) => + result.kind === 'started' && (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' + : 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, + }, + } + : [], +}) + +/** + * 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/connection-requests.ts b/apps/sim/lib/credential-groups/application/connection-requests.ts new file mode 100644 index 00000000000..e648c7b2202 --- /dev/null +++ b/apps/sim/lib/credential-groups/application/connection-requests.ts @@ -0,0 +1,270 @@ +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 { + credentialGroupDelegationPolicy, + requireCredentialGroupWorkflowActor, + requireCurrentWorkflow, +} 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, +} 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, + recordCredentialGroupConnectionRequest, +} from '@/lib/credential-groups/connection-requests' +import { + findCredentialGroupProviderFromProviderId, + getCredentialGroupProviderId, + getCredentialGroupProviderService, + isCredentialGroupProvider, +} from '@/lib/credential-groups/providers' + +export interface OrganizationAccountConnectionInput { + workspaceId: string + email: string + /** Credential provider ID, as Find Organization Account takes it. */ + providerId: string + /** Where the connect page offers to send the person once connected; never a URL. */ + returnTo?: ConnectReturnDestination +} + +export interface OrganizationAccountConnectionStatusResult { + status: OrganizationAccountConnectionStatus + connected: boolean + credentialId: string | null + 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 +} + +/** + * 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 +} + +/** 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, + * refusing an inactive or disallowed integration by name. + */ +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', + `The ${integrationLabel(providerId)} integration is not active in this credential group` + ) + 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 ${integrationLabel(providerId)} integration` + ) + 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') + 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 } = 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: personConnectUrl(context, email, input), + } + }, +}) + +interface RecordedRequest extends OrganizationAccountConnectionRequestResult { + enrollmentId: string + created: boolean + workflowId: string + providerId: string +} + +/** 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) + const { policy } = await loadConnectionRequestPolicy(context.credentialGroupId) + return { ...context, connectionRequestPolicy: policy ?? CONNECTION_REQUESTS_OFF } + }, + authorizationOptions: { delegation: credentialGroupDelegationPolicy }, + async authorizeResource({ principal, context }) { + requireCredentialGroupWorkflowActor(principal) + context.workspaceAccessPolicy = await requireOrganizationAccountsWorkspaceAccess(context) + }, + execute: async ({ principal, input, context }): Promise => { + const { workflowId } = requireCurrentWorkflow(principal) + const email = requireRequestableEmail(input.email) + const accessPolicy = requireWorkspacePolicy(context) + const policy = context.connectionRequestPolicy + const refusal = connectionRequestRefusal(policy, { + 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) + + 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) deliverConnectionRequestEmailSoon(recorded.emailEventId) + 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, + }, + }), +}) + +/** + * 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/application/enrollment-auth.ts b/apps/sim/lib/credential-groups/application/enrollment-auth.ts index b39ac84ea1e..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 @@ -27,7 +28,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, @@ -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/enrollment-link-outcome.ts b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts new file mode 100644 index 00000000000..8e5eceff3b3 --- /dev/null +++ b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts @@ -0,0 +1,101 @@ +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 { 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 = { + /** + * 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; 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 = + | { 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' | 'link_revoked' + organizationName: string + inviterName: string | null + } + | { kind: 'unavailable' } + +/** + * 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 does not keep 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), + loadCredentialGroupViewer(principal.userId), + ]) + if (!record || !viewer || !isCredentialGroupEmailVerified(viewer)) return { kind: 'unknown' } + + 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, 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/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.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-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-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/organization-connection-requests.ts b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts new file mode 100644 index 00000000000..c579787f97c --- /dev/null +++ b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts @@ -0,0 +1,225 @@ +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, + organizationAccountPolicyAllowsWorkspace, +} from '@/lib/credential-groups/application/workspace-access-policy' +import type { ConnectionRequestPolicy } from '@/lib/credential-groups/connection-request-policy' +import { + loadConnectionRequestPolicy, + writeConnectionRequestPolicy, +} from '@/lib/credential-groups/connection-requests' +import { loadScopedAccountsCredentialListContext } from '@/lib/credential-groups/credentials' +import { + getCredentialGroupProviderId, + isCredentialGroupProvider, +} from '@/lib/credential-groups/providers' +import { requireResourcePolicy } 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 access = await requireResourcePolicy({ + organizationId, + resourceType: 'credential_group', + resourceId: group.credentialGroupId, + codec: organizationAccountAccessPolicyCodec, + }) + const accessWorkspaceIds = listOrganizationAccountWorkspaceIds(access.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 activeProviders = group.options.flatMap((option) => + option.status === 'active' && isCredentialGroupProvider(option.provider) + ? [{ id: getCredentialGroupProviderId(option.provider), label: option.label, option }] + : [] + ) + return { + group, + workspaces, + providers: activeProviders.map(({ id, label }) => ({ id, label })), + workspaceIds: new Set(workspaces.map((entry) => entry.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. + */ +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 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, + inEffect: isConnectionRequestPolicyInEffect(policy, state), + workspaces: state.workspaces, + providers: state.providers, + } + }, +}) + +/** + * 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. + */ +export const updateOrganizationConnectionRequestPolicy = defineOrganizationAccountsUseCase({ + operation: organizationConnectionRequestOperations.update, + async execute({ + input, + context, + }: { + input: { organizationId: string; revision: number; policy: ConnectionRequestPolicy } + context: OrganizationMembershipContext + }) { + 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))) + throw new OrchestrationError( + 'validation', + 'Every integration must be an active integration in this organization' + ) + if ( + next.workspaces.mode === 'selected' && + next.workspaces.workspaceIds.some((workspaceId) => !workspaceIds.has(workspaceId)) + ) + throw new OrchestrationError( + '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 + : pruneConnectionRequestPolicy(next, workspaceIds, providerIds) + 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, + 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/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.test.ts b/apps/sim/lib/credential-groups/application/personal-organization-accounts.test.ts index 7743b931744..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 @@ -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) }) @@ -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 a46adaac2ec..b22a73f8405 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 { lockCredentialGroupEnrollmentLifecycle } from '@/lib/credential-groups/enrollments' +import { revokeCredentialGroupEnrollmentLinks } from '@/lib/credential-groups/links' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import { createViewerCredentialGroupEnrollment } from '@/lib/credential-groups/self-enrollment' import { @@ -155,7 +154,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) { @@ -183,7 +182,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(), @@ -192,7 +191,7 @@ export const reconnectPersonalOrganizationAccount = defineAuthorizedCredentialUs authorizationUrl: createCredentialGroupOAuthStartUrl({ invitationLink, optionId: account.optionId, - returnTo: 'accounts', + origin: 'accounts', }), } : {}), @@ -216,14 +215,12 @@ 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 tx - .update(credentialGroupEnrollment) - .set({ invitationTokenHash: sha256Hex(generateId()), updatedAt: new Date() }) - .where(eq(credentialGroupEnrollment.id, current.enrollmentId)) + await revokeCredentialGroupEnrollmentLinks(tx, current.enrollmentId, now) }) return { success: true as const, 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..dae8b64090e 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', @@ -226,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 594ab5910c1..631b5a0989c 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 type { ConnectReturnDestination } from '@/lib/credential-groups/connect-return' import { bindCredentialGroupEnrollmentUser, completeAuthorizedCredentialGroupEnrollment, @@ -18,8 +19,13 @@ import { getAuthorizedPublicCredentialGroupEnrollment, getCredentialGroupMcpOAuthContextForEnrollment, getCredentialGroupOAuthContextForEnrollment, + isFocusedConnectionComplete, type PublicCredentialGroupEnrollmentIdentity, } from '@/lib/credential-groups/enrollments' +import { + CredentialGroupLinkFocusError, + getCredentialGroupEnrollmentLinkOptionId, +} from '@/lib/credential-groups/links' import { completeCredentialGroupMcpOAuth, startCredentialGroupMcpOAuth, @@ -35,10 +41,27 @@ 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( @@ -80,9 +103,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 { @@ -139,19 +168,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 } }, } ) @@ -159,28 +191,49 @@ export const readPublicCredentialGroupEnrollment = defineAuthorizedCredentialGro export const completePublicCredentialGroupEnrollment = defineAuthorizedCredentialGroupEnrollmentUseCase({ 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', - }) + resolveContext: ({ + principal, + }: { + principal: CredentialGroupEnrollmentPrincipal + input: Record + }) => resolvePublicEnrollmentContext(principal), + /** A focused link completes itself when its connection is saved; it has no Submit. */ + async execute({ context, linkOptionId }) { + if (linkOptionId) throw new CredentialGroupLinkFocusError() + 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 - returnTo?: 'search' | 'accounts' + origin?: 'search' | 'accounts' | 'connect' + returnTo?: ConnectReturnDestination } interface PublicCredentialGroupOAuthContext extends PublicCredentialGroupEnrollmentIdentity { @@ -199,6 +252,7 @@ async function resolvePublicOAuthContext( export const startPublicCredentialGroupOAuth = defineAuthorizedCredentialGroupEnrollmentUseCase({ operation: credentialGroupEnrollmentOperations.startOAuth, + target: (input) => ({ optionId: input.optionId }), resolveContext: ({ principal, input, @@ -210,6 +264,7 @@ export const startPublicCredentialGroupOAuth = defineAuthorizedCredentialGroupEn requireInvitationToken(principal, input.invitationToken) return { authorizationUrl: await startCredentialGroupOAuth(context.oauth, input.invitationToken, { + origin: input.origin, returnTo: input.returnTo, }), } @@ -259,6 +314,7 @@ async function resolveOAuthAttemptContext( export const completePublicCredentialGroupOAuth = defineAuthorizedCredentialGroupEnrollmentUseCase({ operation: credentialGroupEnrollmentOperations.completeOAuth, + target: (input) => ({ optionId: input.attempt.optionId }), resolveContext: ({ principal, input, @@ -266,7 +322,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) @@ -286,6 +342,8 @@ export const completePublicCredentialGroupOAuth = defineAuthorizedCredentialGrou displayName: completion.displayName, }, }) + if (linkOptionId && (await isFocusedConnectionComplete(context))) + await completeEnrollment(context, context.oauth.credentialGroupName) return { connectedOptionId: context.oauth.option.id } }, }) @@ -311,6 +369,7 @@ async function resolvePublicMcpOAuthContext( export const startPublicCredentialGroupMcpOAuth = defineAuthorizedCredentialGroupEnrollmentUseCase({ operation: credentialGroupEnrollmentOperations.startMcpOAuth, + target: (input) => ({ mcpServerId: input.mcpServerId }), resolveContext: ({ principal, input, @@ -334,6 +393,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-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..9babb61347f --- /dev/null +++ b/apps/sim/lib/credential-groups/connect-session.ts @@ -0,0 +1,23 @@ +import type { SessionPrincipal } from '@sim/auth/principal' +import { getSession } from '@/lib/auth' +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. + */ +export type CredentialGroupConnectSession = + | { kind: 'sign_in' } + | { kind: 'verify_email' } + | { 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' } + 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 new file mode 100644 index 00000000000..4fde05703a6 --- /dev/null +++ b/apps/sim/lib/credential-groups/connect-subject.ts @@ -0,0 +1,292 @@ +import { db } from '@sim/db' +import { + type CredentialGroupOptionConfig, + credential, + credentialGroup, + credentialGroupEnrollment, + organization, + user, + workspace, +} from '@sim/db/schema' +import { normalizeEmail } from '@sim/utils/string' +import { and, eq, inArray, or } from 'drizzle-orm' +import { LIVE_ENROLLMENT_STATUSES } from '@/lib/credential-groups/credentials' +import { + INVITATION_TTL_MS, + isEnrollmentRequestExpired, + isEnrollmentRevoked, +} from '@/lib/credential-groups/enrollment-lifecycle' +import { + findOrCreateUnissuedEnrollment, + loadCredentialGroupViewer, + lockCredentialGroupEnrollmentLifecycle, +} 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 + * 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< + EnrollmentRow, + 'id' | 'email' | 'userId' | 'status' | 'invitationExpiresAt' + > | 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 loadCredentialGroupViewer(input.userId) + 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, + invitationExpiresAt: credentialGroupEnrollment.invitationExpiresAt, + }) + .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, + } +} + +/** + * 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. */ + | { 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; mayEnroll: MayEnrollThemselves } + /** An organization member with no enrollment, who asked to connect. */ + | { kind: 'self_enrollment'; mayEnroll: MayEnrollThemselves } + +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 + /** An expired request was renewed for this link. */ + renewed: boolean + } + | { 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 + * 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 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: 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 + } +} + +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 { 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, + }) + 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/connect-url.ts b/apps/sim/lib/credential-groups/connect-url.ts new file mode 100644 index 00000000000..658c529cf85 --- /dev/null +++ b/apps/sim/lib/credential-groups/connect-url.ts @@ -0,0 +1,50 @@ +import { getBaseUrl } from '@/lib/core/utils/urls' +import type { ConnectReturnDestination } from '@/lib/credential-groups/connect-return' + +interface CredentialGroupConnectPathInput { + publicId: string + provider: string + optionId?: 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. */ +export function buildCredentialGroupConnectPath({ + publicId, + provider, + optionId, + returnTo, + requestHandle, +}: CredentialGroupConnectPathInput): string { + const query = new URLSearchParams({ provider }) + if (optionId) query.set('optionId', optionId) + if (requestHandle) query.set('for', requestHandle) + if (returnTo) query.set('return', returnTo) + 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. + */ +export function buildCredentialGroupConnectUrl( + input: Omit +): string { + return `${getBaseUrl()}${buildCredentialGroupConnectPath(input)}` +} + +/** + * 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 + returnTo?: ConnectReturnDestination +}): string { + 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/connection-request-email.ts b/apps/sim/lib/credential-groups/connection-request-email.ts new file mode 100644 index 00000000000..93b79c10448 --- /dev/null +++ b/apps/sim/lib/credential-groups/connection-request-email.ts @@ -0,0 +1,170 @@ +import { db } from '@sim/db' +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' +import { truncate, truncateAtCodePoint } from '@sim/utils/string' +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' +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' + +const logger = createLogger('CredentialGroupConnectionRequestEmail') + +const WORKFLOW_NAME_MAX_LENGTH = 60 + +function parsePayload(payload: unknown): ConnectionRequestEmailPayload { + if ( + !isRecordLike(payload) || + typeof payload.enrollmentId !== 'string' || + typeof payload.workflowId !== 'string' || + typeof payload.providerId !== 'string' || + typeof payload.providerName !== 'string' || + typeof payload.connectUrl !== 'string' + ) + throw new Error('Invalid connection request email payload') + return { + enrollmentId: payload.enrollmentId, + workflowId: payload.workflowId, + providerId: payload.providerId, + providerName: payload.providerName, + connectUrl: payload.connectUrl, + reminder: payload.reminder === true, + } +} + +/** + * The requesting workflow's name as the email body shows it. The name is whatever its builder + * 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(/\s+/g, ' ') + .replace(/[\p{Cc}\p{Cf}]/gu, '') + .trim() + return cleaned ? truncateAtCodePoint(cleaned, WORKFLOW_NAME_MAX_LENGTH, '…') : 'A workflow' +} + +/** + * 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 currentRequest(payload: ConnectionRequestEmailPayload): SQL | undefined { + return and( + 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 + * 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, + organizationId: organization.id, + organizationName: organization.name, + }) + .from(credentialGroupEnrollment) + .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) + .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) + .where(currentRequest(payload)) + .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, + owner: { kind: 'organization', name: target.organizationName }, + invitationLink: payload.connectUrl, + workflowRequest: { + workflowName: connectionRequestWorkflowName(requester?.name), + providerName: payload.providerName, + }, + }) + const result = await sendEmail({ + to: target.email, + subject: getCredentialGroupConnectionRequestSubject({ + organizationName: target.organizationName, + providerName: payload.providerName, + reminder: payload.reminder, + }), + html, + from: getFromEmailAddress(), + emailType: 'transactional', + }) + + if (!result.success) { + await db + .update(credentialGroupEnrollment) + .set({ + status: 'delivery_failed', + lastDeliveryError: truncate(result.message, 500), + updatedAt: new Date(), + }) + .where(stillRequested(payload, 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', + sentAt: new Date(), + lastDeliveryError: null, + updatedAt: new Date(), + }) + .where(stillRequested(payload, target.invitedAt)) + } catch (error) { + logger.error('Failed to record a sent connection request email', { + enrollmentId: payload.enrollmentId, + error: getErrorMessage(error), + }) + } +} + +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..50b211dfc90 --- /dev/null +++ b/apps/sim/lib/credential-groups/connection-request-event.ts @@ -0,0 +1,17 @@ +/** 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 + /** + * The requesting workflow; the email names it, read when sent from the workflow record in the + * 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. */ + reminder?: boolean +} 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..27d9916e5bc --- /dev/null +++ b/apps/sim/lib/credential-groups/connection-request-policy.ts @@ -0,0 +1,136 @@ +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 +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([ + '163.com', + 'aol.com', + 'gmail.com', + 'gmx.com', + 'gmx.de', + 'googlemail.com', + 'hotmail.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}$/ +const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/ + +/** 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() +} + +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)) + .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, 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 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() + +/** + * 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' }) + } +) + +export type ConnectionRequestPolicy = z.output + +/** 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 + /** 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 ( + 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 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 new file mode 100644 index 00000000000..e46d54f3d8d --- /dev/null +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -0,0 +1,428 @@ +import { db } from '@sim/db' +import { + credential, + credentialGroupConnectionRequest, + credentialGroupConnectionRequestPolicy, + credentialGroupEnrollment, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { + and, + countDistinct, + eq, + gt, + inArray, + isNotNull, + isNull, + lt, + type SQL, + sql, +} from 'drizzle-orm' +import { OrchestrationError } from '@/lib/core/orchestration/types' +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, +} 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 { + 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 { 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`). + */ +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' + +/** + * 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 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) } +} + +/** + * 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 OrchestrationError( + 'conflict', + 'Someone else changed these settings. Review and save again.' + ) + return row.revision +} + +interface RecordedConnectionRequest { + enrollmentId: string + /** Whether this request created the enrollment. */ + created: boolean + /** The outbox event that will email the person, when one was enqueued. */ + emailEventId: string | null +} + +/** + * 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, + 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), + ...(enrollment.requestedByWorkflowId !== null + ? { requestedByWorkflowId: request.workflowId, requestedProviderId: request.providerId } + : {}), + 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 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: 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 + * {@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 + * days by the hourly `cleanup-credential-group-links` job. + */ +export async function recordCredentialGroupConnectionRequest(input: { + credentialGroupId: string + email: string + workspaceId: string + workflowId: string + providerId: 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) + const log = credentialGroupConnectionRequest + await acquireAdvisoryXactLock( + tx, + '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) + .where( + and( + eq(log.credentialGroupId, input.credentialGroupId), + eq(log.email, input.email), + gt(log.createdAt, dayAgo) + ) + ) + .limit(1) + if (!askedToday) + 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, + now, + request: { workflowId: input.workflowId, providerId: input.providerId }, + }) + const email = (reminder: boolean) => ({ + enrollmentId: row.id, + workflowId: input.workflowId, + providerId: input.providerId, + providerName: input.providerName, + connectUrl: input.connectUrl, + ...(reminder ? { reminder } : {}), + }) + if (created) + return { + enrollmentId: row.id, + created, + emailEventId: input.sendEmail + ? await enqueueConnectionRequestEmail(tx, email(false)) + : null, + } + + 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 + .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: row.id, + created, + emailEventId: reminded ? await enqueueConnectionRequestEmail(tx, email(true)) : null, + } + }) +} + +/** + * 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, + providerId, + providerName, + connectUrl: input.connectUrlFor({ providerId, email: row.email }), + reminder: true, + }) + 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) + }) +} diff --git a/apps/sim/lib/credential-groups/credentials.ts b/apps/sim/lib/credential-groups/credentials.ts index bbe6a0762ff..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]) ) @@ -487,6 +488,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/enrollment-lifecycle.ts b/apps/sim/lib/credential-groups/enrollment-lifecycle.ts new file mode 100644 index 00000000000..17ce0a61125 --- /dev/null +++ b/apps/sim/lib/credential-groups/enrollment-lifecycle.ts @@ -0,0 +1,60 @@ +import type { credentialGroupEnrollment } from '@sim/db/schema' +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 + +/** + * 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', + 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; a revocation sets the status (and `revoked_at`). */ +export function isEnrollmentRevoked(enrollment: Pick): boolean { + return enrollment.status === 'revoked' +} + +/** + * 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/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/enrollments.test.ts b/apps/sim/lib/credential-groups/enrollments.test.ts index be3077a0df5..4f93c956d35 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(), })) @@ -39,10 +42,8 @@ vi.mock('@/lib/credential-groups/availability', () => ({ vi.mock('@/lib/credential-groups/provider-registry', () => credentialGroupsProvidersMock) -import { renderCredentialGroupInvitationEmail } from '@/components/emails/credential-groups/render' import { bindCredentialGroupEnrollmentUser, - completeCredentialGroupEnrollment, createCredentialGroupSelfEnrollmentLink, deleteCredentialGroupEnrollment, getAuthorizedCredentialGroupOAuthContext, @@ -82,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'), @@ -105,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 }, @@ -373,21 +375,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]) - 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( @@ -438,48 +425,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([{ ...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', () => { @@ -502,100 +447,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', @@ -607,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', @@ -621,39 +471,9 @@ 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 () => { - 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() - ) - 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' }] }, ])('refuses an enrollment or option that is no longer live', async (change) => { @@ -688,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') @@ -714,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' }, @@ -777,14 +597,14 @@ describe('verified immutable enrollment identity binding', () => { credentialGroupId: 'group-1', enrollmentId: ENROLLMENT.id, email: ENROLLMENT.email, - invitationTokenHash: ENROLLMENT.invitationTokenHash, + invitationTokenHash: TOKEN_HASH, } beforeEach(() => { resetDbChainMock() }) 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( @@ -792,16 +612,16 @@ describe('verified immutable enrollment identity binding', () => { ) expect(isNull).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.userId) expect(eq).toHaveBeenCalledWith( - schemaMock.credentialGroupEnrollment.invitationTokenHash, + schemaMock.credentialGroupEnrollmentLink.tokenHash, identity.invitationTokenHash ) }) 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' @@ -813,7 +633,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() @@ -824,7 +644,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 7c12d0feb7e..149dde573af 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -4,12 +4,12 @@ import { credential, credentialGroup, credentialGroupEnrollment, + credentialGroupEnrollmentLink, mcpServers, organization, 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' @@ -26,6 +26,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 { + hashInvitationToken, + 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' @@ -34,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' @@ -45,13 +58,13 @@ 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' 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 const DELIVERY_CONCURRENCY = 5 const MAX_ENROLLMENT_PAGE_SIZE = 100 const CONNECTION_SUMMARIES_PER_ENROLLMENT = (CREDENTIAL_GROUP_PROVIDER_IDS.length + 1) * 3 @@ -92,7 +105,7 @@ interface SendInvitationOptions { interface IssuedInvitation { enrollment: EnrollmentRow invitationLink: string - tokenHash: string + linkId: string } export interface PublicCredentialGroupEnrollment { @@ -188,7 +201,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 @@ -251,10 +264,6 @@ function decodeCredentialGroupEnrollmentCursor(cursor: string): CredentialGroupE } } -function hashInvitationToken(token: string): string { - return sha256Hex(token) -} - 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 +294,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 (isEnrollmentRevoked(row.enrollment)) return null const ownerScope = resourceScopeFromOwner(row) if (!(await isScopedCredentialGroupsAvailable(ownerScope))) return null @@ -306,24 +310,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 +336,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( @@ -369,7 +372,7 @@ export async function bindCredentialGroupEnrollmentUser( .select({ enrollment: credentialGroupEnrollment, email: user.email, - verified: user.emailVerified, + emailVerified: user.emailVerified, }) .from(credentialGroupEnrollment) .innerJoin( @@ -381,7 +384,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,16 +392,11 @@ 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) { 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) @@ -422,7 +420,7 @@ export async function bindCredentialGroupEnrollmentUser( }) } -function toCredentialGroupEnrollment(row: EnrollmentRow): CredentialGroupEnrollmentRecord { +export function toCredentialGroupEnrollment(row: EnrollmentRow): CredentialGroupEnrollmentRecord { return { id: row.id, credentialGroupId: row.credentialGroupId, @@ -433,7 +431,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(), } @@ -509,6 +507,82 @@ async function getInvitationContext( } } +function invitationLinkFor(token: string): string { + return `${getBaseUrl()}/credential-groups/enroll/${token}` +} + +/** + * Locks the invitation target and reads its enrollment, if any, under the enrollment's lifecycle + * lock as well. + */ +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 +} + +/** + * 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 + * 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, /** @@ -523,40 +597,10 @@ async function issueInvitation( options: SendInvitationOptions ): 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) => { - 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 - } - + 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) } @@ -566,22 +610,23 @@ async function issueInvitation( const preservesProgress = current?.status === 'in_progress' || current?.status === 'completed' const nextStatus = preservesProgress ? current.status : ('invited' as const) - const mutableValues = { - status: nextStatus, - invitationTokenHash: tokenHash, + const invitationValues = { invitationExpiresAt: expiresAt, + status: nextStatus, invitedAt: now, sentAt: null, completedAt: preservesProgress ? current.completedAt : null, revokedAt: null, lastDeliveryError: null, createdBy: userId ?? null, + requestedByWorkflowId: null, + connectionRequestReminders: 0, updatedAt: now, } const [next] = current ? await tx .update(credentialGroupEnrollment) - .set(mutableValues) + .set(invitationValues) .where(eq(credentialGroupEnrollment.id, current.id)) .returning() : await tx @@ -590,19 +635,68 @@ 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 { token, linkId } = await insertEnrollmentLink(tx, { + enrollmentId: next.id, + purpose: 'email', + expiresAt, + now, + }) + return { enrollment: next, linkId, invitationLink: invitationLinkFor(token) } }) +} - return { - enrollment, - invitationLink: `${getBaseUrl()}/credential-groups/enroll/${token}`, - tokenHash, - } +/** + * 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. + */ +async function issueSelfEnrollmentLink( + groupId: string, + email: string +): Promise<{ enrollment: EnrollmentRow; invitationLink: string }> { + return db.transaction(async (tx) => { + const now = new Date() + const { row: enrollment } = await findOrCreateUnissuedEnrollment(tx, { + credentialGroupId: groupId, + email, + now, + }) + if (isEnrollmentRevoked(enrollment)) { + throw new CredentialGroupEnrollmentError('Revoked enrollment cannot be resent', 409) + } + const { token } = await insertEnrollmentLink(tx, { + enrollmentId: enrollment.id, + purpose: 'self', + now, + }) + return { enrollment, invitationLink: invitationLinkFor(token) } + }) +} + +/** + * 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 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( @@ -617,18 +711,19 @@ async function sendInvitation( const { enrollment: issued, invitationLink, - tokenHash, + linkId, } = await issueInvitation(context, userId, email, options) 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, - 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 } @@ -650,13 +745,7 @@ async function sendInvitation( lastDeliveryError: truncate(result.message, 500), updatedAt: new Date(), }) - .where( - and( - eq(credentialGroupEnrollment.id, issued.id), - eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), - eq(credentialGroupEnrollment.status, issued.status) - ) - ) + .where(and(eq(credentialGroupEnrollment.id, issued.id), deliveryStillCurrent(issued, linkId))) .returning({ id: credentialGroupEnrollment.id }) if (!failed) { throw new CredentialGroupEnrollmentError( @@ -670,13 +759,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), - eq(credentialGroupEnrollment.invitationTokenHash, tokenHash), - eq(credentialGroupEnrollment.status, issued.status) - ) - ) + .where(and(eq(credentialGroupEnrollment.id, issued.id), deliveryStillCurrent(issued, linkId))) .returning() if (!sent) { throw new CredentialGroupEnrollmentError( @@ -874,6 +957,8 @@ export async function listCredentialGroupEnrollments( return { enrollments: pageRows.map(({ enrollment }) => ({ ...toCredentialGroupEnrollment(enrollment), + requestedByWorkflow: enrollment.requestedByWorkflowId !== null, + bound: enrollment.userId !== null, connections: connectionsByEnrollment.get(enrollment.id) ?? [], mcpConnections: mcpConnectionsByEnrollment.get(enrollment.id) ?? [], })), @@ -925,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> { @@ -967,9 +1064,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', - }) + const issued = await issueSelfEnrollmentLink(context.groupId, normalizeEmail(email)) return { enrollment: toCredentialGroupEnrollment(issued.enrollment), invitationLink: issued.invitationLink, @@ -1094,6 +1189,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 }) @@ -1109,15 +1205,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 } @@ -1277,19 +1364,51 @@ 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), - }) - if (!row) return null - const result = await completeResolvedCredentialGroupEnrollment( - row, - identityForPublicEnrollmentRow(row) +/** + * Whether a connection made through a focused link finishes the enrollment on its own: a + * 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 + 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, + activeOptions.map((option) => option.id) + ), + eq(credential.managedOauthStatus, 'active'), + isNull(credential.revokedAt) + ) + ) + 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 result?.completed ?? null + return true + return activeOptions.every((option) => connectedOptionIds.has(option.id)) } +/** Finalizes an enrollment after the recipient finishes their optional account selections. */ export async function completeAuthorizedCredentialGroupEnrollment( identity: PublicCredentialGroupEnrollmentIdentity ): Promise { @@ -1306,23 +1425,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) return null const [group] = await tx .select({ @@ -1351,7 +1463,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/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..734bf987182 --- /dev/null +++ b/apps/sim/lib/credential-groups/links.ts @@ -0,0 +1,260 @@ +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, ne, or, type SQL, sql } from 'drizzle-orm' +import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' +import { resourceScopeFromOwner } from '@/lib/core/resource-scope' +import { + INVITATION_TTL_MS, + isEnrollmentRevoked, +} from '@/lib/credential-groups/enrollment-lifecycle' +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, decided by {@link unexpiredLinkCondition} alone: + * - `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. + */ + +/** 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) +} + +/** + * 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 unexpiredLinkCondition(now: Date): SQL { + const link = credentialGroupEnrollmentLink + const enrollment = credentialGroupEnrollment + return sql`(${or( + and(isNotNull(enrollment.userId), eq(link.purpose, 'email')), + gt(link.expiresAt, now) + )})` +} + +/** + * 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 + 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. + * + * 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 enrollment = credentialGroupEnrollment + return sql`(${and( + sql`${enrollment.id} = ${enrollmentIdForTokenHash(tokenHash)}`, + 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) + )}))` +} + +/** 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) + ) + ) +} + +/** + * 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 + } +): Promise<{ token: string; linkId: string; expiresAt: Date }> { + const 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 it may connect any option. */ +export async function getCredentialGroupEnrollmentLinkOptionId( + tokenHash: string +): Promise { + const [row] = await db + .select({ optionId: credentialGroupEnrollmentLink.optionId }) + .from(credentialGroupEnrollmentLink) + .where(eq(credentialGroupEnrollmentLink.tokenHash, tokenHash)) + .limit(1) + return row?.optionId ?? null +} + +/** 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' + } +} + +/** Whether `error`, or an error it wraps, is a {@link CredentialGroupLinkFocusError}. */ +export function isCredentialGroupLinkFocusError(error: unknown): boolean { + return asOrchestrationError(error) instanceof CredentialGroupLinkFocusError +} + +interface CredentialGroupEnrollmentLinkRecord { + email: string + userId: string | null + status: EnrollmentRow['status'] + /** The link's purpose. */ + purpose: EnrollmentLinkPurpose + /** Past its expiry under {@link unexpiredLinkCondition}. */ + 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, 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 now = new Date() + const [row] = await db + .select({ + email: credentialGroupEnrollment.email, + userId: credentialGroupEnrollment.userId, + status: credentialGroupEnrollment.status, + expired: sql`not ${unexpiredLinkCondition(now)}`, + 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)) + .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(sql`${credentialGroupEnrollment.id} = ${enrollmentIdForTokenHash(tokenHash)}`) + .limit(1) + if (!row || !(await isScopedCredentialGroupsAvailable(resourceScopeFromOwner(row)))) return null + const focusOption = row.linkOptionId + ? row.options.find((option) => option.id === row.linkOptionId) + : undefined + return { + email: row.email, + userId: row.userId, + status: row.status, + purpose: row.linkPurpose, + expired: row.expired, + revoked: isEnrollmentRevoked(row), + 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/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..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() }) @@ -103,10 +104,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 +152,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,16 +161,17 @@ 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() + 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/apps/sim/lib/credential-groups/oauth-state.ts b/apps/sim/lib/credential-groups/oauth-state.ts index 3aaa95094d6..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, @@ -14,8 +18,22 @@ import { isCredentialGroupProvider, } from '@/lib/credential-groups/providers' -const OAUTH_ATTEMPT_TTL_MS = 10 * 60 * 1000 -const OAUTH_ATTEMPT_VERSION = 5 as const +/** Where a managed-enrollment OAuth attempt lands once the provider sends the person back. */ +export type CredentialGroupOAuthOrigin = + | 'search' + | 'accounts' + | 'connect' + | 'integrations' + | 'github-installation' + +/** 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 = ` @@ -44,7 +62,8 @@ interface StoredCredentialGroupOAuthAttempt { completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: 'search' | 'accounts' | 'integrations' | 'github-installation' + origin?: CredentialGroupOAuthOrigin + returnTo?: ConnectReturnDestination nonceHash: string encryptedCodeVerifier?: string encryptedInvitationToken: string @@ -69,7 +88,8 @@ export interface CredentialGroupOAuthAttempt { completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: 'search' | 'accounts' | 'integrations' | 'github-installation' + origin?: CredentialGroupOAuthOrigin + returnTo?: ConnectReturnDestination codeVerifier?: string invitationToken: string createdAt: number @@ -91,7 +111,8 @@ interface CreateCredentialGroupOAuthAttemptParams { completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: 'search' | 'accounts' | 'integrations' | 'github-installation' + origin?: CredentialGroupOAuthOrigin + returnTo?: ConnectReturnDestination codeVerifier?: string invitationToken: string } @@ -137,14 +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 === '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.returnTo === undefined || + parseConnectReturnDestination(candidate.returnTo) !== undefined) && typeof candidate.nonceHash === 'string' && (candidate.encryptedCodeVerifier === undefined || typeof candidate.encryptedCodeVerifier === 'string') && @@ -164,7 +188,7 @@ 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') @@ -193,6 +217,7 @@ 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 } : {}), nonceHash: sha256Hex(nonce), ...(encryptedCodeVerifier ? { encryptedCodeVerifier: encryptedCodeVerifier.encrypted } : {}), @@ -203,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') @@ -215,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 @@ -227,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, @@ -250,6 +285,7 @@ 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 } : {}), ...(codeVerifier ? { codeVerifier: codeVerifier.decrypted } : {}), invitationToken: invitationToken.decrypted, diff --git a/apps/sim/lib/credential-groups/oauth.test.ts b/apps/sim/lib/credential-groups/oauth.test.ts index a008244d970..f4972226b89 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]) @@ -288,7 +255,7 @@ describe('credential group OAuth persistence', () => { connectedCredentialId: 'credential-1', }) expect(eq).toHaveBeenCalledWith( - schemaMock.credentialGroupEnrollment.invitationTokenHash, + schemaMock.credentialGroupEnrollmentLink.tokenHash, expect.any(String) ) } @@ -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 f8773adffd7..265824221d7 100644 --- a/apps/sim/lib/credential-groups/oauth.ts +++ b/apps/sim/lib/credential-groups/oauth.ts @@ -13,14 +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 { liveEnrollmentLinkCondition } from '@/lib/credential-groups/links' import type { CredentialGroupConnectionIntent } from '@/lib/credential-groups/oauth-intent' import { type CredentialGroupOAuthAttempt, + type CredentialGroupOAuthOrigin, createCredentialGroupOAuthAttempt, } from '@/lib/credential-groups/oauth-state' import type { @@ -121,7 +124,8 @@ export async function startCredentialGroupOAuth( completionRedirect?: boolean connectionIntent?: CredentialGroupConnectionIntent completionId?: string - returnTo?: 'search' | 'accounts' | 'integrations' | 'github-installation' + origin?: CredentialGroupOAuthOrigin + returnTo?: ConnectReturnDestination } = {} ): Promise { if (!context.credentialOwnerId) throw new CredentialGroupInvitationUnavailableError() @@ -144,6 +148,7 @@ export async function startCredentialGroupOAuth( completionRedirect: options.completionRedirect, completionId: options.completionId, connectionIntent: options.connectionIntent, + origin: options.origin, returnTo: options.returnTo, invitationToken, }) @@ -171,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( @@ -182,11 +184,11 @@ 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) - if (!enrollment || enrollment.status === 'revoked' || enrollment.revokedAt) { + if (!enrollment) { throw new CredentialGroupInvitationUnavailableError() } @@ -410,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/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/rate-limit.ts b/apps/sim/lib/credential-groups/rate-limit.ts index c1865c3e5b8..e6fe5b51c73 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 = { @@ -87,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 } @@ -110,6 +114,35 @@ 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 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 +): 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 { constructor( readonly retryAfterSeconds: number, 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/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/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..06fca0c9582 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 @@ -98,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[] } 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 4b7290d8a85..a889b75c5fb 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 = { @@ -42,7 +35,6 @@ const input = { } const source = { enrollmentStatus: 'in_progress', - enrollmentRevokedAt: null, credentialGroupId: input.credentialGroupId, groupStatus: 'active', linkedCredentialGroupId: input.credentialGroupId, @@ -56,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' }, ])( @@ -65,13 +55,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,12 +70,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.credentialGroupEnrollment.invitationTokenHash, - input.invitationTokenHash - ) - expect(eq).toHaveBeenCalledWith(schemaMock.mcpServers.oauthConfigVersion, 2) expect(dbChainMockFns.values).toHaveBeenCalledWith( expect.objectContaining({ organizationId: 'org-1', diff --git a/apps/sim/lib/credentials/managed-mcp.ts b/apps/sim/lib/credentials/managed-mcp.ts index 9ee170a3fc6..5cf4f126498 100644 --- a/apps/sim/lib/credentials/managed-mcp.ts +++ b/apps/sim/lib/credentials/managed-mcp.ts @@ -23,6 +23,7 @@ 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 } from '@/lib/credential-groups/links' import { getManagedMcpConnector, managedMcpAccountLimit, @@ -353,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, @@ -371,7 +371,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), @@ -386,8 +386,6 @@ export async function persistManagedMcpCredential(params: { !source || !source.managedConnectorId || source.groupStatus !== 'active' || - source.enrollmentRevokedAt || - !['invited', '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/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/apps/sim/lib/credentials/personal-tokens.test.ts b/apps/sim/lib/credentials/personal-tokens.test.ts index faaf7485557..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,11 +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', - 'in_progress', - 'completed', - ]) expect(isNull).toHaveBeenCalledWith(schemaMock.credentialGroupEnrollment.revokedAt) } 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/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 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/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'], 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/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/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/packages/db/migrations/0490_credential_group_connect.sql b/packages/db/migrations/0490_credential_group_connect.sql new file mode 100644 index 00000000000..e1fca5fece6 --- /dev/null +++ b/packages/db/migrations/0490_credential_group_connect.sql @@ -0,0 +1,84 @@ +-- 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. +-- +-- 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 +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 +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, 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, + 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 +WHERE e."invitation_token_hash" IS NOT NULL +ON CONFLICT ("token_hash") DO NOTHING; +--> statement-breakpoint +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, + "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 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, + "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 +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/0490_snapshot.json b/packages/db/migrations/meta/0490_snapshot.json new file mode 100644 index 00000000000..387bb4a556b --- /dev/null +++ b/packages/db/migrations/meta/0490_snapshot.json @@ -0,0 +1,35177 @@ +{ + "id": "5c5435c6-77b4-41bb-8c2a-83bd6221e9d0", + "prevId": "32dff090-1cd7-4284-8167-19869fa46e89", + "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": {} + }, + "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": { + "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": false + }, + "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 + }, + "requested_provider_id": { + "name": "requested_provider_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_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": {} + }, + "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": { + "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 + }, + "require_two_factor": { + "name": "require_two_factor", + "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.two_factor": { + "name": "two_factor", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "backup_codes": { + "name": "backup_codes", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "verified": { + "name": "verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "failed_verification_count": { + "name": "failed_verification_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "two_factor_user_id_idx": { + "name": "two_factor_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "two_factor_user_id_user_id_fk": { + "name": "two_factor_user_id_user_id_fk", + "tableFrom": "two_factor", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "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 + }, + "two_factor_enabled": { + "name": "two_factor_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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 6ed4c7d7ef2..d842d0a1915 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -3424,6 +3424,13 @@ "when": 1796319577103, "tag": "0489_two_factor", "breakpoints": true + }, + { + "idx": 490, + "version": "7", + "when": 1796334996916, + "tag": "0490_credential_group_connect", + "breakpoints": true } ] } diff --git a/packages/db/schema.ts b/packages/db/schema.ts index 6125917682c..3da28f95722 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -7451,7 +7451,16 @@ 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'), - invitationTokenHash: text('invitation_token_hash').notNull(), + /** + * @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'), + /** + * 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'), @@ -7459,6 +7468,15 @@ 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, then moved to the workflow that + * asked most recently; an admin invitation clears it. + */ + requestedByWorkflowId: text('requested_by_workflow_id'), + /** 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), createdAt: timestamp('created_at').notNull().defaultNow(), updatedAt: timestamp('updated_at').notNull().defaultNow(), }, @@ -7494,6 +7512,108 @@ 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 + ), + /** 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` + ), + }) +) + +/** + * 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 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', + { + 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), + /** 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` + ), + }) +) + /** 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..815432f9c74 100644 --- a/packages/testing/src/mocks/credential-groups-enrollments.mock.ts +++ b/packages/testing/src/mocks/credential-groups-enrollments.mock.ts @@ -18,7 +18,7 @@ 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). + * resolves `undefined`. Link storage lives in `@/lib/credential-groups/links`. * * @example * ```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(), @@ -42,9 +46,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(), @@ -65,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, @@ -75,10 +81,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/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, diff --git a/packages/testing/src/mocks/schema-tables.generated.ts b/packages/testing/src/mocks/schema-tables.generated.ts index b76d14c5b1b..35ecd2d7630 100644 --- a/packages/testing/src/mocks/schema-tables.generated.ts +++ b/packages/testing/src/mocks/schema-tables.generated.ts @@ -1887,9 +1887,38 @@ export const GENERATED_SCHEMA_TABLES = { 'revokedAt', 'lastDeliveryError', 'createdBy', + 'requestedByWorkflowId', + 'requestedProviderId', + 'connectionRequestReminders', 'createdAt', 'updatedAt', ], + credentialGroupEnrollmentLink: [ + 'id', + 'enrollmentId', + 'tokenHash', + 'purpose', + 'optionId', + 'expiresAt', + 'revokedAt', + 'createdAt', + ], + credentialGroupConnectionRequestPolicy: [ + 'credentialGroupId', + 'policy', + 'revision', + 'updatedBy', + 'createdAt', + 'updatedAt', + ], + credentialGroupConnectionRequest: [ + 'id', + 'credentialGroupId', + 'email', + 'workspaceId', + 'workflowId', + 'createdAt', + ], assistantToolPermission: [ 'organizationId', 'userId', @@ -2578,6 +2607,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'], 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', 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 diff --git a/scripts/check-unused-exports.baseline.json b/scripts/check-unused-exports.baseline.json index 4635383ead6..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", @@ -4175,7 +4174,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",