@alytegen/sdk 0.3.0 → 0.5.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.
- package/BROWSER.md +117 -0
- package/QUICKSTART.md +15 -3
- package/README.md +37 -1
- package/dist/browser.d.ts +183 -0
- package/dist/browser.js +159 -0
- package/dist/merchant.d.ts +24 -1
- package/dist/merchant.js +3 -1
- package/dist/types.d.ts +2 -1
- package/examples/merchant-onboard.ts +1 -1
- package/package.json +7 -2
package/BROWSER.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# Buyer purchases inside your chat
|
|
2
|
+
|
|
3
|
+
Available since SDK 0.4.0 with Alyte's Model 1 browser endpoints (0.5.0 types the attested
|
|
4
|
+
mint). The merchant token stays on your backend. Your chat receives a short-lived bounded
|
|
5
|
+
buyer bearer. How a permission gets created depends on the session you minted:
|
|
6
|
+
**merchant-attested** (enabled merchants, within staff-set ceilings) — Alyte's iframe creates
|
|
7
|
+
it on your attestation, no code; **ordinary** — the iframe asks the buyer to confirm a code
|
|
8
|
+
Alyte emails them. Either way the verification happens inside Alyte's iframe, and the full
|
|
9
|
+
verification bearer stays there. No raw agent credential reaches your chat.
|
|
10
|
+
Your pages and your backend must never call the step-up endpoints or handle the
|
|
11
|
+
buyer's verification code; the iframe does that. A code entered anywhere in your own
|
|
12
|
+
UI is a defect in the integration. The step-up endpoints refuse browser calls from
|
|
13
|
+
partner origins; that refusal is a browser boundary, not a substitute for this rule.
|
|
14
|
+
|
|
15
|
+
Prerequisite: this flow is offered to merchants onboarded under an Alyte contract,
|
|
16
|
+
which carries the rule above. Alyte is invite-onboarded and production keys need
|
|
17
|
+
Alyte's go-live approval; the contract is checked at those steps, not by the
|
|
18
|
+
minting or exchange endpoints themselves.
|
|
19
|
+
|
|
20
|
+
## Availability and contracted attestation
|
|
21
|
+
|
|
22
|
+
The separately enabled merchant-attested path can grant within staff-set
|
|
23
|
+
ceilings without the emailed code. Mint that session on your backend with an
|
|
24
|
+
attest-only key and `merchantAttested: true`, then exchange it and call
|
|
25
|
+
`openConsent` as below. Published SDK 0.4.0 lacks the TypeScript mint field;
|
|
26
|
+
use the [REST example](https://alyte.mintlify.site/guides/console-api-keys).
|
|
27
|
+
The API key never belongs in the browser. Removing staff enablement or revoking
|
|
28
|
+
the key removes the session's attestation exception.
|
|
29
|
+
|
|
30
|
+
The proposed emailed-link confirmation flow is not enabled yet. The current
|
|
31
|
+
verification-code flow remains in use. `openConsent`'s signature and result
|
|
32
|
+
are planned to stay compatible when the new Alyte surfaces ship; 0.4.0 has no
|
|
33
|
+
pending-consent client methods.
|
|
34
|
+
[Follow availability](https://alyte.mintlify.site/guides/consent-confirmation).
|
|
35
|
+
|
|
36
|
+
## Register and attest
|
|
37
|
+
|
|
38
|
+
Register your exact HTTPS chat origin in the shop's `embedOrigin` (multiple origins
|
|
39
|
+
are comma-separated). This controls both framing and buyer CORS. New registrations
|
|
40
|
+
can take up to 30 seconds to reach preflight caches. Local HTTP development is supported.
|
|
41
|
+
On your backend, authenticate your own user, derive their email from that session,
|
|
42
|
+
then call `merchant.buyerSessions.mint({ merchantId, email })` — or, on a `mandates:attest`
|
|
43
|
+
key for an enabled merchant, `mint({ merchantId, email, merchantAttested: true })` so the
|
|
44
|
+
buyer can create a permission within your ceilings without the emailed code. Return only the
|
|
45
|
+
`token` query value extracted from `new URL(session.redeemPath, ALYTE_URL)` to that user's
|
|
46
|
+
browser. Do not navigate the redeem link too: either consumer uses the token once.
|
|
47
|
+
The mint endpoint must not accept an arbitrary browser-supplied email as identity.
|
|
48
|
+
|
|
49
|
+
## Connect and open consent
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { exchangeBuyerSession, createBuyerClient, openConsent } from '@alytegen/sdk/browser';
|
|
53
|
+
|
|
54
|
+
const connection = await exchangeBuyerSession({ baseUrl: ALYTE_URL, token });
|
|
55
|
+
const buyer = createBuyerClient({ baseUrl: ALYTE_URL, bearer: connection.bearer });
|
|
56
|
+
const controller = new AbortController(); // abort when your chat/modal closes
|
|
57
|
+
const { agentId, mandateId } = await openConsent({
|
|
58
|
+
baseUrl: ALYTE_URL, merchantId, bearer: connection.bearer,
|
|
59
|
+
container: document.querySelector<HTMLElement>('#alyte-consent')!,
|
|
60
|
+
signal: controller.signal, lang: 'en',
|
|
61
|
+
theme: { accent: '#006466', radius: 8, scheme: 'light' },
|
|
62
|
+
});
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Keep the connection in memory. It expires after 30 minutes (`expiresAt`). On expiry
|
|
66
|
+
or a `401 unauthorized`, ask your backend for a fresh mint and exchange it; a replayed
|
|
67
|
+
or expired mint returns `401 link_invalid`. Create a new client with the new bearer.
|
|
68
|
+
Cookie login endpoints are not available to the parent chat.
|
|
69
|
+
|
|
70
|
+
The iframe lets the buyer choose an existing usable Alyte agent/permission or
|
|
71
|
+
create one. Selecting an existing permission needs no new email verification.
|
|
72
|
+
Creating authority does, except for an enabled merchant-attested session within
|
|
73
|
+
its ceilings. Completion returns IDs only and removes the iframe.
|
|
74
|
+
Cancellation/abort rejects with `AlyteConsentError.code = 'consent_cancelled'`;
|
|
75
|
+
an initial handshake timeout uses `consent_unavailable`. Server errors retain their
|
|
76
|
+
code. `readyTimeoutMs` defaults to 15 seconds and never limits code-entry time.
|
|
77
|
+
|
|
78
|
+
Optional `returnUrl` must belong to the chat origin. `onNavigate(url)` decides how
|
|
79
|
+
your chat handles the Back link. The SDK does not navigate the host automatically.
|
|
80
|
+
Themes accept only `accent`, `background`, `surface`, `text`, `font`, `radius`, `scheme`.
|
|
81
|
+
Colours are opaque hex; font is system/sans/serif, radius is 0–16, scheme light/dark.
|
|
82
|
+
Omit `font` to keep Alyte's self-hosted Hanken Grotesk. Explicit `system`, `sans` and
|
|
83
|
+
`serif` select system UI, Arial and Georgia respectively. Secondary text and dividers
|
|
84
|
+
are derived automatically from the palette while preserving readable contrast.
|
|
85
|
+
If contrast fails, all four colours fall back to scheme defaults; they are not
|
|
86
|
+
adjusted. Permission terms, errors and disabled controls keep fixed readable colours.
|
|
87
|
+
Provider card inputs keep their provider styling.
|
|
88
|
+
|
|
89
|
+
## Buy, watch and revoke
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
const attempt = { agentId, tierId, quantity: 1, attemptId: crypto.randomUUID() };
|
|
93
|
+
// Persist BEFORE sending. Use your app's durable purchase-attempt store; retain it
|
|
94
|
+
// across reloads and reconnects. Namespace it to this buyer/shop/cart.
|
|
95
|
+
await attempts.save(attempt);
|
|
96
|
+
const purchase = await buyer.buy(attempt);
|
|
97
|
+
if (purchase.status === 'pending') {
|
|
98
|
+
const receipt = await buyer.payment(purchase.intentId); // refresh later if pending
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The UUID is required; the SDK never invents one or retries requests automatically.
|
|
103
|
+
After a network failure, resume with the **same saved attempt**, including agent,
|
|
104
|
+
tier, quantity and ID. Never create a fresh attempt to retry an uncertain charge.
|
|
105
|
+
`settled` is success; `pending` remains unresolved. `sca_required` is an authentication
|
|
106
|
+
continuation requirement; browser SCA resume is not yet available. Do not treat it
|
|
107
|
+
as success or dispatch a new purchase. Non-2xx responses throw `AlyteApiError` with
|
|
108
|
+
`status`, `code` and `details`; purchase `402` outcome bodies are in `details`.
|
|
109
|
+
|
|
110
|
+
Other methods: `me()`, `catalog()`, `agents()`, `instruments()`, `instrumentCaps()`,
|
|
111
|
+
`watches()`, `watch({ agentId, tierId, quantity, expiresInDays? })`,
|
|
112
|
+
`cancelWatch(id)`, `revokeMandate(id)`. Revocation is immediate and server-enforced.
|
|
113
|
+
Every buy/watch still depends on the buyer's current mandate, card evidence and
|
|
114
|
+
live availability. An ordinary bounded bearer cannot create or widen spending authority.
|
|
115
|
+
|
|
116
|
+
Your backend still fulfills from verified settlement webhooks, idempotently.
|
|
117
|
+
Browser completion messages are presentation state, not fulfillment evidence.
|
package/QUICKSTART.md
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
# @alytegen/sdk — quickstart
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Choose the credential for the runtime:
|
|
4
4
|
|
|
5
5
|
| Client | Credential | Runs | Does |
|
|
6
6
|
|---|---|---|---|
|
|
7
|
-
| `AlyteMerchant` | API token (console → API keys, `merchant:read`/`merchant:write`) | **your server only** | catalog CRUD, PSP links, payments visibility, buyer-session mint |
|
|
7
|
+
| `AlyteMerchant` | API token (console → API keys, `merchant:read`/`merchant:write`; `merchant:admin` for creating or deleting shops and linking a PSP) | **your server only** | catalog CRUD, PSP links, payments visibility, buyer-session mint |
|
|
8
8
|
| `AlyteAgent` | agent JWT | your agent runtime | discover → quote → hold → confirm |
|
|
9
|
+
| `@alytegen/sdk/browser` | bounded buyer bearer | your chat page | embedded consent and purchases using the buyer's Alyte agent |
|
|
9
10
|
|
|
10
11
|
```bash
|
|
11
12
|
npm install @alytegen/sdk # zero dependencies, Node ≥18 (built-in fetch)
|
|
@@ -37,10 +38,21 @@ When a signed-in user wants an AI agent shopping for them, **your server attests
|
|
|
37
38
|
them** and you redirect:
|
|
38
39
|
|
|
39
40
|
```ts
|
|
40
|
-
const s = await alyte.buyerSessions.mint({
|
|
41
|
+
const s = await alyte.buyerSessions.mint({
|
|
42
|
+
merchantId: merchant.id, email: user.email,
|
|
43
|
+
lang: user.locale, // optional: Alyte's pages open in the language of YOUR site
|
|
44
|
+
});
|
|
41
45
|
res.redirect(ALYTE_URL + s.redeemPath); // single-use, 15-min TTL
|
|
42
46
|
```
|
|
43
47
|
|
|
48
|
+
Merchants that Alyte staff have enabled under contract can mint with `merchantAttested: true`
|
|
49
|
+
on a key holding only `mandates:attest`: the buyer then creates a permission within your
|
|
50
|
+
shop's ceilings without the emailed code (see the README's hand-off section).
|
|
51
|
+
|
|
52
|
+
Embedding in a chat? Follow [BROWSER.md](./BROWSER.md) to exchange the single-use
|
|
53
|
+
token and launch consent without third-party cookies. Directly framing the full
|
|
54
|
+
authorize page is also supported, but its cookie session depends on browser policy.
|
|
55
|
+
|
|
44
56
|
They land authenticated on the shop's authorize page: pick or bring an agent,
|
|
45
57
|
set a spending cap and scope — all enforced server-side by Alyte on every
|
|
46
58
|
purchase. `buyerId` is deterministic per email, so the same user arriving later
|
package/README.md
CHANGED
|
@@ -14,13 +14,17 @@ between the buyer and the merchant's Stripe or Adyen account.
|
|
|
14
14
|
npm install @alytegen/sdk
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
##
|
|
17
|
+
## Entry points
|
|
18
18
|
|
|
19
19
|
| Export | Credential | Runs where | Does |
|
|
20
20
|
|---|---|---|---|
|
|
21
21
|
| `AlyteMerchant` | API token (console → API keys) | your server only | shops, events, tiers, PSP links, buyer-session mint, payments visibility |
|
|
22
22
|
| `AlyteAgent` | agent JWT | your agent runtime | discover → quote → hold → confirm |
|
|
23
23
|
| `createWebhookHandler` / `verifyWebhookSignature` | webhook secret | your server | signed, at-least-once purchase events with typed dispatch |
|
|
24
|
+
| `exchangeBuyerSession` / `createBuyerClient` / `openConsent` from `@alytegen/sdk/browser` | bounded buyer bearer | partner browser/chat | isolated consent, then buy/watch/list/revoke within existing authority |
|
|
25
|
+
|
|
26
|
+
The browser entry is new in 0.4.0. See [the chat integration](./BROWSER.md) for setup,
|
|
27
|
+
cookie-independent consent, reconnecting and handling uncertain purchases.
|
|
24
28
|
|
|
25
29
|
## Merchant: onboard in four calls
|
|
26
30
|
|
|
@@ -50,6 +54,25 @@ const s = await alyte.buyerSessions.mint({ merchantId: merchant.id, email: user.
|
|
|
50
54
|
res.redirect(ALYTE_URL + s.redeemPath); // single-use, 15-minute link
|
|
51
55
|
```
|
|
52
56
|
|
|
57
|
+
Two kinds of session, decided by how you mint:
|
|
58
|
+
|
|
59
|
+
- **Ordinary** (above): the buyer can act inside permission they already granted. Creating or
|
|
60
|
+
widening permission asks them to confirm a 6-digit code Alyte emails them, typed into Alyte's
|
|
61
|
+
own screen — never into yours.
|
|
62
|
+
- **Merchant-attested** — for merchants Alyte staff have enabled under contract — lets the buyer
|
|
63
|
+
create a permission **without the code**, within the ceilings staff set for your shop, because
|
|
64
|
+
you vouch for your signed-in, email-verified customer. It needs a key holding only
|
|
65
|
+
`mandates:attest` (the console offers **attest verified customers only** once enabled):
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
const attesting = new AlyteMerchant({ baseUrl: ALYTE_URL, token: process.env.ALYTE_ATTEST_KEY! });
|
|
69
|
+
const s = await attesting.buyerSessions.mint({ merchantId: merchant.id, email: user.email, merchantAttested: true });
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The buyer sees "Set up by {your shop}" on that agent and can revoke it. A grant outside the
|
|
73
|
+
ceilings answers `403 merchant_consent_ceiling_exceeded` and Alyte's screen falls back to the
|
|
74
|
+
buyer's own code; without the enablement, the mint answers `403 merchant_consent_not_enabled`.
|
|
75
|
+
|
|
53
76
|
## Receive purchases
|
|
54
77
|
|
|
55
78
|
```ts
|
|
@@ -78,6 +101,19 @@ const out = await agent.confirm(hold.id,
|
|
|
78
101
|
No amount is passed at confirm — the charge is the locked quote. A spend-cap refusal means
|
|
79
102
|
the buyer's mandate said no: surface it, don't retry.
|
|
80
103
|
|
|
104
|
+
## Current API and console capabilities
|
|
105
|
+
|
|
106
|
+
SDK **0.5.0** types the merchant-attested mint (`merchantAttested: true`), alongside the browser
|
|
107
|
+
entry point and the typed tier-create restrictions (`onSaleStart`, `onSaleEnd`, `maxQtyPerPurchase`,
|
|
108
|
+
`sellable`, `allowedGeos`, `allowedSchemes` — put them in the initial `createTier` call so a
|
|
109
|
+
scheduled tier is never briefly on sale).
|
|
110
|
+
|
|
111
|
+
The console offers **attest verified customers only** while Alyte staff have enabled contracted
|
|
112
|
+
consent for your organization; that key holds only `mandates:attest`, and a read/write key does
|
|
113
|
+
not include it. Permission creation for everyone else goes through Alyte's consent screen with the
|
|
114
|
+
emailed code — there is no API for your code to create or widen a buyer's spending authority, by
|
|
115
|
+
design. Alyte's server runs Node 22; this SDK supports Node 18 and later.
|
|
116
|
+
|
|
81
117
|
## Learn more
|
|
82
118
|
|
|
83
119
|
- [QUICKSTART.md](./QUICKSTART.md) — the walkthrough with every call explained.
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import type { DiscoveredEvent, Scheme } from './types.js';
|
|
2
|
+
export { AlyteApiError } from './http.js';
|
|
3
|
+
export interface BuyerConnection {
|
|
4
|
+
bearer: string;
|
|
5
|
+
buyerId: string;
|
|
6
|
+
expiresAt: string;
|
|
7
|
+
}
|
|
8
|
+
export interface BuyerIdentity {
|
|
9
|
+
tenantId: string;
|
|
10
|
+
buyerId: string;
|
|
11
|
+
email: string;
|
|
12
|
+
merchantId: string;
|
|
13
|
+
merchantName?: string;
|
|
14
|
+
currency?: string;
|
|
15
|
+
geo?: string;
|
|
16
|
+
tier: 'bounded' | 'full';
|
|
17
|
+
}
|
|
18
|
+
export interface BuyerMandate {
|
|
19
|
+
id: string;
|
|
20
|
+
agentId: string;
|
|
21
|
+
capMinor: number;
|
|
22
|
+
currency: string;
|
|
23
|
+
spentMinor?: number;
|
|
24
|
+
expiresAt?: string;
|
|
25
|
+
status: 'active' | 'amended' | 'revoked';
|
|
26
|
+
recurring: boolean;
|
|
27
|
+
maxTransactions?: number;
|
|
28
|
+
cadence?: string;
|
|
29
|
+
scope: {
|
|
30
|
+
merchants?: string[];
|
|
31
|
+
events?: string[];
|
|
32
|
+
tierKinds?: ('general' | 'seated')[];
|
|
33
|
+
quantity?: {
|
|
34
|
+
min?: number;
|
|
35
|
+
max?: number;
|
|
36
|
+
step?: number;
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export interface BuyerAgent {
|
|
41
|
+
id: string;
|
|
42
|
+
name: string;
|
|
43
|
+
kind: 'alyte' | 'byoa';
|
|
44
|
+
spendCapMinor: number;
|
|
45
|
+
scheme: Scheme;
|
|
46
|
+
quantity: number;
|
|
47
|
+
instrumentToken?: string;
|
|
48
|
+
instrumentStatus?: 'ok' | 'missing';
|
|
49
|
+
mandates: BuyerMandate[];
|
|
50
|
+
}
|
|
51
|
+
export interface BuyerWatch {
|
|
52
|
+
id: string;
|
|
53
|
+
agentId: string;
|
|
54
|
+
merchantId: string;
|
|
55
|
+
tierId: string;
|
|
56
|
+
quantity: number;
|
|
57
|
+
status: 'queued' | 'paused' | 'firing' | 'fired' | 'failed' | 'cancelled' | 'expired';
|
|
58
|
+
result?: Record<string, unknown>;
|
|
59
|
+
expiresAt?: string;
|
|
60
|
+
createdAt: string;
|
|
61
|
+
firedAt?: string;
|
|
62
|
+
}
|
|
63
|
+
export type BuyerPurchase = {
|
|
64
|
+
status: 'settled' | 'pending';
|
|
65
|
+
intentId: string;
|
|
66
|
+
chargeMinor: number;
|
|
67
|
+
currency: string;
|
|
68
|
+
paymentState?: string;
|
|
69
|
+
agentName?: string;
|
|
70
|
+
} | {
|
|
71
|
+
status: 'sca_required';
|
|
72
|
+
} | {
|
|
73
|
+
status: 'refused' | 'error';
|
|
74
|
+
outcome: unknown;
|
|
75
|
+
};
|
|
76
|
+
export interface BuyerReceipt {
|
|
77
|
+
intentId: string;
|
|
78
|
+
status: 'settled' | 'pending' | 'refused';
|
|
79
|
+
chargeMinor: number;
|
|
80
|
+
currency: string;
|
|
81
|
+
paymentState?: string;
|
|
82
|
+
}
|
|
83
|
+
export interface BuyerClientOptions {
|
|
84
|
+
baseUrl: string;
|
|
85
|
+
bearer: string;
|
|
86
|
+
fetch?: typeof globalThis.fetch;
|
|
87
|
+
}
|
|
88
|
+
/** Pass only the token from the merchant-minted redeemPath. Keep the result in memory. */
|
|
89
|
+
export declare function exchangeBuyerSession(opts: {
|
|
90
|
+
baseUrl: string;
|
|
91
|
+
token: string;
|
|
92
|
+
fetch?: typeof globalThis.fetch;
|
|
93
|
+
}): Promise<BuyerConnection>;
|
|
94
|
+
/** Existing-authority actions only. Setup and permission changes belong in openConsent. */
|
|
95
|
+
export declare function createBuyerClient(opts: BuyerClientOptions): {
|
|
96
|
+
me: () => Promise<BuyerIdentity>;
|
|
97
|
+
catalog: () => Promise<{
|
|
98
|
+
events: DiscoveredEvent[];
|
|
99
|
+
}>;
|
|
100
|
+
agents: () => Promise<{
|
|
101
|
+
agents: BuyerAgent[];
|
|
102
|
+
}>;
|
|
103
|
+
instruments: () => Promise<{
|
|
104
|
+
instruments: Array<{
|
|
105
|
+
token: string;
|
|
106
|
+
scheme: Scheme;
|
|
107
|
+
last4: string;
|
|
108
|
+
mine: boolean;
|
|
109
|
+
}>;
|
|
110
|
+
}>;
|
|
111
|
+
instrumentCaps: () => Promise<{
|
|
112
|
+
caps: Array<{
|
|
113
|
+
instrumentToken: string;
|
|
114
|
+
capMinor: number;
|
|
115
|
+
currency: string;
|
|
116
|
+
grantedMinor: number;
|
|
117
|
+
}>;
|
|
118
|
+
}>;
|
|
119
|
+
watches: () => Promise<{
|
|
120
|
+
watches: BuyerWatch[];
|
|
121
|
+
}>;
|
|
122
|
+
/** Save attemptId BEFORE dispatch and reuse it after an uncertain response. Never retry with a new ID. */
|
|
123
|
+
buy: (input: {
|
|
124
|
+
agentId: string;
|
|
125
|
+
tierId: string;
|
|
126
|
+
quantity: number;
|
|
127
|
+
attemptId: string;
|
|
128
|
+
}) => Promise<BuyerPurchase>;
|
|
129
|
+
payment: (intentId: string) => Promise<BuyerReceipt>;
|
|
130
|
+
watch: (input: {
|
|
131
|
+
agentId: string;
|
|
132
|
+
tierId: string;
|
|
133
|
+
quantity: number;
|
|
134
|
+
expiresInDays?: number;
|
|
135
|
+
}) => Promise<{
|
|
136
|
+
watch: BuyerWatch;
|
|
137
|
+
}>;
|
|
138
|
+
cancelWatch: (watchId: string) => Promise<{
|
|
139
|
+
watch: BuyerWatch;
|
|
140
|
+
}>;
|
|
141
|
+
revokeMandate: (mandateId: string) => Promise<{
|
|
142
|
+
ok: true;
|
|
143
|
+
id: string;
|
|
144
|
+
status: "revoked";
|
|
145
|
+
}>;
|
|
146
|
+
};
|
|
147
|
+
export type BuyerClient = ReturnType<typeof createBuyerClient>;
|
|
148
|
+
export interface ConsentTheme {
|
|
149
|
+
accent?: string;
|
|
150
|
+
background?: string;
|
|
151
|
+
surface?: string;
|
|
152
|
+
text?: string;
|
|
153
|
+
font?: 'system' | 'sans' | 'serif';
|
|
154
|
+
radius?: number;
|
|
155
|
+
scheme?: 'light' | 'dark';
|
|
156
|
+
}
|
|
157
|
+
export interface ConsentResult {
|
|
158
|
+
agentId: string;
|
|
159
|
+
mandateId: string;
|
|
160
|
+
}
|
|
161
|
+
export interface ConsentOptions {
|
|
162
|
+
baseUrl: string;
|
|
163
|
+
merchantId: string;
|
|
164
|
+
bearer: string;
|
|
165
|
+
container: HTMLElement;
|
|
166
|
+
theme?: ConsentTheme;
|
|
167
|
+
tierId?: string;
|
|
168
|
+
quantity?: number;
|
|
169
|
+
lang?: string;
|
|
170
|
+
/** Optional back link. Restricted to this host origin; the callback decides navigation. */
|
|
171
|
+
returnUrl?: string;
|
|
172
|
+
onNavigate?: (url: string) => void;
|
|
173
|
+
/** Abort when your modal closes; removes the iframe and rejects with consent_cancelled. */
|
|
174
|
+
signal?: AbortSignal;
|
|
175
|
+
/** Bounds the initial ready handshake, not the buyer's time entering a code. Default 15s. */
|
|
176
|
+
readyTimeoutMs?: number;
|
|
177
|
+
}
|
|
178
|
+
export declare class AlyteConsentError extends Error {
|
|
179
|
+
readonly code: string;
|
|
180
|
+
constructor(code: string);
|
|
181
|
+
}
|
|
182
|
+
/** Mount Alyte's isolated consent surface; the full verification credential never leaves it. */
|
|
183
|
+
export declare function openConsent(opts: ConsentOptions): Promise<ConsentResult>;
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/** Browser-only buyer connection. No merchant key or raw agent credential belongs here. */
|
|
2
|
+
import { AlyteApiError } from './http.js';
|
|
3
|
+
export { AlyteApiError } from './http.js';
|
|
4
|
+
function baseOrigin(value) {
|
|
5
|
+
const url = new URL(value);
|
|
6
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
|
|
7
|
+
throw new TypeError('baseUrl must be an HTTP(S) origin');
|
|
8
|
+
if (url.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
|
|
9
|
+
throw new TypeError('baseUrl must use HTTPS outside local development');
|
|
10
|
+
return url.origin;
|
|
11
|
+
}
|
|
12
|
+
/** HTTP errors retain the server taxonomy; no request is automatically retried. */
|
|
13
|
+
async function request(fetcher, base, path, method, bearer, body) {
|
|
14
|
+
const res = await fetcher(base + path, { method, credentials: 'omit', redirect: 'error', cache: 'no-store',
|
|
15
|
+
headers: { ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
|
|
16
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
17
|
+
});
|
|
18
|
+
const json = await res.json().catch(() => undefined);
|
|
19
|
+
if (!res.ok) {
|
|
20
|
+
const error = json?.error;
|
|
21
|
+
throw new AlyteApiError(res.status, error?.code ?? `http_${res.status}`, error?.message ?? `Alyte API error (HTTP ${res.status})`, error?.details ?? json);
|
|
22
|
+
}
|
|
23
|
+
return json;
|
|
24
|
+
}
|
|
25
|
+
/** Pass only the token from the merchant-minted redeemPath. Keep the result in memory. */
|
|
26
|
+
export function exchangeBuyerSession(opts) {
|
|
27
|
+
if (typeof opts.token !== 'string' || !opts.token)
|
|
28
|
+
throw new TypeError('token is required');
|
|
29
|
+
return request(opts.fetch ?? globalThis.fetch, baseOrigin(opts.baseUrl), '/v1/buyer/session-token', 'POST', undefined, { token: opts.token });
|
|
30
|
+
}
|
|
31
|
+
/** Existing-authority actions only. Setup and permission changes belong in openConsent. */
|
|
32
|
+
export function createBuyerClient(opts) {
|
|
33
|
+
const base = baseOrigin(opts.baseUrl), fetcher = opts.fetch ?? globalThis.fetch;
|
|
34
|
+
if (typeof opts.bearer !== 'string' || !opts.bearer)
|
|
35
|
+
throw new TypeError('bearer is required');
|
|
36
|
+
const call = (method, path, body) => request(fetcher, base, '/v1/buyer' + path, method, opts.bearer, body);
|
|
37
|
+
return {
|
|
38
|
+
me: () => call('GET', '/me'),
|
|
39
|
+
catalog: () => call('GET', '/catalog'),
|
|
40
|
+
agents: () => call('GET', '/agents'),
|
|
41
|
+
instruments: () => call('GET', '/instruments'),
|
|
42
|
+
instrumentCaps: () => call('GET', '/instruments/caps'),
|
|
43
|
+
watches: () => call('GET', '/watches'),
|
|
44
|
+
/** Save attemptId BEFORE dispatch and reuse it after an uncertain response. Never retry with a new ID. */
|
|
45
|
+
buy: (input) => {
|
|
46
|
+
if (typeof input.attemptId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(input.attemptId))
|
|
47
|
+
throw new TypeError('A saved UUID attemptId is required');
|
|
48
|
+
return call('POST', `/agents/${encodeURIComponent(input.agentId)}/buy`, { tierId: input.tierId, quantity: input.quantity, attemptId: input.attemptId });
|
|
49
|
+
},
|
|
50
|
+
payment: (intentId) => call('GET', `/payments/${encodeURIComponent(intentId)}`),
|
|
51
|
+
watch: (input) => call('POST', '/watches', input),
|
|
52
|
+
cancelWatch: (watchId) => call('DELETE', `/watches/${encodeURIComponent(watchId)}`),
|
|
53
|
+
revokeMandate: (mandateId) => call('DELETE', `/mandates/${encodeURIComponent(mandateId)}`),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export class AlyteConsentError extends Error {
|
|
57
|
+
code;
|
|
58
|
+
constructor(code) {
|
|
59
|
+
super(`Alyte consent: ${code}`);
|
|
60
|
+
this.code = code;
|
|
61
|
+
this.name = 'AlyteConsentError';
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Mount Alyte's isolated consent surface; the full verification credential never leaves it. */
|
|
65
|
+
export function openConsent(opts) {
|
|
66
|
+
const base = baseOrigin(opts.baseUrl);
|
|
67
|
+
if (!opts.merchantId || !opts.bearer)
|
|
68
|
+
throw new TypeError('merchantId and bearer are required');
|
|
69
|
+
const doc = opts.container.ownerDocument, host = doc.defaultView;
|
|
70
|
+
if (!host)
|
|
71
|
+
throw new TypeError('container must belong to a browser document');
|
|
72
|
+
if (opts.readyTimeoutMs !== undefined && (!Number.isFinite(opts.readyTimeoutMs) || opts.readyTimeoutMs <= 0))
|
|
73
|
+
throw new TypeError('readyTimeoutMs must be positive');
|
|
74
|
+
const url = new URL(`/shop/${encodeURIComponent(opts.merchantId)}/authorize`, base);
|
|
75
|
+
url.searchParams.set('view', 'consent');
|
|
76
|
+
url.searchParams.set('embed', '1');
|
|
77
|
+
if (opts.tierId)
|
|
78
|
+
url.searchParams.set('tier', opts.tierId);
|
|
79
|
+
if (opts.quantity !== undefined) {
|
|
80
|
+
if (!Number.isInteger(opts.quantity) || opts.quantity < 1 || opts.quantity > 10)
|
|
81
|
+
throw new TypeError('quantity must be 1–10');
|
|
82
|
+
url.searchParams.set('qty', String(opts.quantity));
|
|
83
|
+
}
|
|
84
|
+
if (opts.lang)
|
|
85
|
+
url.searchParams.set('lang', opts.lang);
|
|
86
|
+
if (opts.returnUrl) {
|
|
87
|
+
const back = new URL(opts.returnUrl);
|
|
88
|
+
if (back.origin !== host.location.origin)
|
|
89
|
+
throw new TypeError('returnUrl must belong to the host origin');
|
|
90
|
+
url.searchParams.set('return', back.href);
|
|
91
|
+
}
|
|
92
|
+
for (const key of ['accent', 'background', 'surface', 'text', 'font', 'radius', 'scheme']) {
|
|
93
|
+
const value = opts.theme?.[key];
|
|
94
|
+
if ((typeof value === 'string' || typeof value === 'number') && String(value).length <= 64)
|
|
95
|
+
url.searchParams.set(key, String(value));
|
|
96
|
+
}
|
|
97
|
+
return new Promise((resolve, reject) => {
|
|
98
|
+
const iframe = doc.createElement('iframe');
|
|
99
|
+
iframe.title = 'Alyte consent';
|
|
100
|
+
iframe.src = url.href;
|
|
101
|
+
iframe.referrerPolicy = 'no-referrer';
|
|
102
|
+
iframe.style.width = '100%';
|
|
103
|
+
iframe.style.height = '640px';
|
|
104
|
+
iframe.style.border = '0';
|
|
105
|
+
let done = false, ready = false;
|
|
106
|
+
let timer;
|
|
107
|
+
const cleanup = () => { clearTimeout(timer); host.removeEventListener('message', receive); opts.signal?.removeEventListener('abort', abort); iframe.remove(); };
|
|
108
|
+
const fail = (code) => { if (!done) {
|
|
109
|
+
done = true;
|
|
110
|
+
cleanup();
|
|
111
|
+
reject(new AlyteConsentError(code));
|
|
112
|
+
} };
|
|
113
|
+
const abort = () => fail('consent_cancelled');
|
|
114
|
+
const receive = (event) => {
|
|
115
|
+
if (done || event.origin !== base || event.source !== iframe.contentWindow)
|
|
116
|
+
return;
|
|
117
|
+
const data = event.data;
|
|
118
|
+
if (!data || data.type !== 'alyte:consent' || data.merchantId !== opts.merchantId)
|
|
119
|
+
return;
|
|
120
|
+
if (data.event === 'ready') {
|
|
121
|
+
// Language changes reload this same trusted frame. Each fresh document
|
|
122
|
+
// needs bootstrap; the Alyte page accepts it only once per document.
|
|
123
|
+
ready = true;
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
iframe.contentWindow?.postMessage({ type: 'alyte:consent', event: 'bootstrap', bearer: opts.bearer }, base);
|
|
126
|
+
}
|
|
127
|
+
else if (data.event === 'granted' && ready) {
|
|
128
|
+
if (typeof data.agentId !== 'string' || !data.agentId || typeof data.mandateId !== 'string' || !data.mandateId)
|
|
129
|
+
return;
|
|
130
|
+
done = true;
|
|
131
|
+
cleanup();
|
|
132
|
+
resolve({ agentId: data.agentId, mandateId: data.mandateId });
|
|
133
|
+
}
|
|
134
|
+
else if (data.event === 'cancelled')
|
|
135
|
+
abort();
|
|
136
|
+
else if (data.event === 'error' && typeof data.code === 'string')
|
|
137
|
+
fail(data.code);
|
|
138
|
+
else if (data.event === 'resize' && Number.isFinite(data.height))
|
|
139
|
+
iframe.style.height = `${Math.max(240, Math.min(1200, Math.ceil(data.height)))}px`;
|
|
140
|
+
else if (data.event === 'navigate' && typeof data.url === 'string') {
|
|
141
|
+
try {
|
|
142
|
+
const back = new URL(data.url);
|
|
143
|
+
if (back.origin === host.location.origin)
|
|
144
|
+
opts.onNavigate?.(back.href);
|
|
145
|
+
}
|
|
146
|
+
catch { /* Ignore malformed navigation messages. */ }
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
if (opts.signal?.aborted) {
|
|
150
|
+
abort();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
host.addEventListener('message', receive);
|
|
154
|
+
opts.signal?.addEventListener('abort', abort, { once: true });
|
|
155
|
+
timer = setTimeout(() => fail('consent_unavailable'), opts.readyTimeoutMs ?? 15_000);
|
|
156
|
+
iframe.addEventListener('error', () => fail('consent_unavailable'), { once: true });
|
|
157
|
+
opts.container.append(iframe);
|
|
158
|
+
});
|
|
159
|
+
}
|
package/dist/merchant.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { type ClientOptions } from './http.js';
|
|
|
2
2
|
import type { BuyerSessionMint, CatalogMerchant, Merchant, EventItem, MerchantPspLink, Tier, TierKind, FeeBearer, Scheme, PaymentRow, WebhookEndpoint, MerchantInsights } from './types.js';
|
|
3
3
|
/**
|
|
4
4
|
* Merchant integration client — drives the `/v1/integration/*` surface with a
|
|
5
|
-
* console-minted API token (`merchant:read` / `merchant:write` scopes
|
|
5
|
+
* console-minted API token (`merchant:read` / `merchant:write` scopes; `merchant:admin` for
|
|
6
|
+
* creating or deleting shops and linking a PSP — the "full" console preset).
|
|
6
7
|
*
|
|
7
8
|
* SERVER-SIDE ONLY: the API token is a secret. Never ship it to a browser.
|
|
8
9
|
*
|
|
@@ -58,6 +59,12 @@ export declare class AlyteMerchant {
|
|
|
58
59
|
currency: string;
|
|
59
60
|
kind: TierKind;
|
|
60
61
|
availableCount?: number;
|
|
62
|
+
maxQtyPerPurchase?: number | null;
|
|
63
|
+
sellable?: boolean;
|
|
64
|
+
onSaleStart?: string | null;
|
|
65
|
+
onSaleEnd?: string | null;
|
|
66
|
+
allowedGeos?: string[] | null;
|
|
67
|
+
allowedSchemes?: Scheme[] | null;
|
|
61
68
|
}): Promise<{
|
|
62
69
|
tier: Tier;
|
|
63
70
|
}>;
|
|
@@ -145,10 +152,26 @@ export declare class AlyteMerchant {
|
|
|
145
152
|
* Attest YOUR authenticated user → a single-use redeem link (15-min TTL).
|
|
146
153
|
* Redirect the user to `baseUrl + redeemPath`; the buyer-session cookie and
|
|
147
154
|
* the shop's authorize page take over from there.
|
|
155
|
+
* Unknown fields are rejected with 400 and error.details.fields.
|
|
148
156
|
*/
|
|
149
157
|
mint: (input: {
|
|
150
158
|
merchantId: string;
|
|
151
159
|
email: string;
|
|
160
|
+
/** The tier the buyer chose — opens the authorize page as a checkout for it. */
|
|
161
|
+
tierId?: string;
|
|
162
|
+
/** Ticket count hint (1–10), requires tierId; permission and tier limits still govern. */
|
|
163
|
+
quantity?: number;
|
|
164
|
+
/** Back-to-shop link, not an automatic redirect. HTTPS (local HTTP allowed);
|
|
165
|
+
* restricted to registered embed origins when configured. */
|
|
166
|
+
returnUrl?: string;
|
|
167
|
+
/** The buyer's language on YOUR site (BCP-47, e.g. "de" or "de-AT"), so Alyte's
|
|
168
|
+
* pages open in the same language. Presentation only. */
|
|
169
|
+
lang?: string;
|
|
170
|
+
/** Attest this customer's consent yourself: the session may then create a permission
|
|
171
|
+
* without Alyte's emailed code, within your account's limits. Requires a key with the
|
|
172
|
+
* `mandates:attest` scope and merchant-attested consent enabled for your account by Alyte
|
|
173
|
+
* (a contract is in place). The permission records that YOU attested it. */
|
|
174
|
+
merchantAttested?: true;
|
|
152
175
|
}) => Promise<BuyerSessionMint>;
|
|
153
176
|
};
|
|
154
177
|
}
|
package/dist/merchant.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { Transport } from './http.js';
|
|
2
2
|
/**
|
|
3
3
|
* Merchant integration client — drives the `/v1/integration/*` surface with a
|
|
4
|
-
* console-minted API token (`merchant:read` / `merchant:write` scopes
|
|
4
|
+
* console-minted API token (`merchant:read` / `merchant:write` scopes; `merchant:admin` for
|
|
5
|
+
* creating or deleting shops and linking a PSP — the "full" console preset).
|
|
5
6
|
*
|
|
6
7
|
* SERVER-SIDE ONLY: the API token is a secret. Never ship it to a browser.
|
|
7
8
|
*
|
|
@@ -100,6 +101,7 @@ export class AlyteMerchant {
|
|
|
100
101
|
* Attest YOUR authenticated user → a single-use redeem link (15-min TTL).
|
|
101
102
|
* Redirect the user to `baseUrl + redeemPath`; the buyer-session cookie and
|
|
102
103
|
* the shop's authorize page take over from there.
|
|
104
|
+
* Unknown fields are rejected with 400 and error.details.fields.
|
|
103
105
|
*/
|
|
104
106
|
mint: (input) => this.t.request('POST', '/v1/integration/buyer-sessions', input),
|
|
105
107
|
};
|
package/dist/types.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export interface Merchant {
|
|
|
19
19
|
/** Public discovery opt-in (default false) — see AlyteMerchant.updateShopDiscovery. */
|
|
20
20
|
discoverable?: boolean;
|
|
21
21
|
imageUrl?: string;
|
|
22
|
-
/**
|
|
22
|
+
/** Up to three partner origins (space- or comma-separated) allowed to embed the authorize page and call the buyer API from a browser (G14, L2). */
|
|
23
23
|
embedOrigin?: string;
|
|
24
24
|
}
|
|
25
25
|
export interface EventItem {
|
|
@@ -180,6 +180,7 @@ export interface MerchantInsights {
|
|
|
180
180
|
tierTitle: string;
|
|
181
181
|
eventTitle: string;
|
|
182
182
|
queued: number;
|
|
183
|
+
paused: number;
|
|
183
184
|
fired: number;
|
|
184
185
|
failed: number;
|
|
185
186
|
cancelled: number;
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Merchant onboarding, end to end: shop → PSP → event → tier → your user shopping.
|
|
3
3
|
*
|
|
4
4
|
* ALYTE_BASE_URL=https://alyte-sandbox-….run.app \
|
|
5
|
-
* ALYTE_API_TOKEN=<console-minted, merchant:read+merchant:write> \
|
|
5
|
+
* ALYTE_API_TOKEN=<console-minted, the "full" preset: merchant:read+merchant:write+merchant:admin> \
|
|
6
6
|
* npx tsx merchant-onboard.ts
|
|
7
7
|
*/
|
|
8
8
|
import { AlyteMerchant } from '@alytegen/sdk';
|
package/package.json
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alytegen/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Alyte client SDK
|
|
3
|
+
"version": "0.5.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
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
|
+
"./browser": {
|
|
10
|
+
"types": "./dist/browser.d.ts",
|
|
11
|
+
"import": "./dist/browser.js"
|
|
12
|
+
},
|
|
9
13
|
".": {
|
|
10
14
|
"types": "./dist/index.d.ts",
|
|
11
15
|
"import": "./dist/index.js"
|
|
@@ -14,6 +18,7 @@
|
|
|
14
18
|
"files": [
|
|
15
19
|
"dist",
|
|
16
20
|
"QUICKSTART.md",
|
|
21
|
+
"BROWSER.md",
|
|
17
22
|
"examples"
|
|
18
23
|
],
|
|
19
24
|
"scripts": {
|