|
| 1 | +import Shopify, { DataType, OnlineAccessResponse } from "@shopify/shopify-api"; |
| 2 | +import { HttpResponseError } from "@shopify/shopify-api/dist/error"; |
| 3 | +import { Session } from "@shopify/shopify-api/dist/auth/session"; |
| 4 | + |
| 5 | +import { createSession } from "./session"; |
| 6 | + |
| 7 | +// Cache object with current requests so we can avoid making the same request multiple times. |
| 8 | +// The key is in the format `{shop}:{tokenType}:{encodedSessionToken}:{saveSession}` and the value is the promise of the request. |
| 9 | +const currentTokenExchangeRequests = new Map<string, Promise<Session>>(); |
| 10 | + |
| 11 | +/** Given the shop, encoded JWT session token, and token type, return a session object with an access token. |
| 12 | + https://shopify.dev/docs/apps/auth/get-access-tokens/token-exchange |
| 13 | +
|
| 14 | + The request will be de-duplicated, so if multiple requests are made at once with the same shop, token and token type, only one request will be made. |
| 15 | +
|
| 16 | + @param shop The shop's myshopify domain |
| 17 | + @param encodedSessionToken The encoded JWT session token |
| 18 | + @param tokenType The type of access token to exchange for ('online' or 'offline') |
| 19 | + @param saveSession If true, the new session will be saved to storage (default) |
| 20 | +
|
| 21 | + @returns The new session object |
| 22 | + */ |
| 23 | +export async function exchangeSessionTokenForAccessTokenSession( |
| 24 | + shop: string, |
| 25 | + encodedSessionToken: string, |
| 26 | + tokenType: "online" | "offline", |
| 27 | + saveSession = true // If true, the new session will be saved to storage |
| 28 | +) { |
| 29 | + // Check if we already have a request in progress |
| 30 | + const key = `${shop}:${tokenType}:${encodedSessionToken}:${saveSession}`; |
| 31 | + const existingRequest = currentTokenExchangeRequests.get(key); |
| 32 | + if (existingRequest) return existingRequest; // If we already have a request in progress, use it |
| 33 | + |
| 34 | + // Otherwise make the request with a timeout |
| 35 | + const requestOrTimeout = Promise.race([ |
| 36 | + makeTokenExchangeRequest({ shop, encodedSessionToken, tokenType, saveSession }), |
| 37 | + new Promise<Session>((resolve, reject) => |
| 38 | + setTimeout(() => reject(new Error("Request timed out")), 10000) |
| 39 | + ), |
| 40 | + ]); |
| 41 | + |
| 42 | + // Save the request to the cache |
| 43 | + currentTokenExchangeRequests.set(key, requestOrTimeout); |
| 44 | + |
| 45 | + // When the request is done, remove it from the cache |
| 46 | + requestOrTimeout.finally(() => { |
| 47 | + currentTokenExchangeRequests.delete(key); |
| 48 | + }); |
| 49 | + |
| 50 | + return requestOrTimeout; |
| 51 | +} |
| 52 | + |
| 53 | +// Internal function that makes the request to Shopify to exchange the session token for an access token. The main function is a wrapper around this one that implements de-duplicating the requests. |
| 54 | +async function makeTokenExchangeRequest(params: { |
| 55 | + shop: string; |
| 56 | + encodedSessionToken: string; |
| 57 | + tokenType: "online" | "offline"; |
| 58 | + saveSession: boolean; |
| 59 | +}) { |
| 60 | + const { shop, encodedSessionToken, tokenType, saveSession } = params; |
| 61 | + |
| 62 | + const sanitizedShop = Shopify.Utils.sanitizeShop(shop, true); |
| 63 | + |
| 64 | + // Construct the request body |
| 65 | + const body = { |
| 66 | + client_id: Shopify.Context.API_KEY, |
| 67 | + client_secret: Shopify.Context.API_SECRET_KEY, |
| 68 | + grant_type: "urn:ietf:params:oauth:grant-type:token-exchange", |
| 69 | + subject_token: encodedSessionToken, |
| 70 | + subject_token_type: "urn:ietf:params:oauth:token-type:id_token", |
| 71 | + requested_token_type: `urn:shopify:params:oauth:token-type:${tokenType}-access-token`, |
| 72 | + }; |
| 73 | + |
| 74 | + // Make the request |
| 75 | + const response = await fetch(`https://${sanitizedShop}/admin/oauth/access_token`, { |
| 76 | + method: "POST", |
| 77 | + headers: { "Content-Type": DataType.JSON, Accept: DataType.JSON }, |
| 78 | + body: JSON.stringify(body), |
| 79 | + }); |
| 80 | + |
| 81 | + // Check the response for errors |
| 82 | + if (!response.ok) { |
| 83 | + const { status, statusText, headers } = response; |
| 84 | + throw new HttpResponseError({ |
| 85 | + message: `Failed to exchange session token for access token: ${status} ${statusText}`, |
| 86 | + code: status, |
| 87 | + statusText, |
| 88 | + body, |
| 89 | + headers: headers as any, |
| 90 | + }); |
| 91 | + } |
| 92 | + |
| 93 | + // Parse the response |
| 94 | + const sessionResponse: OnlineAccessResponse = await response.json(); |
| 95 | + |
| 96 | + // Create the session |
| 97 | + const session = createSession(sessionResponse, shop); |
| 98 | + |
| 99 | + // Make sure the session is active |
| 100 | + if (!session.isActive()) { |
| 101 | + throw new Error( |
| 102 | + `The session '${session?.id}' we just got from Shopify is not active for shop '${shop}'` |
| 103 | + ); |
| 104 | + } |
| 105 | + |
| 106 | + // Save the session to storage if requested |
| 107 | + if (saveSession) await Shopify.Utils.storeSession(session); |
| 108 | + |
| 109 | + return session; |
| 110 | +} |
0 commit comments