From 26549dd8e82cf1697225009c98421b50f72ada1e Mon Sep 17 00:00:00 2001 From: "shopify-build-cli[bot]" <145388831+shopify-build-cli[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:00:50 +0000 Subject: [PATCH] Update from World Published by the World mirror. World-Commit: 8c4cf21a003797927cceaa7fed1ace4dfa6a043d --- .changeset/app-dev-service-account.md | 5 + packages/app/src/cli/commands/app/dev.test.ts | 5 +- packages/app/src/cli/commands/app/dev.ts | 1 + .../app/src/cli/commands/app/dev/clean.ts | 1 + packages/app/src/cli/services/dev.ts | 6 +- .../src/cli/services/dev/extension.test.ts | 51 ++++++- .../app/src/cli/services/dev/extension.ts | 17 ++- .../dev/extension/server/middlewares.test.ts | 124 ++++++++++++++++++ .../dev/extension/server/middlewares.ts | 23 +++- .../dev/extension/server/utilities.test.ts | 32 +++++ .../dev/extension/server/utilities.ts | 15 +-- .../services/dev/extension/utilities.test.ts | 47 ++++++- .../cli/services/dev/extension/utilities.ts | 12 +- .../dev/processes/previewable-extension.ts | 2 +- .../dev/processes/setup-dev-processes.test.ts | 92 +++++++++++++ .../dev/processes/setup-dev-processes.ts | 35 +++-- .../dev/processes/theme-app-extension.test.ts | 23 +++- .../dev/processes/theme-app-extension.ts | 11 +- .../src/cli/services/store-context.test.ts | 121 +++++++++++++++++ .../app/src/cli/services/store-context.ts | 45 ++++++- 20 files changed, 626 insertions(+), 42 deletions(-) create mode 100644 .changeset/app-dev-service-account.md diff --git a/.changeset/app-dev-service-account.md b/.changeset/app-dev-service-account.md new file mode 100644 index 00000000000..ef4f30ed933 --- /dev/null +++ b/.changeset/app-dev-service-account.md @@ -0,0 +1,5 @@ +--- +'@shopify/app': minor +--- + +Run `shopify app dev --store` on a dev store with `SHOPIFY_SERVICE_ACCOUNT_TOKEN`. diff --git a/packages/app/src/cli/commands/app/dev.test.ts b/packages/app/src/cli/commands/app/dev.test.ts index 2bf7d8544a3..c931cf3cd0a 100644 --- a/packages/app/src/cli/commands/app/dev.test.ts +++ b/packages/app/src/cli/commands/app/dev.test.ts @@ -324,6 +324,7 @@ describe('app dev command', () => { forceRelink: false, userProvidedConfigName: 'prod', }) + expect(storeContext).toHaveBeenCalledWith(expect.objectContaining({devSession: true})) expect(service).toHaveBeenCalled() }) }) @@ -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'}}), ) diff --git a/packages/app/src/cli/commands/app/dev.ts b/packages/app/src/cli/commands/app/dev.ts index 55e273cdbef..6c327e33bc7 100644 --- a/packages/app/src/cli/commands/app/dev.ts +++ b/packages/app/src/cli/commands/app/dev.ts @@ -153,6 +153,7 @@ export default class Dev extends AppLinkedCommand { storeFqdn: flags.store, forceReselectStore: flags.reset, storeCreationMode: 'selection-option', + devSession: true, }) const devOptions: DevOptions = { diff --git a/packages/app/src/cli/commands/app/dev/clean.ts b/packages/app/src/cli/commands/app/dev/clean.ts index e5054492159..cc1f7a06f29 100644 --- a/packages/app/src/cli/commands/app/dev/clean.ts +++ b/packages/app/src/cli/commands/app/dev/clean.ts @@ -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}) diff --git a/packages/app/src/cli/services/dev.ts b/packages/app/src/cli/services/dev.ts index 7a9c75c05f1..50d94fa1ad0 100644 --- a/packages/app/src/cli/services/dev.ts +++ b/packages/app/src/cli/services/dev.ts @@ -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 @@ -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, @@ -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, diff --git a/packages/app/src/cli/services/dev/extension.test.ts b/packages/app/src/cli/services/dev/extension.test.ts index 56ed3a8d7be..8c62a4b4488 100644 --- a/packages/app/src/cli/services/dev/extension.test.ts +++ b/packages/app/src/cli/services/dev/extension.test.ts @@ -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() @@ -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') + }) }) diff --git a/packages/app/src/cli/services/dev/extension.ts b/packages/app/src/cli/services/dev/extension.ts index d10bfb0d835..ee57ba8ef94 100644 --- a/packages/app/src/cli/services/dev/extension.ts +++ b/packages/app/src/cli/services/dev/extension.ts @@ -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' @@ -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 @@ -162,7 +163,15 @@ export async function devUIExtensions(options: ExtensionDevOptions): Promise { const actual: any = await vi.importActual('h3') return { @@ -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') diff --git a/packages/app/src/cli/services/dev/extension/server/middlewares.ts b/packages/app/src/cli/services/dev/extension/server/middlewares.ts index 5477c00c9a4..67fded85ace 100644 --- a/packages/app/src/cli/services/dev/extension/server/middlewares.ts +++ b/packages/app/src/cli/services/dev/extension/server/middlewares.ts @@ -1,6 +1,7 @@ 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' @@ -8,6 +9,7 @@ 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' @@ -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}` +} diff --git a/packages/app/src/cli/services/dev/extension/server/utilities.test.ts b/packages/app/src/cli/services/dev/extension/server/utilities.test.ts index 10b1ba23f10..92049865ded 100644 --- a/packages/app/src/cli/services/dev/extension/server/utilities.test.ts +++ b/packages/app/src/cli/services/dev/extension/server/utilities.test.ts @@ -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', diff --git a/packages/app/src/cli/services/dev/extension/server/utilities.ts b/packages/app/src/cli/services/dev/extension/server/utilities.ts index ba6a2fce2c7..8326507f1ba 100644 --- a/packages/app/src/cli/services/dev/extension/server/utilities.ts +++ b/packages/app/src/cli/services/dev/extension/server/utilities.ts @@ -33,17 +33,14 @@ export function getExtensionPointRedirectUrl( switch (surface) { case 'checkout': - // This can never be null because we always generate it - // whenever there is an extension point targeting Checkout - - rawUrl.pathname = options.checkoutCartUrl! + // Dev builds the cart URL at startup, except for a service account's extension added while dev runs. + if (!options.checkoutCartUrl) return undefined + rawUrl.pathname = options.checkoutCartUrl rawUrl.searchParams.append('dev', `${options.url}/extensions`) break case 'post_purchase': - // This can never be null because we always generate it - // whenever there is an extension point targeting Post Purchase - - rawUrl.pathname = options.checkoutCartUrl! + if (!options.checkoutCartUrl) return undefined + rawUrl.pathname = options.checkoutCartUrl rawUrl.searchParams.set( 'script_url', @@ -69,6 +66,8 @@ export function getExtensionPointRedirectUrl( rawUrl.searchParams.append('target', requestedTarget) break case 'customer-accounts': + // The customer account URL names the store by ID, which a service account can't look up. + if (!options.storeId) return undefined rawUrl = getCustomerAccountsRedirectUrl(extension, options, requestedTarget) break default: diff --git a/packages/app/src/cli/services/dev/extension/utilities.test.ts b/packages/app/src/cli/services/dev/extension/utilities.test.ts index 7a1211a7f84..5c7c34ac094 100644 --- a/packages/app/src/cli/services/dev/extension/utilities.test.ts +++ b/packages/app/src/cli/services/dev/extension/utilities.test.ts @@ -1,5 +1,48 @@ -import {getExtensionPointTargetSurface} from './utilities.js' -import {describe, expect, test} from 'vitest' +import {buildCartURLIfNeeded, getExtensionPointTargetSurface} from './utilities.js' +import {ExtensionInstance} from '../../../models/extensions/extension-instance.js' +import {fetchProductVariant} from '../../../utilities/extensions/fetch-product-variant.js' +import {describe, expect, test, vi} from 'vitest' +import {isServiceAccountTokenSet} from '@shopify/cli-kit/node/session' + +vi.mock('../../../utilities/extensions/fetch-product-variant.js') +vi.mock('@shopify/cli-kit/node/session') + +const checkoutExtension = {shouldFetchCartUrl: () => true} as unknown as ExtensionInstance + +describe('buildCartURLIfNeeded()', () => { + test('returns the cart URL of the first product variant', async () => { + vi.mocked(fetchProductVariant).mockResolvedValue('123') + + await expect(buildCartURLIfNeeded([checkoutExtension], 'store.myshopify.com')).resolves.toBe('/cart/123:1') + }) + + test('returns the given cart URL without looking up a product', async () => { + vi.mocked(isServiceAccountTokenSet).mockReturnValue(true) + + await expect(buildCartURLIfNeeded([checkoutExtension], 'store.myshopify.com', '/cart/456:2')).resolves.toBe( + '/cart/456:2', + ) + expect(fetchProductVariant).not.toHaveBeenCalled() + }) + + test('keeps the given cart URL when no extension needs a cart yet', async () => { + const otherExtension = {shouldFetchCartUrl: () => false} as unknown as ExtensionInstance + + await expect(buildCartURLIfNeeded([otherExtension], 'store.myshopify.com', '/cart/456:2')).resolves.toBe( + '/cart/456:2', + ) + }) + + test('asks for a cart URL instead of looking up a product when a service account token is set', async () => { + vi.mocked(isServiceAccountTokenSet).mockReturnValue(true) + + await expect(buildCartURLIfNeeded([checkoutExtension], 'store.myshopify.com')).rejects.toMatchObject({ + message: "A service account can't look up a product to preview checkout UI extensions.", + tryMessage: expect.stringContaining('--checkout-cart-url'), + }) + expect(fetchProductVariant).not.toHaveBeenCalled() + }) +}) describe('getExtensionPointTargetSurface()', () => { test('returns "admin" for an Admin UI extension', async () => { diff --git a/packages/app/src/cli/services/dev/extension/utilities.ts b/packages/app/src/cli/services/dev/extension/utilities.ts index 6288f770faf..d35996a547f 100644 --- a/packages/app/src/cli/services/dev/extension/utilities.ts +++ b/packages/app/src/cli/services/dev/extension/utilities.ts @@ -1,6 +1,8 @@ import {ExtensionInstance} from '../../../models/extensions/extension-instance.js' import {fetchProductVariant} from '../../../utilities/extensions/fetch-product-variant.js' +import {AbortError} from '@shopify/cli-kit/node/error' +import {isServiceAccountTokenSet} from '@shopify/cli-kit/node/session' /** * To prepare UI Extensions targeting Checkout for dev'ing we need to retrieve a valid product variant ID @@ -8,9 +10,17 @@ import {fetchProductVariant} from '../../../utilities/extensions/fetch-product-v * @param store - The store FQDN */ export async function buildCartURLIfNeeded(extensions: ExtensionInstance[], store: string, checkoutCartUrl?: string) { + // Keep a supplied cart URL even without a checkout extension, for checkout extensions added while dev runs. + if (checkoutCartUrl) return checkoutCartUrl const hasUIExtension = extensions.filter((extension) => extension.shouldFetchCartUrl()).length > 0 if (!hasUIExtension) return undefined - if (checkoutCartUrl) return checkoutCartUrl + // Finding a product variant calls the store's Admin API, which a service account token can't do. + if (isServiceAccountTokenSet()) { + throw new AbortError( + "A service account can't look up a product to preview checkout UI extensions.", + 'Pass a cart with --checkout-cart-url, in the format "/cart/{productVariantID}:{productQuantity}".', + ) + } const variantId = await fetchProductVariant(store) return `/cart/${variantId}:1` } diff --git a/packages/app/src/cli/services/dev/processes/previewable-extension.ts b/packages/app/src/cli/services/dev/processes/previewable-extension.ts index c6e064ba1d4..c666ed9d70b 100644 --- a/packages/app/src/cli/services/dev/processes/previewable-extension.ts +++ b/packages/app/src/cli/services/dev/processes/previewable-extension.ts @@ -11,7 +11,7 @@ const MANIFEST_VERSION = '3' interface PreviewableExtensionOptions { apiKey: string storeFqdn: string - storeId: string + storeId?: string port: number pathPrefix: string cartUrl?: string diff --git a/packages/app/src/cli/services/dev/processes/setup-dev-processes.test.ts b/packages/app/src/cli/services/dev/processes/setup-dev-processes.test.ts index 19b5ad12620..902335c69aa 100644 --- a/packages/app/src/cli/services/dev/processes/setup-dev-processes.test.ts +++ b/packages/app/src/cli/services/dev/processes/setup-dev-processes.test.ts @@ -32,8 +32,13 @@ import {getEnvironmentVariables} from '@shopify/cli-kit/node/environment' import {isStorefrontPasswordProtected} from '@shopify/theme' import {fetchTheme} from '@shopify/cli-kit/node/themes/api' import {adminFqdn} from '@shopify/cli-kit/node/context/fqdn' +import {outputWarn} from '@shopify/cli-kit/node/output' vi.mock('@shopify/cli-kit/node/session.js') +vi.mock('@shopify/cli-kit/node/output', async (importOriginal) => { + const original = await importOriginal() + return {...original, outputWarn: vi.fn()} +}) vi.mock('../fetch.js') vi.mock('@shopify/cli-kit/node/environment') vi.mock('@shopify/theme') @@ -583,6 +588,93 @@ describe('setup-dev-processes', () => { }) }) + test('process list skips app polling when the store has no ID, as with a service account', async () => { + vi.mocked(getEnvironmentVariables).mockReturnValue({SHOPIFY_CLI_ENABLE_APP_LOG_POLLING: '1'}) + + const developerPlatformClient: DeveloperPlatformClient = testDeveloperPlatformClient() + const storeFqdn = 'store.myshopify.io' + const storeId = undefined + const remoteAppUpdated = true + const graphiqlPort = 1234 + const commandOptions: DevConfig['commandOptions'] = { + ...appContextResult, + subscriptionProductUrl: '/products/999999', + checkoutCartUrl: '/cart/999999:1', + theme: '1', + directory: '', + update: false, + commandConfig: new Config({root: ''}), + skipDependenciesInstallation: false, + tunnel: {mode: 'auto'}, + } + const network: DevConfig['network'] = { + proxyUrl: 'https://example.com/proxy', + proxyPort: 444, + backendPort: 111, + frontendPort: 222, + currentUrls: { + applicationUrl: 'https://example.com/application', + redirectUrlWhitelist: ['https://example.com/redirect'], + }, + } + const functionExtension = await testFunctionExtension() + const previewable = await testUIExtension({type: 'checkout_ui_extension'}) + const draftable = await testTaxCalculationExtension() + const theme = await testThemeExtensions() + const localApp = testAppWithConfig({ + config: {}, + app: { + webs: [ + { + directory: 'web', + configuration: { + roles: [WebType.Backend, WebType.Frontend], + commands: {dev: 'npm exec remix dev'}, + webhooks_path: '/webhooks', + hmr_server: { + http_paths: ['/ping'], + }, + }, + }, + ], + allExtensions: [previewable, draftable, theme, functionExtension], + }, + }) + vi.spyOn(loader, 'reloadApp').mockResolvedValue(localApp) + + const remoteApp: DevConfig['remoteApp'] = { + apiKey: 'api-key', + apiSecretKeys: [{secret: 'api-secret'}], + id: '1234', + title: 'App', + organizationId: '5678', + grantedScopes: [], + flags: [], + developerPlatformClient, + } + + const graphiqlKey = 'somekey' + + const res = await setupDevProcesses({ + localApp, + commandOptions, + network, + remoteApp, + apiSecret: 'api-secret', + remoteAppUpdated, + storeFqdn, + storeId, + developerPlatformClient, + partnerUrlsUpdated: true, + graphiqlPort, + graphiqlKey, + }) + + const appLogsProcess = res.processes.find((process) => process.type === 'app-logs-subscribe') + expect(appLogsProcess).toBeUndefined() + expect(outputWarn).toHaveBeenCalledWith("Function logs aren't streamed, because dev doesn't know the store's ID.") + }) + test('process list skips app polling when envVar is enabled but no functions are registered on the app', async () => { vi.mocked(getEnvironmentVariables).mockReturnValue({SHOPIFY_CLI_ENABLE_APP_LOG_POLLING: '1'}) diff --git a/packages/app/src/cli/services/dev/processes/setup-dev-processes.ts b/packages/app/src/cli/services/dev/processes/setup-dev-processes.ts index 473535164c0..21182af7a9c 100644 --- a/packages/app/src/cli/services/dev/processes/setup-dev-processes.ts +++ b/packages/app/src/cli/services/dev/processes/setup-dev-processes.ts @@ -23,7 +23,7 @@ import {resolveGraphiQLKey} from '@shopify/cli-kit/node/graphiql/server' import {getAvailableTCPPort} from '@shopify/cli-kit/node/tcp' import {isTruthy} from '@shopify/cli-kit/node/context/utilities' import {getEnvironmentVariables} from '@shopify/cli-kit/node/environment' -import {outputInfo} from '@shopify/cli-kit/node/output' +import {outputInfo, outputWarn} from '@shopify/cli-kit/node/output' import {adminFqdn} from '@shopify/cli-kit/node/context/fqdn' interface ProxyServerProcess extends BaseProcess<{ @@ -62,7 +62,7 @@ export interface DevConfig { remoteApp: OrganizationApp developerPlatformClient: DeveloperPlatformClient storeFqdn: string - storeId: string + storeId?: string commandOptions: DevOptions network: DevNetworkOptions partnerUrlsUpdated: boolean @@ -72,6 +72,13 @@ export interface DevConfig { apiSecret: string | undefined } +function warnAppLogsUnavailable(app: AppLinkedInterface): undefined { + if (app.allExtensions.some((extension) => extension.isFunctionExtension)) { + outputWarn("Function logs aren't streamed, because dev doesn't know the store's ID.") + } + return undefined +} + export async function setupDevProcesses({ localApp, remoteAppUpdated, @@ -194,17 +201,19 @@ export async function setupDevProcesses({ apiSecret, remoteAppUpdated, }), - await setupAppLogsPollingProcess({ - developerPlatformClient, - subscription: { - shopIds: [Number(storeId)], - apiKey, - }, - storeName: storeFqdn, - organizationId: remoteApp.organizationId, - localApp, - appWatcher, - }), + storeId === undefined + ? warnAppLogsUnavailable(reloadedApp) + : await setupAppLogsPollingProcess({ + developerPlatformClient, + subscription: { + shopIds: [Number(storeId)], + apiKey, + }, + storeName: storeFqdn, + organizationId: remoteApp.organizationId, + localApp, + appWatcher, + }), await setupAppWatcherProcess({ appWatcher, }), diff --git a/packages/app/src/cli/services/dev/processes/theme-app-extension.test.ts b/packages/app/src/cli/services/dev/processes/theme-app-extension.test.ts index 166a1322b0a..a25c13058da 100644 --- a/packages/app/src/cli/services/dev/processes/theme-app-extension.test.ts +++ b/packages/app/src/cli/services/dev/processes/theme-app-extension.test.ts @@ -7,12 +7,13 @@ import { testThemeExtensions, } from '../../../models/app/app.test-data.js' import {ClientName} from '../../../utilities/developer-platform-client.js' -import {AdminSession, ensureAuthenticatedAdmin} from '@shopify/cli-kit/node/session' +import {AdminSession, ensureAuthenticatedAdmin, isServiceAccountTokenSet} from '@shopify/cli-kit/node/session' import {fetchTheme} from '@shopify/cli-kit/node/themes/api' import {AbortError} from '@shopify/cli-kit/node/error' import {Theme} from '@shopify/cli-kit/node/themes/types' import {vi, describe, test, expect, beforeEach} from 'vitest' import {renderInfo} from '@shopify/cli-kit/node/ui' +import {outputWarn} from '@shopify/cli-kit/node/output' import {partnersFqdn, adminFqdn} from '@shopify/cli-kit/node/context/fqdn' import {ensureValidPassword, isStorefrontPasswordProtected, fetchOrCreateCrawlerSignatureHeaders} from '@shopify/theme' @@ -78,6 +79,26 @@ describe('setupPreviewThemeAppExtensionsProcess', () => { expect(result).toBeUndefined() }) + test('Returns undefined and warns when a service account token is set', async () => { + // Given + vi.mocked(isServiceAccountTokenSet).mockReturnValue(true) + const localApp = testApp({allExtensions: [await testThemeExtensions()]}) + const remoteApp = testOrganizationApp() + const storeFqdn = 'test.myshopify.com' + + // When + const result = await setupPreviewThemeAppExtensionsProcess({ + localApp, + remoteApp, + storeFqdn, + }) + + // Then + expect(result).toBeUndefined() + expect(ensureAuthenticatedAdmin).not.toHaveBeenCalled() + expect(outputWarn).toHaveBeenCalledWith(expect.stringContaining('SHOPIFY_SERVICE_ACCOUNT_TOKEN')) + }) + test('Returns PreviewThemeAppExtensionsOptions if theme extensions are present - Partners API app', async () => { // Given const mockTheme = {id: 123} as Theme diff --git a/packages/app/src/cli/services/dev/processes/theme-app-extension.ts b/packages/app/src/cli/services/dev/processes/theme-app-extension.ts index d4065b78d90..94729044171 100644 --- a/packages/app/src/cli/services/dev/processes/theme-app-extension.ts +++ b/packages/app/src/cli/services/dev/processes/theme-app-extension.ts @@ -3,8 +3,8 @@ import {HostThemeManager} from '../../../utilities/extensions/theme/host-theme-m import {AppInterface} from '../../../models/app/app.js' import {OrganizationApp} from '../../../models/organization.js' import {ClientName} from '../../../utilities/developer-platform-client.js' -import {outputDebug} from '@shopify/cli-kit/node/output' -import {AdminSession, ensureAuthenticatedAdmin} from '@shopify/cli-kit/node/session' +import {outputDebug, outputWarn} from '@shopify/cli-kit/node/output' +import {AdminSession, ensureAuthenticatedAdmin, isServiceAccountTokenSet} from '@shopify/cli-kit/node/session' import {fetchTheme} from '@shopify/cli-kit/node/themes/api' import {AbortError} from '@shopify/cli-kit/node/error' import {Theme} from '@shopify/cli-kit/node/themes/types' @@ -49,6 +49,13 @@ export async function setupPreviewThemeAppExtensionsProcess( if (themeExtensions.length === 0) { return } + // The theme preview calls the store's Admin API, which a service account token can't do. + if (isServiceAccountTokenSet()) { + outputWarn( + "The theme app extension preview isn't available with SHOPIFY_SERVICE_ACCOUNT_TOKEN. Dev runs without it.", + ) + return + } const themeExtension = themeExtensions[0]! const themeExtensionDirectory = themeExtension.directory diff --git a/packages/app/src/cli/services/store-context.test.ts b/packages/app/src/cli/services/store-context.test.ts index 110abd2aa82..02cf369e045 100644 --- a/packages/app/src/cli/services/store-context.test.ts +++ b/packages/app/src/cli/services/store-context.test.ts @@ -12,6 +12,7 @@ import { import metadata from '../metadata.js' import {appHiddenConfigPath, AppLinkedInterface} from '../models/app/app.js' import {vi, describe, test, expect} from 'vitest' +import {isServiceAccountTokenSet} from '@shopify/cli-kit/node/session' import {hashString} from '@shopify/cli-kit/node/crypto' import {inTemporaryDirectory, mkdir, readFile, writeFile} from '@shopify/cli-kit/node/fs' import {joinPath} from '@shopify/cli-kit/node/path' @@ -20,6 +21,7 @@ import type {ActiveConfig} from '../models/project/active-config.js' vi.mock('./dev/fetch') vi.mock('./dev/select-store') +vi.mock('@shopify/cli-kit/node/session') describe('storeContext', () => { const mockApp = testAppLinked({ @@ -270,6 +272,125 @@ describe('storeContext', () => { expect(mockDeveloperPlatformClient.ensureUserAccessToStore).toHaveBeenCalledWith(mockOrganization.id, mockStore) }) }) + + test('builds the dev store from its domain without the organizations API when a service account token is set', async () => { + await inTemporaryDirectory(async (dir) => { + vi.mocked(isServiceAccountTokenSet).mockReturnValue(true) + await prepareAppFolder(mockApp, dir) + + const result = await storeContext({ + appContextResult, + storeFqdn: 'https://Explicit-Store.myshopify.com', + forceReselectStore: false, + devSession: true, + }) + + expect(result).toEqual({ + shopId: '', + link: '', + shopDomain: 'explicit-store.myshopify.com', + shopName: 'explicit-store.myshopify.com', + transferDisabled: true, + convertableToPartnerTest: false, + provisionable: false, + }) + expect(fetchStore).not.toHaveBeenCalled() + expect(mockDeveloperPlatformClient.devStoresForOrg).not.toHaveBeenCalled() + expect(mockDeveloperPlatformClient.ensureUserAccessToStore).not.toHaveBeenCalled() + }) + }) + + test('keeps the saved dev store when a service account passes a store that is not checked yet', async () => { + await inTemporaryDirectory(async (dir) => { + vi.mocked(isServiceAccountTokenSet).mockReturnValue(true) + await prepareAppFolder(mockApp, dir) + await writeFile( + appHiddenConfigPath(dir), + JSON.stringify({client_id: {dev_store_url: 'cached-store.myshopify.com'}}), + ) + + await storeContext({ + appContextResult, + storeFqdn: 'typoo.myshopify.com', + forceReselectStore: false, + devSession: true, + }) + + const hiddenConfig = await readFile(appHiddenConfigPath(dir)) + expect(hiddenConfig).toContain('"dev_store_url":"cached-store.myshopify.com"') + expect(hiddenConfig).not.toContain('typoo') + }) + }) + + test('asks for a dev store when a service account token is set and no store is given', async () => { + vi.mocked(isServiceAccountTokenSet).mockReturnValue(true) + const appWithoutStore = testAppLinked({ + configuration: {client_id: 'client_id', name: 'app-config-name'} as any, + hiddenConfig: {}, + }) + + await expect( + storeContext({ + appContextResult: {...appContextResult, app: appWithoutStore}, + forceReselectStore: false, + devSession: true, + }), + ).rejects.toMatchObject({ + message: 'A service account needs a dev store to run this command.', + tryMessage: expect.stringContaining('--store'), + }) + expect(mockDeveloperPlatformClient.devStoresForOrg).not.toHaveBeenCalled() + }) + + test('uses the cached dev_store_url without the organizations API when a service account token is set', async () => { + await inTemporaryDirectory(async (dir) => { + vi.mocked(isServiceAccountTokenSet).mockReturnValue(true) + await prepareAppFolder(mockApp, dir) + + const result = await storeContext({appContextResult, forceReselectStore: false, devSession: true}) + + expect(result.shopDomain).toEqual('cached-store.myshopify.com') + expect(fetchStore).not.toHaveBeenCalled() + expect(mockDeveloperPlatformClient.ensureUserAccessToStore).not.toHaveBeenCalled() + }) + }) + + test('looks up the store when a service account token is set outside a dev session', async () => { + await inTemporaryDirectory(async (dir) => { + vi.mocked(isServiceAccountTokenSet).mockReturnValue(true) + vi.mocked(fetchStore).mockResolvedValue(mockStore) + await prepareAppFolder(mockApp, dir) + + const result = await storeContext({ + appContextResult, + storeFqdn: 'explicit-store.myshopify.com', + forceReselectStore: false, + }) + + expect(fetchStore).toHaveBeenCalled() + expect(ensureTransferDisabledStore).toHaveBeenCalledWith(mockStore) + expect(result).toEqual(mockStore) + }) + }) + + test('looks up the store when a service account token is set and other store types are allowed', async () => { + await inTemporaryDirectory(async (dir) => { + vi.mocked(isServiceAccountTokenSet).mockReturnValue(true) + vi.mocked(fetchStore).mockResolvedValue(mockStore) + await prepareAppFolder(mockApp, dir) + + const result = await storeContext({ + appContextResult, + storeFqdn: 'explicit-store.myshopify.com', + forceReselectStore: false, + storeTypes: ['APP_DEVELOPMENT', 'PRODUCTION'], + devSession: true, + }) + + expect(fetchStore).toHaveBeenCalled() + expect(result).toEqual(mockStore) + }) + }) }) async function prepareAppFolder(app: AppLinkedInterface, directory: string) { diff --git a/packages/app/src/cli/services/store-context.ts b/packages/app/src/cli/services/store-context.ts index 2c6bc2b06ff..9d03e703796 100644 --- a/packages/app/src/cli/services/store-context.ts +++ b/packages/app/src/cli/services/store-context.ts @@ -6,6 +6,8 @@ import {Store} from '../utilities/developer-platform-client.js' import metadata from '../metadata.js' import {hashString} from '@shopify/cli-kit/node/crypto' import {normalizeStoreFqdn} from '@shopify/cli-kit/node/context/fqdn' +import {isServiceAccountTokenSet} from '@shopify/cli-kit/node/session' +import {AbortError} from '@shopify/cli-kit/node/error' /** * Input options for the `storeContext` function. @@ -15,6 +17,8 @@ import {normalizeStoreFqdn} from '@shopify/cli-kit/node/context/fqdn' * @param storeFqdn - a store FQDN, optional, when explicitly provided it has preference over anything else. * @param storeTypes - Store types to filter by. Defaults to dev stores only. * @param storeCreationMode - When store creation is offered during store selection. Defaults to disabled. + * @param devSession - Whether the command runs a dev session, whose App Dev API checks the store. Only then can a + * service account skip the organizations API. */ interface StoreContextOptions { appContextResult: LoadedAppContextOutput @@ -22,6 +26,7 @@ interface StoreContextOptions { storeFqdn?: string storeTypes?: Store[] storeCreationMode?: StoreCreationMode + devSession?: boolean } /** @@ -30,6 +35,9 @@ interface StoreContextOptions { * If a storeFqdn is explicitly provided, it has preference over anything else. * If not, check if there is a cached storeFqdn in the app configuration. If forceReselectStore is true, it will be ignored. * If still don't have a store, fetch all stores for the organization and let the user select one. + * + * With SHOPIFY_SERVICE_ACCOUNT_TOKEN set, dev session commands need a store domain and don't look the store up or + * provision access to it: the organizations API only serves user accounts, and the App Dev API checks the store. */ export async function storeContext({ appContextResult, @@ -37,6 +45,7 @@ export async function storeContext({ forceReselectStore, storeTypes = ['APP_DEVELOPMENT'], storeCreationMode = 'disabled', + devSession = false, }: StoreContextOptions): Promise { const {app, organization, developerPlatformClient} = appContextResult let selectedStore: OrganizationStore @@ -55,7 +64,11 @@ export async function storeContext({ // Check if we're filtering to dev stores only const isDevStoresOnly = storeTypes.length === 1 && storeTypes[0] === 'APP_DEVELOPMENT' - if (storeFqdnToUse) { + const skipsOrganizationApi = devSession && isDevStoresOnly && isServiceAccountTokenSet() + + if (skipsOrganizationApi) { + selectedStore = serviceAccountStore(storeFqdnToUse) + } else if (storeFqdnToUse) { selectedStore = await fetchStore(organization, storeFqdnToUse, developerPlatformClient, storeTypes) if (isDevStoresOnly) { ensureTransferDisabledStore(selectedStore) @@ -69,17 +82,41 @@ export async function storeContext({ selectedStore.shopDomain = normalizeStoreFqdn(selectedStore.shopDomain) await logMetadata(selectedStore, forceReselectStore) - // Save the selected store in the hidden config file - if (selectedStore.shopDomain !== cachedStoreURL || !devStoreUrlFromHiddenConfig) { + // Save the selected store in the hidden config file. A service account's store isn't checked until the dev session + // starts, so saving it here could replace a working store with a mistyped one. + if (!skipsOrganizationApi && (selectedStore.shopDomain !== cachedStoreURL || !devStoreUrlFromHiddenConfig)) { await app.updateHiddenConfig({dev_store_url: selectedStore.shopDomain}) } // Ensure that the user is able to login to the store and install apps - await developerPlatformClient.ensureUserAccessToStore(organization.id, selectedStore) + if (!skipsOrganizationApi) { + await developerPlatformClient.ensureUserAccessToStore(organization.id, selectedStore) + } return selectedStore } +function serviceAccountStore(storeFqdn: string | undefined): OrganizationStore { + if (!storeFqdn) { + throw new AbortError( + 'A service account needs a dev store to run this command.', + 'Pass the dev store with --store, or set build.dev_store_url in the app configuration.', + ) + } + const shopDomain = normalizeStoreFqdn(storeFqdn) + // The store's ID comes from the organizations API, so it's unknown here. Dev skips what needs it: app logs, and + // customer account extension previews. + return { + shopId: '', + link: '', + shopDomain, + shopName: shopDomain, + transferDisabled: true, + convertableToPartnerTest: false, + provisionable: false, + } +} + async function logMetadata(selectedStore: OrganizationStore, resetUsed: boolean) { await metadata.addPublicMetadata(() => ({ cmd_app_reset_used: resetUsed,