-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathsession.ts
More file actions
373 lines (347 loc) · 12.8 KB
/
Copy pathsession.ts
File metadata and controls
373 lines (347 loc) · 12.8 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import {shopifyFetch} from './http.js'
import {nonRandomUUID} from './crypto.js'
import {getAppAutomationToken} from './environment.js'
import {AbortError, BugError} from './error.js'
import {outputContent, outputToken, outputDebug} from './output.js'
import * as sessionStore from '../../private/node/session/store.js'
import {
exchangeCustomPartnerToken,
exchangeAppAutomationTokenForAppManagementAccessToken,
exchangeAppAutomationTokenForBusinessPlatformAccessToken,
} from '../../private/node/session/exchange.js'
import {
AdminAPIScope,
AppManagementAPIScope,
BusinessPlatformScope,
EnsureAuthenticatedAdditionalOptions,
PartnersAPIScope,
StorefrontRendererScope,
ensureAuthenticated,
setLastSeenAuthMethod,
setLastSeenUserIdAfterAuth,
} from '../../private/node/session.js'
import {isThemeAccessSession} from '../../private/node/api/rest.js'
/**
* Session Object to access the Admin API, includes the token and the store FQDN.
*/
export interface AdminSession {
token: string
storeFqdn: string
}
/**
* Session Object for Partners API and App Management API access.
*/
export interface Session {
token: string
businessPlatformToken: string
accountInfo: AccountInfo
userId: string
}
export type AccountInfo = UserAccountInfo | ServiceAccountInfo | UnknownAccountInfo
/**
* Records the user ID that should be attached to command analytics for this process.
*
* @param userId - User identifier to report on the command analytics event.
*/
export function setLastSeenUserId(userId: string): void {
setLastSeenUserIdAfterAuth(userId)
}
interface UserAccountInfo {
type: 'UserAccount'
email: string
}
interface ServiceAccountInfo {
type: 'ServiceAccount'
orgName: string
}
interface UnknownAccountInfo {
type: 'UnknownAccount'
}
/**
* Type guard to check if an account is a UserAccount.
*
* @param account - The account to check.
* @returns True if the account is a UserAccount.
*/
export function isUserAccount(account: AccountInfo): account is UserAccountInfo {
return account.type === 'UserAccount'
}
/**
* Type guard to check if an account is a ServiceAccount.
*
* @param account - The account to check.
* @returns True if the account is a ServiceAccount.
*/
export function isServiceAccount(account: AccountInfo): account is ServiceAccountInfo {
return account.type === 'ServiceAccount'
}
/**
* Reports whether the CLI already has stored credentials, without prompting the
* user, opening a browser, or making any network request.
*
* This is a passive, side-effect-free check: it reads the local session store and
* returns `true` when at least one valid session is present. Unlike the
* `ensureAuthenticated*` functions, it never triggers a login flow and never logs
* the user out. Because it does not contact the network, it cannot tell whether the
* stored token is currently valid/unexpired — only that credentials exist locally.
*
* Intended for best-effort, opportunistic behaviour (for example, enriching
* telemetry only for users who are already logged in).
*
* @returns True if local credentials exist, false otherwise.
*/
export async function sessionExists(): Promise<boolean> {
const sessions = await sessionStore.fetch()
return sessions !== undefined && Object.keys(sessions).length > 0
}
/**
* Ensure that we have a valid session with no particular scopes.
*
* @param env - Optional environment variables to use.
* @param options - Optional extra options to use.
* @returns The user ID.
*/
export async function ensureAuthenticatedUser(
env = process.env,
options: EnsureAuthenticatedAdditionalOptions = {},
): Promise<{userId: string}> {
outputDebug(outputContent`Ensuring that the user is authenticated with no particular scopes`)
const tokens = await ensureAuthenticated({}, env, options)
return {userId: tokens.userId}
}
/**
* Ensure that we have a valid session to access the Partners API.
* If SHOPIFY_CLI_PARTNERS_TOKEN exists, that token will be used to obtain a valid Partners Token
* If SHOPIFY_CLI_PARTNERS_TOKEN exists, scopes will be ignored.
*
* @param scopes - Optional array of extra scopes to authenticate with.
* @param env - Optional environment variables to use.
* @param options - Optional extra options to use.
* @returns The access token for the Partners API.
*/
export async function ensureAuthenticatedPartners(
scopes: PartnersAPIScope[] = [],
env = process.env,
options: EnsureAuthenticatedAdditionalOptions = {},
): Promise<{token: string; userId: string}> {
outputDebug(outputContent`Ensuring that the user is authenticated with the Partners API with the following scopes:
${outputToken.json(scopes)}
`)
const envToken = getAppAutomationToken()
if (envToken) {
const result = await exchangeCustomPartnerToken(envToken)
return {token: result.accessToken, userId: result.userId}
}
const tokens = await ensureAuthenticated({partnersApi: {scopes}}, env, options)
if (!tokens.partners) {
throw new BugError('No partners token found after ensuring authenticated')
}
return {token: tokens.partners, userId: tokens.userId}
}
/**
* Ensure that we have a valid session to access the App Management API.
*
* @param options - Optional extra options to use.
* @param appManagementScopes - Optional array of extra scopes to authenticate with.
* @param businessPlatformScopes - Optional array of extra scopes to authenticate with.
* @param env - Optional environment variables to use.
* @returns The access token for the App Management API.
*/
export async function ensureAuthenticatedAppManagementAndBusinessPlatform(
options: EnsureAuthenticatedAdditionalOptions = {},
appManagementScopes: AppManagementAPIScope[] = [],
businessPlatformScopes: BusinessPlatformScope[] = [],
env = process.env,
): Promise<{appManagementToken: string; userId: string; businessPlatformToken: string}> {
outputDebug(outputContent`Ensuring that the user is authenticated with the App Management API with the following scopes:
${outputToken.json(appManagementScopes)}
`)
const envToken = getAppAutomationToken()
if (envToken) {
const appManagmentToken = await exchangeAppAutomationTokenForAppManagementAccessToken(envToken)
const businessPlatformToken = await exchangeAppAutomationTokenForBusinessPlatformAccessToken(envToken)
return {
appManagementToken: appManagmentToken.accessToken,
userId: appManagmentToken.userId,
businessPlatformToken: businessPlatformToken.accessToken,
}
}
const tokens = await ensureAuthenticated(
{appManagementApi: {scopes: appManagementScopes}, businessPlatformApi: {scopes: businessPlatformScopes}},
env,
options,
)
if (!tokens.appManagement || !tokens.businessPlatform) {
throw new BugError('No App Management or Business Platform token found after ensuring authenticated')
}
return {
appManagementToken: tokens.appManagement,
userId: tokens.userId,
businessPlatformToken: tokens.businessPlatform,
}
}
/**
* Ensure that we have a valid session to access the Storefront API.
*
* @param scopes - Optional array of extra scopes to authenticate with.
* @param password - Optional password to use.
* @param options - Optional extra options to use.
* @returns The access token for the Storefront API.
*/
export async function ensureAuthenticatedStorefront(
scopes: StorefrontRendererScope[] = [],
password: string | undefined = undefined,
options: EnsureAuthenticatedAdditionalOptions = {},
): Promise<string> {
if (password) {
const session = {token: password, storeFqdn: ''}
const authMethod = isThemeAccessSession(session) ? 'theme_access_token' : 'custom_app_token'
setLastSeenAuthMethod(authMethod)
setLastSeenUserIdAfterAuth(nonRandomUUID(password))
return password
}
outputDebug(outputContent`Ensuring that the user is authenticated with the Storefront API with the following scopes:
${outputToken.json(scopes)}
`)
const tokens = await ensureAuthenticated({storefrontRendererApi: {scopes}}, process.env, options)
if (!tokens.storefront) {
throw new BugError('No storefront token found after ensuring authenticated')
}
return tokens.storefront
}
/**
* Ensure that we have a valid Admin session for the given store.
*
* @param store - Store fqdn to request auth for.
* @param scopes - Optional array of extra scopes to authenticate with.
* @param options - Optional extra options to use.
* @returns The access token for the Admin API.
*/
export async function ensureAuthenticatedAdmin(
store: string,
scopes: AdminAPIScope[] = [],
options: EnsureAuthenticatedAdditionalOptions = {},
): Promise<AdminSession> {
outputDebug(outputContent`Ensuring that the user is authenticated with the Admin API with the following scopes for the store ${outputToken.raw(
store,
)}:
${outputToken.json(scopes)}
`)
const tokens = await ensureAuthenticated({adminApi: {scopes, storeFqdn: store}}, process.env, {
...options,
})
if (!tokens.admin) {
throw new BugError('No admin token found after ensuring authenticated')
}
return tokens.admin
}
/**
* Ensure that we have a valid session to access the Theme API.
* If a password is provided, that token will be used against Theme Access API.
* Otherwise, it will ensure that the user is authenticated with the Admin API.
*
* @param store - Store fqdn to request auth for.
* @param password - Password generated from Theme Access app.
* @param scopes - Optional array of extra scopes to authenticate with.
* @param options - Optional extra options to use.
* @returns The access token and store.
*/
export async function ensureAuthenticatedThemes(
store: string,
password: string | undefined,
scopes: AdminAPIScope[] = [],
options: EnsureAuthenticatedAdditionalOptions = {},
): Promise<AdminSession> {
outputDebug(outputContent`Ensuring that the user is authenticated with the Theme API with the following scopes:
${outputToken.json(scopes)}
`)
if (password) {
const session = {token: password, storeFqdn: store}
const authMethod = isThemeAccessSession(session) ? 'theme_access_token' : 'custom_app_token'
setLastSeenAuthMethod(authMethod)
setLastSeenUserIdAfterAuth(nonRandomUUID(password))
return session
}
return ensureAuthenticatedAdmin(store, scopes, options)
}
/**
* Ensure that we have a valid session to access the Business Platform API.
*
* @param scopes - Optional array of extra scopes to authenticate with.
* @returns The access token for the Business Platform API.
*/
export async function ensureAuthenticatedBusinessPlatform(scopes: BusinessPlatformScope[] = []): Promise<string> {
outputDebug(outputContent`Ensuring that the user is authenticated with the Business Platform API with the following scopes:
${outputToken.json(scopes)}
`)
const tokens = await ensureAuthenticated({businessPlatformApi: {scopes}}, process.env)
if (!tokens.businessPlatform) {
throw new BugError('No business-platform token found after ensuring authenticated')
}
return tokens.businessPlatform
}
/**
* Logout from Shopify.
*
* @returns A promise that resolves when the logout is complete.
*/
export function logout(): Promise<void> {
return sessionStore.remove()
}
/**
* Ensure that we have a valid Admin session for the given store, with access on behalf of the app.
*
* See `ensureAuthenticatedAdmin` for access on behalf of a user.
*
* @param storeFqdn - Store fqdn to request auth for.
* @param clientId - Client ID of the app.
* @param clientSecret - Client secret of the app.
* @returns The access token for the Admin API.
*/
export async function ensureAuthenticatedAdminAsApp(
storeFqdn: string,
clientId: string,
clientSecret: string,
): Promise<AdminSession> {
const bodyData = {
client_id: clientId,
client_secret: clientSecret,
grant_type: 'client_credentials',
}
const tokenResponse = await shopifyFetch(
`https://${storeFqdn}/admin/oauth/access_token`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(bodyData),
},
'slow-request',
)
const body = await tokenResponse.text()
if (tokenResponse.status === 400) {
if (body.includes('app_not_installed')) {
throw new AbortError(
outputContent`App is not installed on ${outputToken.green(
storeFqdn,
)}. Try running ${outputToken.genericShellCommand(`shopify app dev`)} to connect your app to the shop.`,
)
}
throw new AbortError(
`Failed to get access token for app ${clientId} on store ${storeFqdn}: ${tokenResponse.statusText}`,
)
}
try {
const tokenJson = JSON.parse(body) as {access_token: string}
return {token: tokenJson.access_token, storeFqdn}
} catch (error) {
if (error instanceof SyntaxError) {
throw new AbortError(
`Received invalid response from admin authentication service (HTTP ${tokenResponse.status}).`,
'The response could not be parsed as JSON. The service may be temporarily unavailable. Please try again.',
)
}
throw error
}
}