Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
41e0e64
feat(instagram): add Instagram Login OAuth, tools, and block
Jul 10, 2026
5fa0c84
feat(instagram): add Gmail-style media uploads for publish ops
Jul 10, 2026
5897592
refactor(instagram): simplify messaging tools to direct requests, cle…
Jul 10, 2026
363a68e
fix(instagram): parallelize carousel child polling, enforce 2-10 item…
Jul 10, 2026
e310f97
fix(instagram): resolve user id from user_id only, accept numeric use…
Jul 10, 2026
05f51a3
fix(instagram): use form/query params for publish and comment endpoin…
Jul 10, 2026
293230a
fix(instagram): normalize Graph ID outputs to strings so downstream .…
Jul 10, 2026
c3c4f1d
style(instagram): use brand gradient tile for the block icon
Jul 10, 2026
9236d5b
fix(instagram): tighten publish defaults and cloud-storage upload UX
Jul 12, 2026
f8c9516
fix(instagram): fail closed when cloud storage status is unknown
Jul 12, 2026
6128a18
fix(instagram): proactively refresh long-lived tokens before expiry
Jul 12, 2026
6720e40
Merge branch 'staging' into feature/instagram-integration
BillLeoutsakosvl346 Jul 12, 2026
7a6f33a
fix(oauth): restore TikTok clientIdParamName JSDoc after merge
Jul 12, 2026
89caa68
fix(api): Zod-contract storage-status and ratchet validation baseline
Jul 12, 2026
24bdce9
fix(instagram): match Gmail advanced media placeholders
Jul 12, 2026
b247bb1
Merge branch 'staging' into feature/instagram-integration
icecrasher321 Jul 13, 2026
5952e1d
Merge remote-tracking branch 'origin/staging' into feature/instagram-…
icecrasher321 Jul 13, 2026
3ba73dc
Merge remote-tracking branch 'origin/staging' into feature/instagram-…
icecrasher321 Jul 13, 2026
0fa622c
code review + hide from toolbar
icecrasher321 Jul 13, 2026
b2238e7
address comments
icecrasher321 Jul 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions apps/docs/components/icons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,21 @@ export function LinkedInIcon(props: SVGProps<SVGSVGElement>) {
)
}

/** Instagram camera glyph rendered with the block's brand gradient background. */
export function InstagramIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg
{...props}
viewBox='0 0 24 24'
fill='currentColor'
xmlns='http://www.w3.org/2000/svg'
aria-hidden='true'
>
<path d='M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z' />
</svg>
)
}

export function CrunchbaseIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg
Expand Down
10 changes: 10 additions & 0 deletions apps/sim/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,16 @@ API_ENCRYPTION_KEY=your_api_encryption_key # Use `openssl rand -hex 32` to gener
# S3_ENDPOINT= # Custom endpoint for S3-compatible storage (Cloudflare R2, MinIO, Backblaze B2). Leave unset for AWS S3
# S3_FORCE_PATH_STYLE=true # Required for MinIO/Ceph RGW. Leave unset for AWS S3 and R2

# Instagram OAuth (Optional - Instagram App ID/Secret from Meta App Dashboard > Instagram > API setup with Instagram login)
# INSTAGRAM_CLIENT_ID=
# INSTAGRAM_CLIENT_SECRET=
# Instagram publish file uploads require S3 or Azure Blob above (Meta must fetch a public HTTPS URL).
# Gmail attachments do not need this.

# TikTok OAuth (Optional - Client Key/Secret from the TikTok for Developers app)
# TIKTOK_CLIENT_ID=
# TIKTOK_CLIENT_SECRET=

# Azure Blob Storage takes precedence over S3 if both are configured
# AZURE_ACCOUNT_NAME= # Azure storage account name
# AZURE_ACCOUNT_KEY= # Azure storage account key
Expand Down
89 changes: 89 additions & 0 deletions apps/sim/app/api/auth/instagram/authorize/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { createLogger } from '@sim/logger'
import { generateShortId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { authorizeInstagramContract } from '@/lib/api/contracts/oauth-connections'
import { parseRequest } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
import { env } from '@/lib/core/config/env'
import { getBaseUrl } from '@/lib/core/utils/urls'
import { isSameOrigin } from '@/lib/core/utils/validation'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { createConnectDraft } from '@/lib/credentials/connect-draft'
import { getCanonicalScopesForProvider } from '@/lib/oauth/utils'
import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils'

const logger = createLogger('InstagramAuthorize')

export const dynamic = 'force-dynamic'

const INSTAGRAM_STATE_COOKIE = 'instagram_oauth_state'
const INSTAGRAM_RETURN_URL_COOKIE = 'instagram_return_url'
const INSTAGRAM_STATE_COOKIE_PATH = '/api/auth'
const INSTAGRAM_STATE_COOKIE_MAX_AGE_SECONDS = 60 * 10

export const GET = withRouteHandler(async (request: NextRequest) => {
try {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const parsed = await parseRequest(authorizeInstagramContract, request, {})
if (!parsed.success) return parsed.response
const { returnUrl, workspaceId } = parsed.data.query

if (workspaceId) {
const access = await checkWorkspaceAccess(workspaceId, session.user.id)
if (!access.canWrite) {
return NextResponse.json({ error: 'Workspace write access denied' }, { status: 403 })
}
await createConnectDraft({
userId: session.user.id,
workspaceId,
providerId: 'instagram',
})
}

const clientId = env.INSTAGRAM_CLIENT_ID
if (!clientId) {
logger.error('INSTAGRAM_CLIENT_ID not configured')
return NextResponse.json({ error: 'Instagram client ID not configured' }, { status: 500 })
}

const baseUrl = getBaseUrl()
const state = generateShortId(32)
const redirectUri = `${baseUrl}/api/auth/oauth2/callback/instagram`
const scope = getCanonicalScopesForProvider('instagram').join(',')

const authUrl = new URL('https://www.instagram.com/oauth/authorize')
authUrl.searchParams.set('client_id', clientId)
authUrl.searchParams.set('redirect_uri', redirectUri)
authUrl.searchParams.set('response_type', 'code')
authUrl.searchParams.set('scope', scope)
authUrl.searchParams.set('state', state)

const response = NextResponse.redirect(authUrl.toString())
response.cookies.set(INSTAGRAM_STATE_COOKIE, state, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: INSTAGRAM_STATE_COOKIE_MAX_AGE_SECONDS,
path: INSTAGRAM_STATE_COOKIE_PATH,
})

if (returnUrl && isSameOrigin(returnUrl)) {
response.cookies.set(INSTAGRAM_RETURN_URL_COOKIE, returnUrl, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: INSTAGRAM_STATE_COOKIE_MAX_AGE_SECONDS,
path: INSTAGRAM_STATE_COOKIE_PATH,
})
}

return response
} catch (error) {
logger.error('Error starting Instagram OAuth', { error })
return NextResponse.json({ error: 'Failed to start Instagram OAuth' }, { status: 500 })
}
})
54 changes: 46 additions & 8 deletions apps/sim/app/api/auth/oauth/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { withLeaderLock } from '@/lib/concurrency/leader-lock'
import { coalesceLocally } from '@/lib/concurrency/singleflight'
import { decryptSecret } from '@/lib/core/security/encryption'
import { refreshOAuthToken } from '@/lib/oauth'
import { isInstagramProvider, shouldProactivelyRefreshInstagramToken } from '@/lib/oauth/instagram'
import {
getMicrosoftRefreshTokenExpiry,
isMicrosoftProvider,
Expand Down Expand Up @@ -546,6 +547,7 @@ export async function getOAuthToken(userId: string, providerId: string): Promise
accessTokenExpiresAt: account.accessTokenExpiresAt,
idToken: account.idToken,
scope: account.scope,
updatedAt: account.updatedAt,
})
.from(account)
.where(and(eq(account.userId, userId), eq(account.providerId, providerId)))
Expand All @@ -559,19 +561,33 @@ export async function getOAuthToken(userId: string, providerId: string): Promise

const credential = connections[0]

// Determine whether we should refresh: missing token OR expired token
// Determine whether we should refresh: missing/expired token, or Instagram
// long-lived token nearing expiry (Meta cannot refresh after expiry).
const now = new Date()
const tokenExpiry = credential.accessTokenExpiresAt
const shouldAttemptRefresh =
const accessTokenNeedsRefresh =
!!credential.refreshToken && (!credential.accessToken || (tokenExpiry && tokenExpiry < now))
const instagramNeedsProactiveRefresh =
!!credential.refreshToken &&
isInstagramProvider(providerId) &&
shouldProactivelyRefreshInstagramToken({
accessTokenExpiresAt: credential.accessTokenExpiresAt,
updatedAt: credential.updatedAt,
now,
})

if (shouldAttemptRefresh) {
return performCoalescedRefresh({
if (accessTokenNeedsRefresh || instagramNeedsProactiveRefresh) {
const fresh = await performCoalescedRefresh({
accountId: credential.id,
providerId,
refreshToken: credential.refreshToken!,
userId,
})
if (fresh) return fresh
if (!accessTokenNeedsRefresh && credential.accessToken) {
return credential.accessToken
}
return null
}

if (!credential.accessToken) {
Expand Down Expand Up @@ -645,7 +661,18 @@ export async function refreshAccessTokenIfNeeded(
refreshTokenExpiresAt &&
refreshTokenExpiresAt <= proactiveRefreshThreshold

const shouldRefresh = accessTokenNeedsRefresh || refreshTokenNeedsProactiveRefresh
// Instagram long-lived tokens can only be refreshed while still valid.
const instagramNeedsProactiveRefresh =
!!credential.refreshToken &&
isInstagramProvider(credential.providerId) &&
shouldProactivelyRefreshInstagramToken({
accessTokenExpiresAt,
updatedAt: credential.updatedAt,
now,
})

const shouldRefresh =
accessTokenNeedsRefresh || refreshTokenNeedsProactiveRefresh || instagramNeedsProactiveRefresh

const accessToken = credential.accessToken

Expand All @@ -662,8 +689,8 @@ export async function refreshAccessTokenIfNeeded(
})
if (fresh) return fresh

// If refresh was only triggered proactively (Microsoft refresh-token aging),
// the still-valid access token is a fine fallback.
// If refresh was only triggered proactively (Microsoft refresh-token aging /
// Instagram long-lived nearing expiry), the still-valid access token is fine.
if (!accessTokenNeedsRefresh && accessToken) {
logger.info(`[${requestId}] Refresh unavailable; reusing still-valid access token`)
return accessToken
Expand Down Expand Up @@ -711,7 +738,18 @@ export async function refreshTokenIfNeeded(
refreshTokenExpiresAt &&
refreshTokenExpiresAt <= proactiveRefreshThreshold

const shouldRefresh = accessTokenNeedsRefresh || refreshTokenNeedsProactiveRefresh
// Instagram long-lived tokens can only be refreshed while still valid.
const instagramNeedsProactiveRefresh =
!!credential.refreshToken &&
isInstagramProvider(credential.providerId) &&
shouldProactivelyRefreshInstagramToken({
accessTokenExpiresAt,
updatedAt: credential.updatedAt,
now,
})

const shouldRefresh =
accessTokenNeedsRefresh || refreshTokenNeedsProactiveRefresh || instagramNeedsProactiveRefresh

// If token appears valid and present, return it directly
if (!shouldRefresh) {
Expand Down
66 changes: 1 addition & 65 deletions apps/sim/app/api/auth/oauth2/authorize/route.ts
Original file line number Diff line number Diff line change
@@ -1,81 +1,17 @@
import { db } from '@sim/db'
import { pendingCredentialDraft, user } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { generateId } from '@sim/utils/id'
import { and, eq, lt } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { authorizeOAuth2Contract } from '@/lib/api/contracts/oauth-connections'
import { parseRequest } from '@/lib/api/server'
import { auth, getSession } from '@/lib/auth/auth'
import { getBaseUrl } from '@/lib/core/utils/urls'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { getAllOAuthServices } from '@/lib/oauth/utils'
import { createConnectDraft } from '@/lib/credentials/connect-draft'
import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils'

const logger = createLogger('OAuth2Authorize')

export const dynamic = 'force-dynamic'

const DRAFT_TTL_MS = 15 * 60 * 1000

/**
* Creates the pending credential draft at click time so its TTL starts when the
* user actually initiates the connect. Better Auth's `account.create.after` hook
* consumes this draft to materialize the real credential after the OAuth
* callback; starting the clock here guarantees the draft outlives the (≤5 min)
* OAuth round-trip rather than expiring mid-flow and silently producing no
* credential.
*/
async function createConnectDraft(params: {
userId: string
workspaceId: string
providerId: string
}): Promise<void> {
const { userId, workspaceId, providerId } = params

const service = getAllOAuthServices().find((s) => s.providerId === providerId)
const serviceName = service?.name ?? providerId

let displayName = serviceName
try {
const [row] = await db.select({ name: user.name }).from(user).where(eq(user.id, userId))
if (row?.name) {
displayName = `${row.name}'s ${serviceName}`
}
} catch {
// Fall back to service name only
}

const now = new Date()
const expiresAt = new Date(now.getTime() + DRAFT_TTL_MS)
await db
.delete(pendingCredentialDraft)
.where(
and(eq(pendingCredentialDraft.userId, userId), lt(pendingCredentialDraft.expiresAt, now))
)
await db
.insert(pendingCredentialDraft)
.values({
id: generateId(),
userId,
workspaceId,
providerId,
displayName,
expiresAt,
createdAt: now,
})
.onConflictDoUpdate({
target: [
pendingCredentialDraft.userId,
pendingCredentialDraft.providerId,
pendingCredentialDraft.workspaceId,
],
set: { displayName, expiresAt, createdAt: now },
})

logger.info('Created OAuth connect credential draft', { userId, workspaceId, providerId })
}

/**
* Browser-initiated entrypoint for linking a generic OAuth2 account.
*/
Expand Down
Loading
Loading