diff --git a/apps/docs/content/docs/platform/connected-accounts.mdx b/apps/docs/content/docs/platform/connected-accounts.mdx index 27145b429e5..5b339fd24a0 100644 --- a/apps/docs/content/docs/platform/connected-accounts.mdx +++ b/apps/docs/content/docs/platform/connected-accounts.mdx @@ -60,6 +60,8 @@ Use the invitation email for workflow lookups. For example, inviting `alex@examp On first use, the invitation email must match the signed-in user's verified Sim email. Sim binds the invitation to that user account. Opening the link as another person cannot take it over, and a later email change does not transfer it to another Sim user. The invitation email remains the workflow lookup key. +A person whose Sim email is not verified cannot connect until they verify it. Where your deployment cannot send verification codes, they sign in again with Google or GitHub, if configured, to confirm the address. + 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. Each person shows one status: @@ -69,7 +71,7 @@ Each person shows one status: | **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 | +| **Email failed** | Sim could not deliver the request email, and the person has not accepted it | | **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 | @@ -77,7 +79,7 @@ Each person shows one status: 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. +Use **Send email** in a person's menu, or **Send reminder** once Sim has emailed them, 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 @@ -96,6 +98,10 @@ For example, allowing Gmail in the Support workspace lets its authorized workflo Changes apply to subsequent calls. Removing access cannot recall a provider request already in flight or erase data already received. Standalone Chat continues to use each person's own connections; the workspace grant does not give Chat other people's accounts. +### Workflow connection requests + +Workflows cannot ask people to connect until an admin turns on **Allow workflow requests** under **Workflow connection requests** on **Access**, choosing workspaces, email domains, integrations, a daily limit, and whether to **Also email the person**. The workspace must also have the integration on **Access**. Once on, any run of a workflow in a chosen workspace can use **Request Connection** to ask people at those domains, and Sim emails them when that option is on. See [Connection status and requests](/workflows/blocks/credential#connection-requests). + ## Use account references in workflows In an eligible workspace, use the Credential block's organization operations: @@ -106,6 +112,8 @@ In an eligible workspace, use the Credential block's organization operations: | **List Organization Accounts** | A page of OAuth accounts, optionally filtered by email and providers | | **Find Organization MCP Connection** | One managed MCP connection matching the invitation email and MCP provider | | **List Organization MCP Connections** | A page of managed MCP connections, optionally filtered by email and provider | +| **Get Connection Status** | Whether a person has a usable account for an integration, and their link to connect it | +| **Request Connection** | Asks a person to connect an integration, when workflow connection requests allow it | The workflow's workspace determines the organization. You do not enter a credential group or organization ID. diff --git a/apps/docs/content/docs/workflows/blocks/credential.mdx b/apps/docs/content/docs/workflows/blocks/credential.mdx index 7b0143cc273..c04eac482a0 100644 --- a/apps/docs/content/docs/workflows/blocks/credential.mdx +++ b/apps/docs/content/docs/workflows/blocks/credential.mdx @@ -101,15 +101,15 @@ For example, name the block **Account**, choose Find Organization Account, set E | `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. +The status never says whether the person was invited, removed, or never asked. `connectUrl` is that person's link and carries no secret: the page checks that the signed-in person has that email before anything is connected, and tells anyone else the link was sent to a different email. 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. +**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, and the workspace has that integration on **Access**. Nothing else gates a request: 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. +The daily limit counts distinct people asked in the last 24 hours, a rolling window, across all workspaces. Everyone asked counts, including people asked or connected before; asking again for someone already counted in the window does not count again. Once the limit is reached, every request fails, including one for someone already counted. A request the person has not accepted expires after 7 days; asking again renews it. Sim emails the person only when the admin turned on **Also email the person**. The email carries the link and the workflow's name. Sim sends up to 3 reminders, each only when a workflow asks again after a day with no request for that person, and none after 30 days. Runs from the workflow editor are real: they send real emails and count toward the daily limit. diff --git a/apps/sim/app/(auth)/auth-redirect.ts b/apps/sim/app/(auth)/auth-redirect.ts index e11d8d742b4..9c53c85d4fa 100644 --- a/apps/sim/app/(auth)/auth-redirect.ts +++ b/apps/sim/app/(auth)/auth-redirect.ts @@ -10,6 +10,14 @@ export const POST_AUTH_REDIRECT_STORAGE_KEY = 'postAuthRedirectUrl' /** Route the verify hop lives at, entered only from signup. */ export const VERIFY_FROM_SIGNUP_ROUTE = '/verify?fromSignup=true' +/** + * The verify page for a signed-in person whose email is still unverified. Nothing sent them a code + * on the way here, so the page sends one as it opens, then returns to `redirectAfter`. + */ +export function buildVerifyEmailPath(redirectAfter: string): string { + return `/verify?${new URLSearchParams({ sendCode: 'true', redirectAfter })}` +} + /** * Default post-auth destination when no callback URL was carried in: the app * entry, which resolves to the viewer's organization or their workspaces. diff --git a/apps/sim/app/(auth)/components/oauth-provider-checker.tsx b/apps/sim/app/(auth)/components/oauth-provider-checker.tsx index a8ba38dcfb4..fc44e2266f2 100644 --- a/apps/sim/app/(auth)/components/oauth-provider-checker.tsx +++ b/apps/sim/app/(auth)/components/oauth-provider-checker.tsx @@ -4,6 +4,7 @@ import { isGoogleAuthDisabled, isMicrosoftAuthDisabled, } from '@/lib/core/config/env-flags' +import { isEmailVerificationEffectivelyEnabled } from '@/lib/messaging/email/verification' export async function getOAuthProviderStatus() { const githubAvailable = @@ -17,3 +18,21 @@ export async function getOAuthProviderStatus() { return { githubAvailable, googleAvailable, microsoftAvailable } } + +/** + * How a signed-in person can verify their email here: with a code, by signing in again through + * a provider that vouches for the address (Google or GitHub, which may link to an existing + * account), or not at all. Microsoft is left out: it links only when Entra asserts the domain. + */ +export type EmailVerificationRoute = + | { kind: 'code' } + | { kind: 'sign_in'; providers: string[] } + | { kind: 'none' } + +/** Resolves on the server which {@link EmailVerificationRoute} this deployment offers. */ +export async function resolveEmailVerificationRoute(): Promise { + if (isEmailVerificationEffectivelyEnabled()) return { kind: 'code' } + const { googleAvailable, githubAvailable } = await getOAuthProviderStatus() + const providers = [...(googleAvailable ? ['Google'] : []), ...(githubAvailable ? ['GitHub'] : [])] + return providers.length > 0 ? { kind: 'sign_in', providers } : { kind: 'none' } +} diff --git a/apps/sim/app/(auth)/verify/use-verification.test.tsx b/apps/sim/app/(auth)/verify/use-verification.test.tsx index 2a78c1e29a1..7efc92c8154 100644 --- a/apps/sim/app/(auth)/verify/use-verification.test.tsx +++ b/apps/sim/app/(auth)/verify/use-verification.test.tsx @@ -2,13 +2,14 @@ import { act } from 'react' import { authClientMock, authClientMockFns } from '@sim/testing/mocks/auth-client.mock' -import { nextNavigationMock } from '@sim/testing/mocks/next-navigation.mock' +import { nextNavigationMock, nextNavigationMockFns } from '@sim/testing/mocks/next-navigation.mock' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('@/lib/auth/client', () => authClientMock) vi.mock('next/navigation', () => nextNavigationMock) +import { VERIFY_FROM_SIGNUP_ROUTE } from '@/app/(auth)/auth-redirect' import { useVerification } from '@/app/(auth)/verify/use-verification' const mocks = { @@ -46,6 +47,8 @@ beforeEach(() => { document.body.appendChild(container) root = createRoot(container) sessionStorage.clear() + vi.clearAllMocks() + nextNavigationMockFns.mockUseSearchParams.mockReturnValue(new URLSearchParams()) authClientMockFns.mockUseSession.mockReturnValue({ data: { user: { email: 'member@example.com', emailVerified: false } }, refetch: vi.fn(), @@ -72,4 +75,66 @@ describe('verification after opening an enrollment in a new tab', () => { type: 'email-verification', }) }) + + it('counts the resend cooldown down from 30 to 0 after a resend', async () => { + const result = renderVerification() + expect(result.current.resendCountdown).toBe(0) + await act(async () => result.current.resendCode()) + expect(result.current.resendCountdown).toBe(30) + for (let second = 0; second < 30; second += 1) { + await act(async () => vi.advanceTimersByTime(1000)) + } + expect(result.current.resendCountdown).toBe(0) + }) +}) + +describe('verification opened for a signed-in account nothing sent a code to', () => { + it('sends one code as the page opens', async () => { + nextNavigationMockFns.mockUseSearchParams.mockReturnValue( + new URLSearchParams({ sendCode: 'true', redirectAfter: '/credential-groups/g/connect' }) + ) + const result = renderVerification() + await act(async () => {}) + expect(mocks.resend).toHaveBeenCalledTimes(1) + expect(mocks.resend).toHaveBeenCalledWith({ + email: 'member@example.com', + type: 'email-verification', + }) + expect(result.current.resendCountdown).toBe(30) + }) + + it('never sends the code to an address left in the tab by an earlier signup', async () => { + sessionStorage.setItem('verificationEmail', 'previous@example.com') + authClientMockFns.mockUseSession.mockReturnValue({ data: null, refetch: vi.fn() }) + nextNavigationMockFns.mockUseSearchParams.mockReturnValue( + new URLSearchParams({ sendCode: 'true' }) + ) + const result = renderVerification() + await act(async () => {}) + expect(mocks.resend).not.toHaveBeenCalled() + expect(result.current.resendCountdown).toBe(0) + }) + + it('sends nothing when the account is already verified', async () => { + authClientMockFns.mockUseSession.mockReturnValue({ + data: { user: { email: 'member@example.com', emailVerified: true } }, + refetch: vi.fn(), + }) + nextNavigationMockFns.mockUseSearchParams.mockReturnValue( + new URLSearchParams({ sendCode: 'true' }) + ) + renderVerification() + await act(async () => {}) + expect(mocks.resend).not.toHaveBeenCalled() + }) + + it('sends nothing on the signup route, which carries no sendCode', async () => { + nextNavigationMockFns.mockUseSearchParams.mockReturnValue( + new URL(VERIFY_FROM_SIGNUP_ROUTE, 'http://localhost').searchParams + ) + const result = renderVerification() + await act(async () => {}) + expect(mocks.resend).not.toHaveBeenCalled() + expect(result.current.resendCountdown).toBe(0) + }) }) diff --git a/apps/sim/app/(auth)/verify/use-verification.ts b/apps/sim/app/(auth)/verify/use-verification.ts index b2382f95c9d..0a08ecf84bf 100644 --- a/apps/sim/app/(auth)/verify/use-verification.ts +++ b/apps/sim/app/(auth)/verify/use-verification.ts @@ -1,6 +1,6 @@ 'use client' -import { useEffect, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { createLogger } from '@sim/logger' import { normalizeEmail } from '@sim/utils/string' import { useSearchParams } from 'next/navigation' @@ -12,6 +12,9 @@ import { DEFAULT_POST_AUTH_ROUTE, POST_AUTH_REDIRECT_STORAGE_KEY } from '@/app/( const logger = createLogger('useVerification') +/** How long after a code is sent before another may be requested. */ +const RESEND_COOLDOWN_SECONDS = 30 + /** * Resolves the post-auth destination at the moment of redirect rather than * caching it in state. @@ -61,6 +64,8 @@ interface UseVerificationReturn { email: string status: VerificationStatus isResending: boolean + /** Seconds until another code may be requested; 0 when it may be now. */ + resendCountdown: number errorMessage: string isOtpComplete: boolean hasEmailService: boolean @@ -82,6 +87,7 @@ export function useVerification({ const [storedEmail, setStoredEmail] = useState('') const [status, setStatus] = useState('idle') const [isResending, setIsResending] = useState(false) + const [resendCountdown, setResendCountdown] = useState(0) const [errorMessage, setErrorMessage] = useState('') useEffect(() => { @@ -178,6 +184,7 @@ export function useVerification({ return setIsResending(true) + setResendCountdown(RESEND_COOLDOWN_SECONDS) setErrorMessage('') const normalizedEmail = normalizeEmail(email) @@ -228,6 +235,27 @@ export function useVerification({ } }, [otp, email, status, isResending]) + /** + * Signup and sign-in arrive with a code already on its way. A page that sends a signed-in, + * unverified person here asks for one with `sendCode`, sent once per visit to the session's + * own address: a signup address left in this tab's storage may belong to someone else. + */ + const sendCodeOnOpen = searchParams.get('sendCode') === 'true' + const sessionEmail = session?.user?.email + const sessionVerified = session?.user?.emailVerified === true + const sentCodeOnOpen = useRef(false) + useEffect(() => { + if (!sendCodeOnOpen || !sessionEmail || sessionVerified || sentCodeOnOpen.current) return + sentCodeOnOpen.current = true + resendCode() + }, [sendCodeOnOpen, sessionEmail, sessionVerified]) + + useEffect(() => { + if (resendCountdown <= 0) return + const timer = setTimeout(() => setResendCountdown((seconds) => seconds - 1), 1000) + return () => clearTimeout(timer) + }, [resendCountdown]) + useEffect(() => { if (isEmailVerificationEnabled) return @@ -257,6 +285,7 @@ export function useVerification({ email, status, isResending, + resendCountdown, errorMessage, isOtpComplete, hasEmailService, diff --git a/apps/sim/app/(auth)/verify/verify-content.tsx b/apps/sim/app/(auth)/verify/verify-content.tsx index 042285c4aa1..ff0d155a08b 100644 --- a/apps/sim/app/(auth)/verify/verify-content.tsx +++ b/apps/sim/app/(auth)/verify/verify-content.tsx @@ -1,6 +1,6 @@ 'use client' -import { Suspense, useEffect, useState } from 'react' +import { Suspense } from 'react' import { AuthCodeEntry } from '@sim/auth-ui' import { POST_AUTH_REDIRECT_STORAGE_KEY } from '@/app/(auth)/auth-redirect' import { AuthHeader, AuthNavPrompt } from '@/app/(auth)/components' @@ -22,24 +22,20 @@ function VerificationForm({ isProduction: boolean isEmailVerificationEnabled: boolean }) { - const { otp, email, status, isResending, errorMessage, verifyCode, resendCode, handleOtpChange } = - useVerification({ hasEmailService, isProduction, isEmailVerificationEnabled }) + const { + otp, + email, + status, + isResending, + resendCountdown, + errorMessage, + verifyCode, + resendCode, + handleOtpChange, + } = useVerification({ hasEmailService, isProduction, isEmailVerificationEnabled }) const isVerified = status === 'verified' - const [countdown, setCountdown] = useState(0) - - useEffect(() => { - if (countdown <= 0) return - const timer = setTimeout(() => setCountdown((c) => c - 1), 1000) - return () => clearTimeout(timer) - }, [countdown]) - - const handleResend = () => { - resendCode() - setCountdown(30) - } - return (
{ void verifyCode() }} - onResend={hasEmailService ? handleResend : undefined} + onResend={hasEmailService ? resendCode : undefined} verifying={status === 'verifying'} resending={isResending} - countdown={countdown} + countdown={resendCountdown} error={errorMessage} help={ hasEmailService diff --git a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts index e73e836b762..dd6ff61a69b 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.test.ts @@ -7,8 +7,7 @@ * 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. + * through a cache or a Referer. */ import { authMockFns } from '@sim/testing/mocks/auth.mock' import { createMockRequest } from '@sim/testing/mocks/request.mock' @@ -22,9 +21,6 @@ const { mockStart, mockUserRateLimit } = vi.hoisted(() => ({ 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, })) @@ -76,7 +72,7 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { 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' + '/credential-groups/public-1/connect?return=slack&error=unavailable' ) expect(mockUserRateLimit).not.toHaveBeenCalled() expect(mockStart).not.toHaveBeenCalled() @@ -109,15 +105,12 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { } ) - 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('sends a start that did not begin back to the connect page to explain it', async () => { + mockStart.mockResolvedValueOnce({ kind: 'not_invited' }) + 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() @@ -128,8 +121,4 @@ describe('POST /api/credential-groups/connect/[publicId]', () => { 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 index a5cf8736412..af7272a7944 100644 --- a/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts +++ b/apps/sim/app/api/credential-groups/connect/[publicId]/route.ts @@ -7,8 +7,10 @@ import { startCredentialGroupConnect } from '@/lib/credential-groups/application import { parseConnectReturnDestination } from '@/lib/credential-groups/connect-return' import { resolveCredentialGroupConnectSession } from '@/lib/credential-groups/connect-session' import { - buildCredentialGroupConnectOAuthStartPath, + buildCredentialGroupConnectErrorPath, buildCredentialGroupConnectPath, + buildCredentialGroupOAuthStartPath, + type CredentialGroupConnectError, } from '@/lib/credential-groups/connect-url' import { checkCredentialGroupConnectUserRateLimit } from '@/lib/credential-groups/rate-limit' import { createNoStoreRedirect } from '@/app/api/credential-groups/enrollment-redirect' @@ -28,26 +30,26 @@ export const POST = withRouteHandler( 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}`, + buildCredentialGroupConnectErrorPath(publicId, 'unavailable', returnTo), 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) - } + const backToConnect = (error?: CredentialGroupConnectError) => + createNoStoreRedirect( + buildCredentialGroupConnectPath({ + publicId, + provider, + optionId, + requestHandle, + returnTo, + error, + }), + 303 + ) if (!isSameOriginSessionRequest(request)) return backToConnect('try_again') const session = await resolveCredentialGroupConnectSession() @@ -68,7 +70,7 @@ export const POST = withRouteHandler( }) if (started.kind !== 'started') return backToConnect() return createNoStoreRedirect( - buildCredentialGroupConnectOAuthStartPath({ ...started, returnTo }), + buildCredentialGroupOAuthStartPath({ ...started, origin: 'connect', returnTo }), 303 ) } diff --git a/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts b/apps/sim/app/api/credential-groups/enroll/[token]/mcp/[mcpServerId]/route.ts index 1971643e383..2b864c186b9 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 @@ -13,6 +13,7 @@ import { } from '@/lib/credential-groups/rate-limit' import { makeTimedStep } from '@/lib/mcp/oauth' import { + type CredentialGroupEnrollmentStartRefusal, createCredentialGroupEnrollmentRedirect, createNoStoreRedirect, } from '@/app/api/credential-groups/enrollment-redirect' @@ -38,7 +39,7 @@ export const GET = withRouteHandler( ...(origin ? { origin } : {}), ...(returnTo ? { return: returnTo } : {}), } - const backToEnrollment = (oauth: string) => + const backToEnrollment = (oauth: CredentialGroupEnrollmentStartRefusal) => createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth }) const principal = await authenticateCredentialGroupEnrollment(token) if (!principal) { 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 72fcfba06b9..dfc29726d20 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 @@ -13,6 +13,7 @@ import { enforcePublicCredentialGroupOAuthStartIpRateLimit, } from '@/lib/credential-groups/rate-limit' import { + type CredentialGroupEnrollmentStartRefusal, createCredentialGroupEnrollmentRedirect, createNoStoreRedirect, } from '@/app/api/credential-groups/enrollment-redirect' @@ -35,7 +36,7 @@ export const GET = withRouteHandler( ...(origin ? { optionId, origin } : {}), ...(returnTo ? { return: returnTo } : {}), } - const backToEnrollment = (oauth: string) => + const backToEnrollment = (oauth: CredentialGroupEnrollmentStartRefusal) => createCredentialGroupEnrollmentRedirect(token, { ...focus, oauth }) const principal = await authenticateCredentialGroupEnrollment(token) if (!principal) { diff --git a/apps/sim/app/api/credential-groups/enrollment-redirect.ts b/apps/sim/app/api/credential-groups/enrollment-redirect.ts index 0e63405075e..a4680b0b69e 100644 --- a/apps/sim/app/api/credential-groups/enrollment-redirect.ts +++ b/apps/sim/app/api/credential-groups/enrollment-redirect.ts @@ -13,6 +13,9 @@ export function createNoStoreRedirect(location: string, status: 303 | 307 = 307) }) } +/** Why an enrollment OAuth or MCP start sent the person back to the enrollment page. */ +export type CredentialGroupEnrollmentStartRefusal = CredentialGroupOAuthFailure | 'other_option' + export function createCredentialGroupEnrollmentRedirect( token: string, params: Record 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 index 84e193250ec..f900064e58b 100644 --- a/apps/sim/app/api/cron/cleanup-credential-group-links/route.ts +++ b/apps/sim/app/api/cron/cleanup-credential-group-links/route.ts @@ -1,5 +1,3 @@ -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' @@ -8,24 +6,21 @@ import { runCleanupCredentialGroupLinks } from '@/background/cleanup-credential- 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. + * past the daily cap's window, and connect-page and self-enrollment links a day past expiry. A + * table whose drain failed fails the run with a 500 once the other table has had its turn. */ 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 }) + const result = await runCleanupCredentialGroupLinks() + if (result.failedTables.length > 0) { return NextResponse.json( - { error: getErrorMessage(error, 'Failed to clean up credential group links') }, + { error: 'Failed to clean up credential group links', ...result }, { status: 500 } ) } + return NextResponse.json({ success: true, ...result }) }) diff --git a/apps/sim/app/api/organizations/[id]/connected-accounts/workspace-access/workspaces/route.ts b/apps/sim/app/api/organizations/[id]/connected-accounts/workspace-access/workspaces/route.ts new file mode 100644 index 00000000000..32ab7a14e80 --- /dev/null +++ b/apps/sim/app/api/organizations/[id]/connected-accounts/workspace-access/workspaces/route.ts @@ -0,0 +1,21 @@ +import { searchOrganizationAccountWorkspacesContract } from '@/lib/api/contracts/organization-accounts' +import { + defineInternalJsonRoute, + internalOrchestrationErrorPolicy, + internalRateLimits, + internalSessionAuth, +} from '@/lib/api/server/routes' +import { + organizationAccountAccessOperations, + searchOrganizationAccountWorkspaces, +} from '@/lib/credential-groups/application/organization-access' + +export const GET = defineInternalJsonRoute({ + contract: searchOrganizationAccountWorkspacesContract, + auth: internalSessionAuth, + operation: organizationAccountAccessOperations.read, + rateLimit: internalRateLimits.user({ bucketName: 'organization-accounts:workspace-search' }), + errorPolicy: internalOrchestrationErrorPolicy, + mapInput: ({ params, query }) => ({ organizationId: params.id, search: query.search }), + useCase: searchOrganizationAccountWorkspaces, +}) diff --git a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx index 0e665137143..5d60a5f40b6 100644 --- a/apps/sim/app/credential-groups/[publicId]/connect/page.tsx +++ b/apps/sim/app/credential-groups/[publicId]/connect/page.tsx @@ -7,13 +7,19 @@ import { parseConnectReturnDestination, } from '@/lib/credential-groups/connect-return' import { resolveCredentialGroupConnectSession } from '@/lib/credential-groups/connect-session' -import { buildCredentialGroupConnectPath } from '@/lib/credential-groups/connect-url' +import { + buildCredentialGroupConnectPath, + buildCredentialGroupConnectStartPath, + parseCredentialGroupConnectError, +} from '@/lib/credential-groups/connect-url' import { getCredentialGroupProviderService } from '@/lib/credential-groups/providers' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' +import { resolveEmailVerificationRoute } from '@/app/(auth)/components/oauth-provider-checker' import { AlreadyConnected, ChooseConnectOption, ConnectConfirm, + ConnectionRevoked, DifferentEmail, NotInvited, RequestExpired, @@ -64,18 +70,27 @@ export default async function CredentialGroupConnectPage({ }: CredentialGroupConnectPageProps) { const { publicId } = await params const query = await searchParams - const provider = getSearchParam(query, 'provider') + const providerParam = 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 startError = parseCredentialGroupConnectError(getSearchParam(query, 'error')) + const provider = + publicId && publicId.length <= 128 && providerParam && providerParam.length <= 128 + ? providerParam + : undefined + const link = { publicId, optionId, requestHandle, returnTo } + const rateLimited = (retryHref: string | undefined) => ( + + ) const limited = await enforcePublicCredentialGroupIpRateLimit( { headers: await headers() }, 'metadata' ) - if (limited) return + if (limited) + return rateLimited(provider && buildCredentialGroupConnectPath({ ...link, provider })) const unavailable = ( ) - if ( - startError === 'unavailable' || - !publicId || - publicId.length > 128 || - !provider || - provider.length > 128 - ) - return unavailable + if (startError === 'unavailable' || !provider) return unavailable const linkPath = (overrides: { optionId?: string } = {}) => - buildCredentialGroupConnectPath({ - publicId, - provider, - optionId, - requestHandle, - returnTo, - ...overrides, - }) + buildCredentialGroupConnectPath({ ...link, provider, ...overrides }) const callbackUrl = linkPath() const tryAgain = ( ) - const verifyEmail = ( + const verifyEmail = async () => ( ) @@ -122,11 +124,18 @@ export default async function CredentialGroupConnectPage({ case 'sign_in': return redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) case 'verify_email': - return verifyEmail + return verifyEmail() + } + switch (startError) { + case 'rate_limited': + return rateLimited(callbackUrl) + case 'try_again': + return tryAgain + case undefined: + break + default: + startError satisfies never } - if (startError === 'rate_limited') - return - if (startError === 'try_again') return tryAgain const outcome = await openCredentialGroupConnect.execute({ principal: session.principal, @@ -140,14 +149,18 @@ export default async function CredentialGroupConnectPage({ 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 ( ) @@ -161,7 +174,7 @@ export default async function CredentialGroupConnectPage({ /> ) case 'verify_email': - return verifyEmail + return verifyEmail() case 'different_email': return ( case 'revoked': - return ( - - ) + return case 'choose_option': return ( -export interface CredentialGroupCompletionView { +interface CredentialGroupCompletionView { failure?: CredentialGroupOAuthFailure /** What the page says about {@link failure}. */ error?: string @@ -29,20 +29,14 @@ 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. - */ +/** An expired attempt a Slack workflow asked for is retried from Slack. */ function failureMessage( failure: CredentialGroupOAuthFailure, - returnTo: ConnectReturnDestination | undefined, - integrationsHref: string | undefined + returnTo: ConnectReturnDestination | undefined ): string { - if (failure !== 'expired' || integrationsHref) - return CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure] - return returnTo === 'slack' + return failure === 'expired' && 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.' + : CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES[failure] } /** @@ -63,7 +57,7 @@ export function resolveCredentialGroupCompletionView( ? organizationRoutes(encodeURIComponent(organizationId)).integrations : undefined return { - ...(failure ? { failure, error: failureMessage(failure, returnTo, integrationsHref) } : {}), + ...(failure ? { failure, error: failureMessage(failure, returnTo) } : {}), ...(completionId && isValidUuid(completionId) ? { completionId } : {}), ...(integrationsHref ? { integrationsHref } : {}), ...(returnTo ? { slackHref: connectReturnHref(returnTo) } : {}), diff --git a/apps/sim/app/credential-groups/enroll/[token]/page.tsx b/apps/sim/app/credential-groups/enroll/[token]/page.tsx index af21660c98f..4318a7af95d 100644 --- a/apps/sim/app/credential-groups/enroll/[token]/page.tsx +++ b/apps/sim/app/credential-groups/enroll/[token]/page.tsx @@ -27,18 +27,21 @@ import { buildCredentialGroupConnectPath } from '@/lib/credential-groups/connect 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 { CREDENTIAL_GROUP_LINK_OAUTH_ORIGINS } from '@/lib/credential-groups/oauth-intent' 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 } from '@/app/(auth)/components' +import { resolveEmailVerificationRoute } from '@/app/(auth)/components/oauth-provider-checker' import { OAuthConnectLink } from '@/app/credential-groups/enroll/[token]/oauth-reconnect-link' import { CredentialGroupOAuthToast } from '@/app/credential-groups/enroll/[token]/oauth-toast' import { + ConnectionRevoked, CredentialGroupLinkActions, CredentialGroupPageShell as PageShell, UnavailableInvitation, + VerifyEmail, WrongAccount, } from '@/app/credential-groups/link-states' import { SourceCompletion } from '@/app/desktop/connect/source-completion' @@ -70,7 +73,7 @@ function needsNewLinkCopy( ): string { const asker = outcome.inviterName ?? - (outcome.organizationName ? `an admin at ${outcome.organizationName}` : 'an admin') + (outcome.organizationName ? `an admin of ${outcome.organizationName}` : 'an admin') return `Ask ${asker} for a new link.` } @@ -96,10 +99,9 @@ function EnrollmentLinkProblem({ ) case 'revoked': return ( - ) @@ -228,15 +230,12 @@ export default async function CredentialGroupEnrollmentPage({ if (!session?.user) { redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`) } - if (!isCredentialGroupEmailVerified(session.user)) + if (!session.user.emailVerified) return ( - ) @@ -259,8 +258,7 @@ export default async function CredentialGroupEnrollmentPage({ if (!principal) return explainLinkProblem() const origin = getSearchParam(resolvedSearchParams, 'origin') const originIsSearch = origin === 'search' - const requestedOrigin = - origin === 'search' || origin === 'accounts' || origin === 'connect' ? origin : undefined + const requestedOrigin = CREDENTIAL_GROUP_LINK_OAUTH_ORIGINS.find((value) => value === origin) const requestedOptionId = resolvedSearchParams.optionId const requestedFocusOptionId = typeof requestedOptionId === 'string' && requestedOptionId.length <= 128 diff --git a/apps/sim/app/credential-groups/link-states.tsx b/apps/sim/app/credential-groups/link-states.tsx index 35c04dd2056..7535db80858 100644 --- a/apps/sim/app/credential-groups/link-states.tsx +++ b/apps/sim/app/credential-groups/link-states.tsx @@ -1,7 +1,9 @@ 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 { buildVerifyEmailPath } from '@/app/(auth)/auth-redirect' import { AuthHeader, AuthShell as LogoShell, SupportFooter } from '@/app/(auth)/components' +import type { EmailVerificationRoute } from '@/app/(auth)/components/oauth-provider-checker' import { SourceCompletion } from '@/app/desktop/connect/source-completion' import { SwitchAccount } from '@/app/desktop/connect/switch-account' @@ -70,7 +72,10 @@ interface UnavailableInvitationProps { /** The enrollment token, when the page was opened from one, so a desktop handoff can finish. */ token?: string title?: string + /** Too many requests: defaults the title and copy, and offers Try again at {@link retryHref} unless {@link recovery} is given. */ rateLimited?: boolean + /** The rate-limited link without its error, when it is well-formed enough to retry. */ + retryHref?: string /** 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. */ @@ -84,10 +89,13 @@ export function UnavailableInvitation({ token, title, rateLimited = false, + retryHref, message, recovery, slackHref, }: UnavailableInvitationProps) { + const action = + rateLimited && retryHref && !recovery ? { href: retryHref, label: 'Try again' } : recovery return ( {token && } @@ -99,18 +107,18 @@ export function UnavailableInvitation({ ? undefined : (message ?? (rateLimited - ? 'This link has been opened too many times. Wait a few minutes and try again.' + ? 'Wait a few minutes, then try again.' : 'Sign in with the account this invitation was sent to. If the link has expired, ask an organization admin for a new invitation.')) } /> - {recovery ? ( - - {recovery.label} + {action ? ( + + {action.label} ) : ( !slackHref && Open Sim @@ -177,7 +185,7 @@ export function DifferentEmail({ viewerEmail, callbackUrl, slackHref }: Differen return ( @@ -220,30 +228,78 @@ export function RequestExpired({ organizationName, slackHref }: RequestExpiredPr return ( ) } -interface VerifyEmailProps { +interface ConnectionRevokedProps { token?: string - verifyHref: string + /** Empty when the organization is unknown. */ + organizationName: string slackHref?: string } -export function VerifyEmail({ token, verifyHref, slackHref }: VerifyEmailProps) { +/** An admin revoked the person; only an admin can ask them again. */ +export function ConnectionRevoked({ token, organizationName, slackHref }: ConnectionRevokedProps) { return ( ) } +interface VerifyEmailProps { + token?: string + /** The page to come back to once the email is verified. */ + callbackUrl: string + verification: EmailVerificationRoute + slackHref?: string +} + +/** + * The signed-in person's email is unverified, so they cannot claim a request made for that + * address. Where no code can be sent, only signing in through a provider that vouches for the + * address can verify it; with none configured, nothing on this deployment can. + */ +export function VerifyEmail({ token, callbackUrl, verification, slackHref }: VerifyEmailProps) { + switch (verification.kind) { + case 'sign_in': + return ( + + ) + case 'none': + return ( + + ) + case 'code': + return ( + + ) + } +} + interface AlreadyConnectedProps { integration: string organizationName: string @@ -274,6 +330,8 @@ export function AlreadyConnected({ interface ConnectConfirmProps { integration: string organizationName: string + /** The person's account stopped working and must be connected again. */ + reconnect?: boolean /** The same-origin POST that starts the connection; the page itself never writes. */ action: string slackHref?: string @@ -286,19 +344,21 @@ interface ConnectConfirmProps { export function ConnectConfirm({ integration, organizationName, + reconnect = false, action, slackHref, }: ConnectConfirmProps) { + const verb = reconnect ? 'Reconnect' : 'Connect' return (
- Connect {integration} + {verb} {integration}
diff --git a/apps/sim/background/cleanup-credential-group-links.ts b/apps/sim/background/cleanup-credential-group-links.ts index b0476f7286b..5dbe593f75a 100644 --- a/apps/sim/background/cleanup-credential-group-links.ts +++ b/apps/sim/background/cleanup-credential-group-links.ts @@ -25,7 +25,7 @@ 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 { +async function drain(table: string, deleteBatch: () => Promise) { let deleted = 0 try { for (let batch = 0; batch < MAX_BATCHES_PER_TABLE; batch += 1) { @@ -33,14 +33,15 @@ async function drain(table: string, deleteBatch: () => Promise): Promise deleted += count if (count < CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) break } + return { table, deleted, failed: false } } catch (error) { logger.error('Credential group retention drain failed', { table, deleted, error: getErrorMessage(error), }) + return { table, deleted, failed: true } } - return deleted } /** @@ -48,64 +49,66 @@ async function drain(table: string, deleteBatch: () => Promise): Promise * 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. + * locked. `failedTables` names each table whose drain failed after the other still ran. */ export async function runCleanupCredentialGroupLinks( now = new Date() -): Promise<{ connectionRequests: number; sessionLinks: number }> { +): Promise<{ connectionRequests: number; sessionLinks: number; failedTables: string[] }> { 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 }) + const drains = [ + 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)) + .returning({ id: request.id }) + return removed.length + }), + 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 }) + .orderBy(asc(link.expiresAt)) + .limit(CREDENTIAL_GROUP_PRUNE_BATCH_SIZE) + .for('update', { of: link, skipLocked: true }) + ) ) - ) - .returning({ id: link.id }) - return removed.length - }) - + .returning({ id: link.id }) + return removed.length + }), + ] as const + const [{ deleted: connectionRequests }, { deleted: sessionLinks }] = drains + const failedTables = drains.filter((result) => result.failed).map((result) => result.table) if (connectionRequests > 0 || sessionLinks > 0) logger.info('Pruned credential group connect history', { connectionRequests, sessionLinks }) - return { connectionRequests, sessionLinks } + return { connectionRequests, sessionLinks, failedTables } } diff --git a/apps/sim/blocks/blocks/credential.ts b/apps/sim/blocks/blocks/credential.ts index 827f7ec8c92..a104c32a210 100644 --- a/apps/sim/blocks/blocks/credential.ts +++ b/apps/sim/blocks/blocks/credential.ts @@ -255,7 +255,7 @@ export const CredentialBlock: BlockConfig = { connectUrl: { type: 'string', description: - 'Link the person opens to sign in and connect this integration. Safe to share; it carries no secret.', + 'Link for this one person to sign in and connect the integration. It carries no secret; anyone with a different email who opens it is told so.', condition: { field: 'operation', value: CONNECTION_OPERATIONS }, }, requested: { diff --git a/apps/sim/ee/credential-groups/components/organization-account-people.tsx b/apps/sim/ee/credential-groups/components/organization-account-people.tsx index 23baaec89e0..0debadbd19b 100644 --- a/apps/sim/ee/credential-groups/components/organization-account-people.tsx +++ b/apps/sim/ee/credential-groups/components/organization-account-people.tsx @@ -49,7 +49,8 @@ type PersonStatus = keyof typeof PERSON_STATUS_BADGES /** * Collapses an enrollment and its connections into the one status an admin - * acts on. A broken connection outranks a working one so it is never hidden. + * acts on. A failed email matters only until the person accepts the request. + * A broken connection outranks a working one so it is never hidden. * Once the person accepted (the enrollment is bound or has progressed), it is * Not connected until an account is. A request nobody accepted is Expired past * its expiry (the same `expired` the connect page refuses on), Invited once Sim @@ -57,7 +58,7 @@ type PersonStatus = keyof typeof PERSON_STATUS_BADGES */ function getPersonStatus(person: CredentialGroupEnrollmentDetail): PersonStatus { if (person.status === 'revoked') return 'revoked' - if (person.status === 'delivery_failed') return 'delivery_failed' + if (person.status === 'delivery_failed' && !person.bound) return 'delivery_failed' const connections = [...person.connections, ...person.mcpConnections] if (connections.some((connection) => connection.status === 'needs_reauth')) { return 'needs_reconnect' @@ -196,7 +197,12 @@ export function OrganizationAccountPeople({ organizationId }: OrganizationAccoun onSelect: () => resend.mutate( { organizationId, enrollmentId: person.id }, - { onSuccess: () => toast.success('Reminder sent') } + { + onSuccess: () => + toast.success( + person.sentAt ? 'Reminder sent' : 'Email sent' + ), + } ), }, ] 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 1ccd93b85d5..95d42ccfeb5 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 @@ -129,7 +129,9 @@ function setAccess(grants = gmailGrants(['workspace-1']), revision = 3) { data: { grants, revision, - workspaces: WORKSPACES, + workspaces: WORKSPACES.filter((workspace) => + grants.some((grant) => grant.workspaceId === workspace.id) + ), credentialTypes: [ { id: 'oauth:gmail', label: 'Gmail' }, { id: 'oauth:google-calendar', label: 'Google Calendar' }, 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 95edd2b9513..542ef758e16 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 @@ -1,7 +1,7 @@ 'use client' import { useState } from 'react' -import { Chip, toast } from '@sim/emcn' +import { Chip, Tooltip, toast } from '@sim/emcn' import { Plus, Workspaces } from '@sim/emcn/icons' import { getErrorMessage } from '@sim/utils/errors' import { useQueryState } from 'nuqs' @@ -93,12 +93,11 @@ function WorkspaceAccessForm({ organizationId, access, searchTerm }: WorkspaceAc } } } - const allowedWorkspaces = access.workspaces.filter((workspace) => grantsById.has(workspace.id)) + const atGrantLimit = access.grants.length >= ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT const normalizedSearch = searchTerm.trim().toLowerCase() - const visibleWorkspaces = allowedWorkspaces.filter((workspace) => + const visibleWorkspaces = access.workspaces.filter((workspace) => workspace.name.toLowerCase().includes(normalizedSearch) ) - const availableWorkspaces = access.workspaces.filter((workspace) => !grantsById.has(workspace.id)) const save = async (grants: WorkspaceAccess['grants'], revision: number) => { try { @@ -111,13 +110,8 @@ function WorkspaceAccessForm({ organizationId, access, searchTerm }: WorkspaceAc } const saveGrant = (grant: Grant) => { if (!editor) throw new Error('Workspace access editor is not open') - if (!byId.has(grant.workspaceId)) throw new Error('Selected workspace is unavailable') if (editor.mode === 'create') { if (grantsById.has(grant.workspaceId)) throw new Error('Workspace already has access') - if (access.grants.length >= ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT) - throw new Error( - `Workspace access cannot exceed ${ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT} workspaces` - ) void save([...access.grants, grant], editor.revision) } else { if (grant.workspaceId !== editor.grant.workspaceId) @@ -131,25 +125,37 @@ function WorkspaceAccessForm({ organizationId, access, searchTerm }: WorkspaceAc } } + const addWorkspaceChip = ( + } + disabled={update.isPending || atGrantLimit} + className={atGrantLimit ? 'pointer-events-none' : undefined} + onClick={() => { + update.reset() + setEditor({ mode: 'create', revision: access.revision }) + }} + > + Add workspace + + ) + return ( <> } - disabled={ - update.isPending || - !availableWorkspaces.length || - access.grants.length >= ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT - } - onClick={() => { - update.reset() - setEditor({ mode: 'create', revision: access.revision }) - }} - > - Add workspace - + atGrantLimit ? ( + + + {addWorkspaceChip} + + + {`Access is limited to ${ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT.toLocaleString('en-US')} workspaces. Remove one to add another.`} + + + ) : ( + addWorkspaceChip + ) } > {update.error && ( @@ -200,7 +206,7 @@ function WorkspaceAccessForm({ organizationId, access, searchTerm }: WorkspaceAc {editor && ( 0 } as const) : ({ mode: 'edit', grant: editor.grant, diff --git a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx index 207f9486064..3625dcf7784 100644 --- a/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx +++ b/apps/sim/ee/credential-groups/components/organization-connection-requests.tsx @@ -123,7 +123,7 @@ export function OrganizationConnectionRequests({ description={ policy ? policy.enabled && !inEffect - ? `${summarize(policy)} · No chosen workspace can use a chosen integration on Access` + ? `${summarize(policy)} · No selected workspace has any of these integrations on Access` : summarize(policy) : undefined } @@ -318,7 +318,7 @@ function ConnectionRequestPolicyModal({ value={dailyLimit} onChange={setDailyLimit} inputMode='numeric' - hint='Counts every workflow request for a new person each day' + hint='Distinct people asked in the last 24 hours' error={ dailyLimit && !limitValid ? `Enter a number from 1 to ${CONNECTION_REQUEST_DAILY_LIMIT_MAX}` diff --git a/apps/sim/ee/credential-groups/components/organization-workspace-grant-modal.test.tsx b/apps/sim/ee/credential-groups/components/organization-workspace-grant-modal.test.tsx index d4fdb37de07..d66e2af994d 100644 --- a/apps/sim/ee/credential-groups/components/organization-workspace-grant-modal.test.tsx +++ b/apps/sim/ee/credential-groups/components/organization-workspace-grant-modal.test.tsx @@ -1,8 +1,15 @@ /** @vitest-environment jsdom */ import { act } from 'react' +import { + organizationAccountsQueriesMock, + organizationAccountsQueriesMockFns, +} from '@sim/testing/mocks/organization-accounts-queries.mock' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { OrganizationAccountWorkspaceAccess } from '@/lib/api/contracts/organization-accounts' + +vi.mock('@/hooks/queries/organization-accounts', () => organizationAccountsQueriesMock) + import { OrganizationWorkspaceGrantModal } from '@/ee/credential-groups/components/organization-workspace-grant-modal' describe('workspace integration grant editor', () => { @@ -21,6 +28,12 @@ describe('workspace integration grant editor', () => { container = document.createElement('div') document.body.appendChild(container) root = createRoot(container) + organizationAccountsQueriesMockFns.mockUseOrganizationAccountWorkspaceSearch.mockReturnValue({ + data: { workspaces: [{ id: 'finance', name: 'Finance' }] }, + error: null, + isPending: false, + isPlaceholderData: false, + }) }) afterEach(async () => { await act(async () => root.unmount()) @@ -40,7 +53,7 @@ describe('workspace integration grant editor', () => { workspaceName: 'Finance', onRemove: remove, } as const) - : ({ mode: 'create', workspaces: [{ id: 'finance', name: 'Finance' }] } as const))} + : ({ mode: 'create', organizationId: 'org-1', hasGrants: true } as const))} credentialTypes={credentialTypes} disabled={disabled} onSave={save} @@ -79,15 +92,16 @@ describe('workspace integration grant editor', () => { await act(async () => button(label).click()) } async function selectWorkspace() { - const trigger = button('Select workspace') - await act(async () => - trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, button: 0 })) - ) - const option = [...document.querySelectorAll('[role="menuitemradio"]')].find( + const trigger = document.querySelector('[role="combobox"][aria-label="Workspace"]') + expect(trigger).not.toBeNull() + await act(async () => trigger?.click()) + const option = [...document.querySelectorAll('[role="option"]')].find( (element) => element.textContent === 'Finance' ) expect(option).toBeDefined() - await act(async () => option?.click()) + await act(async () => + option?.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 })) + ) } it('allows explicitly granting all current and future integrations', async () => { diff --git a/apps/sim/ee/credential-groups/components/organization-workspace-grant-modal.tsx b/apps/sim/ee/credential-groups/components/organization-workspace-grant-modal.tsx index fdc2eb01f69..5da2631e94d 100644 --- a/apps/sim/ee/credential-groups/components/organization-workspace-grant-modal.tsx +++ b/apps/sim/ee/credential-groups/components/organization-workspace-grant-modal.tsx @@ -2,19 +2,26 @@ import { useState } from 'react' import { + ChipCombobox, ChipDropdown, ChipModal, ChipModalBody, ChipModalError, ChipModalField, + type ChipModalFieldAria, ChipModalFooter, ChipModalHeader, - ChipSelect, + type ComboboxOption, } from '@sim/emcn' import type { OrganizationAccountWorkspaceAccess } from '@/lib/api/contracts/organization-accounts' import { isOrganizationCredentialType } from '@/lib/credential-groups/credential-types' +import { ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_MAX_LENGTH } from '@/lib/credential-groups/limits' +import { SEARCH_DEBOUNCE_MS } from '@/lib/url-state' +import { useOrganizationAccountWorkspaceSearch } from '@/hooks/queries/organization-accounts' +import { useSearchFilterValue } from '@/hooks/use-search-filter-value' type Grant = OrganizationAccountWorkspaceAccess['grants'][number] +type Workspace = OrganizationAccountWorkspaceAccess['workspaces'][number] const ALL_INTEGRATIONS = 'all' interface OrganizationWorkspaceGrantModalBaseProps { @@ -28,7 +35,9 @@ interface OrganizationWorkspaceGrantModalBaseProps { interface CreateOrganizationWorkspaceGrantModalProps extends OrganizationWorkspaceGrantModalBaseProps { mode: 'create' - workspaces: OrganizationAccountWorkspaceAccess['workspaces'] + organizationId: string + /** Whether any workspace has access, which tells an empty search what it means. */ + hasGrants: boolean } interface EditOrganizationWorkspaceGrantModalProps @@ -46,20 +55,14 @@ type OrganizationWorkspaceGrantModalProps = /** All integrations is an explicit grant; an empty picker selection never grants access. */ export function OrganizationWorkspaceGrantModal(props: OrganizationWorkspaceGrantModalProps) { const { credentialTypes, disabled, error, onSave, onClose } = props - const [workspaceId, setWorkspaceId] = useState( - props.mode === 'edit' ? props.grant.workspaceId : '' - ) + const [workspace, setWorkspace] = useState(null) + const workspaceId = props.mode === 'edit' ? props.grant.workspaceId : (workspace?.id ?? '') const [access, setAccess] = useState( props.mode === 'edit' ? props.grant.access : { mode: 'selected', credentialTypes: [] } ) const title = props.mode === 'create' ? 'Add workspace' : `Edit ${props.workspaceName} access` const save = () => { if (!workspaceId) throw new Error('Select a workspace before granting access') - if ( - props.mode === 'create' && - !props.workspaces.some((workspace) => workspace.id === workspaceId) - ) - throw new Error('Selected workspace is unavailable') if (access.mode === 'selected' && !access.credentialTypes.length) throw new Error('Select at least one integration') onSave({ workspaceId, access }) @@ -80,22 +83,13 @@ export function OrganizationWorkspaceGrantModal(props: OrganizationWorkspaceGran {props.mode === 'create' && ( {(aria) => ( - ({ - value: workspace.id, - label: workspace.name, - }))} - value={workspaceId} - onChange={setWorkspaceId} - placeholder='Select workspace' - aria-label='Workspace' - searchable - searchPlaceholder='Search workspaces' + )} @@ -167,3 +161,64 @@ export function OrganizationWorkspaceGrantModal(props: OrganizationWorkspaceGran ) } + +interface WorkspaceSearchSelectProps { + organizationId: string + hasGrants: boolean + selected: Workspace | null + onSelect: (workspace: Workspace) => void + disabled: boolean + aria: ChipModalFieldAria +} + +/** Searches the organization's workspaces without access on the server, however many it has. */ +function WorkspaceSearchSelect({ + organizationId, + hasGrants, + selected, + onSelect, + disabled, + aria, +}: WorkspaceSearchSelectProps) { + const [search, setSearch] = useState('') + const [open, setOpen] = useState(false) + const term = useSearchFilterValue(search, SEARCH_DEBOUNCE_MS).trim() + const query = useOrganizationAccountWorkspaceSearch(organizationId, term, { enabled: open }) + const waiting = search.trim() !== term || query.isPlaceholderData + const matches = waiting || query.isRefetchError ? [] : (query.data?.workspaces ?? []) + const options: ComboboxOption[] = matches.map((match) => ({ value: match.id, label: match.name })) + if (selected && !matches.some((match) => match.id === selected.id)) + options.unshift({ value: selected.id, label: selected.name, hidden: true }) + return ( + { + const match = matches.find((candidate) => candidate.id === value) + if (match) onSelect(match) + }} + placeholder='Select workspace' + aria-label='Workspace' + searchable + searchMode='server' + searchMaxLength={ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_MAX_LENGTH} + onSearchChange={setSearch} + onOpenChange={setOpen} + searchPlaceholder='Search workspaces' + isLoading={waiting || query.isPending} + error={query.error?.message} + emptyMessage={ + term + ? 'No workspaces match' + : hasGrants + ? 'Every workspace already has access' + : 'This organization has no workspaces' + } + disabled={disabled} + dropdownWidth='trigger' + align='start' + className='w-full' + /> + ) +} diff --git a/apps/sim/executor/handlers/credential/handler.ts b/apps/sim/executor/handlers/credential/handler.ts index 88f81f518cd..ef82c2782b3 100644 --- a/apps/sim/executor/handlers/credential/handler.ts +++ b/apps/sim/executor/handlers/credential/handler.ts @@ -69,7 +69,6 @@ function parseConnectReturnTo(value: unknown): { returnTo?: ConnectReturnDestina 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" @@ -153,25 +152,17 @@ 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 'request_connection': { + const input = { + workspaceId: ctx.workspaceId, + email: requireConnectionEmail(inputs.email), + providerId: requireString(inputs.organizationProvider, 'Integration'), + ...parseConnectReturnTo(inputs.returnTo), + } + return operation === 'get_connection_status' + ? getOrganizationAccountConnectionStatus.execute({ principal, input }) + : requestOrganizationAccountConnection.execute({ principal, input }) + } 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 be5aa9ced32..46ad059d4e4 100644 --- a/apps/sim/hooks/queries/organization-accounts.ts +++ b/apps/sim/hooks/queries/organization-accounts.ts @@ -4,6 +4,7 @@ import { useEffect, useRef } from 'react' import { generateId } from '@sim/utils/id' import { isServer, + keepPreviousData, queryOptions, useInfiniteQuery, useMutation, @@ -39,6 +40,7 @@ import { resendOrganizationAccountInvitationContract, revokeOrganizationAccountEnrollmentContract, type StartOrganizationAccountConnectionBody, + searchOrganizationAccountWorkspacesContract, startOrganizationAccountConnectionContract, type UpdateOrganizationAccountsBody, type UpdateOrganizationAccountWorkspaceAccessBody, @@ -310,13 +312,10 @@ export function useWorkspaceOrganizationAccounts(workspaceId?: string, enabled = }, }) } -export function useOrganizationAccountWorkspaceAccess( - organizationId: string, - options?: { enabled?: boolean } -) { +export function useOrganizationAccountWorkspaceAccess(organizationId: string) { return useQuery({ queryKey: organizationAccountsKeys.access(organizationId), - enabled: Boolean(organizationId) && (options?.enabled ?? true), + enabled: Boolean(organizationId), staleTime: ORGANIZATION_ACCOUNTS_STALE_TIME, queryFn: ({ signal }) => requestJson(getOrganizationAccountWorkspaceAccessContract, { @@ -325,6 +324,28 @@ export function useOrganizationAccountWorkspaceAccess( }), }) } +/** + * Active workspaces without access whose name matches `search`, for the Add workspace picker. + * Pass `enabled: false` while the picker is closed so it searches only once opened. + */ +export function useOrganizationAccountWorkspaceSearch( + organizationId: string, + search: string, + { enabled }: { enabled: boolean } +) { + return useQuery({ + queryKey: organizationAccountsKeys.accessWorkspaceSearch(organizationId, search), + enabled: Boolean(organizationId) && enabled, + staleTime: ORGANIZATION_ACCOUNTS_STALE_TIME, + placeholderData: keepPreviousData, + queryFn: ({ signal }) => + requestJson(searchOrganizationAccountWorkspacesContract, { + params: { id: organizationId }, + query: { search }, + signal, + }), + }) +} export function useUpdateOrganizationAccountWorkspaceAccess() { const queryClient = useQueryClient() return useMutation({ diff --git a/apps/sim/hooks/queries/utils/organization-accounts-keys.ts b/apps/sim/hooks/queries/utils/organization-accounts-keys.ts index f7077971222..e859b3d87e2 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`: saving Access changes which workspaces can still be added. */ + accessWorkspaceSearch: (id: string, search: string) => + [...organizationAccountsKeys.access(id), 'workspace-search', search] as const, /** Under `access`: its workspace and integration choices come from the Access allowlist. */ connectionRequests: (id?: string) => [...organizationAccountsKeys.access(id), 'connection-requests'] as const, diff --git a/apps/sim/lib/api/contracts/credential-groups.ts b/apps/sim/lib/api/contracts/credential-groups.ts index 8106a6f55c2..438aadea91b 100644 --- a/apps/sim/lib/api/contracts/credential-groups.ts +++ b/apps/sim/lib/api/contracts/credential-groups.ts @@ -13,6 +13,7 @@ import { CREDENTIAL_GROUP_WORKFLOW_NAME_MAX_LENGTH, } from '@/lib/credential-groups/limits' import { MANAGED_MCP_CONNECTOR_IDS } from '@/lib/credential-groups/managed-mcp-connectors' +import { CREDENTIAL_GROUP_LINK_OAUTH_ORIGINS } from '@/lib/credential-groups/oauth-intent' import { CREDENTIAL_GROUP_PROVIDER_IDS, CREDENTIAL_GROUP_STANDARD_OAUTH_PROVIDER_IDS, @@ -586,7 +587,7 @@ const completeCredentialGroupEnrollmentQuerySchema = z.object({ }) export const startCredentialGroupOAuthQuerySchema = z.object({ - origin: z.enum(['search', 'accounts', 'connect']).optional(), + origin: z.enum(CREDENTIAL_GROUP_LINK_OAUTH_ORIGINS).optional(), return: connectReturnQuerySchema, }) export type StartCredentialGroupOAuthQuery = z.output diff --git a/apps/sim/lib/api/contracts/organization-accounts.ts b/apps/sim/lib/api/contracts/organization-accounts.ts index 41ce6289cbf..57046cf59ce 100644 --- a/apps/sim/lib/api/contracts/organization-accounts.ts +++ b/apps/sim/lib/api/contracts/organization-accounts.ts @@ -27,6 +27,8 @@ import { ACCOUNT_SITE_NAME_MAX_LENGTH, ACCOUNT_SITE_URL_MAX_LENGTH, ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT, + ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_LIMIT, + ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_MAX_LENGTH, ORGANIZATION_VIEWER_ACCOUNT_LIMIT, } from '@/lib/credential-groups/limits' import { @@ -177,6 +179,10 @@ export type EnsureOrganizationAccountsBody = z.input< > export type UpdateOrganizationAccountsBody = z.input +const organizationAccountWorkspaceSchema = z.object({ + id: workspaceIdSchema, + name: z.string().max(256), +}) export const organizationAccountWorkspaceAccessSchema = z.object({ revision: z.number().int().positive(), grants: organizationAccountWorkspaceGrantsSchema, @@ -193,12 +199,33 @@ export const getOrganizationAccountWorkspaceAccessContract = defineRouteContract z.object({ id: organizationCredentialTypeSchema, label: z.string().min(1).max(256) }) ) .max(ORGANIZATION_CREDENTIAL_TYPES.length), + /** The granted workspaces that are still active, with their names. */ workspaces: z - .array(z.object({ id: workspaceIdSchema, name: z.string().max(256) })) + .array(organizationAccountWorkspaceSchema) .max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT), }), }, }) +export const searchOrganizationAccountWorkspacesQuerySchema = z + .object({ + search: z.string().trim().max(ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_MAX_LENGTH).default(''), + }) + .strict() +/** Active workspaces without access whose name matches, for adding one on the Access tab. */ +export const searchOrganizationAccountWorkspacesContract = defineRouteContract({ + method: 'GET', + path: '/api/organizations/[id]/connected-accounts/workspace-access/workspaces', + params: organizationAccountsParamsSchema, + query: searchOrganizationAccountWorkspacesQuerySchema, + response: { + mode: 'json', + schema: z.object({ + workspaces: z + .array(organizationAccountWorkspaceSchema) + .max(ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_LIMIT), + }), + }, +}) export const updateOrganizationAccountWorkspaceAccessBodySchema = organizationAccountWorkspaceAccessSchema.strict() @@ -229,7 +256,7 @@ export const getOrganizationConnectionRequestPolicyContract = defineRouteContrac /** 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) })) + .array(organizationAccountWorkspaceSchema) .max(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT), providers: z .array(z.object({ id: z.string().min(1).max(64), label: z.string().max(256) })) diff --git a/apps/sim/lib/credential-groups/README.md b/apps/sim/lib/credential-groups/README.md index d4bc197070d..f2462cd4817 100644 --- a/apps/sim/lib/credential-groups/README.md +++ b/apps/sim/lib/credential-groups/README.md @@ -4,7 +4,7 @@ An organization has at most one account pool. Owners and admins manage it in **O Credential Groups remains available whenever its organization feature is enabled, independently of Search. Search administrators use **Settings → Sources**; members use **Integrations**. The live Sources page has no credential-pool setup or People tabs. These surfaces reuse current grants without changing credential-group API access or stored workspace policies. -**Credential Groups → People → Request connections** sends manual email invitations. Each person shows one status (Invited, 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. +**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 **Revoke** in their actions menu, plus, while they still lack a connection, **Send email** (nothing was emailed yet) or **Send reminder**; a revoked person has **Re-invite**, which is the ordinary invitation. On a workflow's open request, either emails that workflow's request for its integration, as a reminder only once a request email went out, 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 @@ -64,7 +64,7 @@ For a targeted hosted Search rollout, add the organization to `knowledge-member- Workspace-scoped callers resolve their owning organization's entitlement; personal workspaces cannot enable connected accounts. This entitlement is separate from the organization's workspace access allowlist, which still controls which workflows may use the pool. Normal settings no longer prefetch the legacy workspace-owned account container. -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. +Current bounds: 100 entries per discovery page, 1,000 workspace allowlist entries, and 1,000 deployed event subscriptions per organization. Trigger event delivery is synchronous after enrollment commits; a delivery failure surfaces as an error and does not roll back the saved connection, and it is not retried. Connection request emails, by contrast, go through the outbox and are retried. ## Invitation links @@ -84,19 +84,19 @@ Revoking an enrollment sets its status to `revoked` and revokes all of its links ## Connect URL -A workflow's `connectUrl` is `/credential-groups//connect?provider=`, plus `for=` when it was built for one person (a keyed hash of the group and their address) and `return=slack` when the workflow asked to send the person back to Slack. It carries no secret. Opening it only reads (`openCredentialGroupConnect`); its one Connect button is a same-origin POST (`startCredentialGroupConnect`) that, in one transaction, enrolls a member enrolling themselves, binds the person to the enrollment requested at their verified address, and mints a one-hour `connect` link, then goes straight to the provider. A link whose `for` names someone else says so without revealing the address and never offers self-enrollment. A 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. +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 a Reconnect 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. +Claiming an enrollment always needs a verified email. On a deployment that cannot send a verification code (verification off, or no mail provider), the page asks the person to sign in again through Google or GitHub, whichever is configured, since those vouch for the address (`resolveEmailVerificationRoute`); with neither, it says the address can't be confirmed there. -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. +The daily request limit counts distinct addresses per group over a rolling 24 hours; below it, asking again for an address already asked in that window 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 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. +OAuth attempt state is versioned (OAuth v6, managed MCP v5); an OAuth attempt lives thirty minutes and a managed MCP attempt ten. An attempt of any other version is rejected before token exchange, with an instruction to reopen the invitation and connect again; saved credentials are unaffected. 1. Apply `0328_organization_connected_accounts.sql` before deploying code that reads the new columns. It expands ownership columns and checks, adds stable enrollment identity and MCP configuration versions, and builds indexes concurrently. No grants, enrollments, or Search data are moved or deleted. Constraints are added `NOT VALID` to avoid scanning existing tables while holding the DDL lock; validate them separately after auditing existing rows. 2. Inventory existing groups and their Search dependencies before enabling the feature. The queries below read IDs/counts only. Review archived/deleted sources too because a reset must account for retained documents and cleanup work. diff --git a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts index e4898d6590b..86bf8431898 100644 --- a/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/connect-target.integration.ts @@ -347,12 +347,14 @@ describe('the connect URL', () => { organizationName: 'Acme', provider: 'google-drive', optionId: DRIVE.id, + reconnect: false, }) await expect(openTarget(teammate.userId, { publicId: fixture.publicId })).resolves.toEqual({ kind: 'confirm_self_enrollment', organizationName: 'Acme', provider: 'google-drive', optionId: DRIVE.id, + reconnect: false, }) expect(await enrollmentsIn(fixture.groupId)).toEqual([before]) expect(await connectLinksIn(fixture.groupId)).toHaveLength(0) @@ -405,28 +407,23 @@ describe('the connect URL', () => { ) }) - it('asks an unverified person to verify, unless the deployment cannot verify email', async () => { + it('asks an unverified person to verify, even on a deployment that 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) - ) + 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', + }) } finally { emailVerification.enforced = true } - expect((await enrollmentOf(fixture.groupId, person.email)).userId).toBe(person.userId) + expect((await enrollmentOf(fixture.groupId, person.email)).userId).toBeNull() }) it('tells someone holding a link made for another address only that, and never enrolls them', async () => { @@ -511,6 +508,7 @@ describe('the connect URL', () => { organizationName: 'Acme', provider: 'google-drive', optionId: DRIVE.id, + reconnect: false, }) expect(await enrollmentsIn(fixture.groupId)).toEqual([before]) @@ -902,6 +900,7 @@ describe('a focused connect link', () => { organizationName: 'Acme', provider: 'google-drive', optionId: DRIVE.id, + reconnect: true, }) }) diff --git a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts index 2aa4e503539..a5a4fd5cf21 100644 --- a/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/enrollment-link-outcome.integration.ts @@ -27,10 +27,6 @@ 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() diff --git a/apps/sim/lib/credential-groups/__integration__/organization-workspace-access.integration.ts b/apps/sim/lib/credential-groups/__integration__/organization-workspace-access.integration.ts new file mode 100644 index 00000000000..86bcbad0c59 --- /dev/null +++ b/apps/sim/lib/credential-groups/__integration__/organization-workspace-access.integration.ts @@ -0,0 +1,249 @@ +/** + * The Access tab of organization connected accounts against real PostgreSQL, real organization + * authorization, and the real resource policy, for an organization with more workspaces than one + * policy may grant. + * + * Failure modes: the Access read refusing (or loading every workspace) once the organization has + * more workspaces than the grant cap; the read naming workspaces that have no access; the search + * offering a workspace that already has access, an archived one, or another organization's; a + * `%` or `_` in the search matching every name; the search returning an unbounded list; a + * workspace found by search failing to save; a member who is not an admin reading the search; a + * granted workspace later archived or moved to another organization still reading as granted, + * which breaks the tab and blocks every save of the remaining grants. + */ +import { db } from '@sim/db' +import { + credentialGroup, + member, + organization, + resourcePolicy, + user, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it, onTestFinished, vi } from 'vitest' +import { + getOrganizationAccountWorkspaceAccess, + searchOrganizationAccountWorkspaces, + updateOrganizationAccountWorkspaceAccess, +} from '@/lib/credential-groups/application/organization-access' +import { buildOrganizationAccountAccessPolicy } from '@/lib/credential-groups/application/workspace-access-policy' +import { + ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT, + ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_LIMIT, +} from '@/lib/credential-groups/limits' + +vi.mock('@/lib/credential-groups/scoped-availability', () => ({ + isScopedCredentialGroupsAvailable: async () => true, +})) + +const organizationId = generateId() +const otherOrganizationId = generateId() +const groupId = generateId() +const adminId = generateId() +const memberId = generateId() +const domain = `${generateId().slice(0, 12).toLowerCase()}.test` + +/** One more than a policy may grant, so the organization outgrows the grant cap. */ +const bulkWorkspaceIds = Array.from({ length: ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT + 1 }, () => + generateId() +) +const grantedId = bulkWorkspaceIds[0] +const payrollId = generateId() +const archivedPayrollId = generateId() +const otherPayrollId = generateId() +const retiringId = generateId() +const movingId = generateId() + +const admin = () => createSessionPrincipal({ userId: adminId, sessionId: generateId() }) +const search = (term: string, principal = admin()) => + searchOrganizationAccountWorkspaces.execute({ + principal, + input: { organizationId, search: term }, + }) +const read = () => + getOrganizationAccountWorkspaceAccess.execute({ principal: admin(), input: { organizationId } }) + +beforeAll(async () => { + const now = new Date() + await db.insert(organization).values( + [organizationId, otherOrganizationId].map((id) => ({ + id, + name: 'Workspace access fixture', + slug: id, + createdAt: now, + })) + ) + await db.insert(user).values( + [adminId, memberId].map((id) => ({ + id, + name: id === adminId ? 'Admin' : 'Member', + email: `${id}@${domain}`, + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await db.insert(member).values([ + { id: generateId(), organizationId, userId: adminId, role: 'owner', createdAt: now }, + { id: generateId(), organizationId, userId: memberId, role: 'member', createdAt: now }, + ]) + const row = (id: string, name: string, owner: string) => ({ + id, + name, + ownerId: adminId, + billedAccountUserId: adminId, + organizationId: owner, + }) + await insertWorkspaceFixture(db, [ + ...bulkWorkspaceIds.map((id, index) => + row(id, `Team ${String(index).padStart(4, '0')}`, organizationId) + ), + row(payrollId, 'Payroll 100%', organizationId), + { ...row(archivedPayrollId, 'Payroll archive', organizationId), archivedAt: now }, + row(otherPayrollId, 'Payroll elsewhere', otherOrganizationId), + row(retiringId, 'Zeta retiring', organizationId), + row(movingId, 'Zeta moving', organizationId), + ]) + await db.insert(credentialGroup).values({ + id: groupId, + organizationId, + publicId: generateId(), + name: 'Connected accounts', + options: [], + }) + await db.insert(resourcePolicy).values({ + id: generateId(), + organizationId, + resourceType: 'credential_group', + resourceId: groupId, + document: buildOrganizationAccountAccessPolicy(groupId, [ + { workspaceId: grantedId, access: { mode: 'all' } }, + ]), + }) +}, 120_000) + +afterAll(async () => { + const organizations = [organizationId, otherOrganizationId] + await deleteWorkspaceFixture(db, inArray(workspace.organizationId, organizations)) + await db.delete(organization).where(inArray(organization.id, organizations)) + await db.delete(user).where(inArray(user.id, [adminId, memberId])) +}) + +describe('Access tab for an organization with more workspaces than the grant cap', () => { + it('reads the grants with only the granted workspaces named', async () => { + const access = await read() + expect(access.grants).toEqual([{ workspaceId: grantedId, access: { mode: 'all' } }]) + expect(access.workspaces).toEqual([{ id: grantedId, name: 'Team 0000' }]) + }) + + it('finds a workspace without access by name, leaving out granted, archived, and foreign ones', async () => { + const payroll = await search('payroll') + expect(payroll.workspaces).toEqual([{ id: payrollId, name: 'Payroll 100%' }]) + const team = await search('Team 000') + expect(team.workspaces.map((entry) => entry.name)).toEqual( + Array.from({ length: 9 }, (_, index) => `Team 000${index + 1}`) + ) + }) + + it('treats % and _ in the search as literal characters', async () => { + expect((await search('100%')).workspaces).toEqual([{ id: payrollId, name: 'Payroll 100%' }]) + expect((await search('%')).workspaces).toEqual([{ id: payrollId, name: 'Payroll 100%' }]) + expect((await search('_')).workspaces).toEqual([]) + }) + + it('returns at most one page of matches for an empty search', async () => { + const { workspaces } = await search('') + expect(workspaces).toHaveLength(ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_LIMIT) + expect(workspaces.map((entry) => entry.id)).not.toContain(grantedId) + }) + + it('refuses the search to a member who is not an admin', async () => { + await expect( + search('payroll', createSessionPrincipal({ userId: memberId, sessionId: generateId() })) + ).rejects.toMatchObject({ code: 'forbidden' }) + }) + + it('saves a workspace found by search, which then reads as granted and leaves the search', async () => { + const before = await read() + const [found] = (await search('payroll')).workspaces + if (!found) throw new Error('Payroll workspace was not found') + await updateOrganizationAccountWorkspaceAccess.execute({ + principal: admin(), + input: { + organizationId, + revision: before.revision, + grants: [...before.grants, { workspaceId: found.id, access: { mode: 'all' } }], + }, + }) + const after = await read() + expect(after.revision).toBe(before.revision + 1) + expect(after.workspaces).toEqual([ + { id: payrollId, name: 'Payroll 100%' }, + { id: grantedId, name: 'Team 0000' }, + ]) + expect((await search('payroll')).workspaces).toEqual([]) + const [policy] = await db + .select({ revision: resourcePolicy.revision }) + .from(resourcePolicy) + .where(eq(resourcePolicy.resourceId, groupId)) + expect(policy?.revision).toBe(after.revision) + }) + + it('leaves out a granted workspace once it is archived or moved, and saves the remaining grants', async () => { + const before = await read() + const added = [retiringId, movingId].map((workspaceId) => ({ + workspaceId, + access: { mode: 'all' as const }, + })) + await updateOrganizationAccountWorkspaceAccess.execute({ + principal: admin(), + input: { organizationId, revision: before.revision, grants: [...before.grants, ...added] }, + }) + await db.update(workspace).set({ archivedAt: new Date() }).where(eq(workspace.id, retiringId)) + const projectOf = async (workspaceId: string) => { + const [row] = await db + .select({ projectId: workspace.projectId }) + .from(workspace) + .where(eq(workspace.id, workspaceId)) + if (!row) throw new Error('Workspace fixture was not found') + return row.projectId + } + const originalProjectId = await projectOf(movingId) + await db + .update(workspace) + .set({ organizationId: otherOrganizationId, projectId: await projectOf(otherPayrollId) }) + .where(eq(workspace.id, movingId)) + onTestFinished(async () => { + await db + .update(workspace) + .set({ organizationId, projectId: originalProjectId }) + .where(eq(workspace.id, movingId)) + }) + + const stale = await read() + expect(stale.grants).toEqual(before.grants) + expect(stale.workspaces).toEqual(before.workspaces) + + await updateOrganizationAccountWorkspaceAccess.execute({ + principal: admin(), + input: { organizationId, revision: stale.revision, grants: stale.grants }, + }) + const after = await read() + expect(after.revision).toBe(stale.revision + 1) + expect(after.grants).toEqual(before.grants) + await expect( + updateOrganizationAccountWorkspaceAccess.execute({ + principal: admin(), + input: { + organizationId, + revision: after.revision, + grants: [...after.grants, { workspaceId: retiringId, access: { mode: 'all' } }], + }, + }) + ).rejects.toMatchObject({ code: 'validation' }) + }) +}) diff --git a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts index 1138244d611..6c396ca25f7 100644 --- a/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/workflow-connection-requests.integration.ts @@ -300,6 +300,20 @@ const request = ( input: { workspaceId, email, providerId }, }) +/** An organization of its own whose group offers, and whose policy allows, Drive and Calendar. */ +async function createOrgOfferingCalendar() { + 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] }) + return { fixture, calendarId } +} + async function refusal(result: Promise) { const error = await result.then( () => null, @@ -793,6 +807,22 @@ describe('connection request emails', () => { expect((await emailEvents(enrollment.id)).filter((event) => event.reminder)).toHaveLength(3) }) + it('sends the first email of a request created while emails were off as a request, not a reminder', async () => { + await setRequestPolicy(orgA, OPEN_POLICY) + const email = address('emailed-later') + 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([]) + + await setRequestPolicy(orgA, { ...OPEN_POLICY, sendEmail: true }) + await ageRequests(orgA, email) + await request(orgA, email) + expect(await emailEvents(enrollment.id)).toEqual([{ reminder: null }]) + const [after] = await enrollmentsFor(orgA, email) + expect(after?.connectionRequestReminders).toBe(0) + }) + it('sends no reminder once the enrollment was requested more than 30 days ago', async () => { const email = address('long-ago') await request(orgA, email) @@ -869,15 +899,7 @@ describe('connection request emails', () => { }) 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 { fixture, calendarId } = await createOrgOfferingCalendar() const email = address('second-workflow') const secondWorkflowId = generateId() @@ -976,16 +998,22 @@ describe('connection request email delivery', () => { return { email, enrollmentId: enrollment.id } } - async function deliver(enrollmentId: string, reminder?: boolean) { + /** Queues a request email for {@link enrollmentId} in the given fixture's group, then processes it as the outbox would. */ + async function deliver( + enrollmentId: string, + { reminder, fixture = orgA }: { reminder?: boolean; fixture?: OrgFixture } = {} + ) { 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 }), + connectUrl: buildCredentialGroupConnectUrl({ + publicId: fixture.publicId, + provider: DRIVE_ID, + }), ...(reminder ? { reminder } : {}), } ) @@ -1018,7 +1046,7 @@ describe('connection request email delivery', () => { 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) + await deliver(enrollmentId, { reminder: true }) expect(mail.sent).toEqual([ { @@ -1049,20 +1077,23 @@ describe('connection request email delivery', () => { }) }) - it('sends nothing, and records nothing, once a later workflow request has replaced this one', async () => { - const { email, enrollmentId } = await requestedEnrollment('superseded-request') - await request(orgA, email, orgA.workspaceId, DRIVE_ID, workflowId) - const replaced = await enrollmentRow(enrollmentId) - expect(replaced.requestedByWorkflowId).toBe(workflowId) + it('still sends a request’s email, and records it, after another workflow asks for another integration', async () => { + const { fixture, calendarId } = await createOrgOfferingCalendar() + const email = address('later-request') + await request(fixture, email, fixture.workspaceId, DRIVE_ID, namedWorkflowId) + const [enrollment] = await enrollmentsFor(fixture, email) + if (!enrollment) throw new Error('Request created no enrollment') + await request(fixture, email, fixture.workspaceId, calendarId, generateId()) - mail.failWith = 'Mailbox unavailable' - await deliver(enrollmentId) + await deliver(enrollment.id, { fixture }) - expect(mail.sent).toEqual([]) - expect(await enrollmentRow(enrollmentId)).toMatchObject({ - status: replaced.status, - lastDeliveryError: replaced.lastDeliveryError, - sentAt: replaced.sentAt, + expect(mail.sent).toEqual([ + { to: email, subject: 'Connection requests fixture asked you to connect Google Drive' }, + ]) + expect(await enrollmentRow(enrollment.id)).toMatchObject({ + status: 'invited', + lastDeliveryError: null, + sentAt: expect.any(Date), }) }) diff --git a/apps/sim/lib/credential-groups/application/connect-target.ts b/apps/sim/lib/credential-groups/application/connect-target.ts index e96721b6999..53273e9759c 100644 --- a/apps/sim/lib/credential-groups/application/connect-target.ts +++ b/apps/sim/lib/credential-groups/application/connect-target.ts @@ -11,7 +11,7 @@ import { organizationAccountOperations } from '@/lib/credential-groups/applicati import { connectRequestHandleMatches } from '@/lib/credential-groups/connect-request-handle' import { type CredentialGroupConnectLinkTarget, - hasLiveConnectConnection, + findConnectConnectionStatus, issueCredentialGroupConnectLink, loadCredentialGroupConnectSubject, } from '@/lib/credential-groups/connect-subject' @@ -29,7 +29,6 @@ import { 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' @@ -105,10 +104,16 @@ interface AlreadyConnected { provider: CredentialGroupProvider } +/** A connection the page offers to start. */ +interface ConnectConfirmOffer extends ConnectOffer { + /** The person's account for the option stopped working. */ + reconnect: boolean +} + /** What the connect page shows a signed-in person. */ -export type CredentialGroupConnectOutcome = +type CredentialGroupConnectOutcome = | CredentialGroupConnectRefusal - | ConnectOffer + | ConnectConfirmOffer | AlreadyConnected type ConnectDecision = @@ -136,23 +141,25 @@ async function canSelfEnroll( { 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 + error instanceof OrganizationMembershipNotFoundError ) return false throw error } + return hasOrganizationSetup(organizationId, credentialGroupId, tx) } -/** Binding an invited person needs the organization's setup, as the invitation page does. */ -async function hasOrganizationSetup(organizationId: string, credentialGroupId: string) { +/** Whether the organization's Connected accounts setup is complete, read through `tx` when given. */ +async function hasOrganizationSetup( + organizationId: string, + credentialGroupId: string, + tx?: DbTransaction +): Promise { try { - await requireOrganizationAccountsSetup(organizationId, credentialGroupId) + await requireOrganizationAccountsSetup(organizationId, credentialGroupId, tx) return true } catch (error) { if (error instanceof OrganizationAccountsSetupRequiredError) return false @@ -189,7 +196,7 @@ async function decideConnectTarget( ) const [option] = options if (!option) return UNAVAILABLE - if (!isCredentialGroupEmailVerified(viewer)) return { kind: 'verify_email' } + if (!viewer.emailVerified) return { kind: 'verify_email' } const { organizationName } = group if ( @@ -263,16 +270,16 @@ export const openCredentialGroupConnect = defineAuthorizedCredentialUserUseCase( 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 } + const connection = + target.kind === 'enrollment' + ? await findConnectConnectionStatus({ + enrollmentId: target.enrollmentId, + optionId, + userId: principal.userId, + }) + : null + if (connection === 'active') return { kind: 'already_connected', organizationName, provider } + return { kind, organizationName, provider, optionId, reconnect: connection === 'needs_reauth' } }, }) diff --git a/apps/sim/lib/credential-groups/application/connection-requests.ts b/apps/sim/lib/credential-groups/application/connection-requests.ts index e648c7b2202..330b92b1c4d 100644 --- a/apps/sim/lib/credential-groups/application/connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/connection-requests.ts @@ -15,7 +15,7 @@ import { } from '@/lib/credential-groups/application/organization-workspace-access' import { type OrganizationAccountAccessPolicy, - organizationAccountPolicyAllowsWorkspace, + organizationAccountPolicyAllowsProvider, } 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' @@ -32,13 +32,12 @@ import { recordCredentialGroupConnectionRequest, } from '@/lib/credential-groups/connection-requests' import { + activeOptionsForProviderId, findCredentialGroupProviderFromProviderId, - getCredentialGroupProviderId, getCredentialGroupProviderService, - isCredentialGroupProvider, } from '@/lib/credential-groups/providers' -export interface OrganizationAccountConnectionInput { +interface OrganizationAccountConnectionInput { workspaceId: string email: string /** Credential provider ID, as Find Organization Account takes it. */ @@ -47,7 +46,7 @@ export interface OrganizationAccountConnectionInput { returnTo?: ConnectReturnDestination } -export interface OrganizationAccountConnectionStatusResult { +interface OrganizationAccountConnectionStatusResult { status: OrganizationAccountConnectionStatus connected: boolean credentialId: string | null @@ -98,32 +97,19 @@ function requireAllowedProviderOptions( ) { 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 options = activeOptionsForProviderId(context.options, providerId) 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) + if (!organizationAccountPolicyAllowsProvider(policy, context.workspaceId, first.provider)) throw new OrchestrationError( 'forbidden', - `This workspace is not allowed to use the ${integrationLabel(providerId)} integration` + `The Access tab doesn’t give this workspace the ${integrationLabel(providerId)} integration` ) - return { options: allowed, label: first.label } + return { options, label: first.label } } /** The connect URL for one person: its `for` handle tells the page whom it was made for. */ diff --git a/apps/sim/lib/credential-groups/application/enrollment-auth.ts b/apps/sim/lib/credential-groups/application/enrollment-auth.ts index 5375373152f..197110a039d 100644 --- a/apps/sim/lib/credential-groups/application/enrollment-auth.ts +++ b/apps/sim/lib/credential-groups/application/enrollment-auth.ts @@ -1,11 +1,10 @@ import type { CredentialGroupEnrollmentPrincipal } from '@sim/auth/principal' -import { sha256Hex } from '@sim/security/hash' import { getSession } from '@/lib/auth' import { OrchestrationError } from '@/lib/core/orchestration/types' import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' import { authenticatePublicCredentialGroupEnrollment } from '@/lib/credential-groups/enrollments' +import { hashInvitationToken } from '@/lib/credential-groups/links' 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( @@ -13,7 +12,7 @@ export async function authenticateCredentialGroupEnrollment( ): Promise { if (!invitationToken.trim() || invitationToken.length > 128) return null const session = await getSession() - if (!session?.user?.id || !isCredentialGroupEmailVerified(session.user)) return null + if (!session?.user?.id || !session.user.emailVerified) return null const identity = await authenticatePublicCredentialGroupEnrollment(invitationToken) if (!identity) return null if (identity.userId && identity.userId !== session.user.id) return null @@ -45,7 +44,7 @@ export async function credentialGroupOAuthAttemptPrincipal( if ( !attempt.userId || !session?.user || - !isCredentialGroupEmailVerified(session.user) || + !session.user.emailVerified || session.user.id !== attempt.userId ) { throw new OrchestrationError( @@ -60,6 +59,6 @@ export async function credentialGroupOAuthAttemptPrincipal( credentialGroupId: attempt.credentialGroupId, enrollmentId: attempt.enrollmentId, email: attempt.email, - invitationTokenHash: sha256Hex(attempt.invitationToken), + invitationTokenHash: hashInvitationToken(attempt.invitationToken), }) } diff --git a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts index 8e5eceff3b3..cb16b64269d 100644 --- a/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts +++ b/apps/sim/lib/credential-groups/application/enrollment-link-outcome.ts @@ -8,7 +8,6 @@ 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 = { @@ -66,7 +65,7 @@ export const explainCredentialGroupEnrollmentLink = defineAuthorizedCredentialUs findCredentialGroupEnrollmentLinkRecord(input.invitationToken), loadCredentialGroupViewer(principal.userId), ]) - if (!record || !viewer || !isCredentialGroupEmailVerified(viewer)) return { kind: 'unknown' } + if (!record || !viewer || !viewer.emailVerified) return { kind: 'unknown' } const belongsToUser = record.userId ? record.userId === principal.userId 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 2933cf2da48..5ef1d26c3a8 100644 --- a/apps/sim/lib/credential-groups/application/organization-access.test.ts +++ b/apps/sim/lib/credential-groups/application/organization-access.test.ts @@ -34,6 +34,7 @@ import { resourcePolicyRepositoryMock, resourcePolicyRepositoryMockFns, } from '@sim/testing/mocks/resource-policy-repository.mock' +import { urlsMockFns } from '@sim/testing/mocks/urls.mock' import { eq } from 'drizzle-orm' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -210,7 +211,9 @@ describe('organization workspace sharing administration', () => { }) mocks.invite.mockResolvedValue({ invitationLink: 'https://sim.test/credential-groups/enroll/fixture-token', + invitationToken: 'fixture-token', }) + urlsMockFns.mockGetBaseUrl.mockReturnValueOnce('https://sim.test') await expect( startOrganizationAccountConnection.execute({ principal, @@ -234,7 +237,9 @@ describe('organization workspace sharing administration', () => { }) mocks.invite.mockResolvedValue({ invitationLink: 'https://sim.test/credential-groups/enroll/fixture-token', + invitationToken: 'fixture-token', }) + urlsMockFns.mockGetBaseUrl.mockReturnValueOnce('https://sim.test') expect( await startOrganizationAccountConnection.execute({ principal, diff --git a/apps/sim/lib/credential-groups/application/organization-access.ts b/apps/sim/lib/credential-groups/application/organization-access.ts index f05d749ee24..a6f6c2ecc9d 100644 --- a/apps/sim/lib/credential-groups/application/organization-access.ts +++ b/apps/sim/lib/credential-groups/application/organization-access.ts @@ -1,7 +1,8 @@ import { db } from '@sim/db' import { ORGANIZATION_ACCOUNT_POLICY_DOCUMENT_MAX_BYTES } from '@sim/db/credential-group-resource-policies' import { workspace } from '@sim/db/schema' -import { and, asc, eq, inArray, isNull } from 'drizzle-orm' +import { escapeLikePattern } from '@sim/utils/string' +import { and, asc, eq, ilike, inArray, isNull, notInArray } 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' @@ -9,11 +10,12 @@ import { defineOrganizationAccountsUseCase } from '@/lib/credential-groups/appli import { buildOrganizationAccountAccessPolicy, listOrganizationAccountWorkspaceGrants, + listOrganizationAccountWorkspaceIds, organizationAccountAccessPolicyCodec, } from '@/lib/credential-groups/application/workspace-access-policy' import { getOrganizationCredentialTypeCatalog } from '@/lib/credential-groups/credential-types' import { loadScopedAccountsCredentialListContext } from '@/lib/credential-groups/credentials' -import { ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT } from '@/lib/credential-groups/limits' +import { ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_LIMIT } from '@/lib/credential-groups/limits' import { type OrganizationAccountWorkspaceGrant, organizationAccountWorkspaceGrantsSchema, @@ -55,40 +57,90 @@ async function requireGroup(organizationId: string) { return group } +/** The organization's connected-accounts group and its Access policy; not found when either is missing. */ +export async function requireOrganizationAccountAccess(organizationId: string) { + const group = await requireGroup(organizationId) + const policy = await requireResourcePolicy({ + organizationId, + resourceType: 'credential_group', + resourceId: group.credentialGroupId, + codec: organizationAccountAccessPolicyCodec, + }) + return { group, policy } +} + +const activeOrganizationWorkspace = (organizationId: string) => + and(eq(workspace.organizationId, organizationId), isNull(workspace.archivedAt)) + +/** + * The granted workspaces still active in the organization, by name. A grant whose workspace was + * archived or moved away since is left out; the next save drops it from the policy. + */ +export async function listActiveGrantedWorkspaces( + organizationId: string, + grantedIds: string[] +): Promise<{ id: string; name: string }[]> { + if (!grantedIds.length) return [] + return db + .select({ id: workspace.id, name: workspace.name }) + .from(workspace) + .where(and(activeOrganizationWorkspace(organizationId), inArray(workspace.id, grantedIds))) + .orderBy(asc(workspace.name), asc(workspace.id)) +} + +/** + * The Access grants of active workspaces, with their names. Reads only granted workspaces, so it + * is bounded by the grant cap however many workspaces the organization has. + */ export const getOrganizationAccountWorkspaceAccess = defineOrganizationAccountsUseCase({ operation: organizationAccountAccessOperations.read, async execute({ context }) { - const group = await requireGroup(context.organizationId) - const [policy, workspaces] = await Promise.all([ - requireResourcePolicy({ - organizationId: context.organizationId, - resourceType: 'credential_group', - resourceId: group.credentialGroupId, - codec: organizationAccountAccessPolicyCodec, - }), - db - .select({ id: workspace.id, name: workspace.name }) - .from(workspace) - .where( - and(eq(workspace.organizationId, context.organizationId), isNull(workspace.archivedAt)) - ) - .orderBy(asc(workspace.name), asc(workspace.id)) - .limit(ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT + 1), - ]) - if (workspaces.length > ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT) - throw new OrchestrationError( - 'validation', - `Workspace access supports at most ${ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT} workspaces` - ) + const { policy } = await requireOrganizationAccountAccess(context.organizationId) + const workspaces = await listActiveGrantedWorkspaces( + context.organizationId, + listOrganizationAccountWorkspaceIds(policy.document) + ) + const activeIds = new Set(workspaces.map((entry) => entry.id)) return { revision: policy.revision, - grants: listOrganizationAccountWorkspaceGrants(policy.document), + grants: listOrganizationAccountWorkspaceGrants(policy.document).filter((grant) => + activeIds.has(grant.workspaceId) + ), workspaces, credentialTypes: getOrganizationCredentialTypeCatalog(), } }, }) +/** Finds active workspaces of the organization that do not have access yet, by name. */ +export const searchOrganizationAccountWorkspaces = defineOrganizationAccountsUseCase({ + operation: organizationAccountAccessOperations.read, + async execute({ + input, + context, + }: { + input: { organizationId: string; search: string } + context: OrganizationMembershipContext + }) { + const { policy } = await requireOrganizationAccountAccess(context.organizationId) + const grantedIds = listOrganizationAccountWorkspaceIds(policy.document) + const search = input.search.trim() + const workspaces = await db + .select({ id: workspace.id, name: workspace.name }) + .from(workspace) + .where( + and( + activeOrganizationWorkspace(context.organizationId), + grantedIds.length ? notInArray(workspace.id, grantedIds) : undefined, + search ? ilike(workspace.name, `%${escapeLikePattern(search)}%`) : undefined + ) + ) + .orderBy(asc(workspace.name), asc(workspace.id)) + .limit(ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_LIMIT) + return { workspaces } + }, +}) + export const updateOrganizationAccountWorkspaceAccess = defineOrganizationAccountsUseCase({ operation: organizationAccountAccessOperations.update, async execute({ @@ -111,12 +163,11 @@ export const updateOrganizationAccountWorkspaceAccess = defineOrganizationAccoun .from(workspace) .where( and( - eq(workspace.organizationId, context.organizationId), + activeOrganizationWorkspace(context.organizationId), inArray( workspace.id, parsed.data.map((grant) => grant.workspaceId) - ), - isNull(workspace.archivedAt) + ) ) ) if (rows.length !== parsed.data.length) 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 bbe3816f627..f8521c1ac30 100644 --- a/apps/sim/lib/credential-groups/application/organization-account-management.ts +++ b/apps/sim/lib/credential-groups/application/organization-account-management.ts @@ -27,7 +27,7 @@ import { } from '@/lib/credential-groups/managed-mcp-service' import { clearCredentialGroupMcpOAuthAttempts } from '@/lib/credential-groups/mcp-oauth-state' import { - getCredentialGroupProviderId, + activeOptionsForProviderId, isCredentialGroupProvider, } from '@/lib/credential-groups/providers' import { evictMcpServerConnections } from '@/lib/mcp/connection-pool' @@ -213,12 +213,7 @@ export const resendOrganizationAccountInvitation = defineOrganizationAccountsUse credentialGroupId: group.credentialGroupId, enrollmentId: input.enrollmentId, providerNameFor: (providerId) => - group.options.find( - (option) => - option.status === 'active' && - isCredentialGroupProvider(option.provider) && - getCredentialGroupProviderId(option.provider) === providerId - )?.label ?? null, + activeOptionsForProviderId(group.options, providerId)[0]?.label ?? null, connectUrlFor: ({ providerId, email }) => buildCredentialGroupConnectUrl({ publicId: group.publicId, diff --git a/apps/sim/lib/credential-groups/application/organization-accounts.ts b/apps/sim/lib/credential-groups/application/organization-accounts.ts index d32450a2874..b66f0b872aa 100644 --- a/apps/sim/lib/credential-groups/application/organization-accounts.ts +++ b/apps/sim/lib/credential-groups/application/organization-accounts.ts @@ -19,11 +19,11 @@ import { import { runWithOutboundOrganization } from '@/lib/core/network/context.server' import { OrchestrationError } from '@/lib/core/orchestration/types' import { validateUpdateCredentialGroupInput } from '@/lib/credential-groups/application/validation' -import { loadScopedAccountsCredentialListContext } from '@/lib/credential-groups/credentials' import { - createCredentialGroupMcpOAuthStartUrl, - createCredentialGroupOAuthStartUrl, -} from '@/lib/credential-groups/enrollment-links' + buildCredentialGroupMcpOAuthStartUrl, + buildCredentialGroupOAuthStartUrl, +} from '@/lib/credential-groups/connect-url' +import { loadScopedAccountsCredentialListContext } from '@/lib/credential-groups/credentials' import { CredentialGroupEnrollmentError } from '@/lib/credential-groups/enrollments' import { ManagedMcpConnectorError } from '@/lib/credential-groups/managed-mcp-service' import type { CredentialGroupConnectionIntent } from '@/lib/credential-groups/oauth-intent' @@ -305,14 +305,17 @@ export const startOrganizationAccountConnection = defineOrganizationAccountsUseC connectionIntent: input.connectionIntent ?? { kind: 'create' }, }) } - const { invitationLink } = await createViewerCredentialGroupEnrollment({ + const { invitationLink, invitationToken } = await createViewerCredentialGroupEnrollment({ organizationId: context.organizationId, userId: context.userId, credentialGroupId: group.id, }) return { invitationLink, - authorizationUrl: createCredentialGroupMcpOAuthStartUrl(invitationLink, input.mcpServerId), + authorizationUrl: buildCredentialGroupMcpOAuthStartUrl({ + invitationToken, + mcpServerId: input.mcpServerId, + }), } } if ( @@ -331,7 +334,7 @@ export const startOrganizationAccountConnection = defineOrganizationAccountsUseC connectionIntent: input.connectionIntent ?? { kind: 'create' }, }) } - const { invitationLink } = await createViewerCredentialGroupEnrollment({ + const { invitationLink, invitationToken } = await createViewerCredentialGroupEnrollment({ organizationId: context.organizationId, userId: context.userId, credentialGroupId: group.id, @@ -341,8 +344,8 @@ export const startOrganizationAccountConnection = defineOrganizationAccountsUseC url.searchParams.set('origin', 'search') return { invitationLink: url.toString(), - authorizationUrl: createCredentialGroupOAuthStartUrl({ - invitationLink, + authorizationUrl: buildCredentialGroupOAuthStartUrl({ + invitationToken, optionId: input.optionId, 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 index c579787f97c..eeb870741d8 100644 --- a/apps/sim/lib/credential-groups/application/organization-connection-requests.ts +++ b/apps/sim/lib/credential-groups/application/organization-connection-requests.ts @@ -1,26 +1,25 @@ -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 { + listActiveGrantedWorkspaces, + requireOrganizationAccountAccess, +} from '@/lib/credential-groups/application/organization-access' import { defineOrganizationAccountsUseCase } from '@/lib/credential-groups/application/organization-accounts' import { listOrganizationAccountWorkspaceIds, - organizationAccountAccessPolicyCodec, - organizationAccountPolicyAllowsWorkspace, + organizationAccountPolicyAllowsProvider, } 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 { + type CredentialGroupProvider, getCredentialGroupProviderId, isCredentialGroupProvider, } from '@/lib/credential-groups/providers' -import { requireResourcePolicy } from '@/lib/resource-policies/repository' export const organizationConnectionRequestOperations = { read: defineOrganizationOperation({ @@ -44,55 +43,33 @@ export const organizationConnectionRequestOperations = { } 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({ + const { group, policy: access } = await requireOrganizationAccountAccess(organizationId) + const workspaces = await listActiveGrantedWorkspaces( 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 }] - : [] + listOrganizationAccountWorkspaceIds(access.document) ) + const providerById = new Map() + const providers: { id: string; label: string }[] = [] + for (const option of group.options) { + if (option.status !== 'active' || !isCredentialGroupProvider(option.provider)) continue + const id = getCredentialGroupProviderId(option.provider) + providers.push({ id, label: option.label }) + if (!providerById.has(id)) providerById.set(id, option.provider) + } return { group, workspaces, - providers: activeProviders.map(({ id, label }) => ({ id, label })), + providers, workspaceIds: new Set(workspaces.map((entry) => entry.id)), - providerIds: new Set(activeProviders.map((provider) => provider.id)), + providerIds: new Set(providers.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}` - ) - ), + accessAllows: (workspaceId: string, providerId: string) => { + const provider = providerById.get(providerId) + return ( + provider !== undefined && + organizationAccountPolicyAllowsProvider(access.document, workspaceId, provider) + ) + }, } } 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 d5aaecf4919..011cfbcd651 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 @@ -12,6 +12,7 @@ import { credentialGroupsSelfEnrollmentMock, credentialGroupsSelfEnrollmentMockFns, } from '@sim/testing/mocks/credential-groups-self-enrollment.mock' +import { urlsMockFns } from '@sim/testing/mocks/urls.mock' import { eq } from 'drizzle-orm' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -64,6 +65,7 @@ describe('personal organization contributions', () => { mocks.available.mockResolvedValue(true) mocks.invite.mockResolvedValue({ invitationLink: 'https://sim.test/credential-groups/enroll/fixture-token', + invitationToken: 'fixture-token', }) }) @@ -85,6 +87,7 @@ describe('personal organization contributions', () => { queueTableRows(schemaMock.credential, [ { ...row, type: 'managed_oauth', optionId: 'gmail-option' }, ]) + urlsMockFns.mockGetBaseUrl.mockReturnValueOnce('https://sim.test') const result = await reconnectPersonalOrganizationAccount.execute({ principal, input }) const url = new URL(result.invitationLink) expect(url.searchParams.get('optionId')).toBe('gmail-option') 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 b22a73f8405..00e77b14465 100644 --- a/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts +++ b/apps/sim/lib/credential-groups/application/personal-organization-accounts.ts @@ -13,7 +13,7 @@ import { defineOperation } from '@/lib/core/application' import { runWithOutboundOrganization } from '@/lib/core/network/context.server' import { OrchestrationError } from '@/lib/core/orchestration/types' import { sameResourceScopeCondition } from '@/lib/core/resource-scope.server' -import { createCredentialGroupOAuthStartUrl } from '@/lib/credential-groups/enrollment-links' +import { buildCredentialGroupOAuthStartUrl } from '@/lib/credential-groups/connect-url' import { lockCredentialGroupEnrollmentLifecycle } from '@/lib/credential-groups/enrollments' import { revokeCredentialGroupEnrollmentLinks } from '@/lib/credential-groups/links' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' @@ -174,7 +174,7 @@ export const reconnectPersonalOrganizationAccount = defineAuthorizedCredentialUs throw new OrchestrationError('not_found', 'This account provider is no longer available') }) } - const { invitationLink } = await createViewerCredentialGroupEnrollment({ + const { invitationLink, invitationToken } = await createViewerCredentialGroupEnrollment({ organizationId: account.organizationId, credentialGroupId: account.groupId, userId: principal.userId, @@ -188,8 +188,8 @@ export const reconnectPersonalOrganizationAccount = defineAuthorizedCredentialUs invitationLink: url.toString(), ...(account.type === 'managed_oauth' && account.optionId ? { - authorizationUrl: createCredentialGroupOAuthStartUrl({ - invitationLink, + authorizationUrl: buildCredentialGroupOAuthStartUrl({ + invitationToken, optionId: account.optionId, origin: 'accounts', }), diff --git a/apps/sim/lib/credential-groups/application/public-enrollment.ts b/apps/sim/lib/credential-groups/application/public-enrollment.ts index 631b5a0989c..0f7d869c6be 100644 --- a/apps/sim/lib/credential-groups/application/public-enrollment.ts +++ b/apps/sim/lib/credential-groups/application/public-enrollment.ts @@ -1,6 +1,5 @@ import type { CredentialGroupEnrollmentPrincipal, Principal } from '@sim/auth/principal' import { safeCompare } from '@sim/security/compare' -import { sha256Hex } from '@sim/security/hash' import type { OperationUseCase } from '@/lib/core/application' import { withResourceOutboundScope } from '@/lib/core/network/resource-scope.server' import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -25,6 +24,7 @@ import { import { CredentialGroupLinkFocusError, getCredentialGroupEnrollmentLinkOptionId, + hashInvitationToken, } from '@/lib/credential-groups/links' import { completeCredentialGroupMcpOAuth, @@ -35,6 +35,7 @@ import { completeCredentialGroupOAuth, startCredentialGroupOAuth, } from '@/lib/credential-groups/oauth' +import type { CredentialGroupLinkOAuthOrigin } from '@/lib/credential-groups/oauth-intent' import type { CredentialGroupOAuthAttempt } from '@/lib/credential-groups/oauth-state' import { CredentialGroupInvitationUnavailableError } from '@/lib/credential-groups/provider-adapter' import { fireCredentialGroupTrigger } from '@/lib/credential-groups/trigger' @@ -143,7 +144,7 @@ function requireInvitationToken( principal: CredentialGroupEnrollmentPrincipal, invitationToken: string ): void { - if (!safeCompare(sha256Hex(invitationToken), principal.invitationTokenHash)) { + if (!safeCompare(hashInvitationToken(invitationToken), principal.invitationTokenHash)) { throw new OrchestrationError('not_found', 'Invitation is invalid or expired') } } @@ -232,7 +233,7 @@ async function completeEnrollment( interface PublicCredentialGroupOAuthInput { invitationToken: string optionId: string - origin?: 'search' | 'accounts' | 'connect' + origin?: CredentialGroupLinkOAuthOrigin returnTo?: ConnectReturnDestination } diff --git a/apps/sim/lib/credential-groups/application/workspace-access-policy.ts b/apps/sim/lib/credential-groups/application/workspace-access-policy.ts index bc037f9277c..e0b16b7d1c9 100644 --- a/apps/sim/lib/credential-groups/application/workspace-access-policy.ts +++ b/apps/sim/lib/credential-groups/application/workspace-access-policy.ts @@ -4,6 +4,7 @@ import { type OrganizationCredentialType, } from '@/lib/credential-groups/credential-types' import { ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT } from '@/lib/credential-groups/limits' +import type { CredentialGroupProvider } from '@/lib/credential-groups/providers' import { type OrganizationAccountWorkspaceGrant, organizationAccountWorkspaceGrantsSchema, @@ -174,6 +175,15 @@ export function listOrganizationAccountWorkspaceIds( ].sort() } +/** Whether the Access tab lets a workspace use the accounts of one Credential Group provider. */ +export function organizationAccountPolicyAllowsProvider( + document: OrganizationAccountAccessPolicy, + workspaceId: string, + provider: CredentialGroupProvider +): boolean { + return organizationAccountPolicyAllowsWorkspace(document, workspaceId, `oauth:${provider}`) +} + /** Tests the resource policy with the canonical integration, or any registered integration for a catalog entry point. */ export function organizationAccountPolicyAllowsWorkspace( document: OrganizationAccountAccessPolicy, diff --git a/apps/sim/lib/credential-groups/connect-session.ts b/apps/sim/lib/credential-groups/connect-session.ts index 9babb61347f..7071c979dcb 100644 --- a/apps/sim/lib/credential-groups/connect-session.ts +++ b/apps/sim/lib/credential-groups/connect-session.ts @@ -1,12 +1,11 @@ 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 = +type CredentialGroupConnectSession = | { kind: 'sign_in' } | { kind: 'verify_email' } | { kind: 'signed_in'; principal: SessionPrincipal; email: string } @@ -14,7 +13,7 @@ export type CredentialGroupConnectSession = export async function resolveCredentialGroupConnectSession(): Promise { const session = await getSession() if (!session?.user) return { kind: 'sign_in' } - if (!isCredentialGroupEmailVerified(session.user)) return { kind: 'verify_email' } + if (!session.user.emailVerified) return { kind: 'verify_email' } return { kind: 'signed_in', principal: { kind: 'session', userId: session.user.id, sessionId: session.session.id }, diff --git a/apps/sim/lib/credential-groups/connect-subject.ts b/apps/sim/lib/credential-groups/connect-subject.ts index 4fde05703a6..e2560c28e0a 100644 --- a/apps/sim/lib/credential-groups/connect-subject.ts +++ b/apps/sim/lib/credential-groups/connect-subject.ts @@ -12,9 +12,9 @@ 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, + requestExpiresAt, } from '@/lib/credential-groups/enrollment-lifecycle' import { findOrCreateUnissuedEnrollment, @@ -22,7 +22,6 @@ import { 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' /** @@ -106,17 +105,17 @@ export async function loadCredentialGroupConnectSubject(input: { } /** - * Whether the person's own enrollment already holds a live connection for the option: an active - * managed account they connected, on an enrollment bound to them that is still live. An account - * the provider stopped honoring is not live, so the person is offered a reconnect instead. + * The state of the person's own connection for the option, on an enrollment bound to them that + * is still live: `active` when it works, `needs_reauth` when the provider stopped honoring it and + * the person must reconnect, `null` when they have none. */ -export async function hasLiveConnectConnection(input: { +export async function findConnectConnectionStatus(input: { enrollmentId: string optionId: string userId: string -}): Promise { - const [row] = await db - .select({ id: credential.id }) +}): Promise<'active' | 'needs_reauth' | null> { + const rows = await db + .select({ status: credential.managedOauthStatus }) .from(credential) .innerJoin( credentialGroupEnrollment, @@ -130,11 +129,11 @@ export async function hasLiveConnectConnection(input: { eq(credential.credentialGroupOptionId, input.optionId), eq(credential.createdBy, input.userId), eq(credential.type, 'managed_oauth'), - eq(credential.managedOauthStatus, 'active') + inArray(credential.managedOauthStatus, ['active', 'needs_reauth']) ) ) - .limit(1) - return row !== undefined + if (rows.some((row) => row.status === 'active')) return 'active' + return rows.length > 0 ? 'needs_reauth' : null } /** @@ -223,8 +222,7 @@ async function issueConnectLinkInTransaction( .from(user) .where(eq(user.id, input.userId)) .limit(1) - if (!viewer || !isCredentialGroupEmailVerified(viewer)) - throw new ConnectLinkRefusal('unavailable') + if (!viewer || !viewer.emailVerified) throw new ConnectLinkRefusal('unavailable') const viewerEmail = normalizeEmail(viewer.email) const { target } = input @@ -278,7 +276,7 @@ async function issueConnectLinkInTransaction( .update(credentialGroupEnrollment) .set({ userId: input.userId, - ...(renewed ? { invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS) } : {}), + ...(renewed ? { invitationExpiresAt: requestExpiresAt(now) } : {}), updatedAt: now, }) .where(eq(credentialGroupEnrollment.id, enrollmentId)) diff --git a/apps/sim/lib/credential-groups/connect-url.ts b/apps/sim/lib/credential-groups/connect-url.ts index 658c529cf85..cc9b6ee4035 100644 --- a/apps/sim/lib/credential-groups/connect-url.ts +++ b/apps/sim/lib/credential-groups/connect-url.ts @@ -1,7 +1,19 @@ import { getBaseUrl } from '@/lib/core/utils/urls' import type { ConnectReturnDestination } from '@/lib/credential-groups/connect-return' +import type { CredentialGroupLinkOAuthOrigin } from '@/lib/credential-groups/oauth-intent' -interface CredentialGroupConnectPathInput { +/** Why the Connect button's start route sent the person back to the connect page. */ +const CREDENTIAL_GROUP_CONNECT_ERRORS = ['unavailable', 'rate_limited', 'try_again'] as const +export type CredentialGroupConnectError = (typeof CREDENTIAL_GROUP_CONNECT_ERRORS)[number] + +/** Reads the connect page's `error` param; anything else is no error. */ +export function parseCredentialGroupConnectError( + value: string | undefined +): CredentialGroupConnectError | undefined { + return CREDENTIAL_GROUP_CONNECT_ERRORS.find((error) => error === value) +} + +interface CredentialGroupConnectTarget { publicId: string provider: string optionId?: string @@ -10,41 +22,92 @@ interface CredentialGroupConnectPathInput { requestHandle?: string } -/** The connect page's path and query, relative to the app origin. */ -export function buildCredentialGroupConnectPath({ - publicId, +function connectQuery({ provider, optionId, returnTo, requestHandle, -}: CredentialGroupConnectPathInput): string { - const query = new URLSearchParams({ provider }) + error, +}: Partial> & { + error?: CredentialGroupConnectError +}): URLSearchParams { + const query = new URLSearchParams() + if (provider) query.set('provider', provider) if (optionId) query.set('optionId', optionId) if (requestHandle) query.set('for', requestHandle) if (returnTo) query.set('return', returnTo) + if (error) query.set('error', error) + return query +} + +function connectPagePath(publicId: string, query: URLSearchParams): string { return `/credential-groups/${encodeURIComponent(publicId)}/connect?${query}` } +/** The connect page's path and query, relative to the app origin. */ +export function buildCredentialGroupConnectPath({ + publicId, + ...query +}: CredentialGroupConnectTarget & { error?: CredentialGroupConnectError }): string { + return connectPagePath(publicId, connectQuery(query)) +} + +/** The connect page for a request too malformed to name a provider: it only shows the error. */ +export function buildCredentialGroupConnectErrorPath( + publicId: string, + error: CredentialGroupConnectError, + returnTo?: ConnectReturnDestination +): string { + return connectPagePath(publicId, connectQuery({ returnTo, error })) +} + +/** The start route the connect page's Connect button POSTs to, carrying the page's own query. */ +export function buildCredentialGroupConnectStartPath({ + publicId, + ...query +}: CredentialGroupConnectTarget): string { + return `/api/credential-groups/connect/${encodeURIComponent(publicId)}?${connectQuery(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 + 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: { +interface CredentialGroupOAuthStartTarget { invitationToken: string optionId: string + origin: CredentialGroupLinkOAuthOrigin returnTo?: ConnectReturnDestination -}): string { - const query = new URLSearchParams({ origin: 'connect' }) +} + +/** + * The enrollment OAuth start for one option, through an enrollment link's token. A started + * connection goes here with the focused link just minted for it, so the person lands at the + * provider without another click. + */ +export function buildCredentialGroupOAuthStartPath( + target: CredentialGroupOAuthStartTarget +): string { + const query = new URLSearchParams({ origin: target.origin }) if (target.returnTo) query.set('return', target.returnTo) return `/api/credential-groups/enroll/${encodeURIComponent(target.invitationToken)}/oauth/${encodeURIComponent(target.optionId)}?${query}` } + +/** {@link buildCredentialGroupOAuthStartPath} on the app origin, for a page outside the flow. */ +export function buildCredentialGroupOAuthStartUrl(target: CredentialGroupOAuthStartTarget): string { + return `${getBaseUrl()}${buildCredentialGroupOAuthStartPath(target)}` +} + +/** The managed MCP enrollment start for one server, which owns personal OAuth and PKCE. */ +export function buildCredentialGroupMcpOAuthStartUrl(target: { + invitationToken: string + mcpServerId: string +}): string { + return `${getBaseUrl()}/api/credential-groups/enroll/${encodeURIComponent(target.invitationToken)}/mcp/${encodeURIComponent(target.mcpServerId)}` +} diff --git a/apps/sim/lib/credential-groups/connection-request-email.ts b/apps/sim/lib/credential-groups/connection-request-email.ts index 93b79c10448..6d9bee71a23 100644 --- a/apps/sim/lib/credential-groups/connection-request-email.ts +++ b/apps/sim/lib/credential-groups/connection-request-email.ts @@ -17,8 +17,8 @@ import type { OutboxHandler } from '@/lib/core/outbox/service' import { CONNECTION_REQUEST_EMAIL_EVENT, type ConnectionRequestEmailPayload, + pendingWorkflowRequestCondition, } 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' @@ -31,7 +31,6 @@ function parsePayload(payload: unknown): ConnectionRequestEmailPayload { !isRecordLike(payload) || typeof payload.enrollmentId !== 'string' || typeof payload.workflowId !== 'string' || - typeof payload.providerId !== 'string' || typeof payload.providerName !== 'string' || typeof payload.connectUrl !== 'string' ) @@ -39,7 +38,6 @@ function parsePayload(payload: unknown): ConnectionRequestEmailPayload { return { enrollmentId: payload.enrollmentId, workflowId: payload.workflowId, - providerId: payload.providerId, providerName: payload.providerName, connectUrl: payload.connectUrl, reminder: payload.reminder === true, @@ -61,23 +59,18 @@ function connectionRequestWorkflowName(name: string | undefined): string { } /** - * 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). + * The enrollment is still a workflow's open request, and not issued again since it was read (an + * admin's reinvitation moves `invitedAt`). A later workflow's request for the same person keeps the + * request open, so the email still goes out; it names the workflow and integration it was enqueued + * for. */ -function currentRequest(payload: ConnectionRequestEmailPayload): SQL | undefined { +function stillRequested(enrollmentId: string, invitedAt: Date): SQL | undefined { return and( - pendingWorkflowRequestCondition(payload.enrollmentId), - eq(credentialGroupEnrollment.requestedByWorkflowId, payload.workflowId), - eq(credentialGroupEnrollment.requestedProviderId, payload.providerId) + pendingWorkflowRequestCondition(enrollmentId), + eq(credentialGroupEnrollment.invitedAt, invitedAt) ) } -/** {@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 @@ -101,7 +94,7 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { .from(credentialGroupEnrollment) .innerJoin(credentialGroup, eq(credentialGroup.id, credentialGroupEnrollment.credentialGroupId)) .innerJoin(organization, eq(organization.id, credentialGroup.organizationId)) - .where(currentRequest(payload)) + .where(pendingWorkflowRequestCondition(payload.enrollmentId)) .limit(1) if (!target) return const [requester] = await db @@ -142,7 +135,7 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { lastDeliveryError: truncate(result.message, 500), updatedAt: new Date(), }) - .where(stillRequested(payload, target.invitedAt)) + .where(stillRequested(payload.enrollmentId, target.invitedAt)) logger.warn('Connection request email failed', { enrollmentId: payload.enrollmentId }) throw new Error('Connection request email delivery failed') } @@ -156,7 +149,7 @@ const sendConnectionRequestEmail: OutboxHandler = async (rawPayload) => { lastDeliveryError: null, updatedAt: new Date(), }) - .where(stillRequested(payload, target.invitedAt)) + .where(stillRequested(payload.enrollmentId, target.invitedAt)) } catch (error) { logger.error('Failed to record a sent connection request email', { enrollmentId: payload.enrollmentId, diff --git a/apps/sim/lib/credential-groups/connection-request-event.ts b/apps/sim/lib/credential-groups/connection-request-event.ts index 50b211dfc90..d32f193aa7b 100644 --- a/apps/sim/lib/credential-groups/connection-request-event.ts +++ b/apps/sim/lib/credential-groups/connection-request-event.ts @@ -1,3 +1,6 @@ +import { credentialGroupEnrollment } from '@sim/db/schema' +import { and, eq, inArray, isNotNull, isNull, type SQL } from 'drizzle-orm' + /** 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' @@ -8,10 +11,21 @@ export interface ConnectionRequestEmailPayload { * group's organization. */ workflowId: string - /** The requested integration; with `workflowId`, identifies the request the email belongs to. */ - providerId: string providerName: string connectUrl: string /** A repeat request for an enrollment already asked for; its subject reads as a reminder. */ reminder?: boolean } + +/** + * 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) + ) +} diff --git a/apps/sim/lib/credential-groups/connection-request-policy.ts b/apps/sim/lib/credential-groups/connection-request-policy.ts index 27d9916e5bc..0d80dd858dc 100644 --- a/apps/sim/lib/credential-groups/connection-request-policy.ts +++ b/apps/sim/lib/credential-groups/connection-request-policy.ts @@ -126,7 +126,7 @@ export function connectionRequestRefusal( policy.workspaces.mode === 'selected' && !policy.workspaces.workspaceIds.includes(request.workspaceId) ) - return 'This workspace is not allowed to request connections' + return 'Workflow connection requests don’t include this workspace' const domain = request.email.slice(request.email.lastIndexOf('@') + 1) if (!policy.emailDomains.includes(domain)) return `Connection requests are not allowed for ${domain} addresses` diff --git a/apps/sim/lib/credential-groups/connection-requests.ts b/apps/sim/lib/credential-groups/connection-requests.ts index e46d54f3d8d..49bf187066c 100644 --- a/apps/sim/lib/credential-groups/connection-requests.ts +++ b/apps/sim/lib/credential-groups/connection-requests.ts @@ -6,26 +6,17 @@ import { 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 { and, countDistinct, eq, gt, inArray, isNotNull, lt, 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 { credentialGroupConnectionRequestOutboxHandlers } from '@/lib/credential-groups/connection-request-email' import { CONNECTION_REQUEST_EMAIL_EVENT, type ConnectionRequestEmailPayload, + pendingWorkflowRequestCondition, } from '@/lib/credential-groups/connection-request-event' import { type ConnectionRequestPolicy, @@ -35,10 +26,7 @@ import { LIVE_ENROLLMENT_STATUSES, listCredentialGroupCredentialReferences, } from '@/lib/credential-groups/credentials' -import { - INVITATION_TTL_MS, - isEnrollmentRevoked, -} from '@/lib/credential-groups/enrollment-lifecycle' +import { isEnrollmentRevoked, requestExpiresAt } from '@/lib/credential-groups/enrollment-lifecycle' import { findOrCreateUnissuedEnrollment, lockCredentialGroupEnrollmentLifecycle, @@ -54,19 +42,6 @@ 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' @@ -219,7 +194,7 @@ async function renewEnrollmentRequest( await tx .update(credentialGroupEnrollment) .set({ - invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), + invitationExpiresAt: requestExpiresAt(now), ...(enrollment.requestedByWorkflowId !== null ? { requestedByWorkflowId: request.workflowId, requestedProviderId: request.providerId } : {}), @@ -251,12 +226,13 @@ function enqueueConnectionRequestEmail( * * 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 + * unbound one is renewed (its expiry moves out to {@link requestExpiresAt} 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. + * {@link CONNECTION_REQUEST_MAX_REMINDERS} reminders. It reads as a reminder only once a request + * email was sent. * * 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 @@ -321,7 +297,6 @@ export async function recordCredentialGroupConnectionRequest(input: { const email = (reminder: boolean) => ({ enrollmentId: row.id, workflowId: input.workflowId, - providerId: input.providerId, providerName: input.providerName, connectUrl: input.connectUrl, ...(reminder ? { reminder } : {}), @@ -344,7 +319,10 @@ export async function recordCredentialGroupConnectionRequest(input: { const [reminded] = await tx .update(credentialGroupEnrollment) .set({ - connectionRequestReminders: sql`${credentialGroupEnrollment.connectionRequestReminders} + 1`, + connectionRequestReminders: + row.sentAt === null + ? credentialGroupEnrollment.connectionRequestReminders + : sql`${credentialGroupEnrollment.connectionRequestReminders} + 1`, updatedAt: now, }) .where( @@ -364,17 +342,20 @@ export async function recordCredentialGroupConnectionRequest(input: { return { enrollmentId: row.id, created, - emailEventId: reminded ? await enqueueConnectionRequestEmail(tx, email(true)) : null, + emailEventId: reminded + ? await enqueueConnectionRequestEmail(tx, email(row.sentAt !== null)) + : 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. + * An admin's "Send email" or "Send reminder" on a workflow's open request: emails the workflow's + * request for the integration it asked for and renews the wait, keeping the workflow's attribution + * (an admin invitation would take the enrollment over). The email reads as a reminder only once a + * request email was sent. 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 @@ -401,17 +382,16 @@ export async function remindWorkflowConnectionRequest(input: { if (!row || !workflowId || !providerId || !providerName) return null const [renewed] = await tx .update(credentialGroupEnrollment) - .set({ invitationExpiresAt: new Date(now.getTime() + INVITATION_TTL_MS), updatedAt: now }) + .set({ invitationExpiresAt: requestExpiresAt(now), 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, + reminder: row.sentAt !== null, }) return { enrollment: renewed, emailEventId } }) @@ -420,9 +400,6 @@ export async function remindWorkflowConnectionRequest(input: { /** 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 b1bea32b7fb..9ae0a404526 100644 --- a/apps/sim/lib/credential-groups/credentials.ts +++ b/apps/sim/lib/credential-groups/credentials.ts @@ -16,7 +16,6 @@ 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 @@ -140,7 +139,7 @@ export async function loadCredentialGroupEnrollmentAccess( .where( and( eq(user.id, userId), - isEmailVerificationEffectivelyEnabled() ? eq(user.emailVerified, true) : undefined, + eq(user.emailVerified, true), eq(credentialGroupEnrollment.credentialGroupId, credentialGroupId), inArray(credentialGroupEnrollment.status, [...LIVE_ENROLLMENT_STATUSES]) ) diff --git a/apps/sim/lib/credential-groups/enrollment-lifecycle.ts b/apps/sim/lib/credential-groups/enrollment-lifecycle.ts index 17ce0a61125..aad46f1a0c1 100644 --- a/apps/sim/lib/credential-groups/enrollment-lifecycle.ts +++ b/apps/sim/lib/credential-groups/enrollment-lifecycle.ts @@ -15,6 +15,11 @@ type EnrollmentRow = typeof credentialGroupEnrollment.$inferSelect */ export const INVITATION_TTL_MS = 7 * DAY_MS +/** When an unbound request issued or renewed at `now` stops waiting for its person. */ +export function requestExpiresAt(now: Date): Date { + return new Date(now.getTime() + INVITATION_TTL_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 @@ -30,7 +35,7 @@ export function unissuedEnrollmentValues(input: { credentialGroupId: input.credentialGroupId, email: input.email, status: 'invited', - invitationExpiresAt: new Date(input.now.getTime() + INVITATION_TTL_MS), + invitationExpiresAt: requestExpiresAt(input.now), invitedAt: input.now, createdBy: null, createdAt: input.now, diff --git a/apps/sim/lib/credential-groups/enrollment-links.test.ts b/apps/sim/lib/credential-groups/enrollment-links.test.ts deleted file mode 100644 index b462fca1535..00000000000 --- a/apps/sim/lib/credential-groups/enrollment-links.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createCredentialGroupOAuthStartUrl } from '@/lib/credential-groups/enrollment-links' - -describe('credential group OAuth start links', () => { - it('preserves the generated origin and encodes both path identifiers once', () => { - const origin = 'http://localhost:3015' - const token = 'fixture/token ?+%' - const optionId = 'option/with ?+%' - const url = new URL( - createCredentialGroupOAuthStartUrl({ - invitationLink: `${origin}/credential-groups/enroll/${encodeURIComponent(token)}?optionId=old&origin=accounts#old`, - optionId, - origin: 'search', - }) - ) - expect(url.origin).toBe(origin) - expect(url.pathname).toBe( - `/api/credential-groups/enroll/${encodeURIComponent(token)}/oauth/${encodeURIComponent(optionId)}` - ) - expect(url.search).toBe('?origin=search') - expect(url.hash).toBe('') - }) - - it.each(['/enroll/token', '/credential-groups/enroll/', '/credential-groups/enroll/token/extra'])( - 'rejects a noncanonical enrollment path %s', - (path) => { - expect(() => - createCredentialGroupOAuthStartUrl({ - invitationLink: `https://sim.test${path}`, - optionId: 'option-1', - 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 deleted file mode 100644 index 0a1234b34c3..00000000000 --- a/apps/sim/lib/credential-groups/enrollment-links.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** Starts OAuth through the existing enrollment boundary, which owns authentication and PKCE. */ -export function createCredentialGroupOAuthStartUrl(input: { - invitationLink: string - optionId: string - origin: 'search' | 'accounts' -}): string { - const invitation = new URL(input.invitationLink) - const token = invitation.pathname.match(/^\/credential-groups\/enroll\/([^/]+)$/)?.[1] - if (!token) throw new Error('Invalid credential group enrollment link') - const url = new URL( - `/api/credential-groups/enroll/${encodeURIComponent(decodeURIComponent(token))}/oauth/${encodeURIComponent(input.optionId)}`, - invitation.origin - ) - url.searchParams.set('origin', input.origin) - return url.toString() -} - -/** Uses the managed MCP enrollment boundary for personal OAuth and PKCE. */ -export function createCredentialGroupMcpOAuthStartUrl( - invitationLink: string, - mcpServerId: string -): string { - const invitation = new URL(invitationLink) - const token = invitation.pathname.match(/^\/credential-groups\/enroll\/([^/]+)$/)?.[1] - if (!token) throw new Error('Invalid credential group enrollment link') - return new URL( - `/api/credential-groups/enroll/${encodeURIComponent(decodeURIComponent(token))}/mcp/${encodeURIComponent(mcpServerId)}`, - invitation.origin - ).toString() -} diff --git a/apps/sim/lib/credential-groups/enrollments.test.ts b/apps/sim/lib/credential-groups/enrollments.test.ts index 4f93c956d35..c09e9a66d75 100644 --- a/apps/sim/lib/credential-groups/enrollments.test.ts +++ b/apps/sim/lib/credential-groups/enrollments.test.ts @@ -23,9 +23,6 @@ const { adapter } = vi.hoisted(() => ({ }, })) -vi.mock('@/lib/messaging/email/verification', () => ({ - isEmailVerificationEffectivelyEnabled: () => true, -})) vi.mock('@/components/emails/credential-groups/render', () => ({ renderCredentialGroupInvitationEmail: vi.fn(), })) diff --git a/apps/sim/lib/credential-groups/enrollments.ts b/apps/sim/lib/credential-groups/enrollments.ts index 149dde573af..a498687071f 100644 --- a/apps/sim/lib/credential-groups/enrollments.ts +++ b/apps/sim/lib/credential-groups/enrollments.ts @@ -27,9 +27,9 @@ 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, + requestExpiresAt, unissuedEnrollmentValues, } from '@/lib/credential-groups/enrollment-lifecycle' import { @@ -44,9 +44,9 @@ import { requireOrganizationAccountsSetup } from '@/lib/credential-groups/organi import { getCredentialGroupProviderAdapter } from '@/lib/credential-groups/provider-registry' import type { CredentialGroupProvider } from '@/lib/credential-groups/providers' import { + activeOptionsForProviderId, CREDENTIAL_GROUP_PROVIDER_IDS, getCredentialGroupProviderFromProviderId, - getCredentialGroupProviderId, isCredentialGroupProvider, } from '@/lib/credential-groups/providers' import { credentialGroupScope } from '@/lib/credential-groups/scope' @@ -58,7 +58,6 @@ 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' @@ -83,6 +82,8 @@ export interface ListCredentialGroupEnrollmentFilters { export interface CredentialGroupInvitationLink { enrollment: CredentialGroupEnrollmentRecord invitationLink: string + /** The link's token, for the OAuth and MCP start paths that go through it. */ + invitationToken: string } interface InvitationContext { @@ -396,7 +397,7 @@ export async function bindCredentialGroupEnrollmentUser( throw new CredentialGroupEnrollmentError('Invitation is invalid or expired', 404) } if ( - !isCredentialGroupEmailVerified(row) || + !row.emailVerified || (row.enrollment.userId ? row.enrollment.userId !== userId : normalizeEmail(row.email) !== identity.email) @@ -597,7 +598,7 @@ async function issueInvitation( options: SendInvitationOptions ): Promise { const now = new Date() - const expiresAt = new Date(now.getTime() + INVITATION_TTL_MS) + const expiresAt = requestExpiresAt(now) return db.transaction(async (tx) => { const current = await lockInvitationEnrollment(tx, context.groupId, email) @@ -658,7 +659,7 @@ async function issueInvitation( async function issueSelfEnrollmentLink( groupId: string, email: string -): Promise<{ enrollment: EnrollmentRow; invitationLink: string }> { +): Promise<{ enrollment: EnrollmentRow; invitationLink: string; invitationToken: string }> { return db.transaction(async (tx) => { const now = new Date() const { row: enrollment } = await findOrCreateUnissuedEnrollment(tx, { @@ -674,7 +675,7 @@ async function issueSelfEnrollmentLink( purpose: 'self', now, }) - return { enrollment, invitationLink: invitationLinkFor(token) } + return { enrollment, invitationLink: invitationLinkFor(token), invitationToken: token } }) } @@ -1068,6 +1069,7 @@ export async function createCredentialGroupSelfEnrollmentLink( return { enrollment: toCredentialGroupEnrollment(issued.enrollment), invitationLink: issued.invitationLink, + invitationToken: issued.invitationToken, } } @@ -1397,11 +1399,8 @@ export async function isFocusedConnectionComplete( 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 + activeOptionsForProviderId(activeOptions, requestedProviderId).some((option) => + connectedOptionIds.has(option.id) ) ) return true diff --git a/apps/sim/lib/credential-groups/limits.ts b/apps/sim/lib/credential-groups/limits.ts index 35e90ac0b63..c5bf8ec0c91 100644 --- a/apps/sim/lib/credential-groups/limits.ts +++ b/apps/sim/lib/credential-groups/limits.ts @@ -1,7 +1,11 @@ export const DAY_MS = 24 * 60 * 60 * 1000 export const CREDENTIAL_GROUP_MCP_SERVER_LIMIT = 50 export const ORGANIZATION_VIEWER_ACCOUNT_LIMIT = 100 +/** Workspaces one Access policy may grant; bounds the policy document, not the organization. */ export const ORGANIZATION_ACCOUNT_WORKSPACE_LIMIT = 1000 +/** Matches one Access workspace search returns; a longer query narrows it. */ +export const ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_LIMIT = 50 +export const ORGANIZATION_ACCOUNT_WORKSPACE_SEARCH_MAX_LENGTH = 256 export const CREDENTIAL_GROUP_WORKFLOW_ACCESS_LIMIT = 50 export const CREDENTIAL_GROUP_WORKFLOW_CATALOG_LIMIT = 500 export const CREDENTIAL_GROUP_WORKFLOW_NAME_MAX_LENGTH = 255 diff --git a/apps/sim/lib/credential-groups/links.ts b/apps/sim/lib/credential-groups/links.ts index 734bf987182..b70c08e757d 100644 --- a/apps/sim/lib/credential-groups/links.ts +++ b/apps/sim/lib/credential-groups/links.ts @@ -35,8 +35,6 @@ import type { DbTransaction } from '@/lib/db/types' /** 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 { @@ -170,8 +168,6 @@ export function isCredentialGroupLinkFocusError(error: unknown): boolean { interface CredentialGroupEnrollmentLinkRecord { email: string userId: string | null - status: EnrollmentRow['status'] - /** The link's purpose. */ purpose: EnrollmentLinkPurpose /** Past its expiry under {@link unexpiredLinkCondition}. */ expired: boolean @@ -238,7 +234,6 @@ export async function findCredentialGroupEnrollmentLinkRecord( return { email: row.email, userId: row.userId, - status: row.status, purpose: row.linkPurpose, expired: row.expired, revoked: isEnrollmentRevoked(row), diff --git a/apps/sim/lib/credential-groups/mcp-oauth.ts b/apps/sim/lib/credential-groups/mcp-oauth.ts index b8c267c7927..6db8c7fa1a9 100644 --- a/apps/sim/lib/credential-groups/mcp-oauth.ts +++ b/apps/sim/lib/credential-groups/mcp-oauth.ts @@ -2,12 +2,12 @@ import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js' import { db } from '@sim/db' import { credential } from '@sim/db/schema' import { createLogger } from '@sim/logger' -import { sha256Hex } from '@sim/security/hash' import { getErrorMessage } from '@sim/utils/errors' import { and, eq, isNull } from 'drizzle-orm' import { OrchestrationError } from '@/lib/core/orchestration/types' import { resourceScopeFields, resourceScopeFromOwner } from '@/lib/core/resource-scope' import type { CredentialGroupMcpOAuthContext } from '@/lib/credential-groups/enrollments' +import { hashInvitationToken } from '@/lib/credential-groups/links' import { managedMcpAccountIdentityCall } from '@/lib/credential-groups/managed-mcp-connectors' import { type ManagedMcpAccountIdentity, @@ -215,7 +215,7 @@ export async function completeCredentialGroupMcpOAuth( server: context.server, }) const completion = await persistManagedMcpCredential({ - invitationTokenHash: sha256Hex(invitationToken), + invitationTokenHash: hashInvitationToken(invitationToken), oauthConfigVersion: context.server.oauthConfigVersion, configurationFingerprint: preregistered?.configurationFingerprint, enrollmentId: context.enrollmentId, diff --git a/apps/sim/lib/credential-groups/oauth-intent.ts b/apps/sim/lib/credential-groups/oauth-intent.ts index 5871ea6af69..3f986148d5f 100644 --- a/apps/sim/lib/credential-groups/oauth-intent.ts +++ b/apps/sim/lib/credential-groups/oauth-intent.ts @@ -6,3 +6,11 @@ export const credentialGroupConnectionIntentSchema = z.discriminatedUnion('kind' z.object({ kind: z.literal('reconnect'), credentialId: z.string().min(1).max(128) }).strict(), ]) export type CredentialGroupConnectionIntent = z.infer + +/** + * The pages that send a person into enrollment OAuth through a link, as the start route's `origin` + * names them; the callback returns the person to the page they came from. + */ +export const CREDENTIAL_GROUP_LINK_OAUTH_ORIGINS = ['search', 'accounts', 'connect'] as const + +export type CredentialGroupLinkOAuthOrigin = (typeof CREDENTIAL_GROUP_LINK_OAUTH_ORIGINS)[number] diff --git a/apps/sim/lib/credential-groups/oauth-state.ts b/apps/sim/lib/credential-groups/oauth-state.ts index e4d58a5d02f..c7ed34f7608 100644 --- a/apps/sim/lib/credential-groups/oauth-state.ts +++ b/apps/sim/lib/credential-groups/oauth-state.ts @@ -11,6 +11,7 @@ import { import { assertCredentialGroupOAuthAttemptVersion } from '@/lib/credential-groups/oauth-attempt-version' import { type CredentialGroupConnectionIntent, + type CredentialGroupLinkOAuthOrigin, credentialGroupConnectionIntentSchema, } from '@/lib/credential-groups/oauth-intent' import { @@ -20,9 +21,7 @@ import { /** Where a managed-enrollment OAuth attempt lands once the provider sends the person back. */ export type CredentialGroupOAuthOrigin = - | 'search' - | 'accounts' - | 'connect' + | CredentialGroupLinkOAuthOrigin | 'integrations' | 'github-installation' @@ -241,7 +240,7 @@ export function isCredentialGroupOAuthState(state: string): boolean { } /** An attempt the person took too long to finish; only where they came from is kept. */ -export interface ExpiredCredentialGroupOAuthAttempt { +interface ExpiredCredentialGroupOAuthAttempt { expired: true returnTo?: ConnectReturnDestination } diff --git a/apps/sim/lib/credential-groups/oauth.ts b/apps/sim/lib/credential-groups/oauth.ts index 265824221d7..9017fc73fb5 100644 --- a/apps/sim/lib/credential-groups/oauth.ts +++ b/apps/sim/lib/credential-groups/oauth.ts @@ -1,7 +1,6 @@ import { db } from '@sim/db' import { credential, credentialGroup, credentialGroupEnrollment } 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 { and, eq, ne } from 'drizzle-orm' @@ -19,7 +18,7 @@ import { lockCredentialGroupEnrollmentLifecycle, } from '@/lib/credential-groups/enrollments' import { CREDENTIAL_GROUP_ACCOUNTS_PER_PROVIDER_LIMIT } from '@/lib/credential-groups/limits' -import { liveEnrollmentLinkCondition } from '@/lib/credential-groups/links' +import { hashInvitationToken, liveEnrollmentLinkCondition } from '@/lib/credential-groups/links' import type { CredentialGroupConnectionIntent } from '@/lib/credential-groups/oauth-intent' import { type CredentialGroupOAuthAttempt, @@ -404,7 +403,7 @@ export async function completeCredentialGroupOAuth( adapter, policy, grant, - sha256Hex(attempt.invitationToken), + hashInvitationToken(attempt.invitationToken), attempt.connectionIntent ) /** Only Search cards and GitHub setup read a receipt; Integrations refreshes its inventory. */ diff --git a/apps/sim/lib/credential-groups/providers.ts b/apps/sim/lib/credential-groups/providers.ts index 1a8276cbbf7..da1009d8a34 100644 --- a/apps/sim/lib/credential-groups/providers.ts +++ b/apps/sim/lib/credential-groups/providers.ts @@ -307,6 +307,23 @@ export function findCredentialGroupProviderFromProviderId( ) } +/** + * A group's active options that collect accounts for an OAuth provider ID, with the provider + * narrowed. A provider ID belongs to one Credential Group provider, so the options all share it. + */ +export function activeOptionsForProviderId( + options: readonly T[], + providerId: string +): Array { + return options.flatMap((option) => + option.status === 'active' && + isCredentialGroupProvider(option.provider) && + getCredentialGroupProviderId(option.provider) === providerId + ? [{ ...option, provider: option.provider }] + : [] + ) +} + export function getCredentialGroupProviderFromProviderId( providerId: string ): CredentialGroupProvider { diff --git a/apps/sim/lib/credential-groups/self-enrollment-oauth.test.ts b/apps/sim/lib/credential-groups/self-enrollment-oauth.test.ts index bc212728033..c60476006d3 100644 --- a/apps/sim/lib/credential-groups/self-enrollment-oauth.test.ts +++ b/apps/sim/lib/credential-groups/self-enrollment-oauth.test.ts @@ -33,6 +33,7 @@ beforeEach(() => { m.enroll.mockResolvedValue({ enrollment: { id: 'enrollment', email: 'person@example.test' }, invitationLink: 'https://sim.test/credential-groups/enroll/token', + invitationToken: 'token', }) m.context.mockResolvedValue({ credentialOwnerId: 'person' }) m.start.mockResolvedValue('https://provider.test/oauth') diff --git a/apps/sim/lib/credential-groups/self-enrollment-oauth.ts b/apps/sim/lib/credential-groups/self-enrollment-oauth.ts index b6620623fc8..ba7fbccaabd 100644 --- a/apps/sim/lib/credential-groups/self-enrollment-oauth.ts +++ b/apps/sim/lib/credential-groups/self-enrollment-oauth.ts @@ -19,9 +19,8 @@ export async function startViewerCredentialGroupOAuth(input: { origin?: 'integrations' connectionIntent?: CredentialGroupConnectionIntent }): Promise<{ invitationLink: string; authorizationUrl: string }> { - const { enrollment, invitationLink } = await createViewerCredentialGroupEnrollment(input) - const token = new URL(invitationLink).pathname.split('/').at(-1) - if (!token) throw new Error('Account enrollment did not return an invitation token') + const { enrollment, invitationLink, invitationToken } = + await createViewerCredentialGroupEnrollment(input) const oauth = await getCredentialGroupOAuthContextForEnrollment( { organizationId: input.organizationId, @@ -35,7 +34,7 @@ export async function startViewerCredentialGroupOAuth(input: { ) if (!oauth) throw new OrchestrationError('forbidden', 'This account connection is no longer available') - const authorizationUrl = await startCredentialGroupOAuth(oauth, token, { + const authorizationUrl = await startCredentialGroupOAuth(oauth, invitationToken, { completionRedirect: true, origin: input.origin ?? 'search', completionId: input.completionId, @@ -54,9 +53,8 @@ export async function startViewerCredentialGroupMcpOAuth(input: { origin?: 'integrations' connectionIntent?: CredentialGroupConnectionIntent }): Promise<{ invitationLink: string; authorizationUrl: string }> { - const { enrollment, invitationLink } = await createViewerCredentialGroupEnrollment(input) - const token = new URL(invitationLink).pathname.split('/').at(-1) - if (!token) throw new Error('Account enrollment did not return an invitation token') + const { enrollment, invitationLink, invitationToken } = + await createViewerCredentialGroupEnrollment(input) const oauth = await getCredentialGroupMcpOAuthContextForEnrollment( { organizationId: input.organizationId, @@ -69,7 +67,7 @@ export async function startViewerCredentialGroupMcpOAuth(input: { ) if (!oauth) throw new OrchestrationError('forbidden', 'This account connection is no longer available') - const authorizationUrl = await startCredentialGroupMcpOAuth(oauth, token, { + const authorizationUrl = await startCredentialGroupMcpOAuth(oauth, invitationToken, { completionId: input.completionId, origin: input.origin, connectionIntent: input.connectionIntent, diff --git a/apps/sim/lib/credential-groups/self-enrollment.test.ts b/apps/sim/lib/credential-groups/self-enrollment.test.ts index a68424e339d..373b7e541d7 100644 --- a/apps/sim/lib/credential-groups/self-enrollment.test.ts +++ b/apps/sim/lib/credential-groups/self-enrollment.test.ts @@ -5,9 +5,6 @@ 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' @@ -35,6 +32,7 @@ describe('viewer account enrollment', () => { issue.mockResolvedValue({ enrollment: { id: 'enrollment' }, invitationLink: 'https://sim.test/enroll/token', + invitationToken: 'token', }) await createViewerCredentialGroupEnrollment(input) expect(issue).toHaveBeenCalledWith( diff --git a/apps/sim/lib/credential-groups/self-enrollment.ts b/apps/sim/lib/credential-groups/self-enrollment.ts index 691fca2870c..9191440dc23 100644 --- a/apps/sim/lib/credential-groups/self-enrollment.ts +++ b/apps/sim/lib/credential-groups/self-enrollment.ts @@ -10,7 +10,6 @@ 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: { @@ -25,7 +24,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 (!isCredentialGroupEmailVerified(viewer)) { + if (!viewer.emailVerified) { throw new OrchestrationError( 'validation', 'Verify your email address before connecting an account' @@ -53,9 +52,7 @@ export async function createViewerCredentialGroupEnrollment(input: { input.credentialGroupId, email ) - const token = new URL(result.invitationLink).pathname.split('/').at(-1) - if (!token) throw new Error('Enrollment link is missing its token') - const identity = await authenticatePublicCredentialGroupEnrollment(token) + const identity = await authenticatePublicCredentialGroupEnrollment(result.invitationToken) if (!identity) throw new Error('Enrollment is no longer available') await bindCredentialGroupEnrollmentUser(identity, input.userId) return result diff --git a/apps/sim/lib/credential-groups/verified-email.ts b/apps/sim/lib/credential-groups/verified-email.ts deleted file mode 100644 index eaa91c594bf..00000000000 --- a/apps/sim/lib/credential-groups/verified-email.ts +++ /dev/null @@ -1,11 +0,0 @@ -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/application/personal-connection.test.ts b/apps/sim/lib/credentials/application/personal-connection.test.ts index 01c639d6552..87853a6b5fd 100644 --- a/apps/sim/lib/credentials/application/personal-connection.test.ts +++ b/apps/sim/lib/credentials/application/personal-connection.test.ts @@ -117,6 +117,7 @@ describe('personal connection launch', () => { mocks.startOAuth.mockResolvedValue('https://accounts.example.com/authorize?state=one-use') mocks.enroll.mockResolvedValue({ invitationLink: 'https://sim.test/credential-groups/enroll/opaque-token', + invitationToken: 'opaque-token', enrollment: { id: 'enrollment', email: 'viewer@example.com' }, }) }) diff --git a/apps/sim/lib/credentials/application/personal-connection.ts b/apps/sim/lib/credentials/application/personal-connection.ts index c824ad03f57..79d52b90cb7 100644 --- a/apps/sim/lib/credentials/application/personal-connection.ts +++ b/apps/sim/lib/credentials/application/personal-connection.ts @@ -61,13 +61,11 @@ export const startPersonalCredentialConnection = defineAuthorizedWorkspaceUseCas `Ask an organization admin to enable ${service.name} in organization settings` ) } - const { enrollment, invitationLink } = await createViewerCredentialGroupEnrollment({ + const { enrollment, invitationToken } = await createViewerCredentialGroupEnrollment({ organizationId: group.organizationId, credentialGroupId: group.credentialGroupId, userId, }) - const token = new URL(invitationLink).pathname.split('/').at(-1) - if (!token) throw new Error('Account enrollment did not return an invitation token') const oauth = await getCredentialGroupOAuthContextForEnrollment( { organizationId: group.organizationId, @@ -80,7 +78,7 @@ export const startPersonalCredentialConnection = defineAuthorizedWorkspaceUseCas if (!oauth) throw new OrchestrationError('forbidden', 'This account connection is no longer available') return { - url: await startCredentialGroupOAuth(oauth, token, { completionRedirect: true }), + url: await startCredentialGroupOAuth(oauth, invitationToken, { completionRedirect: true }), providerId: input.providerId, } }, diff --git a/apps/sim/lib/knowledge/application/github-setup.test.ts b/apps/sim/lib/knowledge/application/github-setup.test.ts index a0d4494c4ac..53d73bb972f 100644 --- a/apps/sim/lib/knowledge/application/github-setup.test.ts +++ b/apps/sim/lib/knowledge/application/github-setup.test.ts @@ -210,6 +210,7 @@ beforeEach(() => { m.enrollment.mockResolvedValue({ enrollment: { id: 'enrollment', email: 'admin@example.test' }, invitationLink: 'https://sim.example/credential-groups/enroll/fixture-invitation', + invitationToken: 'fixture-invitation', }) m.oauthContext.mockResolvedValue({ fixture: 'oauth-context' }) m.oauthStart.mockResolvedValue('https://github.com/login/oauth/authorize?state=cg_fixture') diff --git a/apps/sim/lib/knowledge/application/github-setup.ts b/apps/sim/lib/knowledge/application/github-setup.ts index 60df3ead8cf..443bfaf2970 100644 --- a/apps/sim/lib/knowledge/application/github-setup.ts +++ b/apps/sim/lib/knowledge/application/github-setup.ts @@ -7,6 +7,7 @@ import { and, eq, isNull } from 'drizzle-orm' import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' import { completePublicCredentialGroupOAuth } from '@/lib/credential-groups/application/public-enrollment' import { getCredentialGroupOAuthContextForEnrollment } from '@/lib/credential-groups/enrollments' +import { hashInvitationToken } from '@/lib/credential-groups/links' import { startCredentialGroupOAuth } from '@/lib/credential-groups/oauth' import { CREDENTIAL_GROUP_OAUTH_FAILURE_MESSAGES, @@ -225,13 +226,11 @@ async function authorizeReader(attempt: GitHubSetupAttempt) { userId: attempt.userId, connectorMeta: CONNECTOR_META_REGISTRY.github!, }) - const { enrollment, invitationLink } = await createViewerCredentialGroupEnrollment({ + const { enrollment, invitationToken } = await createViewerCredentialGroupEnrollment({ organizationId: attempt.organizationId, userId: attempt.userId, credentialGroupId: binding.credentialGroupId, }) - const token = new URL(invitationLink).pathname.split('/').at(-1) - if (!token) throw new Error('Account enrollment did not return an invitation token') const context = await getCredentialGroupOAuthContextForEnrollment( { organizationId: attempt.organizationId, @@ -264,7 +263,7 @@ async function authorizeReader(attempt: GitHubSetupAttempt) { 'Reconnect one of your GitHub accounts in Integrations, then try setup again.' ) const [existing] = connected - const url = await startCredentialGroupOAuth(context, token, { + const url = await startCredentialGroupOAuth(context, invitationToken, { completionRedirect: true, completionId: attempt.setupId, origin: 'github-installation', @@ -531,7 +530,7 @@ export const completeGitHubSetupReaderOAuth = defineAuthorizedKnowledgeUseCase({ credentialGroupId: input.attempt.credentialGroupId, enrollmentId: input.attempt.enrollmentId, email: input.attempt.email, - invitationTokenHash: sha256Hex(input.attempt.invitationToken), + invitationTokenHash: hashInvitationToken(input.attempt.invitationToken), }, input, request, diff --git a/apps/sim/lib/mothership/tools/server/settings-connected-accounts.ts b/apps/sim/lib/mothership/tools/server/settings-connected-accounts.ts index 30bf4b31c4e..61bc712d4b5 100644 --- a/apps/sim/lib/mothership/tools/server/settings-connected-accounts.ts +++ b/apps/sim/lib/mothership/tools/server/settings-connected-accounts.ts @@ -8,11 +8,13 @@ import { ensureOrganizationAccountsBodySchema, inviteOrganizationAccountPeopleBodySchema, listOrganizationAccountPeopleQuerySchema, + searchOrganizationAccountWorkspacesQuerySchema, startOrganizationAccountConnectionBodySchema, updateOrganizationAccountWorkspaceAccessBodySchema, } from '@/lib/api/contracts/organization-accounts' import { getOrganizationAccountWorkspaceAccess, + searchOrganizationAccountWorkspaces, updateOrganizationAccountWorkspaceAccess, } from '@/lib/credential-groups/application/organization-access' import { @@ -139,6 +141,15 @@ export const connectedAccountSettingsActions = { input: { organizationId: settingsOrganizationId(context) }, }) ), + search_workspaces: settingsOperation( + 'read', + searchOrganizationAccountWorkspacesQuerySchema, + (context, input) => + searchOrganizationAccountWorkspaces.execute({ + principal: context.principal, + input: { ...input, organizationId: settingsOrganizationId(context) }, + }) + ), set_workspace_access: settingsOperation( 'write', updateOrganizationAccountWorkspaceAccessBodySchema, diff --git a/packages/testing/src/mocks/credential-groups-self-enrollment.mock.ts b/packages/testing/src/mocks/credential-groups-self-enrollment.mock.ts index ed53fa49daa..69d65bd85ae 100644 --- a/packages/testing/src/mocks/credential-groups-self-enrollment.mock.ts +++ b/packages/testing/src/mocks/credential-groups-self-enrollment.mock.ts @@ -8,7 +8,8 @@ import { vi } from 'vitest' * import { credentialGroupsSelfEnrollmentMockFns } from '@sim/testing/mocks/credential-groups-self-enrollment.mock' * * credentialGroupsSelfEnrollmentMockFns.mockCreateViewerCredentialGroupEnrollment.mockResolvedValue({ - * invitationLink: 'https://example.test/enroll', enrollment: { id: 'enrollment-1', email: 'a@b.test' }, + * invitationLink: 'https://example.test/enroll/token-1', invitationToken: 'token-1', + * enrollment: { id: 'enrollment-1', email: 'a@b.test' }, * }) * ``` */ diff --git a/packages/testing/src/mocks/organization-accounts-queries.mock.ts b/packages/testing/src/mocks/organization-accounts-queries.mock.ts index 313ae1c30ad..853e8346937 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`, + * `useOrganizationAccountWorkspaceSearch`, * `usePersonalOrganizationAccounts`, `useOrganizationConnectionRequestPolicy`, * `useOrganizationAccountPeople`) return a fresh {@link createQueryResultMock} (not-yet-fetched: * `data: undefined`, `isPending: true`). Every mutation hook returns a fresh @@ -35,6 +36,7 @@ export const organizationAccountsQueriesMockFns = { mockUseConnectOrganizationAccount: mutationHook(), mockUseWorkspaceOrganizationAccounts: queryHook(), mockUseOrganizationAccountWorkspaceAccess: queryHook(), + mockUseOrganizationAccountWorkspaceSearch: queryHook(), mockUseUpdateOrganizationAccountWorkspaceAccess: mutationHook(), mockUseOrganizationConnectionRequestPolicy: queryHook(), mockUseUpdateOrganizationConnectionRequestPolicy: mutationHook(), @@ -77,6 +79,8 @@ export const organizationAccountsQueriesMock = { organizationAccountsQueriesMockFns.mockUseWorkspaceOrganizationAccounts, useOrganizationAccountWorkspaceAccess: organizationAccountsQueriesMockFns.mockUseOrganizationAccountWorkspaceAccess, + useOrganizationAccountWorkspaceSearch: + organizationAccountsQueriesMockFns.mockUseOrganizationAccountWorkspaceSearch, useUpdateOrganizationAccountWorkspaceAccess: organizationAccountsQueriesMockFns.mockUseUpdateOrganizationAccountWorkspaceAccess, useOrganizationConnectionRequestPolicy: