Skip to content
Merged
12 changes: 10 additions & 2 deletions apps/docs/content/docs/platform/connected-accounts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -69,15 +71,15 @@ 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 |
| **Revoked** | An admin revoked the person |

People asked by a workflow are also marked **Requested by workflow**.

Use **Send reminder** in a person's menu while any integration they were asked for is not connected; it also renews an expired request. A reminder for a workflow's request stays attributed to the workflow. **Revoke** stops the organization from using their contributions. They cannot undo an administrator's revocation by reconnecting themselves; use **Re-invite** to ask them again.
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

Expand All @@ -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:
Expand All @@ -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.

Expand Down
6 changes: 3 additions & 3 deletions apps/docs/content/docs/workflows/blocks/credential.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
8 changes: 8 additions & 0 deletions apps/sim/app/(auth)/auth-redirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
19 changes: 19 additions & 0 deletions apps/sim/app/(auth)/components/oauth-provider-checker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand All @@ -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<EmailVerificationRoute> {
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' }
}
67 changes: 66 additions & 1 deletion apps/sim/app/(auth)/verify/use-verification.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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(),
Expand All @@ -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)
})
})
31 changes: 30 additions & 1 deletion apps/sim/app/(auth)/verify/use-verification.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -82,6 +87,7 @@ export function useVerification({
const [storedEmail, setStoredEmail] = useState('')
const [status, setStatus] = useState<VerificationStatus>('idle')
const [isResending, setIsResending] = useState(false)
const [resendCountdown, setResendCountdown] = useState(0)
const [errorMessage, setErrorMessage] = useState('')

useEffect(() => {
Expand Down Expand Up @@ -178,6 +184,7 @@ export function useVerification({
return

setIsResending(true)
setResendCountdown(RESEND_COOLDOWN_SECONDS)
setErrorMessage('')

const normalizedEmail = normalizeEmail(email)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -257,6 +285,7 @@ export function useVerification({
email,
status,
isResending,
resendCountdown,
errorMessage,
isOtpComplete,
hasEmailService,
Expand Down
32 changes: 14 additions & 18 deletions apps/sim/app/(auth)/verify/verify-content.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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 (
<div className='au:space-y-[var(--auth-group-gap)]'>
<AuthHeader
Expand All @@ -65,10 +61,10 @@ function VerificationForm({
onVerify={() => {
void verifyCode()
}}
onResend={hasEmailService ? handleResend : undefined}
onResend={hasEmailService ? resendCode : undefined}
verifying={status === 'verifying'}
resending={isResending}
countdown={countdown}
countdown={resendCountdown}
error={errorMessage}
help={
hasEmailService
Expand Down
Loading
Loading