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
5 changes: 5 additions & 0 deletions .changeset/app-dev-service-account.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/app': minor
---

Run `shopify app dev --store` on a dev store with `SHOPIFY_SERVICE_ACCOUNT_TOKEN`.
5 changes: 4 additions & 1 deletion packages/app/src/cli/commands/app/dev.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ describe('app dev command', () => {
forceRelink: false,
userProvidedConfigName: 'prod',
})
expect(storeContext).toHaveBeenCalledWith(expect.objectContaining({devSession: true}))
expect(service).toHaveBeenCalled()
})
})
Expand Down Expand Up @@ -353,7 +354,9 @@ describe('app dev command', () => {
tunnelUrl: undefined,
localhostPort: undefined,
})
expect(storeContext).toHaveBeenCalledWith(expect.objectContaining({storeCreationMode: 'selection-option'}))
expect(storeContext).toHaveBeenCalledWith(
expect.objectContaining({storeCreationMode: 'selection-option', devSession: true}),
)
expect(dev).toHaveBeenCalledWith(
expect.objectContaining({installMkcert: undefined, unsafeValidation: false, tunnel: {mode: 'auto'}}),
)
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/cli/commands/app/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ export default class Dev extends AppLinkedCommand {
storeFqdn: flags.store,
forceReselectStore: flags.reset,
storeCreationMode: 'selection-option',
devSession: true,
})

const devOptions: DevOptions = {
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/cli/commands/app/dev/clean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export default class DevClean extends AppLinkedCommand {
appContextResult,
storeFqdn: flags.store,
forceReselectStore: flags.reset,
devSession: true,
})

const result = await devClean({appContextResult, store})
Expand Down
6 changes: 4 additions & 2 deletions packages/app/src/cli/services/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {AbortError} from '@shopify/cli-kit/node/error'
import {withDevInstance, type DevInstance} from '@shopify/cli-kit/node/dev-instance'
import {basename} from '@shopify/cli-kit/node/path'
import {isTruthy} from '@shopify/cli-kit/node/context/utilities'
import {isServiceAccountTokenSet} from '@shopify/cli-kit/node/session'

export interface DevOptions {
app: AppLinkedInterface
Expand Down Expand Up @@ -138,7 +139,8 @@ async function prepareForDev(commandOptions: DevOptions, tunnelClient?: TunnelCl

// If the dev_store_url is set in the app configuration, keep updating it.
// If not, `store-context.ts` will take care of caching it in the hidden config.
if (app.configuration.build?.dev_store_url) {
// A service account's store is checked only when the dev session starts, so it isn't saved.
if (app.configuration.build?.dev_store_url && !isServiceAccountTokenSet()) {
app.configuration.build = {
...app.configuration.build,
dev_store_url: store.shopDomain,
Expand Down Expand Up @@ -199,7 +201,7 @@ async function prepareForDev(commandOptions: DevOptions, tunnelClient?: TunnelCl

return {
storeFqdn: store.shopDomain,
storeId: store.shopId,
storeId: store.shopId || undefined,
remoteApp,
remoteAppUpdated: remoteApp.apiKey !== previousAppId,
localApp: app,
Expand Down
51 changes: 49 additions & 2 deletions packages/app/src/cli/services/dev/extension.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ import * as websocket from './extension/websocket.js'
import {devUIExtensions, ExtensionDevOptions} from './extension.js'
import {ExtensionsEndpointPayload} from './extension/payload/models.js'
import {WebsocketConnection} from './extension/websocket/models.js'
import {AppEventWatcher} from './app-events/app-event-watcher.js'
import {testAppLinked} from '../../models/app/app.test-data.js'
import {AppEvent, AppEventWatcher, EventType} from './app-events/app-event-watcher.js'
import {testAppLinked, testUIExtension} from '../../models/app/app.test-data.js'
import {describe, test, vi, expect} from 'vitest'
import {isServiceAccountTokenSet} from '@shopify/cli-kit/node/session'
import {mockAndCaptureOutput} from '@shopify/cli-kit/node/testing/output'
import {Server} from 'http'

vi.mock('@shopify/cli-kit/node/session')

describe('devUIExtensions()', () => {
const serverCloseSpy = vi.fn()
const websocketCloseSpy = vi.fn()
Expand Down Expand Up @@ -143,4 +147,47 @@ describe('devUIExtensions()', () => {
// THEN
expect(getExtensions()).toStrictEqual([newUIExtension])
})

test('warns instead of stopping dev when a service account adds a checkout extension without a cart URL', async () => {
// GIVEN
spyOnEverything()
vi.mocked(isServiceAccountTokenSet).mockReturnValue(true)
const addExtension = vi.fn()
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
vi.spyOn(store, 'ExtensionsPayloadStore').mockImplementation(function () {
return {addExtension} as unknown as store.ExtensionsPayloadStore
} as any)
const appWatcher = new AppEventWatcher(app, 'url', 'path')
const onEvent = vi.spyOn(appWatcher, 'onEvent')
const output = mockAndCaptureOutput()
output.clear()
const checkoutExtension = await testUIExtension({
type: 'ui_extension',
handle: 'checkout-extension',
configuration: {
name: 'checkout-extension',
type: 'ui_extension',
handle: 'checkout-extension',
metafields: [],
extension_points: [{target: 'purchase.checkout.block.render', module: './src/index.js'}],
},
})
await devUIExtensions({...options, appWatcher, checkoutCartUrl: undefined, extensions: []})
const eventHandler = onEvent.mock.calls[0]![0]

// WHEN
const appEvent: AppEvent = {
app,
extensionEvents: [{type: EventType.Created, extension: checkoutExtension}],
path: '',
startTime: [0, 0],
}
await eventHandler(appEvent)

// THEN
expect(addExtension).toHaveBeenCalledWith(checkoutExtension, 'path')
expect(output.warn()).toContain("checkout-extension can't be previewed without a cart")
expect(output.warn()).toContain('--checkout-cart-url')
})
})
17 changes: 13 additions & 4 deletions packages/app/src/cli/services/dev/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import {AppEvent, AppEventWatcher, EventType} from './app-events/app-event-watch
import {buildCartURLIfNeeded} from './extension/utilities.js'
import {ExtensionInstance} from '../../models/extensions/extension-instance.js'
import {AbortSignal} from '@shopify/cli-kit/node/abort'
import {outputDebug} from '@shopify/cli-kit/node/output'
import {outputDebug, outputWarn} from '@shopify/cli-kit/node/output'
import {isServiceAccountTokenSet} from '@shopify/cli-kit/node/session'
import {DotEnvFile} from '@shopify/cli-kit/node/dot-env'
import {Writable} from 'stream'

Expand Down Expand Up @@ -82,9 +83,9 @@ export interface ExtensionDevOptions {
storeFqdn: string

/**
* Id of the store where the extension wants to be previewed
* Id of the store where the extension wants to be previewed. Unknown when a service account runs dev.
*/
storeId: string
storeId?: string

/**
* List of granted approval scopes belonging to the parent app
Expand Down Expand Up @@ -162,7 +163,15 @@ export async function devUIExtensions(options: ExtensionDevOptions): Promise<voi
switch (event.type) {
case EventType.Created:
payloadOptions.extensions.push(event.extension)
if (!payloadOptions.checkoutCartUrl) {
if (!payloadOptions.checkoutCartUrl && isServiceAccountTokenSet()) {
// A service account can't look up a product for the cart, and stopping here would end the dev session.
if (event.extension.shouldFetchCartUrl()) {
outputWarn(
`${event.extension.localIdentifier} can't be previewed without a cart. Restart dev with --checkout-cart-url, in the format "/cart/{productVariantID}:{productQuantity}".`,
payloadOptions.stderr,
)
}
} else if (!payloadOptions.checkoutCartUrl) {
const cartUrl = await buildCartURLIfNeeded(payloadOptions.extensions, payloadOptions.storeFqdn)
// eslint-disable-next-line require-atomic-updates
payloadOptions.checkoutCartUrl = cartUrl
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ import {describe, expect, vi, test} from 'vitest'
import {inTemporaryDirectory, mkdir, touchFile, writeFile} from '@shopify/cli-kit/node/fs'
import * as h3 from 'h3'
import {joinPath} from '@shopify/cli-kit/node/path'
import {isServiceAccountTokenSet} from '@shopify/cli-kit/node/session'

import type {H3Event} from 'h3'

vi.mock('@shopify/cli-kit/node/session')
vi.mock('h3', async () => {
const actual: any = await vi.importActual('h3')
return {
Expand Down Expand Up @@ -865,6 +867,128 @@ describe('getExtensionPointMiddleware()', () => {
})
})

test('explains that customer account previews need the store ID when it is unknown', async () => {
vi.mocked(isServiceAccountTokenSet).mockReturnValue(true)
const extensionId = '123abc'
const extensionPointTarget = 'customer-account.page.render'
const options = getOptions({
devOptions: {
url: 'http://mock.url',
storeId: undefined,
extensions: [
await testUIExtension({
devUUID: extensionId,
configuration: {
name: 'testName',
type: 'ui_extension',
metafields: [],
extension_points: [
{
target: extensionPointTarget,
},
],
},
}),
],
},
})

const event = getMockEvent({
params: {
extensionId,
extensionPointTarget,
},
})

await getExtensionPointMiddleware(options)(event)

expect(utilities.sendError).toHaveBeenCalledWith(event, {
statusCode: 404,
statusMessage: `Can't preview extension with id ${extensionId} and extension target "${extensionPointTarget}": customer account previews need the store's ID, which dev can't look up with SHOPIFY_SERVICE_ACCOUNT_TOKEN`,
})
})

test('does not blame the service account token when the store of a user has no ID', async () => {
vi.mocked(isServiceAccountTokenSet).mockReturnValue(false)
const extensionId = '123abc'
const extensionPointTarget = 'customer-account.page.render'
const options = getOptions({
devOptions: {
url: 'http://mock.url',
storeId: undefined,
extensions: [
await testUIExtension({
devUUID: extensionId,
configuration: {
name: 'testName',
type: 'ui_extension',
metafields: [],
extension_points: [
{
target: extensionPointTarget,
},
],
},
}),
],
},
})

const event = getMockEvent({
params: {
extensionId,
extensionPointTarget,
},
})

await getExtensionPointMiddleware(options)(event)

expect(utilities.sendError).toHaveBeenCalledWith(event, {
statusCode: 404,
statusMessage: `Can't preview extension with id ${extensionId} and extension target "${extensionPointTarget}": customer account previews need the store's ID, which dev could not find`,
})
})

test('explains that checkout previews need a cart when there is no cart URL', async () => {
const extensionId = '123abc'
const extensionPointTarget = 'purchase.checkout.block.render'
const options = getOptions({
devOptions: {
url: 'http://mock.url',
storeFqdn: 'example.myshopify.com',
extensions: [
await testUIExtension({
devUUID: extensionId,
configuration: {
name: 'testName',
type: 'ui_extension',
metafields: [],
extension_points: [
{
target: extensionPointTarget,
},
],
},
}),
],
},
})

const event = getMockEvent({
params: {
extensionId,
extensionPointTarget,
},
})

await getExtensionPointMiddleware(options)(event)

expect(utilities.sendError).toHaveBeenCalledWith(event, {
statusCode: 404,
statusMessage: `Can't preview extension with id ${extensionId} and extension target "${extensionPointTarget}" without a cart. Restart dev with --checkout-cart-url, in the format "/cart/{productVariantID}:{productQuantity}"`,
})
})

test('returns the redirect URL if the requested extension target is configured', async () => {
vi.spyOn(utilities, 'getRedirectUrl').mockReturnValue('http://www.mock.com/redirect/url')

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import {getExtensionPointRedirectUrl, getExtensionUrl, getRedirectUrl, sendError} from './utilities.js'
import {GetExtensionsMiddlewareOptions} from './models.js'
import {getUIExtensionPayload, SOURCE_MAP_SUFFIX} from '../payload.js'
import {getExtensionPointTargetSurface} from '../utilities.js'
import {getHTML} from '../templates.js'
import {getWebSocketUrl} from '../../extension.js'
import {resolveOutputDir} from '../../../build/steps/include-assets/generate-manifest.js'
import {fileExists, isDirectory, readFile} from '@shopify/cli-kit/node/fs'
import {sendRedirect, defineEventHandler, getRequestHeader, getRouterParams, setResponseHeader} from 'h3'
import {joinPath, resolvePath, isSubpath, extname} from '@shopify/cli-kit/node/path'
import {outputDebug} from '@shopify/cli-kit/node/output'
import {isServiceAccountTokenSet} from '@shopify/cli-kit/node/session'

import type {H3Event} from 'h3'

Expand Down Expand Up @@ -207,10 +209,29 @@ export function getExtensionPointMiddleware({devOptions, getExtensions}: GetExte
if (!url) {
return sendError(event, {
statusCode: 404,
statusMessage: `Redirect url can't be constructed for extension with id ${extensionID} and extension target "${requestedTarget}"`,
statusMessage: missingRedirectUrlMessage(extensionID, requestedTarget, devOptions),
})
}

return sendRedirect(event, url, 307)
})
}

function missingRedirectUrlMessage(
extensionID: string | undefined,
requestedTarget: string,
devOptions: GetExtensionsMiddlewareOptions['devOptions'],
) {
const target = `extension with id ${extensionID} and extension target "${requestedTarget}"`
const surface = getExtensionPointTargetSurface(requestedTarget)
if ((surface === 'checkout' || surface === 'post_purchase') && !devOptions.checkoutCartUrl) {
return `Can't preview ${target} without a cart. Restart dev with --checkout-cart-url, in the format "/cart/{productVariantID}:{productQuantity}"`
}
if (surface === 'customer-accounts' && !devOptions.storeId) {
const reason = isServiceAccountTokenSet()
? ", which dev can't look up with SHOPIFY_SERVICE_ACCOUNT_TOKEN"
: ', which dev could not find'
return `Can't preview ${target}: customer account previews need the store's ID${reason}`
}
return `Redirect url can't be constructed for ${target}`
}
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,38 @@ describe('getExtensionPointRedirectUrl()', () => {
)
})

test('returns undefined for a customer account target when the store ID is unknown', () => {
const extension = {
devUUID: '123abc',
} as ExtensionInstance

const options = {
storeFqdn: 'example.myshopify.com',
storeId: undefined,
url: 'https://localhost:8081',
id: 123,
} as unknown as ExtensionsPayloadStoreOptions

expect(getExtensionPointRedirectUrl('customer-account.page.render', extension, options)).toBeUndefined()
})

test('returns undefined for checkout and post-purchase targets when there is no cart URL', () => {
const extension = {
devUUID: '123abc',
localIdentifier: 'checkout-extension',
configuration: {},
} as ExtensionInstance

const options = {
storeFqdn: 'example.myshopify.com',
url: 'https://localhost:8081',
apiKey: 'api-key',
} as unknown as ExtensionsPayloadStoreOptions

expect(getExtensionPointRedirectUrl('purchase.checkout.block.render', extension, options)).toBeUndefined()
expect(getExtensionPointRedirectUrl('purchase.post.render', extension, options)).toBeUndefined()
})

test('returns undefined if the extension point surface is not supported', () => {
const extension = {
devUUID: '123abc',
Expand Down
Loading
Loading