-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathserver.ts
More file actions
305 lines (268 loc) · 9.9 KB
/
server.ts
File metadata and controls
305 lines (268 loc) · 9.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import {defaultQuery, graphiqlTemplate} from './templates/graphiql.js'
import {unauthorizedTemplate} from './templates/unauthorized.js'
import {filterCustomHeaders} from './utilities.js'
import {performActionWithRetryAfterRecovery} from '../../common/retry.js'
import {CLI_KIT_VERSION} from '../../common/version.js'
import {AbortError} from '../error.js'
import {adminUrl, supportedApiVersions} from '../api/admin.js'
import {fetch} from '../http.js'
import {renderLiquidTemplate} from '../liquid.js'
import {outputDebug} from '../output.js'
import {
createApp,
createRouter,
defineEventHandler,
getQuery,
getRequestHeader,
getRequestHeaders,
readBody,
setResponseHeader,
setResponseStatus,
toNodeListener,
} from 'h3'
import {createHmac} from 'crypto'
import {createServer, Server} from 'http'
import {readFileSync} from 'fs'
import {Writable} from 'stream'
import {createRequire} from 'module'
/**
* Derives a deterministic GraphiQL authentication key from the app's API secret and store FQDN.
* The key is stable across dev server restarts (so browser tabs survive restarts)
* but is not guessable without the app secret.
*
* @param apiSecret - The Partners app's client secret used as the HMAC key.
* @param storeFqdn - The myshopify.com domain the GraphiQL session targets.
* @returns A 64-character hex string suitable for use as the `?key=` query param.
*/
export function deriveGraphiQLKey(apiSecret: string, storeFqdn: string): string {
return createHmac('sha256', apiSecret).update(`graphiql:${storeFqdn}`).digest('hex')
}
/**
* Resolves the GraphiQL authentication key. Uses the explicitly provided key
* if non-empty, otherwise derives one deterministically from the app secret.
*
* @param providedKey - An explicit key supplied by the caller; takes precedence when non-empty.
* @param apiSecret - The Partners app's client secret, used to derive a stable key as a fallback.
* @param storeFqdn - The myshopify.com domain the GraphiQL session targets.
* @returns The resolved key.
*/
export function resolveGraphiQLKey(providedKey: string | undefined, apiSecret: string, storeFqdn: string): string {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- intentional: empty string after trim should fall through to deriveGraphiQLKey
return providedKey?.trim() || deriveGraphiQLKey(apiSecret, storeFqdn)
}
const require = createRequire(import.meta.url)
class TokenRefreshError extends AbortError {
constructor() {
super('Failed to refresh credentials. Check that your app is installed, and try again.')
}
}
interface SetupGraphiQLServerOptions {
stdout: Writable
port: number
appName: string
appUrl: string
apiKey: string
apiSecret: string
key?: string
storeFqdn: string
}
/**
* Starts a local HTTP server that hosts the GraphiQL UI and proxies requests to the
* Admin API for the configured store. The server uses the OAuth `client_credentials`
* grant with the supplied `apiKey` / `apiSecret` to mint and refresh access tokens
* on the fly.
*
* @param options - Configuration for the server, including the target store, the
* Partners app credentials, and the local port to bind to.
* @returns The underlying Node `http.Server` instance, already listening on `options.port`.
*/
export function setupGraphiQLServer(options: SetupGraphiQLServerOptions): Server {
const {stdout, port, appName, appUrl, apiKey, apiSecret, key: providedKey, storeFqdn} = options
// Always require an authentication key. If not explicitly provided, derive one
// deterministically from apiSecret + storeFqdn so the key is stable across restarts
// (browser tabs survive dev server restarts) but not guessable without the app secret.
const key = resolveGraphiQLKey(providedKey, apiSecret, storeFqdn)
outputDebug(`Setting up GraphiQL HTTP server on port ${port}...`, stdout)
const app = createApp()
const router = createRouter()
let _token: string | undefined
async function token(): Promise<string> {
// eslint-disable-next-line require-atomic-updates
_token ??= await refreshToken()
return _token
}
async function refreshToken(): Promise<string> {
try {
outputDebug('refreshing token', stdout)
_token = undefined
const bodyData = {
client_id: apiKey,
client_secret: apiSecret,
grant_type: 'client_credentials',
}
const tokenResponse = await fetch(`https://${storeFqdn}/admin/oauth/access_token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(bodyData),
})
const tokenJson = (await tokenResponse.json()) as {access_token: string}
return tokenJson.access_token
} catch (_error) {
throw new TokenRefreshError()
}
}
async function fetchApiVersionsWithTokenRefresh(): Promise<string[]> {
return performActionWithRetryAfterRecovery(
async () => supportedApiVersions({storeFqdn, token: await token()}),
refreshToken,
)
}
const faviconPath = require.resolve('@shopify/cli-kit/assets/graphiql/favicon.ico')
const faviconContent = readFileSync(faviconPath)
const stylePath = require.resolve('@shopify/cli-kit/assets/graphiql/style.css')
const styleContent = readFileSync(stylePath, 'utf8')
app.use(
defineEventHandler((event) => {
setResponseHeader(event, 'Access-Control-Allow-Origin', '*')
setResponseHeader(event, 'Access-Control-Allow-Methods', 'GET, OPTIONS')
setResponseHeader(
event,
'Access-Control-Allow-Headers',
'Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, ngrok-skip-browser-warning',
)
}),
)
router.get(
'/graphiql/ping',
defineEventHandler(() => 'pong'),
)
router.get(
'/graphiql/favicon.ico',
defineEventHandler((event) => {
setResponseHeader(event, 'Content-Type', 'image/x-icon')
return faviconContent
}),
)
router.get(
'/graphiql/simple.css',
defineEventHandler((event) => {
setResponseHeader(event, 'Content-Type', 'text/css')
return styleContent
}),
)
router.get(
'/graphiql/status',
defineEventHandler(async () => {
try {
await fetchApiVersionsWithTokenRefresh()
return {status: 'OK', storeFqdn, appName, appUrl}
// eslint-disable-next-line no-catch-all/no-catch-all
} catch {
return {status: 'UNAUTHENTICATED'}
}
}),
)
router.get(
'/graphiql',
defineEventHandler(async (event) => {
outputDebug('Handling /graphiql request', stdout)
const query = getQuery(event)
if (key && query.key !== key) {
setResponseStatus(event, 404)
return `Invalid path ${event.path}`
}
const forwardedProto = getRequestHeader(event, 'x-forwarded-proto')
const usesHttps = forwardedProto === 'https'
const host = getRequestHeader(event, 'host')
const url = `http${usesHttps ? 's' : ''}://${host}`
let apiVersions: string[]
try {
apiVersions = await fetchApiVersionsWithTokenRefresh()
} catch (err) {
if (err instanceof TokenRefreshError) {
return renderLiquidTemplate(unauthorizedTemplate, {
previewUrl: appUrl,
url,
})
}
throw err
}
const apiVersion = apiVersions.sort().reverse()[0]!
function decodeQueryString(input: string | undefined) {
return input ? decodeURIComponent(input).replace(/\n/g, '\\n') : undefined
}
const queryParam = decodeQueryString(query.query as string | undefined)
const variables = decodeQueryString(query.variables as string | undefined)
return renderLiquidTemplate(
graphiqlTemplate({
apiVersion,
apiVersions: [...apiVersions, 'unstable'],
appName,
appUrl,
key,
storeFqdn,
}),
{
url,
defaultQueries: [{query: defaultQuery}],
query: queryParam ? JSON.stringify(queryParam) : undefined,
variables: variables ? JSON.stringify(variables) : undefined,
},
)
}),
)
router.post(
'/graphiql/graphql.json',
defineEventHandler(async (event) => {
outputDebug('Handling /graphiql/graphql.json request', stdout)
const query = getQuery(event)
if (key && query.key !== key) {
setResponseStatus(event, 404)
return `Invalid path ${event.path}`
}
const graphqlUrl = adminUrl(storeFqdn, query.api_version as string)
try {
const body = await readBody(event)
const reqBody = JSON.stringify(body)
const reqHeaders = getRequestHeaders(event)
const customHeaders = filterCustomHeaders(reqHeaders)
const runRequest = async () => {
const headers = {
...customHeaders,
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Shopify-Access-Token': await token(),
'User-Agent': `ShopifyCLIGraphiQL/${CLI_KIT_VERSION}`,
}
return fetch(graphqlUrl, {
method: 'POST',
headers,
body: reqBody,
})
}
let result = await runRequest()
if (result.status === 401) {
outputDebug('Token expired, fetching new token', stdout)
await refreshToken()
result = await runRequest()
}
setResponseHeader(event, 'Content-Type', 'application/json')
setResponseStatus(event, result.status)
return result.json()
// eslint-disable-next-line no-catch-all/no-catch-all
} catch (error: unknown) {
setResponseStatus(event, 500)
if (error instanceof Error) {
return {errors: [error.message]}
}
return {errors: ['Unknown error']}
}
}),
)
app.use(router)
const server = createServer(toNodeListener(app))
server.listen(port, 'localhost', () => stdout.write(`GraphiQL server started on port ${port}`))
return server
}