From 9668f7d4fdab886fa034bf0c25f26a787e956a1f Mon Sep 17 00:00:00 2001 From: Marten Klitzke Date: Thu, 19 Nov 2026 00:03:12 +0100 Subject: [PATCH] feat(rsi): add store SKUs, upgrades and buy-backs to the RSI cart --- __tests__/cart.test.ts | 221 ++++++++++++++++++++++++++++++ __tests__/message-handler.test.ts | 1 + lib/cart.ts | 187 +++++++++++++++++++++++++ lib/message-handler.ts | 27 ++++ lib/rsi.ts | 100 ++++++++++++++ 5 files changed, 536 insertions(+) create mode 100644 __tests__/cart.test.ts create mode 100644 lib/cart.ts diff --git a/__tests__/cart.test.ts b/__tests__/cart.test.ts new file mode 100644 index 0000000..8301b37 --- /dev/null +++ b/__tests__/cart.test.ts @@ -0,0 +1,221 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { addToCart, parseCartItems, parseCsrfToken } from "@/lib/cart"; +import { onMessage } from "@/lib/message-handler"; + +const CART_PAGE = ''; + +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); + +// Answers by path, and records each request's path, headers and body. +function mockRsi(routes: Record Response>) { + const calls: { path: string; headers: Record; body: any }[] = []; + + vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const path = new URL(String(input)).pathname; + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + calls.push({ path, headers: (init?.headers ?? {}) as Record, body }); + + if (path === "/en/store/pledge/cart") return new Response(CART_PAGE); + const route = routes[path]; + if (!route) throw new Error(`unexpected request to ${path}`); + + return route(body); + }); + + return calls; +} + +beforeEach(() => { + vi.restoreAllMocks(); +}); + +describe("parseCartItems", () => { + it("reads every kind, ids given as strings or numbers", () => { + expect( + parseCartItems([ + { id: "a", kind: "sku", skuId: "17402" }, + { id: "b", kind: "upgrade", fromShipId: 271, toShipId: 103, toSkuId: 13053 }, + { id: "c", kind: "upgrade", fromShipId: 56, toShipId: 329, toSkuId: 19753, pledgeId: "115843848" }, + { id: "d", kind: "buyback", pledgeId: "115575665" }, + ]) + ).toEqual([ + { id: "a", kind: "sku", skuId: 17402, qty: 1 }, + { id: "b", kind: "upgrade", fromShipId: 271, toShipId: 103, toSkuId: 13053, pledgeId: null }, + { id: "c", kind: "upgrade", fromShipId: 56, toShipId: 329, toSkuId: 19753, pledgeId: 115843848 }, + { id: "d", kind: "buyback", pledgeId: 115575665 }, + ]); + }); + + it("refuses anything but plain ids", () => { + expect(parseCartItems([{ id: "a", kind: "sku", skuId: "1/../2" }])).toBeNull(); + expect(parseCartItems([{ id: "a", kind: "buyback", pledgeId: "https://x" }])).toBeNull(); + expect(parseCartItems([{ id: "a", kind: "upgrade", fromShipId: 1, toShipId: 2 }])).toBeNull(); + expect(parseCartItems([{ id: "a b", kind: "sku", skuId: 1 }])).toBeNull(); + expect(parseCartItems([{ id: "a", kind: "checkout" }])).toBeNull(); + expect(parseCartItems([])).toBeNull(); + expect(parseCartItems("a")).toBeNull(); + }); + + it("refuses more than a cart's worth", () => { + const items = Array.from({ length: 51 }, (_, index) => ({ id: `i${index}`, kind: "sku", skuId: 1 })); + + expect(parseCartItems(items)).toBeNull(); + }); +}); + +describe("parseCsrfToken", () => { + it("reads the meta tag in either attribute order", () => { + expect(parseCsrfToken(CART_PAGE)).toBe("csrf-123"); + expect(parseCsrfToken('')).toBe("csrf-456"); + expect(parseCsrfToken("")).toBeNull(); + }); +}); + +describe("addToCart", () => { + it("adds a store SKU with the page's CSRF token", async () => { + const calls = mockRsi({ + "/graphql": () => json([{ data: { store: { cart: { mutations: { addMany: { count: 1 } } } } } }]), + }); + + const result = await addToCart("rsi-token", [{ id: "a", kind: "sku", skuId: 17402, qty: 1 }]); + + expect(result).toEqual({ code: 200, payload: { results: [{ id: "a", ok: true }] } }); + const mutation = calls.find((call) => call.path === "/graphql")!; + expect(mutation.headers["X-CSRF-TOKEN"]).toBe("csrf-123"); + expect(mutation.headers["X-Rsi-Token"]).toBe("rsi-token"); + expect(mutation.body[0].variables.query).toEqual([{ skuId: "17402", qty: 1 }]); + }); + + it("adds an upgrade in three steps, a bought-back one naming its pledge", async () => { + const calls = mockRsi({ + "/api/ship-upgrades/setContextToken": () => json({ success: 1, code: "OK" }), + "/pledge-store/api/upgrade/v2/graphql": () => json([{ data: { addToCart: { jwt: "jwt-1" } } }]), + "/api/store/v2/cart/token": () => json({ success: 1, code: "OK", data: true }), + }); + + const result = await addToCart("rsi-token", [ + { id: "b", kind: "upgrade", fromShipId: 56, toShipId: 329, toSkuId: 19753, pledgeId: 115843848 }, + ]); + + expect(result.payload?.results).toEqual([{ id: "b", ok: true }]); + expect(calls.map((call) => call.path)).toEqual([ + "/en/store/pledge/cart", + "/api/ship-upgrades/setContextToken", + "/pledge-store/api/upgrade/v2/graphql", + "/api/store/v2/cart/token", + ]); + expect(calls[1]!.body).toEqual({ fromShipId: 56, toShipId: 329, toSkuId: 19753, pledgeId: 115843848 }); + expect(calls[2]!.body[0].variables).toEqual({ from: 56, to: 19753 }); + expect(calls[3]!.body).toEqual({ jwt: "jwt-1" }); + }); + + it("says why RSI refused each item, and goes on with the next", async () => { + mockRsi({ + "/graphql": () => + json([ + { + errors: [ + { + message: "Invalid cart", + code: "TyCartValidationException", + extensions: { details: { skus: "Cannot acquire more than 1 item at once with a Pledge Buy-Back" } }, + }, + ], + }, + ]), + "/api/ship-upgrades/setContextToken": () => json({ success: 1 }), + "/pledge-store/api/upgrade/v2/graphql": () => + json([{ errors: [{ message: "Upgrade not available. Upgrade from ship 103 to ship sku 13053 is not available." }], data: null }]), + "/api/store/buyBackPledge": () => json({ success: 0, code: "ErrBuyBackPledge", msg: "Invalid Buy-Back Pledge" }), + }); + + const result = await addToCart("rsi-token", [ + { id: "a", kind: "sku", skuId: 17402, qty: 1 }, + { id: "b", kind: "upgrade", fromShipId: 103, toShipId: 103, toSkuId: 13053, pledgeId: null }, + { id: "c", kind: "buyback", pledgeId: 1 }, + ]); + + expect(result.payload?.results).toEqual([ + { id: "a", ok: false, error: "buybackNotAlone", message: "Cannot acquire more than 1 item at once with a Pledge Buy-Back" }, + { id: "b", ok: false, error: "unavailable", message: "Upgrade not available. Upgrade from ship 103 to ship sku 13053 is not available." }, + { id: "c", ok: false, error: "buybackInvalid", message: "Invalid Buy-Back Pledge" }, + ]); + }); + + it("reads an unknown SKU as unavailable", async () => { + mockRsi({ + "/graphql": () => + json([{ errors: [{ message: "Invalid cart", code: "TyCartValidationException", extensions: { details: null } }] }]), + }); + + const result = await addToCart("rsi-token", [{ id: "a", kind: "sku", skuId: 1, qty: 1 }]); + + expect(result.payload?.results).toEqual([{ id: "a", ok: false, error: "unavailable", message: "Invalid cart" }]); + }); + + it("adds nothing when the store page carries no CSRF token", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("")); + + const result = await addToCart("rsi-token", [{ id: "a", kind: "sku", skuId: 1, qty: 1 }]); + + expect(result).toEqual({ code: 502, error: "Store unreadable" }); + expect(fetch).toHaveBeenCalledTimes(1); + }); +}); + +describe("onMessage addToCart", () => { + it("answers 400 for items it will not send to RSI", async () => { + const sendResponse = vi.fn(); + const fetchSpy = vi.spyOn(globalThis, "fetch"); + + await onMessage( + JSON.stringify({ action: "addToCart", items: [{ id: "a", kind: "sku", skuId: "x" }] }), + sendResponse, + vi.fn().mockResolvedValue("rsi-token"), + "1.0.0" + ); + + expect(JSON.parse(sendResponse.mock.calls[0]![0])).toEqual({ + code: 400, + action: "addToCart", + error: "Invalid cart items", + }); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("answers 401 without an RSI session", async () => { + const sendResponse = vi.fn(); + + await onMessage( + JSON.stringify({ action: "addToCart", items: [{ id: "a", kind: "sku", skuId: 1 }] }), + sendResponse, + vi.fn().mockResolvedValue(null), + "1.0.0" + ); + + expect(JSON.parse(sendResponse.mock.calls[0]![0])).toEqual({ + code: 401, + action: "addToCart", + error: "No RSI session", + }); + }); + + it("answers with a result per item", async () => { + const sendResponse = vi.fn(); + mockRsi({ "/api/store/buyBackPledge": () => json({ success: 1, code: "OK" }) }); + + await onMessage( + JSON.stringify({ action: "addToCart", items: [{ id: "d", kind: "buyback", pledgeId: "115575665" }] }), + sendResponse, + vi.fn().mockResolvedValue("rsi-token"), + "1.0.0" + ); + + expect(JSON.parse(sendResponse.mock.calls[0]![0])).toEqual({ + action: "addToCart", + code: 200, + payload: { results: [{ id: "d", ok: true }] }, + }); + }); +}); diff --git a/__tests__/message-handler.test.ts b/__tests__/message-handler.test.ts index 24878f8..93f25bf 100644 --- a/__tests__/message-handler.test.ts +++ b/__tests__/message-handler.test.ts @@ -32,6 +32,7 @@ describe("onMessage", () => { "syncBuybackDetail", "syncBuybackPricing", "syncStoreCredit", + "addToCart", "verify-write", "verify-remove", "org-verify-write", diff --git a/lib/cart.ts b/lib/cart.ts new file mode 100644 index 0000000..149cf10 --- /dev/null +++ b/lib/cart.ts @@ -0,0 +1,187 @@ +import { + addSkusToCart, + buyBackPledge, + createUpgradeCartToken, + fetchCartPage, + redeemCartToken, + setUpgradeContext, +} from "./rsi"; + +export type CartItem = + | { id: string; kind: "sku"; skuId: number; qty: number } + | { + id: string; + kind: "upgrade"; + fromShipId: number; + toShipId: number; + toSkuId: number; + pledgeId: number | null; + } + | { id: string; kind: "buyback"; pledgeId: number }; + +// What the page shows the user, by cause rather than by RSI's wording. +export type CartError = + | "unavailable" + | "buybackInvalid" + | "buybackNotAlone" + | "failed"; + +export type CartResult = + | { id: string; ok: true } + | { id: string; ok: false; error: CartError; message?: string }; + +// The page asking can be any script on a FleetYards origin, so it names what +// to add by ids alone, and only a cart's worth of them. +export const MAX_CART_ITEMS = 50; +const ITEM_ID_PATTERN = /^[\w:-]{1,64}$/; +const ID_PATTERN = /^\d{1,12}$/; + +const rsiId = (value: unknown) => + (typeof value === "number" || typeof value === "string") && + ID_PATTERN.test(String(value)) + ? Number(value) + : undefined; + +export function parseCartItems(value: unknown): CartItem[] | null { + if (!Array.isArray(value) || value.length === 0 || value.length > MAX_CART_ITEMS) { + return null; + } + + const items: CartItem[] = []; + for (const raw of value) { + const id = raw?.id; + if (typeof id !== "string" || !ITEM_ID_PATTERN.test(id)) return null; + + if (raw.kind === "sku") { + const skuId = rsiId(raw.skuId); + const qty = raw.qty ?? 1; + if (!skuId || !Number.isInteger(qty) || qty < 1 || qty > 20) return null; + items.push({ id, kind: "sku", skuId, qty }); + } else if (raw.kind === "upgrade") { + const fromShipId = rsiId(raw.fromShipId); + const toShipId = rsiId(raw.toShipId); + const toSkuId = rsiId(raw.toSkuId); + const pledgeId = raw.pledgeId == null ? null : rsiId(raw.pledgeId); + if (!fromShipId || !toShipId || !toSkuId || pledgeId === undefined) return null; + items.push({ id, kind: "upgrade", fromShipId, toShipId, toSkuId, pledgeId }); + } else if (raw.kind === "buyback") { + const pledgeId = rsiId(raw.pledgeId); + if (!pledgeId) return null; + items.push({ id, kind: "buyback", pledgeId }); + } else { + return null; + } + } + + return items; +} + +export function parseCsrfToken(html: string) { + const tag = html.match(/]*\bname="csrf-token"[^>]*>/i)?.[0]; + + return tag?.match(/\bcontent="([^"]+)"/i)?.[1] ?? null; +} + +const BUYBACK_ALONE = /Buy-?Back/i; + +// GraphQL refusals come back with a 200: the cause sits in `errors`. +function graphqlError(body: any): { error: CartError; message?: string } | null { + const error = (Array.isArray(body) ? body[0] : body)?.errors?.[0]; + if (!error) return null; + + const details = error.extensions?.details; + if (typeof details?.skus === "string" && BUYBACK_ALONE.test(details.skus)) { + return { error: "buybackNotAlone", message: details.skus }; + } + if ( + error.code === "TyCartValidationException" || + /not available/i.test(error.message ?? "") + ) { + return { error: "unavailable", message: error.message }; + } + + return { error: "failed", message: error.message }; +} + +// RSI's REST endpoints refuse with a 200 and `success: 0`. +function restError(body: any): { error: CartError; message?: string } | null { + if (body?.success !== 0) return null; + + return { + error: body.code === "ErrBuyBackPledge" ? "buybackInvalid" : "failed", + message: body.msg, + }; +} + +async function readJson(response: Response) { + return response.json().catch(() => undefined); +} + +type Outcome = { error: CartError; message?: string } | null; + +async function addSku(token: string, csrf: string, item: Extract): Promise { + const response = await addSkusToCart(token, csrf, [item]); + if (!response.ok) return { error: "failed", message: `HTTP ${response.status}` }; + + const body = await readJson(response); + const error = graphqlError(body); + if (error) return error; + + const added = (Array.isArray(body) ? body[0] : body)?.data?.store?.cart?.mutations?.addMany?.count; + + return added ? null : { error: "unavailable" }; +} + +async function addUpgrade(token: string, csrf: string, item: Extract): Promise { + const { fromShipId, toShipId, toSkuId, pledgeId } = item; + + const context = await setUpgradeContext(token, csrf, { fromShipId, toShipId, toSkuId, pledgeId }); + if (!context.ok) return { error: "failed", message: `HTTP ${context.status}` }; + const contextError = restError(await readJson(context)); + if (contextError) return contextError; + + const created = await createUpgradeCartToken(token, csrf, fromShipId, toSkuId); + if (!created.ok) return { error: "failed", message: `HTTP ${created.status}` }; + const body = await readJson(created); + const createError = graphqlError(body); + if (createError) return createError; + + const jwt = (Array.isArray(body) ? body[0] : body)?.data?.addToCart?.jwt; + if (typeof jwt !== "string") return { error: "failed" }; + + const redeemed = await redeemCartToken(token, csrf, jwt); + if (!redeemed.ok) return { error: "failed", message: `HTTP ${redeemed.status}` }; + + return restError(await readJson(redeemed)); +} + +async function addBuyback(token: string, csrf: string, item: Extract): Promise { + const response = await buyBackPledge(token, csrf, item.pledgeId); + if (!response.ok) return { error: "failed", message: `HTTP ${response.status}` }; + + return restError(await readJson(response)); +} + +// One at a time, so each item gets its own answer: one SKU RSI refuses fails +// a whole batched mutation without saying which. +export async function addToCart(token: string, items: CartItem[]) { + const page = await fetchCartPage(token); + const csrf = page.ok ? parseCsrfToken(await page.text()) : null; + if (!csrf) { + return { code: page.ok ? 502 : page.status, error: "Store unreadable" }; + } + + const results: CartResult[] = []; + for (const item of items) { + const outcome = await (item.kind === "sku" + ? addSku(token, csrf, item) + : item.kind === "upgrade" + ? addUpgrade(token, csrf, item) + : addBuyback(token, csrf, item) + ).catch((error): Outcome => ({ error: "failed", message: String(error?.message ?? error) })); + + results.push(outcome ? { id: item.id, ok: false, ...outcome } : { id: item.id, ok: true }); + } + + return { code: 200, payload: { results } }; +} diff --git a/lib/message-handler.ts b/lib/message-handler.ts index d0f392c..86dadbf 100644 --- a/lib/message-handler.ts +++ b/lib/message-handler.ts @@ -23,6 +23,7 @@ import { tokenOnPage, } from "./org"; import { appendToken, removeAppendedToken } from "./tokens"; +import { addToCart, parseCartItems } from "./cart"; import { BioTooLongError, VERIFICATION_TOKEN_PATTERN, @@ -43,6 +44,7 @@ export const SUPPORTED_ACTIONS = [ "syncBuybackDetail", "syncBuybackPricing", "syncStoreCredit", + "addToCart", "verify-write", "verify-remove", "org-verify-write", @@ -493,6 +495,31 @@ export async function onMessage( return { code: 500, error: "Store credit failed" }; }); + sendResponse(JSON.stringify({ action: message.action, ...result })); + } + } else if (message?.action == "addToCart") { + const items = parseCartItems(message.items); + const token = await getToken(); + + if (!items) { + sendResponse( + JSON.stringify({ code: 400, action: message.action, error: "Invalid cart items" }) + ); + } else if (!token) { + sendResponse( + JSON.stringify({ code: 401, action: message.action, error: "No RSI session" }) + ); + } else { + // One cart per account: a second request must not interleave its + // upgrade context with the first one's. + const result = await oneAtATime("cart", () => addToCart(token, items)).catch( + (error) => { + console.error("FY Sync: Add to cart failed", error); + + return { code: 500, error: "Add to cart failed" }; + } + ); + sendResponse(JSON.stringify({ action: message.action, ...result })); } } else if ( diff --git a/lib/rsi.ts b/lib/rsi.ts index b6df15d..b484e13 100644 --- a/lib/rsi.ts +++ b/lib/rsi.ts @@ -187,3 +187,103 @@ export function publishOrgDraft(token: string, sid: string) { headers: ORG_ADMIN_HEADERS, }); } + +// Any store page carries the CSRF token RSI's cart mutations ask for, in a +// meta tag of the HTML the server sends. +export function fetchCartPage(token: string) { + return fetch(`${RSI_BASE_URL}/en/store/pledge/cart`, { + method: "GET", + headers: { + ...HTML_PAGE_HEADERS, + "X-Rsi-Token": token, + }, + credentials: "include", + cache: "no-store", + }); +} + +const csrfHeaders = (csrfToken: string) => ({ "X-CSRF-TOKEN": csrfToken }); + +export function addSkusToCart( + token: string, + csrfToken: string, + items: { skuId: number; qty: number }[] +) { + return fetchRSIApi({ + url: `${RSI_BASE_URL}/graphql`, + payload: [ + { + operationName: "AddCartMultiItemMutation", + variables: { + storeFront: "pledge", + query: items.map(({ skuId, qty }) => ({ skuId: String(skuId), qty })), + }, + query: + 'mutation AddCartMultiItemMutation($query: [CartAddInput!], $storeFront: String = "pledge") { store(name: $storeFront) { cart { mutations { addMany(query: $query) { count } } } } }', + }, + ], + rsiToken: token, + headers: csrfHeaders(csrfToken), + }); +} + +// The upgrade tool reads what it adds from this context: a pledge id makes the +// upgrade a buy-back, none a store purchase. +export function setUpgradeContext( + token: string, + csrfToken: string, + context: { + fromShipId: number; + toShipId: number; + toSkuId: number; + pledgeId: number | null; + } +) { + return fetchRSIApi({ + url: `${RSI_BASE_URL}/api/ship-upgrades/setContextToken`, + payload: context, + rsiToken: token, + headers: csrfHeaders(csrfToken), + }); +} + +// Answers with a JWT the cart takes for 30 seconds. +export function createUpgradeCartToken( + token: string, + csrfToken: string, + from: number, + to: number +) { + return fetchRSIApi({ + url: `${RSI_BASE_URL}/pledge-store/api/upgrade/v2/graphql`, + payload: [ + { + operationName: "addToCart", + variables: { from, to }, + query: + "mutation addToCart($from: Int!, $to: Int!) { addToCart(from: $from, to: $to) { jwt } }", + }, + ], + rsiToken: token, + headers: csrfHeaders(csrfToken), + }); +} + +export function redeemCartToken(token: string, csrfToken: string, jwt: string) { + return fetchRSIApi({ + url: `${RSI_BASE_URL}/api/store/v2/cart/token`, + payload: { jwt }, + rsiToken: token, + headers: csrfHeaders(csrfToken), + }); +} + +// Replaces whatever the cart held: a buy-back is only ever bought alone. +export function buyBackPledge(token: string, csrfToken: string, id: number) { + return fetchRSIApi({ + url: `${RSI_BASE_URL}/api/store/buyBackPledge`, + payload: { id }, + rsiToken: token, + headers: csrfHeaders(csrfToken), + }); +}