Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(shopify-app): add an embedded app that turns product photos into 3D product media
nirholas7b52431a9215
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0fee87547..6a88b3706 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,10 +9,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Docs · Staked Event Markets** (`/docs/event-markets-staking`): Decision record for staked Event Markets on Solana: the parimutuel model, fee and buyback split, limits, void and refund rules, and the jurisdiction and age questions that stay with the owner.- **Docs: Discord Activity (Forge Room)** (`/docs/discord-activity`): How the three.ws Discord Activity works: the OAuth2 auth flow, Discord's /.proxy/ URL mapping and CSP, the shared event-sourced room state, and why it ships with no purchases.- **Docs: LiveKit and Pipecat avatar integrations** (`/docs/voice-framework-integrations`): How to drive a three.ws <agent-3d> avatar's lipsync and gestures from a LiveKit Agents or Pipecat voice pipeline, with the livekit-plugins-threews and pipecat-threews packages, runnable local examples, and the data-channel message contract both share.+- **Docs: Shopify app (Photo to 3D product media)** (`/docs/shopify-app`): How the three.ws Shopify app works: OAuth and embedded session tokens, the photo-to-GLB-to-productCreateMedia pipeline, usage-based Billing API integration, and the mandatory privacy webhooks.- **Forge Room (Discord Activity)** (`/discord-activity`): A shared Forge room that runs embedded inside a Discord voice channel: everyone in the call prompts, watches the same 3D model generate, and votes together.- **Open source credits** (`/open-source`): Every open-source project, GPU model, and asset source three.ws is built on, grouped by what it powers: rendering, formats and compression, generation models, motion, voice, assets, and infrastructure. Generated from package.json on every build.+- **Photo to 3D product media (Shopify app)** (`/apps/shopify`): An embedded Shopify admin app that turns a product photo into a real GLB and attaches it to the product, so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone.- **Video to Motion: Turn Any Video into an Animation File** (`/video-to-motion`): Upload a video of a person and download the motion as a GLB, BVH, or FBX animation file. Preview it on a default avatar or your own rig, trim it, and save it to your animation library.- **A Discord Activity brings a shared Forge room into any voice channel**: Open the new Activity from a Discord voice channel and everyone in the call shares one Forge room: one prompt, one in-progress generation, one finished model with a shared vote count, and an agent that reacts in text to what just happened. Auth maps a verified Discord identity (re-checked against Discord's own /users/@me, never trusted from the client) to a room-scoped session; generation and voting reuse the real /api/forge pipeline and forge_votes table rather than a separate throwaway pipeline. No coin, wallet, or purchase path. Docs: /docs/discord-activity. Submission packet for Developer Portal setup and Discovery copy: marketing/growth/submissions/discord-activity.md. (`/docs/discord-activity`) `[feature, docs]`+- **A Shopify app turns product photos into 3D product media**: A new embedded Shopify app, built end to end but not yet installable (Partner account, env vars, and App Store submission are owner actions): pick a product photo in the admin, generate a real GLB through three.ws's own /api/forge pipeline, preview it in-page, and attach it with productCreateMedia so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone from the one upload (Shopify derives the USDZ automatically). Bulk mode generates across a whole catalog with real per-item status. Billing runs through Shopify's own usage-based Billing API, priced from Forge's own per-call cost, in test mode until the app has Public distribution. The three mandatory privacy webhooks plus app/uninstalled are HMAC-verified and delivery-deduplicated. Docs: /docs/shopify-app. Submission packet for Partner Dashboard setup and App Store listing copy: marketing/growth/submissions/shopify-app.md. (`/docs/shopify-app`) `[feature, docs]`- **A three.ws avatar now lipsyncs to any LiveKit Agents or Pipecat voice pipeline**: Two new packages, livekit-plugins-threews and pipecat-threews, republish a running voice agent's TTS and user-turn frames as the same transcript/gesture/speech_started/speech_ended message shape over the room's data channel, which <agent-3d voice="livekit"> already renders client-side: no server-side video rendering, no change to the browser code at all. The LiveKit package is an AvatarSession plugin dropped into an AgentSession; the Pipecat package is a FrameProcessor placed after the TTS service. Each ships a runnable local example against a real open-source livekit-server with a real local TTS, verified end to end with real browser automation driving the actual avatar lipsync and gesture cues off a live bot in both frameworks. Docs: /docs/voice-framework-integrations. (`/docs/voice-framework-integrations`) `[feature, sdk, docs]`- **Get it printed: live Craftcloud prices for any Forge model, buyer pays direct**: A new "Get it printed" action on model pages and in the Forge export menu uploads the model straight to Craftcloud (All3DP) and shows live, real prices across whichever of its roughly 186 print shops can run the job, cheapest first with shipping attached. This is not Materialize: three.ws never takes payment here. Craftcloud's public v5 API has no endpoint that hands a server-created cart back to a browser for checkout, so the panel links out to Craftcloud's own upload page instead of faking a continue-to-checkout button, where pasting the same STL reproduces the prices in an authenticated, checkout-capable session. Backed by a new fulfillment adapter, api/_lib/print/adapters/craftcloud.js, registered ahead of the manual adapter since quoting never spends. Docs: /docs/forge#get-it-printed-live-prices-from-craftcloud and /docs/materialize. (`/docs/forge#get-it-printed-live-prices-from-craftcloud`) `[feature, docs]`- **Open source credits: every dependency, model, and asset source three.ws runs on, in one place**: A new /open-source page lists every third-party dependency, GPU worker model, and free asset source the platform runs on, grouped by area (rendering, formats and compression, generation models, motion, voice, assets, infrastructure) with license, upstream link, and what each one powers here. The dataset is generated from package.json and each worker's own README, not hand-maintained, and a guard test fails the build if a new direct dependency lands without a credited entry. Credits now also show up where the work actually happens: /objects and the object viewer name Poly Haven, the CC0 asset library the catalog sources from; the Forge export dialog names meshoptimizer and glTF-Transform; and the animation gallery shows each clip's source and license, including a fallback for studio-tier clips that lack an explicit manifest entry. Docs: /docs/open-source-credits. (`/open-source`) `[feature, docs]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 8ad358830..08b64ebdb 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -356,6 +356,7 @@ bottom.| Desktop menu bar panel | [apps/desktop/src/main/panel.js](apps/desktop/src/main/panel.js), pure logic [src/panel/model.js](apps/desktop/src/panel/model.js), renderer [src/panel/](apps/desktop/src/panel), preload [src/panel-preload.cjs](apps/desktop/src/panel-preload.cjs) | In-repo; ships with the desktop app | A popover under the tray icon: the selected agent alive in 3D (the published walk embed, gesture tied to local runtime state), SOL balance, start and stop, a pending-approvals card that opens the native review dialog (the panel has no approve call), alerts, companion switch and a one-line ask box. Docs: [docs/desktop-menu-bar-panel.md](docs/desktop-menu-bar-panel.md). Tests: tests/desktop-panel.test.js || DCC tool integrations (Blender, ComfyUI, Modly) | [integrations/](integrations): [integrations/blender/](integrations/blender), [integrations/comfyui/](integrations/comfyui), Modly extensions [integrations/modly/](integrations/modly) (`three-ws/` cloud nodes, `three-ws-publish/` publish node), shared Python client [integrations/_pyclient/](integrations/_pyclient) | In-repo; Modly extensions install by linking the folder, one-click GitHub install is owner-gated ([SUBMITTING.md](integrations/modly/SUBMITTING.md)) | First-party plugins that drive the public Forge pipeline (`/api/forge`, rig, remesh, publish) from inside the tools artists already use, so a model is generated without leaving the DCC. Docs: [integrations/README.md](integrations/README.md), [integrations/modly/README.md](integrations/modly/README.md) || LiveKit and Pipecat avatar integrations | [integrations/livekit/livekit-plugins-threews/](integrations/livekit/livekit-plugins-threews) (published as `livekit-plugins-threews`), [integrations/pipecat/pipecat-threews/](integrations/pipecat/pipecat-threews) (published as `pipecat-threews`) | In-repo; PyPI publish and the upstream community-integration PRs are owner actions | A LiveKit Agents `AvatarSession` plugin and a Pipecat `FrameProcessor` that both republish a running voice pipeline's TTS and user-turn frames as the same `transcript`/`gesture`/`speech_started`/`speech_ended` JSON message shape over the room's data channel, which `<agent-3d voice="livekit">` ([src/runtime/livekit-voice.js](src/runtime/livekit-voice.js)) already renders client-side, no server-side video rendering. Each ships a runnable local example against a real open-source `livekit-server`, no cloud account needed. Docs: [docs/voice-framework-integrations.md](docs/voice-framework-integrations.md). Tests: `integrations/livekit/livekit-plugins-threews/tests/`, `integrations/pipecat/pipecat-threews/tests/`, browser E2E [tests/e2e/agent-3d-livekit-avatar.spec.js](tests/e2e/agent-3d-livekit-avatar.spec.js), [tests/e2e/agent-3d-pipecat-avatar.spec.js](tests/e2e/agent-3d-pipecat-avatar.spec.js) |+| Shopify app: Photo to 3D product media | [api/shopify/](api/shopify), [api/_lib/shopify/](api/_lib/shopify), [pages/shopify-app.html](pages/shopify-app.html), [src/shopify-app/app.js](src/shopify-app/app.js), migration [api/_lib/migrations/20261015060000_shopify_app.sql](api/_lib/migrations/20261015060000_shopify_app.sql) | In-repo; Shopify Partner account, env vars, migration apply, and App Store submission are owner actions | An embedded Shopify admin app that turns a product photo into a real GLB (via three.ws's own `/api/forge`) and attaches it with `productCreateMedia`, so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone from one upload (Shopify derives the USDZ). OAuth with session-token-authenticated embedded calls, bulk generation with real per-item status, usage-based Billing API subscription, and the three mandatory privacy webhooks plus `app/uninstalled`. Docs: [docs/shopify-app.md](docs/shopify-app.md), submission packet [marketing/growth/submissions/shopify-app.md](marketing/growth/submissions/shopify-app.md). || Base58 difficulty model (the honest math) | [src/solana/vanity/base58-distribution.js](src/solana/vanity/base58-distribution.js), dispatch in [src/solana/vanity/validation.js](src/solana/vanity/validation.js); ported copies in [solana-agent-sdk/src/vanity/verify.ts](solana-agent-sdk/src/vanity/verify.ts) and [mcp-server/src/lib/base58-distribution.js](mcp-server/src/lib/base58-distribution.js), held in agreement by [tests/vanity-model-parity.test.js](tests/vanity-model-parity.test.js) | In-repo | The exact probability that a random Solana address matches a vanity pattern, and the single source of truth behind every quote, price, rarity tier, bounty payout and signed receipt. Base58 is a positional encoding of a 256-bit integer, so the *leading* character is not uniform: the 40 symbols `K`-`z` are 17.2x harder to lead with than `5`-`H`, a 58x spread the old flat 58ⁿ model erased. Models are versioned (`base58-exact/v2`, superseding `58^effectiveLength`) and receipts name theirs, so attestations issued before the correction still verify. Spec: [docs/PROTOCOL-vanity.md](docs/PROTOCOL-vanity.md#41-difficulty-model-versioning) || Vanity address grinder (Rust → WASM) | [crates/vanity-grinder/](crates/vanity-grinder) → compiled to [src/solana/vanity/wasm/](src/solana/vanity/wasm); consumed by [src/agent-vanity-grinder.js](src/agent-vanity-grinder.js), [src/agent-eth-vanity-card.js](src/agent-eth-vanity-card.js) | In-repo | The Rust source behind in-browser Solana/EVM vanity-address mining. Compiled to WebAssembly so grinding runs on the visitor's machine, never the server. Surfaced as the `vanity_grinder` MCP tool and the premium pre-ground inventory (`vanity_premium`). || x402 payment modal (drop-in UI) | [x402-payment-modal/](x402-payment-modal) | Published as `@three-ws/x402-payment-modal` | A drop-in payment modal for any x402 paid endpoint — one ES import turns a 402 challenge into a wallet-connect + pay flow. Has a build step, so it sits outside the zero-dependency `packages/*` SDK family. |diff --git a/api/_lib/migrations/20261015060000_shopify_app.sql b/api/_lib/migrations/20261015060000_shopify_app.sqlnew file mode 100644index 000000000..177478155--- /dev/null+++ b/api/_lib/migrations/20261015060000_shopify_app.sql@@ -0,0 +1,73 @@+-- Shopify product-media app (work order 091-partners-08): OAuth sessions,+-- per-image media-generation jobs, webhook delivery idempotency, and the+-- one Billing API subscription a shop activates.+--+-- access_token is the OFFLINE token from the token exchange (api/shopify/callback.js):+-- it never expires on its own and is scoped to the app's whole install, which+-- is what every background job (bulk mode, the status poller) needs to keep+-- working without a merchant's browser tab open. Shopify does not support+-- rotating it server-side, so uninstalling and reinstalling is the only way a+-- shop gets a new one; `uninstalled_at` marks a session dead without deleting+-- the row, so a reinstall's callback can reuse the primary key cleanly.+create table if not exists shopify_shops (+ shop_domain text primary key,+ access_token text not null,+ scope text not null,+ installed_at timestamptz not null default now(),+ uninstalled_at timestamptz+);++-- One row per "generate a 3D model for this product's image" action, whether+-- fired from the single-product flow or bulk mode. Bulk mode is just N of+-- these inserted together; the embedded UI polls each by id for real+-- per-item status instead of one opaque batch spinner.+create table if not exists shopify_media_jobs (+ id uuid primary key default gen_random_uuid(),+ shop_domain text not null references shopify_shops(shop_domain),+ product_id text not null,+ product_title text,+ image_url text not null,+ forge_job_id text,+ status text not null default 'generating',+ glb_url text,+ staged_resource_url text,+ media_id text,+ error text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ constraint shopify_media_jobs_status_check check (+ status in ('generating', 'ready_to_attach', 'attaching', 'attached', 'failed')+ )+);++create index if not exists shopify_media_jobs_shop_idx+ on shopify_media_jobs (shop_domain, created_at desc);++-- Idempotency ledger for the three mandatory privacy webhooks plus+-- app/uninstalled, mirroring forge_webhook_deliveries+-- (20261015040000_forge_webhook_deliveries.sql): Shopify retries a webhook+-- delivery that doesn't 200 fast enough, and a replayed shop/redact or+-- customers/redact must not re-run its handler a second time.+create table if not exists shopify_webhook_deliveries (+ shop_domain text not null,+ topic text not null,+ delivery_id text not null,+ received_at timestamptz not null default now(),+ primary key (topic, delivery_id)+);++-- One usage-pricing AppSubscription per shop. `test_mode` records whether the+-- activated subscription carried `test: true` (Shopify never charges a test+-- subscription's usage records), so the app can show the merchant an honest+-- "test mode, no charge" badge instead of silently billing nothing and+-- looking broken.+create table if not exists shopify_billing (+ shop_domain text primary key references shopify_shops(shop_domain),+ subscription_id text not null,+ line_item_id text not null,+ test_mode boolean not null default true,+ status text not null default 'pending',+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ constraint shopify_billing_status_check check (status in ('pending', 'active', 'declined', 'cancelled'))+);diff --git a/api/_lib/shopify/auth-request.js b/api/_lib/shopify/auth-request.jsnew file mode 100644index 000000000..dc618c8e9--- /dev/null+++ b/api/_lib/shopify/auth-request.js@@ -0,0 +1,33 @@+// Shared auth path for every embedded-app API route: verify App Bridge's+// session token, then load the shop's stored offline access token (the+// session token proves WHO is calling, it is never itself usable against the+// Admin API).++import { SessionTokenError, verifySessionToken, bearerFromRequest } from './session-token.js';+import { getShopSession } from './store.js';++export class RequestAuthError extends Error {+ constructor(message, status = 401) {+ super(message);+ this.status = status;+ }+}++/** @returns {Promise<{ shop: string, accessToken: string, userId: string }>} */+export async function authenticateEmbeddedRequest(req) {+ const token = bearerFromRequest(req);+ let claims;+ try {+ claims = await verifySessionToken(token);+ } catch (err) {+ if (err instanceof SessionTokenError) throw new RequestAuthError(err.message, 401);+ throw err;+ }++ const session = await getShopSession(claims.shop);+ if (!session || session.uninstalled_at) {+ throw new RequestAuthError('app is not installed on this shop; reinstall to continue', 401);+ }++ return { shop: claims.shop, accessToken: session.access_token, userId: claims.userId };+}diff --git a/api/_lib/shopify/billing.js b/api/_lib/shopify/billing.jsnew file mode 100644index 000000000..75e98ce88--- /dev/null+++ b/api/_lib/shopify/billing.js@@ -0,0 +1,90 @@+// Shopify Billing API: one usage-based AppSubscription per shop+// (shopify.dev/docs/apps/launch/billing/subscription-billing/create-usage-based-subscriptions),+// charged per product converted rather than a flat monthly fee, since usage+// tracks the real Forge cost this app incurs per model.++import { adminGraphql, assertNoUserErrors } from './graphql.js';+import { USAGE_PRICE_USD, USAGE_CAP_USD, billingTestMode } from './config.js';++const SUBSCRIPTION_CREATE = `+ mutation appSubscriptionCreate(+ $name: String!, $returnUrl: URL!, $test: Boolean!,+ $cappedAmount: MoneyInput!, $terms: String!+ ) {+ appSubscriptionCreate(+ name: $name+ returnUrl: $returnUrl+ test: $test+ lineItems: [{+ plan: {+ appUsagePricingDetails: { cappedAmount: $cappedAmount, terms: $terms }+ }+ }]+ ) {+ appSubscription { id lineItems { id } }+ confirmationUrl+ userErrors { field message }+ }+ }+`;++/**+ * Starts (or returns the pending confirmation for) a usage-based+ * subscription. The merchant must open `confirmationUrl` and approve it+ * before any usage record can be recorded: Shopify owns that approval+ * screen, this app only initiates it.+ */+export async function createUsageSubscription(shop, accessToken, returnUrl) {+ const data = await adminGraphql(shop, accessToken, SUBSCRIPTION_CREATE, {+ name: 'Photo to 3D product media',+ returnUrl,+ test: billingTestMode(),+ cappedAmount: { amount: USAGE_CAP_USD, currencyCode: 'USD' },+ terms: `$${USAGE_PRICE_USD} per product converted to a 3D model, capped at $${USAGE_CAP_USD}/month`,+ });+ assertNoUserErrors(data, 'appSubscriptionCreate');+ const { appSubscription, confirmationUrl } = data.appSubscriptionCreate;+ return {+ subscriptionId: appSubscription.id,+ lineItemId: appSubscription.lineItems[0].id,+ confirmationUrl,+ testMode: billingTestMode(),+ };+}++const ACTIVE_SUBSCRIPTIONS_QUERY = `+ query ActiveSubscriptions {+ currentAppInstallation {+ activeSubscriptions { id status lineItems { id } }+ }+ }+`;++/** Re-checks Shopify's own record of whether the subscription was approved. */+export async function fetchActiveSubscription(shop, accessToken) {+ const data = await adminGraphql(shop, accessToken, ACTIVE_SUBSCRIPTIONS_QUERY);+ return data.currentAppInstallation.activeSubscriptions[0] || null;+}++const USAGE_RECORD_CREATE = `+ mutation appUsageRecordCreate($subscriptionLineItemId: ID!, $price: MoneyInput!, $description: String!) {+ appUsageRecordCreate(+ subscriptionLineItemId: $subscriptionLineItemId+ price: $price+ description: $description+ ) {+ appUsageRecord { id }+ userErrors { field message }+ }+ }+`;++export async function recordUsage(shop, accessToken, { lineItemId, description }) {+ const data = await adminGraphql(shop, accessToken, USAGE_RECORD_CREATE, {+ subscriptionLineItemId: lineItemId,+ price: { amount: USAGE_PRICE_USD, currencyCode: 'USD' },+ description,+ });+ assertNoUserErrors(data, 'appUsageRecordCreate');+ return data.appUsageRecordCreate.appUsageRecord.id;+}diff --git a/api/_lib/shopify/config.js b/api/_lib/shopify/config.jsnew file mode 100644index 000000000..6dc00cd08--- /dev/null+++ b/api/_lib/shopify/config.js@@ -0,0 +1,73 @@+// Shared Shopify app config: env access + the few constants every handler+// needs (API version, scopes, mandatory webhook topics). Reads process.env+// directly, matching how every other third-party integration in this repo+// (Discord Activity, Google sign-in) keeps its credentials local to its own+// module rather than growing the shared api/_lib/env.js.++// Admin API version: Shopify ships a new one every quarter and expects apps+// to move forward; pin to the latest stable release at build time and bump+// this string on the next quarterly pass (shopify.dev/docs/api/release-notes).+export const ADMIN_API_VERSION = '2026-10';++// The flow needs: read the shop's products + existing media, create new+// product media, and run the Billing API. No order/customer PII scope is+// requested, since the app never reads customer data (the privacy webhooks+// exist only because Shopify requires every app to answer them, not because+// this app stores anything they'd ever fire for).+export const SCOPES = 'read_products,write_products';++export const MANDATORY_WEBHOOK_TOPICS = Object.freeze([+ 'CUSTOMERS_DATA_REQUEST',+ 'CUSTOMERS_REDACT',+ 'SHOP_REDACT',+ 'APP_UNINSTALLED',+]);++export function shopifyConfigured() {+ return Boolean(process.env.SHOPIFY_API_KEY && process.env.SHOPIFY_API_SECRET);+}++export function apiKey() {+ return process.env.SHOPIFY_API_KEY || '';+}++export function apiSecret() {+ return process.env.SHOPIFY_API_SECRET || '';+}++// Where the OAuth callback and every link the embedded UI builds point back+// to. Falls back to the platform's own origin so a shop installed against a+// non-production deployment (local dev, a preview) still round-trips.+export function appUrl() {+ const explicit = (process.env.SHOPIFY_APP_URL || '').trim();+ if (explicit) return explicit.replace(/\/$/, '');+ const origin = (process.env.PUBLIC_APP_ORIGIN || 'https://three.ws').trim();+ return origin.replace(/\/$/, '');+}++// Usage-based pricing per product converted, in USD. $0.15 is the standard+// Forge tier's own per-call cost (api/_lib/forge-tiers.js priceUsdcAtomics);+// $0.49 covers that, Shopify's revenue share, and the staged-upload/GraphQL+// overhead with margin left over.+export const USAGE_PRICE_USD = '0.49';+export const USAGE_CAP_USD = '100.00';++// Billing API charges only clear real money once Shopify has approved the app+// for the App Store (shopify.dev: AppSubscriptionCreate is otherwise gated to+// apps with Public distribution). Until that review completes, every+// subscription this app creates is a test subscription: Shopify records the+// usage but never settles it, so the flow is fully exercisable pre-launch.+// Flip SHOPIFY_BILLING_LIVE=1 once the app is live on the App Store.+export function billingTestMode() {+ return process.env.SHOPIFY_BILLING_LIVE !== '1';+}++const SHOP_DOMAIN_RE = /^[a-z0-9][a-z0-9-]*\.myshopify\.com$/;++// Shared between install.js (sets it) and callback.js (reads it) for the+// OAuth state-nonce round trip.+export const OAUTH_STATE_COOKIE = '__Host-shopify-oauth-state';++export function isValidShopDomain(shop) {+ return typeof shop === 'string' && shop.length <= 100 && SHOP_DOMAIN_RE.test(shop);+}diff --git a/api/_lib/shopify/graphql.js b/api/_lib/shopify/graphql.jsnew file mode 100644index 000000000..bc87a5768--- /dev/null+++ b/api/_lib/shopify/graphql.js@@ -0,0 +1,57 @@+// Thin Admin GraphQL client. Every Shopify call in this app (products,+// staged uploads, productCreateMedia, billing, webhook registration) goes+// through here so retries, error shaping, and the endpoint URL live in one+// place.++import { ADMIN_API_VERSION } from './config.js';++const TIMEOUT_MS = 20_000;++export class ShopifyApiError extends Error {+ constructor(message, { status, userErrors } = {}) {+ super(message);+ this.name = 'ShopifyApiError';+ this.status = status;+ this.userErrors = userErrors || [];+ }+}++/**+ * @param {string} shop shop_domain, e.g. "example.myshopify.com"+ * @param {string} accessToken offline access token for that shop+ * @param {string} query GraphQL document+ * @param {object} [variables]+ */+export async function adminGraphql(shop, accessToken, query, variables = {}) {+ const res = await fetch(`https://${shop}/admin/api/${ADMIN_API_VERSION}/graphql.json`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'x-shopify-access-token': accessToken,+ },+ body: JSON.stringify({ query, variables }),+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw new ShopifyApiError(`Shopify Admin API returned ${res.status}`, { status: res.status });+ }+ if (Array.isArray(body.errors) && body.errors.length) {+ throw new ShopifyApiError(body.errors.map((e) => e.message).join('; '), { status: 502 });+ }+ return body.data;+}++/**+ * Walks a mutation's `userErrors: [{ field, message }]` array (every+ * Shopify mutation used here returns one) and throws if non-empty.+ */+export function assertNoUserErrors(result, path) {+ const userErrors = path.split('.').reduce((acc, key) => acc?.[key], result)?.userErrors;+ if (Array.isArray(userErrors) && userErrors.length) {+ throw new ShopifyApiError(userErrors.map((e) => `${(e.field || []).join('.')}: ${e.message}`).join('; '), {+ status: 422,+ userErrors,+ });+ }+}diff --git a/api/_lib/shopify/hmac.js b/api/_lib/shopify/hmac.jsnew file mode 100644index 000000000..4e803cfc5--- /dev/null+++ b/api/_lib/shopify/hmac.js@@ -0,0 +1,45 @@+// Shopify's two HMAC schemes: the OAuth query-string signature (install and+// callback redirects) and the webhook body signature (every /api/shopify/webhooks/*+// receiver). Both are HMAC-SHA256 with the app's client secret, but keyed over+// different material, so they are not interchangeable: see shopify.dev/docs/apps/auth/oauth/getting-started.++import { createHmac, timingSafeEqual } from 'node:crypto';++function safeEqualHex(a, b) {+ const bufA = Buffer.from(String(a || ''), 'hex');+ const bufB = Buffer.from(String(b || ''), 'hex');+ if (bufA.length !== bufB.length || bufA.length === 0) return false;+ return timingSafeEqual(bufA, bufB);+}++// OAuth install/callback: every query param except `hmac` (and `signature`,+// a legacy alias Shopify no longer sends but some docs still mention) is+// sorted by key, joined as `key=value&key=value` with `&`/`%` escaped per+// Shopify's documented scheme, then HMAC-SHA256'd as hex.+export function verifyOAuthHmac(searchParams, secret) {+ const hmac = searchParams.get('hmac');+ if (!hmac || !secret) return false;+ const pairs = [];+ for (const [key, value] of searchParams.entries()) {+ if (key === 'hmac' || key === 'signature') continue;+ pairs.push([key, value]);+ }+ pairs.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ const message = pairs+ .map(([k, v]) => `${k.replace(/%/g, '%25').replace(/=/g, '%3D')}=${v.replace(/%/g, '%25').replace(/&/g, '%26')}`)+ .join('&');+ const expected = createHmac('sha256', secret).update(message).digest('hex');+ return safeEqualHex(expected, hmac);+}++// Webhook delivery: HMAC-SHA256 of the exact raw request body, base64-encoded,+// carried in the X-Shopify-Hmac-Sha256 header. Must run on the raw bytes+// Shopify signed, before any JSON.parse.+export function verifyWebhookHmac(rawBody, headerValue, secret) {+ if (!headerValue || !secret) return false;+ const expected = createHmac('sha256', secret).update(rawBody).digest('base64');+ const a = Buffer.from(String(headerValue), 'utf8');+ const b = Buffer.from(expected, 'utf8');+ if (a.length !== b.length || a.length === 0) return false;+ return timingSafeEqual(a, b);+}diff --git a/api/_lib/shopify/media.js b/api/_lib/shopify/media.jsnew file mode 100644index 000000000..5528d5114--- /dev/null+++ b/api/_lib/shopify/media.js@@ -0,0 +1,105 @@+// The product + media half of the app: list a shop's products with their+// current media, stage-upload a GLB, and attach it to a product.+//+// Shopify auto-derives the USDZ iOS AR Quick Look asset from an uploaded GLB+// (shopify.dev/docs/apps/build/online-store/product-media: "Shopify serves+// models in both GLB (web) and USDZ (iOS AR) formats" from one uploaded file),+// so this app uploads exactly one MODEL_3D media entry per product rather+// than generating and attaching a second USDZ file itself: one upload, one+// GraphQL round trip, one thing that can fail instead of two.++import { adminGraphql, assertNoUserErrors, ShopifyApiError } from './graphql.js';++const PRODUCTS_QUERY = `+ query Products($first: Int!, $after: String) {+ products(first: $first, after: $after, sortKey: TITLE) {+ pageInfo { hasNextPage endCursor }+ nodes {+ id+ title+ images(first: 10) { nodes { id url altText } }+ media(first: 5) { nodes { mediaContentType } }+ }+ }+ }+`;++export async function listProducts(shop, accessToken, { first = 25, after = null } = {}) {+ const data = await adminGraphql(shop, accessToken, PRODUCTS_QUERY, { first, after });+ return {+ products: data.products.nodes.map((p) => ({+ id: p.id,+ title: p.title,+ images: p.images.nodes,+ has3dModel: p.media.nodes.some((m) => m.mediaContentType === 'MODEL_3D'),+ })),+ pageInfo: data.products.pageInfo,+ };+}++const STAGED_UPLOADS_CREATE = `+ mutation stagedUploadsCreate($input: [StagedUploadInput!]!) {+ stagedUploadsCreate(input: $input) {+ stagedTargets { url resourceUrl parameters { name value } }+ userErrors { field message }+ }+ }+`;++/**+ * Stages a GLB upload and PUTs the bytes, returning the resourceUrl+ * productCreateMedia needs as `originalSource`.+ */+export async function stageAndUploadGlb(shop, accessToken, { filename, bytes }) {+ const data = await adminGraphql(shop, accessToken, STAGED_UPLOADS_CREATE, {+ input: [+ {+ resource: 'MODEL_3D',+ filename,+ mimeType: 'model/gltf-binary',+ httpMethod: 'POST',+ fileSize: String(bytes.length),+ },+ ],+ });+ assertNoUserErrors(data, 'stagedUploadsCreate');+ const target = data.stagedUploadsCreate.stagedTargets[0];+ if (!target) throw new ShopifyApiError('stagedUploadsCreate returned no target', { status: 502 });++ const form = new FormData();+ for (const { name, value } of target.parameters) form.append(name, value);+ form.append('file', new Blob([bytes], { type: 'model/gltf-binary' }), filename);++ const res = await fetch(target.url, { method: 'POST', body: form, signal: AbortSignal.timeout(60_000) });+ if (!res.ok) {+ const text = await res.text().catch(() => '');+ throw new ShopifyApiError(`staged upload to Shopify's storage returned ${res.status}: ${text.slice(0, 300)}`, {+ status: 502,+ });+ }+ return target.resourceUrl;+}++const PRODUCT_CREATE_MEDIA = `+ mutation productCreateMedia($media: [CreateMediaInput!]!, $productId: ID!) {+ productCreateMedia(media: $media, productId: $productId) {+ media { id alt mediaContentType status }+ mediaUserErrors { field message }+ }+ }+`;++export async function attachModel3d(shop, accessToken, { productId, resourceUrl, alt }) {+ const data = await adminGraphql(shop, accessToken, PRODUCT_CREATE_MEDIA, {+ productId,+ media: [{ originalSource: resourceUrl, mediaContentType: 'MODEL_3D', alt: alt || '3D model' }],+ });+ const errors = data.productCreateMedia.mediaUserErrors;+ if (Array.isArray(errors) && errors.length) {+ throw new ShopifyApiError(errors.map((e) => `${(e.field || []).join('.')}: ${e.message}`).join('; '), {+ status: 422,+ userErrors: errors,+ });+ }+ return data.productCreateMedia.media[0];+}diff --git a/api/_lib/shopify/session-token.js b/api/_lib/shopify/session-token.jsnew file mode 100644index 000000000..2cf6659c0--- /dev/null+++ b/api/_lib/shopify/session-token.js@@ -0,0 +1,63 @@+// Verifies the session token App Bridge attaches to every embedded-app+// request (Authorization: Bearer <token>). This is the auth Shopify now+// requires embedded apps to use instead of cookies (shopify.dev/docs/apps/auth/get-access-tokens/session-tokens):+// a short-lived (1 minute) HS256 JWT, signed with the app's client secret,+// that proves the request came from App Bridge running inside an admin the+// merchant is actually signed into: no third-party cookie, works in+// Incognito, which the App Store's automated embedded-app check requires.+//+// Claims: iss (shop admin URL), dest (shop origin), aud (app's API key),+// sub (the Shopify staff user id), exp/nbf/iat, jti, sid.++import { jwtVerify } from 'jose';+import { apiKey, apiSecret, isValidShopDomain } from './config.js';++export class SessionTokenError extends Error {+ constructor(message) {+ super(message);+ this.name = 'SessionTokenError';+ }+}++function shopFromDest(dest) {+ try {+ return new URL(dest).hostname;+ } catch {+ return '';+ }+}++/**+ * @param {string} token raw bearer token (without the "Bearer " prefix)+ * @returns {Promise<{ shop: string, userId: string, sessionId: string }>}+ */+export async function verifySessionToken(token) {+ if (!token || typeof token !== 'string') throw new SessionTokenError('missing session token');+ const secret = apiSecret();+ if (!secret) throw new SessionTokenError('shopify app is not configured');++ let payload;+ try {+ ({ payload } = await jwtVerify(token, new TextEncoder().encode(secret), { algorithms: ['HS256'] }));+ } catch (err) {+ throw new SessionTokenError(`session token rejected: ${err?.message || err}`);+ }++ if (payload.aud !== apiKey()) throw new SessionTokenError('session token aud does not match this app');++ const shop = shopFromDest(String(payload.dest || ''));+ if (!isValidShopDomain(shop)) throw new SessionTokenError('session token dest is not a valid shop domain');++ const iss = String(payload.iss || '');+ if (!iss.includes(shop)) throw new SessionTokenError('session token iss/dest mismatch');++ return { shop, userId: String(payload.sub || ''), sessionId: String(payload.sid || '') };+}++/** Reads the bearer token out of an incoming request's Authorization header. */+export function bearerFromRequest(req) {+ const raw = req.headers?.authorization || req.headers?.Authorization;+ const value = Array.isArray(raw) ? raw[0] : raw;+ const match = typeof value === 'string' && /^Bearer\s+(.+)$/i.exec(value.trim());+ return match ? match[1] : '';+}diff --git a/api/_lib/shopify/store.js b/api/_lib/shopify/store.jsnew file mode 100644index 000000000..1b8efe9fa--- /dev/null+++ b/api/_lib/shopify/store.js@@ -0,0 +1,121 @@+// All shopify_* table access, isolated here so every route and webhook+// handler is a thin, mockable caller (see tests/shopify-*.test.js) instead of+// embedding `sql` queries inline.++import { sql } from '../db.js';++export async function saveShopSession(shop, accessToken, scope) {+ await sql`+ insert into shopify_shops (shop_domain, access_token, scope, installed_at, uninstalled_at)+ values (${shop}, ${accessToken}, ${scope}, now(), null)+ on conflict (shop_domain) do update+ set access_token = excluded.access_token,+ scope = excluded.scope,+ installed_at = now(),+ uninstalled_at = null+ `;+}++export async function getShopSession(shop) {+ const rows = await sql`+ select shop_domain, access_token, scope, installed_at, uninstalled_at+ from shopify_shops+ where shop_domain = ${shop}+ limit 1+ `;+ return rows[0] || null;+}++export async function markShopUninstalled(shop) {+ await sql`update shopify_shops set uninstalled_at = now() where shop_domain = ${shop}`;+}++// Claims a webhook delivery before its body is interpreted, the same+// claim-before-parse shape as print_webhook_deliveries / forge_webhook_deliveries.+// Returns false when this (topic, delivery_id) pair has already been claimed,+// so the caller can answer Shopify's retry 200 without re-running the handler.+export async function claimWebhookDelivery(shop, topic, deliveryId) {+ const rows = await sql`+ insert into shopify_webhook_deliveries (shop_domain, topic, delivery_id)+ values (${shop}, ${topic}, ${deliveryId})+ on conflict (topic, delivery_id) do nothing+ returning topic+ `;+ return rows.length > 0;+}++export async function createMediaJob({ shop, productId, productTitle, imageUrl, forgeJobId }) {+ const rows = await sql`+ insert into shopify_media_jobs (shop_domain, product_id, product_title, image_url, forge_job_id, status)+ values (${shop}, ${productId}, ${productTitle || null}, ${imageUrl}, ${forgeJobId || null}, 'generating')+ returning id+ `;+ return rows[0].id;+}++export async function getMediaJob(shop, id) {+ const rows = await sql`+ select * from shopify_media_jobs where id = ${id} and shop_domain = ${shop} limit 1+ `;+ return rows[0] || null;+}++export async function setMediaJobReadyToAttach(id, { glbUrl, stagedResourceUrl }) {+ await sql`+ update shopify_media_jobs+ set status = 'ready_to_attach', glb_url = ${glbUrl}, staged_resource_url = ${stagedResourceUrl}, updated_at = now()+ where id = ${id}+ `;+}++export async function setMediaJobAttached(id, mediaId) {+ await sql`+ update shopify_media_jobs+ set status = 'attached', media_id = ${mediaId}, updated_at = now()+ where id = ${id}+ `;+}++export async function setMediaJobFailed(id, errorMessage) {+ await sql`+ update shopify_media_jobs+ set status = 'failed', error = ${String(errorMessage).slice(0, 2000)}, updated_at = now()+ where id = ${id}+ `;+}++export async function setMediaJobForgeId(id, forgeJobId) {+ await sql`update shopify_media_jobs set forge_job_id = ${forgeJobId}, updated_at = now() where id = ${id}`;+}++export async function saveBillingSubscription(shop, { subscriptionId, lineItemId, testMode, status }) {+ await sql`+ insert into shopify_billing (shop_domain, subscription_id, line_item_id, test_mode, status)+ values (${shop}, ${subscriptionId}, ${lineItemId}, ${testMode}, ${status})+ on conflict (shop_domain) do update+ set subscription_id = excluded.subscription_id,+ line_item_id = excluded.line_item_id,+ test_mode = excluded.test_mode,+ status = excluded.status,+ updated_at = now()+ `;+}++export async function getBillingSubscription(shop) {+ const rows = await sql`select * from shopify_billing where shop_domain = ${shop} limit 1`;+ return rows[0] || null;+}++export async function setBillingStatus(shop, status) {+ await sql`update shopify_billing set status = ${status}, updated_at = now() where shop_domain = ${shop}`;+}++// shop/redact fires 48h after uninstall and requires the app to actually+// erase shop-scoped records, unlike the two customer-scoped privacy webhooks+// (this app holds no customer PII, so those are no-ops). Deletes everything+// this app ever stored for the shop: media jobs, billing, and the session row.+export async function eraseShopData(shop) {+ await sql`delete from shopify_media_jobs where shop_domain = ${shop}`;+ await sql`delete from shopify_billing where shop_domain = ${shop}`;+ await sql`delete from shopify_shops where shop_domain = ${shop}`;+}diff --git a/api/_lib/shopify/webhook-register.js b/api/_lib/shopify/webhook-register.jsnew file mode 100644index 000000000..df131649f--- /dev/null+++ b/api/_lib/shopify/webhook-register.js@@ -0,0 +1,38 @@+// Registers the mandatory compliance webhooks plus app/uninstalled right+// after OAuth completes, via webhookSubscriptionCreate (GraphQL) rather than+// shopify.app.toml's static [[webhooks.subscriptions]] block: this app is not+// deployed through the Shopify CLI's config-push flow, so the subscriptions+// have to be created the same way any non-CLI-managed app does.++import { appUrl } from './config.js';+import { adminGraphql, assertNoUserErrors } from './graphql.js';++const MUTATION = `+ mutation webhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) {+ webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) {+ webhookSubscription { id }+ userErrors { field message }+ }+ }+`;++const TOPIC_ENDPOINTS = Object.freeze({+ CUSTOMERS_DATA_REQUEST: '/api/shopify/webhooks/customers-data-request',+ CUSTOMERS_REDACT: '/api/shopify/webhooks/customers-redact',+ SHOP_REDACT: '/api/shopify/webhooks/shop-redact',+ APP_UNINSTALLED: '/api/shopify/webhooks/app-uninstalled',+});++export async function registerMandatoryWebhooks(shop, accessToken) {+ const base = appUrl();+ const results = {};+ for (const [topic, path] of Object.entries(TOPIC_ENDPOINTS)) {+ const data = await adminGraphql(shop, accessToken, MUTATION, {+ topic,+ webhookSubscription: { callbackUrl: `${base}${path}`, format: 'JSON' },+ });+ assertNoUserErrors(data, 'webhookSubscriptionCreate');+ results[topic] = data.webhookSubscriptionCreate.webhookSubscription.id;+ }+ return results;+}diff --git a/api/_lib/shopify/webhook-verify.js b/api/_lib/shopify/webhook-verify.jsnew file mode 100644index 000000000..90ccccf0a--- /dev/null+++ b/api/_lib/shopify/webhook-verify.js@@ -0,0 +1,34 @@+// Shared verify-then-claim path for every /api/shopify/webhooks/* receiver:+// read the raw body, check the HMAC, 401 on failure (Shopify's own+// requirement: "if a mandatory compliance webhook sends a request with an+// invalid Shopify HMAC header, then the app must return a 401 Unauthorized"),+// then claim the delivery id so a retry is a 200 no-op instead of a second+// run of the handler.++import { readBody } from '../http.js';+import { verifyWebhookHmac } from './hmac.js';+import { apiSecret } from './config.js';+import { claimWebhookDelivery } from './store.js';++export class WebhookAuthError extends Error {}++/**+ * @returns {Promise<{ shop: string, body: object, fresh: boolean }>}+ */+export async function verifyAndClaim(req, topic) {+ const raw = await readBody(req, 1_000_000);+ const headerSig = req.headers['x-shopify-hmac-sha256'];+ if (!verifyWebhookHmac(raw, headerSig, apiSecret())) {+ throw new WebhookAuthError('invalid HMAC');+ }+ const shop = String(req.headers['x-shopify-shop-domain'] || '');+ const deliveryId = String(req.headers['x-shopify-webhook-id'] || '');+ const fresh = deliveryId ? await claimWebhookDelivery(shop, topic, deliveryId) : true;+ let body = {};+ try {+ body = JSON.parse(raw.toString('utf8'));+ } catch {+ body = {};+ }+ return { shop, body, fresh };+}diff --git a/api/shopify/billing/activate.js b/api/shopify/billing/activate.jsnew file mode 100644index 000000000..a9dd19bee--- /dev/null+++ b/api/shopify/billing/activate.js@@ -0,0 +1,41 @@+// POST /api/shopify/billing/activate+//+// Starts the shop's usage-based AppSubscription and hands back Shopify's own+// confirmation URL; the embedded UI must redirect the merchant's TOP-LEVEL+// browser tab there (App Bridge's Redirect action, never an iframe) so they+// can approve the plan on Shopify's own page.++import { cors, method, wrap, error, json } from '../../_lib/http.js';+import { authenticateEmbeddedRequest, RequestAuthError } from '../../_lib/shopify/auth-request.js';+import { createUsageSubscription } from '../../_lib/shopify/billing.js';+import { saveBillingSubscription } from '../../_lib/shopify/store.js';+import { appUrl } from '../../_lib/shopify/config.js';+import { ShopifyApiError } from '../../_lib/shopify/graphql.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ let shop, accessToken;+ try {+ ({ shop, accessToken } = await authenticateEmbeddedRequest(req));+ } catch (err) {+ if (err instanceof RequestAuthError) return error(res, err.status, 'unauthorized', err.message);+ throw err;+ }++ try {+ const returnUrl = `${appUrl()}/api/shopify/billing/confirm?shop=${encodeURIComponent(shop)}`;+ const sub = await createUsageSubscription(shop, accessToken, returnUrl);+ await saveBillingSubscription(shop, {+ subscriptionId: sub.subscriptionId,+ lineItemId: sub.lineItemId,+ testMode: sub.testMode,+ status: 'pending',+ });+ return json(res, 200, { confirmationUrl: sub.confirmationUrl, testMode: sub.testMode });+ } catch (err) {+ if (err instanceof ShopifyApiError) return error(res, err.status || 502, 'shopify_api_error', err.message);+ throw err;+ }+});diff --git a/api/shopify/billing/confirm.js b/api/shopify/billing/confirm.jsnew file mode 100644index 000000000..5eb631ea1--- /dev/null+++ b/api/shopify/billing/confirm.js@@ -0,0 +1,35 @@+// GET /api/shopify/billing/confirm?shop=<shop>.myshopify.com+//+// The returnUrl AppSubscriptionCreate redirects the merchant's browser to+// after they approve or decline on Shopify's own confirmation page. This is+// a full navigation (like callback.js), not an App Bridge XHR, so there is+// no session token here; the shop's own stored OAuth session is enough to+// re-ask Shopify's own record of what the merchant decided.++import { cors, method, wrap, error, redirect } from '../../_lib/http.js';+import { apiKey, isValidShopDomain } from '../../_lib/shopify/config.js';+import { getShopSession, setBillingStatus } from '../../_lib/shopify/store.js';+import { fetchActiveSubscription } from '../../_lib/shopify/billing.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://x');+ const shop = (url.searchParams.get('shop') || '').trim().toLowerCase();+ if (!isValidShopDomain(shop)) return error(res, 400, 'invalid_shop', 'shop must be a *.myshopify.com domain');++ const session = await getShopSession(shop);+ if (!session || session.uninstalled_at) {+ return error(res, 401, 'not_installed', 'app is not installed on this shop');+ }++ try {+ const active = await fetchActiveSubscription(shop, session.access_token);+ await setBillingStatus(shop, active && active.status === 'ACTIVE' ? 'active' : 'declined');+ } catch (err) {+ console.error('shopify billing confirm check failed', shop, err?.message || err);+ }++ return redirect(res, `https://${shop}/admin/apps/${apiKey()}`);+});diff --git a/api/shopify/billing/status.js b/api/shopify/billing/status.jsnew file mode 100644index 000000000..ca9fd5f94--- /dev/null+++ b/api/shopify/billing/status.js@@ -0,0 +1,28 @@+// GET /api/shopify/billing/status+//+// Current billing state for the embedded UI's banner: whether the usage+// subscription exists and is active, so the UI can gate generation behind+// "activate billing" until Shopify confirms the merchant approved it.++import { cors, method, wrap, error, json } from '../../_lib/http.js';+import { authenticateEmbeddedRequest, RequestAuthError } from '../../_lib/shopify/auth-request.js';+import { getBillingSubscription } from '../../_lib/shopify/store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ let shop;+ try {+ ({ shop } = await authenticateEmbeddedRequest(req));+ } catch (err) {+ if (err instanceof RequestAuthError) return error(res, err.status, 'unauthorized', err.message);+ throw err;+ }++ const billing = await getBillingSubscription(shop);+ return json(res, 200, {+ status: billing?.status || 'none',+ testMode: billing?.test_mode ?? true,+ });+});diff --git a/api/shopify/callback.js b/api/shopify/callback.jsnew file mode 100644index 000000000..3d69aacab--- /dev/null+++ b/api/shopify/callback.js@@ -0,0 +1,73 @@+// GET /api/shopify/callback?code=...&shop=...&state=...&hmac=...×tamp=...+//+// Finishes OAuth: verifies the query HMAC and the state cookie from install.js,+// exchanges the code for an OFFLINE access token, stores the session,+// registers the mandatory compliance webhooks, and lands the merchant in the+// embedded admin UI.++import { cors, method, wrap, error, redirect } from '../_lib/http.js';+import { readCookie, clearCookie } from '../_lib/identities.js';+import { apiKey, apiSecret, isValidShopDomain, shopifyConfigured, OAUTH_STATE_COOKIE } from '../_lib/shopify/config.js';+import { verifyOAuthHmac } from '../_lib/shopify/hmac.js';+import { saveShopSession } from '../_lib/shopify/store.js';+import { registerMandatoryWebhooks } from '../_lib/shopify/webhook-register.js';++async function exchangeCodeForToken(shop, code) {+ const res = await fetch(`https://${shop}/admin/oauth/access_token`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ client_id: apiKey(), client_secret: apiSecret(), code }),+ signal: AbortSignal.timeout(20_000),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok || !body.access_token) {+ throw Object.assign(new Error(`token exchange failed: ${res.status}`), { status: 502 });+ }+ return { accessToken: body.access_token, scope: body.scope || '' };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;+ if (!shopifyConfigured()) {+ return error(res, 501, 'not_configured', 'Shopify app is not configured');+ }++ const url = new URL(req.url, 'http://x');+ const shop = (url.searchParams.get('shop') || '').trim().toLowerCase();+ if (!isValidShopDomain(shop)) return error(res, 400, 'invalid_shop', 'shop must be a *.myshopify.com domain');++ if (!verifyOAuthHmac(url.searchParams, apiSecret())) {+ return error(res, 401, 'invalid_hmac', 'OAuth callback HMAC verification failed');+ }++ const state = url.searchParams.get('state') || '';+ const cookieState = readCookie(req, OAUTH_STATE_COOKIE);+ if (!state || !cookieState || state !== cookieState) {+ return error(res, 401, 'invalid_state', 'OAuth state mismatch; start the install flow again');+ }+ res.setHeader('set-cookie', clearCookie(OAUTH_STATE_COOKIE));++ const code = url.searchParams.get('code') || '';+ if (!code) return error(res, 400, 'missing_code', 'missing authorization code');++ let accessToken, scope;+ try {+ ({ accessToken, scope } = await exchangeCodeForToken(shop, code));+ } catch (err) {+ return error(res, 502, 'token_exchange_failed', err?.message || 'token exchange failed');+ }++ await saveShopSession(shop, accessToken, scope);++ try {+ await registerMandatoryWebhooks(shop, accessToken);+ } catch (err) {+ // Webhook registration failing must not strand the install: the merchant+ // is mid-flow and a retry endpoint can re-run this safely (webhookSubscriptionCreate+ // is idempotent per topic+shop on Shopify's side). Surface it in logs only.+ console.error('shopify webhook registration failed', shop, err?.message || err);+ }++ return redirect(res, `https://${shop}/admin/apps/${apiKey()}`);+});diff --git a/api/shopify/install.js b/api/shopify/install.jsnew file mode 100644index 000000000..f85b31e58--- /dev/null+++ b/api/shopify/install.js@@ -0,0 +1,36 @@+// GET /api/shopify/install?shop=<shop>.myshopify.com+//+// Start of OAuth. Shopify (or the merchant pasting the app's listing URL)+// lands here first; this redirects to the shop's own /admin/oauth/authorize+// with a random state nonce carried in a short-lived signed cookie, verified+// back in callback.js.++import { cors, method, wrap, error, redirect } from '../_lib/http.js';+import { cookie } from '../_lib/identities.js';+import { randomBytes } from 'node:crypto';+import { apiKey, appUrl, isValidShopDomain, shopifyConfigured, SCOPES, OAUTH_STATE_COOKIE } from '../_lib/shopify/config.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;+ if (!shopifyConfigured()) {+ return error(res, 501, 'not_configured', 'Shopify app is not configured (SHOPIFY_API_KEY/SHOPIFY_API_SECRET unset)');+ }++ const url = new URL(req.url, 'http://x');+ const shop = (url.searchParams.get('shop') || '').trim().toLowerCase();+ if (!isValidShopDomain(shop)) {+ return error(res, 400, 'invalid_shop', 'shop must be a *.myshopify.com domain');+ }++ const state = randomBytes(24).toString('hex');+ res.setHeader('set-cookie', cookie(OAUTH_STATE_COOKIE, state, 600));++ const authorizeUrl = new URL(`https://${shop}/admin/oauth/authorize`);+ authorizeUrl.searchParams.set('client_id', apiKey());+ authorizeUrl.searchParams.set('scope', SCOPES);+ authorizeUrl.searchParams.set('redirect_uri', `${appUrl()}/api/shopify/callback`);+ authorizeUrl.searchParams.set('state', state);++ return redirect(res, authorizeUrl.toString());+});diff --git a/api/shopify/media/attach.js b/api/shopify/media/attach.jsnew file mode 100644index 000000000..e8dd10aa9--- /dev/null+++ b/api/shopify/media/attach.js@@ -0,0 +1,68 @@+// POST /api/shopify/media/attach { jobId }+//+// Attaches a staged GLB to its product via productCreateMedia, then records+// the Billing API usage charge for the conversion (the shop is only charged+// once the model is actually on the product, never for a generation the+// merchant discarded).++import { cors, method, wrap, error, json, readJson } from '../../_lib/http.js';+import { authenticateEmbeddedRequest, RequestAuthError } from '../../_lib/shopify/auth-request.js';+import { getMediaJob, setMediaJobAttached, getBillingSubscription } from '../../_lib/shopify/store.js';+import { attachModel3d } from '../../_lib/shopify/media.js';+import { recordUsage } from '../../_lib/shopify/billing.js';+import { ShopifyApiError } from '../../_lib/shopify/graphql.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ let shop, accessToken;+ try {+ ({ shop, accessToken } = await authenticateEmbeddedRequest(req));+ } catch (err) {+ if (err instanceof RequestAuthError) return error(res, err.status, 'unauthorized', err.message);+ throw err;+ }++ const body = await readJson(req, 100_000);+ const jobId = String(body?.jobId || '');+ if (!jobId) return error(res, 400, 'missing_job_id', 'jobId is required');++ const job = await getMediaJob(shop, jobId);+ if (!job) return error(res, 404, 'not_found', 'no media job with that id for this shop');+ if (job.status !== 'ready_to_attach') {+ return error(res, 409, 'not_ready', `job is not ready to attach (status: ${job.status})`);+ }++ let media;+ try {+ media = await attachModel3d(shop, accessToken, {+ productId: job.product_id,+ resourceUrl: job.staged_resource_url,+ alt: job.product_title ? `${job.product_title} 3D model` : '3D model',+ });+ } catch (err) {+ if (err instanceof ShopifyApiError) return error(res, err.status || 502, 'shopify_api_error', err.message);+ throw err;+ }++ await setMediaJobAttached(jobId, media.id || null);++ const billing = await getBillingSubscription(shop);+ let usageRecorded = false;+ if (billing && billing.status === 'active') {+ try {+ await recordUsage(shop, accessToken, {+ lineItemId: billing.line_item_id,+ description: `3D model for "${job.product_title || job.product_id}"`,+ });+ usageRecorded = true;+ } catch (err) {+ // Attach already succeeded and must not be rolled back for a billing+ // hiccup; log loudly so a missed usage record is investigable, not silent.+ console.error('shopify usage record failed', shop, jobId, err?.message || err);+ }+ }++ return json(res, 200, { jobId, status: 'attached', media, usageRecorded });+});diff --git a/api/shopify/media/create.js b/api/shopify/media/create.jsnew file mode 100644index 000000000..0b9af5b0f--- /dev/null+++ b/api/shopify/media/create.js@@ -0,0 +1,49 @@+// POST /api/shopify/media/create { productId, productTitle, imageUrl }+//+// Starts a Forge image→3D job for one product photo and records a tracking+// row. Reuses the exact /api/forge pipeline every other three.ws surface+// runs on (api/_mcp-studio/forge-client.js) rather than any new generation+// logic: this app is a thin orchestration layer over production infra that+// already exists.++import { cors, method, wrap, error, json, readJson } from '../../_lib/http.js';+import { authenticateEmbeddedRequest, RequestAuthError } from '../../_lib/shopify/auth-request.js';+import { createMediaJob, setMediaJobForgeId, setMediaJobFailed } from '../../_lib/shopify/store.js';+import { startForge, originFromReq } from '../../_mcp-studio/forge-client.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ let shop;+ try {+ ({ shop } = await authenticateEmbeddedRequest(req));+ } catch (err) {+ if (err instanceof RequestAuthError) return error(res, err.status, 'unauthorized', err.message);+ throw err;+ }++ const body = await readJson(req, 1_000_000);+ const productId = String(body?.productId || '');+ const productTitle = typeof body?.productTitle === 'string' ? body.productTitle.slice(0, 500) : '';+ const imageUrl = String(body?.imageUrl || '');+ if (!productId || !imageUrl) return error(res, 400, 'missing_fields', 'productId and imageUrl are required');+ if (!/^https?:\/\//i.test(imageUrl)) return error(res, 400, 'invalid_image_url', 'imageUrl must be an http(s) URL');++ const id = await createMediaJob({ shop, productId, productTitle, imageUrl });++ try {+ const base = originFromReq(req);+ const job = await startForge(base, {+ imageUrls: [imageUrl],+ path: 'image',+ internal: true,+ clientKey: `shopify:${shop}`,+ });+ if (job.job_id) await setMediaJobForgeId(id, job.job_id);+ return json(res, 202, { jobId: id, forgeJobId: job.job_id || null, status: 'generating' });+ } catch (err) {+ await setMediaJobFailed(id, err?.message || 'failed to start generation');+ return error(res, 502, 'forge_submit_failed', err?.message || 'failed to start 3D generation');+ }+});diff --git a/api/shopify/media/status.js b/api/shopify/media/status.jsnew file mode 100644index 000000000..f7b4b5513--- /dev/null+++ b/api/shopify/media/status.js@@ -0,0 +1,80 @@+// GET /api/shopify/media/status?job=<id>+//+// One-shot status check for a media job, polled by the embedded UI. Does a+// single non-blocking GET against /api/forge (never the blocking pollJob+// loop: this is an HTTP handler, not a background worker) and, the moment+// Forge reports done, stages the resulting GLB into Shopify's upload storage+// so the UI's next action (attach) is instant.++import { cors, method, wrap, error, json } from '../../_lib/http.js';+import { authenticateEmbeddedRequest, RequestAuthError } from '../../_lib/shopify/auth-request.js';+import { getMediaJob, setMediaJobReadyToAttach, setMediaJobFailed } from '../../_lib/shopify/store.js';+import { originFromReq } from '../../_mcp-studio/forge-client.js';+import { stageAndUploadGlb } from '../../_lib/shopify/media.js';+import { ShopifyApiError } from '../../_lib/shopify/graphql.js';++async function pollForgeOnce(base, forgeJobId) {+ const res = await fetch(`${base}/api/forge?job=${encodeURIComponent(forgeJobId)}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(20_000),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(data?.message || `generation poll returned ${res.status}`);+ return data;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ let shop, accessToken;+ try {+ ({ shop, accessToken } = await authenticateEmbeddedRequest(req));+ } catch (err) {+ if (err instanceof RequestAuthError) return error(res, err.status, 'unauthorized', err.message);+ throw err;+ }++ const url = new URL(req.url, 'http://x');+ const jobId = url.searchParams.get('job') || '';+ if (!jobId) return error(res, 400, 'missing_job', 'job query param is required');++ const job = await getMediaJob(shop, jobId);+ if (!job) return error(res, 404, 'not_found', 'no media job with that id for this shop');++ if (job.status !== 'generating' || !job.forge_job_id) {+ return json(res, 200, { jobId, status: job.status, glbUrl: job.glb_url || null, error: job.error || null });+ }++ let forgeState;+ try {+ forgeState = await pollForgeOnce(originFromReq(req), job.forge_job_id);+ } catch (err) {+ return json(res, 200, { jobId, status: 'generating', error: null, pollError: err?.message || 'poll failed' });+ }++ if (forgeState.status === 'failed') {+ await setMediaJobFailed(jobId, forgeState.error || 'generation failed');+ return json(res, 200, { jobId, status: 'failed', error: forgeState.error || 'generation failed' });+ }++ if (!(forgeState.status === 'done' && forgeState.glb_url)) {+ return json(res, 200, { jobId, status: 'generating', error: null });+ }++ try {+ const glbRes = await fetch(forgeState.glb_url, { signal: AbortSignal.timeout(30_000) });+ if (!glbRes.ok) throw new Error(`fetching generated GLB returned ${glbRes.status}`);+ const bytes = Buffer.from(await glbRes.arrayBuffer());+ const resourceUrl = await stageAndUploadGlb(shop, accessToken, {+ filename: `${job.product_id.replace(/[^a-zA-Z0-9-]/g, '_')}.glb`,+ bytes,+ });+ await setMediaJobReadyToAttach(jobId, { glbUrl: forgeState.glb_url, stagedResourceUrl: resourceUrl });+ return json(res, 200, { jobId, status: 'ready_to_attach', glbUrl: forgeState.glb_url, error: null });+ } catch (err) {+ const message = err instanceof ShopifyApiError ? err.message : err?.message || 'staging the GLB to Shopify failed';+ await setMediaJobFailed(jobId, message);+ return json(res, 200, { jobId, status: 'failed', error: message });+ }+});diff --git a/api/shopify/products.js b/api/shopify/products.jsnew file mode 100644index 000000000..b81817747--- /dev/null+++ b/api/shopify/products.js@@ -0,0 +1,33 @@+// GET /api/shopify/products?after=<cursor>+//+// Lists the shop's products (title, first image, whether a 3D model is+// already attached) for the embedded admin's product grid.++import { cors, method, wrap, error, json } from '../_lib/http.js';+import { authenticateEmbeddedRequest, RequestAuthError } from '../_lib/shopify/auth-request.js';+import { listProducts } from '../_lib/shopify/media.js';+import { ShopifyApiError } from '../_lib/shopify/graphql.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ let shop, accessToken;+ try {+ ({ shop, accessToken } = await authenticateEmbeddedRequest(req));+ } catch (err) {+ if (err instanceof RequestAuthError) return error(res, err.status, 'unauthorized', err.message);+ throw err;+ }++ const url = new URL(req.url, 'http://x');+ const after = url.searchParams.get('after') || null;++ try {+ const { products, pageInfo } = await listProducts(shop, accessToken, { after });+ return json(res, 200, { products, pageInfo });+ } catch (err) {+ if (err instanceof ShopifyApiError) return error(res, err.status || 502, 'shopify_api_error', err.message);+ throw err;+ }+});diff --git a/api/shopify/webhooks/app-uninstalled.js b/api/shopify/webhooks/app-uninstalled.jsnew file mode 100644index 000000000..b13ea6fa8--- /dev/null+++ b/api/shopify/webhooks/app-uninstalled.js@@ -0,0 +1,26 @@+// POST /api/shopify/webhooks/app-uninstalled+//+// Shopify fires this the moment a merchant uninstalls. The access token is+// already invalid by the time this arrives, so the only job here is to stop+// using it: mark the shop's session dead so no handler tries it again and the+// next install starts clean.++import { cors, method, wrap, error, json } from '../../_lib/http.js';+import { verifyAndClaim, WebhookAuthError } from '../../_lib/shopify/webhook-verify.js';+import { markShopUninstalled } from '../../_lib/shopify/store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ let shop, fresh;+ try {+ ({ shop, fresh } = await verifyAndClaim(req, 'app/uninstalled'));+ } catch (err) {+ if (err instanceof WebhookAuthError) return error(res, 401, 'invalid_hmac', 'webhook HMAC verification failed');+ throw err;+ }++ if (fresh) await markShopUninstalled(shop);+ return json(res, 200, { ok: true });+});diff --git a/api/shopify/webhooks/customers-data-request.js b/api/shopify/webhooks/customers-data-request.jsnew file mode 100644index 000000000..0c7f05f17--- /dev/null+++ b/api/shopify/webhooks/customers-data-request.js@@ -0,0 +1,25 @@+// POST /api/shopify/webhooks/customers-data-request (mandatory GDPR webhook)+//+// Fired when a shop owner requests the data this app holds about one of+// their customers. This app never reads customer data (scopes are+// read_products,write_products only; see api/_lib/shopify/config.js) and+// stores nothing keyed by a customer id, so there is nothing to return.+// Still mandatory to implement, verify, and answer 200 per Shopify's+// compliance-webhook requirements.++import { cors, method, wrap, error, json } from '../../_lib/http.js';+import { verifyAndClaim, WebhookAuthError } from '../../_lib/shopify/webhook-verify.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ try {+ await verifyAndClaim(req, 'customers/data_request');+ } catch (err) {+ if (err instanceof WebhookAuthError) return error(res, 401, 'invalid_hmac', 'webhook HMAC verification failed');+ throw err;+ }++ return json(res, 200, { ok: true, customer_data_held: false });+});diff --git a/api/shopify/webhooks/customers-redact.js b/api/shopify/webhooks/customers-redact.jsnew file mode 100644index 000000000..ad8a5f448--- /dev/null+++ b/api/shopify/webhooks/customers-redact.js@@ -0,0 +1,23 @@+// POST /api/shopify/webhooks/customers-redact (mandatory GDPR webhook)+//+// Fired 10 days after a customer redaction request. Same story as+// customers-data-request.js: this app stores nothing keyed by a customer id+// (media jobs and billing records are keyed by shop only), so there is+// nothing to erase. Still mandatory to implement, verify, and answer 200.++import { cors, method, wrap, error, json } from '../../_lib/http.js';+import { verifyAndClaim, WebhookAuthError } from '../../_lib/shopify/webhook-verify.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ try {+ await verifyAndClaim(req, 'customers/redact');+ } catch (err) {+ if (err instanceof WebhookAuthError) return error(res, 401, 'invalid_hmac', 'webhook HMAC verification failed');+ throw err;+ }++ return json(res, 200, { ok: true, customer_data_held: false });+});diff --git a/api/shopify/webhooks/shop-redact.js b/api/shopify/webhooks/shop-redact.jsnew file mode 100644index 000000000..ea2239a47--- /dev/null+++ b/api/shopify/webhooks/shop-redact.js@@ -0,0 +1,26 @@+// POST /api/shopify/webhooks/shop-redact (mandatory GDPR webhook)+//+// Fired 48 hours after a shop uninstalls the app. Unlike the two+// customer-scoped privacy webhooks, this one is not a no-op: it requires the+// app to actually erase everything it stored for the shop (media jobs,+// billing records, the OAuth session row).++import { cors, method, wrap, error, json } from '../../_lib/http.js';+import { verifyAndClaim, WebhookAuthError } from '../../_lib/shopify/webhook-verify.js';+import { eraseShopData } from '../../_lib/shopify/store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ let shop, fresh;+ try {+ ({ shop, fresh } = await verifyAndClaim(req, 'shop/redact'));+ } catch (err) {+ if (err instanceof WebhookAuthError) return error(res, 401, 'invalid_hmac', 'webhook HMAC verification failed');+ throw err;+ }++ if (fresh) await eraseShopData(shop);+ return json(res, 200, { ok: true });+});diff --git a/data/changelog.json b/data/changelog.jsonindex a25f32c22..d1e789d24 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-13",+ "title": "A Shopify app turns product photos into 3D product media",+ "link": "/docs/shopify-app",+ "summary": "A new embedded Shopify app, built end to end but not yet installable (Partner account, env vars, and App Store submission are owner actions): pick a product photo in the admin, generate a real GLB through three.ws's own /api/forge pipeline, preview it in-page, and attach it with productCreateMedia so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone from the one upload (Shopify derives the USDZ automatically). Bulk mode generates across a whole catalog with real per-item status. Billing runs through Shopify's own usage-based Billing API, priced from Forge's own per-call cost, in test mode until the app has Public distribution. The three mandatory privacy webhooks plus app/uninstalled are HMAC-verified and delivery-deduplicated. Docs: /docs/shopify-app. Submission packet for Partner Dashboard setup and App Store listing copy: marketing/growth/submissions/shopify-app.md.",+ "tags": [+ "feature",+ "docs"+ ]+ },{"date": "2026-10-13","title": "Video to Motion: download any video's motion as a GLB, BVH, or FBX",diff --git a/data/pages.json b/data/pages.jsonindex 866abe36b..efe4e7b93 100644--- a/data/pages.json+++ b/data/pages.json@@ -386,6 +386,15 @@"added": "2026-10-13","indexable": false},+ {+ "path": "/apps/shopify",+ "title": "Photo to 3D product media (Shopify app)",+ "description": "An embedded Shopify admin app that turns a product photo into a real GLB and attaches it to the product, so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone.",+ "priority": 0.2,+ "changefreq": "monthly",+ "added": "2026-10-13",+ "indexable": false+ },{"path": "/knock","title": "Knock",@@ -6730,6 +6739,14 @@"changefreq": "monthly","added": "2026-10-13"},+ {+ "path": "/docs/shopify-app",+ "title": "Docs: Shopify app (Photo to 3D product media)",+ "description": "How the three.ws Shopify app works: OAuth and embedded session tokens, the photo-to-GLB-to-productCreateMedia pipeline, usage-based Billing API integration, and the mandatory privacy webhooks.",+ "priority": 0.6,+ "changefreq": "monthly",+ "added": "2026-10-13"+ },{"path": "/docs/discord-activity","title": "Docs: Discord Activity (Forge Room)",diff --git a/docs/shopify-app.md b/docs/shopify-app.mdnew file mode 100644index 000000000..2d863e6f8--- /dev/null+++ b/docs/shopify-app.md@@ -0,0 +1,102 @@+# Shopify app: Photo to 3D product media++three.ws ships a [Shopify embedded app](https://shopify.dev/docs/apps/build/embedded-app-components)+that turns a product photo into a real, rotatable 3D model and attaches it to+the product. Shopify then shows it on the storefront with its own 3D viewer on+desktop and iOS AR Quick Look on iPhone, both derived from the single GLB this+app uploads.++**On this page:** [How it works](#how-it-works) · [Auth flow](#auth-flow) · [Billing](#billing) · [Privacy webhooks](#privacy-webhooks) · [Owner setup](#owner-setup)++---++## How it works++1. A merchant installs the app from the Shopify App Store (or a direct install+ link during development) and lands on the embedded admin page+ (`pages/shopify-app.html`, `src/shopify-app/app.js`), which lists the+ store's products.+2. For a product without a 3D model, the merchant clicks **Generate 3D+ model**. The app submits the product's first image to three.ws's own+ `/api/forge` image-to-3D pipeline (`api/_mcp-studio/forge-client.js`, the+ same pipeline every other three.ws 3D surface runs on, no separate+ generation logic).+3. Once generation finishes, the GLB is staged into Shopify's own upload+ storage (`stagedUploadsCreate`) and the merchant previews it in-page with+ `<model-viewer>` before confirming **Attach to product**.+4. Attaching calls `productCreateMedia` with `mediaContentType: MODEL_3D`.+ Shopify auto-derives the USDZ AR Quick Look asset from the uploaded GLB, so+ this app uploads exactly one file per product, not two.+5. **Bulk mode**: select every product missing a 3D model and click+ **Generate selected**; each card tracks its own real status+ (generating → ready → attaching → attached, or failed with a retry+ button) instead of one opaque batch spinner.++## Auth flow++Two different authentication shapes, both documented by Shopify:++- **OAuth (install)**: `GET /api/shopify/install` → Shopify's own+ `/admin/oauth/authorize` → `GET /api/shopify/callback`, which verifies the+ query-string HMAC (`api/_lib/shopify/hmac.js`), checks the `state` nonce+ cookie, exchanges the code for an **offline** access token, and registers+ the four mandatory webhooks.+- **Embedded API calls**: every `/api/shopify/*` route other than+ `install`/`callback`/`webhooks`/`billing/confirm` requires a session token+ (`Authorization: Bearer <token>`), the short-lived HS256 JWT Shopify's App+ Bridge CDN script attaches via `window.shopify.idToken()`. Verified in+ `api/_lib/shopify/session-token.js` against the app's client secret, then+ matched to the shop's stored offline token (`api/_lib/shopify/auth-request.js`)+ so the actual Admin GraphQL calls always run with the install-time token,+ never the session token itself.++App Bridge loads via Shopify's CDN script+(`https://cdn.shopify.com/shopifycloud/app-bridge.js`), not the+`@shopify/app-bridge` npm package or the Remix app template: this repo is+vanilla JS + Vite, and the CDN script is Shopify's current framework-agnostic+path. The app's public API key reaches the page through Vite's HTML env+replacement (`%VITE_SHOPIFY_API_KEY%` in `pages/shopify-app.html`), baked in+at build time from the same client id as the server's `SHOPIFY_API_KEY`.++## Billing++One usage-based `AppSubscription` per shop (`api/_lib/shopify/billing.js`):+$0.49 per product converted, capped at $100/month, priced from Forge's own+per-call cost plus Shopify's revenue share. The merchant approves it once+(`POST /api/shopify/billing/activate` → Shopify's own confirmation page,+opened with `window.open(url, '_top')` since Billing approval cannot happen+inside the embedded iframe); `GET /api/shopify/billing/confirm` re-checks+Shopify's own `currentAppInstallation.activeSubscriptions` and records the+result. A usage record is only created at the moment a model is actually+attached (`POST /api/shopify/media/attach`), never for a generation the+merchant discarded.++Every subscription this app creates runs with `test: true` until the app is+approved for Public distribution on the App Store (Shopify's own+`AppSubscriptionCreate` restriction); Shopify records the usage but never+settles a test charge, so the full flow is exercisable before launch. Flip+with `SHOPIFY_BILLING_LIVE=1` once the app is live.++## Privacy webhooks++Four webhooks, registered via GraphQL `webhookSubscriptionCreate` right after+OAuth completes (`api/_lib/shopify/webhook-register.js`), each verified+against `X-Shopify-Hmac-Sha256` (`api/_lib/shopify/webhook-verify.js`) and+claimed against a delivery-id ledger (`shopify_webhook_deliveries`) before any+handler logic runs, so a Shopify retry never double-processes:++- `customers/data_request`, `customers/redact`: no-ops. This app never reads+ customer data (scopes are `read_products,write_products` only) and stores+ nothing keyed by a customer id, so there is nothing to return or erase.+- `shop/redact`: genuinely erases every row this app stored for the shop+ (media jobs, billing, the OAuth session) 48 hours after uninstall.+- `app/uninstalled`: marks the shop's session dead immediately so no later+ call tries to use an access token Shopify has already revoked.++## Owner setup++The app needs a Shopify Partner account, a registered app, and a development+store before any of this can run live. Exact Partner Dashboard settings, env+vars, and the App Store listing copy are written out in+[`marketing/growth/submissions/shopify-app.md`](https://github.com/nirholas/three.ws/blob/main/marketing/growth/submissions/shopify-app.md).+Owner action is tracked in `prompts/finish/_context/production-100-OWNER-ACTIONS.md`.diff --git a/marketing/growth/submissions/shopify-app.md b/marketing/growth/submissions/shopify-app.mdnew file mode 100644index 000000000..9dcb24c82--- /dev/null+++ b/marketing/growth/submissions/shopify-app.md@@ -0,0 +1,198 @@+# Shopify app submission: Photo to 3D product media++Target: [Shopify Partner Dashboard](https://partners.shopify.com) (register+the app) and, once live, the+[Shopify App Store listing requirements](https://shopify.dev/docs/apps/launch/app-requirements-checklist).++Ready for owner order 939. Built and tested in work order 091; the Partner+account, development store, env vars, and App Store submission are owner+actions (CLAUDE.md gate 2 and the "Never blocked" rule for a step that needs+a third-party account only the owner can create). This Evolve session+confirmed no Shopify Partner app exists in production yet:+`node scripts/read-service-env.mjs '^SHOPIFY' --names` returns zero matches,+so `SHOPIFY_API_KEY`, `SHOPIFY_API_SECRET`, `SHOPIFY_APP_URL`, and the+build-time `VITE_SHOPIFY_API_KEY` are all unset.++## What ships++- `api/shopify/install.js`, `api/shopify/callback.js`,+ `api/_lib/shopify/hmac.js`: the OAuth authorization-code flow, query-string+ HMAC verification, offline access-token exchange, and mandatory-webhook+ registration on install.+- `api/_lib/shopify/session-token.js`, `api/_lib/shopify/auth-request.js`:+ embedded-request authentication (HS256 session-token JWTs matched to the+ shop's stored offline token).+- `pages/shopify-app.html` + `src/shopify-app/app.js`: the embedded admin UI+ (App Bridge CDN script, no `@shopify/app-bridge` npm dependency), listing+ products, generating and previewing a model with `<model-viewer>`, bulk+ mode with real per-item status, and a billing banner.+- `api/shopify/products.js`, `api/_lib/shopify/media.js` (`listProducts`): the+ shop's product list via Admin GraphQL, with each product's existing+ 3D-model state already computed server-side.+- `api/shopify/media/create.js`, `api/shopify/media/status.js`,+ `api/shopify/media/attach.js`, `api/_lib/shopify/media.js`: photo to GLB via+ three.ws's own `/api/forge` pipeline, staged upload, and+ `productCreateMedia` with `mediaContentType: MODEL_3D` (Shopify derives the+ USDZ AR asset automatically).+- `api/shopify/billing/activate.js`, `api/shopify/billing/confirm.js`,+ `api/shopify/billing/status.js`, `api/_lib/shopify/billing.js`: usage-based+ `AppSubscription` ($0.49 per product converted, $100/month cap), running in+ Shopify's `test: true` mode until the app has Public distribution.+- `api/shopify/webhooks/customers-data-request.js`,+ `api/shopify/webhooks/customers-redact.js`,+ `api/shopify/webhooks/shop-redact.js`,+ `api/shopify/webhooks/app-uninstalled.js`,+ `api/_lib/shopify/webhook-verify.js`,+ `api/_lib/shopify/webhook-register.js`: the three mandatory privacy+ webhooks plus `app/uninstalled`, HMAC-verified and delivery-id deduplicated+ against `shopify_webhook_deliveries`.+- `api/_lib/shopify/store.js`,+ `api/_lib/migrations/20261015060000_shopify_app.sql`: persistence for the+ OAuth session, media jobs, billing state, and webhook-delivery ledger+ (`shopify_shops`, `shopify_media_jobs`, `shopify_billing`,+ `shopify_webhook_deliveries`).+- Docs: `docs/shopify-app.md`. Changelog, `data/pages.json`, and+ `STRUCTURE.md` wired.++Scopes requested: `read_products,write_products` only. No customer or order+data is ever read, which is why the two customer-facing privacy webhooks are+correct no-ops rather than real data lookups.++## Step 1: create the Shopify Partner account and app++1. Go to <https://partners.shopify.com> and create a Partner account (free)+ if the owner does not already have one.+2. **Apps → Create app** → **Create app manually**.+3. Name: `Photo to 3D product media`.+4. **App URL**: `https://three.ws/apps/shopify`.+5. **Allowed redirection URL(s)**: `https://three.ws/api/shopify/callback`.+6. Under **Client credentials**, copy the **Client ID** (`SHOPIFY_API_KEY`)+ and **Client secret** (`SHOPIFY_API_SECRET`). The secret is shown once.++## Step 2: configure scopes and embedding++1. Under **App setup → App info**, set the configured **Scopes** to+ `read_products,write_products` (matches `SCOPES` in+ `api/_lib/shopify/config.js`; the install flow requests exactly this+ string, no more).+2. Enable **Embedded app** (the admin UI loads inside the Shopify admin+ iframe via App Bridge).+3. Under **App setup → Webhooks**, leave the UI list empty: this app+ registers all four mandatory webhooks itself via GraphQL+ `webhookSubscriptionCreate` right after OAuth completes, pointed at+ `https://three.ws/api/shopify/webhooks/<topic>`.++## Step 3: set the environment on Cloud Run and in the frontend build++Use `--update-env-vars` (never `--set-env-vars`, which replaces the entire+env set):++```bash+gcloud run services update three-ws-api --region us-central1 \+ --update-env-vars SHOPIFY_API_KEY=<client id>,SHOPIFY_API_SECRET=<client secret>,SHOPIFY_APP_URL=https://three.ws+```++`VITE_SHOPIFY_API_KEY` must also be set to the same client ID as a+**build-time** variable (Vite's HTML env replacement bakes it into+`pages/shopify-app.html`'s `<meta name="shopify-api-key">` tag) before the+next `npm run build` that ships to production.++## Step 4: run the migration++```bash+npm run db:status # confirm 20261015060000_shopify_app.sql is the pending one expected+npm run db:migrate # applies immediately, no dry run+```++This creates `shopify_shops`, `shopify_media_jobs`, `shopify_billing`, and+`shopify_webhook_deliveries`.++## Step 5: install on a development store++1. In the Partner Dashboard, **Stores → Add store → Development store**.+2. From the app's **Overview** page, click **Select store** and install on+ the new development store. This exercises the real OAuth flow end to end+ against Shopify's live admin.+3. Add at least one product with a photo before opening the app, so the+ embedded UI has something to generate from.++## Step 6: verify live (this Evolve session cannot reach this point)++1. Open the app from the development store's admin. Confirm the product grid+ loads with real products from the store.+2. Generate a 3D model for one product, preview it with `<model-viewer>`, and+ attach it. Open that product's live storefront page and confirm the 3D+ viewer renders the attached model. Screenshot this as the completion+ evidence for the Definition of Done's first line.+3. Click **Activate billing**, approve the usage plan on Shopify's hosted+ confirmation page (test mode: no real charge), and confirm the banner+ clears. Attach a second model and confirm a usage record appears under+ the app's subscription in the Partner Dashboard's billing section. This is+ the completion evidence for the test-mode-charge Definition of Done line.+4. In the Partner Dashboard, use Shopify's webhook test-delivery tool (+ **App setup → Webhooks → Send test notification**) for each of+ `customers/data_request`, `customers/redact`, `shop/redact`, and+ `app/uninstalled`. Confirm each returns `200` in the delivery log. This is+ the completion evidence for the privacy-webhook Definition of Done line.++## Step 7: App Store submission++Once Step 6 passes, submit through the Partner Dashboard's **Distribution**+tab per the+[App Store requirements checklist](https://shopify.dev/docs/apps/launch/app-requirements-checklist).+Suggested listing copy:++**Name:** Photo to 3D product media++**Tagline:** Turn a product photo into a real 3D model your storefront can+show in AR.++**Description:**++> Give any product a 3D model without a photographer, a 3D artist, or a+> second app to manage payments. Pick a product's photo, generate a real,+> rotatable 3D model, and attach it in one click: Shopify shows it on the+> product page with its own 3D viewer on desktop and AR Quick Look on+> iPhone, automatically, from the single file this app uploads. Bulk-generate+> across an entire catalog with live per-product status, no batch guessing.+> Billing runs through Shopify's own usage-based plan: pay only for the+> products you actually convert, nothing up front.++**Category:** Product media / 3D & AR++**Pricing:** Usage-based, $0.49 per product converted, capped at+$100/month, shown in the merchant's own Shopify bill.++**Primary scopes:** `read_products,write_products` only; no customer or+order data is requested.++## Verification packet++- Source: this repository, `api/shopify/`, `api/_lib/shopify/`,+ `pages/shopify-app.html`, `src/shopify-app/`.+- OAuth HMAC verification and session-token verification are proven with+ real HS256 signing/verification round trips against the app's own secret+ (no mocked crypto); the Admin GraphQL client (`api/_lib/shopify/graphql.js`)+ and Billing mutations are proven against Shopify's documented contract+ shapes, since no live shop or Partner app exists yet to call them against+ for real.+- Local tests: see the `tests/shopify-*.test.js` files added alongside this+ submission.+- `npm run check:rules` passes on every touched file.++## Owner steps (not automatable here)++1. Create the Shopify Partner account and register the app, copy the client+ ID and secret (Step 1).+2. Set scopes to `read_products,write_products` and enable embedding+ (Step 2).+3. Set `SHOPIFY_API_KEY` / `SHOPIFY_API_SECRET` / `SHOPIFY_APP_URL` on Cloud+ Run with `--update-env-vars`, and `VITE_SHOPIFY_API_KEY` before the next+ frontend build (Step 3).+4. Run `npm run db:migrate` for `20261015060000_shopify_app.sql` (Step 4).+5. Create a development store and install the app (Step 5).+6. Generate and attach a model, verify it on the live storefront, approve a+ test-mode billing charge, and send test webhook deliveries from the+ Partner Dashboard; capture the screenshots this Definition of Done needs+ (Step 6).+7. Submit the App Store listing using the copy above (Step 7).diff --git a/pages/shopify-app.html b/pages/shopify-app.htmlnew file mode 100644index 000000000..395c297e1--- /dev/null+++ b/pages/shopify-app.html@@ -0,0 +1,129 @@+<!doctype html>+<html lang="en">+ <head>+ <style>/* three.ws hidden-guard - make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />+ <title>Photo to 3D product media · three.ws for Shopify</title>+ <meta name="description" content="Turn a product photo into a real 3D model your storefront can show in AR, generated in-app and attached to the product automatically." />+ <meta name="robots" content="noindex" />+ <meta name="theme-color" content="#0a0a0a" />+ <!-- %VITE_SHOPIFY_API_KEY% is substituted at build time by Vite's HTML env+ replacement (vite.config.js envPrefix default: VITE_*) from the same+ client id as the server's SHOPIFY_API_KEY; see docs/shopify-app.md. -->+ <meta name="shopify-api-key" content="%VITE_SHOPIFY_API_KEY%" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>+ <script src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js" type="module"></script>+ <style>+ :root {+ --bg: #0d0d0d; --card: #181818; --line: rgba(255,255,255,0.08); --line-2: rgba(255,255,255,0.14);+ --text: #e7e9ee; --muted: rgba(231,233,238,0.6); --dim: rgba(231,233,238,0.4);+ --accent: #008060; --green: #22c55e; --red: #ef4444; --amber: #f59e0b;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; }+ body {+ background: var(--bg); color: var(--text); font: 14px/1.5 -apple-system, system-ui, 'Inter', sans-serif;+ -webkit-font-smoothing: antialiased;+ }+ .sa-shell { max-width: 960px; margin: 0 auto; padding: 20px 16px 60px; display: flex; flex-direction: column; gap: 18px; }+ button { font: inherit; cursor: pointer; }++ .sa-header h1 { font-size: 18px; margin: 0 0 4px; letter-spacing: -0.01em; }+ .sa-header p { margin: 0; color: var(--muted); font-size: 13px; max-width: 60ch; }++ .sa-banner { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; border: 1px solid var(--line-2); border-radius: 12px; background: var(--card); padding: 14px 16px; }+ .sa-banner--warn { border-color: rgba(245,158,11,.35); background: rgba(245,158,11,.08); }+ .sa-banner--error { border-color: rgba(239,68,68,.35); background: rgba(239,68,68,.08); }+ .sa-banner p { margin: 0; font-size: 13px; }+ .sa-banner .sa-dim { color: var(--muted); }++ .sa-btn { background: var(--accent); color: #fff; border: none; border-radius: 8px; padding: 9px 16px; font-weight: 600; transition: filter .15s ease; }+ .sa-btn:hover { filter: brightness(1.12); }+ .sa-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+ .sa-btn:disabled { opacity: .45; cursor: not-allowed; filter: none; }+ .sa-btn--ghost { background: transparent; border: 1px solid var(--line-2); color: var(--text); }+ .sa-btn--ghost:hover { border-color: var(--accent); }+ .sa-btn--sm { padding: 6px 11px; font-size: 12.5px; }+ .sa-btn--danger { background: var(--red); }++ .sa-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }+ .sa-bulkbar { display: flex; align-items: center; gap: 10px; font-size: 13px; color: var(--muted); }+ .sa-bulkbar label { display: flex; align-items: center; gap: 6px; cursor: pointer; }++ .sa-center { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 60px 20px; text-align: center; color: var(--muted); }+ .sa-spinner { width: 26px; height: 26px; border-radius: 50%; border: 3px solid var(--line-2); border-top-color: var(--accent); animation: sa-spin .8s linear infinite; }+ @keyframes sa-spin { to { transform: rotate(360deg); } }+ @media (prefers-reduced-motion: reduce) { .sa-spinner { animation: none; } }++ .sa-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 14px; }+ .sa-card { border: 1px solid var(--line); border-radius: 12px; background: var(--card); overflow: hidden; display: flex; flex-direction: column; }+ .sa-card-select { display: flex; align-items: center; gap: 8px; padding: 8px 10px 0; }+ .sa-card-media { position: relative; width: 100%; height: 160px; background: #000; display: flex; align-items: center; justify-content: center; }+ .sa-card-media img, .sa-card-media model-viewer { width: 100%; height: 100%; object-fit: contain; }+ .sa-card-badge { position: absolute; top: 8px; right: 8px; background: rgba(0,0,0,.65); border: 1px solid var(--line-2); border-radius: 999px; padding: 2px 9px; font-size: 11px; color: var(--green); }+ .sa-card-body { padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; flex: 1; }+ .sa-card-title { font-size: 13px; font-weight: 600; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .sa-card-status { font-size: 12px; color: var(--muted); min-height: 1.3em; }+ .sa-card-status--failed { color: var(--red); }+ .sa-card-status--ready { color: var(--green); }+ .sa-card-actions { display: flex; gap: 8px; margin-top: auto; }++ .sa-empty { border: 1px dashed var(--line-2); border-radius: 12px; padding: 40px 20px; text-align: center; color: var(--muted); }+ .sa-empty strong { color: var(--text); display: block; margin-bottom: 6px; }++ .sa-loadmore { display: flex; justify-content: center; }+ .sa-footer-note { font-size: 11.5px; color: var(--dim); text-align: center; }+ .sa-sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0,0,0,0); }+ </style>+ </head>+ <body>+ <div class="sa-shell">+ <div class="sa-header">+ <h1>Photo to 3D product media</h1>+ <p>Pick a product photo and generate a real, rotatable 3D model. Attach it and Shopify shows it on the storefront with a 3D viewer on desktop and AR Quick Look on iPhone, automatically.</p>+ </div>++ <div id="sa-billing-banner" class="sa-banner sa-banner--warn" hidden>+ <p><strong>Billing isn't active yet.</strong> <span class="sa-dim">$0.49 per product converted, capped at $100/month. Approve the usage plan to start generating.</span></p>+ <button id="sa-billing-activate" class="sa-btn sa-btn--sm" type="button">Activate billing</button>+ </div>++ <div id="sa-error-banner" class="sa-banner sa-banner--error" role="alert" hidden>+ <p id="sa-error-text"></p>+ <button id="sa-error-retry" class="sa-btn sa-btn--ghost sa-btn--sm" type="button">Retry</button>+ </div>++ <div id="sa-boot" class="sa-center">+ <div class="sa-spinner" role="status" aria-label="Loading"></div>+ <p>Loading your products...</p>+ </div>++ <div id="sa-main" hidden style="display: flex; flex-direction: column; gap: 14px;">+ <div class="sa-toolbar">+ <div class="sa-bulkbar">+ <label><input id="sa-select-all" type="checkbox" /> Select all without a 3D model</label>+ <span id="sa-select-count"></span>+ </div>+ <button id="sa-bulk-generate" class="sa-btn" type="button" disabled>Generate selected</button>+ </div>++ <div id="sa-empty" class="sa-empty" hidden>+ <strong>No products yet</strong>+ Add a product with a photo in Shopify admin, then come back here to give it a 3D model.+ </div>++ <div id="sa-grid" class="sa-grid" role="list"></div>++ <div id="sa-loadmore" class="sa-loadmore" hidden>+ <button id="sa-loadmore-btn" class="sa-btn sa-btn--ghost" type="button">Load more products</button>+ </div>+ </div>++ <p class="sa-footer-note">Model generation and hosting run on three.ws's own infrastructure. Shopify charges your store through its standard Billing API; three.ws never sees your payment details.</p>+ </div>++ <script type="module" src="/src/shopify-app/app.js"></script>+ </body>+</html>diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex c16792f65..f6a88b746 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,11 +1,11 @@{- "generated_at": "2026-10-13T16:58:17.417Z",+ "generated_at": "2026-10-13T17:59:16.355Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 4059,+ "total": 4062,"complete": false,"full_feed": "/changelog.json","entries": [@@ -39,6 +39,16 @@"launch"]},+ {+ "date": "2026-10-13",+ "type": "launch",+ "title": "Docs: Shopify app (Photo to 3D product media)",+ "summary": "How the three.ws Shopify app works: OAuth and embedded session tokens, the photo-to-GLB-to-productCreateMedia pipeline, usage-based Billing API integration, and the mandatory privacy webhooks.",+ "link": "/docs/shopify-app",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-13","type": "launch",@@ -59,6 +69,16 @@"launch"]},+ {+ "date": "2026-10-13",+ "type": "launch",+ "title": "Photo to 3D product media (Shopify app)",+ "summary": "An embedded Shopify admin app that turns a product photo into a real GLB and attaches it to the product, so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone.",+ "link": "/apps/shopify",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-13","type": "launch",@@ -80,6 +100,17 @@"docs"]},+ {+ "date": "2026-10-13",+ "type": "update",+ "title": "A Shopify app turns product photos into 3D product media",+ "summary": "A new embedded Shopify app, built end to end but not yet installable (Partner account, env vars, and App Store submission are owner actions): pick a product photo in the admin, generate a real GLB through three.ws's own /api/forge pipeline, preview it in-page, and attach it with productCreateMedia so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone from the one upload (Shopify derives the USDZ automatically). Bulk mode generates across a whole catalog with real per-item status. Billing runs through Shopify's own usage-based Billing API, priced from Forge's own per-call cost, in test mode until the app has Public distribution. The three mandatory privacy webhooks plus app/uninstalled are HMAC-verified and delivery-deduplicated. Docs: /docs/shopify-app. Submission packet for Partner Dashboard setup and App Store listing copy: marketing/growth/submissions/shopify-app.md.",+ "link": "/docs/shopify-app",+ "tags": [+ "feature",+ "docs"+ ]+ },{"date": "2026-10-13","type": "update",@@ -1526,37 +1557,6 @@"feature","security"]- },- {- "date": "2026-10-10",- "type": "update",- "title": "Sign in with Telegram, link devices with one-time codes, and prove payout wallets with a signature",- "summary": "You can now sign in to three.ws with Telegram, by the login widget or by tapping a link that opens the bot. Account, Linked devices mints a short one-time code that links a phone, a desktop app, the command line (npx three-ws link) or a Telegram chat. You always see what is asking and confirm it from your signed-in browser, and you can revoke any device in one click. Agents and owners can attach a Solana or EVM wallet by signing a message. Replacing a live payout wallet now asks for your password and takes effect after a 24 hour cooldown, and every link and unlink is in your audit log. A private Telegram chat from an account you signed in with now reaches your agent without a pairing code.",- "link": "/dashboard/account",- "tags": [- "feature",- "security"- ]- },- {- "date": "2026-10-10",- "type": "update",- "title": "Specialist teams: four agents that research before they trade",- "summary": "Assemble a squad of four 3D agents in one click: a Researcher that vets a token and posts a scored verdict, an Entry scout that checks fresh launches against your entry gates, a Trader that quotes, simulates or trades inside one spend policy, and a Launcher that prepares a launch plan for you to sign. They share a live findings board. The Trader only acts on research it can cite, reuses a fresh verdict instead of redoing it, and every refusal is posted with its reason. Only the Trader can ever sign, and only a live trade you confirm.",- "link": "/teams",- "tags": [- "feature"- ]- },- {- "date": "2026-10-10",- "type": "update",- "title": "Strategies now research every coin and ask before they buy",- "summary": "Trading strategies can now check a coin before spending anything: minimum holders, how much the largest holder owns, liquidity, the rug and honeypot safety score, whether the creator can still mint or freeze, and the creator's track record. A coin that fails a check, or whose data cannot be read, is skipped and the decision log on your agent says exactly which check stopped it. You can also cap price impact per buy. Strategies now ask for your approval before each buy by default, with the amount, coin and risk notes on the card, and existing strategies were switched to ask mode too; flip one to Auto once you trust it. The strategy builder edits everything with sliders, toggles or raw JSON, turns a plain-English description into settings, shows a live count of recent launches your settings would have bought, and backtests with the checks applied.",- "link": "/strategies",- "tags": [- "feature"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex a36e73f59..42595eb89 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-13T16:58:17.389Z",+ "generated_at": "2026-10-13T17:59:16.332Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -36,6 +36,16 @@"launch"]},+ {+ "date": "2026-10-13",+ "type": "launch",+ "title": "Docs: Shopify app (Photo to 3D product media)",+ "summary": "How the three.ws Shopify app works: OAuth and embedded session tokens, the photo-to-GLB-to-productCreateMedia pipeline, usage-based Billing API integration, and the mandatory privacy webhooks.",+ "link": "/docs/shopify-app",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-13","type": "launch",@@ -56,6 +66,16 @@"launch"]},+ {+ "date": "2026-10-13",+ "type": "launch",+ "title": "Photo to 3D product media (Shopify app)",+ "summary": "An embedded Shopify admin app that turns a product photo into a real GLB and attaches it to the product, so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone.",+ "link": "/apps/shopify",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-13","type": "launch",@@ -77,6 +97,17 @@"docs"]},+ {+ "date": "2026-10-13",+ "type": "update",+ "title": "A Shopify app turns product photos into 3D product media",+ "summary": "A new embedded Shopify app, built end to end but not yet installable (Partner account, env vars, and App Store submission are owner actions): pick a product photo in the admin, generate a real GLB through three.ws's own /api/forge pipeline, preview it in-page, and attach it with productCreateMedia so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone from the one upload (Shopify derives the USDZ automatically). Bulk mode generates across a whole catalog with real per-item status. Billing runs through Shopify's own usage-based Billing API, priced from Forge's own per-call cost, in test mode until the app has Public distribution. The three mandatory privacy webhooks plus app/uninstalled are HMAC-verified and delivery-deduplicated. Docs: /docs/shopify-app. Submission packet for Partner Dashboard setup and App Store listing copy: marketing/growth/submissions/shopify-app.md.",+ "link": "/docs/shopify-app",+ "tags": [+ "feature",+ "docs"+ ]+ },{"date": "2026-10-13","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex f0d6db2f3..c77f0b981 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -30,6 +30,14 @@<category>launch</category><description>How to drive a three.ws <agent-3d> avatar's lipsync and gestures from a LiveKit Agents or Pipecat voice pipeline, with the livekit-plugins-threews and pipecat-threews packages, runnable local examples, and the data-channel message contract both share.</description></item>+ <item>+ <title>Docs: Shopify app (Photo to 3D product media)</title>+ <link>https://three.ws/docs/shopify-app</link>+ <guid isPermaLink="false">2026-10-13:Docs: Shopify app (Photo to 3D product media)</guid>+ <pubDate>Tue, 13 Oct 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>How the three.ws Shopify app works: OAuth and embedded session tokens, the photo-to-GLB-to-productCreateMedia pipeline, usage-based Billing API integration, and the mandatory privacy webhooks.</description>+ </item><item><title>Forge Room (Discord Activity)</title><link>https://three.ws/discord-activity</link>@@ -46,6 +54,14 @@<category>launch</category><description>Every open-source project, GPU model, and asset source three.ws is built on, grouped by what it powers: rendering, formats and compression, generation models, motion, voice, assets, and infrastructure. Generated from package.json on every build.</description></item>+ <item>+ <title>Photo to 3D product media (Shopify app)</title>+ <link>https://three.ws/apps/shopify</link>+ <guid isPermaLink="false">2026-10-13:Photo to 3D product media (Shopify app)</guid>+ <pubDate>Tue, 13 Oct 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>An embedded Shopify admin app that turns a product photo into a real GLB and attaches it to the product, so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone.</description>+ </item><item><title>Video to Motion: Turn Any Video into an Animation File</title><link>https://three.ws/video-to-motion</link>@@ -62,6 +78,14 @@<category>feature</category><description>Open the new Activity from a Discord voice channel and everyone in the call shares one Forge room: one prompt, one in-progress generation, one finished model with a shared vote count, and an agent that reacts in text to what just happened. Auth maps a verified Discord identity (re-checked against Discord's own /users/@me, never trusted from the client) to a room-scoped session; generation and voting reuse the real /api/forge pipeline and forge_votes table rather than a separate throwaway pipeline. No coin, wallet, or purchase path. Docs: /docs/discord-activity. Submission packet for Developer Portal setup and Discovery copy: marketing/growth/submissions/discord-activity.md.</description></item>+ <item>+ <title>A Shopify app turns product photos into 3D product media</title>+ <link>https://three.ws/docs/shopify-app</link>+ <guid isPermaLink="false">2026-10-13:A Shopify app turns product photos into 3D product media</guid>+ <pubDate>Tue, 13 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A new embedded Shopify app, built end to end but not yet installable (Partner account, env vars, and App Store submission are owner actions): pick a product photo in the admin, generate a real GLB through three.ws's own /api/forge pipeline, preview it in-page, and attach it with productCreateMedia so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone from the one upload (Shopify derives the USDZ automatically). Bulk mode generates across a whole catalog with real per-item status. Billing runs through Shopify's own usage-based Billing API, priced from Forge's own per-call cost, in test mode until the app has Public distribution. The three mandatory privacy webhooks plus app/uninstalled are HMAC-verified and delivery-deduplicated. Docs: /docs/shopify-app. Submission packet for Partner Dashboard setup and App Store listing copy: marketing/growth/submissions/shopify-app.md.</description>+ </item><item><title>A three.ws avatar now lipsyncs to any LiveKit Agents or Pipecat voice pipeline</title><link>https://three.ws/docs/voice-framework-integrations</link>diff --git a/public/features.json b/public/features.jsonindex 7e14057dc..985be61f2 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-13T16:58:17.372Z",+ "generated_at": "2026-10-13T17:59:16.310Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -554,6 +554,18 @@"priority": 0.3,"job": "explore"},+ {+ "path": "/apps/shopify",+ "title": "Photo to 3D product media (Shopify app)",+ "description": "An embedded Shopify admin app that turns a product photo into a real GLB and attaches it to the product, so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone.",+ "added": "2026-10-13",+ "auth": null,+ "indexable": false,+ "tags": [],+ "showcase": false,+ "priority": 0.2,+ "job": "explore"+ },{"path": "/knock","title": "Knock",@@ -10388,6 +10400,18 @@"priority": 0.7,"job": null},+ {+ "path": "/docs/shopify-app",+ "title": "Docs: Shopify app (Photo to 3D product media)",+ "description": "How the three.ws Shopify app works: OAuth and embedded session tokens, the photo-to-GLB-to-productCreateMedia pipeline, usage-based Billing API integration, and the mandatory privacy webhooks.",+ "added": "2026-10-13",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false,+ "priority": 0.6,+ "job": null+ },{"path": "/docs/discord-activity","title": "Docs: Discord Activity (Forge Room)",diff --git a/public/llms-full.txt b/public/llms-full.txtindex eb180df4a..77e3f7154 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -250,6 +250,13 @@ Indexable: no (excluded from sitemap)A shared Forge room that runs embedded inside a Discord voice channel: everyone in the call prompts, watches the same 3D model generate, and votes together.+### Photo to 3D product media (Shopify app)++URL: https://three.ws/apps/shopify+Indexable: no (excluded from sitemap)++An embedded Shopify admin app that turns a product photo into a real GLB and attaches it to the product, so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone.+### KnockURL: https://three.ws/knock@@ -5222,6 +5229,12 @@ URL: https://three.ws/docs/voice-framework-integrationsHow to drive a three.ws <agent-3d> avatar's lipsync and gestures from a LiveKit Agents or Pipecat voice pipeline, with the livekit-plugins-threews and pipecat-threews packages, runnable local examples, and the data-channel message contract both share.+### Docs: Shopify app (Photo to 3D product media)++URL: https://three.ws/docs/shopify-app++How the three.ws Shopify app works: OAuth and embedded session tokens, the photo-to-GLB-to-productCreateMedia pipeline, usage-based Billing API integration, and the mandatory privacy webhooks.+### Docs: Discord Activity (Forge Room)URL: https://three.ws/docs/discord-activitydiff --git a/public/llms.txt b/public/llms.txtindex eb928567a..1b1370aa7 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -101,6 +101,6 @@ Machine-readable entry points. Fetch these instead of scraping HTML.## Optional-- [llms-full.txt](https://three.ws/llms-full.txt): Every public page (1008), grouped by section, with full descriptions.+- [llms-full.txt](https://three.ws/llms-full.txt): Every public page (1009), grouped by section, with full descriptions.- [Sitemap](https://three.ws/sitemap): The same index for people, with search.- [sitemap.xml](https://three.ws/sitemap.xml): XML sitemap for crawlers, including every agent and avatar page.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 16b4ffb85..b1a4dc6d5 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -96,7 +96,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p><span>1068</span> <span data-i18n="sitemap_index.pages_grouped">pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</span></p>+ <p><span>1070</span> <span data-i18n="sitemap_index.pages_grouped">pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</span></p><div class="sm-formats"><a href="/everything"><code>/everything</code> · browse by goal, not by section</a><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>@@ -109,7 +109,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 1068 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 1070 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd id="sm-filter-kbd" aria-hidden="true">/</kbd></div><p class="sm-filter-count" role="status" aria-live="polite"><span id="sm-filter-count"></span><span id="sm-filter-hint" aria-hidden="true"></span></p>@@ -141,6 +141,14 @@<span class="sm-desc" data-i18n="sitemap_index.d_docs_voice_framework_integrations">How to drive a three.ws <agent-3d> avatar's lipsync and gestures from a LiveKit Agents or Pipecat voice pipeline, with the livekit-plugins-threews and pipecat-threews packages, runnable local examples, and the data-channel message contract both share.</span></a></li>+ <li>+ <a href="/docs/shopify-app">+ <span class="sm-new-date" translate="no">Oct 13, 2026</span>+ <span class="sm-title"><span data-i18n="sitemap_index.t_docs_shopify_app">Docs: Shopify app (Photo to 3D product media)</span></span>+ <span class="sm-path" translate="no">/docs/shopify-app</span>+ <span class="sm-desc" data-i18n="sitemap_index.d_docs_shopify_app">How the three.ws Shopify app works: OAuth and embedded session tokens, the photo-to-GLB-to-productCreateMedia pipeline, usage-based Billing API integration, and the mandatory privacy webhooks.</span>+ </a>+ </li><li><a href="/docs/discord-activity"><span class="sm-new-date" translate="no">Oct 13, 2026</span>@@ -181,14 +189,6 @@<span class="sm-desc" data-i18n="sitemap_index.d_classic">The original three.ws landing page: the pitch, live agent demos and the front door to every flow, kept as the classic view of the desktop.</span></a></li>- <li>- <a href="/everything">- <span class="sm-new-date" translate="no">Oct 11, 2026</span>- <span class="sm-title"><span data-i18n="sitemap_index.t_everything">Everything three.ws Does</span></span>- <span class="sm-path" translate="no">/everything</span>- <span class="sm-desc" data-i18n="sitemap_index.d_everything">Every three.ws feature organised by what you want to do: make a 3D avatar, build an agent, embed it, sell skills, launch a token, trade and more. Searchable, with pins and a new-this-month feed.</span>- </a>- </li></ul></section><nav class="sm-toc" aria-label="Sections">@@ -206,7 +206,7 @@</nav><section class="sm-section" id="main"><header>- <h2><span data-i18n="sitemap_index.section_main">Main</span><span class="sm-count" data-count>72</span></h2>+ <h2><span data-i18n="sitemap_index.section_main">Main</span><span class="sm-count" data-count>73</span></h2><p class="sm-section-desc">Entry points into the product.</p></header><ul class="sm-list">@@ -469,6 +469,13 @@<span class="sm-desc" data-i18n="sitemap_index.d_discord_activity">A shared Forge room that runs embedded inside a Discord voice channel: everyone in the call prompts, watches the same 3D model generate, and votes together.</span></a></li>+ <li>+ <a href="/apps/shopify">+ <span class="sm-title"><span data-i18n="sitemap_index.t_apps_shopify">Photo to 3D product media (Shopify app)</span><span class="sm-badge sm-badge-internal" data-i18n="sitemap_index.badge_internal">internal</span></span>+ <span class="sm-path" translate="no">/apps/shopify</span>+ <span class="sm-desc" data-i18n="sitemap_index.d_apps_shopify">An embedded Shopify admin app that turns a product photo into a real GLB and attaches it to the product, so the storefront shows a 3D viewer on desktop and AR Quick Look on iPhone.</span>+ </a>+ </li><li><a href="/knock"><span class="sm-title"><span data-i18n="sitemap_index.t_knock">Knock</span></span>@@ -2969,7 +2976,7 @@<section class="sm-section" id="learn"><header>- <h2><span data-i18n="sitemap_index.section_learn">Learn</span><span class="sm-count" data-count>503</span></h2>+ <h2><span data-i18n="sitemap_index.section_learn">Learn</span><span class="sm-count" data-count>504</span></h2><p class="sm-section-desc">Docs, tutorials, and reference.</p></header><ul class="sm-list">@@ -6235,6 +6242,13 @@<span class="sm-desc" data-i18n="sitemap_index.d_docs_voice_framework_integrations">How to drive a three.ws <agent-3d> avatar's lipsync and gestures from a LiveKit Agents or Pipecat voice pipeline, with the livekit-plugins-threews and pipecat-threews packages, runnable local examples, and the data-channel message contract both share.</span></a></li>+ <li>+ <a href="/docs/shopify-app">+ <span class="sm-title"><span data-i18n="sitemap_index.t_docs_shopify_app">Docs: Shopify app (Photo to 3D product media)</span></span>+ <span class="sm-path" translate="no">/docs/shopify-app</span>+ <span class="sm-desc" data-i18n="sitemap_index.d_docs_shopify_app">How the three.ws Shopify app works: OAuth and embedded session tokens, the photo-to-GLB-to-productCreateMedia pipeline, usage-based Billing API integration, and the mandatory privacy webhooks.</span>+ </a>+ </li><li><a href="/docs/discord-activity"><span class="sm-title"><span data-i18n="sitemap_index.t_docs_discord_activity">Docs: Discord Activity (Forge Room)</span></span>diff --git a/src/shopify-app/app.js b/src/shopify-app/app.jsnew file mode 100644index 000000000..0640fdd82--- /dev/null+++ b/src/shopify-app/app.js@@ -0,0 +1,336 @@+// Embedded admin UI for the "Photo to 3D product media" Shopify app.+//+// App Bridge is loaded via Shopify's CDN script in pages/shopify-app.html+// (the current documented, framework-agnostic embedding path, no+// @shopify/app-bridge npm package, consistent with this repo building+// directly against Shopify's documented contracts rather than its React/Remix+// SDKs). That script attaches a global `window.shopify` with `idToken()`,+// which this module calls before every API request: embedded apps are+// required to authenticate via session tokens, not cookies.++const POLL_MS = 3_000;+const POLL_TIMEOUT_MS = 10 * 60 * 1000;+const BULK_CONCURRENCY = 3;++const els = {+ billingBanner: document.getElementById('sa-billing-banner'),+ billingActivate: document.getElementById('sa-billing-activate'),+ errorBanner: document.getElementById('sa-error-banner'),+ errorText: document.getElementById('sa-error-text'),+ errorRetry: document.getElementById('sa-error-retry'),+ boot: document.getElementById('sa-boot'),+ main: document.getElementById('sa-main'),+ selectAll: document.getElementById('sa-select-all'),+ selectCount: document.getElementById('sa-select-count'),+ bulkGenerate: document.getElementById('sa-bulk-generate'),+ empty: document.getElementById('sa-empty'),+ grid: document.getElementById('sa-grid'),+ loadMore: document.getElementById('sa-loadmore'),+ loadMoreBtn: document.getElementById('sa-loadmore-btn'),+};++/** @type {Map<string, { product: object, job: { status: string, jobId: string|null, glbUrl: string|null, error: string|null }, selected: boolean }>} */+const cards = new Map();+let pageInfo = { hasNextPage: false, endCursor: null };++function show(el) {+ if (el) el.hidden = false;+}+function hide(el) {+ if (el) el.hidden = true;+}++async function getSessionToken() {+ const deadline = Date.now() + 5_000;+ while (!window.shopify?.idToken) {+ if (Date.now() > deadline) {+ throw new Error('App Bridge did not load. Open this app from inside your Shopify admin.');+ }+ await new Promise((r) => setTimeout(r, 100));+ }+ return window.shopify.idToken();+}++async function api(path, opts = {}) {+ const token = await getSessionToken();+ const res = await fetch(path, {+ ...opts,+ headers: {+ ...(opts.body ? { 'content-type': 'application/json' } : {}),+ authorization: `Bearer ${token}`,+ ...(opts.headers || {}),+ },+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw new Error(data?.error_description || data?.message || `request failed (${res.status})`);+ }+ return data;+}++function fatalError(message, onRetry) {+ els.errorText.textContent = message;+ show(els.errorBanner);+ els.errorRetry.onclick = () => {+ hide(els.errorBanner);+ onRetry();+ };+}++function productImageUrl(product) {+ return product.images?.[0]?.url || null;+}++function renderCardMedia(entry) {+ const { product, job } = entry;+ if (job.status === 'ready_to_attach' || job.status === 'attaching') {+ return `<model-viewer src="${job.glbUrl}" camera-controls auto-rotate shadow-intensity="1" style="width:100%;height:100%;background:#000;" alt="Generated 3D model preview"></model-viewer>`;+ }+ const img = productImageUrl(product);+ return img+ ? `<img src="${img}" alt="" loading="lazy" />`+ : `<span style="color:var(--dim);font-size:12px;">No image</span>`;+}++function statusLabel(job) {+ switch (job.status) {+ case 'idle':+ return '';+ case 'generating':+ return 'Generating 3D model...';+ case 'ready_to_attach':+ return 'Ready to preview above.';+ case 'attaching':+ return 'Attaching to product...';+ case 'attached':+ return 'Attached.';+ case 'failed':+ return job.error ? `Failed: ${job.error}` : 'Generation failed.';+ default:+ return '';+ }+}++function renderCardActions(entry) {+ const { product, job } = entry;+ if (product.has3dModel && job.status === 'idle') {+ return '';+ }+ if (job.status === 'idle' || job.status === 'failed') {+ return `<button class="sa-btn sa-btn--sm sa-act-generate" type="button">${job.status === 'failed' ? 'Retry' : 'Generate 3D model'}</button>`;+ }+ if (job.status === 'generating' || job.status === 'attaching') {+ return `<button class="sa-btn sa-btn--sm sa-btn--ghost" type="button" disabled>Working...</button>`;+ }+ if (job.status === 'ready_to_attach') {+ return `<button class="sa-btn sa-btn--sm sa-act-attach" type="button">Attach to product</button>`;+ }+ return '';+}++function renderCard(entry) {+ const { product, job, selected } = entry;+ const el = document.createElement('div');+ el.className = 'sa-card';+ el.setAttribute('role', 'listitem');+ el.dataset.productId = product.id;+ const canSelect = !product.has3dModel && job.status === 'idle';+ el.innerHTML = `+ <div class="sa-card-select">+ ${canSelect ? `<label class="sa-sr-only" for="sel-${product.id}">Select ${product.title}</label><input id="sel-${product.id}" type="checkbox" class="sa-card-checkbox" ${selected ? 'checked' : ''} />` : ''}+ </div>+ <div class="sa-card-media">+ ${renderCardMedia(entry)}+ ${product.has3dModel ? '<span class="sa-card-badge">3D</span>' : ''}+ </div>+ <div class="sa-card-body">+ <p class="sa-card-title" title="${escapeAttr(product.title)}">${escapeHtml(product.title)}</p>+ <p class="sa-card-status ${job.status === 'failed' ? 'sa-card-status--failed' : ''} ${job.status === 'attached' ? 'sa-card-status--ready' : ''}">${escapeHtml(statusLabel(job))}</p>+ <div class="sa-card-actions">${renderCardActions(entry)}</div>+ </div>+ `;++ const checkbox = el.querySelector('.sa-card-checkbox');+ if (checkbox) {+ checkbox.addEventListener('change', () => {+ entry.selected = checkbox.checked;+ updateBulkBar();+ });+ }+ const genBtn = el.querySelector('.sa-act-generate');+ if (genBtn) genBtn.addEventListener('click', () => startGeneration(entry, { bulk: false }));+ const attachBtn = el.querySelector('.sa-act-attach');+ if (attachBtn) attachBtn.addEventListener('click', () => attachJob(entry));++ return el;+}++function escapeHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}+function escapeAttr(s) {+ return escapeHtml(s).replace(/`/g, '`');+}++function renderGrid() {+ els.grid.innerHTML = '';+ for (const entry of cards.values()) {+ els.grid.appendChild(renderCard(entry));+ }+ hide(els.empty);+ if (cards.size === 0) show(els.empty);+ els.loadMore.hidden = !pageInfo.hasNextPage;+ updateBulkBar();+}++function updateBulkBar() {+ const selectable = [...cards.values()].filter((e) => !e.product.has3dModel && e.job.status === 'idle');+ const selected = selectable.filter((e) => e.selected);+ els.selectCount.textContent = selected.length ? `${selected.length} selected` : '';+ els.bulkGenerate.disabled = selected.length === 0;+ els.selectAll.disabled = selectable.length === 0;+ els.selectAll.checked = selectable.length > 0 && selected.length === selectable.length;+}++async function loadProducts(after = null) {+ const qs = after ? `?after=${encodeURIComponent(after)}` : '';+ const data = await api(`/api/shopify/products${qs}`);+ for (const product of data.products) {+ if (!cards.has(product.id)) {+ cards.set(product.id, { product, job: { status: 'idle', jobId: null, glbUrl: null, error: null }, selected: false });+ }+ }+ pageInfo = data.pageInfo;+ renderGrid();+}++function updateCard(entry) {+ const node = renderCard(entry);+ const existing = els.grid.querySelector(`[data-product-id="${cssEscape(entry.product.id)}"]`);+ if (existing) existing.replaceWith(node);+ else renderGrid();+ updateBulkBar();+}++function cssEscape(s) {+ return window.CSS?.escape ? CSS.escape(s) : String(s).replace(/["\\]/g, '\\$&');+}++async function pollStatus(entry, { bulk }) {+ const deadline = Date.now() + POLL_TIMEOUT_MS;+ while (Date.now() < deadline) {+ let data;+ try {+ data = await api(`/api/shopify/media/status?job=${encodeURIComponent(entry.job.jobId)}`);+ } catch (err) {+ entry.job = { ...entry.job, status: 'failed', error: err.message };+ updateCard(entry);+ return;+ }+ entry.job = { ...entry.job, status: data.status, glbUrl: data.glbUrl || entry.job.glbUrl, error: data.error };+ updateCard(entry);+ if (data.status === 'ready_to_attach') {+ if (bulk) await attachJob(entry);+ return;+ }+ if (data.status === 'failed') return;+ await new Promise((r) => setTimeout(r, POLL_MS));+ }+ entry.job = { ...entry.job, status: 'failed', error: 'generation timed out' };+ updateCard(entry);+}++async function startGeneration(entry, { bulk }) {+ entry.selected = false;+ entry.job = { status: 'generating', jobId: null, glbUrl: null, error: null };+ updateCard(entry);+ try {+ const imageUrl = productImageUrl(entry.product);+ if (!imageUrl) throw new Error('this product has no image to generate from');+ const data = await api('/api/shopify/media/create', {+ method: 'POST',+ body: JSON.stringify({ productId: entry.product.id, productTitle: entry.product.title, imageUrl }),+ });+ entry.job.jobId = data.jobId;+ updateCard(entry);+ await pollStatus(entry, { bulk });+ } catch (err) {+ entry.job = { ...entry.job, status: 'failed', error: err.message };+ updateCard(entry);+ }+}++async function attachJob(entry) {+ entry.job = { ...entry.job, status: 'attaching' };+ updateCard(entry);+ try {+ await api('/api/shopify/media/attach', { method: 'POST', body: JSON.stringify({ jobId: entry.job.jobId }) });+ entry.product.has3dModel = true;+ entry.job = { ...entry.job, status: 'attached' };+ } catch (err) {+ entry.job = { ...entry.job, status: 'failed', error: err.message };+ }+ updateCard(entry);+}++async function runBulk() {+ const selected = [...cards.values()].filter((e) => e.selected);+ els.bulkGenerate.disabled = true;+ let i = 0;+ async function worker() {+ while (i < selected.length) {+ const entry = selected[i++];+ await startGeneration(entry, { bulk: true });+ }+ }+ await Promise.all(Array.from({ length: Math.min(BULK_CONCURRENCY, selected.length) }, worker));+ updateBulkBar();+}++async function loadBillingBanner() {+ const data = await api('/api/shopify/billing/status');+ if (data.status === 'active') {+ hide(els.billingBanner);+ } else {+ show(els.billingBanner);+ }+}++async function activateBilling() {+ els.billingActivate.disabled = true;+ els.billingActivate.textContent = 'Opening Shopify...';+ try {+ const data = await api('/api/shopify/billing/activate', { method: 'POST', body: '{}' });+ window.open(data.confirmationUrl, '_top');+ } catch (err) {+ els.billingActivate.disabled = false;+ els.billingActivate.textContent = 'Activate billing';+ fatalError(err.message, boot);+ }+}++els.selectAll.addEventListener('change', () => {+ for (const entry of cards.values()) {+ if (!entry.product.has3dModel && entry.job.status === 'idle') entry.selected = els.selectAll.checked;+ }+ renderGrid();+});+els.bulkGenerate.addEventListener('click', runBulk);+els.billingActivate.addEventListener('click', activateBilling);+els.loadMoreBtn.addEventListener('click', () => loadProducts(pageInfo.endCursor));++async function boot() {+ hide(els.errorBanner);+ show(els.boot);+ hide(els.main);+ try {+ await Promise.all([loadBillingBanner(), loadProducts()]);+ hide(els.boot);+ show(els.main);+ } catch (err) {+ hide(els.boot);+ fatalError(err.message, boot);+ }+}++boot();diff --git a/tests/shopify-graphql.test.js b/tests/shopify-graphql.test.jsnew file mode 100644index 000000000..3a6e742ef--- /dev/null+++ b/tests/shopify-graphql.test.js@@ -0,0 +1,270 @@+// api/_lib/shopify/graphql.js, media.js, billing.js: the Admin GraphQL+// client and the two higher-level call shapes it backs (product media,+// usage billing), against a mocked fetch that returns Shopify-shaped+// responses. Asserts the exact request shape (endpoint, headers, variables)+// so a future refactor can't silently drop the access token or mis-shape a+// mutation.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++process.env.SHOPIFY_API_KEY = 'test-api-key';+process.env.SHOPIFY_API_SECRET = 'test-api-secret';++const { adminGraphql, assertNoUserErrors, ShopifyApiError } = await import('../api/_lib/shopify/graphql.js');+const { listProducts, stageAndUploadGlb, attachModel3d } = await import('../api/_lib/shopify/media.js');+const { createUsageSubscription, fetchActiveSubscription, recordUsage } = await import(+ '../api/_lib/shopify/billing.js'+);++const SHOP = 'example.myshopify.com';+const TOKEN = 'offline-access-token';++function jsonResponse(body, { ok = true, status = 200 } = {}) {+ return { ok, status, json: async () => body };+}++describe('adminGraphql', () => {+ let fetchSpy;+ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ });+ afterEach(() => fetchSpy.mockRestore());++ it('posts to the versioned Admin API endpoint with the access token header', async () => {+ fetchSpy.mockResolvedValue(jsonResponse({ data: { ok: true } }));+ await adminGraphql(SHOP, TOKEN, 'query { shop { name } }', { a: 1 });++ const [url, init] = fetchSpy.mock.calls[0];+ expect(url).toBe(`https://${SHOP}/admin/api/2026-10/graphql.json`);+ expect(init.method).toBe('POST');+ expect(init.headers['x-shopify-access-token']).toBe(TOKEN);+ expect(JSON.parse(init.body)).toEqual({ query: 'query { shop { name } }', variables: { a: 1 } });+ });++ it('throws ShopifyApiError on a non-2xx response', async () => {+ fetchSpy.mockResolvedValue(jsonResponse({}, { ok: false, status: 401 }));+ await expect(adminGraphql(SHOP, TOKEN, 'query {}')).rejects.toMatchObject({ status: 401 });+ });++ it('throws ShopifyApiError when the GraphQL body carries top-level errors', async () => {+ fetchSpy.mockResolvedValue(jsonResponse({ errors: [{ message: 'Throttled' }] }));+ await expect(adminGraphql(SHOP, TOKEN, 'query {}')).rejects.toBeInstanceOf(ShopifyApiError);+ });+});++describe('assertNoUserErrors', () => {+ it('is a no-op when userErrors is empty', () => {+ expect(() => assertNoUserErrors({ stagedUploadsCreate: { userErrors: [] } }, 'stagedUploadsCreate')).not.toThrow();+ });++ it('throws with the field path when userErrors is non-empty', () => {+ expect(() =>+ assertNoUserErrors(+ { stagedUploadsCreate: { userErrors: [{ field: ['input', 'filename'], message: 'is required' }] } },+ 'stagedUploadsCreate'+ )+ ).toThrow(/filename: is required/);+ });+});++describe('listProducts', () => {+ let fetchSpy;+ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ });+ afterEach(() => fetchSpy.mockRestore());++ it('maps products and computes has3dModel from existing media', async () => {+ fetchSpy.mockResolvedValue(+ jsonResponse({+ data: {+ products: {+ pageInfo: { hasNextPage: false, endCursor: null },+ nodes: [+ {+ id: 'gid://shopify/Product/1',+ title: 'Mug',+ images: { nodes: [{ id: 'img1', url: 'https://x/mug.jpg', altText: null }] },+ media: { nodes: [{ mediaContentType: 'IMAGE' }] },+ },+ {+ id: 'gid://shopify/Product/2',+ title: 'Lamp',+ images: { nodes: [] },+ media: { nodes: [{ mediaContentType: 'MODEL_3D' }] },+ },+ ],+ },+ },+ })+ );++ const { products, pageInfo } = await listProducts(SHOP, TOKEN);+ expect(pageInfo).toEqual({ hasNextPage: false, endCursor: null });+ expect(products).toEqual([+ { id: 'gid://shopify/Product/1', title: 'Mug', images: [{ id: 'img1', url: 'https://x/mug.jpg', altText: null }], has3dModel: false },+ { id: 'gid://shopify/Product/2', title: 'Lamp', images: [], has3dModel: true },+ ]);+ });+});++describe('stageAndUploadGlb', () => {+ let fetchSpy;+ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ });+ afterEach(() => fetchSpy.mockRestore());++ it('stages the upload then PUTs the bytes, returning the resourceUrl', async () => {+ fetchSpy+ .mockResolvedValueOnce(+ jsonResponse({+ data: {+ stagedUploadsCreate: {+ stagedTargets: [+ {+ url: 'https://shopify-staged.example.com/upload',+ resourceUrl: 'https://shopify-staged.example.com/resource/abc',+ parameters: [{ name: 'key', value: 'uploads/abc.glb' }],+ },+ ],+ userErrors: [],+ },+ },+ })+ )+ .mockResolvedValueOnce({ ok: true, text: async () => '' });++ const resourceUrl = await stageAndUploadGlb(SHOP, TOKEN, { filename: 'model.glb', bytes: Buffer.from('glb-bytes') });+ expect(resourceUrl).toBe('https://shopify-staged.example.com/resource/abc');++ const [stageUrl, stageInit] = fetchSpy.mock.calls[0];+ expect(stageUrl).toContain('/admin/api/2026-10/graphql.json');+ const stageVars = JSON.parse(stageInit.body).variables;+ expect(stageVars.input[0]).toMatchObject({ resource: 'MODEL_3D', filename: 'model.glb', mimeType: 'model/gltf-binary' });++ const [uploadUrl, uploadInit] = fetchSpy.mock.calls[1];+ expect(uploadUrl).toBe('https://shopify-staged.example.com/upload');+ expect(uploadInit.method).toBe('POST');+ });++ it('throws when Shopify storage rejects the upload', async () => {+ fetchSpy+ .mockResolvedValueOnce(+ jsonResponse({+ data: {+ stagedUploadsCreate: {+ stagedTargets: [{ url: 'https://shopify-staged.example.com/upload', resourceUrl: 'https://x/resource', parameters: [] }],+ userErrors: [],+ },+ },+ })+ )+ .mockResolvedValueOnce({ ok: false, status: 403, text: async () => 'Forbidden' });++ await expect(+ stageAndUploadGlb(SHOP, TOKEN, { filename: 'model.glb', bytes: Buffer.from('x') })+ ).rejects.toBeInstanceOf(ShopifyApiError);+ });+});++describe('attachModel3d', () => {+ let fetchSpy;+ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ });+ afterEach(() => fetchSpy.mockRestore());++ it('attaches with mediaContentType MODEL_3D and returns the created media', async () => {+ fetchSpy.mockResolvedValue(+ jsonResponse({+ data: {+ productCreateMedia: {+ media: [{ id: 'gid://shopify/MediaImage/9', alt: '3D model', mediaContentType: 'MODEL_3D', status: 'UPLOADED' }],+ mediaUserErrors: [],+ },+ },+ })+ );++ const media = await attachModel3d(SHOP, TOKEN, {+ productId: 'gid://shopify/Product/1',+ resourceUrl: 'https://shopify-staged.example.com/resource/abc',+ alt: 'Mug 3D model',+ });+ expect(media).toEqual({ id: 'gid://shopify/MediaImage/9', alt: '3D model', mediaContentType: 'MODEL_3D', status: 'UPLOADED' });++ const variables = JSON.parse(fetchSpy.mock.calls[0][1].body).variables;+ expect(variables.media[0]).toMatchObject({ originalSource: 'https://shopify-staged.example.com/resource/abc', mediaContentType: 'MODEL_3D' });+ });++ it('throws ShopifyApiError on mediaUserErrors', async () => {+ fetchSpy.mockResolvedValue(+ jsonResponse({+ data: {+ productCreateMedia: {+ media: [],+ mediaUserErrors: [{ field: ['media'], message: 'could not process the model' }],+ },+ },+ })+ );+ await expect(+ attachModel3d(SHOP, TOKEN, { productId: 'gid://shopify/Product/1', resourceUrl: 'https://x', alt: 'x' })+ ).rejects.toBeInstanceOf(ShopifyApiError);+ });+});++describe('billing', () => {+ let fetchSpy;+ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ });+ afterEach(() => fetchSpy.mockRestore());++ it('creates a usage subscription with the capped amount and confirmation URL', async () => {+ fetchSpy.mockResolvedValue(+ jsonResponse({+ data: {+ appSubscriptionCreate: {+ appSubscription: { id: 'gid://shopify/AppSubscription/1', lineItems: [{ id: 'gid://shopify/AppSubscriptionLineItem/1' }] },+ confirmationUrl: 'https://example.myshopify.com/admin/charges/1/confirm',+ userErrors: [],+ },+ },+ })+ );++ const result = await createUsageSubscription(SHOP, TOKEN, 'https://three.ws/api/shopify/billing/confirm');+ expect(result).toMatchObject({+ subscriptionId: 'gid://shopify/AppSubscription/1',+ lineItemId: 'gid://shopify/AppSubscriptionLineItem/1',+ confirmationUrl: 'https://example.myshopify.com/admin/charges/1/confirm',+ });++ const variables = JSON.parse(fetchSpy.mock.calls[0][1].body).variables;+ expect(variables.cappedAmount).toEqual({ amount: '100.00', currencyCode: 'USD' });+ expect(variables.returnUrl).toBe('https://three.ws/api/shopify/billing/confirm');+ });++ it('reads the active subscription or null when none exists', async () => {+ fetchSpy.mockResolvedValue(jsonResponse({ data: { currentAppInstallation: { activeSubscriptions: [] } } }));+ expect(await fetchActiveSubscription(SHOP, TOKEN)).toBeNull();++ fetchSpy.mockResolvedValue(+ jsonResponse({ data: { currentAppInstallation: { activeSubscriptions: [{ id: 'sub-1', status: 'ACTIVE', lineItems: [] }] } } })+ );+ expect(await fetchActiveSubscription(SHOP, TOKEN)).toMatchObject({ id: 'sub-1', status: 'ACTIVE' });+ });++ it('records usage priced at the configured per-conversion rate', async () => {+ fetchSpy.mockResolvedValue(+ jsonResponse({ data: { appUsageRecordCreate: { appUsageRecord: { id: 'gid://shopify/AppUsageRecord/1' }, userErrors: [] } } })+ );+ const id = await recordUsage(SHOP, TOKEN, { lineItemId: 'gid://shopify/AppSubscriptionLineItem/1', description: 'Mug converted' });+ expect(id).toBe('gid://shopify/AppUsageRecord/1');++ const variables = JSON.parse(fetchSpy.mock.calls[0][1].body).variables;+ expect(variables.price).toEqual({ amount: '0.49', currencyCode: 'USD' });+ });+});diff --git a/tests/shopify-hmac.test.js b/tests/shopify-hmac.test.jsnew file mode 100644index 000000000..25810396d--- /dev/null+++ b/tests/shopify-hmac.test.js@@ -0,0 +1,73 @@+// api/_lib/shopify/hmac.js: real HMAC-SHA256 sign/verify round trips for+// both of Shopify's schemes, unmocked. No fake/sample signatures: every+// "valid" case in this file is generated the same way Shopify generates one.++import { describe, it, expect } from 'vitest';+import { createHmac } from 'node:crypto';+import { verifyOAuthHmac, verifyWebhookHmac } from '../api/_lib/shopify/hmac.js';++const SECRET = 'test-shopify-client-secret';++function signOAuthParams(params, secret) {+ const pairs = [...params.entries()].filter(([k]) => k !== 'hmac' && k !== 'signature');+ pairs.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ const message = pairs.map(([k, v]) => `${k}=${v}`).join('&');+ return createHmac('sha256', secret).update(message).digest('hex');+}++describe('shopify hmac: OAuth query string', () => {+ it('accepts a correctly signed install/callback redirect', () => {+ const params = new URLSearchParams({+ shop: 'example.myshopify.com',+ timestamp: '1700000000',+ code: 'abc123',+ });+ params.set('hmac', signOAuthParams(params, SECRET));+ expect(verifyOAuthHmac(params, SECRET)).toBe(true);+ });++ it('rejects a tampered query string', () => {+ const params = new URLSearchParams({+ shop: 'example.myshopify.com',+ timestamp: '1700000000',+ code: 'abc123',+ });+ params.set('hmac', signOAuthParams(params, SECRET));+ params.set('shop', 'attacker.myshopify.com');+ expect(verifyOAuthHmac(params, SECRET)).toBe(false);+ });++ it('rejects a redirect signed with the wrong secret', () => {+ const params = new URLSearchParams({ shop: 'example.myshopify.com', timestamp: '1700000000' });+ params.set('hmac', signOAuthParams(params, 'a-different-secret'));+ expect(verifyOAuthHmac(params, SECRET)).toBe(false);+ });++ it('rejects a missing hmac param or missing secret', () => {+ const params = new URLSearchParams({ shop: 'example.myshopify.com' });+ expect(verifyOAuthHmac(params, SECRET)).toBe(false);+ params.set('hmac', 'deadbeef');+ expect(verifyOAuthHmac(params, '')).toBe(false);+ });+});++describe('shopify hmac: webhook body', () => {+ it('accepts a correctly signed webhook delivery', () => {+ const raw = Buffer.from(JSON.stringify({ shop_id: 1, shop_domain: 'example.myshopify.com' }));+ const sig = createHmac('sha256', SECRET).update(raw).digest('base64');+ expect(verifyWebhookHmac(raw, sig, SECRET)).toBe(true);+ });++ it('rejects a body that does not match the signature', () => {+ const raw = Buffer.from(JSON.stringify({ shop_id: 1 }));+ const sig = createHmac('sha256', SECRET).update(Buffer.from('something else')).digest('base64');+ expect(verifyWebhookHmac(raw, sig, SECRET)).toBe(false);+ });++ it('rejects a missing header or missing secret', () => {+ const raw = Buffer.from('{}');+ expect(verifyWebhookHmac(raw, '', SECRET)).toBe(false);+ const sig = createHmac('sha256', SECRET).update(raw).digest('base64');+ expect(verifyWebhookHmac(raw, sig, '')).toBe(false);+ });+});diff --git a/tests/shopify-session-token.test.js b/tests/shopify-session-token.test.jsnew file mode 100644index 000000000..4f3c03677--- /dev/null+++ b/tests/shopify-session-token.test.js@@ -0,0 +1,85 @@+// api/_lib/shopify/session-token.js: real HS256 JWT sign/verify round trips+// (via `jose`, unmocked) for the session token App Bridge attaches to every+// embedded-app request.++import { describe, it, expect, beforeAll } from 'vitest';+import { SignJWT } from 'jose';++process.env.SHOPIFY_API_KEY = 'test-api-key';+process.env.SHOPIFY_API_SECRET = 'test-api-secret';++const { verifySessionToken, bearerFromRequest, SessionTokenError } = await import(+ '../api/_lib/shopify/session-token.js'+);++async function signToken(claims, { secret = process.env.SHOPIFY_API_SECRET, alg = 'HS256' } = {}) {+ const now = Math.floor(Date.now() / 1000);+ return new SignJWT({+ iss: 'https://example.myshopify.com/admin',+ dest: 'https://example.myshopify.com',+ aud: process.env.SHOPIFY_API_KEY,+ sub: '12345',+ sid: 'session-1',+ ...claims,+ })+ .setProtectedHeader({ alg })+ .setIssuedAt(now)+ .setNotBefore(now)+ .setExpirationTime(now + 60)+ .sign(new TextEncoder().encode(secret));+}++describe('shopify session token', () => {+ it('verifies a real session token and extracts shop/user/session', async () => {+ const token = await signToken({});+ const result = await verifySessionToken(token);+ expect(result).toEqual({ shop: 'example.myshopify.com', userId: '12345', sessionId: 'session-1' });+ });++ it('rejects a token signed with a different secret', async () => {+ const token = await signToken({}, { secret: 'wrong-secret' });+ await expect(verifySessionToken(token)).rejects.toBeInstanceOf(SessionTokenError);+ });++ it('rejects a token whose aud does not match this app', async () => {+ const token = await signToken({ aud: 'some-other-app-client-id' });+ await expect(verifySessionToken(token)).rejects.toBeInstanceOf(SessionTokenError);+ });++ it('rejects a token whose iss does not match its dest shop', async () => {+ const token = await signToken({ iss: 'https://attacker.myshopify.com/admin' });+ await expect(verifySessionToken(token)).rejects.toBeInstanceOf(SessionTokenError);+ });++ it('rejects an expired token', async () => {+ const now = Math.floor(Date.now() / 1000) - 120;+ const token = await new SignJWT({+ iss: 'https://example.myshopify.com/admin',+ dest: 'https://example.myshopify.com',+ aud: process.env.SHOPIFY_API_KEY,+ sub: '12345',+ sid: 'session-1',+ })+ .setProtectedHeader({ alg: 'HS256' })+ .setIssuedAt(now)+ .setExpirationTime(now + 60)+ .sign(new TextEncoder().encode(process.env.SHOPIFY_API_SECRET));+ await expect(verifySessionToken(token)).rejects.toBeInstanceOf(SessionTokenError);+ });++ it('rejects missing/malformed tokens without throwing an unrelated error', async () => {+ await expect(verifySessionToken('')).rejects.toBeInstanceOf(SessionTokenError);+ await expect(verifySessionToken('not-a-jwt')).rejects.toBeInstanceOf(SessionTokenError);+ });+});++describe('bearerFromRequest', () => {+ it('extracts the token from a well-formed Authorization header', () => {+ expect(bearerFromRequest({ headers: { authorization: 'Bearer abc.def.ghi' } })).toBe('abc.def.ghi');+ });++ it('returns empty string when the header is missing or malformed', () => {+ expect(bearerFromRequest({ headers: {} })).toBe('');+ expect(bearerFromRequest({ headers: { authorization: 'Basic xyz' } })).toBe('');+ });+});diff --git a/tests/shopify-store.test.js b/tests/shopify-store.test.jsnew file mode 100644index 000000000..9614032e7--- /dev/null+++ b/tests/shopify-store.test.js@@ -0,0 +1,224 @@+// api/_lib/shopify/store.js against a real in-process Postgres (PGlite): the+// OAuth session upsert, media-job status transitions, billing state, the+// webhook delivery idempotency ledger, and shop/redact's real erase. No+// mocked SQL semantics: this is the real ON CONFLICT, the real CHECK+// constraint, the real FK cascade.++import { beforeAll, beforeEach, describe, it, expect, vi } from 'vitest';+import { createPgliteSql } from './_helpers/pglite-sql.js';++const holder = vi.hoisted(() => ({ db: null }));++vi.mock('../api/_lib/db.js', async (importActual) => {+ const actual = await importActual();+ return { ...actual, sql: (...args) => holder.db.sql(...args) };+});++const DDL = `+ create table shopify_shops (+ shop_domain text primary key,+ access_token text not null,+ scope text not null,+ installed_at timestamptz not null default now(),+ uninstalled_at timestamptz+ );+ create table shopify_media_jobs (+ id uuid primary key default gen_random_uuid(),+ shop_domain text not null references shopify_shops(shop_domain),+ product_id text not null,+ product_title text,+ image_url text not null,+ forge_job_id text,+ status text not null default 'generating',+ glb_url text,+ staged_resource_url text,+ media_id text,+ error text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ constraint shopify_media_jobs_status_check check (+ status in ('generating', 'ready_to_attach', 'attaching', 'attached', 'failed')+ )+ );+ create table shopify_webhook_deliveries (+ shop_domain text not null,+ topic text not null,+ delivery_id text not null,+ received_at timestamptz not null default now(),+ primary key (topic, delivery_id)+ );+ create table shopify_billing (+ shop_domain text primary key references shopify_shops(shop_domain),+ subscription_id text not null,+ line_item_id text not null,+ test_mode boolean not null default true,+ status text not null default 'pending',+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ constraint shopify_billing_status_check check (status in ('pending', 'active', 'declined', 'cancelled'))+ );+`;++let store;++beforeAll(async () => {+ store = await import('../api/_lib/shopify/store.js');+});++beforeEach(async () => {+ holder.db = createPgliteSql();+ await holder.db.exec(DDL);+});++describe('shop session', () => {+ it('saves and reads back a shop session, nulling uninstalled_at on reinstall', async () => {+ const shop = 'example.myshopify.com';+ await store.saveShopSession(shop, 'token-1', 'read_products,write_products');+ let session = await store.getShopSession(shop);+ expect(session).toMatchObject({ shop_domain: shop, access_token: 'token-1', uninstalled_at: null });++ await store.markShopUninstalled(shop);+ session = await store.getShopSession(shop);+ expect(session.uninstalled_at).not.toBeNull();++ await store.saveShopSession(shop, 'token-2', 'read_products,write_products');+ session = await store.getShopSession(shop);+ expect(session).toMatchObject({ access_token: 'token-2', uninstalled_at: null });+ });++ it('returns null for a shop that never installed', async () => {+ expect(await store.getShopSession('nope.myshopify.com')).toBeNull();+ });+});++describe('webhook delivery ledger', () => {+ it('claims a delivery once and rejects a replay of the same id', async () => {+ const first = await store.claimWebhookDelivery('example.myshopify.com', 'APP_UNINSTALLED', 'delivery-1');+ const replay = await store.claimWebhookDelivery('example.myshopify.com', 'APP_UNINSTALLED', 'delivery-1');+ expect(first).toBe(true);+ expect(replay).toBe(false);+ });++ it('treats the same delivery id on a different topic as a separate claim', async () => {+ const a = await store.claimWebhookDelivery('example.myshopify.com', 'APP_UNINSTALLED', 'shared-id');+ const b = await store.claimWebhookDelivery('example.myshopify.com', 'SHOP_REDACT', 'shared-id');+ expect(a).toBe(true);+ expect(b).toBe(true);+ });+});++describe('media jobs', () => {+ async function seedShop(shop = 'example.myshopify.com') {+ await store.saveShopSession(shop, 'token-1', 'read_products,write_products');+ return shop;+ }++ it('walks a job through generating -> ready_to_attach -> attached', async () => {+ const shop = await seedShop();+ const id = await store.createMediaJob({+ shop,+ productId: 'gid://shopify/Product/1',+ productTitle: 'Test Product',+ imageUrl: 'https://cdn.example.com/photo.jpg',+ forgeJobId: null,+ });++ let job = await store.getMediaJob(shop, id);+ expect(job.status).toBe('generating');++ await store.setMediaJobForgeId(id, 'forge-job-1');+ job = await store.getMediaJob(shop, id);+ expect(job.forge_job_id).toBe('forge-job-1');++ await store.setMediaJobReadyToAttach(id, {+ glbUrl: 'https://forge.example.com/model.glb',+ stagedResourceUrl: 'https://shopify-staged.example.com/upload',+ });+ job = await store.getMediaJob(shop, id);+ expect(job.status).toBe('ready_to_attach');+ expect(job.glb_url).toBe('https://forge.example.com/model.glb');++ await store.setMediaJobAttached(id, 'gid://shopify/MediaImage/9');+ job = await store.getMediaJob(shop, id);+ expect(job.status).toBe('attached');+ expect(job.media_id).toBe('gid://shopify/MediaImage/9');+ });++ it('records a failure with its error message', async () => {+ const shop = await seedShop();+ const id = await store.createMediaJob({+ shop,+ productId: 'gid://shopify/Product/2',+ productTitle: null,+ imageUrl: 'https://cdn.example.com/photo2.jpg',+ forgeJobId: null,+ });+ await store.setMediaJobFailed(id, 'forge generation failed: timeout');+ const job = await store.getMediaJob(shop, id);+ expect(job.status).toBe('failed');+ expect(job.error).toBe('forge generation failed: timeout');+ });++ it('rejects an invalid status at the database layer', async () => {+ const shop = await seedShop();+ await expect(+ holder.db.sql`insert into shopify_media_jobs (shop_domain, product_id, image_url, status) values (${shop}, 'p1', 'https://x', 'not-a-real-status')`+ ).rejects.toThrow();+ });+});++describe('billing', () => {+ it('saves, reads, and transitions a billing subscription', async () => {+ const shop = 'example.myshopify.com';+ await store.saveShopSession(shop, 'token-1', 'read_products,write_products');++ await store.saveBillingSubscription(shop, {+ subscriptionId: 'gid://shopify/AppSubscription/1',+ lineItemId: 'gid://shopify/AppSubscriptionLineItem/1',+ testMode: true,+ status: 'pending',+ });+ let billing = await store.getBillingSubscription(shop);+ expect(billing).toMatchObject({ status: 'pending', test_mode: true });++ await store.setBillingStatus(shop, 'active');+ billing = await store.getBillingSubscription(shop);+ expect(billing.status).toBe('active');+ });++ it('returns null when no subscription exists yet', async () => {+ await store.saveShopSession('fresh.myshopify.com', 'token-1', 'read_products,write_products');+ expect(await store.getBillingSubscription('fresh.myshopify.com')).toBeNull();+ });+});++describe('eraseShopData (shop/redact)', () => {+ it('deletes media jobs, billing, and the session row for the shop', async () => {+ const shop = 'erase-me.myshopify.com';+ await store.saveShopSession(shop, 'token-1', 'read_products,write_products');+ await store.createMediaJob({ shop, productId: 'p1', productTitle: 't', imageUrl: 'https://x', forgeJobId: null });+ await store.saveBillingSubscription(shop, {+ subscriptionId: 'sub-1',+ lineItemId: 'li-1',+ testMode: true,+ status: 'active',+ });++ await store.eraseShopData(shop);++ expect(await store.getShopSession(shop)).toBeNull();+ expect(await store.getBillingSubscription(shop)).toBeNull();+ const jobs = await holder.db.sql`select id from shopify_media_jobs where shop_domain = ${shop}`;+ expect(jobs).toHaveLength(0);+ });++ it('leaves other shops untouched', async () => {+ await store.saveShopSession('keep-me.myshopify.com', 'token-1', 'read_products,write_products');+ await store.saveShopSession('erase-me-2.myshopify.com', 'token-1', 'read_products,write_products');++ await store.eraseShopData('erase-me-2.myshopify.com');++ expect(await store.getShopSession('keep-me.myshopify.com')).not.toBeNull();+ expect(await store.getShopSession('erase-me-2.myshopify.com')).toBeNull();+ });+});diff --git a/tests/shopify-webhooks.test.js b/tests/shopify-webhooks.test.jsnew file mode 100644index 000000000..d5a932078--- /dev/null+++ b/tests/shopify-webhooks.test.js@@ -0,0 +1,73 @@+// api/_lib/shopify/webhook-verify.js: the shared verify-then-claim path+// every /api/shopify/webhooks/* receiver runs before any handler logic,+// against a real HMAC and a real (PGlite) delivery-id ledger.++import { beforeAll, beforeEach, describe, it, expect, vi } from 'vitest';+import { createHmac } from 'node:crypto';+import { createPgliteSql } from './_helpers/pglite-sql.js';++process.env.SHOPIFY_API_SECRET = 'test-api-secret';++const holder = vi.hoisted(() => ({ db: null }));++vi.mock('../api/_lib/db.js', async (importActual) => {+ const actual = await importActual();+ return { ...actual, sql: (...args) => holder.db.sql(...args) };+});++const DDL = `+ create table shopify_webhook_deliveries (+ shop_domain text not null,+ topic text not null,+ delivery_id text not null,+ received_at timestamptz not null default now(),+ primary key (topic, delivery_id)+ );+`;++let verifyAndClaim, WebhookAuthError;++beforeAll(async () => {+ ({ verifyAndClaim, WebhookAuthError } = await import('../api/_lib/shopify/webhook-verify.js'));+});++beforeEach(async () => {+ holder.db = createPgliteSql();+ await holder.db.exec(DDL);+});++function fakeReq(bodyObj, { shop = 'example.myshopify.com', topic = 'APP_UNINSTALLED', deliveryId = 'delivery-1', secret = process.env.SHOPIFY_API_SECRET } = {}) {+ const raw = Buffer.from(JSON.stringify(bodyObj));+ const sig = createHmac('sha256', secret).update(raw).digest('base64');+ return {+ headers: {+ 'x-shopify-hmac-sha256': sig,+ 'x-shopify-shop-domain': shop,+ 'x-shopify-webhook-id': deliveryId,+ },+ rawBody: raw,+ };+}++describe('verifyAndClaim', () => {+ it('accepts a correctly signed, fresh delivery and parses the body', async () => {+ const req = fakeReq({ shop_id: 1, shop_domain: 'example.myshopify.com' });+ const result = await verifyAndClaim(req, 'APP_UNINSTALLED');+ expect(result.shop).toBe('example.myshopify.com');+ expect(result.body).toEqual({ shop_id: 1, shop_domain: 'example.myshopify.com' });+ expect(result.fresh).toBe(true);+ });++ it('marks a replayed delivery id as not fresh without re-throwing', async () => {+ const req1 = fakeReq({ a: 1 }, { deliveryId: 'dup-1' });+ const req2 = fakeReq({ a: 1 }, { deliveryId: 'dup-1' });+ await verifyAndClaim(req1, 'SHOP_REDACT');+ const second = await verifyAndClaim(req2, 'SHOP_REDACT');+ expect(second.fresh).toBe(false);+ });++ it('throws WebhookAuthError on an invalid signature', async () => {+ const req = fakeReq({ a: 1 }, { secret: 'wrong-secret' });+ await expect(verifyAndClaim(req, 'APP_UNINSTALLED')).rejects.toBeInstanceOf(WebhookAuthError);+ });+});diff --git a/vercel.json b/vercel.jsonindex 3f39387e9..46dd1754b 100644--- a/vercel.json+++ b/vercel.json@@ -3373,6 +3373,14 @@"src": "/discord-activity/","dest": "/discord-activity.html"},+ {+ "src": "/apps/shopify",+ "dest": "/shopify-app.html"+ },+ {+ "src": "/apps/shopify/",+ "dest": "/shopify-app.html"+ },{"src": "/knock","dest": "/knock.html"diff --git a/vite.config.js b/vite.config.jsindex c4c9e5284..029a80e1b 100644--- a/vite.config.js+++ b/vite.config.js@@ -832,6 +832,7 @@ const appConfig = {'herald-page': resolve(__dirname, 'pages/herald.html'),companion: resolve(__dirname, 'pages/companion.html'),'discord-activity': resolve(__dirname, 'pages/discord-activity.html'),+ 'shopify-app': resolve(__dirname, 'pages/shopify-app.html'),knock: resolve(__dirname, 'pages/knock.html'),'knock-door': resolve(__dirname, 'pages/knock-door.html'),portal: resolve(__dirname, 'pages/portal.html'),