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
fix(aws-marketplace): stop a subscription being claimed by the wrong account and pin the SNS topic before trusting a webhook
nirholas70602a474d91
diff --git a/api/_lib/aws-marketplace.js b/api/_lib/aws-marketplace.jsindex bae9fb500..9e1482952 100644--- a/api/_lib/aws-marketplace.js+++ b/api/_lib/aws-marketplace.js@@ -145,14 +145,36 @@ export async function customerEntitlement(customerIdentifier) {const certCache = new Map();+/**+ * Assert that a URL taken from an SNS payload is an AWS-hosted HTTPS endpoint+ * before anything dereferences it. Both places that follow such a URL (the+ * signing certificate and the SubscribeURL handshake) go through this, so a+ * payload can never steer an outbound request at a host of its choosing.+ * Also turns a missing/garbage URL into this same refusal instead of a+ * TypeError from the URL constructor.+ *+ * @param {unknown} value the URL as it appeared in the payload+ * @param {string} label what the URL is, for the thrown message+ * @returns {URL} the parsed, trusted URL+ */+export function assertAwsHttpsUrl(value, label) {+ let parsed;+ try {+ parsed = new URL(String(value));+ } catch {+ throw new Error(`Untrusted ${label}: ${value}`);+ }+ if (parsed.protocol !== 'https:' || !parsed.hostname.endsWith('.amazonaws.com')) {+ throw new Error(`Untrusted ${label}: ${value}`);+ }+ return parsed;+}+async function fetchCert(url) {if (certCache.has(url)) return certCache.get(url);// Only trust certs hosted on *.amazonaws.com over HTTPS.- const parsed = new URL(url);- if (parsed.protocol !== 'https:' || !parsed.hostname.endsWith('.amazonaws.com')) {- throw new Error(`Untrusted SNS signing cert URL: ${url}`);- }+ assertAwsHttpsUrl(url, 'SNS signing cert URL');const res = await fetch(url);if (!res.ok) throw new Error(`Failed to fetch SNS cert: ${res.status}`);diff --git a/api/aws-marketplace/link.js b/api/aws-marketplace/link.jsindex 1b8af2d31..c42292f1c 100644--- a/api/aws-marketplace/link.js+++ b/api/aws-marketplace/link.js@@ -26,6 +26,12 @@ export default wrap(async (req, res) => {} catch {return json(res, 401, { error: 'unauthenticated' });}+ // getSessionUser RESOLVES to null for a missing/expired/revoked cookie; it+ // only throws when the session lookup itself fails. Without this guard an+ // anonymous POST fell through to the customer lookup and then died on+ // `user.id`, turning a plain 401 into a 500 while still answering "does+ // this customer exist?" for a caller who was never signed in.+ if (!user) return json(res, 401, { error: 'unauthenticated' });let body;try {@@ -40,7 +46,7 @@ export default wrap(async (req, res) => {}const [row] = await sql`- SELECT customer_identifier, subscription_status+ SELECT customer_identifier, subscription_status, user_idFROM aws_marketplace_customersWHERE customer_identifier = ${customerId}`;@@ -53,13 +59,30 @@ export default wrap(async (req, res) => {return json(res, 409, { error: 'subscription_inactive', status: row.subscription_status });}- await sql`+ // A customer already attached to a different three.ws account must not be+ // re-pointed. The UPDATE is guarded on user_id for exactly that reason, but+ // answering ok:true after it matched zero rows told the welcome page the+ // subscription was linked when it was not, and the next call (issue-key,+ // which does check) then answered 403. Give the same answer here.+ if (row.user_id && row.user_id !== user.id) {+ return json(res, 403, { error: 'customer_linked_to_other_account' });+ }++ const linked = await sql`UPDATE aws_marketplace_customersSET user_id = ${user.id},updated_at = now()WHERE customer_identifier = ${customerId}AND (user_id IS NULL OR user_id = ${user.id})+ RETURNING customer_identifier`;+ // Lost a race with a concurrent link from another account between the check+ // above and this write. The guard held, so the row is not ours: report the+ // ownership conflict rather than an ok the database does not back.+ if (!linked.length) {+ return json(res, 403, { error: 'customer_linked_to_other_account' });+ }+return json(res, 200, { ok: true });});diff --git a/api/aws-marketplace/register.js b/api/aws-marketplace/register.jsindex 731cfed6d..5b1e917ce 100644--- a/api/aws-marketplace/register.js+++ b/api/aws-marketplace/register.js@@ -17,7 +17,7 @@import { readForm, wrap } from '../_lib/http.js';import { sql } from '../_lib/db.js';-import { resolveCustomer } from '../_lib/aws-marketplace.js';+import { resolveCustomer, awsMarketplaceConfigured } from '../_lib/aws-marketplace.js';import { getSessionUser } from '../_lib/auth.js';import { env } from '../_lib/env.js';@@ -48,6 +48,21 @@ export default wrap(async (req, res) => {const isFreeTrial = offerType === 'free-trial';+ // Without AWS credentials, ResolveCustomer throws on the missing env var and+ // the customer used to be told their registration token had expired: a dead+ // end that blames them for our deployment gap and sends the operator hunting+ // the wrong bug. Name the real cause in the log and in the reason code.+ if (!awsMarketplaceConfigured()) {+ console.error(+ '[aws-marketplace/register] AWS Marketplace is not configured; set AWS_MP_ACCESS_KEY_ID, AWS_MP_SECRET_ACCESS_KEY and AWS_MP_PRODUCT_CODE',+ );+ res.statusCode = 302;+ res.setHeader('location', `${env.APP_ORIGIN}/aws-marketplace/error?reason=not_configured`);+ res.setHeader('cache-control', 'no-store');+ res.end();+ return;+ }+let customer;try {customer = await resolveCustomer(token);diff --git a/api/aws-marketplace/subscription.js b/api/aws-marketplace/subscription.jsindex f7ac199df..341c6a558 100644--- a/api/aws-marketplace/subscription.js+++ b/api/aws-marketplace/subscription.js@@ -16,7 +16,7 @@import { json, wrap, readBody } from '../_lib/http.js';import { sql } from '../_lib/db.js';-import { verifySnsMessage } from '../_lib/aws-marketplace.js';+import { verifySnsMessage, assertAwsHttpsUrl } from '../_lib/aws-marketplace.js';import { revokeSubscriptionForCustomer } from '../_lib/aws-marketplace-bridge.js';import { env } from '../_lib/env.js';@@ -36,6 +36,19 @@ export default wrap(async (req, res) => {return;}+ // The topic pin is what binds this webhook to OUR listing. A valid signature+ // alone only proves "some AWS account signed this": anyone can create their+ // own SNS topic and have AWS sign a Notification for it, so an unpinned+ // handler would accept a forged subscribe-success (minting a free x402 key+ // for an attacker-chosen customer) or unsubscribe-success (revoking a paying+ // customer's key). Refuse delivery entirely until the ARN is configured+ // instead of trusting whatever topic shows up. SNS retries with backoff, so+ // an operator who sets the var recovers the missed notifications.+ if (!env.AWS_MP_SNS_TOPIC_ARN) {+ console.error('[aws-marketplace/subscription] refusing SNS delivery: AWS_MP_SNS_TOPIC_ARN is not set');+ return json(res, 503, { error: 'not_configured' });+ }+let msg;try {const raw = await readRawBody(req);@@ -57,9 +70,20 @@ export default wrap(async (req, res) => {}if (msg.Type === 'SubscriptionConfirmation' || msg.Type === 'UnsubscribeConfirmation') {+ // The signature covers SubscribeURL, so by here it is AWS-authored. Check+ // the host anyway before following it: this is the one outbound request+ // this handler makes from payload-supplied data, and the check costs+ // nothing next to the blast radius if the signature step ever regresses.+ let subscribeUrl;+ try {+ subscribeUrl = assertAwsHttpsUrl(msg.SubscribeURL, 'SNS SubscribeURL');+ } catch (err) {+ console.error('[aws-marketplace/subscription] refusing SubscribeURL', err?.message);+ return json(res, 400, { error: 'invalid_subscribe_url' });+ }// Confirm the SNS subscription by hitting the provided URL.try {- await fetch(msg.SubscribeURL);+ await fetch(subscribeUrl);} catch (err) {console.error('[aws-marketplace/subscription] failed to confirm SNS subscription', err?.message);}diff --git a/docs/aws-marketplace.md b/docs/aws-marketplace.mdindex 0cea70fb0..95e3bb36e 100644--- a/docs/aws-marketplace.md+++ b/docs/aws-marketplace.md@@ -26,8 +26,38 @@ If you are integrating three.ws programmatically after subscribing via AWS Marke|---|---|| `POST /api/aws-marketplace/register` | Registration URL — receives the Marketplace token, resolves the customer, and starts onboarding || `POST /api/aws-marketplace/subscription` | SNS webhook — receives subscription lifecycle events from AWS |+| `POST /api/aws-marketplace/link` | Attaches your resolved AWS customer record to your signed-in three.ws account. Called by the welcome page; requires a session cookie. |+| `POST /api/aws-marketplace/issue-key` | Mints (or returns) the x402 API key for your linked subscription. The plaintext key is returned once, on first issue. |-These endpoints are called automatically by AWS during the subscription flow. You do not need to call them directly.+`register` and `subscription` are called automatically by AWS during the subscription flow; you do not need to call them directly. `link` and `issue-key` are called by the welcome page on your behalf once you sign in.++Both `link` and `issue-key` require an active session and refuse a subscription that belongs to someone else, so a given AWS customer record can only ever be attached to one three.ws account:++| Status | Meaning |+|---|---|+| `401 unauthenticated` | No valid session cookie. Sign in, then retry. |+| `403 customer_linked_to_other_account` | This AWS subscription is already attached to a different three.ws account. |+| `404 customer_not_found` | The customer identifier is unknown. Re-open the setup link from AWS Marketplace. |+| `409 subscription_inactive` | The AWS subscription is cancelled or expired. Re-subscribe in AWS Marketplace first. |++### Operator configuration++The integration reads its AWS credentials from the environment and ships inert without them: nothing fabricates an entitlement AWS did not grant.++| Variable | Required | Purpose |+|---|---|---|+| `AWS_MP_ACCESS_KEY_ID` | Yes | Credentials for ResolveCustomer, MeterUsage, and GetEntitlements. |+| `AWS_MP_SECRET_ACCESS_KEY` | Yes | Paired secret for the above. |+| `AWS_MP_PRODUCT_CODE` | Yes | Product code from the Marketplace listing. |+| `AWS_MP_SNS_TOPIC_ARN` | Yes, for the webhook | The Marketplace SNS topic. `POST /api/aws-marketplace/subscription` answers `503 not_configured` until it is set. |+| `AWS_MP_REGION` | No (default `us-east-1`) | Region for the Marketplace API clients. |+| `AWS_MP_METERING_DIMENSION` | No | Set for a usage-based listing to report MeterUsage per granted call. Leave unset for a contract listing. |+| `AWS_MP_ENTITLEMENT_REQUIRED` | No | Set truthy on a contract listing to gate key issuance on a live GetEntitlements check. |+| `AWS_MP_DEFAULT_RATE_LIMIT_PER_MINUTE` | No (default `600`) | Rate limit stamped on issued keys. Override per offer with `AWS_MP_RATE_LIMIT_<OFFER_ID>`. |++**`AWS_MP_SNS_TOPIC_ARN` is not optional in practice.** A valid SNS signature only proves that some AWS account signed the message: anyone can create an SNS topic in their own account and have AWS sign a notification for it. The topic ARN is what binds the webhook to this listing, so without it a forged `subscribe-success` could mint a free API key and a forged `unsubscribe-success` could revoke a paying customer's. The handler therefore refuses delivery outright rather than trusting an unpinned topic. SNS retries with backoff, so notifications that arrive during a misconfiguration are redelivered once the variable is set.++If the registration URL is hit while the AWS credentials are missing, the customer is redirected to `/aws-marketplace/error?reason=not_configured` (not `token_expired`) and the missing variables are named in the server log.## Supportdiff --git a/prompts/swarm-100/api-aws-marketplace-01.md b/prompts/swarm-100/api-aws-marketplace-01.mddeleted file mode 100644index 5fa19bb99..000000000--- a/prompts/swarm-100/api-aws-marketplace-01.md+++ /dev/null@@ -1,104 +0,0 @@-# API audit: api/aws-marketplace batch 01 (4 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/aws-marketplace/issue-key.js-- api/aws-marketplace/link.js-- api/aws-marketplace/register.js-- api/aws-marketplace/subscription.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-aws-marketplace-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/src/aws-marketplace-welcome.js b/src/aws-marketplace-welcome.jsindex 4307f7d9f..1489a08e7 100644--- a/src/aws-marketplace-welcome.js+++ b/src/aws-marketplace-welcome.js@@ -18,11 +18,23 @@ const isTrial = p.get('trial') === '1';const wantsSignup = p.get('signup') === '1';const ERROR_MESSAGES = {- token_expired: 'The AWS Marketplace registration link has expired. Please return to AWS Marketplace and subscribe again.',- link_failed: 'We could not link your AWS subscription to your account. Please try signing in again or contact support.',- default: 'We couldn\'t complete your AWS Marketplace subscription setup.',+ token_expired: 'The AWS Marketplace registration link has expired. Please return to AWS Marketplace and subscribe again.',+ not_configured: 'AWS Marketplace subscriptions are temporarily unavailable on three.ws. Your AWS subscription is unaffected. Please open this link again shortly, or contact support if it persists.',+ link_failed: 'We could not link your AWS subscription to your account. Please try signing in again or contact support.',+ // Error codes returned by /api/aws-marketplace/link, so a rejected link says+ // what to do about it instead of "contact support" for every cause.+ unauthenticated: 'Your session expired before we could link the subscription. Please sign in again.',+ customer_linked_to_other_account: 'This AWS subscription is already linked to a different three.ws account. Sign in with that account, or contact support to move it.',+ subscription_inactive: 'This AWS Marketplace subscription is no longer active. Re-subscribe in AWS Marketplace, then open this link again.',+ customer_not_found: 'We could not find this AWS Marketplace subscription. Please return to AWS Marketplace and open the setup link again.',+ default: 'We couldn\'t complete your AWS Marketplace subscription setup.',};+/** Map a thrown link/auth error onto a message the customer can act on. */+function messageFor(err) {+ return ERROR_MESSAGES[err?.message] || err?.message || ERROR_MESSAGES.link_failed;+}+function show(id) {document.querySelectorAll('.state').forEach(el => el.classList.remove('active'));document.getElementById(id).classList.add('active');@@ -47,7 +59,13 @@ async function linkSubscription() {headers: { 'content-type': 'application/json' },body: JSON.stringify({ customer: customerId }),});- if (!resp.ok) throw new Error('link_failed');+ if (!resp.ok) {+ // Carry the server's error code up so the caller can explain the specific+ // failure (wrong account, cancelled subscription) instead of showing the+ // same "contact support" line for all of them.+ const data = await resp.json().catch(() => ({}));+ throw new Error(data.error || 'link_failed');+ }}async function issueApiKey() {@@ -161,10 +179,10 @@ async function init() {try {const sub = await linkAndIssue();showSuccess(sub);- } catch {+ } catch (err) {btn.disabled = false;btn.textContent = 'Confirm & activate';- showErr('err-link', ERROR_MESSAGES.link_failed);+ showErr('err-link', messageFor(err));}});return;@@ -228,7 +246,7 @@ async function handleSignup(e) {} catch (err) {btn.disabled = false;btn.textContent = 'Create account & activate';- showErr('err-auth', err.message);+ showErr('err-auth', messageFor(err));}}@@ -258,7 +276,7 @@ async function handleSignin(e) {} catch (err) {btn.disabled = false;btn.textContent = 'Sign in & activate';- showErr('err-auth', err.message);+ showErr('err-auth', messageFor(err));}}diff --git a/tests/api/aws-marketplace-link.test.js b/tests/api/aws-marketplace-link.test.jsnew file mode 100644index 000000000..84bcfcf82--- /dev/null+++ b/tests/api/aws-marketplace-link.test.js@@ -0,0 +1,184 @@+// Unit tests for /api/aws-marketplace/link, the endpoint that attaches an AWS+// Marketplace subscription to a three.ws account.+//+// Both behaviours pinned here were live defects found by probing the running+// handler:+// • getSessionUser RESOLVES null for an anonymous caller (it only throws when+// the lookup itself fails), so the handler ran the customer lookup and then+// crashed on `user.id`: an anonymous POST got a 500, and the 404-vs-500+// split answered "does this customer exist?" for a caller with no session.+// • The UPDATE is guarded on user_id, but the handler returned ok:true+// regardless of whether it matched. A customer already linked to someone+// else reported success while nothing changed, and the very next call+// (issue-key, which does check ownership) answered 403.+//+// The sql tag is mocked so the authorization logic is asserted without touching+// a real database.++import { describe, it, expect, beforeEach, vi } from 'vitest';++const sqlMock = vi.fn();+vi.mock('../../api/_lib/db.js', () => ({+ sql: Object.assign(+ (...args) => sqlMock(...args),+ { transaction: (...args) => sqlMock(...args) },+ ),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const getSessionUserMock = vi.fn();+vi.mock('../../api/_lib/auth.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, getSessionUser: (...a) => getSessionUserMock(...a) };+});++const { default: handler } = await import('../../api/aws-marketplace/link.js');++const OWNER = 'user-owner-1';+const OTHER = 'user-other-2';+const CUSTOMER = 'THREEsynthetic-awsmp-test';++function makeReq(body = { customer: CUSTOMER }) {+ const raw = Buffer.from(JSON.stringify(body));+ return {+ method: 'POST',+ url: '/api/aws-marketplace/link',+ headers: { 'content-type': 'application/json', 'user-agent': 'vitest' },+ rawBody: raw,+ query: {},+ };+}++function makeRes() {+ const headers = {};+ let body = '';+ const res = {+ statusCode: 200,+ headersSent: false,+ writableEnded: false,+ setHeader: (k, v) => { headers[k.toLowerCase()] = v; },+ getHeader: (k) => headers[k.toLowerCase()],+ end: (chunk) => { body = chunk ?? ''; res.writableEnded = true; },+ _get: () => ({ status: res.statusCode, headers, body: body ? JSON.parse(body) : null }),+ };+ return res;+}++/** Row shape the handler's first SELECT returns. */+function customerRow(overrides = {}) {+ return {+ customer_identifier: CUSTOMER,+ subscription_status: 'active',+ user_id: null,+ ...overrides,+ };+}++beforeEach(() => {+ sqlMock.mockReset();+ getSessionUserMock.mockReset();+});++describe('POST /api/aws-marketplace/link', () => {+ it('returns 401 (not 500) when there is no session', async () => {+ getSessionUserMock.mockResolvedValue(null);+ const res = makeRes();+ await handler(makeReq(), res);+ expect(res._get().status).toBe(401);+ expect(res._get().body).toEqual({ error: 'unauthenticated' });+ });++ it('does not touch the database for an anonymous caller', async () => {+ getSessionUserMock.mockResolvedValue(null);+ await handler(makeReq(), makeRes());+ // No customer lookup means no "does this customer exist" oracle.+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('returns 401 when the session lookup itself throws', async () => {+ getSessionUserMock.mockRejectedValue(new Error('session store down'));+ const res = makeRes();+ await handler(makeReq(), res);+ expect(res._get().status).toBe(401);+ });++ it('links an unclaimed customer to the signed-in user', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlMock+ .mockResolvedValueOnce([customerRow()])+ .mockResolvedValueOnce([{ customer_identifier: CUSTOMER }]);+ const res = makeRes();+ await handler(makeReq(), res);+ expect(res._get().status).toBe(200);+ expect(res._get().body).toEqual({ ok: true });+ });++ it('is idempotent for the account that already owns the customer', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlMock+ .mockResolvedValueOnce([customerRow({ user_id: OWNER })])+ .mockResolvedValueOnce([{ customer_identifier: CUSTOMER }]);+ const res = makeRes();+ await handler(makeReq(), res);+ expect(res._get().status).toBe(200);+ });++ it('refuses to report success when the customer belongs to another account', async () => {+ getSessionUserMock.mockResolvedValue({ id: OTHER });+ sqlMock.mockResolvedValueOnce([customerRow({ user_id: OWNER })]);+ const res = makeRes();+ await handler(makeReq(), res);+ expect(res._get().status).toBe(403);+ expect(res._get().body).toEqual({ error: 'customer_linked_to_other_account' });+ // It must stop at the lookup: no UPDATE may be attempted.+ expect(sqlMock).toHaveBeenCalledTimes(1);+ });++ it('reports the conflict when the guarded UPDATE matches nothing (lost race)', async () => {+ // Ownership was free at SELECT time and taken by the time we wrote: the+ // UPDATE guard held and matched zero rows, so ok:true would be a lie.+ getSessionUserMock.mockResolvedValue({ id: OTHER });+ sqlMock+ .mockResolvedValueOnce([customerRow()])+ .mockResolvedValueOnce([]);+ const res = makeRes();+ await handler(makeReq(), res);+ expect(res._get().status).toBe(403);+ expect(res._get().body).toEqual({ error: 'customer_linked_to_other_account' });+ });++ it('returns 404 for an unknown customer', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlMock.mockResolvedValueOnce([]);+ const res = makeRes();+ await handler(makeReq(), res);+ expect(res._get().status).toBe(404);+ });++ it('returns 409 for a cancelled subscription', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlMock.mockResolvedValueOnce([customerRow({ subscription_status: 'cancelled' })]);+ const res = makeRes();+ await handler(makeReq(), res);+ expect(res._get().status).toBe(409);+ expect(res._get().body).toEqual({ error: 'subscription_inactive', status: 'cancelled' });+ });++ it('returns 400 when the customer field is missing', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ const res = makeRes();+ await handler(makeReq({}), res);+ expect(res._get().status).toBe(400);+ expect(res._get().body).toEqual({ error: 'missing_customer' });+ });++ it('rejects a non-POST method', async () => {+ const req = makeReq();+ req.method = 'GET';+ const res = makeRes();+ await handler(req, res);+ expect(res._get().status).toBe(405);+ expect(res.getHeader('allow')).toBe('POST');+ });+});diff --git a/tests/api/aws-marketplace-sns.test.js b/tests/api/aws-marketplace-sns.test.jsindex e41195221..7e2ee4431 100644--- a/tests/api/aws-marketplace-sns.test.js+++ b/tests/api/aws-marketplace-sns.test.js@@ -55,6 +55,7 @@ function validNotification(overrides = {}) {}let verifySnsMessage;+let assertAwsHttpsUrl;beforeEach(async () => {delete process.env.AWS_MP_SNS_TOPIC_ARN; // default: no ARN pin unless a test sets it@@ -68,7 +69,7 @@ beforeEach(async () => {);// Import fresh each test so the module-level cert cache / env reads are clean.vi.resetModules();- ({ verifySnsMessage } = await import('../../api/_lib/aws-marketplace.js'));+ ({ verifySnsMessage, assertAwsHttpsUrl } = await import('../../api/_lib/aws-marketplace.js'));});afterEach(() => {@@ -122,3 +123,31 @@ describe('verifySnsMessage', () => {await expect(verifySnsMessage(validNotification())).resolves.toBeUndefined();});});++// The same guard now protects both URLs this integration dereferences from an+// SNS payload: the signing certificate and the SubscribeURL handshake.+describe('assertAwsHttpsUrl', () => {+ it('accepts an AWS HTTPS endpoint and returns the parsed URL', () => {+ const url = assertAwsHttpsUrl(CERT_URL, 'SNS signing cert URL');+ expect(url.hostname).toBe('sns.us-east-1.amazonaws.com');+ });++ it('refuses a host that merely ends in a lookalike domain', () => {+ expect(() => assertAwsHttpsUrl('https://sns.us-east-1.amazonaws.com.evil.test/c.pem', 'SNS signing cert URL'))+ .toThrow(/untrusted/i);+ });++ it('refuses a non-HTTPS scheme', () => {+ expect(() => assertAwsHttpsUrl('http://sns.us-east-1.amazonaws.com/c.pem', 'SNS signing cert URL'))+ .toThrow(/untrusted/i);+ });++ it('refuses link-local metadata addresses', () => {+ expect(() => assertAwsHttpsUrl('http://169.254.169.254/latest/meta-data/', 'SNS SubscribeURL'))+ .toThrow(/untrusted/i);+ });++ it('turns a missing URL into the same refusal, not a TypeError', () => {+ expect(() => assertAwsHttpsUrl(undefined, 'SNS SubscribeURL')).toThrow(/untrusted/i);+ });+});diff --git a/tests/api/aws-marketplace-subscription-guard.test.js b/tests/api/aws-marketplace-subscription-guard.test.jsnew file mode 100644index 000000000..fc8708afe--- /dev/null+++ b/tests/api/aws-marketplace-subscription-guard.test.js@@ -0,0 +1,156 @@+// Unit tests for the delivery guard on /api/aws-marketplace/subscription.+//+// A valid AWS SNS signature only proves "some AWS account signed this". Anyone+// can create their own SNS topic and have AWS sign a Notification for it, so+// the TopicArn pin is what actually binds this webhook to OUR Marketplace+// listing. While the pin was optional, an unconfigured deployment accepted any+// topic: a forged subscribe-success would mint a free x402 key for an+// attacker-chosen customer, and a forged unsubscribe-success would revoke a+// paying customer's key. The handler now refuses delivery until the ARN is set.+//+// These tests assert the gate itself, not the crypto. Signature verification is+// covered in aws-marketplace-sns.test.js.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++const sqlMock = vi.fn(async () => []);+vi.mock('../../api/_lib/db.js', () => ({+ sql: Object.assign(+ (...args) => sqlMock(...args),+ { transaction: (...args) => sqlMock(...args) },+ ),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const verifySnsMessageMock = vi.fn(async () => {});+vi.mock('../../api/_lib/aws-marketplace.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, verifySnsMessage: (...a) => verifySnsMessageMock(...a) };+});++const revokeMock = vi.fn(async () => null);+vi.mock('../../api/_lib/aws-marketplace-bridge.js', () => ({+ revokeSubscriptionForCustomer: (...a) => revokeMock(...a),+}));++const { default: handler } = await import('../../api/aws-marketplace/subscription.js');++const TOPIC = 'arn:aws:sns:us-east-1:155407237916:marketplace-topic';++function makeReq(msg) {+ const raw = Buffer.from(JSON.stringify(msg));+ return {+ method: 'POST',+ url: '/api/aws-marketplace/subscription',+ headers: { 'content-type': 'application/json', 'user-agent': 'vitest' },+ rawBody: raw,+ query: {},+ };+}++function makeRes() {+ const headers = {};+ let body = '';+ const res = {+ statusCode: 200,+ headersSent: false,+ writableEnded: false,+ setHeader: (k, v) => { headers[k.toLowerCase()] = v; },+ getHeader: (k) => headers[k.toLowerCase()],+ end: (chunk) => { body = chunk ?? ''; res.writableEnded = true; },+ _get: () => ({ status: res.statusCode, headers, body: body ? JSON.parse(body) : null }),+ };+ return res;+}++function notification(action, customerId = 'THREEsynthetic-awsmp-test') {+ return {+ Type: 'Notification',+ MessageId: 'msg-1',+ Message: JSON.stringify({ action, 'customer-identifier': customerId, 'product-code': 'THREEsyntheticProductCode' }),+ Timestamp: '2026-08-10T00:00:00.000Z',+ TopicArn: TOPIC,+ SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',+ Signature: 'AAAA',+ };+}++beforeEach(() => {+ sqlMock.mockClear();+ verifySnsMessageMock.mockClear().mockResolvedValue(undefined);+ revokeMock.mockClear().mockResolvedValue(null);+ process.env.AWS_MP_SNS_TOPIC_ARN = TOPIC;+});++afterEach(() => {+ delete process.env.AWS_MP_SNS_TOPIC_ARN;+});++describe('POST /api/aws-marketplace/subscription topic pin', () => {+ it('refuses delivery with 503 when no topic ARN is pinned', async () => {+ delete process.env.AWS_MP_SNS_TOPIC_ARN;+ const res = makeRes();+ await handler(makeReq(notification('subscribe-success')), res);+ expect(res._get().status).toBe(503);+ expect(res._get().body).toEqual({ error: 'not_configured' });+ });++ it('writes nothing when unpinned, even for a message that would verify', async () => {+ delete process.env.AWS_MP_SNS_TOPIC_ARN;+ await handler(makeReq(notification('unsubscribe-success')), makeRes());+ expect(sqlMock).not.toHaveBeenCalled();+ expect(revokeMock).not.toHaveBeenCalled();+ // The gate must come before verification, so an unpinned deployment does+ // not even fetch a signing certificate for an unknown topic.+ expect(verifySnsMessageMock).not.toHaveBeenCalled();+ });++ it('processes a subscribe-success once the ARN is pinned', async () => {+ const res = makeRes();+ await handler(makeReq(notification('subscribe-success')), res);+ expect(verifySnsMessageMock).toHaveBeenCalledTimes(1);+ expect(res._get().status).toBe(200);+ expect(res._get().body).toEqual({ ok: true });+ expect(sqlMock).toHaveBeenCalledTimes(1);+ });++ it('rejects a message the verifier refuses', async () => {+ verifySnsMessageMock.mockRejectedValue(new Error('SNS signature verification failed'));+ const res = makeRes();+ await handler(makeReq(notification('unsubscribe-success')), res);+ expect(res._get().status).toBe(403);+ expect(revokeMock).not.toHaveBeenCalled();+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('refuses a SubscribeURL that is not an AWS HTTPS endpoint', async () => {+ const res = makeRes();+ await handler(+ makeReq({+ Type: 'SubscriptionConfirmation',+ MessageId: 'msg-2',+ Message: 'You have chosen to subscribe',+ SubscribeURL: 'http://169.254.169.254/latest/meta-data/',+ Token: 'token-abc',+ Timestamp: '2026-08-10T00:00:00.000Z',+ TopicArn: TOPIC,+ SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',+ Signature: 'AAAA',+ }),+ res,+ );+ expect(res._get().status).toBe(400);+ expect(res._get().body).toEqual({ error: 'invalid_subscribe_url' });+ });++ it('keeps the customer active when a revoke fails, so the retry can win', async () => {+ revokeMock.mockRejectedValue(new Error('x402 revoke exploded'));+ const res = makeRes();+ await handler(makeReq(notification('unsubscribe-success')), res);+ expect(res._get().status).toBe(500);+ expect(res._get().body).toEqual({ error: 'revoke_failed' });+ // Status must NOT flip to cancelled while the key is still live.+ expect(sqlMock).not.toHaveBeenCalled();+ });+});