@alytegen/sdk 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ import { verifyWebhookSignature } from './webhookVerify.js';
2
+ /**
3
+ * Verify and dispatch one Alyte webhook delivery.
4
+ *
5
+ * ## Deliveries are AT-LEAST-ONCE, and your handler owns idempotency.
6
+ *
7
+ * We retry until we see a 2xx, so a handler CAN run more than once for the
8
+ * same `eventId` — most commonly when your handler succeeded but the response
9
+ * never reached us. This SDK deliberately does NOT dedupe for you: doing it
10
+ * here would be a lie, because the dangerous window is not between deliveries,
11
+ * it is inside your own process. If you issue a ticket and crash before
12
+ * recording "handled", a retry double-issues; if you record first and crash,
13
+ * the fulfilment is lost.
14
+ *
15
+ * Only your database can close that window, by writing the dedupe row in the
16
+ * SAME transaction as the ticket:
17
+ *
18
+ * ```ts
19
+ * await db.transaction(async (tx) => {
20
+ * const claimed = await tx.query(
21
+ * `INSERT INTO handled_events (event_id) VALUES ($1)
22
+ * ON CONFLICT DO NOTHING RETURNING event_id`, [event.eventId]);
23
+ * if (!claimed.rowCount) return; // already done — a retry, not a new sale
24
+ * await tx.query(`INSERT INTO tickets (...) VALUES (...)`);
25
+ * });
26
+ * ```
27
+ *
28
+ * ## Failure behaviour
29
+ *
30
+ * - Bad/missing signature → `{ok: false, status: 401}`. Return that status; do
31
+ * NOT run your handler.
32
+ * - Malformed body → `{ok: false, status: 400}`. We will not usefully retry it.
33
+ * - Your handler THROWS → the error propagates. Return 5xx so we retry
34
+ * (30s → 1h backoff, 10 attempts). Swallowing it and returning 200 means the
35
+ * event is gone forever.
36
+ *
37
+ * Pass the RAW request body — verification is over exact bytes, so a parsed
38
+ * and re-serialized object will fail even when the signature is valid.
39
+ */
40
+ export async function handleWebhook(rawBody, signatureHeader, handlers, options) {
41
+ if (!signatureHeader)
42
+ return { ok: false, status: 401, error: 'missing alyte-signature header' };
43
+ if (!verifyWebhookSignature(rawBody, signatureHeader, options.secret, options.toleranceSeconds)) {
44
+ return { ok: false, status: 401, error: 'signature did not verify' };
45
+ }
46
+ let event;
47
+ try {
48
+ event = JSON.parse(rawBody);
49
+ }
50
+ catch {
51
+ return { ok: false, status: 400, error: 'body is not valid JSON' };
52
+ }
53
+ if (!event?.type || !event?.eventId) {
54
+ return { ok: false, status: 400, error: 'not an Alyte event envelope' };
55
+ }
56
+ // A handler that throws propagates on purpose: the caller must return 5xx so
57
+ // the delivery is retried rather than silently dropped.
58
+ switch (event.type) {
59
+ case 'payment.settled':
60
+ await handlers.onSettled?.(event.data, event);
61
+ break;
62
+ case 'watch.failed':
63
+ await handlers.onWatchFailed?.(event.data, event);
64
+ break;
65
+ case 'webhook.test':
66
+ await handlers.onTest?.(event);
67
+ break;
68
+ default:
69
+ await handlers.onUnknown?.(event);
70
+ break;
71
+ }
72
+ return { ok: true, status: 200, eventId: event.eventId, type: event.type };
73
+ }
74
+ /**
75
+ * The same dispatcher, curried for frameworks that want a reusable handler.
76
+ *
77
+ * ```ts
78
+ * const onPurchase = createWebhookHandler({ secret: process.env.ALYTE_WEBHOOK_SECRET! }, {
79
+ * onSettled: async (p) => { await issueTickets(p.tierId, p.quantity, p.buyerRef); },
80
+ * onWatchFailed: async (w) => { await emailBuyer(w.buyerRef, w.reason.message); },
81
+ * });
82
+ *
83
+ * // Express — note express.raw, NOT express.json
84
+ * app.post('/hooks/alyte', express.raw({ type: 'application/json' }), async (req, res) => {
85
+ * const r = await onPurchase(req.body.toString('utf8'), req.header('alyte-signature'));
86
+ * res.status(r.status).send(r.ok ? 'ok' : r.error);
87
+ * });
88
+ * ```
89
+ */
90
+ export function createWebhookHandler(options, handlers) {
91
+ return (rawBody, signatureHeader) => handleWebhook(rawBody, signatureHeader, handlers, options);
92
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Hand-typed mirrors of the Alyte API's response shapes. Money is ALWAYS integer
3
+ * minor units (`…Minor`) — never floats. Format for display only.
4
+ */
5
+ export type Scheme = 'visa' | 'mastercard' | 'amex';
6
+ export type TierKind = 'general' | 'seated';
7
+ export type FeeBearer = 'buyer' | 'merchant';
8
+ export interface Merchant {
9
+ id: string;
10
+ name: string;
11
+ geo: string;
12
+ currency: string;
13
+ /** 'api' = in-flow reserve/confirm; 'hosted' = discovery-only, redirect to checkoutUrl. */
14
+ checkout?: 'api' | 'hosted';
15
+ checkoutUrl?: string;
16
+ allowedSchemes?: Scheme[];
17
+ feeBearer?: FeeBearer;
18
+ taxRateBps?: number;
19
+ /** Public discovery opt-in (default false) — see AlyteMerchant.updateShopDiscovery. */
20
+ discoverable?: boolean;
21
+ imageUrl?: string;
22
+ /** The ONE partner origin allowed to embed the authorize page (G14). */
23
+ embedOrigin?: string;
24
+ }
25
+ export interface EventItem {
26
+ id: string;
27
+ merchantId: string;
28
+ title: string;
29
+ /** ISO-8601 start time. */
30
+ startsAt: string;
31
+ }
32
+ export interface Tier {
33
+ id: string;
34
+ eventId: string;
35
+ title: string;
36
+ /** Integer minor units (cents). NEVER a float. */
37
+ priceMinor: number;
38
+ currency: string;
39
+ kind: TierKind;
40
+ availableCount?: number;
41
+ maxQtyPerPurchase?: number;
42
+ sellable?: boolean;
43
+ onSaleStart?: string;
44
+ onSaleEnd?: string;
45
+ allowedGeos?: string[];
46
+ allowedSchemes?: Scheme[];
47
+ }
48
+ /** Temporal availability, derived server-side at discovery time. */
49
+ export type AvailabilityState = 'on_sale' | 'not_yet_on_sale' | 'sale_ended' | 'sold_out' | 'not_sellable';
50
+ export interface DiscoveredTier extends Tier {
51
+ state: AvailabilityState;
52
+ /** Seconds until worth retrying, present when the sale hasn't opened. */
53
+ retryAfter?: number;
54
+ /** Present when a future purchase could still serve (drop CTA). */
55
+ authorizeUrl?: string;
56
+ }
57
+ export interface DiscoveredEvent extends EventItem {
58
+ tiers: DiscoveredTier[];
59
+ }
60
+ /** A price snapshot locked at quote time; the charge must match it. */
61
+ export interface Quote {
62
+ id: string;
63
+ tierId: string;
64
+ quantity: number;
65
+ unitPriceMinor: number;
66
+ subtotalMinor: number;
67
+ taxMinor: number;
68
+ processingFeeMinor: number;
69
+ /** Alyte's fee — INVOICED to the merchant, never part of the buyer's charge. */
70
+ agentFeeMinor: number;
71
+ /** What the buyer's card is authorised for (depends on feeBearer). */
72
+ chargeMinor: number;
73
+ pspId?: string;
74
+ feeBearer: FeeBearer;
75
+ currency: string;
76
+ /** ISO-8601; re-quote after this. */
77
+ expiresAt: string;
78
+ createdAt: string;
79
+ }
80
+ /** A perishable, oversell-proof reservation. */
81
+ export interface Hold {
82
+ id: string;
83
+ tierId: string;
84
+ seatId?: string;
85
+ quantity: number;
86
+ status: 'held' | 'confirmed' | 'released' | 'expired';
87
+ expiresAt: string;
88
+ createdAt: string;
89
+ /** Present on a partial fill (allowPartial: true). */
90
+ requestedQuantity?: number;
91
+ partialReason?: string;
92
+ }
93
+ export interface PaymentResult {
94
+ intentId: string;
95
+ status: string;
96
+ psp?: string;
97
+ amountMinor?: number;
98
+ currency?: string;
99
+ [k: string]: unknown;
100
+ }
101
+ export type ConfirmOutcome = {
102
+ status: 'settled';
103
+ result: PaymentResult;
104
+ holdStatus: string;
105
+ } | {
106
+ status: 'sca_required';
107
+ challenge: {
108
+ continueToken: string;
109
+ [k: string]: unknown;
110
+ };
111
+ holdStatus: 'held';
112
+ } | {
113
+ status: 'sca_failed';
114
+ holdStatus: 'released';
115
+ };
116
+ export interface MerchantPspLink {
117
+ pspId: string;
118
+ name: string;
119
+ isDefault: boolean;
120
+ rateBps: number;
121
+ /** Opaque reference to the merchant's vaulted PSP secret — never the secret. */
122
+ credentialRef?: string;
123
+ publishableKey?: string;
124
+ }
125
+ export interface CatalogMerchant extends Merchant {
126
+ events: Array<EventItem & {
127
+ tiers: Tier[];
128
+ }>;
129
+ }
130
+ export interface BuyerSessionMint {
131
+ ok: boolean;
132
+ /** Deterministic buyer identity (byr_…) — stable across mint & magic-link logins. */
133
+ buyerId: string;
134
+ expiresAt: string;
135
+ /** RELATIVE single-use redeem path — compose with your Alyte base URL and
136
+ * redirect your user there to drop them into the shop's authorize page. */
137
+ redeemPath: string;
138
+ }
139
+ /** A row on the merchant payments feed (`GET /v1/integration/payments`). */
140
+ export interface PaymentRow {
141
+ intentId: string;
142
+ tenantId: string;
143
+ merchantId: string;
144
+ amountMinor: number;
145
+ currency: string;
146
+ /** 'pending' | 'authorized' | 'declined' | 'error' — FULFIL on 'authorized'
147
+ * (terminal for ticketing: the seat is sold and the charge is captured). */
148
+ status: string;
149
+ pspId?: string;
150
+ scheme?: string;
151
+ source?: string;
152
+ createdBy: string;
153
+ createdAt: string;
154
+ /** The paid ticket tier — fulfil on THIS, never by price-matching. Absent only
155
+ * on legacy rows. */
156
+ tierId?: string;
157
+ quantity?: number;
158
+ /** Stable opaque buyer reference (byr_…) — never an email. Map it to your own
159
+ * customer record at buyer-session mint time if you need contact details. */
160
+ buyerRef?: string;
161
+ }
162
+ /** A registered webhook endpoint (secret is returned ONCE, at create). */
163
+ export interface WebhookEndpoint {
164
+ id: string;
165
+ url: string;
166
+ status: 'active' | 'disabled';
167
+ description?: string;
168
+ createdAt: string;
169
+ }
170
+ /** Agent adoption + per-tier watch demand for one shop (counts only). */
171
+ export interface MerchantInsights {
172
+ agents: {
173
+ total: number;
174
+ alyte: number;
175
+ byoa: number;
176
+ readyToBuy: number;
177
+ };
178
+ watches: Array<{
179
+ tierId: string;
180
+ tierTitle: string;
181
+ eventTitle: string;
182
+ queued: number;
183
+ fired: number;
184
+ failed: number;
185
+ cancelled: number;
186
+ expired: number;
187
+ }>;
188
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Hand-typed mirrors of the Alyte API's response shapes. Money is ALWAYS integer
3
+ * minor units (`…Minor`) — never floats. Format for display only.
4
+ */
5
+ export {};
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Verify an Alyte webhook delivery. The signature is an HMAC-SHA256 over the RAW
3
+ * request body, timestamp-prefixed (Stripe-shaped):
4
+ *
5
+ * alyte-signature: t=<unix-seconds>,v1=hex( hmac_sha256(secret, `${t}.${rawBody}`) )
6
+ *
7
+ * Verify against the RAW bytes, before any JSON parse/re-serialize — most
8
+ * frameworks need a raw-body handler on the webhook route. Deliveries are
9
+ * at-least-once: dedupe by the event's `eventId` (the payment's intentId).
10
+ */
11
+ export declare function verifyWebhookSignature(rawBody: string, signatureHeader: string, secret: string, toleranceSeconds?: number): boolean;
@@ -0,0 +1,23 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ /**
3
+ * Verify an Alyte webhook delivery. The signature is an HMAC-SHA256 over the RAW
4
+ * request body, timestamp-prefixed (Stripe-shaped):
5
+ *
6
+ * alyte-signature: t=<unix-seconds>,v1=hex( hmac_sha256(secret, `${t}.${rawBody}`) )
7
+ *
8
+ * Verify against the RAW bytes, before any JSON parse/re-serialize — most
9
+ * frameworks need a raw-body handler on the webhook route. Deliveries are
10
+ * at-least-once: dedupe by the event's `eventId` (the payment's intentId).
11
+ */
12
+ export function verifyWebhookSignature(rawBody, signatureHeader, secret, toleranceSeconds = 300) {
13
+ const t = /(?:^|,)t=(\d+)/.exec(signatureHeader)?.[1];
14
+ const v1 = /(?:^|,)v1=([0-9a-f]+)/.exec(signatureHeader)?.[1];
15
+ if (!t || !v1)
16
+ return false;
17
+ if (Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds)
18
+ return false; // replay window
19
+ const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
20
+ if (expected.length !== v1.length)
21
+ return false;
22
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
23
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The agent buy path: discover → quote → hold → confirm. Requires an agent JWT
3
+ * (catalog:read + payments:write) whose mandate covers the purchase.
4
+ *
5
+ * ALYTE_BASE_URL=… ALYTE_AGENT_TOKEN=… npx tsx agent-buy.ts
6
+ */
7
+ import { randomUUID } from 'node:crypto';
8
+ import { AlyteAgent, AlyteApiError } from '@alytegen/sdk';
9
+
10
+ const agent = new AlyteAgent({
11
+ baseUrl: process.env.ALYTE_BASE_URL!,
12
+ token: process.env.ALYTE_AGENT_TOKEN!,
13
+ });
14
+
15
+ // 1 · Discover. `state` is live truth: a drop that hasn't opened says so, with a retryAfter.
16
+ const { merchants } = await agent.listMerchants();
17
+ const { events } = await agent.discoverInventory(merchants[0]!.id);
18
+ const tier = events.flatMap((e) => e.tiers).find((t) => t.state === 'on_sale');
19
+ if (!tier) throw new Error('nothing on sale right now');
20
+
21
+ // 2 · Quote — the price is LOCKED until expiresAt. No amount is ever passed again.
22
+ const quote = await agent.quote({ tierId: tier.id, quantity: 2 });
23
+
24
+ // 3 · Hold — oversell-proof; auto-releases if you don't confirm in time.
25
+ const hold = await agent.reserve({ tierId: tier.id, quantity: 2, scheme: 'visa', geo: 'DE' });
26
+
27
+ // 4 · Confirm — pays the locked quote. The idempotencyKey makes retries safe:
28
+ // the same key can NEVER double-charge, even across crashes.
29
+ const [instrument] = (await agent.listInstruments()).instruments;
30
+ try {
31
+ const outcome = await agent.confirm(
32
+ hold.id,
33
+ { quoteId: quote.id, instrumentToken: instrument!.token, scheme: 'visa', geo: 'DE' },
34
+ { idempotencyKey: randomUUID() },
35
+ );
36
+ if (outcome.status === 'settled') console.log('paid:', outcome.result.intentId);
37
+ else if (outcome.status === 'sca_required') {
38
+ // The buyer approves out-of-band; then:
39
+ console.log('resume with:', outcome.challenge.continueToken);
40
+ }
41
+ } catch (e) {
42
+ if (e instanceof AlyteApiError) {
43
+ // Stable taxonomy codes — e.g. a spend-cap refusal means the MANDATE said no;
44
+ // don't retry, tell the buyer.
45
+ console.error(`refused [${e.code}]: ${e.message}`);
46
+ } else throw e;
47
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Merchant onboarding, end to end: shop → PSP → event → tier → your user shopping.
3
+ *
4
+ * ALYTE_BASE_URL=https://alyte-sandbox-….run.app \
5
+ * ALYTE_API_TOKEN=<console-minted, merchant:read+merchant:write> \
6
+ * npx tsx merchant-onboard.ts
7
+ */
8
+ import { AlyteMerchant } from '@alytegen/sdk';
9
+
10
+ const alyte = new AlyteMerchant({
11
+ baseUrl: process.env.ALYTE_BASE_URL!,
12
+ token: process.env.ALYTE_API_TOKEN!, // secret — server-side only
13
+ });
14
+
15
+ // 1 · The shop (your settlement identity — money lands on YOUR PSP, never Alyte's).
16
+ const { merchant } = await alyte.createShop({ name: 'Nova Live', geo: 'DE', currency: 'EUR' });
17
+
18
+ // 2 · Your OWN Stripe. The secret goes straight to Alyte's vault — you get back an
19
+ // opaque ref; the pk_ powers the buyer card-capture iframe.
20
+ await alyte.linkPsp(merchant.id, {
21
+ psp: { id: 'stripe', name: 'Stripe' },
22
+ isDefault: true,
23
+ secret: process.env.MY_STRIPE_SECRET_KEY!,
24
+ publishableKey: process.env.MY_STRIPE_PUBLISHABLE_KEY,
25
+ });
26
+
27
+ // 3 · Inventory. priceMinor is integer cents — 4900 = €49.00.
28
+ const { event } = await alyte.createEvent({
29
+ merchantId: merchant.id,
30
+ title: 'Nova Live — Warsaw',
31
+ startsAt: '2026-11-04T19:00:00Z',
32
+ });
33
+ const { tier } = await alyte.createTier({
34
+ eventId: event.id,
35
+ title: 'General admission',
36
+ priceMinor: 4900,
37
+ currency: 'EUR',
38
+ kind: 'general',
39
+ availableCount: 500,
40
+ });
41
+ await alyte.updateTier(tier.id, { maxQtyPerPurchase: 4 });
42
+
43
+ // 4 · Your signed-in user wants their AI agent to buy for them. You already know
44
+ // who they are — attest them; no email round-trip:
45
+ const session = await alyte.buyerSessions.mint({ merchantId: merchant.id, email: 'fan@example.com' });
46
+ console.log('Redirect your user to:', process.env.ALYTE_BASE_URL + session.redeemPath);
47
+ // They land authenticated on the shop's authorize page: pick/bring an agent,
48
+ // set a spending cap, done. Alyte enforces the cap server-side on every purchase.
@@ -0,0 +1,190 @@
1
+ /**
2
+ * THE REFERENCE INTEGRATION — a complete, runnable merchant server.
3
+ *
4
+ * It is deliberately one file and has no dependencies beyond the SDK and Node,
5
+ * so you can read the whole integration in one sitting and then delete the
6
+ * parts you don't need.
7
+ *
8
+ * It covers exactly the three things a working integration must do:
9
+ *
10
+ * 1. HAND OFF to the buyer → GET /buy/:tierId
11
+ * 2. RECEIVE the purchase → POST /hooks/alyte (signed, at-least-once)
12
+ * 3. FULFIL exactly once → issueTickets(), inside ONE transaction
13
+ *
14
+ * ...and the fourth thing you will need the first time something goes wrong:
15
+ *
16
+ * 4. DIAGNOSE without asking us → GET /admin/why/:watchId
17
+ *
18
+ * Run it:
19
+ *
20
+ * ALYTE_BASE_URL=https://alyte-sandbox-f365cfb3ma-ey.a.run.app \
21
+ * ALYTE_API_TOKEN=alyte_sk_… \
22
+ * ALYTE_WEBHOOK_SECRET=whsec_… \
23
+ * npx tsx server.ts
24
+ *
25
+ * The store here is an in-memory Map standing in for your database. It is the
26
+ * ONLY part you must replace — and §3 explains exactly why the shape matters.
27
+ */
28
+ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
29
+ import { createWebhookHandler, type PaymentSettled, type WatchFailed } from '@alytegen/sdk';
30
+
31
+ const BASE_URL = required('ALYTE_BASE_URL');
32
+ const API_TOKEN = required('ALYTE_API_TOKEN');
33
+ const WEBHOOK_SECRET = required('ALYTE_WEBHOOK_SECRET');
34
+ const PORT = Number(process.env.PORT ?? 8099);
35
+
36
+ function required(name: string): string {
37
+ const v = process.env[name];
38
+ if (!v) { console.error(`Missing ${name}`); process.exit(1); }
39
+ return v;
40
+ }
41
+
42
+ // ─────────────────────────────────────────────────────────────────────────────
43
+ // Your database, stubbed. Replace with the real thing — keep the SHAPE.
44
+ // ─────────────────────────────────────────────────────────────────────────────
45
+ const tickets = new Map<string, { tierId: string; quantity: number; buyerRef: string }>();
46
+ const handledEvents = new Set<string>();
47
+ const notifications: Array<{ buyerRef: string; message: string }> = [];
48
+
49
+ /**
50
+ * §3 · FULFILMENT, EXACTLY ONCE.
51
+ *
52
+ * Deliveries are at-least-once: we retry until we see a 2xx, so this function
53
+ * CAN be called twice for one sale — most often when your handler succeeded but
54
+ * the response never got back to us.
55
+ *
56
+ * The dangerous window is not between deliveries, it is inside this function.
57
+ * Issue the ticket and crash before recording "handled" → a retry double-issues.
58
+ * Record first and crash → the buyer paid and got nothing.
59
+ *
60
+ * The only fix is to make both facts commit together. In real code that is one
61
+ * database transaction:
62
+ *
63
+ * await db.transaction(async (tx) => {
64
+ * const claimed = await tx.query(
65
+ * `INSERT INTO handled_events (event_id) VALUES ($1)
66
+ * ON CONFLICT DO NOTHING RETURNING event_id`, [eventId]);
67
+ * if (!claimed.rowCount) return; // a retry — already fulfilled
68
+ * await tx.query(`INSERT INTO tickets (...) VALUES (...)`);
69
+ * });
70
+ *
71
+ * Claim FIRST inside the transaction, then do the work. If anything throws, the
72
+ * whole thing rolls back and the retry finds the claim gone and tries again.
73
+ */
74
+ function issueTickets(eventId: string, p: PaymentSettled): 'issued' | 'already-issued' {
75
+ if (handledEvents.has(eventId)) return 'already-issued'; // stands in for ON CONFLICT DO NOTHING
76
+ handledEvents.add(eventId);
77
+
78
+ // Fulfil on tierId + quantity — NEVER by matching the amount back to a price.
79
+ // Prices change, tiers don't, and two tiers can cost the same.
80
+ tickets.set(eventId, { tierId: p.tierId, quantity: p.quantity, buyerRef: p.buyerRef });
81
+ return 'issued';
82
+ }
83
+
84
+ // ─────────────────────────────────────────────────────────────────────────────
85
+ // §2 · RECEIVE. Verify, then dispatch. The SDK does not dedupe for you.
86
+ // ─────────────────────────────────────────────────────────────────────────────
87
+ const onAlyteWebhook = createWebhookHandler({ secret: WEBHOOK_SECRET }, {
88
+ onSettled: async (payment: PaymentSettled, event) => {
89
+ const outcome = issueTickets(event.eventId, payment);
90
+ console.log(`[settled] ${event.eventId} · ${payment.quantity}× ${payment.tierId} · ${outcome}`);
91
+ // If this throws, we return 5xx below and Alyte retries (30s → 1h, 10 times).
92
+ },
93
+
94
+ onWatchFailed: async (watch: WatchFailed) => {
95
+ // A queued purchase refused. THIS IS TERMINAL — the watch does not retry,
96
+ // so this is your only chance to tell the buyer. Relay reason.message
97
+ // as-authored; it is written to be read by a person.
98
+ notifications.push({ buyerRef: watch.buyerRef, message: watch.reason.message });
99
+ console.log(`[refused] ${watch.watchId} · ${watch.reason.code} · "${watch.reason.message}"`);
100
+ },
101
+
102
+ onTest: async (event) => {
103
+ // Carries no payment data. Use it to prove your signature check works
104
+ // BEFORE a real sale depends on it. Never fulfil on it.
105
+ console.log(`[test] signature verified · ${event.eventId}`);
106
+ },
107
+ });
108
+
109
+ // ─────────────────────────────────────────────────────────────────────────────
110
+ // §4 · DIAGNOSE. Answer "what happened to that purchase?" yourself.
111
+ // ─────────────────────────────────────────────────────────────────────────────
112
+ async function whyDidThisNotBuy(watchId: string): Promise<unknown> {
113
+ // Most refusals happen BEFORE a payment exists (the spend cap is checked
114
+ // first), so there is often no intentId to look up — this is the entry point
115
+ // that always works. `deliveries` tells you whether WE sent the webhook and
116
+ // what your endpoint said back.
117
+ const res = await fetch(`${BASE_URL}/v1/integration/watches/${watchId}`, {
118
+ headers: { authorization: `Bearer ${API_TOKEN}` },
119
+ });
120
+ if (!res.ok) throw new Error(`lookup failed: ${res.status} ${await res.text()}`);
121
+ return res.json();
122
+ }
123
+
124
+ // ─────────────────────────────────────────────────────────────────────────────
125
+ // Wiring
126
+ // ─────────────────────────────────────────────────────────────────────────────
127
+ function readRawBody(req: IncomingMessage): Promise<string> {
128
+ // RAW bytes. Do not use a JSON body parser on this route — verification is
129
+ // over the exact bytes we signed, and parse-then-restringify breaks it.
130
+ return new Promise((resolve, reject) => {
131
+ const chunks: Buffer[] = [];
132
+ req.on('data', (c: Buffer) => chunks.push(c));
133
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
134
+ req.on('error', reject);
135
+ });
136
+ }
137
+
138
+ const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
139
+ const url = new URL(req.url ?? '/', `http://localhost:${PORT}`);
140
+ const send = (status: number, body: unknown) => {
141
+ res.writeHead(status, { 'content-type': 'application/json' });
142
+ res.end(typeof body === 'string' ? JSON.stringify({ message: body }) : JSON.stringify(body, null, 2));
143
+ };
144
+
145
+ try {
146
+ // §1 · HAND OFF. There is no merchant-side "buy" call, by design: your
147
+ // token cannot spend. You send the buyer to their own authorize page, and
148
+ // they approve in their own session. One URL, no API call.
149
+ if (req.method === 'GET' && url.pathname.startsWith('/buy/')) {
150
+ const tierId = url.pathname.slice('/buy/'.length);
151
+ const merchantId = process.env.ALYTE_MERCHANT_ID ?? 'mrc_your_id';
152
+ const handoff = `${BASE_URL}/shop/${merchantId}/authorize?tier=${encodeURIComponent(tierId)}`;
153
+ res.writeHead(302, { location: handoff });
154
+ return res.end();
155
+ }
156
+
157
+ if (req.method === 'POST' && url.pathname === '/hooks/alyte') {
158
+ const raw = await readRawBody(req);
159
+ const result = await onAlyteWebhook(raw, req.headers['alyte-signature'] as string | undefined);
160
+ // 200 = we stop retrying. Only say it when the work is durably done.
161
+ return send(result.status, result.ok ? { ok: true } : { error: result.error });
162
+ }
163
+
164
+ if (req.method === 'GET' && url.pathname.startsWith('/admin/why/')) {
165
+ return send(200, await whyDidThisNotBuy(url.pathname.slice('/admin/why/'.length)));
166
+ }
167
+
168
+ if (req.method === 'GET' && url.pathname === '/admin/state') {
169
+ return send(200, { tickets: [...tickets.entries()], notifications });
170
+ }
171
+
172
+ return send(404, 'not found');
173
+ } catch (err) {
174
+ // A throw from a handler lands here. Returning 5xx is CORRECT: it tells
175
+ // Alyte to retry. Returning 200 on failure loses the event permanently.
176
+ console.error('[error]', err);
177
+ return send(500, { error: (err as Error).message });
178
+ }
179
+ });
180
+
181
+ server.listen(PORT, () => {
182
+ console.log(`reference merchant on http://localhost:${PORT}`);
183
+ console.log(` hand-off GET /buy/:tierId`);
184
+ console.log(` webhook POST /hooks/alyte`);
185
+ console.log(` diagnose GET /admin/why/:watchId`);
186
+ console.log(` state GET /admin/state`);
187
+ console.log(`\nVerify your signature check before a real sale:`);
188
+ console.log(` 1. expose this server (e.g. a tunnel) and register the URL as a webhook endpoint`);
189
+ console.log(` 2. POST /v1/integration/webhooks/:id/test → you should see "[test] signature verified"`);
190
+ });
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@alytegen/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "Alyte client SDK \u2014 merchant integration (catalog, PSP links, buyer sessions, payments visibility) and the agent buy path (discover \u2192 quote \u2192 hold \u2192 confirm).",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ "./browser": {
10
+ "types": "./dist/browser.d.ts",
11
+ "import": "./dist/browser.js"
12
+ },
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "QUICKSTART.md",
21
+ "BROWSER.md",
22
+ "examples"
23
+ ],
24
+ "scripts": {
25
+ "build": "tsc -p tsconfig.json",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "engines": {
29
+ "node": ">=18"
30
+ },
31
+ "license": "MIT",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/Alytegen/alyte-sdk.git"
35
+ },
36
+ "homepage": "https://github.com/Alytegen/alyte-sdk#readme",
37
+ "bugs": {
38
+ "url": "https://github.com/Alytegen/alyte-sdk/issues"
39
+ },
40
+ "keywords": [
41
+ "alyte",
42
+ "agentic-commerce",
43
+ "ai-agents",
44
+ "payments",
45
+ "mandate",
46
+ "ticketing",
47
+ "sdk"
48
+ ],
49
+ "sideEffects": false,
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^22.10.5",
55
+ "typescript": "^5.7.3"
56
+ },
57
+ "author": "Alyte Agentic Pay"
58
+ }