Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
767 changes: 703 additions & 64 deletions apps/docs/content/docs/integrations/shopify.mdx

Large diffs are not rendered by default.

46 changes: 33 additions & 13 deletions apps/sim/app/api/auth/oauth2/callback/shopify/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { hmacSha256Hex } from '@sim/security/hmac'
import { createMockRequest } from '@sim/testing'
import { authMockFns } from '@sim/testing/mocks/auth.mock'
import { urlsMockFns } from '@sim/testing/mocks/urls.mock'
import { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const { mockCompleteShopifyOAuthConnection, mockRequireConfiguredOAuthClient } = vi.hoisted(() => ({
Expand Down Expand Up @@ -58,19 +59,39 @@ describe('Shopify OAuth callback', () => {
},
})
mockCompleteShopifyOAuthConnection.mockResolvedValue(undefined)
vi.stubGlobal(
'fetch',
vi.fn().mockImplementation(() =>
Promise.resolve(
new Response(JSON.stringify({ access_token: 'shopify-token', scope: 'read_products' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
)
)
})

it.each(['caller', 'provider deadline'] as const)(
'distinguishes %s cancellation at the HTTP boundary',
async (source) => {
const controller = new AbortController()
const reason = new DOMException(
'Connection interrupted',
source === 'caller' ? 'AbortError' : 'TimeoutError'
)
const state = createShopifyOAuthState({
userId: 'user-1',
shopDomain: SHOP_DOMAIN,
clientSecret: CLIENT_SECRET,
})
const request = new NextRequest(callbackRequest(state), { signal: controller.signal })
mockCompleteShopifyOAuthConnection.mockImplementationOnce(async () => {
if (source === 'caller') controller.abort(reason)
throw reason
})

const response = await GET(request)

if (source === 'caller') {
expect(response.status).toBe(499)
expect(response.headers.get('location')).toBeNull()
} else {
expect(response.status).toBe(307)
expect(response.headers.get('location')).toContain('error=shopify_callback_error')
}
}
)

it('completes the credential draft carried by signed state instead of a shared cookie', async () => {
const state = createShopifyOAuthState({
userId: 'user-1',
Expand All @@ -83,9 +104,8 @@ describe('Shopify OAuth callback', () => {
const response = await GET(callbackRequest(state))

expect(mockCompleteShopifyOAuthConnection).toHaveBeenCalledWith({
accessToken: 'shopify-token',
code: 'authorization-code',
shopDomain: SHOP_DOMAIN,
scope: 'read_products',
userId: 'user-1',
draftId: 'draft-from-state',
signal: expect.any(AbortSignal),
Expand Down
51 changes: 10 additions & 41 deletions apps/sim/app/api/auth/oauth2/callback/shopify/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { isSameOrigin } from '@/lib/core/utils/validation'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { APP_ENTRY_PATH } from '@/lib/navigation/paths'
import { completeShopifyOAuthConnection } from '@/lib/oauth/shopify'
import { ShopifyOAuthError } from '@/lib/oauth/shopify-installation'
import { parseShopifyOAuthState } from '@/lib/oauth/shopify-state'

const logger = createLogger('ShopifyCallback')
Expand Down Expand Up @@ -75,7 +76,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
})

const {
values: { SHOPIFY_CLIENT_ID: clientId, SHOPIFY_CLIENT_SECRET: clientSecret },
values: { SHOPIFY_CLIENT_SECRET: clientSecret },
} = requireConfiguredOAuthClient('shopify')

if (!validateHmac(searchParams, clientSecret)) {
Expand Down Expand Up @@ -111,64 +112,32 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
clientSecret,
})

const tokenResponse = await fetch(`https://${shopDomain}/admin/oauth/access_token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
code: code,
}),
})

if (!tokenResponse.ok) {
const errorText = await tokenResponse.text()
logger.error('Failed to exchange code for token:', {
status: tokenResponse.status,
body: errorText,
})
return NextResponse.redirect(`${baseUrl}${APP_ENTRY_PATH}?error=shopify_token_error`)
}

const tokenData = await tokenResponse.json()
const accessToken = tokenData.access_token
const scope = tokenData.scope

logger.info('Shopify token exchange successful:', {
hasAccessToken: !!accessToken,
scope: scope,
})

if (!accessToken) {
logger.error('No access token in response')
return NextResponse.redirect(`${baseUrl}${APP_ENTRY_PATH}?error=shopify_no_token`)
if (returnUrl && !isSameOrigin(returnUrl)) {
throw new Error('Shopify OAuth state contains an invalid return URL')
}

await completeShopifyOAuthConnection({
accessToken,
code,
shopDomain,
scope,
userId: session.user.id,
draftId,
signal: request.signal,
})

if (returnUrl && !isSameOrigin(returnUrl)) {
throw new Error('Shopify OAuth state contains an invalid return URL')
}
const redirectUrl = returnUrl ?? `${baseUrl}${APP_ENTRY_PATH}`
const finalUrl = new URL(redirectUrl)
finalUrl.searchParams.set('shopify_connected', 'true')

return clearShopifyOAuthCookies(NextResponse.redirect(finalUrl))
} catch (error) {
logger.error('Error in Shopify OAuth callback:', error)
if (request.signal.aborted) throw error
logger.error('Shopify OAuth callback failed')
const errorCode =
error instanceof EnvCapabilityConfigurationError && error.capabilityId === 'oauth'
? 'shopify_config_error'
: 'shopify_callback_error'
: error instanceof ShopifyOAuthError
? error.callbackError
: 'shopify_callback_error'
return clearShopifyOAuthCookies(
NextResponse.redirect(`${baseUrl}${APP_ENTRY_PATH}?error=${errorCode}`)
)
Expand Down
29 changes: 29 additions & 0 deletions apps/sim/blocks/blocks/shopify.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest'
import { ShopifyBlock } from '@/blocks/blocks/shopify'

const mapParams = ShopifyBlock.tools.config?.params
if (!mapParams) throw new Error('Shopify parameter mapping is required')

describe('Shopify operation changes', () => {
it.each(['first', 'variantsFirst', 'imagesFirst', 'lineItemsFirst', 'changeFromQuantity'])(
'ignores a stale hidden %s value when updating an order',
(field) => {
const params = mapParams({
operation: 'shopify_update_order',
orderId: 'gid://shopify/Order/1',
orderNote: 'Updated note',
[field]: 'stale invalid number',
})
expect(params.orderId).toBe('gid://shopify/Order/1')
expect(params.note).toBe('Updated note')
}
)

it.each([
['shopify_update_product', 'templateSuffix', 'productId', 'gid://shopify/Product/1'],
['shopify_update_order', 'poNumber', 'orderId', 'gid://shopify/Order/1'],
])('preserves explicit clears for %s field %s', (operation, field, idField, id) => {
expect(mapParams({ operation, [idField]: id, [field]: '' })[field]).toBe('')
expect(mapParams({ operation, [idField]: id })[field]).toBeUndefined()
})
})
Loading
Loading