@stripe/link-sdk 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stripe, LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # `@stripe/link-sdk`
2
+
3
+ Node.js SDK for agents that use Link. It provides typed resources for Link APIs
4
+ and accepts an access token from your application.
5
+
6
+ The SDK does not perform login, persist credentials, or own refresh tokens.
7
+ Authentication state and user-facing authorization flows belong to the CLI or
8
+ application embedding the SDK.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install @stripe/link-sdk
14
+ ```
15
+
16
+ The package is ESM-only and requires Node.js 20 or newer.
17
+
18
+ ## Quick start
19
+
20
+ Pass an access token when creating the client:
21
+
22
+ ```ts
23
+ import Link from '@stripe/link-sdk';
24
+
25
+ const link = new Link({ accessToken: process.env.LINK_ACCESS_TOKEN! });
26
+
27
+ const paymentMethods = await link.paymentMethods.list();
28
+ ```
29
+
30
+ Use a fixed token for a short-lived job or when the caller replaces the entire
31
+ client as credentials change.
32
+
33
+ ## Credentials
34
+
35
+ Exactly one credential option is required.
36
+
37
+ ### Dynamic access tokens
38
+
39
+ When your application manages expiring credentials, provide `getAccessToken`.
40
+ The SDK calls it for each request. After a 401 response, the SDK calls it once
41
+ with `forceRefresh: true` and retries the request with the returned token.
42
+
43
+ ```ts
44
+ const link = new Link({
45
+ getAccessToken: async ({ forceRefresh } = {}) =>
46
+ credentialManager.getLinkAccessToken({ forceRefresh }),
47
+ });
48
+ ```
49
+
50
+ The credential manager should coalesce concurrent refreshes if several
51
+ requests can receive a 401 at the same time. A client configured with a fixed
52
+ `accessToken` does not retry a 401 because it cannot obtain a different token.
53
+
54
+ ## User-approved purchase flow
55
+
56
+ Amounts are expressed in the currency's minor unit, such as cents for USD.
57
+ `context` must be at least 100 characters and should tell the user what the
58
+ agent is buying and why.
59
+
60
+ ```ts
61
+ const methods = await link.paymentMethods.list();
62
+ const paymentMethod = methods.find((method) => method.is_default) ?? methods[0];
63
+
64
+ if (!paymentMethod) {
65
+ throw new Error('The user needs to add a Link payment method.');
66
+ }
67
+
68
+ const spendRequest = await link.spendRequests.create({
69
+ payment_details: paymentMethod.id,
70
+ credential_type: 'card',
71
+ amount: 2599,
72
+ currency: 'usd',
73
+ merchant_name: 'Acme',
74
+ merchant_url: 'https://acme.example',
75
+ context:
76
+ 'The user asked the agent to buy the selected item from Acme for $25.99, including the displayed shipping cost.',
77
+ });
78
+
79
+ const approval = await link.spendRequests.requestApproval(spendRequest.id);
80
+ await sendToUser(`Approve this purchase: ${approval.approval_url}`);
81
+ await saveRunState({ spendRequestId: spendRequest.id });
82
+ ```
83
+
84
+ Retrieve the request in a later agent run:
85
+
86
+ ```ts
87
+ const result = await link.spendRequests.retrieve(state.spendRequestId);
88
+
89
+ if (!result) {
90
+ throw new Error('Spend request not found.');
91
+ }
92
+
93
+ switch (result.status) {
94
+ case 'approved':
95
+ // Use the returned credential without placing it in logs or chat.
96
+ break;
97
+ case 'created':
98
+ return { status: 'approval_not_requested' };
99
+ case 'pending_approval':
100
+ return { status: 'waiting_for_user_approval' };
101
+ case 'requires_action': {
102
+ const action = result.status_details?.requires_action?.next_action;
103
+ return action?.resolution === 'auto_resume'
104
+ ? { status: 'retry_later' }
105
+ : action;
106
+ }
107
+ case 'denied':
108
+ case 'expired':
109
+ case 'succeeded':
110
+ case 'failed':
111
+ case 'canceled':
112
+ return { status: result.status };
113
+ }
114
+ ```
115
+
116
+ Only a `requires_action` result whose `resolution` is `auto_resume` should be
117
+ polled automatically. For any other resolution, surface the action to the user
118
+ and follow its instructions. Keep returned card or shared-payment-token
119
+ credentials out of model context, logs, and user-visible messages.
120
+
121
+ ## Configuration
122
+
123
+ ```ts
124
+ const link = new Link({
125
+ accessToken,
126
+ fetch,
127
+ defaultHeaders: { 'X-Agent-Version': 'acme-agent/1.0' },
128
+ verbose: true,
129
+ logger: { debug: (message) => diagnostics.debug(message) },
130
+ apiBaseUrl: 'https://api.link.com',
131
+ spendRequestBaseUrl: 'https://api.link.com',
132
+ });
133
+ ```
134
+
135
+ Verbose logging includes request methods, URLs, and response status codes. It
136
+ does not include authorization headers or request and response bodies.
137
+
138
+ ## Errors
139
+
140
+ The SDK throws typed errors:
141
+
142
+ - `LinkConfigurationError` for invalid or missing client configuration
143
+ - `LinkTransportError` when a request cannot reach Link
144
+ - `LinkApiError` for non-success API responses
145
+ - `LinkResponseError` when a successful response has an invalid shape
146
+
147
+ `LinkApiError` includes `status`, `code`, and structured `details` fields for
148
+ programmatic handling.
149
+
150
+ ```ts
151
+ import { LinkApiError } from '@stripe/link-sdk';
152
+
153
+ try {
154
+ await link.spendRequests.retrieve('spend_request_id');
155
+ } catch (error) {
156
+ if (error instanceof LinkApiError) {
157
+ diagnostics.error({
158
+ status: error.status,
159
+ code: error.code,
160
+ details: error.details,
161
+ });
162
+ }
163
+ throw error;
164
+ }
165
+ ```
166
+
167
+ ## Client resources
168
+
169
+ - `spendRequests` — create, approve, retrieve, update, cancel, and list
170
+ - `paymentMethods` — list Link payment methods
171
+ - `shippingAddresses` — list shipping addresses
172
+ - `userInfo` — retrieve Link user information
173
+ - `transactions` — list transactions
174
+ - `sources` — list connected sources
175
+ - `balances` — list balances
176
+ - `webBotAuth` — sign URLs for Web Bot Auth
177
+ - `reports` — report agent outcomes
@@ -0,0 +1,413 @@
1
+ type JsonPrimitive = string | number | boolean | null;
2
+ type JsonValue = JsonPrimitive | JsonValue[] | {
3
+ [key: string]: JsonValue;
4
+ };
5
+ interface LineItem {
6
+ name: string;
7
+ url?: string;
8
+ image_url?: string;
9
+ description?: string;
10
+ sku?: string;
11
+ totals?: Total[];
12
+ quantity?: number;
13
+ unit_amount?: number;
14
+ product_url?: string;
15
+ }
16
+ interface Total {
17
+ type: string;
18
+ display_text: string;
19
+ amount: number;
20
+ }
21
+ interface BillingAddress {
22
+ name: string;
23
+ line1: string;
24
+ line2?: string;
25
+ city?: string;
26
+ state?: string;
27
+ postal_code?: string;
28
+ country: string;
29
+ }
30
+ interface Card {
31
+ id: string;
32
+ brand: string;
33
+ exp_month: number;
34
+ exp_year: number;
35
+ number: string;
36
+ cvc?: string;
37
+ billing_address?: BillingAddress;
38
+ valid_until?: string;
39
+ }
40
+ /** Known statuses, while remaining forward-compatible with new API values. */
41
+ type SpendRequestStatus = 'created' | 'pending_approval' | 'expired' | 'approved' | 'denied' | 'succeeded' | 'failed' | 'canceled' | 'requires_action' | (string & Record<never, never>);
42
+ type NextActionType = 'ssn_verification' | 'identity_verification' | 'contact_support' | 'select_payment_method' | 'add_payment_method' | 'update_payment_method' | 're_authorize' | 'three_d_secure' | 'three_d_secure_retry';
43
+ type NextActionResolution = 'auto_resume' | 'create_new_spend_request' | 'create_new_spend_request_after_completion';
44
+ interface NextAction {
45
+ type: NextActionType;
46
+ resolution: NextActionResolution;
47
+ display_message: string;
48
+ action_url: string | null;
49
+ expires_at?: number | null;
50
+ }
51
+ interface SpendRequestStatusDetails {
52
+ requires_action?: {
53
+ failure_code?: string;
54
+ next_action: NextAction;
55
+ };
56
+ }
57
+ type CredentialType = 'shared_payment_token' | 'card';
58
+ interface ApprovalDetail {
59
+ approved_at: number;
60
+ approval_method: 'click' | 'programmatic' | 'voice';
61
+ app_name: string;
62
+ external_user_id: string;
63
+ ip_address?: string;
64
+ user_agent?: string;
65
+ device_type?: 'mobile' | 'web';
66
+ agent_log_id?: string;
67
+ external_user_name?: string;
68
+ external_session_id?: string;
69
+ authentication_method?: 'biometric_face' | 'biometric_fingerprint' | 'passkey';
70
+ }
71
+ interface SharedPaymentToken {
72
+ id: string;
73
+ billing_address?: BillingAddress;
74
+ valid_until?: string;
75
+ }
76
+ interface RefundDetails {
77
+ amount: number;
78
+ currency: string;
79
+ state: string;
80
+ created: number;
81
+ }
82
+ interface PaymentStatusDetails {
83
+ outcome: 'success' | 'failure';
84
+ code?: string | null;
85
+ decline_code?: string | null;
86
+ amount: number;
87
+ currency: string;
88
+ created?: number | null;
89
+ refund_details?: RefundDetails | null;
90
+ }
91
+ interface SpendRequest {
92
+ id: string;
93
+ merchant_name?: string;
94
+ merchant_url?: string;
95
+ context?: string;
96
+ amount?: number;
97
+ currency?: string;
98
+ line_items?: LineItem[];
99
+ totals?: Total[];
100
+ payment_method?: string;
101
+ payment_details?: string;
102
+ credential_type?: CredentialType;
103
+ network_id?: string;
104
+ card_brand?: string;
105
+ card_last4?: string;
106
+ status: SpendRequestStatus;
107
+ approval_url?: string;
108
+ card?: Card;
109
+ shared_payment_token?: SharedPaymentToken | null;
110
+ link_pay_token?: string;
111
+ payment_status_details?: PaymentStatusDetails | null;
112
+ status_details?: SpendRequestStatusDetails | null;
113
+ link_transaction_id?: string;
114
+ activity_url?: string;
115
+ metadata?: Record<string, string>;
116
+ expires_at?: number;
117
+ created_at: string;
118
+ updated_at: string;
119
+ }
120
+ interface RequestApprovalResponse {
121
+ id: string;
122
+ approval_url: string;
123
+ }
124
+ interface CardDetails {
125
+ brand: string;
126
+ last4: string;
127
+ exp_month: number;
128
+ exp_year: number;
129
+ }
130
+ interface BankAccountDetails {
131
+ last4: string;
132
+ bank_name?: string;
133
+ }
134
+ interface UserInfo {
135
+ email?: string | null;
136
+ name?: string | null;
137
+ first_name?: string | null;
138
+ last_name?: string | null;
139
+ phone?: string | null;
140
+ }
141
+ interface ProductCapability {
142
+ eligible: boolean;
143
+ ineligibility_reasons: string[];
144
+ }
145
+ interface PaymentMethod {
146
+ id: string;
147
+ type: string;
148
+ is_default: boolean;
149
+ nickname?: string;
150
+ card_details?: CardDetails;
151
+ bank_account_details?: BankAccountDetails;
152
+ capabilities?: Record<string, ProductCapability>;
153
+ }
154
+ interface ShippingAddress {
155
+ name: string | null;
156
+ line_1: string | null;
157
+ line_2: string | null;
158
+ locality: string | null;
159
+ dependent_locality: string | null;
160
+ administrative_area: string | null;
161
+ postal_code: string | null;
162
+ sorting_code: string | null;
163
+ country_code: string | null;
164
+ }
165
+ interface ShippingAddressRecord {
166
+ id: string;
167
+ is_default: boolean;
168
+ nickname: string | null;
169
+ address: ShippingAddress | null;
170
+ }
171
+ type TransactionOrigin = 'link' | 'external_connection';
172
+ interface Transaction {
173
+ id: string;
174
+ source_id: string | null;
175
+ amount: number;
176
+ currency: string;
177
+ created_date: string;
178
+ description: string;
179
+ origin: TransactionOrigin;
180
+ category: string | null;
181
+ status: string;
182
+ }
183
+ interface TransactionsPage {
184
+ data: Transaction[];
185
+ has_more?: boolean;
186
+ [key: string]: unknown;
187
+ }
188
+ interface Source {
189
+ id?: string | null;
190
+ name?: string | null;
191
+ type?: string | null;
192
+ capabilities?: Record<string, unknown> | null;
193
+ external_connection?: Record<string, unknown> | null;
194
+ granted_actions?: string[] | null;
195
+ bank_account?: Record<string, unknown> | null;
196
+ card?: Record<string, unknown> | null;
197
+ [key: string]: unknown;
198
+ }
199
+ interface SourcesPage {
200
+ data: Source[];
201
+ has_more?: boolean;
202
+ [key: string]: unknown;
203
+ }
204
+ interface CashBalance {
205
+ available: Record<string, number>;
206
+ }
207
+ interface CreditBalance {
208
+ used: Record<string, number>;
209
+ }
210
+ interface Balance {
211
+ source_id: string;
212
+ type: 'cash' | 'credit';
213
+ cash?: CashBalance | null;
214
+ credit?: CreditBalance | null;
215
+ current: number;
216
+ currency: string;
217
+ as_of: string;
218
+ [key: string]: unknown;
219
+ }
220
+ interface BalancesPage {
221
+ data: Balance[];
222
+ has_more?: boolean;
223
+ [key: string]: unknown;
224
+ }
225
+ interface WebBotAuthBlock {
226
+ signature: string;
227
+ signature_input: string;
228
+ signature_agent: string;
229
+ authority: string;
230
+ expires_at: string;
231
+ }
232
+
233
+ interface GetAccessTokenOptions {
234
+ forceRefresh?: boolean;
235
+ }
236
+ type AccessTokenProvider = (options?: GetAccessTokenOptions) => Promise<string> | string;
237
+ interface CreateSpendRequestParams {
238
+ payment_details?: string;
239
+ credential_type?: CredentialType;
240
+ network_id?: string;
241
+ execution_method?: 'link_pay_token';
242
+ merchant_account_id?: string;
243
+ amount?: number;
244
+ currency?: string;
245
+ merchant_name?: string;
246
+ merchant_url?: string;
247
+ context: string;
248
+ line_items?: LineItem[];
249
+ totals?: Total[];
250
+ request_approval?: boolean;
251
+ test?: boolean;
252
+ approval_details?: ApprovalDetail;
253
+ metadata?: Record<string, string>;
254
+ }
255
+ interface UpdateSpendRequestParams {
256
+ payment_details?: string;
257
+ amount?: number;
258
+ merchant_url?: string;
259
+ profile_id?: string;
260
+ merchant_id?: string;
261
+ currency?: string;
262
+ line_items?: LineItem[];
263
+ totals?: Total[];
264
+ }
265
+ interface ISpendRequestResource {
266
+ list(opts?: {
267
+ includeHistory?: boolean;
268
+ }): Promise<SpendRequest[]>;
269
+ create(params: CreateSpendRequestParams): Promise<SpendRequest>;
270
+ update(id: string, params: UpdateSpendRequestParams): Promise<SpendRequest>;
271
+ requestApproval(id: string): Promise<RequestApprovalResponse>;
272
+ cancel(id: string): Promise<SpendRequest>;
273
+ retrieve(id: string, opts?: {
274
+ include?: string[];
275
+ }): Promise<SpendRequest | null>;
276
+ }
277
+ interface IPaymentMethodsResource {
278
+ list(): Promise<PaymentMethod[]>;
279
+ }
280
+ interface IShippingAddressResource {
281
+ list(): Promise<ShippingAddressRecord[]>;
282
+ }
283
+ interface IUserInfoResource {
284
+ retrieve(): Promise<UserInfo>;
285
+ }
286
+ interface IWebBotAuthResource {
287
+ signUrl(url: string): Promise<WebBotAuthBlock>;
288
+ }
289
+ interface ListTransactionsParams {
290
+ limit?: number;
291
+ starting_after?: string;
292
+ ending_before?: string;
293
+ start_date?: string;
294
+ end_date?: string;
295
+ category?: string;
296
+ origin?: TransactionOrigin;
297
+ sources?: string[];
298
+ }
299
+ interface ITransactionsResource {
300
+ list(params?: ListTransactionsParams): Promise<TransactionsPage>;
301
+ }
302
+ interface ListSourcesParams {
303
+ limit?: number;
304
+ starting_after?: string;
305
+ ending_before?: string;
306
+ }
307
+ interface ISourcesResource {
308
+ list(params?: ListSourcesParams): Promise<SourcesPage>;
309
+ }
310
+ interface ListBalancesParams {
311
+ sources?: string[];
312
+ limit?: number;
313
+ starting_after?: string;
314
+ ending_before?: string;
315
+ }
316
+ interface IBalancesResource {
317
+ list(params?: ListBalancesParams): Promise<BalancesPage>;
318
+ }
319
+ declare const REPORT_OUTCOMES: readonly ["success", "blocked", "abandoned"];
320
+ type ReportOutcome = (typeof REPORT_OUTCOMES)[number];
321
+ declare const REPORT_TAGS: readonly ["stripe_checkout", "captcha", "anti_bot_script", "cdn_block", "waf_block", "dns_block", "rate_limited", "login_required", "3ds_challenge", "page_inaccessible", "timeout", "site_error", "payment_declined", "other"];
322
+ type ReportTag = (typeof REPORT_TAGS)[number];
323
+ interface CreateReportParams {
324
+ domain: string;
325
+ outcome: ReportOutcome;
326
+ spend_request_id: string;
327
+ tags?: ReportTag[];
328
+ step?: string;
329
+ freeform_context?: string;
330
+ }
331
+ interface ReportRecord {
332
+ object: string;
333
+ created_at: string;
334
+ domain: string;
335
+ outcome: string;
336
+ spend_request_id: string;
337
+ status: string;
338
+ }
339
+ interface IReportResource {
340
+ create(params: CreateReportParams): Promise<ReportRecord>;
341
+ }
342
+
343
+ interface LinkSdkLogger {
344
+ debug(message: string): void;
345
+ }
346
+ interface LinkClientOptions {
347
+ verbose?: boolean;
348
+ defaultHeaders?: Record<string, string>;
349
+ fetch?: typeof globalThis.fetch;
350
+ apiBaseUrl?: string;
351
+ spendRequestBaseUrl?: string;
352
+ logger?: LinkSdkLogger;
353
+ }
354
+ type LinkOptions = LinkClientOptions & ({
355
+ accessToken: string;
356
+ getAccessToken?: never;
357
+ } | {
358
+ accessToken?: never;
359
+ getAccessToken: AccessTokenProvider;
360
+ });
361
+
362
+ declare class Link {
363
+ readonly spendRequests: ISpendRequestResource;
364
+ readonly paymentMethods: IPaymentMethodsResource;
365
+ readonly shippingAddresses: IShippingAddressResource;
366
+ readonly userInfo: IUserInfoResource;
367
+ readonly transactions: ITransactionsResource;
368
+ readonly sources: ISourcesResource;
369
+ readonly balances: IBalancesResource;
370
+ readonly webBotAuth: IWebBotAuthResource;
371
+ readonly reports: IReportResource;
372
+ constructor(options: LinkOptions);
373
+ }
374
+
375
+ declare class LinkSdkError extends Error {
376
+ readonly code: string;
377
+ constructor(message: string, options?: {
378
+ code?: string;
379
+ cause?: unknown;
380
+ });
381
+ }
382
+ declare class LinkResponseError extends LinkSdkError {
383
+ readonly status: number;
384
+ constructor(operation: string, status: number, options?: {
385
+ cause?: unknown;
386
+ });
387
+ }
388
+ declare class LinkConfigurationError extends LinkSdkError {
389
+ constructor(message: string, options?: {
390
+ cause?: unknown;
391
+ });
392
+ }
393
+ declare class LinkTransportError extends LinkSdkError {
394
+ constructor(message: string, options?: {
395
+ cause?: unknown;
396
+ });
397
+ }
398
+ declare class LinkApiError extends LinkSdkError {
399
+ readonly status: number;
400
+ readonly rawBody: string | undefined;
401
+ readonly details?: unknown;
402
+ constructor(message: string, options: {
403
+ status: number;
404
+ code?: string;
405
+ rawBody?: string;
406
+ details?: unknown;
407
+ cause?: unknown;
408
+ });
409
+ }
410
+
411
+ declare function getDuplicateSpendRequest(error: unknown): SpendRequest | null;
412
+
413
+ export { type AccessTokenProvider, type ApprovalDetail, type Balance, type BalancesPage, type BankAccountDetails, type BillingAddress, type Card, type CardDetails, type CashBalance, type CreateReportParams, type CreateSpendRequestParams, type CredentialType, type CreditBalance, type GetAccessTokenOptions, type IBalancesResource, type IPaymentMethodsResource, type IReportResource, type IShippingAddressResource, type ISourcesResource, type ISpendRequestResource, type ITransactionsResource, type IUserInfoResource, type IWebBotAuthResource, type JsonPrimitive, type JsonValue, type LineItem, Link, LinkApiError, LinkConfigurationError, type LinkOptions, LinkResponseError, LinkSdkError, type LinkSdkLogger, LinkTransportError, type ListBalancesParams, type ListSourcesParams, type ListTransactionsParams, type NextAction, type NextActionResolution, type NextActionType, type PaymentMethod, type PaymentStatusDetails, type ProductCapability, REPORT_OUTCOMES, REPORT_TAGS, type RefundDetails, type ReportOutcome, type ReportRecord, type ReportTag, type RequestApprovalResponse, type SharedPaymentToken, type ShippingAddress, type ShippingAddressRecord, type Source, type SourcesPage, type SpendRequest, type SpendRequestStatus, type SpendRequestStatusDetails, type Total, type Transaction, type TransactionOrigin, type TransactionsPage, type UpdateSpendRequestParams, type UserInfo, type WebBotAuthBlock, Link as default, getDuplicateSpendRequest };