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(aws-marketplace): key buyers by license ARN so the new SaaS integration resolves them
nirholascd40a59e47bf
diff --git a/api/_lib/aws-marketplace-bridge.js b/api/_lib/aws-marketplace-bridge.jsindex 65fa6ff7b..28ead5e65 100644--- a/api/_lib/aws-marketplace-bridge.js+++ b/api/_lib/aws-marketplace-bridge.js@@ -10,23 +10,30 @@// was revoked (e.g. customer cancelled then// re-subscribed). Plaintext is only returned// for fresh mints.-// meterAwsSubscriptionUsage() — fire-and-forget MeterUsage(1) for a+// meterAwsSubscriptionUsage() : fire-and-forget metering for a// subscription id, when the subscription// was issued via AWS Marketplace AND a// metering dimension is configured.// revokeSubscriptionForCustomer() — revoke the linked x402 subscription-// when AWS sends unsubscribe-success.+// when AWS ends the agreement or+// deprovisions the license.//// We rely on the x402_subscriptions.meta JSONB to carry the AWS linkage:// { source: 'aws-marketplace',-// aws_customer_identifier: '<CustomerIdentifier>',-// aws_product_code: '<ProductCode>',-// aws_offer_id: '<OfferIdentifier|null>',-// is_free_trial: true|false,-// issued_for: 'aws-marketplace' }+// aws_customer_row_id: '<aws_marketplace_customers.id>',+// aws_license_arn: '<LicenseArn|null>',+// aws_customer_account_id: '<CustomerAWSAccountId|null>',+// aws_customer_identifier: '<CustomerIdentifier|null, legacy>',+// aws_product_code: '<ProductCode>',+// aws_offer_id: '<OfferIdentifier|null>',+// is_free_trial: true|false,+// issued_for: 'aws-marketplace' }//-// Look-up by aws_customer_identifier uses the GIN-friendly meta->>'…' index-// declared in migrations/20260528000000_aws_marketplace_x402_link.sql.+// The row id is the join key rather than the license ARN: a license ARN is a+// grant identifier and belongs in exactly one table, and the row id survives a+// buyer whose row was opened by an agreement event before any license existed.+// Look-up uses the expression index declared in+// migrations/20260817120000_aws_marketplace_concurrent_agreements.sql.import { sql } from './db.js';import { env } from './env.js';@@ -36,26 +43,33 @@ import {revokeSubscription,} from './x402/api-keys.js';-const AWS_META_KEY = 'aws_customer_identifier';+const AWS_ROW_META_KEY = 'aws_customer_row_id';+const AWS_LEGACY_META_KEY = 'aws_customer_identifier';/*** Returns true when an x402 subscription belongs to an AWS Marketplace* customer whose AWS-side subscription_status is no longer active. The* access-control hook calls this so cancellations are enforced even before- * the SNS unsubscribe-success notification revokes the x402 row (delivery- * can lag by minutes). Returns false when the subscription isn't AWS-issued.+ * the lifecycle event revokes the x402 row (delivery can lag by minutes).+ * Returns false when the subscription isn't AWS-issued.*/export async function isAwsCustomerInactive(subscription) {if (!subscription) return false;if (subscription.meta?.source !== 'aws-marketplace') return false;- const customerId = subscription.meta?.[AWS_META_KEY];- if (!customerId) return false;- const [row] = await sql`- select subscription_status- from aws_marketplace_customers- where customer_identifier = ${customerId}- limit 1- `;++ const rowId = subscription.meta?.[AWS_ROW_META_KEY];+ const legacyId = subscription.meta?.[AWS_LEGACY_META_KEY];+ if (!rowId && !legacyId) return false;++ const [row] = rowId+ ? await sql`+ select subscription_status from aws_marketplace_customers+ where id = ${rowId} limit 1+ `+ : await sql`+ select subscription_status from aws_marketplace_customers+ where customer_identifier = ${legacyId} limit 1+ `;if (!row) return true;return row.subscription_status === 'cancelled' || row.subscription_status === 'expired';}@@ -82,18 +96,13 @@ function rateLimitForCustomer(customer) {* The plaintext `token` is only returned at first surface — we never persist* it in clear, so a third call after the key was shown will return null again.*- * @param {object} customer- * @param {string} customer.customer_identifier — stable AWS CustomerIdentifier- * @param {string} customer.product_code — AWS ProductCode- * @param {string|null} [customer.offer_id]- * @param {boolean} [customer.is_free_trial]- * @param {string|null} [customer.user_id] — three.ws user (when linked)+ * @param {object} customer a row from aws-marketplace-store.js* @returns {Promise<{ subscriptionId, keyPrefix, token, alreadyIssued, rateLimitPerMinute }>}*/export async function issueSubscriptionForCustomer(customer) {- const customerId = customer.customer_identifier;- if (!customerId) {- throw new Error('issueSubscriptionForCustomer: customer_identifier is required');+ const rowId = customer?.id;+ if (!rowId) {+ throw new Error('issueSubscriptionForCustomer: customer row id is required');}// Already linked to an ACTIVE x402 subscription? Return that.@@ -108,7 +117,7 @@ export async function issueSubscriptionForCustomer(customer) {s.expires_atfrom aws_marketplace_customers cleft join x402_subscriptions s on s.id = c.x402_subscription_id- where c.customer_identifier = ${customerId}+ where c.id = ${rowId}limit 1`;const stillActive =@@ -127,12 +136,15 @@ export async function issueSubscriptionForCustomer(customer) {const rateLimit = rateLimitForCustomer(customer);const subscription = await createSubscription({- name: `aws-marketplace:${customerId}`,+ name: `aws-marketplace:${rowId}`,rateLimitPerMinute: rateLimit,meta: {source: 'aws-marketplace',- [AWS_META_KEY]: customerId,- aws_product_code: customer.product_code || env.AWS_MP_PRODUCT_CODE,+ [AWS_ROW_META_KEY]: rowId,+ aws_license_arn: customer.license_arn || null,+ aws_customer_account_id: customer.customer_aws_account_id || null,+ [AWS_LEGACY_META_KEY]: customer.customer_identifier || null,+ aws_product_code: customer.product_code || null,aws_offer_id: customer.offer_id || null,is_free_trial: Boolean(customer.is_free_trial),issued_for: 'aws-marketplace',@@ -144,7 +156,7 @@ export async function issueSubscriptionForCustomer(customer) {update aws_marketplace_customersset x402_subscription_id = ${subscription.id},updated_at = now()- where customer_identifier = ${customerId}+ where id = ${rowId}`;return {@@ -157,7 +169,7 @@ export async function issueSubscriptionForCustomer(customer) {}/**- * Revoke the x402 subscription tied to an AWS customer. Idempotent.+ * Revoke the x402 subscription tied to an AWS customer row. Idempotent.** Clears `aws_marketplace_customers.x402_subscription_id` so a future* re-subscribe can mint a fresh key. The revoked x402_subscriptions row is@@ -166,12 +178,12 @@ export async function issueSubscriptionForCustomer(customer) {** Returns the revoked subscription id, or null if no link existed.*/-export async function revokeSubscriptionForCustomer(customerIdentifier) {- if (!customerIdentifier) return null;+export async function revokeSubscriptionForCustomer(rowId) {+ if (!rowId) return null;const [row] = await sql`select x402_subscription_idfrom aws_marketplace_customers- where customer_identifier = ${customerIdentifier}+ where id = ${rowId}limit 1`;if (!row?.x402_subscription_id) return null;@@ -180,25 +192,25 @@ export async function revokeSubscriptionForCustomer(customerIdentifier) {update aws_marketplace_customersset x402_subscription_id = null,updated_at = now()- where customer_identifier = ${customerIdentifier}+ where id = ${rowId}`;return row.x402_subscription_id;}-// In-flight de-dupe: AWS Marketplace charges idempotently per usage-// allocation id, but issuing MeterUsage twice per second is wasted I/O.-// This memoizes (subscriptionId, secondBucket) so an x402 endpoint that-// fires multiple times in the same second only meters once. The Postgres-// audit row in aws_marketplace_metering carries the canonical count.+// In-flight de-dupe: AWS Marketplace de-duplicates metering records on the+// hour, but issuing a metering call twice per second is wasted I/O. This+// memoizes (subscriptionId, secondBucket) so an x402 endpoint that fires+// multiple times in the same second only meters once. The Postgres audit row in+// aws_marketplace_metering carries the canonical count.const _inFlight = new Set();/*** Fire-and-forget metering for a granted bypass on an AWS-linked subscription.- * Resolves the AWS customer via the subscription meta and writes one row to- * aws_marketplace_metering for every successful MeterUsage call.+ * Resolves the AWS customer via the subscription link and writes one row to+ * aws_marketplace_metering for every accepted metering call.** No-op when:- * • AWS_MP_METERING_DIMENSION env is unset (Contract product, not Usage).+ * • AWS_MP_METERING_DIMENSION env is unset (free or contract listing).* • The subscription was not issued via AWS Marketplace.* • The customer subscription is no longer active.*@@ -219,6 +231,9 @@ export function meterAwsSubscriptionUsage({ subscriptionId, route }) {try {const [row] = await sql`select+ c.id,+ c.license_arn,+ c.customer_aws_account_id,c.customer_identifier,c.subscription_statusfrom x402_subscriptions s@@ -232,20 +247,22 @@ export function meterAwsSubscriptionUsage({ subscriptionId, route }) {return;}- const allocationId = `${subscriptionId}-${bucket}`;const recordId = await meterUsage({+ licenseArn: row.license_arn,+ customerAWSAccountId: row.customer_aws_account_id,customerIdentifier: row.customer_identifier,dimension,quantity: 1,timestamp: new Date(bucket * 1000),- usageAllocationId: allocationId,});await sql`insert into aws_marketplace_metering- (customer_identifier, dimension, quantity, metering_record_id, usage_allocation_id)+ (customer_row_id, customer_identifier, license_arn, dimension, quantity,+ metering_record_id, usage_allocation_id)values- (${row.customer_identifier}, ${dimension}, ${1}, ${recordId || null}, ${allocationId})+ (${row.id}, ${row.customer_identifier}, ${row.license_arn}, ${dimension}, ${1},+ ${recordId || null}, ${`${subscriptionId}-${bucket}`})on conflict (metering_record_id) do nothing`;} catch (err) {@@ -266,4 +283,4 @@ export function meterAwsSubscriptionUsage({ subscriptionId, route }) {* Test helper — exposes the in-flight set so unit tests can assert dedupe* behavior. Not part of the production API.*/-export const __test = { _inFlight, AWS_META_KEY };+export const __test = { _inFlight, AWS_ROW_META_KEY, AWS_LEGACY_META_KEY };diff --git a/api/_lib/aws-marketplace-store.js b/api/_lib/aws-marketplace-store.jsnew file mode 100644index 000000000..b53027b3a--- /dev/null+++ b/api/_lib/aws-marketplace-store.js@@ -0,0 +1,369 @@+// AWS Marketplace customer records.+//+// One place that knows how a marketplace buyer is identified, because AWS+// changed the answer and the answer is now different depending on which side of+// the integration the buyer arrives from:+//+// • ResolveCustomer (the registration URL, when the buyer clicks "Set up your+// account") returns LicenseArn + CustomerAWSAccountId + ProductCode. For a+// new SaaS integration CustomerIdentifier arrives empty, so LicenseArn is+// the identity.+// • EventBridge agreement events (Purchase Agreement Created/Ended) carry an+// agreement id and the acceptor's AWS account id, but no license ARN.+// • EventBridge license events (License Updated/Deprovisioned) carry the+// license ARN and the product code.+//+// Those three can arrive in any order, so every write here merges rather than+// assuming it is the first to see the buyer. Under Concurrent Agreements one AWS+// account can hold several live agreements for the same product, which is why+// nothing keys on (aws account, product code) alone.+//+// The handle we hand to the browser is the row's own UUID, never the license ARN+// A license ARN in a redirect URL is a grant identifier sitting in history,+// referrers, and logs for no benefit.++import { sql } from './db.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++const CUSTOMER_COLUMNS = sql`+ id, customer_identifier, license_arn, agreement_id, product_code,+ customer_aws_account_id, offer_id, user_id, subscription_status,+ is_free_trial, x402_subscription_id, subscribed_at, cancelled_at+`;++/** True when the row is in a state that should still grant access. */+export function isActiveStatus(status) {+ return status === 'active' || status === 'trial' || status === 'pending';+}++/**+ * Look up a customer by the opaque handle the welcome page carries.+ *+ * Accepts the row UUID (what register.js issues today) or a legacy+ * CustomerIdentifier, so a buyer who subscribed before the re-key can still+ * complete setup from a bookmarked link.+ */+export async function findCustomerByHandle(handle) {+ if (!handle || typeof handle !== 'string') return null;+ const [row] = UUID_RE.test(handle)+ ? await sql`select ${CUSTOMER_COLUMNS} from aws_marketplace_customers where id = ${handle} limit 1`+ : await sql`select ${CUSTOMER_COLUMNS} from aws_marketplace_customers where customer_identifier = ${handle} limit 1`;+ return row ?? null;+}++/** Look up a customer by row id. */+export async function findCustomerById(id) {+ if (!id) return null;+ const [row] = await sql`select ${CUSTOMER_COLUMNS} from aws_marketplace_customers where id = ${id} limit 1`;+ return row ?? null;+}++/** Look up a customer by the AWS-granted license ARN. */+export async function findCustomerByLicenseArn(licenseArn) {+ if (!licenseArn) return null;+ const [row] = await sql`select ${CUSTOMER_COLUMNS} from aws_marketplace_customers where license_arn = ${licenseArn} limit 1`;+ return row ?? null;+}++/**+ * Record the buyer resolved from a registration token.+ *+ * Merge order: the license ARN if we have seen it, then a legacy customer+ * identifier, then a pending row already opened by a Purchase Agreement Created+ * event for the same AWS account and product. Only when none of those match do+ * we insert.+ *+ * @param {object} resolved+ * @param {string|null} resolved.licenseArn+ * @param {string|null} resolved.customerAWSAccountId+ * @param {string|null} resolved.customerIdentifier+ * @param {string} resolved.productCode+ * @param {boolean} [resolved.isFreeTrial]+ * @returns {Promise<object>} the stored customer row+ */+export async function upsertResolvedCustomer({+ licenseArn = null,+ customerAWSAccountId = null,+ customerIdentifier = null,+ productCode,+ isFreeTrial = false,+}) {+ if (!licenseArn && !customerIdentifier) {+ throw new Error('upsertResolvedCustomer: ResolveCustomer returned neither LicenseArn nor CustomerIdentifier');+ }+ const status = isFreeTrial ? 'trial' : 'active';++ const existing =+ (await findCustomerByLicenseArn(licenseArn)) ??+ (customerIdentifier ? await findCustomerByLegacyIdentifier(customerIdentifier) : null) ??+ (await findAdoptablePendingRow({ customerAWSAccountId, productCode }));++ if (existing) {+ const [row] = await sql`+ update aws_marketplace_customers+ set license_arn = coalesce(${licenseArn}, license_arn),+ customer_identifier = coalesce(${customerIdentifier}, customer_identifier),+ customer_aws_account_id = coalesce(${customerAWSAccountId}, customer_aws_account_id),+ product_code = coalesce(${productCode}, product_code),+ is_free_trial = ${isFreeTrial},+ -- A cancelled buyer who re-subscribes comes back through this same+ -- path, so a terminal status has to reopen. An already-live status+ -- is left alone: the lifecycle events own it from here.+ subscription_status = case+ when subscription_status in ('cancelled', 'expired', 'pending') then ${status}+ else subscription_status+ end,+ subscribed_at = coalesce(subscribed_at, now()),+ cancelled_at = null,+ updated_at = now()+ where id = ${existing.id}+ returning ${CUSTOMER_COLUMNS}+ `;+ return row;+ }++ const [row] = await sql`+ insert into aws_marketplace_customers+ (customer_identifier, license_arn, product_code, customer_aws_account_id,+ subscription_status, is_free_trial, subscribed_at)+ values+ (${customerIdentifier}, ${licenseArn}, ${productCode}, ${customerAWSAccountId},+ ${status}, ${isFreeTrial}, now())+ on conflict (license_arn) where license_arn is not null do update set+ customer_identifier = coalesce(excluded.customer_identifier, aws_marketplace_customers.customer_identifier),+ customer_aws_account_id = coalesce(excluded.customer_aws_account_id, aws_marketplace_customers.customer_aws_account_id),+ is_free_trial = excluded.is_free_trial,+ subscription_status = case+ when aws_marketplace_customers.subscription_status in ('cancelled', 'expired', 'pending')+ then excluded.subscription_status+ else aws_marketplace_customers.subscription_status+ end,+ subscribed_at = coalesce(aws_marketplace_customers.subscribed_at, now()),+ cancelled_at = null,+ updated_at = now()+ returning ${CUSTOMER_COLUMNS}+ `;+ return row;+}++async function findCustomerByLegacyIdentifier(customerIdentifier) {+ const [row] = await sql`+ select ${CUSTOMER_COLUMNS} from aws_marketplace_customers+ where customer_identifier = ${customerIdentifier} limit 1+ `;+ return row ?? null;+}++/**+ * A Purchase Agreement Created event can land before the buyer ever clicks+ * "Set up your account", leaving a row that knows the agreement but not the+ * license. When registration then resolves a license for that same AWS account+ * and product, adopt that row instead of opening a second one.+ *+ * Only an unlicensed, unclaimed row qualifies, and only when exactly one+ * matches. With concurrent agreements a buyer can legitimately have several,+ * and guessing between them would attach the wrong agreement.+ */+async function findAdoptablePendingRow({ customerAWSAccountId, productCode }) {+ if (!customerAWSAccountId) return null;+ const rows = await sql`+ select ${CUSTOMER_COLUMNS} from aws_marketplace_customers+ where customer_aws_account_id = ${customerAWSAccountId}+ and product_code = ${productCode}+ and license_arn is null+ and user_id is null+ and subscription_status not in ('cancelled', 'expired')+ limit 2+ `;+ return rows.length === 1 ? rows[0] : null;+}++/**+ * Record a Purchase Agreement Created event.+ *+ * Stamps the agreement id onto the buyer's row so a later Purchase Agreement+ * Ended can be resolved unambiguously. Opens a pending row when the buyer has+ * not registered yet; registration adopts it.+ */+export async function recordAgreementCreated({ agreementId, acceptorAccountId, offerId, productCode }) {+ if (!agreementId) return null;++ const [byAgreement] = await sql`+ select ${CUSTOMER_COLUMNS} from aws_marketplace_customers+ where agreement_id = ${agreementId} limit 1+ `;+ if (byAgreement) {+ const [row] = await sql`+ update aws_marketplace_customers+ set offer_id = coalesce(${offerId ?? null}, offer_id),+ subscription_status = case+ when subscription_status in ('cancelled', 'expired') then 'active'+ else subscription_status+ end,+ cancelled_at = null,+ subscribed_at = coalesce(subscribed_at, now()),+ updated_at = now()+ where id = ${byAgreement.id}+ returning ${CUSTOMER_COLUMNS}+ `;+ return row;+ }++ // The buyer may already have registered (license known, agreement not yet+ // stamped). Claim the single unstamped row for this AWS account, if there is+ // exactly one; otherwise open a fresh pending row for this agreement.+ const candidates = acceptorAccountId+ ? await sql`+ select ${CUSTOMER_COLUMNS} from aws_marketplace_customers+ where customer_aws_account_id = ${acceptorAccountId}+ and product_code = ${productCode}+ and agreement_id is null+ and subscription_status not in ('cancelled', 'expired')+ limit 2+ `+ : [];++ if (candidates.length === 1) {+ const [row] = await sql`+ update aws_marketplace_customers+ set agreement_id = ${agreementId},+ offer_id = coalesce(${offerId ?? null}, offer_id),+ subscribed_at = coalesce(subscribed_at, now()),+ updated_at = now()+ where id = ${candidates[0].id}+ returning ${CUSTOMER_COLUMNS}+ `;+ return row;+ }++ const [row] = await sql`+ insert into aws_marketplace_customers+ (agreement_id, product_code, customer_aws_account_id, offer_id,+ subscription_status, subscribed_at)+ values+ (${agreementId}, ${productCode}, ${acceptorAccountId ?? null}, ${offerId ?? null},+ 'pending', now())+ returning ${CUSTOMER_COLUMNS}+ `;+ return row;+}++/**+ * Attach the license ARN AWS issues for an agreement (License Updated event).+ * This is how an agreement-first row learns its license without waiting for the+ * buyer to open the registration URL.+ */+export async function attachLicenseToAgreement({ agreementId, licenseArn, acceptorAccountId, productCode, offerId }) {+ if (!licenseArn) return null;++ const known = await findCustomerByLicenseArn(licenseArn);+ if (known) {+ const [row] = await sql`+ update aws_marketplace_customers+ set agreement_id = coalesce(${agreementId ?? null}, agreement_id),+ offer_id = coalesce(${offerId ?? null}, offer_id),+ subscription_status = case+ when subscription_status in ('cancelled', 'expired') then 'active'+ else subscription_status+ end,+ cancelled_at = null,+ updated_at = now()+ where id = ${known.id}+ returning ${CUSTOMER_COLUMNS}+ `;+ return row;+ }++ if (agreementId) {+ const [linked] = await sql`+ update aws_marketplace_customers+ set license_arn = ${licenseArn},+ offer_id = coalesce(${offerId ?? null}, offer_id),+ subscription_status = case+ when subscription_status = 'pending' then 'active'+ else subscription_status+ end,+ updated_at = now()+ where agreement_id = ${agreementId}+ and license_arn is null+ returning ${CUSTOMER_COLUMNS}+ `;+ if (linked) return linked;+ }++ const [row] = await sql`+ insert into aws_marketplace_customers+ (license_arn, agreement_id, product_code, customer_aws_account_id, offer_id,+ subscription_status, subscribed_at)+ values+ (${licenseArn}, ${agreementId ?? null}, ${productCode}, ${acceptorAccountId ?? null},+ ${offerId ?? null}, 'active', now())+ on conflict (license_arn) where license_arn is not null do update set+ agreement_id = coalesce(excluded.agreement_id, aws_marketplace_customers.agreement_id),+ updated_at = now()+ returning ${CUSTOMER_COLUMNS}+ `;+ return row;+}++/**+ * Resolve the row(s) an ending/deprovisioning event refers to.+ *+ * Returns an array so the caller can refuse to act on an ambiguous match rather+ * than revoking a paying buyer's other, still-live agreement. Resolution order+ * is most specific first: license ARN, then agreement id, then the single live+ * row for that AWS account.+ */+export async function resolveLifecycleTargets({ licenseArn, agreementId, acceptorAccountId, productCode }) {+ if (licenseArn) {+ const row = await findCustomerByLicenseArn(licenseArn);+ return row ? [row] : [];+ }+ if (agreementId) {+ const rows = await sql`+ select ${CUSTOMER_COLUMNS} from aws_marketplace_customers+ where agreement_id = ${agreementId}+ `;+ if (rows.length) return rows;+ }+ if (acceptorAccountId) {+ return await sql`+ select ${CUSTOMER_COLUMNS} from aws_marketplace_customers+ where customer_aws_account_id = ${acceptorAccountId}+ and product_code = ${productCode}+ and subscription_status not in ('cancelled', 'expired')+ limit 2+ `;+ }+ return [];+}++/** Flip a row to a terminal status. Stamps cancelled_at only on a terminal one. */+export async function markCustomerStatus(id, status) {+ const cancelled = status === 'cancelled' || status === 'expired';+ const [row] = await sql`+ update aws_marketplace_customers+ set subscription_status = ${status},+ cancelled_at = case when ${cancelled}::boolean then now() else cancelled_at end,+ updated_at = now()+ where id = ${id}+ returning ${CUSTOMER_COLUMNS}+ `;+ return row ?? null;+}++/** Attach a three.ws user to a marketplace row. Returns the updated row, or null on a lost race. */+export async function claimCustomerForUser(id, userId) {+ const [row] = await sql`+ update aws_marketplace_customers+ set user_id = ${userId},+ updated_at = now()+ where id = ${id}+ and (user_id is null or user_id = ${userId})+ returning ${CUSTOMER_COLUMNS}+ `;+ return row ?? null;+}++export const __test = { UUID_RE };diff --git a/api/_lib/aws-marketplace.js b/api/_lib/aws-marketplace.jsindex 9e1482952..d3b6a7861 100644--- a/api/_lib/aws-marketplace.js+++ b/api/_lib/aws-marketplace.js@@ -1,21 +1,33 @@// AWS Marketplace integration helpers.//-// Covers the three integration points for a SaaS usage-based listing:-// 1. resolveCustomer — exchange a registration token for a stable customer ID-// 2. meterUsage — report metered consumption to AWS for billing-// 3. getEntitlements — check what a customer is entitled to (contract products)-// 4. verifySnsMessage — validate that an SNS notification is genuinely from AWS+// Covers the integration points for a SaaS listing under the Concurrent+// Agreements requirements AWS made mandatory for new products on 2026-06-01:+// 1. resolveCustomer : exchange a registration token for the buyer's+// LicenseArn + CustomerAWSAccountId+// 2. meterUsage : report consumption (BatchMeterUsage, keyed on+// LicenseArn) for a usage-priced listing+// 3. getEntitlements : check entitlements for a contract listing+// 4. verifySnsMessage : validate a legacy SNS lifecycle notification+// 5. parseMarketplaceEvent : normalize an EventBridge agreement/license event+// 6. verifyEventSecret : authenticate the EventBridge API destination+//+// Why both notification transports: AWS still documents the SNS subscription+// topic for existing integrations, but new products receive agreement and+// license lifecycle events on the seller account's default EventBridge bus+// instead, and SNS never carries a LicenseArn. The webhook accepts either+// envelope so the listing works whichever one AWS wires up for it.import {MarketplaceMeteringClient,ResolveCustomerCommand,MeterUsageCommand,+ BatchMeterUsageCommand,} from '@aws-sdk/client-marketplace-metering';import {MarketplaceEntitlementServiceClient,GetEntitlementsCommand,} from '@aws-sdk/client-marketplace-entitlement-service';-import { createVerify, createPublicKey } from 'node:crypto';+import { createVerify, createPublicKey, timingSafeEqual } from 'node:crypto';import { env } from './env.js';function credentials() {@@ -41,10 +53,16 @@ function entitlementClient() {/*** Exchange the registration token (from the POST body of the registration URL)- * for a stable CustomerIdentifier and ProductCode.+ * for the buyer's identity.+ *+ * For a NEW SaaS integration AWS leaves `CustomerIdentifier` empty and returns+ * `LicenseArn` + `CustomerAWSAccountId` instead, so all four fields are surfaced+ * and the caller keys on whichever it got. Our listing has never been created,+ * which makes it a new integration by definition; the legacy field is carried+ * only so a pre-existing row can still be matched.*- * Returns { customerIdentifier, productCode, customerAWSAccountId }.- * Throws on invalid/expired token.+ * Returns { customerIdentifier, licenseArn, customerAWSAccountId, productCode }.+ * Throws on an invalid or expired token.*/export async function resolveCustomer(registrationToken) {const client = meteringClient();@@ -52,47 +70,98 @@ export async function resolveCustomer(registrationToken) {new ResolveCustomerCommand({ RegistrationToken: registrationToken }),);return {- customerIdentifier: result.CustomerIdentifier,+ customerIdentifier: result.CustomerIdentifier || null,+ licenseArn: result.LicenseArn || null,+ customerAWSAccountId: result.CustomerAWSAccountId || null,productCode: result.ProductCode,- customerAWSAccountId: result.CustomerAWSAccountId,};}/*** Report metered usage to AWS Marketplace for billing.*+ * New integrations meter through BatchMeterUsage with `LicenseArn` ++ * `CustomerAWSAccountId` per record; `MeterUsage` with a `CustomerIdentifier` is+ * the legacy shape and is only used when that is genuinely all we hold for the+ * buyer. Returns the metering record id, or null when AWS accepted the batch+ * without issuing one.+ ** @param {object} params- * @param {string} params.customerIdentifier — from resolveCustomer- * @param {string} params.dimension — usage dimension defined in seller portal- * @param {number} params.quantity — units consumed- * @param {Date} [params.timestamp] — defaults to now- * @param {string} [params.usageAllocationId] — idempotency key (UUID recommended)+ * @param {string} [params.licenseArn] from resolveCustomer (new integrations)+ * @param {string} [params.customerAWSAccountId] from resolveCustomer (new integrations)+ * @param {string} [params.customerIdentifier] legacy integrations only+ * @param {string} params.dimension usage dimension defined in the seller portal+ * @param {number} params.quantity units consumed+ * @param {Date} [params.timestamp] defaults to now*/-export async function meterUsage({ customerIdentifier, dimension, quantity, timestamp, usageAllocationId }) {+export async function meterUsage({+ licenseArn,+ customerAWSAccountId,+ customerIdentifier,+ dimension,+ quantity,+ timestamp,+}) {const client = meteringClient();+ const when = timestamp ?? new Date();++ if (licenseArn || customerAWSAccountId) {+ const result = await client.send(+ new BatchMeterUsageCommand({+ ProductCode: env.AWS_MP_PRODUCT_CODE,+ UsageRecords: [+ {+ Timestamp: when,+ Dimension: dimension,+ Quantity: quantity,+ ...(licenseArn ? { LicenseArn: licenseArn } : {}),+ ...(customerAWSAccountId ? { CustomerAWSAccountId: customerAWSAccountId } : {}),+ },+ ],+ }),+ );+ const [record] = result.Results ?? [];+ if (record && record.Status && record.Status !== 'Success') {+ throw new Error(`BatchMeterUsage rejected the record: ${record.Status}`);+ }+ return record?.MeteringRecordId ?? null;+ }++ if (!customerIdentifier) {+ throw new Error('meterUsage: need LicenseArn/CustomerAWSAccountId (new integrations) or CustomerIdentifier (legacy)');+ }+const result = await client.send(new MeterUsageCommand({ProductCode: env.AWS_MP_PRODUCT_CODE,UsageDimension: dimension,UsageQuantity: quantity,- Timestamp: timestamp ?? new Date(),+ Timestamp: when,CustomerIdentifier: customerIdentifier,- ...(usageAllocationId ? { UsageAllocations: [{ AllocatedUsageQuantity: quantity, Tags: [{ Key: 'allocationId', Value: usageAllocationId }] }] } : {}),}),);- return result.MeteringRecordId;+ return result.MeteringRecordId ?? null;}/**- * Check entitlements for a customer (used for contract-based products).- * Returns the list of active entitlement objects.+ * Check entitlements for a buyer (contract-based products).+ *+ * Filters on CUSTOMER_AWS_ACCOUNT_ID, which is the filter new integrations must+ * use; CUSTOMER_IDENTIFIER remains only for a legacy row that has nothing else.+ * Returns the list of entitlement objects.*/-export async function getEntitlements(customerIdentifier) {+export async function getEntitlements({ customerAWSAccountId, customerIdentifier }) {+ const filter = customerAWSAccountId+ ? { CUSTOMER_AWS_ACCOUNT_ID: [customerAWSAccountId] }+ : { CUSTOMER_IDENTIFIER: [customerIdentifier] };+ if (!customerAWSAccountId && !customerIdentifier) {+ throw new Error('getEntitlements: need CustomerAWSAccountId or CustomerIdentifier');+ }const client = entitlementClient();const result = await client.send(new GetEntitlementsCommand({ProductCode: env.AWS_MP_PRODUCT_CODE,- Filter: { CUSTOMER_IDENTIFIER: [customerIdentifier] },+ Filter: filter,}),);return result.Entitlements ?? [];@@ -121,10 +190,13 @@ export function awsMarketplaceConfigured() {** @returns {Promise<{ configured: boolean, entitled: boolean|null, entitlements: object[] }>}*/-export async function customerEntitlement(customerIdentifier) {+export async function customerEntitlement({ customerAWSAccountId, customerIdentifier }) {if (!awsMarketplaceConfigured()) return { configured: false, entitled: null, entitlements: [] };+ if (!customerAWSAccountId && !customerIdentifier) {+ return { configured: true, entitled: null, entitlements: [] };+ }try {- const entitlements = await getEntitlements(customerIdentifier);+ const entitlements = await getEntitlements({ customerAWSAccountId, customerIdentifier });const now = Date.now();const active = entitlements.filter((e) => !e.ExpirationDate || new Date(e.ExpirationDate).getTime() > now,@@ -199,6 +271,11 @@ function buildSignatureString(msg) {/*** Verify that a parsed SNS message object was genuinely signed by AWS.* Throws if verification fails; returns void on success.+ *+ * SignatureVersion selects the digest: version 1 topics sign with SHA1, and+ * version 2 topics (which AWS now recommends, and which a topic can be switched+ * to at any time) sign with SHA256. Hardcoding SHA1 rejects every message from+ * a version 2 topic with a signature failure that reads like an attack.*/export async function verifySnsMessage(msg) {const expectedTopicArn = env.AWS_MP_SNS_TOPIC_ARN;@@ -206,10 +283,91 @@ export async function verifySnsMessage(msg) {throw new Error(`SNS TopicArn mismatch: got ${msg.TopicArn}`);}+ const digest = String(msg.SignatureVersion) === '2' ? 'SHA256' : 'SHA1';const pem = await fetchCert(msg.SigningCertURL);const pubKey = createPublicKey(pem);- const verifier = createVerify('SHA1');+ const verifier = createVerify(digest);verifier.update(buildSignatureString(msg));const valid = verifier.verify(pubKey, msg.Signature, 'base64');if (!valid) throw new Error('SNS signature verification failed');}++// ── EventBridge agreement + license events ───────────────────────────────────+// New SaaS products receive lifecycle notifications as EventBridge events on the+// seller account's default bus, not on an SNS topic. EventBridge cannot call an+// external HTTPS endpoint directly, so a rule relays them through an API+// destination, whose connection attaches a shared secret header. That header is+// the only thing standing between this endpoint and an anonymous caller who+// wants to revoke a buyer's access, so an unset secret refuses delivery outright+// rather than trusting the payload.++export const AGREEMENT_EVENT_SOURCE = 'aws.agreement-marketplace';++/** Header the EventBridge API destination connection attaches. */+export const EVENT_SECRET_HEADER = 'x-three-ws-marketplace-secret';++/**+ * Constant-time comparison of the request's shared secret against the configured+ * one. Returns a reason string on failure, or null when the request is trusted.+ */+export function verifyEventSecret(req) {+ const expected = env.AWS_MP_EVENT_SECRET;+ if (!expected) return 'not_configured';+ const presented = req.headers?.[EVENT_SECRET_HEADER];+ if (typeof presented !== 'string' || presented.length === 0) return 'missing_secret';+ const a = Buffer.from(presented, 'utf8');+ const b = Buffer.from(expected, 'utf8');+ if (a.length !== b.length) return 'bad_secret';+ return timingSafeEqual(a, b) ? null : 'bad_secret';+}++/** True when the parsed body looks like an EventBridge envelope rather than SNS. */+export function isEventBridgeEnvelope(body) {+ return Boolean(body && typeof body === 'object' && typeof body['detail-type'] === 'string' && body.source);+}++/**+ * Normalize an AWS Marketplace EventBridge event into the fields the webhook+ * acts on. Returns null for an event from another source.+ *+ * `kind` is one of:+ * agreement-created a new/renewed/amended agreement; grant access+ * agreement-ended expired, cancelled, or terminated; revoke access+ * license-updated the buyer's license was provisioned or changed+ * license-deprovisioned the buyer's license ended; revoke access+ * ignored a marketplace event this listing takes no action on+ *+ * Manufacturer and proposer variants of the agreement events are identical for+ * our purposes (we are both), so the role suffix is stripped.+ */+export function parseMarketplaceEvent(event) {+ if (!event || event.source !== AGREEMENT_EVENT_SOURCE) return null;++ const detailType = String(event['detail-type'] || '');+ const base = detailType.replace(/\s+-\s+(Manufacturer|Proposer|Acceptor)$/, '').trim();+ const detail = event.detail || {};++ const common = {+ detailType,+ agreementId: detail.agreement?.id ?? null,+ agreementStatus: detail.agreement?.status ?? null,+ acceptorAccountId: detail.acceptor?.accountId ?? detail.agreement?.acceptorId ?? null,+ offerId: detail.offer?.id ?? detail.agreement?.offerId ?? null,+ productCode: detail.product?.code ?? null,+ licenseArn: detail.license?.arn ?? null,+ };++ switch (base) {+ case 'Purchase Agreement Created':+ case 'Purchase Agreement Amended':+ return { kind: 'agreement-created', ...common };+ case 'Purchase Agreement Ended':+ return { kind: 'agreement-ended', ...common };+ case 'License Updated':+ return { kind: 'license-updated', ...common };+ case 'License Deprovisioned':+ return { kind: 'license-deprovisioned', ...common };+ default:+ return { kind: 'ignored', ...common };+ }+}diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 2ace880b3..a984f06c4 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -1145,9 +1145,20 @@ export const env = {},// SNS topic ARN that AWS sends subscription notifications to. Used to// reject SNS messages that did not originate from the Marketplace topic.+ // Legacy transport: a product created after 2026-06-01 receives lifecycle+ // events on EventBridge instead, guarded by AWS_MP_EVENT_SECRET below.get AWS_MP_SNS_TOPIC_ARN() {return opt('AWS_MP_SNS_TOPIC_ARN');},+ // Shared secret the EventBridge API destination's connection attaches to+ // every relayed agreement/license event. EventBridge cannot post to an+ // external HTTPS endpoint on its own, so the rule targets an API destination+ // and this header is what proves the POST came from that rule and not from+ // anyone who found the URL. Unset means the webhook refuses EventBridge+ // deliveries entirely rather than trusting an unauthenticated body.+ get AWS_MP_EVENT_SECRET() {+ return opt('AWS_MP_EVENT_SECRET');+ },// Rate limit applied to the auto-issued x402 subscription minted when an// AWS Marketplace customer links their account. Tune per-tier by reading// from offer-identifier in subscription.js if you split listings.diff --git a/api/_lib/migrations/20260817120000_aws_marketplace_concurrent_agreements.sql b/api/_lib/migrations/20260817120000_aws_marketplace_concurrent_agreements.sqlnew file mode 100644index 000000000..84179088c--- /dev/null+++ b/api/_lib/migrations/20260817120000_aws_marketplace_concurrent_agreements.sql@@ -0,0 +1,70 @@+-- AWS Marketplace: Concurrent Agreements re-key.+--+-- AWS made updated integration requirements mandatory for every NEW SaaS+-- product from 2026-06-01. Two consequences for this schema:+--+-- 1. ResolveCustomer no longer populates CustomerIdentifier for a new+-- integration. It returns CustomerAWSAccountId + LicenseArn, and LicenseArn+-- is the per-grant identity. Our listing has never been created, so it is a+-- new integration by definition and customer_identifier will arrive NULL.+-- 2. Lifecycle notifications moved from the SNS subscription topic to+-- EventBridge agreement/license events, which carry an agreement id and a+-- license ARN rather than a customer identifier.+--+-- Under Concurrent Agreements one AWS account can hold several simultaneous+-- agreements for the same product, so (customer_aws_account_id, product_code) is+-- deliberately NOT unique. license_arn is the unique key; agreement_id is a+-- non-unique correlation key stamped from the agreement events.+--+-- Idempotent.++alter table aws_marketplace_customers+ add column if not exists license_arn text,+ add column if not exists agreement_id text;++alter table aws_marketplace_customers+ alter column customer_identifier drop not null;++create unique index if not exists aws_marketplace_customers_license_arn_uniq+ on aws_marketplace_customers (license_arn)+ where license_arn is not null;++create index if not exists aws_marketplace_customers_agreement_idx+ on aws_marketplace_customers (agreement_id)+ where agreement_id is not null;++create index if not exists aws_marketplace_customers_aws_account_idx+ on aws_marketplace_customers (customer_aws_account_id, product_code)+ where customer_aws_account_id is not null;++-- The metering audit table pointed at customer_identifier by foreign key, which+-- cannot survive that column going nullable. Point it at the customer row's own+-- primary key instead and keep the old text column for the legacy rows.+alter table aws_marketplace_metering+ add column if not exists customer_row_id uuid+ references aws_marketplace_customers(id) on delete cascade,+ add column if not exists license_arn text;++alter table aws_marketplace_metering+ drop constraint if exists aws_marketplace_metering_customer_identifier_fkey;++alter table aws_marketplace_metering+ alter column customer_identifier drop not null;++update aws_marketplace_metering m+set customer_row_id = c.id+from aws_marketplace_customers c+where m.customer_row_id is null+ and m.customer_identifier is not null+ and c.customer_identifier = m.customer_identifier;++create index if not exists aws_marketplace_metering_customer_row_idx+ on aws_marketplace_metering (customer_row_id)+ where customer_row_id is not null;++-- Reverse lookup for the x402 bridge: subscriptions issued from a marketplace+-- row now carry the row id in meta, because the license ARN is the thing we do+-- not want to spread across JSONB in more places than necessary.+create index if not exists x402_subscriptions_aws_customer_row_idx+ on x402_subscriptions ((meta->>'aws_customer_row_id'))+ where meta ? 'aws_customer_row_id';diff --git a/api/aws-marketplace/issue-key.js b/api/aws-marketplace/issue-key.jsindex 82b93df89..640b79432 100644--- a/api/aws-marketplace/issue-key.js+++ b/api/aws-marketplace/issue-key.js@@ -8,13 +8,13 @@// Called by /aws-marketplace/welcome after /api/aws-marketplace/link succeeds,// so the customer can copy the key and start calling /api/x402/* immediately.//-// Body (JSON): { customer: "<customerIdentifier>" }+// Body (JSON): { customer: "<row id, or a legacy CustomerIdentifier>" }// Requires an active session cookie.import { cors, json, readJson, wrap } from '../_lib/http.js';-import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { issueSubscriptionForCustomer } from '../_lib/aws-marketplace-bridge.js';+import { findCustomerByHandle } from '../_lib/aws-marketplace-store.js';import { customerEntitlement } from '../_lib/aws-marketplace.js';import { env } from '../_lib/env.js';@@ -48,12 +48,7 @@ export default wrap(async (req, res) => {return json(res, 400, { error: 'missing_customer' });}- const [row] = await sql`- SELECT customer_identifier, product_code, offer_id, is_free_trial,- subscription_status, user_id- FROM aws_marketplace_customers- WHERE customer_identifier = ${customerId}- `;+ const row = await findCustomerByHandle(customerId);if (!row) return json(res, 404, { error: 'customer_not_found' });if (row.user_id && row.user_id !== user.id) {@@ -70,7 +65,10 @@ export default wrap(async (req, res) => {// a throttled/unavailable AWS surfaces an actionable 503 instead of a 500.if (env.AWS_MP_ENTITLEMENT_REQUIRED) {try {- const ent = await customerEntitlement(row.customer_identifier);+ const ent = await customerEntitlement({+ customerAWSAccountId: row.customer_aws_account_id,+ customerIdentifier: row.customer_identifier,+ });if (ent.configured && ent.entitled === false) {return json(res, 403, {error: 'not_entitled',@@ -89,13 +87,7 @@ export default wrap(async (req, res) => {let issued;try {- issued = await issueSubscriptionForCustomer({- customer_identifier: row.customer_identifier,- product_code: row.product_code,- offer_id: row.offer_id,- is_free_trial: row.is_free_trial,- user_id: row.user_id || user.id,- });+ issued = await issueSubscriptionForCustomer({ ...row, user_id: row.user_id || user.id });} catch (err) {console.error('[aws-marketplace/issue-key] failed', {customerId,diff --git a/api/aws-marketplace/link.js b/api/aws-marketplace/link.jsindex c42292f1c..cf0f3fd25 100644--- a/api/aws-marketplace/link.js+++ b/api/aws-marketplace/link.js@@ -3,12 +3,12 @@// Called by the /aws-marketplace/welcome page after the user authenticates.// Links an existing aws_marketplace_customers row to the signed-in user account.//-// Body (JSON): { customer: "<customerIdentifier>" }+// Body (JSON): { customer: "<row id, or a legacy CustomerIdentifier>" }// Requires an active session cookie (set by /api/auth/login or /api/auth/register).import { cors, json, readJson, wrap } from '../_lib/http.js';-import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';+import { findCustomerByHandle, claimCustomerForUser } from '../_lib/aws-marketplace-store.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;@@ -45,11 +45,7 @@ export default wrap(async (req, res) => {return json(res, 400, { error: 'missing_customer' });}- const [row] = await sql`- SELECT customer_identifier, subscription_status, user_id- FROM aws_marketplace_customers- WHERE customer_identifier = ${customerId}- `;+ const row = await findCustomerByHandle(customerId);if (!row) {return json(res, 404, { error: 'customer_not_found' });@@ -68,19 +64,12 @@ export default wrap(async (req, res) => {return json(res, 403, { error: 'customer_linked_to_other_account' });}- const linked = await sql`- UPDATE aws_marketplace_customers- SET user_id = ${user.id},- updated_at = now()- WHERE customer_identifier = ${customerId}- AND (user_id IS NULL OR user_id = ${user.id})- RETURNING customer_identifier- `;+ const linked = await claimCustomerForUser(row.id, user.id);// 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) {+ if (!linked) {return json(res, 403, { error: 'customer_linked_to_other_account' });}diff --git a/api/aws-marketplace/register.js b/api/aws-marketplace/register.jsindex 5b1e917ce..27246ed30 100644--- a/api/aws-marketplace/register.js+++ b/api/aws-marketplace/register.js@@ -2,25 +2,37 @@//// Registration URL for AWS Marketplace SaaS products.//-// When a customer subscribes in AWS Marketplace they are redirected here via-// an HTTP POST (application/x-www-form-urlencoded) with:-// x-amzn-marketplace-token — short-lived token to exchange for customer ID+// When a customer subscribes in AWS Marketplace and chooses "Set up your+// account" they are redirected here via an HTTP POST+// (application/x-www-form-urlencoded) with:+// x-amzn-marketplace-token : short-lived token to exchange for the buyer's identity// x-amzn-marketplace-offer-type — "free-trial" when the subscription is a trial//// Steps:-// 1. Exchange token for stable CustomerIdentifier via ResolveCustomer.-// 2. Upsert the customer row in aws_marketplace_customers.-// 3. If the caller is already signed into three.ws, link the customer record-// to their user account immediately.-// 4. Redirect to /aws-marketplace/welcome?customer=<id>&trial=<bool>-// so the frontend can show a tailored onboarding flow.+// 1. Exchange the token via ResolveCustomer. For a new SaaS integration AWS+// returns LicenseArn + CustomerAWSAccountId and leaves CustomerIdentifier+// empty, so the store keys on the license.+// 2. Upsert (or adopt) the row in aws_marketplace_customers.+// 3. If the caller is already signed into three.ws, link the row to their+// user account immediately.+// 4. Redirect to /aws-marketplace/welcome?customer=<row id>&trial=<bool> so+// the frontend can show a tailored onboarding flow. The handle is the row+// id, never the license ARN: a grant identifier does not belong in a URL+// that lands in browser history, referrers, and access logs.import { readForm, wrap } from '../_lib/http.js';-import { sql } from '../_lib/db.js';import { resolveCustomer, awsMarketplaceConfigured } from '../_lib/aws-marketplace.js';+import { upsertResolvedCustomer, claimCustomerForUser } from '../_lib/aws-marketplace-store.js';import { getSessionUser } from '../_lib/auth.js';import { env } from '../_lib/env.js';+function redirect(res, location) {+ res.statusCode = 302;+ res.setHeader('location', location);+ res.setHeader('cache-control', 'no-store');+ res.end();+}+export default wrap(async (req, res) => {if (req.method !== 'POST') {res.statusCode = 405;@@ -56,67 +68,61 @@ export default wrap(async (req, res) => {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();+ redirect(res, `${env.APP_ORIGIN}/aws-marketplace/error?reason=not_configured`);return;}- let customer;+ let resolved;try {- customer = await resolveCustomer(token);+ resolved = await resolveCustomer(token);} catch (err) {console.error('[aws-marketplace/register] resolveCustomer failed', err?.message);// Surface a user-readable error page rather than a raw 500.- res.statusCode = 302;- res.setHeader('location', `${env.APP_ORIGIN}/aws-marketplace/error?reason=token_expired`);- res.setHeader('cache-control', 'no-store');- res.end();+ redirect(res, `${env.APP_ORIGIN}/aws-marketplace/error?reason=token_expired`);return;}- const { customerIdentifier, productCode, customerAWSAccountId } = customer;+ // A token that resolves but yields no usable identity is an integration+ // fault, not a buyer fault, and silently inserting an unkeyed row would+ // hand out access we could never revoke. Refuse it loudly.+ if (!resolved.licenseArn && !resolved.customerIdentifier) {+ console.error('[aws-marketplace/register] ResolveCustomer returned neither LicenseArn nor CustomerIdentifier', {+ productCode: resolved.productCode,+ customerAWSAccountId: resolved.customerAWSAccountId,+ });+ redirect(res, `${env.APP_ORIGIN}/aws-marketplace/error?reason=unresolved_customer`);+ return;+ }- // Persist / update the customer record.- await sql`- INSERT INTO aws_marketplace_customers- (customer_identifier, product_code, customer_aws_account_id,- subscription_status, is_free_trial, subscribed_at)- VALUES- (${customerIdentifier}, ${productCode}, ${customerAWSAccountId ?? null},- ${isFreeTrial ? 'trial' : 'active'}, ${isFreeTrial}, now())- ON CONFLICT (customer_identifier) DO UPDATE SET- customer_aws_account_id = COALESCE(EXCLUDED.customer_aws_account_id, aws_marketplace_customers.customer_aws_account_id),- subscription_status = CASE- WHEN aws_marketplace_customers.subscription_status IN ('cancelled', 'expired')- THEN EXCLUDED.subscription_status- ELSE aws_marketplace_customers.subscription_status- END,- updated_at = now()- `;+ let customer;+ try {+ customer = await upsertResolvedCustomer({+ licenseArn: resolved.licenseArn,+ customerAWSAccountId: resolved.customerAWSAccountId,+ customerIdentifier: resolved.customerIdentifier,+ productCode: resolved.productCode || env.AWS_MP_PRODUCT_CODE,+ isFreeTrial,+ });+ } catch (err) {+ console.error('[aws-marketplace/register] failed to persist customer', err?.message);+ redirect(res, `${env.APP_ORIGIN}/aws-marketplace/error?reason=link_failed`);+ return;+ }// If a three.ws session is already active, link accounts right now.const user = await getSessionUser(req).catch(() => null);- if (user) {- await sql`- UPDATE aws_marketplace_customers- SET user_id = ${user.id},- updated_at = now()- WHERE customer_identifier = ${customerIdentifier}- AND user_id IS NULL- `;+ if (user && !customer.user_id) {+ await claimCustomerForUser(customer.id, user.id).catch((err) => {+ console.error('[aws-marketplace/register] auto-link failed', err?.message);+ return null;+ });}- // Redirect to the frontend onboarding page.const params = new URLSearchParams({- customer: customerIdentifier,+ customer: customer.id,trial: isFreeTrial ? '1' : '0',});if (!user) params.set('signup', '1');- res.statusCode = 302;- res.setHeader('location', `${env.APP_ORIGIN}/aws-marketplace/welcome?${params}`);- res.setHeader('cache-control', 'no-store');- res.end();+ redirect(res, `${env.APP_ORIGIN}/aws-marketplace/welcome?${params}`);});diff --git a/api/aws-marketplace/subscription.js b/api/aws-marketplace/subscription.jsindex 341c6a558..ac42f36fd 100644--- a/api/aws-marketplace/subscription.js+++ b/api/aws-marketplace/subscription.js@@ -1,23 +1,43 @@// POST /api/aws-marketplace/subscription//-// Amazon SNS webhook called by AWS Marketplace when a customer subscribes,-// unsubscribes, or when entitlements change.+// Lifecycle webhook for the AWS Marketplace listing. Accepts BOTH transports,+// because which one AWS uses depends on when the product was created://-// AWS sends three message types:-// SubscriptionConfirmation — one-time handshake; we must GET the SubscribeURL.-// UnsubscribeConfirmation — mirrored when AWS cancels the subscription.-// Notification — actual subscription lifecycle events.+// EventBridge, the transport AWS has required of new products since 2026-06-01.+// Agreement and license events land on the seller account's default event+// bus with source `aws.agreement-marketplace`. EventBridge cannot POST to an+// external HTTPS endpoint, so a rule relays them through an API destination+// whose connection attaches a shared secret header. The events carry a+// LicenseArn and an agreement id; they never carry a CustomerIdentifier.+// Purchase Agreement Created / Amended → grant+// Purchase Agreement Ended → revoke+// License Updated → grant, and attach the license+// License Deprovisioned → revoke//-// Notification actions received for SaaS usage-based products:-// subscribe-success — customer has subscribed (isFreeTrialTermPresent may be true)-// subscribe-fail — subscription could not be completed-// unsubscribe-success — customer cancelled or subscription expired-// entitlement-updated — contract product entitlement changed+// Amazon SNS (existing products)+// The aws-mp-subscription-notification-<PRODUCTCODE> topic, signed by AWS.+// subscribe-success / unsubscribe-success / subscribe-fail / entitlement-updated+//+// Both paths converge on the same store, so a listing that is migrated from one+// transport to the other keeps working without a code change.import { json, wrap, readBody } from '../_lib/http.js';import { sql } from '../_lib/db.js';-import { verifySnsMessage, assertAwsHttpsUrl } from '../_lib/aws-marketplace.js';+import {+ verifySnsMessage,+ assertAwsHttpsUrl,+ isEventBridgeEnvelope,+ parseMarketplaceEvent,+ verifyEventSecret,+} from '../_lib/aws-marketplace.js';import { revokeSubscriptionForCustomer } from '../_lib/aws-marketplace-bridge.js';+import {+ upsertResolvedCustomer,+ recordAgreementCreated,+ attachLicenseToAgreement,+ resolveLifecycleTargets,+ markCustomerStatus,+} from '../_lib/aws-marketplace-store.js';import { env } from '../_lib/env.js';// Delegates to the shared readBody (api/_lib/http.js), which prefers the@@ -28,14 +48,105 @@ async function readRawBody(req) {return (await readBody(req, 1_000_000)).toString('utf8');}-export default wrap(async (req, res) => {- // AWS SNS sends POST for all message types.- if (req.method !== 'POST') {- res.statusCode = 405;- res.end();- return;+/**+ * Revoke a buyer's access. Revokes the x402 key BEFORE flipping status. If the+ * revoke fails we leave the row live so the event can be retried, rather than+ * ending up with a cancelled customer who still holds a working key.+ */+async function revokeCustomer(row, status) {+ await revokeSubscriptionForCustomer(row.id);+ await markCustomerStatus(row.id, status);+}++// ── EventBridge ──────────────────────────────────────────────────────────────++async function handleEventBridge(req, res, event) {+ const secretFailure = verifyEventSecret(req);+ if (secretFailure) {+ if (secretFailure === 'not_configured') {+ console.error('[aws-marketplace/subscription] refusing EventBridge delivery: AWS_MP_EVENT_SECRET is not set');+ return json(res, 503, { error: 'not_configured' });+ }+ console.error('[aws-marketplace/subscription] EventBridge secret rejected', { reason: secretFailure });+ return json(res, 403, { error: 'forbidden' });+ }++ const parsed = parseMarketplaceEvent(event);+ if (!parsed) {+ console.error('[aws-marketplace/subscription] event from unexpected source', { source: event.source });+ return json(res, 400, { error: 'unexpected_source' });+ }+ if (parsed.kind === 'ignored') {+ return json(res, 200, { ok: true, ignored: parsed.detailType });+ }++ const productCode = parsed.productCode || env.AWS_MP_PRODUCT_CODE;++ if (parsed.kind === 'agreement-created') {+ const row = await recordAgreementCreated({+ agreementId: parsed.agreementId,+ acceptorAccountId: parsed.acceptorAccountId,+ offerId: parsed.offerId,+ productCode,+ });+ return json(res, 200, { ok: true, customer: row?.id ?? null });+ }++ if (parsed.kind === 'license-updated') {+ const row = await attachLicenseToAgreement({+ agreementId: parsed.agreementId,+ licenseArn: parsed.licenseArn,+ acceptorAccountId: parsed.acceptorAccountId,+ offerId: parsed.offerId,+ productCode,+ });+ return json(res, 200, { ok: true, customer: row?.id ?? null });}+ // agreement-ended | license-deprovisioned+ const targets = await resolveLifecycleTargets({+ licenseArn: parsed.licenseArn,+ agreementId: parsed.agreementId,+ acceptorAccountId: parsed.acceptorAccountId,+ productCode,+ });++ if (targets.length === 0) {+ // The buyer never completed registration, so there is nothing to revoke.+ // Not an error: AWS sends the end event regardless.+ return json(res, 200, { ok: true, matched: 0 });+ }++ // Under Concurrent Agreements one AWS account can hold several live+ // agreements for the same product. If the event only identified the account,+ // revoking would be a coin flip between them, and the wrong call cuts off a+ // paying buyer. Retrying cannot add information, so answer 200 and make the+ // ambiguity loud instead of silently guessing.+ if (targets.length > 1) {+ console.error('[aws-marketplace/subscription] ambiguous lifecycle target; refusing to revoke', {+ detailType: parsed.detailType,+ agreementId: parsed.agreementId,+ acceptorAccountId: parsed.acceptorAccountId,+ matched: targets.length,+ });+ return json(res, 200, { ok: true, unresolved: true, matched: targets.length });+ }++ try {+ await revokeCustomer(targets[0], 'cancelled');+ } catch (err) {+ console.error('[aws-marketplace/subscription] revoke failed', {+ customer: targets[0].id,+ error: err?.message,+ });+ return json(res, 500, { error: 'revoke_failed' });+ }+ return json(res, 200, { ok: true, revoked: targets[0].id });+}++// ── Amazon SNS (legacy transport) ────────────────────────────────────────────++async function handleSns(req, res, msg) {// 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@@ -49,17 +160,6 @@ export default wrap(async (req, res) => {return json(res, 503, { error: 'not_configured' });}- let msg;- try {- const raw = await readRawBody(req);- msg = JSON.parse(raw);- } catch {- res.statusCode = 400;- res.end();- return;- }-- // Verify the message was genuinely signed by AWS.try {await verifySnsMessage(msg);} catch (err) {@@ -81,7 +181,6 @@ export default wrap(async (req, res) => {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(subscribeUrl);} catch (err) {@@ -102,79 +201,91 @@ export default wrap(async (req, res) => {return json(res, 400, { error: 'malformed_message' });}- const { action, 'customer-identifier': customerId, 'product-code': productCode, 'offer-identifier': offerId, isFreeTrialTermPresent } = payload;+ const {+ action,+ 'customer-identifier': customerId,+ 'product-code': productCode,+ 'offer-identifier': offerId,+ isFreeTrialTermPresent,+ } = payload;const isFreeTrial = isFreeTrialTermPresent === 'true' || isFreeTrialTermPresent === true;+ // SNS never carries a LicenseArn, so this transport can only ever address a+ // buyer by the legacy identifier. A notification without one is unusable.if (!customerId) {console.error('[aws-marketplace/subscription] missing customer-identifier', payload);return json(res, 400, { error: 'missing_customer_identifier' });}if (action === 'subscribe-success') {- await sql`- INSERT INTO aws_marketplace_customers- (customer_identifier, product_code, offer_id, subscription_status, is_free_trial, subscribed_at)- VALUES- (${customerId}, ${productCode ?? env.AWS_MP_PRODUCT_CODE}, ${offerId ?? null},- ${isFreeTrial ? 'trial' : 'active'}, ${isFreeTrial}, now())- ON CONFLICT (customer_identifier) DO UPDATE SET- subscription_status = EXCLUDED.subscription_status,- is_free_trial = EXCLUDED.is_free_trial,- offer_id = COALESCE(EXCLUDED.offer_id, aws_marketplace_customers.offer_id),- subscribed_at = COALESCE(aws_marketplace_customers.subscribed_at, now()),- cancelled_at = NULL,- updated_at = now()- `;- } else if (action === 'unsubscribe-success') {- // Revoke the x402 bypass key BEFORE flipping status — if the revoke- // fails we leave the row 'active' so we can retry from the dead-letter- // queue rather than ending up with a cancelled customer who still has- // a working key.- try {- await revokeSubscriptionForCustomer(customerId);- } catch (err) {- console.error('[aws-marketplace/subscription] revoke failed', {- customerId,- error: err?.message,- });- return json(res, 500, { error: 'revoke_failed' });+ const row = await upsertResolvedCustomer({+ customerIdentifier: customerId,+ productCode: productCode ?? env.AWS_MP_PRODUCT_CODE,+ isFreeTrial,+ });+ if (offerId) {+ await sql`+ update aws_marketplace_customers+ set offer_id = ${offerId}, updated_at = now()+ where id = ${row.id}+ `;}- await sql`- UPDATE aws_marketplace_customers- SET subscription_status = 'cancelled',- cancelled_at = now(),- updated_at = now()- WHERE customer_identifier = ${customerId}- `;- } else if (action === 'subscribe-fail') {+ return json(res, 200, { ok: true, customer: row.id });+ }++ const [row] = await sql`+ select id from aws_marketplace_customers+ where customer_identifier = ${customerId} limit 1+ `;+ if (!row) {+ return json(res, 200, { ok: true, matched: 0 });+ }++ if (action === 'unsubscribe-success' || action === 'subscribe-fail') {+ const status = action === 'unsubscribe-success' ? 'cancelled' : 'expired';try {- await revokeSubscriptionForCustomer(customerId);+ await revokeCustomer(row, status);} catch (err) {- console.error('[aws-marketplace/subscription] revoke on fail failed', {- customerId,- error: err?.message,- });+ console.error('[aws-marketplace/subscription] revoke failed', { customerId, error: err?.message });+ return json(res, 500, { error: 'revoke_failed' });}- await sql`- UPDATE aws_marketplace_customers- SET subscription_status = 'expired',- updated_at = now()- WHERE customer_identifier = ${customerId}- `;} else if (action === 'entitlement-updated') {// Contract products use entitlements; usage products ignore this beat.- // For both, we touch updated_at so audit queries reflect the event.- // If a tier change implies a different rate-limit, the partner will- // see it on next /api/x402/* call: lookupSubscription reads the live- // rate_limit_per_minute from the row, so a follow-up admin update- // (or future per-tier auto-tune) takes effect without a re-issue.+ // For both, we touch updated_at so audit queries reflect the event. If a+ // tier change implies a different rate limit, the partner sees it on the+ // next /api/x402/* call: lookupSubscription reads the live+ // rate_limit_per_minute from the row, so a follow-up update takes effect+ // without a re-issue.await sql`- UPDATE aws_marketplace_customers- SET offer_id = COALESCE(${offerId ?? null}, offer_id),+ update aws_marketplace_customers+ set offer_id = coalesce(${offerId ?? null}, offer_id),updated_at = now()- WHERE customer_identifier = ${customerId}+ where id = ${row.id}`;}return json(res, 200, { ok: true });+}++export default wrap(async (req, res) => {+ if (req.method !== 'POST') {+ res.statusCode = 405;+ res.setHeader('allow', 'POST');+ res.end();+ return;+ }++ let body;+ try {+ body = JSON.parse(await readRawBody(req));+ } catch {+ res.statusCode = 400;+ res.end();+ return;+ }++ if (isEventBridgeEnvelope(body)) {+ return handleEventBridge(req, res, body);+ }+ return handleSns(req, res, body);});diff --git a/api/user/x402-subscriptions.js b/api/user/x402-subscriptions.jsindex ae8f21716..467c1b3fe 100644--- a/api/user/x402-subscriptions.js+++ b/api/user/x402-subscriptions.js@@ -8,7 +8,7 @@// rotate: revoke the old key and mint a fresh one. The new plaintext is// returned ONCE. For AWS-Marketplace-sourced keys this goes// through the billing bridge so the new key stays linked to the-// AWS CustomerIdentifier and keeps metering correctly.+// AWS subscription record and keeps metering correctly.// revoke: permanently disable a NATIVE key. AWS-sourced keys cannot be// bare-revoked here (that would cut off access the customer is// paying AWS for); cancellation must originate in AWS Marketplace.@@ -26,6 +26,7 @@ import {issueSubscriptionForCustomer,revokeSubscriptionForCustomer,} from '../_lib/aws-marketplace-bridge.js';+import { findCustomerByHandle } from '../_lib/aws-marketplace-store.js';const AWS_SOURCE = 'aws-marketplace';@@ -140,16 +141,14 @@ export default wrap(async (req, res) => {// rotateif (isAws) {- const customerId = meta.aws_customer_identifier;+ // Keys minted since the Concurrent Agreements re-key carry the customer+ // row id; older ones only carry the legacy CustomerIdentifier, which AWS+ // no longer issues. findCustomerByHandle resolves either.+ const customerId = meta.aws_customer_row_id || meta.aws_customer_identifier;if (!customerId) {return json(res, 422, { error: 'aws_customer_unresolved' });}- const [customer] = await sql`- SELECT customer_identifier, product_code, offer_id, is_free_trial,- subscription_status, user_id- FROM aws_marketplace_customers- WHERE customer_identifier = ${customerId}- `;+ const customer = await findCustomerByHandle(customerId);if (!customer) return json(res, 404, { error: 'customer_not_found' });if (customer.subscription_status === 'cancelled' ||@@ -164,17 +163,11 @@ export default wrap(async (req, res) => {}// Revoke the prior link, then mint a fresh key through the bridge so the- // new key stays attached to the AWS CustomerIdentifier and keeps metering.- await revokeSubscriptionForCustomer(customerId);+ // new key stays attached to the AWS subscription and keeps metering.+ await revokeSubscriptionForCustomer(customer.id);let issued;try {- issued = await issueSubscriptionForCustomer({- customer_identifier: customer.customer_identifier,- product_code: customer.product_code,- offer_id: customer.offer_id,- is_free_trial: customer.is_free_trial,- user_id: customer.user_id || user.id,- });+ issued = await issueSubscriptionForCustomer({ ...customer, user_id: customer.user_id || user.id });} catch (err) {console.error('[user/x402-subscriptions] aws rotate failed', { customerId, error: err?.message });return json(res, 502, { error: 'rotate_failed' });diff --git a/tests/api/aws-marketplace-eventbridge.test.js b/tests/api/aws-marketplace-eventbridge.test.jsnew file mode 100644index 000000000..db55195ad--- /dev/null+++ b/tests/api/aws-marketplace-eventbridge.test.js@@ -0,0 +1,258 @@+// EventBridge lifecycle transport for /api/aws-marketplace/subscription.+//+// AWS made Concurrent Agreements mandatory for new SaaS products on 2026-06-01.+// Two consequences this file guards:+//+// 1. Lifecycle notifications for a new listing arrive as EventBridge events+// (source `aws.agreement-marketplace`), relayed through an API destination,+// not as signed SNS envelopes. The webhook has to recognize and act on+// them, and it has to refuse them when the relay secret is unset or wrong.+// an unauthenticated caller who can post here can revoke a paying buyer.+// 2. Those events never carry a CustomerIdentifier. They carry a license ARN+// and an agreement id, and under concurrent agreements a single AWS account+// can hold several live agreements for the same product, so an event that+// only names the account must not be allowed to guess which one to revoke.++import { describe, it, expect, beforeEach, 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 {+ parseMarketplaceEvent,+ isEventBridgeEnvelope,+ EVENT_SECRET_HEADER,+} = await import('../../api/_lib/aws-marketplace.js');++const SECRET = 'THREEsynthetic-eventbridge-secret';+const LICENSE = 'arn:aws:license-manager:us-east-1:155407237916:l-synthetic0000';+const AGREEMENT = 'agmt-synthetic0000000000000';++function event(detailType, detail) {+ return {+ version: '0',+ id: '12345678-1234-1234-1234-123456789012',+ 'detail-type': detailType,+ source: 'aws.agreement-marketplace',+ account: '155407237916',+ time: '2026-08-17T00:00:00Z',+ region: 'us-east-1',+ resources: [`arn:aws:aws-marketplace::aws:agreement:${AGREEMENT}`],+ detail: { requestId: 'req-1', catalog: 'AWSMarketplace', ...detail },+ };+}++function makeReq(body, headers = {}) {+ return {+ method: 'POST',+ url: '/api/aws-marketplace/subscription',+ headers: { 'content-type': 'application/json', 'user-agent': 'vitest', ...headers },+ rawBody: Buffer.from(JSON.stringify(body)),+ query: {},+ };+}++function signedReq(body) {+ return makeReq(body, { [EVENT_SECRET_HEADER]: SECRET });+}++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;+}++beforeEach(() => {+ sqlMock.mockClear().mockResolvedValue([{ id: 'row-1', license_arn: LICENSE }]);+ revokeMock.mockClear().mockResolvedValue(null);+ verifySnsMessageMock.mockClear().mockResolvedValue(undefined);+ process.env.AWS_MP_EVENT_SECRET = SECRET;+ process.env.AWS_MP_PRODUCT_CODE = 'THREEsyntheticProductCode';+});++describe('parseMarketplaceEvent', () => {+ it('maps every lifecycle detail-type onto the action the listing takes', () => {+ const cases = [+ ['Purchase Agreement Created - Proposer', 'agreement-created'],+ ['Purchase Agreement Created - Manufacturer', 'agreement-created'],+ ['Purchase Agreement Amended - Manufacturer', 'agreement-created'],+ ['Purchase Agreement Ended - Manufacturer', 'agreement-ended'],+ ['License Updated - Manufacturer', 'license-updated'],+ ['License Deprovisioned - Manufacturer', 'license-deprovisioned'],+ ['Spend Threshold Reached', 'ignored'],+ ];+ for (const [detailType, kind] of cases) {+ expect(parseMarketplaceEvent(event(detailType, {})).kind).toBe(kind);+ }+ });++ it('reads the license, agreement, acceptor, and offer out of a License Updated event', () => {+ const parsed = parseMarketplaceEvent(+ event('License Updated - Manufacturer', {+ agreement: { id: AGREEMENT },+ product: { code: 'THREEsyntheticProductCode', id: 'prod-synthetic' },+ license: { arn: LICENSE },+ acceptor: { accountId: '111122223333' },+ offer: { id: 'offer-synthetic' },+ }),+ );+ expect(parsed).toMatchObject({+ kind: 'license-updated',+ licenseArn: LICENSE,+ agreementId: AGREEMENT,+ acceptorAccountId: '111122223333',+ offerId: 'offer-synthetic',+ productCode: 'THREEsyntheticProductCode',+ });+ });++ it('ignores an event from any other source', () => {+ expect(parseMarketplaceEvent({ source: 'aws.marketplacecatalog', 'detail-type': 'Offer Released' })).toBeNull();+ });++ it('tells an EventBridge envelope apart from an SNS one', () => {+ expect(isEventBridgeEnvelope(event('Purchase Agreement Ended - Manufacturer', {}))).toBe(true);+ expect(isEventBridgeEnvelope({ Type: 'Notification', TopicArn: 'arn:aws:sns:…', Message: '{}' })).toBe(false);+ });+});++describe('POST /api/aws-marketplace/subscription EventBridge relay', () => {+ it('refuses delivery with 503 when no relay secret is configured', async () => {+ delete process.env.AWS_MP_EVENT_SECRET;+ const res = makeRes();+ await handler(signedReq(event('Purchase Agreement Ended - Manufacturer', { license: { arn: LICENSE } })), res);+ expect(res._get().status).toBe(503);+ expect(res._get().body).toEqual({ error: 'not_configured' });+ expect(revokeMock).not.toHaveBeenCalled();+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('rejects a relayed event carrying the wrong secret', async () => {+ const res = makeRes();+ await handler(+ makeReq(event('License Deprovisioned - Manufacturer', { license: { arn: LICENSE } }), {+ [EVENT_SECRET_HEADER]: 'not-the-secret',+ }),+ res,+ );+ expect(res._get().status).toBe(403);+ expect(revokeMock).not.toHaveBeenCalled();+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('rejects a relayed event carrying no secret at all', async () => {+ const res = makeRes();+ await handler(makeReq(event('License Deprovisioned - Manufacturer', { license: { arn: LICENSE } })), res);+ expect(res._get().status).toBe(403);+ expect(revokeMock).not.toHaveBeenCalled();+ });++ it('revokes the buyer named by a License Deprovisioned event', async () => {+ const res = makeRes();+ await handler(+ signedReq(+ event('License Deprovisioned - Manufacturer', {+ agreement: { id: AGREEMENT },+ license: { arn: LICENSE },+ acceptor: { accountId: '111122223333' },+ }),+ ),+ res,+ );+ expect(res._get().status).toBe(200);+ expect(res._get().body).toEqual({ ok: true, revoked: 'row-1' });+ expect(revokeMock).toHaveBeenCalledWith('row-1');+ });++ it('refuses to guess when an end event matches more than one live agreement', async () => {+ // No license ARN and no stamped agreement: resolution falls back to the+ // acceptor's AWS account, which under concurrent agreements can hold+ // several. Revoking either would cut off access the buyer still pays for.+ sqlMock.mockResolvedValue([{ id: 'row-1' }, { id: 'row-2' }]);+ const res = makeRes();+ await handler(+ signedReq(+ event('Purchase Agreement Ended - Manufacturer', {+ acceptor: { accountId: '111122223333' },+ }),+ ),+ res,+ );+ expect(res._get().status).toBe(200);+ expect(res._get().body).toEqual({ ok: true, unresolved: true, matched: 2 });+ expect(revokeMock).not.toHaveBeenCalled();+ });++ it('answers 200 without revoking when no buyer matches the end event', async () => {+ sqlMock.mockResolvedValue([]);+ const res = makeRes();+ await handler(+ signedReq(event('Purchase Agreement Ended - Manufacturer', { license: { arn: LICENSE } })),+ res,+ );+ expect(res._get().status).toBe(200);+ expect(res._get().body).toEqual({ ok: true, matched: 0 });+ expect(revokeMock).not.toHaveBeenCalled();+ });++ it('records a new agreement without touching the x402 key', async () => {+ const res = makeRes();+ await handler(+ signedReq(+ event('Purchase Agreement Created - Proposer', {+ agreement: { id: AGREEMENT, status: 'ACTIVE' },+ acceptor: { accountId: '111122223333' },+ offer: { id: 'offer-synthetic' },+ }),+ ),+ res,+ );+ expect(res._get().status).toBe(200);+ expect(res._get().body).toEqual({ ok: true, customer: 'row-1' });+ expect(revokeMock).not.toHaveBeenCalled();+ });++ it('acknowledges a marketplace event it takes no action on', async () => {+ const res = makeRes();+ await handler(signedReq(event('Spend Threshold Vet Succeeded', {})), res);+ expect(res._get().status).toBe(200);+ expect(res._get().body).toEqual({ ok: true, ignored: 'Spend Threshold Vet Succeeded' });+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('never falls through to the SNS verifier for an EventBridge body', async () => {+ await handler(+ signedReq(event('License Deprovisioned - Manufacturer', { license: { arn: LICENSE } })),+ makeRes(),+ );+ expect(verifySnsMessageMock).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/aws-marketplace-sns.test.js b/tests/api/aws-marketplace-sns.test.jsindex 7e2ee4431..59ee72426 100644--- a/tests/api/aws-marketplace-sns.test.js+++ b/tests/api/aws-marketplace-sns.test.js@@ -35,10 +35,18 @@ function signingString(msg) {.join('');}-/** Build a message and attach a valid AWS-style RSA-SHA1 signature over it. */-function signed(msg) {- const m = { ...msg, SigningCertURL: msg.SigningCertURL ?? CERT_URL, SignatureVersion: '1' };- const sig = createSign('RSA-SHA1').update(signingString(m)).sign(privateKey, 'base64');+/**+ * Build a message and attach a valid AWS-style signature over it.+ *+ * SignatureVersion selects the digest, and SNS supports both: version 1 topics+ * sign with SHA1, version 2 topics with SHA256. A topic can be switched to+ * version 2 at any time, so the verifier has to follow the field rather than+ * assume one.+ */+function signed(msg, signatureVersion = '1') {+ const m = { ...msg, SigningCertURL: msg.SigningCertURL ?? CERT_URL, SignatureVersion: signatureVersion };+ const algorithm = signatureVersion === '2' ? 'RSA-SHA256' : 'RSA-SHA1';+ const sig = createSign(algorithm).update(signingString(m)).sign(privateKey, 'base64');return { ...m, Signature: sig };}@@ -122,6 +130,41 @@ describe('verifySnsMessage', () => {process.env.AWS_MP_SNS_TOPIC_ARN = 'arn:aws:sns:us-east-1:155407237916:marketplace-topic';await expect(verifySnsMessage(validNotification())).resolves.toBeUndefined();});++ // A SignatureVersion 2 topic signs with SHA256. Verifying it with SHA1 fails+ // every genuine message, and the failure reads exactly like a forgery, so the+ // operator hunts an attack that is not there while real lifecycle events are+ // dropped with a 403.+ it('accepts a SignatureVersion 2 message, which AWS signs with SHA256', async () => {+ const msg = signed(+ {+ Type: 'Notification',+ MessageId: 'id-v2',+ Subject: 'AWS Marketplace',+ Message: JSON.stringify({ action: 'subscribe-success', 'customer-identifier': 'CUST1' }),+ Timestamp: '2026-08-17T00:00:00.000Z',+ TopicArn: 'arn:aws:sns:us-east-1:155407237916:marketplace-topic',+ },+ '2',+ );+ await expect(verifySnsMessage(msg)).resolves.toBeUndefined();+ });++ it('still rejects a tampered SignatureVersion 2 message', async () => {+ const msg = signed(+ {+ Type: 'Notification',+ MessageId: 'id-v2-tampered',+ Subject: 'AWS Marketplace',+ Message: JSON.stringify({ action: 'subscribe-success', 'customer-identifier': 'CUST1' }),+ Timestamp: '2026-08-17T00:00:00.000Z',+ TopicArn: 'arn:aws:sns:us-east-1:155407237916:marketplace-topic',+ },+ '2',+ );+ msg.Message = JSON.stringify({ action: 'unsubscribe-success', 'customer-identifier': 'CUST1' });+ await expect(verifySnsMessage(msg)).rejects.toThrow(/signature verification failed/i);+ });});// The same guard now protects both URLs this integration dereferences from andiff --git a/tests/api/aws-marketplace-subscription-guard.test.js b/tests/api/aws-marketplace-subscription-guard.test.jsindex fc8708afe..d297af1a4 100644--- a/tests/api/aws-marketplace-subscription-guard.test.js+++ b/tests/api/aws-marketplace-subscription-guard.test.js@@ -77,7 +77,9 @@ function notification(action, customerId = 'THREEsynthetic-awsmp-test') {}beforeEach(() => {- sqlMock.mockClear();+ // Every store query in this path either reads or returns the customer row,+ // so a single-row answer keeps the mock honest without a database.+ sqlMock.mockClear().mockResolvedValue([{ id: 'row-1', customer_identifier: 'THREEsynthetic-awsmp-test' }]);verifySnsMessageMock.mockClear().mockResolvedValue(undefined);revokeMock.mockClear().mockResolvedValue(null);process.env.AWS_MP_SNS_TOPIC_ARN = TOPIC;@@ -111,8 +113,8 @@ describe('POST /api/aws-marketplace/subscription topic pin', () => {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);+ expect(res._get().body).toEqual({ ok: true, customer: 'row-1' });+ expect(sqlMock).toHaveBeenCalled();});it('rejects a message the verifier refuses', async () => {@@ -150,7 +152,17 @@ describe('POST /api/aws-marketplace/subscription topic pin', () => {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();+ // Only the lookup that found the row may have run. Status must NOT flip to+ // cancelled while the key is still live.+ expect(sqlMock).toHaveBeenCalledTimes(1);+ });++ it('answers 200 without revoking when the notification names an unknown customer', async () => {+ sqlMock.mockResolvedValue([]);+ const res = makeRes();+ await handler(makeReq(notification('unsubscribe-success')), res);+ expect(res._get().status).toBe(200);+ expect(res._get().body).toEqual({ ok: true, matched: 0 });+ expect(revokeMock).not.toHaveBeenCalled();});});diff --git a/tests/metering.test.js b/tests/metering.test.jsindex 000fc208b..854848a78 100644--- a/tests/metering.test.js+++ b/tests/metering.test.js@@ -149,21 +149,33 @@ describe('atomicsToUsd', () => {});});-describe('AWS Marketplace — MeterUsage call shape (SDK boundary mocked)', () => {- it('issues a MeterUsage command with the product code, dimension, and idempotency allocation', async () => {+describe('AWS Marketplace metering call shape (SDK boundary mocked)', () => {+ // AWS stopped populating CustomerIdentifier for new SaaS integrations and+ // requires LicenseArn + CustomerAWSAccountId instead. The metering helper has+ // to pick the right command for whichever identity the buyer's row holds:+ // BatchMeterUsage for a licensed buyer, the legacy MeterUsage only when a+ // pre-existing row has nothing but a customer identifier.+ async function loadMetering(response) {vi.resetModules();const sent = [];vi.doMock('@aws-sdk/client-marketplace-metering', () => ({MarketplaceMeteringClient: class {async send(cmd) {sent.push(cmd);- return { MeteringRecordId: 'rec-1' };+ return response;}},ResolveCustomerCommand: class {},MeterUsageCommand: class {constructor(input) {this.input = input;+ this.commandName = 'MeterUsage';+ }+ },+ BatchMeterUsageCommand: class {+ constructor(input) {+ this.input = input;+ this.commandName = 'BatchMeterUsage';}},}));@@ -174,25 +186,70 @@ describe('AWS Marketplace — MeterUsage call shape (SDK boundary mocked)', () =vi.doMock('../api/_lib/env.js', () => ({env: { AWS_MP_PRODUCT_CODE: 'prod123', AWS_MP_REGION: 'us-east-1', AWS_MP_ACCESS_KEY_ID: 'k', AWS_MP_SECRET_ACCESS_KEY: 's' },}));-const { meterUsage } = await import('../api/_lib/aws-marketplace.js');+ return { meterUsage, sent };+ }++ function unmock() {+ vi.doUnmock('@aws-sdk/client-marketplace-metering');+ vi.doUnmock('@aws-sdk/client-marketplace-entitlement-service');+ vi.doUnmock('../api/_lib/env.js');+ }++ it('meters a licensed buyer through BatchMeterUsage with the license ARN', async () => {+ const { meterUsage, sent } = await loadMetering({+ Results: [{ Status: 'Success', MeteringRecordId: 'rec-1' }],+ });const recordId = await meterUsage({- customerIdentifier: 'cust-1',+ licenseArn: 'arn:aws:license-manager:us-east-1:155407237916:l-synthetic',+ customerAWSAccountId: '111122223333',dimension: 'api_call',quantity: 1,- usageAllocationId: 'alloc-1',});expect(recordId).toBe('rec-1');expect(sent).toHaveLength(1);- const input = sent[0].input;- expect(input.ProductCode).toBe('prod123');- expect(input.UsageDimension).toBe('api_call');- expect(input.UsageQuantity).toBe(1);- expect(input.CustomerIdentifier).toBe('cust-1');- // Idempotency allocation carries the dedupe key AWS bills against.- expect(input.UsageAllocations[0].Tags[0].Value).toBe('alloc-1');- vi.doUnmock('@aws-sdk/client-marketplace-metering');- vi.doUnmock('@aws-sdk/client-marketplace-entitlement-service');- vi.doUnmock('../api/_lib/env.js');+ expect(sent[0].commandName).toBe('BatchMeterUsage');+ const record = sent[0].input.UsageRecords[0];+ expect(sent[0].input.ProductCode).toBe('prod123');+ expect(record.LicenseArn).toBe('arn:aws:license-manager:us-east-1:155407237916:l-synthetic');+ expect(record.CustomerAWSAccountId).toBe('111122223333');+ expect(record.Dimension).toBe('api_call');+ expect(record.Quantity).toBe(1);+ expect(record.CustomerIdentifier).toBeUndefined();+ unmock();+ });++ it('surfaces a rejected usage record instead of reporting it as metered', async () => {+ const { meterUsage } = await loadMetering({+ Results: [{ Status: 'CustomerNotSubscribed' }],+ });+ await expect(+ meterUsage({+ licenseArn: 'arn:aws:license-manager:us-east-1:155407237916:l-synthetic',+ dimension: 'api_call',+ quantity: 1,+ }),+ ).rejects.toThrow(/CustomerNotSubscribed/);+ unmock();+ });++ it('falls back to the legacy MeterUsage command for a customer-identifier-only row', async () => {+ const { meterUsage, sent } = await loadMetering({ MeteringRecordId: 'rec-legacy' });+ const recordId = await meterUsage({+ customerIdentifier: 'cust-1',+ dimension: 'api_call',+ quantity: 1,+ });+ expect(recordId).toBe('rec-legacy');+ expect(sent[0].commandName).toBe('MeterUsage');+ expect(sent[0].input.CustomerIdentifier).toBe('cust-1');+ expect(sent[0].input.UsageDimension).toBe('api_call');+ unmock();+ });++ it('refuses to meter a buyer it cannot identify at all', async () => {+ const { meterUsage } = await loadMetering({});+ await expect(meterUsage({ dimension: 'api_call', quantity: 1 })).rejects.toThrow(/LicenseArn/);+ unmock();});});