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: wire three.ws to AWS MyApplications + Marketplace SaaS integration

nirholas3fcdfe996c02
diff --git a/api/_lib/aws-marketplace.js b/api/_lib/aws-marketplace.js
new file mode 100644
index 000000000..bbef8d651
--- /dev/null
+++ b/api/_lib/aws-marketplace.js
@@ -0,0 +1,153 @@
+// 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
+
+import {
+ MarketplaceMeteringClient,
+ ResolveCustomerCommand,
+ MeterUsageCommand,
+} from '@aws-sdk/client-marketplace-metering';
+import {
+ MarketplaceEntitlementServiceClient,
+ GetEntitlementsCommand,
+} from '@aws-sdk/client-marketplace-entitlement-service';
+import { createVerify, createPublicKey } from 'node:crypto';
+import { env } from './env.js';
+
+function credentials() {
+ return {
+ accessKeyId: env.AWS_MP_ACCESS_KEY_ID,
+ secretAccessKey: env.AWS_MP_SECRET_ACCESS_KEY,
+ };
+}
+
+function meteringClient() {
+ return new MarketplaceMeteringClient({
+ region: env.AWS_MP_REGION,
+ credentials: credentials(),
+ });
+}
+
+function entitlementClient() {
+ return new MarketplaceEntitlementServiceClient({
+ region: env.AWS_MP_REGION,
+ credentials: credentials(),
+ });
+}
+
+/**
+ * Exchange the registration token (from the POST body of the registration URL)
+ * for a stable CustomerIdentifier and ProductCode.
+ *
+ * Returns { customerIdentifier, productCode, customerAWSAccountId }.
+ * Throws on invalid/expired token.
+ */
+export async function resolveCustomer(registrationToken) {
+ const client = meteringClient();
+ const result = await client.send(
+ new ResolveCustomerCommand({ RegistrationToken: registrationToken }),
+ );
+ return {
+ customerIdentifier: result.CustomerIdentifier,
+ productCode: result.ProductCode,
+ customerAWSAccountId: result.CustomerAWSAccountId,
+ };
+}
+
+/**
+ * Report metered usage to AWS Marketplace for billing.
+ *
+ * @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)
+ */
+export async function meterUsage({ customerIdentifier, dimension, quantity, timestamp, usageAllocationId }) {
+ const client = meteringClient();
+ const result = await client.send(
+ new MeterUsageCommand({
+ ProductCode: env.AWS_MP_PRODUCT_CODE,
+ UsageDimension: dimension,
+ UsageQuantity: quantity,
+ Timestamp: timestamp ?? new Date(),
+ CustomerIdentifier: customerIdentifier,
+ ...(usageAllocationId ? { UsageAllocations: [{ AllocatedUsageQuantity: quantity, Tags: [{ Key: 'allocationId', Value: usageAllocationId }] }] } : {}),
+ }),
+ );
+ return result.MeteringRecordId;
+}
+
+/**
+ * Check entitlements for a customer (used for contract-based products).
+ * Returns the list of active entitlement objects.
+ */
+export async function getEntitlements(customerIdentifier) {
+ const client = entitlementClient();
+ const result = await client.send(
+ new GetEntitlementsCommand({
+ ProductCode: env.AWS_MP_PRODUCT_CODE,
+ Filter: { CUSTOMER_IDENTIFIER: [customerIdentifier] },
+ }),
+ );
+ return result.Entitlements ?? [];
+}
+
+// ── SNS signature verification ────────────────────────────────────────────────
+// AWS signs every SNS message with a private key and includes the cert URL.
+// We download the cert once (cached per URL), build the canonical string, and
+// verify the signature so we know the notification genuinely came from AWS.
+
+const certCache = new Map();
+
+async function fetchCert(url) {
+ if (certCache.has(url)) return certCache.get(url);
+
+ // Only trust certs hosted on *.amazonaws.com over HTTPS.
+ const parsed = new URL(url);
+ if (parsed.protocol !== 'https:' || !parsed.hostname.endsWith('.amazonaws.com')) {
+ throw new Error(`Untrusted SNS signing cert URL: ${url}`);
+ }
+
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`Failed to fetch SNS cert: ${res.status}`);
+ const pem = await res.text();
+ certCache.set(url, pem);
+ return pem;
+}
+
+// Fields included in the signature string differ by message type.
+const NOTIFICATION_FIELDS = ['Message', 'MessageId', 'Subject', 'Timestamp', 'TopicArn', 'Type'];
+const SUBSCRIPTION_FIELDS = ['Message', 'MessageId', 'SubscribeURL', 'Timestamp', 'Token', 'TopicArn', 'Type'];
+
+function buildSignatureString(msg) {
+ const fields =
+ msg.Type === 'Notification' ? NOTIFICATION_FIELDS : SUBSCRIPTION_FIELDS;
+ return fields
+ .filter((k) => msg[k] !== undefined)
+ .map((k) => `${k}\n${msg[k]}\n`)
+ .join('');
+}
+
+/**
+ * Verify that a parsed SNS message object was genuinely signed by AWS.
+ * Throws if verification fails; returns void on success.
+ */
+export async function verifySnsMessage(msg) {
+ const expectedTopicArn = env.AWS_MP_SNS_TOPIC_ARN;
+ if (expectedTopicArn && msg.TopicArn !== expectedTopicArn) {
+ throw new Error(`SNS TopicArn mismatch: got ${msg.TopicArn}`);
+ }
+
+ const pem = await fetchCert(msg.SigningCertURL);
+ const pubKey = createPublicKey(pem);
+ const verifier = createVerify('SHA1');
+ verifier.update(buildSignatureString(msg));
+ const valid = verifier.verify(pubKey, msg.Signature, 'base64');
+ if (!valid) throw new Error('SNS signature verification failed');
+}
diff --git a/api/_lib/env.js b/api/_lib/env.js
index e7e052da3..47fd7b8ba 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -296,6 +296,29 @@ export const env = {
get X402_PAY_TO_BSC() {
return opt('X402_PAY_TO_BSC', '0x00000000381f09742a30a5a49975514AeC1B72Cc');
},
+ // ── AWS Marketplace ──────────────────────────────────────────────────────
+ // IAM credentials with marketplaceMetering:ResolveCustomer,
+ // marketplaceMetering:MeterUsage, and aws-marketplace:GetEntitlements.
+ // Keep separate from S3_* credentials so each key has minimal permissions.
+ get AWS_MP_ACCESS_KEY_ID() {
+ return req('AWS_MP_ACCESS_KEY_ID');
+ },
+ get AWS_MP_SECRET_ACCESS_KEY() {
+ return req('AWS_MP_SECRET_ACCESS_KEY');
+ },
+ get AWS_MP_REGION() {
+ return opt('AWS_MP_REGION', 'us-east-1');
+ },
+ // Product code from the AWS Marketplace listing (shown in Seller portal).
+ get AWS_MP_PRODUCT_CODE() {
+ return req('AWS_MP_PRODUCT_CODE');
+ },
+ // SNS topic ARN that AWS sends subscription notifications to. Used to
+ // reject SNS messages that did not originate from the Marketplace topic.
+ get AWS_MP_SNS_TOPIC_ARN() {
+ return opt('AWS_MP_SNS_TOPIC_ARN');
+ },
+
// Optional operator EOA private key for scripts/erc8004-mint-bsc.mjs.
// Used to register marketplace agents on the BSC IdentityRegistry. Never
// referenced by request handlers — keep it out of the serverless surface.
diff --git a/api/aws-marketplace/register.js b/api/aws-marketplace/register.js
new file mode 100644
index 000000000..731cfed6d
--- /dev/null
+++ b/api/aws-marketplace/register.js
@@ -0,0 +1,107 @@
+// POST /api/aws-marketplace/register
+//
+// 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
+// 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.
+
+import { readForm, wrap } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { resolveCustomer } from '../_lib/aws-marketplace.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { env } from '../_lib/env.js';
+
+export default wrap(async (req, res) => {
+ if (req.method !== 'POST') {
+ res.statusCode = 405;
+ res.setHeader('allow', 'POST');
+ res.end();
+ return;
+ }
+
+ let token, offerType;
+ try {
+ const body = await readForm(req);
+ token = body['x-amzn-marketplace-token'];
+ offerType = body['x-amzn-marketplace-offer-type'] ?? '';
+ } catch {
+ res.statusCode = 400;
+ res.end('bad request');
+ return;
+ }
+
+ if (!token) {
+ res.statusCode = 400;
+ res.end('missing x-amzn-marketplace-token');
+ return;
+ }
+
+ const isFreeTrial = offerType === 'free-trial';
+
+ let customer;
+ try {
+ customer = 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();
+ return;
+ }
+
+ const { customerIdentifier, productCode, customerAWSAccountId } = customer;
+
+ // 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()
+ `;
+
+ // 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
+ `;
+ }
+
+ // Redirect to the frontend onboarding page.
+ const params = new URLSearchParams({
+ customer: customerIdentifier,
+ 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();
+});
diff --git a/api/aws-marketplace/subscription.js b/api/aws-marketplace/subscription.js
new file mode 100644
index 000000000..b12829568
--- /dev/null
+++ b/api/aws-marketplace/subscription.js
@@ -0,0 +1,127 @@
+// POST /api/aws-marketplace/subscription
+//
+// Amazon SNS webhook called by AWS Marketplace when a customer subscribes,
+// unsubscribes, or when entitlements change.
+//
+// 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.
+//
+// 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
+
+import { json, wrap } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { verifySnsMessage } from '../_lib/aws-marketplace.js';
+import { env } from '../_lib/env.js';
+
+async function readRawBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ req.on('data', (c) => chunks.push(c));
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
+ req.on('error', reject);
+ });
+}
+
+export default wrap(async (req, res) => {
+ // AWS SNS sends POST for all message types.
+ if (req.method !== 'POST') {
+ res.statusCode = 405;
+ res.end();
+ return;
+ }
+
+ 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) {
+ console.error('[aws-marketplace/subscription] SNS verification failed', err?.message);
+ res.statusCode = 403;
+ res.end();
+ return;
+ }
+
+ if (msg.Type === 'SubscriptionConfirmation' || msg.Type === 'UnsubscribeConfirmation') {
+ // Confirm the SNS subscription by hitting the provided URL.
+ try {
+ await fetch(msg.SubscribeURL);
+ } catch (err) {
+ console.error('[aws-marketplace/subscription] failed to confirm SNS subscription', err?.message);
+ }
+ return json(res, 200, { ok: true });
+ }
+
+ if (msg.Type !== 'Notification') {
+ return json(res, 200, { ok: true });
+ }
+
+ let payload;
+ try {
+ payload = JSON.parse(msg.Message);
+ } catch {
+ console.error('[aws-marketplace/subscription] malformed Notification message');
+ return json(res, 400, { error: 'malformed_message' });
+ }
+
+ const { action, 'customer-identifier': customerId, 'product-code': productCode, 'offer-identifier': offerId, isFreeTrialTermPresent } = payload;
+ const isFreeTrial = isFreeTrialTermPresent === 'true' || isFreeTrialTermPresent === true;
+
+ 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()),
+ updated_at = now()
+ `;
+ } else if (action === 'unsubscribe-success') {
+ 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') {
+ await sql`
+ UPDATE aws_marketplace_customers
+ SET subscription_status = 'expired',
+ updated_at = now()
+ WHERE customer_identifier = ${customerId}
+ `;
+ } else if (action === 'entitlement-updated') {
+ await sql`
+ UPDATE aws_marketplace_customers
+ SET updated_at = now()
+ WHERE customer_identifier = ${customerId}
+ `;
+ }
+
+ return json(res, 200, { ok: true });
+});
diff --git a/infra/README.md b/infra/README.md
new file mode 100644
index 000000000..34f685eca
--- /dev/null
+++ b/infra/README.md
@@ -0,0 +1,46 @@
+# three.ws AWS Infrastructure
+
+CDK stack for the three.ws AWS resources. Deploys to account `155407237916`, region `us-east-1`.
+
+All resources are tagged with the `awsApplication` key pointing to the three.ws MyApplications ARN, so they surface in the [AWS console dashboard](https://us-east-1.console.aws.amazon.com/systems-manager/appmanager/application/AWS_AppRegistry_Application-three.ws).
+
+## Resources
+
+| Resource | ID | Purpose |
+|---|---|---|
+| S3 Bucket | `3d-agent-avatars` | 3D avatar uploads (used by `api/_lib/r2.js`) |
+| CloudWatch Log Group | `/three-ws/api` | API observability |
+| AppRegistry Association | — | Links this stack to the MyApplications entry |
+
+## First-time setup
+
+```bash
+cd infra
+npm install
+npx cdk bootstrap aws://155407237916/us-east-1 # once per account/region
+```
+
+## Deploy
+
+```bash
+cd infra
+npm run deploy
+```
+
+## If the S3 bucket already exists
+
+If `3d-agent-avatars` was created outside CDK, import it instead of re-creating:
+
+```bash
+cd infra
+npx cdk import ThreeWsStack
+```
+
+CDK will prompt you to confirm the bucket name, then take it under management.
+
+## Diff
+
+```bash
+cd infra
+npm run diff
+```
diff --git a/infra/bin/app.ts b/infra/bin/app.ts
new file mode 100644
index 000000000..1894c5597
--- /dev/null
+++ b/infra/bin/app.ts
@@ -0,0 +1,20 @@
+#!/usr/bin/env node
+import * as cdk from 'aws-cdk-lib';
+import { ThreeWsStack } from '../lib/three-ws-stack';
+
+const app = new cdk.App();
+
+const stack = new ThreeWsStack(app, 'ThreeWsStack', {
+ env: {
+ account: '155407237916',
+ region: 'us-east-1',
+ },
+ description: 'three.ws — platform for 3D AI agents on-chain',
+});
+
+// Tag every resource in this stack with the MyApplications application tag.
+// This makes them visible in the three.ws AWS application dashboard.
+cdk.Tags.of(stack).add(
+ 'awsApplication',
+ 'arn:aws:resource-groups:us-east-1:155407237916:group/three.ws/03adso8olrmj6rbu0wvadul7ih',
+);
diff --git a/infra/cdk.json b/infra/cdk.json
new file mode 100644
index 000000000..88b6dbd59
--- /dev/null
+++ b/infra/cdk.json
@@ -0,0 +1,14 @@
+{
+ "app": "npx ts-node bin/app.ts",
+ "watch": {
+ "include": ["**"],
+ "exclude": ["README.md", "cdk*.json", "**/*.d.ts", "**/*.js", "tsconfig.json", "node_modules"]
+ },
+ "context": {
+ "@aws-cdk/aws-lambda:recognizeLayerVersion": true,
+ "@aws-cdk/aws-cloudformation:createRoleWithManagedPolicies": true,
+ "@aws-cdk/aws-iam:minimizePolicies": true,
+ "@aws-cdk/core:validateSnapshotRemovalPolicy": true,
+ "@aws-cdk/aws-s3:keepNotificationInImportedBucket": false
+ }
+}
diff --git a/infra/lib/three-ws-stack.ts b/infra/lib/three-ws-stack.ts
new file mode 100644
index 000000000..ad63f8f06
--- /dev/null
+++ b/infra/lib/three-ws-stack.ts
@@ -0,0 +1,61 @@
+import * as cdk from 'aws-cdk-lib';
+import * as s3 from 'aws-cdk-lib/aws-s3';
+import * as logs from 'aws-cdk-lib/aws-logs';
+import { Construct } from 'constructs';
+
+export class ThreeWsStack extends cdk.Stack {
+ constructor(scope: Construct, id: string, props?: cdk.StackProps) {
+ super(scope, id, props);
+
+ // Avatar asset bucket — used by api/_lib/r2.js for 3D avatar uploads
+ const avatarBucket = new s3.Bucket(this, 'AvatarBucket', {
+ bucketName: '3d-agent-avatars',
+ versioned: false,
+ encryption: s3.BucketEncryption.S3_MANAGED,
+ blockPublicAccess: new s3.BlockPublicAccess({
+ blockPublicAcls: true,
+ blockPublicPolicy: true,
+ ignorePublicAcls: true,
+ restrictPublicBuckets: false, // CDN serves public reads via CloudFront/R2 domain
+ }),
+ cors: [
+ {
+ allowedMethods: [s3.HttpMethods.GET, s3.HttpMethods.PUT, s3.HttpMethods.HEAD],
+ allowedOrigins: ['https://three.ws', 'https://*.three.ws', 'http://localhost:3000'],
+ allowedHeaders: ['*'],
+ exposedHeaders: ['ETag'],
+ maxAge: 3000,
+ },
+ ],
+ lifecycleRules: [
+ {
+ id: 'expire-tmp',
+ prefix: 'tmp/',
+ expiration: cdk.Duration.days(1),
+ },
+ ],
+ removalPolicy: cdk.RemovalPolicy.RETAIN,
+ });
+
+ // CloudWatch log group for API-level observability (Vercel forwards structured logs here)
+ new logs.LogGroup(this, 'ApiLogGroup', {
+ logGroupName: '/three-ws/api',
+ retention: logs.RetentionDays.ONE_MONTH,
+ removalPolicy: cdk.RemovalPolicy.RETAIN,
+ });
+
+ // Associate this CloudFormation stack with the three.ws MyApplications entry.
+ // This surfaces all stack resources in the AWS MyApplications dashboard.
+ new cdk.CfnResource(this, 'AppRegistryAssociation', {
+ type: 'AWS::ServiceCatalogAppRegistry::ResourceAssociation',
+ properties: {
+ Application: 'arn:aws:servicecatalog:us-east-1:155407237916:/applications/03adso8olrmj6rbu0wvadul7ih',
+ Resource: cdk.Aws.STACK_ID,
+ ResourceType: 'CFN_STACK',
+ },
+ });
+
+ new cdk.CfnOutput(this, 'AvatarBucketName', { value: avatarBucket.bucketName });
+ new cdk.CfnOutput(this, 'AvatarBucketArn', { value: avatarBucket.bucketArn });
+ }
+}
diff --git a/infra/package.json b/infra/package.json
new file mode 100644
index 000000000..8bd59875c
--- /dev/null
+++ b/infra/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "three-ws-infra",
+ "version": "1.0.0",
+ "private": true,
+ "scripts": {
+ "build": "tsc",
+ "synth": "cdk synth",
+ "diff": "cdk diff",
+ "deploy": "cdk deploy",
+ "destroy": "cdk destroy"
+ },
+ "dependencies": {
+ "aws-cdk-lib": "^2.180.0",
+ "constructs": "^10.4.2"
+ },
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "aws-cdk": "^2.180.0",
+ "ts-node": "^10.9.2",
+ "typescript": "^5.7.0"
+ }
+}
diff --git a/infra/tsconfig.json b/infra/tsconfig.json
new file mode 100644
index 000000000..69d7b918f
--- /dev/null
+++ b/infra/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "commonjs",
+ "lib": ["es2020"],
+ "strict": true,
+ "esModuleInterop": true,
+ "experimentalDecorators": true,
+ "emitDecoratorMetadata": true,
+ "resolveJsonModule": true,
+ "skipLibCheck": true,
+ "outDir": "dist"
+ },
+ "include": ["bin/**/*.ts", "lib/**/*.ts"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/migrations/20260526000000_aws_marketplace_customers.sql b/migrations/20260526000000_aws_marketplace_customers.sql
new file mode 100644
index 000000000..b4713df46
--- /dev/null
+++ b/migrations/20260526000000_aws_marketplace_customers.sql
@@ -0,0 +1,45 @@
+-- AWS Marketplace customer subscriptions.
+-- customer_identifier is the stable ID returned by ResolveCustomer.
+-- user_id is set once the customer completes registration on three.ws.
+
+CREATE TABLE aws_marketplace_customers (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ customer_identifier TEXT NOT NULL UNIQUE,
+ product_code TEXT NOT NULL,
+ customer_aws_account_id TEXT,
+ user_id UUID REFERENCES users(id) ON DELETE SET NULL,
+
+ -- Lifecycle
+ subscription_status TEXT NOT NULL DEFAULT 'pending'
+ CHECK (subscription_status IN ('pending', 'active', 'trial', 'cancelled', 'expired')),
+ is_free_trial BOOLEAN NOT NULL DEFAULT false,
+ offer_id TEXT,
+
+ subscribed_at TIMESTAMPTZ,
+ trial_ends_at TIMESTAMPTZ,
+ cancelled_at TIMESTAMPTZ,
+
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX aws_marketplace_customers_user_id_idx
+ ON aws_marketplace_customers (user_id)
+ WHERE user_id IS NOT NULL;
+
+CREATE INDEX aws_marketplace_customers_status_idx
+ ON aws_marketplace_customers (subscription_status);
+
+-- Metering records — each successful MeterUsage call is stored for audit.
+CREATE TABLE aws_marketplace_metering (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ customer_identifier TEXT NOT NULL REFERENCES aws_marketplace_customers(customer_identifier) ON DELETE CASCADE,
+ dimension TEXT NOT NULL,
+ quantity INTEGER NOT NULL CHECK (quantity > 0),
+ metering_record_id TEXT UNIQUE, -- AWS-returned record ID
+ usage_allocation_id TEXT,
+ reported_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX aws_marketplace_metering_customer_idx
+ ON aws_marketplace_metering (customer_identifier);
diff --git a/package-lock.json b/package-lock.json
index 1d4742e22..e80abf42b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -50,7 +50,7 @@
"@octokit/rest": "^22.0.1",
"@pixiv/three-vrm": "^3.5.3",
"@pump-fun/agent-payments-sdk": "^3.1.0",
- "@pump-fun/pump-sdk": "^1.1.0",
+ "@pump-fun/pump-sdk": "^1.36.0",
"@pump-fun/pump-swap-sdk": "^1.0.0",
"@pythnetwork/hermes-client": "^3.1.0",
"@recast-navigation/core": "^0.43.1",
@@ -149,7 +149,7 @@
"@coral-xyz/anchor": "^0.31.1",
"@ethereum-attestation-service/eas-sdk": "0.29.1",
"@metaplex-foundation/js": "^0.20.1",
- "@pump-fun/pump-sdk": "^1.1.0",
+ "@pump-fun/pump-sdk": "^1.36.0",
"@pump-fun/pump-swap-sdk": "1.0.0",
"@solana/spl-token": "^0.4.9",
"@solana/web3.js": "^1.98.0",
@@ -378,6 +378,15 @@
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
},
+ "character-studio/node_modules/@pump-fun/pump-sdk": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@pump-fun/pump-sdk/-/pump-sdk-1.1.0.tgz",
+ "integrity": "sha512-4YWLdJujp5Ec+2KBqpgOEdpjXKO1HFovJq4M3yJO1FL5uU+mFqURej4A4b2Nkqw67eEJT2cqpuMx2z6GvGGg0g==",
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "^6.20.0"
+ }
+ },
"character-studio/node_modules/@vitest/expect": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz",
@@ -952,6 +961,12 @@
"node": ">=18"
}
},
+ "character-studio/node_modules/undici-types": {
+ "version": "6.26.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.26.0.tgz",
+ "integrity": "sha512-anbjel3h0aEs7QuwKb3qbvApZmBE4lD0xonwP/6fOHvOj/1D3wmBWula2MOjOV2RRPOLnE9istBSlA+mqVhzMA==",
+ "license": "MIT"
+ },
"character-studio/node_modules/vitest": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz",
@@ -1213,6 +1228,21 @@
"node": ">=20"
}
},
+ "multiplayer/node_modules/@pump-fun/pump-sdk": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@pump-fun/pump-sdk/-/pump-sdk-1.1.0.tgz",
+ "integrity": "sha512-4YWLdJujp5Ec+2KBqpgOEdpjXKO1HFovJq4M3yJO1FL5uU+mFqURej4A4b2Nkqw67eEJT2cqpuMx2z6GvGGg0g==",
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "^6.20.0"
+ }
+ },
+ "multiplayer/node_modules/undici-types": {
+ "version": "6.26.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.26.0.tgz",
+ "integrity": "sha512-anbjel3h0aEs7QuwKb3qbvApZmBE4lD0xonwP/6fOHvOj/1D3wmBWula2MOjOV2RRPOLnE9istBSlA+mqVhzMA==",
+ "license": "MIT"
+ },
"node_modules/@0no-co/graphql.web": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@0no-co/graphql.web/-/graphql.web-1.2.0.tgz",
@@ -15512,14 +15542,104 @@
"link": true
},
"node_modules/@pump-fun/pump-sdk": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@pump-fun/pump-sdk/-/pump-sdk-1.1.0.tgz",
- "integrity": "sha512-4YWLdJujp5Ec+2KBqpgOEdpjXKO1HFovJq4M3yJO1FL5uU+mFqURej4A4b2Nkqw67eEJT2cqpuMx2z6GvGGg0g==",
+ "version": "1.36.0",
+ "resolved": "https://registry.npmjs.org/@pump-fun/pump-sdk/-/pump-sdk-1.36.0.tgz",
+ "integrity": "sha512-X8rf+Wm/p/jhBj6zbwouM9blJ3UW8XJFSL7YTT8osBnpHsOH0ccT0DjCkIi6AAT7b6jf1nM3MXk7l78Fuf1M0g==",
"license": "MIT",
"dependencies": {
+ "@coral-xyz/anchor": "^0.31.1",
+ "@pump-fun/agent-payments-sdk": "1.0.7",
+ "@pump-fun/pump-swap-sdk": "^1.13.0",
+ "@solana/spl-token": "^0.4.13",
+ "@solana/web3.js": "^1.98.2",
+ "bn.js": "^5.2.2",
"undici-types": "^6.20.0"
}
},
+ "node_modules/@pump-fun/pump-sdk/node_modules/@coral-xyz/anchor": {
+ "version": "0.31.1",
+ "resolved": "https://registry.npmjs.org/@coral-xyz/anchor/-/anchor-0.31.1.tgz",
+ "integrity": "sha512-QUqpoEK+gi2S6nlYc2atgT2r41TT3caWr/cPUEL8n8Md9437trZ68STknq897b82p5mW0XrTBNOzRbmIRJtfsA==",
+ "license": "(MIT OR Apache-2.0)",
+ "dependencies": {
+ "@coral-xyz/anchor-errors": "^0.31.1",
+ "@coral-xyz/borsh": "^0.31.1",
+ "@noble/hashes": "^1.3.1",
+ "@solana/web3.js": "^1.69.0",
+ "bn.js": "^5.1.2",
+ "bs58": "^4.0.1",
+ "buffer-layout": "^1.2.2",
+ "camelcase": "^6.3.0",
+ "cross-fetch": "^3.1.5",
+ "eventemitter3": "^4.0.7",
+ "pako": "^2.0.3",
+ "superstruct": "^0.15.4",
+ "toml": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=17"
+ }
+ },
+ "node_modules/@pump-fun/pump-sdk/node_modules/@coral-xyz/anchor/node_modules/bs58": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/bs58/-/bs58-4.0.1.tgz",
+ "integrity": "sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw==",
+ "license": "MIT",
+ "dependencies": {
+ "base-x": "^3.0.2"
+ }
+ },
+ "node_modules/@pump-fun/pump-sdk/node_modules/@pump-fun/agent-payments-sdk": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/@pump-fun/agent-payments-sdk/-/agent-payments-sdk-1.0.7.tgz",
+ "integrity": "sha512-RnYh3GDMTaLvrmu9Hz4W11ulRNQYhrQoOOJyhpMa/wMRuY7ibhoQczcA17R3Zy3fKyhveiLmYI+GKF4pnp2nVg==",
+ "license": "ISC",
+ "dependencies": {
+ "@coral-xyz/anchor": "^0.31.1",
+ "@solana/spl-token": "^0.4.9",
+ "@solana/web3.js": "^1.98.0"
+ },
+ "optionalDependencies": {
+ "@rollup/rollup-linux-x64-gnu": "*"
+ }
+ },
+ "node_modules/@pump-fun/pump-sdk/node_modules/@pump-fun/pump-swap-sdk": {
+ "version": "1.16.0",
+ "resolved": "https://registry.npmjs.org/@pump-fun/pump-swap-sdk/-/pump-swap-sdk-1.16.0.tgz",
+ "integrity": "sha512-UFj4+c3/TZtZ2eNtzJ2Q9SoBr854nSWNdWexpL8Vt04/RnCZisAAtD4gzQXtvyTjefsrcwZOXZ+9g14QAYJ/HA==",
+ "license": "MIT",
+ "dependencies": {
+ "@coral-xyz/anchor": "^0.31.1",
+ "@solana/spl-token": "^0.4.9",
+ "@solana/web3.js": "^1.98.2",
+ "bn.js": "^5.2.2",
+ "bs58": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@pump-fun/pump-sdk/node_modules/base-x": {
+ "version": "3.0.11",
+ "resolved": "https://registry.npmjs.org/base-x/-/base-x-3.0.11.tgz",
+ "integrity": "sha512-xz7wQ8xDhdyP7tQxwdteLYeFfS68tSMNCZ/Y37WJ4bhGfKPpqEIlmIyueQHqOyoPhE6xNUqjzRr8ra0eF9VRvA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/@pump-fun/pump-sdk/node_modules/eventemitter3": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
+ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
+ "license": "MIT"
+ },
+ "node_modules/@pump-fun/pump-sdk/node_modules/superstruct": {
+ "version": "0.15.5",
+ "resolved": "https://registry.npmjs.org/superstruct/-/superstruct-0.15.5.tgz",
+ "integrity": "sha512-4AOeU+P5UuE/4nOUkmcQdW5y7i9ndt1cQd/3iUe+LTz3RxESf/W/5lg4B74HbDMMv8PHnPnGCQFH45kBcrQYoQ==",
+ "license": "MIT"
+ },
"node_modules/@pump-fun/pump-sdk/node_modules/undici-types": {
"version": "6.25.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.25.0.tgz",
diff --git a/package.json b/package.json
index da1a4a4de..db90348dd 100644
--- a/package.json
+++ b/package.json
@@ -109,6 +109,8 @@
"@ai-sdk/anthropic": "^3.0.79",
"@ai-sdk/openai": "^3.0.65",
"@avaturn/sdk": "^1.1.4",
+ "@aws-sdk/client-marketplace-entitlement-service": "latest",
+ "@aws-sdk/client-marketplace-metering": "latest",
"@aws-sdk/client-s3": "latest",
"@aws-sdk/s3-request-presigner": "latest",
"@bonfida/spl-name-service": "0.1.67",
@@ -133,7 +135,7 @@
"@octokit/rest": "^22.0.1",
"@pixiv/three-vrm": "^3.5.3",
"@pump-fun/agent-payments-sdk": "^3.1.0",
- "@pump-fun/pump-sdk": "^1.1.0",
+ "@pump-fun/pump-sdk": "^1.36.0",
"@pump-fun/pump-swap-sdk": "^1.0.0",
"@pythnetwork/hermes-client": "^3.1.0",
"@recast-navigation/core": "^0.43.1",