Skip to content

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.

feat: auto-issue x402 API keys for AWS Marketplace subscribers

nirholas38d674138cc3
diff --git a/.env.example b/.env.example
index 825d8cde1..6355e5586 100644
--- a/.env.example
+++ b/.env.example
@@ -704,6 +704,14 @@ AWS_MP_PRODUCT_CODE=
# SNS message whose TopicArn does not match (defense-in-depth on top of
# AWS's signature verification).
AWS_MP_SNS_TOPIC_ARN=
+# Per-minute rate limit applied to every auto-issued x402 subscription a
+# linked AWS Marketplace customer receives. Default 600/min — bump per tier
+# if you split into multiple listings.
+AWS_MP_DEFAULT_RATE_LIMIT_PER_MINUTE=600
+# When set, every successful paid /api/x402/* call by an AWS Marketplace
+# subscription reports one unit on this MeterUsage dimension (Usage product).
+# Leave blank for Contract products (flat-fee subscription; entitlement-only).
+AWS_MP_METERING_DIMENSION=
# ── Debug toggles (leave unset in prod) ──────────────────────────────────────
# Set DEBUG=true to log knowledge-retrieval failures from widget chat.
diff --git a/api/_lib/aws-marketplace-bridge.js b/api/_lib/aws-marketplace-bridge.js
new file mode 100644
index 000000000..2b7696135
--- /dev/null
+++ b/api/_lib/aws-marketplace-bridge.js
@@ -0,0 +1,247 @@
+// AWS Marketplace ↔ x402 bridge.
+//
+// AWS Marketplace customers reach paid /api/x402/* endpoints by carrying a
+// regular x402 subscription key. This module is the seam:
+//
+// issueSubscriptionForCustomer() — mint x402_subscriptions row + link it
+// onto aws_marketplace_customers. Returns
+// the existing key when it's still active;
+// mints a replacement when the prior link
+// was revoked (e.g. customer cancelled then
+// re-subscribed). Plaintext is only returned
+// for fresh mints.
+// meterAwsSubscriptionUsage() — fire-and-forget MeterUsage(1) 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.
+//
+// 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' }
+//
+// Look-up by aws_customer_identifier uses the GIN-friendly meta->>'…' index
+// declared in migrations/20260528000000_aws_marketplace_x402_link.sql.
+
+import { sql } from './db.js';
+import { env } from './env.js';
+import { meterUsage } from './aws-marketplace.js';
+import {
+ createSubscription,
+ revokeSubscription,
+} from './x402/api-keys.js';
+
+const AWS_META_KEY = 'aws_customer_identifier';
+
+function rateLimitForCustomer(customer) {
+ // Per-offer rate-limit overrides via env. Pattern: AWS_MP_RATE_LIMIT_<OFFER_ID>.
+ // Falls back to the default. Useful when a single product code has multiple
+ // pricing dimensions but the listing isn't split across product codes.
+ if (customer.offer_id) {
+ const key = `AWS_MP_RATE_LIMIT_${customer.offer_id.replace(/[^a-zA-Z0-9_]/g, '_')}`;
+ const override = Number(process.env[key]);
+ if (Number.isFinite(override) && override > 0) return override;
+ }
+ return env.AWS_MP_DEFAULT_RATE_LIMIT_PER_MINUTE;
+}
+
+/**
+ * Issue (or re-use) the x402 subscription for an AWS Marketplace customer.
+ *
+ * - Existing key is still active → return it with `token: null, alreadyIssued: true`.
+ * - Existing key was revoked → mint a fresh subscription, relink, return plaintext.
+ * - No existing key at all → mint and return plaintext.
+ *
+ * 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)
+ * @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');
+ }
+
+ // Already linked to an ACTIVE x402 subscription? Return that.
+ // When the prior link is revoked (customer cancelled then re-subscribed),
+ // fall through and mint a fresh subscription so the new bypass key works.
+ const [existing] = await sql`
+ select
+ c.x402_subscription_id,
+ s.key_prefix,
+ s.rate_limit_per_minute,
+ s.revoked_at,
+ s.expires_at
+ from aws_marketplace_customers c
+ left join x402_subscriptions s on s.id = c.x402_subscription_id
+ where c.customer_identifier = ${customerId}
+ limit 1
+ `;
+ const stillActive =
+ existing?.x402_subscription_id &&
+ !existing.revoked_at &&
+ (!existing.expires_at || new Date(existing.expires_at).getTime() > Date.now());
+ if (stillActive) {
+ return {
+ subscriptionId: existing.x402_subscription_id,
+ keyPrefix: existing.key_prefix,
+ token: null,
+ alreadyIssued: true,
+ rateLimitPerMinute: existing.rate_limit_per_minute,
+ };
+ }
+
+ const rateLimit = rateLimitForCustomer(customer);
+ const subscription = await createSubscription({
+ name: `aws-marketplace:${customerId}`,
+ rateLimitPerMinute: rateLimit,
+ meta: {
+ source: 'aws-marketplace',
+ [AWS_META_KEY]: customerId,
+ aws_product_code: customer.product_code || env.AWS_MP_PRODUCT_CODE,
+ aws_offer_id: customer.offer_id || null,
+ is_free_trial: Boolean(customer.is_free_trial),
+ issued_for: 'aws-marketplace',
+ },
+ createdBy: customer.user_id || null,
+ });
+
+ await sql`
+ update aws_marketplace_customers
+ set x402_subscription_id = ${subscription.id},
+ updated_at = now()
+ where customer_identifier = ${customerId}
+ `;
+
+ return {
+ subscriptionId: subscription.id,
+ keyPrefix: subscription.key_prefix,
+ token: subscription.token,
+ alreadyIssued: false,
+ rateLimitPerMinute: subscription.rate_limit_per_minute,
+ };
+}
+
+/**
+ * Revoke the x402 subscription tied to an AWS customer. Idempotent.
+ *
+ * Clears `aws_marketplace_customers.x402_subscription_id` so a future
+ * re-subscribe can mint a fresh key. The revoked x402_subscriptions row is
+ * retained for audit (revoked_at is set, key_hash kept) — it can no longer
+ * authenticate any request.
+ *
+ * Returns the revoked subscription id, or null if no link existed.
+ */
+export async function revokeSubscriptionForCustomer(customerIdentifier) {
+ if (!customerIdentifier) return null;
+ const [row] = await sql`
+ select x402_subscription_id
+ from aws_marketplace_customers
+ where customer_identifier = ${customerIdentifier}
+ limit 1
+ `;
+ if (!row?.x402_subscription_id) return null;
+ await revokeSubscription(row.x402_subscription_id);
+ await sql`
+ update aws_marketplace_customers
+ set x402_subscription_id = null,
+ updated_at = now()
+ where customer_identifier = ${customerIdentifier}
+ `;
+ 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.
+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.
+ *
+ * No-op when:
+ * • AWS_MP_METERING_DIMENSION env is unset (Contract product, not Usage).
+ * • The subscription was not issued via AWS Marketplace.
+ * • The customer subscription is no longer active.
+ *
+ * @param {object} args
+ * @param {string} args.subscriptionId — id of the x402_subscriptions row
+ * @param {string} args.route — route path for audit (e.g. /api/x402/...)
+ */
+export function meterAwsSubscriptionUsage({ subscriptionId, route }) {
+ const dimension = env.AWS_MP_METERING_DIMENSION;
+ if (!dimension || !subscriptionId) return;
+
+ const bucket = Math.floor(Date.now() / 1000);
+ const dedupeKey = `${subscriptionId}:${bucket}`;
+ if (_inFlight.has(dedupeKey)) return;
+ _inFlight.add(dedupeKey);
+
+ queueMicrotask(async () => {
+ try {
+ const [row] = await sql`
+ select
+ c.customer_identifier,
+ c.subscription_status
+ from x402_subscriptions s
+ join aws_marketplace_customers c on c.x402_subscription_id = s.id
+ where s.id = ${subscriptionId}
+ and s.revoked_at is null
+ limit 1
+ `;
+ if (!row) return;
+ if (row.subscription_status === 'cancelled' || row.subscription_status === 'expired') {
+ return;
+ }
+
+ const allocationId = `${subscriptionId}-${bucket}`;
+ const recordId = await meterUsage({
+ 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)
+ values
+ (${row.customer_identifier}, ${dimension}, ${1}, ${recordId || null}, ${allocationId})
+ on conflict (metering_record_id) do nothing
+ `;
+ } catch (err) {
+ console.error('[aws-mp/bridge] meterAwsSubscriptionUsage failed', {
+ subscriptionId,
+ route,
+ error: err?.message,
+ });
+ } finally {
+ // Drop the dedupe entry after the bucket closes so the next second
+ // can meter again. Keep memory bounded under steady traffic.
+ setTimeout(() => _inFlight.delete(dedupeKey), 5000).unref?.();
+ }
+ });
+}
+
+/**
+ * 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 };
diff --git a/api/_lib/env.js b/api/_lib/env.js
index f6dc16cce..42219faab 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -337,6 +337,18 @@ export const env = {
get AWS_MP_SNS_TOPIC_ARN() {
return opt('AWS_MP_SNS_TOPIC_ARN');
},
+ // 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.
+ get AWS_MP_DEFAULT_RATE_LIMIT_PER_MINUTE() {
+ return Number(opt('AWS_MP_DEFAULT_RATE_LIMIT_PER_MINUTE', '600'));
+ },
+ // When set, every successful paid-endpoint call by an AWS Marketplace
+ // subscription fires MeterUsage on this dimension with quantity=1. Leave
+ // blank for Contract products (flat-rate entitlement; no usage metering).
+ get AWS_MP_METERING_DIMENSION() {
+ return opt('AWS_MP_METERING_DIMENSION');
+ },
// Optional operator EOA private key for scripts/erc8004-mint-bsc.mjs.
// Used to register marketplace agents on the BSC IdentityRegistry. Never
diff --git a/api/_lib/migrations/20260528000000_aws_marketplace_x402_link.sql b/api/_lib/migrations/20260528000000_aws_marketplace_x402_link.sql
new file mode 100644
index 000000000..41f640a4e
--- /dev/null
+++ b/api/_lib/migrations/20260528000000_aws_marketplace_x402_link.sql
@@ -0,0 +1,32 @@
+-- Migration: AWS Marketplace ↔ x402 subscription linkage.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260528000000_aws_marketplace_x402_link.sql
+-- Idempotent.
+--
+-- Bridges the AWS Marketplace SaaS listing to the existing x402 bypass
+-- infrastructure. When a customer activates their AWS subscription on
+-- /aws-marketplace/welcome, we mint a row in x402_subscriptions and store
+-- the id here. Their plaintext x402_live_* key is the only artifact the
+-- customer sees — it grants bypass on every paid /api/x402/* endpoint.
+--
+-- Lifecycle:
+-- • subscribe-success / register → issue x402 subscription, link here.
+-- • unsubscribe-success / expired → revoke x402 subscription (sets revoked_at).
+-- • entitlement-updated → no-op for usage products; for contract
+-- products the rate-limit tier may flip.
+
+alter table aws_marketplace_customers
+ add column if not exists x402_subscription_id text
+ references x402_subscriptions(id) on delete set null;
+
+create index if not exists aws_marketplace_customers_x402_sub_idx
+ on aws_marketplace_customers(x402_subscription_id)
+ where x402_subscription_id is not null;
+
+-- Reverse-lookup index for the access-control hook: given a subscription id
+-- (which is what x402 access logs and metering callbacks carry), find the
+-- AWS customer in O(1) so we can fire MeterUsage with the right CustomerIdentifier.
+-- meta->>'aws_customer_identifier' is also written for redundancy when the
+-- subscription is created outside this table.
+create index if not exists x402_subscriptions_aws_customer_idx
+ on x402_subscriptions ((meta->>'aws_customer_identifier'))
+ where meta ? 'aws_customer_identifier';
diff --git a/api/_lib/solana/sdk-bridge.js b/api/_lib/solana/sdk-bridge.js
index 94c5e7137..07e7c4150 100644
--- a/api/_lib/solana/sdk-bridge.js
+++ b/api/_lib/solana/sdk-bridge.js
@@ -8,9 +8,8 @@
import { PublicKey } from '@solana/web3.js';
let _sdkPromise = null;
-const _pumpSdkId = '@nirholas/pump-sdk';
async function loadSdk() {
- if (!_sdkPromise) _sdkPromise = import(_pumpSdkId);
+ if (!_sdkPromise) _sdkPromise = import('@nirholas/pump-sdk');
return _sdkPromise;
}
diff --git a/api/_lib/x402/access-control.js b/api/_lib/x402/access-control.js
index ee168bff4..63aa331b1 100644
--- a/api/_lib/x402/access-control.js
+++ b/api/_lib/x402/access-control.js
@@ -24,6 +24,7 @@ import {
lookupSubscription,
} from './api-keys.js';
import { clientIp } from '../rate-limit.js';
+import { meterAwsSubscriptionUsage } from '../aws-marketplace-bridge.js';
const API_KEY_HEADER = 'x-api-key';
@@ -153,6 +154,12 @@ export function installAccessControl({ requiredScope, resolveCaller } = {}) {
granted: true,
meta: { ...meta, remaining: rl.remaining, limit: rl.limit },
});
+ // AWS Marketplace customers carry source=aws-marketplace in meta;
+ // when configured for a Usage product, meter the call to AWS so
+ // they're billed for this entitled access.
+ if (sub.meta?.source === 'aws-marketplace') {
+ meterAwsSubscriptionUsage({ subscriptionId: sub.id, route });
+ }
return {
grantAccess: true,
reason: `subscription:${sub.id}`,
diff --git a/api/aws-marketplace/issue-key.js b/api/aws-marketplace/issue-key.js
new file mode 100644
index 000000000..1cf9dccbc
--- /dev/null
+++ b/api/aws-marketplace/issue-key.js
@@ -0,0 +1,91 @@
+// POST /api/aws-marketplace/issue-key
+//
+// Mints (or returns the existing) x402 subscription API key for the AWS
+// Marketplace customer linked to the signed-in user. The plaintext key is
+// returned ONCE on first issue — subsequent calls return alreadyIssued=true
+// without the plaintext (we never store it in clear).
+//
+// 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>" }
+// 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';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+
+ if (req.method !== 'POST') {
+ res.statusCode = 405;
+ res.setHeader('allow', 'POST');
+ res.end();
+ return;
+ }
+
+ let user;
+ try {
+ user = await getSessionUser(req);
+ } catch {
+ return json(res, 401, { error: 'unauthenticated' });
+ }
+ if (!user) return json(res, 401, { error: 'unauthenticated' });
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch {
+ return json(res, 400, { error: 'invalid_json' });
+ }
+
+ const { customer: customerId } = body;
+ if (!customerId || typeof customerId !== 'string') {
+ 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}
+ `;
+
+ if (!row) return json(res, 404, { error: 'customer_not_found' });
+ if (row.user_id && row.user_id !== user.id) {
+ return json(res, 403, { error: 'customer_linked_to_other_account' });
+ }
+ if (row.subscription_status === 'cancelled' || row.subscription_status === 'expired') {
+ return json(res, 409, { error: 'subscription_inactive', status: row.subscription_status });
+ }
+
+ 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,
+ });
+ } catch (err) {
+ console.error('[aws-marketplace/issue-key] failed', {
+ customerId,
+ error: err?.message,
+ });
+ return json(res, 502, { error: 'issue_failed' });
+ }
+
+ return json(res, 200, {
+ ok: true,
+ subscription: {
+ id: issued.subscriptionId,
+ keyPrefix: issued.keyPrefix,
+ token: issued.token,
+ rateLimitPerMinute: issued.rateLimitPerMinute,
+ alreadyIssued: issued.alreadyIssued,
+ },
+ });
+});
diff --git a/api/aws-marketplace/subscription.js b/api/aws-marketplace/subscription.js
index b12829568..2f4dd7bc8 100644
--- a/api/aws-marketplace/subscription.js
+++ b/api/aws-marketplace/subscription.js
@@ -17,6 +17,7 @@
import { json, wrap } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { verifySnsMessage } from '../_lib/aws-marketplace.js';
+import { revokeSubscriptionForCustomer } from '../_lib/aws-marketplace-bridge.js';
import { env } from '../_lib/env.js';
async function readRawBody(req) {
@@ -98,9 +99,23 @@ export default wrap(async (req, res) => {
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' });
+ }
await sql`
UPDATE aws_marketplace_customers
SET subscription_status = 'cancelled',
@@ -109,6 +124,14 @@ export default wrap(async (req, res) => {
WHERE customer_identifier = ${customerId}
`;
} else if (action === 'subscribe-fail') {
+ try {
+ await revokeSubscriptionForCustomer(customerId);
+ } catch (err) {
+ console.error('[aws-marketplace/subscription] revoke on fail failed', {
+ customerId,
+ error: err?.message,
+ });
+ }
await sql`
UPDATE aws_marketplace_customers
SET subscription_status = 'expired',
@@ -116,9 +139,16 @@ export default wrap(async (req, res) => {
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.
await sql`
UPDATE aws_marketplace_customers
- SET updated_at = now()
+ SET offer_id = COALESCE(${offerId ?? null}, offer_id),
+ updated_at = now()
WHERE customer_identifier = ${customerId}
`;
}
diff --git a/pages/aws-marketplace/welcome.html b/pages/aws-marketplace/welcome.html
index c6a62c747..d71a0451f 100644
--- a/pages/aws-marketplace/welcome.html
+++ b/pages/aws-marketplace/welcome.html
@@ -64,6 +64,23 @@
#state-linked .sub { margin-bottom: 28px; }
#state-linked .btn { max-width: 260px; margin: 0 auto; display: block; }
+ /* ── API key reveal ── */
+ .key-panel { text-align: left; background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 18px 20px; margin: 0 0 24px; }
+ .key-panel-label { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 10px; }
+ .key-panel-label span { font-size: 12px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; color: var(--muted); }
+ .key-panel-label .copy { background: transparent; border: 1px solid var(--border); border-radius: 8px; color: var(--text); font-size: 12px; padding: 5px 10px; cursor: pointer; transition: background 0.15s, border-color 0.15s; }
+ .key-panel-label .copy:hover { background: rgba(255,255,255,0.04); border-color: rgba(255,255,255,0.3); }
+ .key-panel-label .copy.copied { color: var(--green); border-color: rgba(34,197,94,0.5); }
+ .key-value { font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace; font-size: 13px; color: var(--text); background: #0a0a0a; border: 1px solid #1c1c1c; border-radius: 8px; padding: 11px 13px; word-break: break-all; user-select: all; }
+ .key-note { font-size: 12px; color: var(--yellow); margin-top: 10px; line-height: 1.5; }
+ .usage { text-align: left; background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 18px 20px; margin: 0 0 24px; }
+ .usage h3 { font-size: 13px; font-weight: 600; color: var(--muted); margin-bottom: 10px; letter-spacing: 0.04em; text-transform: uppercase; }
+ .usage pre { font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace; font-size: 12px; color: #cfcfdc; background: #0a0a0a; border: 1px solid #1c1c1c; border-radius: 8px; padding: 11px 13px; overflow-x: auto; line-height: 1.55; }
+ .usage a { color: var(--text); text-decoration: underline; }
+ .linked-actions { display: flex; gap: 10px; max-width: 420px; margin: 0 auto; }
+ .linked-actions .btn { margin: 0; flex: 1; }
+ .already-issued { background: rgba(245,158,11,0.08); border: 1px solid rgba(245,158,11,0.3); border-radius: 10px; padding: 11px 13px; font-size: 13px; color: #fbbf24; margin-bottom: 16px; text-align: left; line-height: 1.5; }
+
/* ── error state ── */
#state-error { text-align: center; }
#state-error .icon { font-size: 40px; margin-bottom: 16px; }
@@ -164,8 +181,31 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="#22c55e" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
</div>
<h1>Subscription activated.</h1>
- <p class="sub" id="linked-sub">Your AWS Marketplace subscription is now linked to your three.ws account. Usage will be metered and billed through AWS.</p>
- <a href="/dashboard" class="btn">Go to dashboard</a>
+ <p class="sub" id="linked-sub">Your AWS Marketplace subscription is linked to your three.ws account. Use the API key below to call any x402 endpoint — no on-chain payment required.</p>
+
+ <div id="already-issued-note" class="already-issued" style="display:none">
+ Your API key was issued during a previous activation. For security we don't store the plaintext — manage and rotate it from <a href="/api-keys" style="color:inherit;text-decoration:underline">API keys</a>.
+ </div>
+
+ <div id="key-panel" class="key-panel" style="display:none">
+ <div class="key-panel-label">
+ <span>Your API key</span>
+ <button type="button" class="copy" id="btn-copy-key">Copy</button>
+ </div>
+ <div class="key-value" id="key-value"></div>
+ <div class="key-note">Store this somewhere safe — it's shown once and grants every paid call on your AWS subscription. You can rotate it any time from <a href="/api-keys" style="color:inherit;text-decoration:underline">API keys</a>.</div>
+ </div>
+
+ <div class="usage">
+ <h3>Use it</h3>
+<pre>curl https://three.ws/api/x402/agent-reputation?agent_id=&lt;uuid&gt; \
+ -H "x-api-key: x402_live_…"</pre>
+ </div>
+
+ <div class="linked-actions">
+ <a href="/api-keys" class="btn btn-sec">Manage keys</a>
+ <a href="/dashboard" class="btn">Dashboard</a>
+ </div>
</div>
<!-- error -->
diff --git a/scripts/fix-pump-sdk-esm.mjs b/scripts/fix-pump-sdk-esm.mjs
index 5463d1009..dd183897c 100644
--- a/scripts/fix-pump-sdk-esm.mjs
+++ b/scripts/fix-pump-sdk-esm.mjs
@@ -1,28 +1,40 @@
-// Patches @pump-fun/pump-sdk and @pump-fun/pump-swap-sdk after install.
+// Patches pump-sdk packages after install so they can be loaded as ESM and
+// resolved by esbuild during Vercel API bundling.
//
-// Both packages ship `dist/esm/index.js` containing ES `import` statements,
-// but neither the package root nor the `dist/esm/` directory declares
-// `"type": "module"`. Node.js loads those files as CommonJS and throws
-// "Cannot use import statement outside a module" at first dynamic import.
+// 1. @pump-fun/pump-sdk / @pump-fun/pump-swap-sdk:
+// Both ship `dist/esm/index.js` containing ES `import` statements, but
+// neither the package root nor the `dist/esm/` directory declares
+// `"type": "module"`. Node loads those files as CommonJS and throws
+// "Cannot use import statement outside a module" on first dynamic import.
+// Fix: drop a `{"type":"module"}` package.json into each `dist/esm/` folder.
//
-// We drop a `{"type":"module"}` package.json into each `dist/esm/` folder so
-// Node treats the bundle as ESM. Idempotent; survives `npm ci` via postinstall.
+// 2. @nirholas/pump-sdk:
+// v1.30.0's package.json `module` and `exports.import` point at
+// `dist/esm/index.js`, but the actual file shipped is `dist/esm/index.mjs`.
+// esbuild respects `exports` strictly and fails with "Could not resolve",
+// which causes bundle-api.mjs to leave any batch containing pump-sdk
+// importers unbundled — those routes then fall through to Vercel's nft
+// tracer, which scans the full node_modules tree (~2 GB) and exceeds the
+// 45 minute build timeout. Fix: rewrite `module` / `exports.import` to
+// point at the real `.mjs` file.
+//
+// Idempotent; runs from `postinstall` so it survives `npm ci`.
-import { mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
+import { writeFileSync, existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = dirname(fileURLToPath(import.meta.url));
const repo = dirname(root);
-const targets = [
+const esmTypeTargets = [
'node_modules/@pump-fun/pump-sdk/dist/esm',
'node_modules/@pump-fun/pump-swap-sdk/dist/esm',
];
let patched = 0;
let skipped = 0;
-for (const rel of targets) {
+for (const rel of esmTypeTargets) {
const dir = join(repo, rel);
if (!existsSync(dir)) {
skipped++;
@@ -41,4 +53,31 @@ for (const rel of targets) {
patched++;
}
-console.log(`[fix-pump-sdk-esm] patched ${patched}, skipped ${skipped}`);
+// Rewrite @nirholas/pump-sdk's exports/module to point at the real .mjs file.
+const nirholasPkgPath = join(repo, 'node_modules/@nirholas/pump-sdk/package.json');
+let nirholasPatched = false;
+if (existsSync(nirholasPkgPath)) {
+ const pkg = JSON.parse(readFileSync(nirholasPkgPath, 'utf8'));
+ const esmActual = './dist/esm/index.mjs';
+ const esmActualAbs = join(repo, 'node_modules/@nirholas/pump-sdk', esmActual);
+ if (existsSync(esmActualAbs)) {
+ let changed = false;
+ if (pkg.module !== esmActual) {
+ pkg.module = esmActual;
+ changed = true;
+ }
+ if (pkg.exports && pkg.exports['.'] && pkg.exports['.'].import !== esmActual) {
+ pkg.exports['.'].import = esmActual;
+ changed = true;
+ }
+ if (changed) {
+ writeFileSync(nirholasPkgPath, JSON.stringify(pkg, null, 2) + '\n');
+ nirholasPatched = true;
+ }
+ }
+}
+
+console.log(
+ `[fix-pump-sdk-esm] patched ${patched}, skipped ${skipped}` +
+ (nirholasPatched ? ', rewrote @nirholas/pump-sdk exports' : ''),
+);
diff --git a/src/aws-marketplace-welcome.js b/src/aws-marketplace-welcome.js
index 8f5461c7a..34ea4a1dc 100644
--- a/src/aws-marketplace-welcome.js
+++ b/src/aws-marketplace-welcome.js
@@ -49,26 +49,92 @@ async function linkSubscription() {
if (!resp.ok) throw new Error('link_failed');
}
-function showSuccess() {
+async function issueApiKey() {
+ const resp = await fetch('/api/aws-marketplace/issue-key', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ customer: customerId }),
+ });
+ if (!resp.ok) return null;
+ const data = await resp.json().catch(() => ({}));
+ return data.subscription || null;
+}
+
+async function linkAndIssue() {
+ await linkSubscription();
+ // Surface the API key alongside success. Failures here are recoverable —
+ // the user can rotate from /api-keys — but log so we notice patterns.
+ try {
+ return await issueApiKey();
+ } catch (err) {
+ console.error('[aws-marketplace/welcome] issueApiKey failed', err);
+ return null;
+ }
+}
+
+function renderApiKey(subscription) {
+ const note = document.getElementById('already-issued-note');
+ // issueApiKey returned null (network/parse error after a successful link):
+ // the customer is fully activated but we couldn't surface the plaintext.
+ // Direct them to the dashboard where they can mint or rotate a key.
+ if (!subscription) {
+ note.style.display = '';
+ return;
+ }
+ const panel = document.getElementById('key-panel');
+
+ if (subscription.token) {
+ document.getElementById('key-value').textContent = subscription.token;
+ panel.style.display = '';
+ const btn = document.getElementById('btn-copy-key');
+ btn.addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(subscription.token);
+ btn.textContent = 'Copied';
+ btn.classList.add('copied');
+ setTimeout(() => {
+ btn.textContent = 'Copy';
+ btn.classList.remove('copied');
+ }, 1800);
+ } catch {
+ // Clipboard API may be blocked — fall back to text selection.
+ const range = document.createRange();
+ range.selectNodeContents(document.getElementById('key-value'));
+ const sel = window.getSelection();
+ sel.removeAllRanges();
+ sel.addRange(range);
+ }
+ });
+ } else if (subscription.alreadyIssued) {
+ note.style.display = '';
+ }
+}
+
+function showSuccess(subscription) {
const sub = document.getElementById('linked-sub');
if (isTrial) {
- sub.textContent = 'Your free trial is now active. Usage is metered and billed through AWS once the trial period ends.';
+ sub.textContent = 'Your free trial is active. Use the API key below to call any x402 endpoint. Billing through AWS begins automatically when the trial ends.';
}
+ renderApiKey(subscription);
show('state-linked');
}
async function init() {
- if (!customerId) {
- showErrorPage('default');
- return;
- }
-
+ // register.js redirects to /aws-marketplace/error?reason=... with NO
+ // customer param on token-exchange failures, so the reason check must
+ // come before the missing-customer check.
const reason = p.get('reason');
if (reason) {
showErrorPage(reason);
return;
}
+ if (!customerId) {
+ showErrorPage('default');
+ return;
+ }
+
// Check if already signed in.
let me = null;
try {
@@ -92,8 +158,8 @@ async function init() {
btn.textContent = 'Linking…';
clearErr('err-link');
try {
- await linkSubscription();
- showSuccess();
+ const sub = await linkAndIssue();
+ showSuccess(sub);
} catch {
btn.disabled = false;
btn.textContent = 'Confirm & activate';
@@ -149,8 +215,8 @@ async function handleSignup(e) {
});
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || data.message || 'Registration failed');
- await linkSubscription();
- showSuccess();
+ const sub = await linkAndIssue();
+ showSuccess(sub);
} catch (err) {
btn.disabled = false;
btn.textContent = 'Create account & activate';
@@ -177,8 +243,8 @@ async function handleSignin(e) {
});
const data = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(data.error || data.message || 'Sign in failed');
- await linkSubscription();
- showSuccess();
+ const sub = await linkAndIssue();
+ showSuccess(sub);
} catch (err) {
btn.disabled = false;
btn.textContent = 'Sign in & activate';