Skip to content

Commit fa26b98

Browse files
authored
fix(credential-groups): final audit follow-ups for connect links and Access (#10766)
* fix(credential-groups): require verified email, send queued request emails, honest expiry copy - Claiming a request for an address again requires user.emailVerified everywhere, including on deployments that cannot verify email: drop verified-email.ts and the relaxed credentials query. - Verify email state sends a code when opened (/verify?sendCode=true); where no code can be sent it asks the person to sign in with Google or Microsoft instead of looping through /verify. - A connection request email is sent while the enrollment is still a pending workflow request, no longer pinned to the latest workflow and integration, so a later request for another integration no longer drops the first email. providerId leaves the outbox payload. - An expired non-Slack OAuth attempt shows the generic expired message. * fix(credential-groups): tidy the connect link code paths - Link cleanup cron returns 500 when a table's drain fails, after both tables run - One active-options-for-provider helper and one Access-tab provider predicate for the request path and the admin policy's in-effect check - Connect, start, OAuth start and MCP start URLs come from connect-url builders; enrollment links hand back their token instead of being parsed (enrollment-links.ts removed) - Invitation tokens hash through hashInvitationToken everywhere - requestExpiresAt(now) replaces five copies of the renewal arithmetic - Link OAuth origins come from one const array the contract and types derive from - pendingWorkflowRequestCondition lives with the request email event; static import of the email handlers ends the cycle - Drop an unread link-record field, file-local exports, a restating TSDoc, and the duplicated connection-status/request input; reuse hasOrganizationSetup in canSelfEnroll - Connect route test: drop the declaration test and the six identical outcome cases - README: MCP attempts live ten minutes, Send email vs Send reminder, outbox wording - A first workflow-request email sent from People no longer reads as a reminder - Policy and Access refusals name the setting they come from * fix(credential-groups): clearer connect states, reconnect wording, and request docs * fix(credential-groups): open the Access tab for organizations with more than 1000 workspaces The Access read loaded every active workspace in the organization and refused once there were more than the grant cap, so large organizations saw only "Workspace access supports at most 1000 workspaces" and could not use Access or Workflow connection requests. The read now names only the granted workspaces (bounded by the grant cap), and Add workspace searches the organization's workspaces without access on the server: a bounded, wildcard-escaped name search behind the same admin read operation, exposed to the settings UI and to Copilot (search_workspaces). The grant cap itself is unchanged. * fix(credential-groups): honest verify fallback, active-only access grants, review follow-ups * improvement(credential-groups): simplify connect errors, verify cooldown and access helpers * chore(credential-groups): cleanup pass on comments and tests * fix(credential-groups): first request email keeps every reminder, hide unmatched picker selection
1 parent 22b5058 commit fa26b98

81 files changed

Lines changed: 1361 additions & 727 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/docs/content/docs/platform/connected-accounts.mdx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ Use the invitation email for workflow lookups. For example, inviting `alex@examp
6060

6161
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.
6262

63+
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.
64+
6365
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.
6466

6567
Each person shows one status:
@@ -69,15 +71,15 @@ Each person shows one status:
6971
| **Invited** | Sim emailed a request the person has not accepted yet |
7072
| **Requested** | A workflow asked, but Sim did not email the person |
7173
| **Expired** | The request went unaccepted for 7 days; send a reminder to renew it |
72-
| **Email failed** | Sim could not deliver the request email |
74+
| **Email failed** | Sim could not deliver the request email, and the person has not accepted it |
7375
| **Not connected** | The person accepted but has no connected account |
7476
| **Connected** | At least one account is connected |
7577
| **Needs reconnect** | An account stopped working and must be reconnected |
7678
| **Revoked** | An admin revoked the person |
7779

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

80-
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.
82+
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.
8183

8284
### 3. Grant workspace access
8385

@@ -96,6 +98,10 @@ For example, allowing Gmail in the Support workspace lets its authorized workflo
9698

9799
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.
98100

101+
### Workflow connection requests
102+
103+
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).
104+
99105
## Use account references in workflows
100106

101107
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:
106112
| **List Organization Accounts** | A page of OAuth accounts, optionally filtered by email and providers |
107113
| **Find Organization MCP Connection** | One managed MCP connection matching the invitation email and MCP provider |
108114
| **List Organization MCP Connections** | A page of managed MCP connections, optionally filtered by email and provider |
115+
| **Get Connection Status** | Whether a person has a usable account for an integration, and their link to connect it |
116+
| **Request Connection** | Asks a person to connect an integration, when workflow connection requests allow it |
109117

110118
The workflow's workspace determines the organization. You do not enter a credential group or organization ID.
111119

‎apps/docs/content/docs/workflows/blocks/credential.mdx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,15 +101,15 @@ For example, name the block **Account**, choose Find Organization Account, set E
101101
| `credentialId` | The account Find Organization Account would return, or `null` unless connected |
102102
| `connectUrl` | A link the person opens to sign in to Sim and connect this integration |
103103

104-
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.
104+
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.
105105

106106
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`.
107107

108108
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.
109109

110-
**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.
110+
**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.
111111

112-
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.
112+
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.
113113

114114
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.
115115

‎apps/sim/app/(auth)/auth-redirect.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ export const POST_AUTH_REDIRECT_STORAGE_KEY = 'postAuthRedirectUrl'
1010
/** Route the verify hop lives at, entered only from signup. */
1111
export const VERIFY_FROM_SIGNUP_ROUTE = '/verify?fromSignup=true'
1212

13+
/**
14+
* The verify page for a signed-in person whose email is still unverified. Nothing sent them a code
15+
* on the way here, so the page sends one as it opens, then returns to `redirectAfter`.
16+
*/
17+
export function buildVerifyEmailPath(redirectAfter: string): string {
18+
return `/verify?${new URLSearchParams({ sendCode: 'true', redirectAfter })}`
19+
}
20+
1321
/**
1422
* Default post-auth destination when no callback URL was carried in: the app
1523
* entry, which resolves to the viewer's organization or their workspaces.

‎apps/sim/app/(auth)/components/oauth-provider-checker.tsx‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
isGoogleAuthDisabled,
55
isMicrosoftAuthDisabled,
66
} from '@/lib/core/config/env-flags'
7+
import { isEmailVerificationEffectivelyEnabled } from '@/lib/messaging/email/verification'
78

89
export async function getOAuthProviderStatus() {
910
const githubAvailable =
@@ -17,3 +18,21 @@ export async function getOAuthProviderStatus() {
1718

1819
return { githubAvailable, googleAvailable, microsoftAvailable }
1920
}
21+
22+
/**
23+
* How a signed-in person can verify their email here: with a code, by signing in again through
24+
* a provider that vouches for the address (Google or GitHub, which may link to an existing
25+
* account), or not at all. Microsoft is left out: it links only when Entra asserts the domain.
26+
*/
27+
export type EmailVerificationRoute =
28+
| { kind: 'code' }
29+
| { kind: 'sign_in'; providers: string[] }
30+
| { kind: 'none' }
31+
32+
/** Resolves on the server which {@link EmailVerificationRoute} this deployment offers. */
33+
export async function resolveEmailVerificationRoute(): Promise<EmailVerificationRoute> {
34+
if (isEmailVerificationEffectivelyEnabled()) return { kind: 'code' }
35+
const { googleAvailable, githubAvailable } = await getOAuthProviderStatus()
36+
const providers = [...(googleAvailable ? ['Google'] : []), ...(githubAvailable ? ['GitHub'] : [])]
37+
return providers.length > 0 ? { kind: 'sign_in', providers } : { kind: 'none' }
38+
}

‎apps/sim/app/(auth)/verify/use-verification.test.tsx‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22

33
import { act } from 'react'
44
import { authClientMock, authClientMockFns } from '@sim/testing/mocks/auth-client.mock'
5-
import { nextNavigationMock } from '@sim/testing/mocks/next-navigation.mock'
5+
import { nextNavigationMock, nextNavigationMockFns } from '@sim/testing/mocks/next-navigation.mock'
66
import { createRoot, type Root } from 'react-dom/client'
77
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
88

99
vi.mock('@/lib/auth/client', () => authClientMock)
1010
vi.mock('next/navigation', () => nextNavigationMock)
1111

12+
import { VERIFY_FROM_SIGNUP_ROUTE } from '@/app/(auth)/auth-redirect'
1213
import { useVerification } from '@/app/(auth)/verify/use-verification'
1314

1415
const mocks = {
@@ -46,6 +47,8 @@ beforeEach(() => {
4647
document.body.appendChild(container)
4748
root = createRoot(container)
4849
sessionStorage.clear()
50+
vi.clearAllMocks()
51+
nextNavigationMockFns.mockUseSearchParams.mockReturnValue(new URLSearchParams())
4952
authClientMockFns.mockUseSession.mockReturnValue({
5053
data: { user: { email: 'member@example.com', emailVerified: false } },
5154
refetch: vi.fn(),
@@ -72,4 +75,66 @@ describe('verification after opening an enrollment in a new tab', () => {
7275
type: 'email-verification',
7376
})
7477
})
78+
79+
it('counts the resend cooldown down from 30 to 0 after a resend', async () => {
80+
const result = renderVerification()
81+
expect(result.current.resendCountdown).toBe(0)
82+
await act(async () => result.current.resendCode())
83+
expect(result.current.resendCountdown).toBe(30)
84+
for (let second = 0; second < 30; second += 1) {
85+
await act(async () => vi.advanceTimersByTime(1000))
86+
}
87+
expect(result.current.resendCountdown).toBe(0)
88+
})
89+
})
90+
91+
describe('verification opened for a signed-in account nothing sent a code to', () => {
92+
it('sends one code as the page opens', async () => {
93+
nextNavigationMockFns.mockUseSearchParams.mockReturnValue(
94+
new URLSearchParams({ sendCode: 'true', redirectAfter: '/credential-groups/g/connect' })
95+
)
96+
const result = renderVerification()
97+
await act(async () => {})
98+
expect(mocks.resend).toHaveBeenCalledTimes(1)
99+
expect(mocks.resend).toHaveBeenCalledWith({
100+
email: 'member@example.com',
101+
type: 'email-verification',
102+
})
103+
expect(result.current.resendCountdown).toBe(30)
104+
})
105+
106+
it('never sends the code to an address left in the tab by an earlier signup', async () => {
107+
sessionStorage.setItem('verificationEmail', 'previous@example.com')
108+
authClientMockFns.mockUseSession.mockReturnValue({ data: null, refetch: vi.fn() })
109+
nextNavigationMockFns.mockUseSearchParams.mockReturnValue(
110+
new URLSearchParams({ sendCode: 'true' })
111+
)
112+
const result = renderVerification()
113+
await act(async () => {})
114+
expect(mocks.resend).not.toHaveBeenCalled()
115+
expect(result.current.resendCountdown).toBe(0)
116+
})
117+
118+
it('sends nothing when the account is already verified', async () => {
119+
authClientMockFns.mockUseSession.mockReturnValue({
120+
data: { user: { email: 'member@example.com', emailVerified: true } },
121+
refetch: vi.fn(),
122+
})
123+
nextNavigationMockFns.mockUseSearchParams.mockReturnValue(
124+
new URLSearchParams({ sendCode: 'true' })
125+
)
126+
renderVerification()
127+
await act(async () => {})
128+
expect(mocks.resend).not.toHaveBeenCalled()
129+
})
130+
131+
it('sends nothing on the signup route, which carries no sendCode', async () => {
132+
nextNavigationMockFns.mockUseSearchParams.mockReturnValue(
133+
new URL(VERIFY_FROM_SIGNUP_ROUTE, 'http://localhost').searchParams
134+
)
135+
const result = renderVerification()
136+
await act(async () => {})
137+
expect(mocks.resend).not.toHaveBeenCalled()
138+
expect(result.current.resendCountdown).toBe(0)
139+
})
75140
})

‎apps/sim/app/(auth)/verify/use-verification.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use client'
22

3-
import { useEffect, useState } from 'react'
3+
import { useEffect, useRef, useState } from 'react'
44
import { createLogger } from '@sim/logger'
55
import { normalizeEmail } from '@sim/utils/string'
66
import { useSearchParams } from 'next/navigation'
@@ -12,6 +12,9 @@ import { DEFAULT_POST_AUTH_ROUTE, POST_AUTH_REDIRECT_STORAGE_KEY } from '@/app/(
1212

1313
const logger = createLogger('useVerification')
1414

15+
/** How long after a code is sent before another may be requested. */
16+
const RESEND_COOLDOWN_SECONDS = 30
17+
1518
/**
1619
* Resolves the post-auth destination at the moment of redirect rather than
1720
* caching it in state.
@@ -61,6 +64,8 @@ interface UseVerificationReturn {
6164
email: string
6265
status: VerificationStatus
6366
isResending: boolean
67+
/** Seconds until another code may be requested; 0 when it may be now. */
68+
resendCountdown: number
6469
errorMessage: string
6570
isOtpComplete: boolean
6671
hasEmailService: boolean
@@ -82,6 +87,7 @@ export function useVerification({
8287
const [storedEmail, setStoredEmail] = useState('')
8388
const [status, setStatus] = useState<VerificationStatus>('idle')
8489
const [isResending, setIsResending] = useState(false)
90+
const [resendCountdown, setResendCountdown] = useState(0)
8591
const [errorMessage, setErrorMessage] = useState('')
8692

8793
useEffect(() => {
@@ -178,6 +184,7 @@ export function useVerification({
178184
return
179185

180186
setIsResending(true)
187+
setResendCountdown(RESEND_COOLDOWN_SECONDS)
181188
setErrorMessage('')
182189

183190
const normalizedEmail = normalizeEmail(email)
@@ -228,6 +235,27 @@ export function useVerification({
228235
}
229236
}, [otp, email, status, isResending])
230237

238+
/**
239+
* Signup and sign-in arrive with a code already on its way. A page that sends a signed-in,
240+
* unverified person here asks for one with `sendCode`, sent once per visit to the session's
241+
* own address: a signup address left in this tab's storage may belong to someone else.
242+
*/
243+
const sendCodeOnOpen = searchParams.get('sendCode') === 'true'
244+
const sessionEmail = session?.user?.email
245+
const sessionVerified = session?.user?.emailVerified === true
246+
const sentCodeOnOpen = useRef(false)
247+
useEffect(() => {
248+
if (!sendCodeOnOpen || !sessionEmail || sessionVerified || sentCodeOnOpen.current) return
249+
sentCodeOnOpen.current = true
250+
resendCode()
251+
}, [sendCodeOnOpen, sessionEmail, sessionVerified])
252+
253+
useEffect(() => {
254+
if (resendCountdown <= 0) return
255+
const timer = setTimeout(() => setResendCountdown((seconds) => seconds - 1), 1000)
256+
return () => clearTimeout(timer)
257+
}, [resendCountdown])
258+
231259
useEffect(() => {
232260
if (isEmailVerificationEnabled) return
233261

@@ -257,6 +285,7 @@ export function useVerification({
257285
email,
258286
status,
259287
isResending,
288+
resendCountdown,
260289
errorMessage,
261290
isOtpComplete,
262291
hasEmailService,

‎apps/sim/app/(auth)/verify/verify-content.tsx‎

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use client'
22

3-
import { Suspense, useEffect, useState } from 'react'
3+
import { Suspense } from 'react'
44
import { AuthCodeEntry } from '@sim/auth-ui'
55
import { POST_AUTH_REDIRECT_STORAGE_KEY } from '@/app/(auth)/auth-redirect'
66
import { AuthHeader, AuthNavPrompt } from '@/app/(auth)/components'
@@ -22,24 +22,20 @@ function VerificationForm({
2222
isProduction: boolean
2323
isEmailVerificationEnabled: boolean
2424
}) {
25-
const { otp, email, status, isResending, errorMessage, verifyCode, resendCode, handleOtpChange } =
26-
useVerification({ hasEmailService, isProduction, isEmailVerificationEnabled })
25+
const {
26+
otp,
27+
email,
28+
status,
29+
isResending,
30+
resendCountdown,
31+
errorMessage,
32+
verifyCode,
33+
resendCode,
34+
handleOtpChange,
35+
} = useVerification({ hasEmailService, isProduction, isEmailVerificationEnabled })
2736

2837
const isVerified = status === 'verified'
2938

30-
const [countdown, setCountdown] = useState(0)
31-
32-
useEffect(() => {
33-
if (countdown <= 0) return
34-
const timer = setTimeout(() => setCountdown((c) => c - 1), 1000)
35-
return () => clearTimeout(timer)
36-
}, [countdown])
37-
38-
const handleResend = () => {
39-
resendCode()
40-
setCountdown(30)
41-
}
42-
4339
return (
4440
<div className='au:space-y-[var(--auth-group-gap)]'>
4541
<AuthHeader
@@ -65,10 +61,10 @@ function VerificationForm({
6561
onVerify={() => {
6662
void verifyCode()
6763
}}
68-
onResend={hasEmailService ? handleResend : undefined}
64+
onResend={hasEmailService ? resendCode : undefined}
6965
verifying={status === 'verifying'}
7066
resending={isResending}
71-
countdown={countdown}
67+
countdown={resendCountdown}
7268
error={errorMessage}
7369
help={
7470
hasEmailService

0 commit comments

Comments
 (0)