@tenthbilling/node 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +133 -2
- package/dist/client.d.ts +115 -0
- package/dist/client.js +220 -0
- package/dist/errors.d.ts +32 -0
- package/dist/errors.js +37 -0
- package/dist/generated/openapi.d.ts +3208 -0
- package/dist/generated/openapi.js +1 -0
- package/dist/http.d.ts +46 -0
- package/dist/http.js +165 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +6 -0
- package/dist/token.d.ts +16 -0
- package/dist/token.js +44 -0
- package/dist/types.d.ts +81 -0
- package/dist/types.js +38 -0
- package/dist/webhook.d.ts +16 -0
- package/dist/webhook.js +85 -0
- package/package.json +44 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** Sent in the User-Agent. Must equal package.json's version (checked by version.test.ts). */
|
|
2
|
+
export declare const SDK_VERSION = "0.1.0";
|
|
3
|
+
export type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
|
4
|
+
/** Per-call overrides, accepted as the last argument of every resource method. */
|
|
5
|
+
export interface RequestOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Sent as `Idempotency-Key` on mutating requests; generated when left out. Pass your own (e.g.
|
|
8
|
+
* your job id) to make a retry from your side safe too.
|
|
9
|
+
*/
|
|
10
|
+
idempotencyKey?: string;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
maxRetries?: number;
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
}
|
|
15
|
+
export interface TransportConfig {
|
|
16
|
+
secretKey: string;
|
|
17
|
+
baseUrl: string;
|
|
18
|
+
timeoutMs: number;
|
|
19
|
+
maxRetries: number;
|
|
20
|
+
fetch: FetchLike;
|
|
21
|
+
}
|
|
22
|
+
type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
|
23
|
+
type Query = Record<string, string | number | boolean | undefined>;
|
|
24
|
+
export interface RequestSpec {
|
|
25
|
+
method: Method;
|
|
26
|
+
/** A constant, or built with {@link path} so every segment is encoded. */
|
|
27
|
+
path: string | (() => string);
|
|
28
|
+
query?: Query;
|
|
29
|
+
body?: unknown;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Fills a path template, encoding each value and refusing ones that would change the route. Built
|
|
33
|
+
* lazily inside request(), so a bad id rejects the returned promise instead of throwing.
|
|
34
|
+
*/
|
|
35
|
+
export declare function path(strings: TemplateStringsArray, ...values: string[]): () => string;
|
|
36
|
+
export declare function idempotencyKeyFor(options: RequestOptions | undefined): string;
|
|
37
|
+
export declare class Transport {
|
|
38
|
+
#private;
|
|
39
|
+
constructor(config: TransportConfig);
|
|
40
|
+
request<T>(spec: RequestSpec, options?: RequestOptions): Promise<T>;
|
|
41
|
+
}
|
|
42
|
+
/** Retry-After as delta-seconds or an HTTP date (RFC 9110 §10.2.3). */
|
|
43
|
+
export declare function parseRetryAfter(value: string | null, now?: number): number | undefined;
|
|
44
|
+
/** Exponential backoff with jitter: 50–100% of min(8 s, 0.5 s × 2^attempt). */
|
|
45
|
+
export declare function backoffMs(attempt: number): number;
|
|
46
|
+
export {};
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { TenthError } from './errors.js';
|
|
3
|
+
export const SDK_VERSION = '0.1.0';
|
|
4
|
+
const MAX_RETRY_AFTER_MS = 30_000;
|
|
5
|
+
const BACKOFF_BASE_MS = 500;
|
|
6
|
+
const BACKOFF_MAX_MS = 8_000;
|
|
7
|
+
const IDEMPOTENCY_KEY_RE = /^[\x21-\x7e]{1,255}$/;
|
|
8
|
+
export function path(strings, ...values) {
|
|
9
|
+
return () => {
|
|
10
|
+
let out = strings[0];
|
|
11
|
+
values.forEach((value, i) => {
|
|
12
|
+
out += segment(value) + strings[i + 1];
|
|
13
|
+
});
|
|
14
|
+
return out;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function segment(value) {
|
|
18
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > 255) {
|
|
19
|
+
throw new TenthError('invalid_argument', 'Ids must be non-empty strings of at most 255 characters.');
|
|
20
|
+
}
|
|
21
|
+
if (value === '.' || value === '..') {
|
|
22
|
+
throw new TenthError('invalid_argument', 'An id can’t be "." or "..".');
|
|
23
|
+
}
|
|
24
|
+
return encodeURIComponent(value);
|
|
25
|
+
}
|
|
26
|
+
export function idempotencyKeyFor(options) {
|
|
27
|
+
const key = options?.idempotencyKey ?? randomUUID();
|
|
28
|
+
if (!IDEMPOTENCY_KEY_RE.test(key)) {
|
|
29
|
+
throw new TenthError('invalid_argument', 'idempotencyKey must be 1–255 printable ASCII characters.');
|
|
30
|
+
}
|
|
31
|
+
return key;
|
|
32
|
+
}
|
|
33
|
+
export class Transport {
|
|
34
|
+
#config;
|
|
35
|
+
constructor(config) {
|
|
36
|
+
this.#config = config;
|
|
37
|
+
}
|
|
38
|
+
async request(spec, options = {}) {
|
|
39
|
+
const url = this.#url(spec);
|
|
40
|
+
const headers = {
|
|
41
|
+
authorization: `Bearer ${this.#config.secretKey}`,
|
|
42
|
+
accept: 'application/json',
|
|
43
|
+
'user-agent': `tenth-node/${SDK_VERSION}`,
|
|
44
|
+
};
|
|
45
|
+
let body;
|
|
46
|
+
if (spec.body !== undefined) {
|
|
47
|
+
headers['content-type'] = 'application/json';
|
|
48
|
+
body = JSON.stringify(spec.body);
|
|
49
|
+
}
|
|
50
|
+
if (spec.method !== 'GET')
|
|
51
|
+
headers['idempotency-key'] = idempotencyKeyFor(options);
|
|
52
|
+
const timeoutMs = options.timeoutMs ?? this.#config.timeoutMs;
|
|
53
|
+
const maxRetries = options.maxRetries ?? this.#config.maxRetries;
|
|
54
|
+
for (let attempt = 0;; attempt++) {
|
|
55
|
+
const canRetry = attempt < maxRetries;
|
|
56
|
+
throwIfAborted(options.signal);
|
|
57
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
58
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
59
|
+
let response;
|
|
60
|
+
let text;
|
|
61
|
+
try {
|
|
62
|
+
response = await this.#config.fetch(url, { method: spec.method, headers, body, signal });
|
|
63
|
+
text = await response.text();
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throwIfAborted(options.signal);
|
|
67
|
+
const timedOut = timeout.aborted;
|
|
68
|
+
if (canRetry) {
|
|
69
|
+
await sleep(backoffMs(attempt), options.signal);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
throw timedOut
|
|
73
|
+
? new TenthError('timeout', `Tenth didn't respond within ${timeoutMs} ms.`)
|
|
74
|
+
: new TenthError('network_error', 'Could not reach the Tenth API.');
|
|
75
|
+
}
|
|
76
|
+
if (response.ok)
|
|
77
|
+
return parseSuccess(response, text);
|
|
78
|
+
const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
|
|
79
|
+
if (canRetry && (response.status === 429 || response.status >= 500)) {
|
|
80
|
+
await sleep(retryAfterMs === undefined
|
|
81
|
+
? backoffMs(attempt)
|
|
82
|
+
: Math.min(retryAfterMs, MAX_RETRY_AFTER_MS), options.signal);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
throw problemError(response, text, retryAfterMs);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
#url(spec) {
|
|
89
|
+
const pathname = typeof spec.path === 'string' ? spec.path : spec.path();
|
|
90
|
+
const url = new URL(pathname, this.#config.baseUrl);
|
|
91
|
+
for (const [k, v] of Object.entries(spec.query ?? {})) {
|
|
92
|
+
if (v !== undefined)
|
|
93
|
+
url.searchParams.set(k, String(v));
|
|
94
|
+
}
|
|
95
|
+
return url.toString();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function parseSuccess(response, text) {
|
|
99
|
+
if (response.status === 204 || text.length === 0)
|
|
100
|
+
return undefined;
|
|
101
|
+
try {
|
|
102
|
+
return JSON.parse(text);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new TenthError('invalid_response', 'Tenth returned a response that is not JSON.', {
|
|
106
|
+
status: response.status,
|
|
107
|
+
requestId: requestIdOf(response),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function problemError(response, text, retryAfterMs) {
|
|
112
|
+
let problem = {};
|
|
113
|
+
try {
|
|
114
|
+
const parsed = JSON.parse(text);
|
|
115
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
116
|
+
problem = parsed;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
}
|
|
121
|
+
const code = typeof problem.code === 'string' ? problem.code : `http_${response.status}`;
|
|
122
|
+
const detail = typeof problem.detail === 'string' ? problem.detail : undefined;
|
|
123
|
+
const title = typeof problem.title === 'string' ? problem.title : undefined;
|
|
124
|
+
const requestId = requestIdOf(response) ??
|
|
125
|
+
(typeof problem.request_id === 'string' ? problem.request_id : undefined);
|
|
126
|
+
return new TenthError(code, detail ?? title ?? `Tenth returned HTTP ${response.status}.`, {
|
|
127
|
+
status: response.status,
|
|
128
|
+
detail,
|
|
129
|
+
requestId,
|
|
130
|
+
errors: problem.errors,
|
|
131
|
+
retryAfterSeconds: retryAfterMs === undefined ? undefined : Math.ceil(retryAfterMs / 1000),
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
function requestIdOf(response) {
|
|
135
|
+
return response.headers.get('x-request-id') ?? undefined;
|
|
136
|
+
}
|
|
137
|
+
export function parseRetryAfter(value, now = Date.now()) {
|
|
138
|
+
if (!value)
|
|
139
|
+
return undefined;
|
|
140
|
+
if (/^\d+$/.test(value.trim()))
|
|
141
|
+
return Number(value.trim()) * 1000;
|
|
142
|
+
const date = Date.parse(value);
|
|
143
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - now);
|
|
144
|
+
}
|
|
145
|
+
export function backoffMs(attempt) {
|
|
146
|
+
const ceiling = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** attempt);
|
|
147
|
+
return Math.round(ceiling * (0.5 + Math.random() * 0.5));
|
|
148
|
+
}
|
|
149
|
+
function throwIfAborted(signal) {
|
|
150
|
+
if (signal?.aborted)
|
|
151
|
+
throw new TenthError('aborted', 'The request was aborted.');
|
|
152
|
+
}
|
|
153
|
+
function sleep(ms, signal) {
|
|
154
|
+
return new Promise((resolve, reject) => {
|
|
155
|
+
const onAbort = () => {
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
reject(new TenthError('aborted', 'The request was aborted.'));
|
|
158
|
+
};
|
|
159
|
+
const timer = setTimeout(() => {
|
|
160
|
+
signal?.removeEventListener('abort', onAbort);
|
|
161
|
+
resolve();
|
|
162
|
+
}, ms);
|
|
163
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
164
|
+
});
|
|
165
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { Tenth, type TenthOptions } from './client.js';
|
|
2
|
+
export type * from './client.js';
|
|
3
|
+
export { TenthError, TenthWebhookError } from './errors.js';
|
|
4
|
+
export type { ClientErrorCode, TenthErrorInit, WebhookErrorReason } from './errors.js';
|
|
5
|
+
export { SDK_VERSION, type FetchLike, type RequestOptions } from './http.js';
|
|
6
|
+
export { mintCustomerToken, MAX_CUSTOMER_TOKEN_TTL_SECONDS, TENTH_TOKEN_ISSUER, type MintCustomerTokenInput, } from './token.js';
|
|
7
|
+
export { verifyWebhook, SIGNATURE_HEADER, type VerifyWebhookInput } from './webhook.js';
|
|
8
|
+
export { WEBHOOK_EVENT_TYPES } from './types.js';
|
|
9
|
+
export type * from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { Tenth } from './client.js';
|
|
2
|
+
export { TenthError, TenthWebhookError } from './errors.js';
|
|
3
|
+
export { SDK_VERSION } from './http.js';
|
|
4
|
+
export { mintCustomerToken, MAX_CUSTOMER_TOKEN_TTL_SECONDS, TENTH_TOKEN_ISSUER, } from './token.js';
|
|
5
|
+
export { verifyWebhook, SIGNATURE_HEADER } from './webhook.js';
|
|
6
|
+
export { WEBHOOK_EVENT_TYPES } from './types.js';
|
package/dist/token.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Environment } from './types.js';
|
|
2
|
+
export declare const TENTH_TOKEN_ISSUER = "https://api.tenthbilling.com";
|
|
3
|
+
export declare const MAX_CUSTOMER_TOKEN_TTL_SECONDS = 86400;
|
|
4
|
+
export interface MintCustomerTokenInput {
|
|
5
|
+
/** The app environment's customer token secret, from the dashboard. Keep it on your server. */
|
|
6
|
+
tokenSecret: string;
|
|
7
|
+
appId: string;
|
|
8
|
+
environment: Environment;
|
|
9
|
+
appUserId: string;
|
|
10
|
+
/** 1–86400; defaults to 3600. */
|
|
11
|
+
ttlSeconds?: number;
|
|
12
|
+
/** For tests. */
|
|
13
|
+
now?: Date;
|
|
14
|
+
}
|
|
15
|
+
/** Mints the JWT your app sends as `X-Customer-Token` with its publishable key. */
|
|
16
|
+
export declare function mintCustomerToken(input: MintCustomerTokenInput): string;
|
package/dist/token.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
import { TenthError } from './errors.js';
|
|
3
|
+
export const TENTH_TOKEN_ISSUER = 'https://api.tenthbilling.com';
|
|
4
|
+
export const MAX_CUSTOMER_TOKEN_TTL_SECONDS = 86_400;
|
|
5
|
+
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
|
|
6
|
+
export function mintCustomerToken(input) {
|
|
7
|
+
const { tokenSecret, appId, environment, appUserId } = input;
|
|
8
|
+
const ttl = input.ttlSeconds ?? 3600;
|
|
9
|
+
if (typeof tokenSecret !== 'string' || tokenSecret.length === 0) {
|
|
10
|
+
throw new TenthError('invalid_argument', 'tokenSecret is required.');
|
|
11
|
+
}
|
|
12
|
+
if (typeof appId !== 'string' || appId.length === 0 || appId.length > 64) {
|
|
13
|
+
throw new TenthError('invalid_argument', 'appId is required.');
|
|
14
|
+
}
|
|
15
|
+
if (environment !== 'test' && environment !== 'live') {
|
|
16
|
+
throw new TenthError('invalid_argument', "environment must be 'test' or 'live'.");
|
|
17
|
+
}
|
|
18
|
+
if (typeof appUserId !== 'string' ||
|
|
19
|
+
appUserId.length === 0 ||
|
|
20
|
+
appUserId.length > 255 ||
|
|
21
|
+
CONTROL.test(appUserId) ||
|
|
22
|
+
appUserId.trim() !== appUserId) {
|
|
23
|
+
throw new TenthError('invalid_argument', 'appUserId must be 1–255 characters, without control characters or surrounding spaces.');
|
|
24
|
+
}
|
|
25
|
+
if (!Number.isInteger(ttl) || ttl < 1 || ttl > MAX_CUSTOMER_TOKEN_TTL_SECONDS) {
|
|
26
|
+
throw new TenthError('invalid_argument', `ttlSeconds must be an integer from 1 to ${MAX_CUSTOMER_TOKEN_TTL_SECONDS}.`);
|
|
27
|
+
}
|
|
28
|
+
const iat = Math.floor((input.now?.getTime() ?? Date.now()) / 1000);
|
|
29
|
+
const header = base64url(JSON.stringify({ alg: 'HS256' }));
|
|
30
|
+
const payload = base64url(JSON.stringify({
|
|
31
|
+
iss: TENTH_TOKEN_ISSUER,
|
|
32
|
+
aud: `tenth:${appId}:${environment}`,
|
|
33
|
+
sub: appUserId,
|
|
34
|
+
iat,
|
|
35
|
+
exp: iat + ttl,
|
|
36
|
+
}));
|
|
37
|
+
const signature = createHmac('sha256', tokenSecret)
|
|
38
|
+
.update(`${header}.${payload}`)
|
|
39
|
+
.digest('base64url');
|
|
40
|
+
return `${header}.${payload}.${signature}`;
|
|
41
|
+
}
|
|
42
|
+
function base64url(value) {
|
|
43
|
+
return Buffer.from(value, 'utf8').toString('base64url');
|
|
44
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { components, paths } from './generated/openapi.js';
|
|
2
|
+
type Schemas = components['schemas'];
|
|
3
|
+
export type Environment = 'test' | 'live';
|
|
4
|
+
export type CustomerState = Schemas['CustomerState'];
|
|
5
|
+
export type EntitlementState = Schemas['EntitlementState'];
|
|
6
|
+
export type CreditBalance = Schemas['CreditBalance'];
|
|
7
|
+
export type CreditTransaction = Schemas['CreditTransaction'];
|
|
8
|
+
export type CreditHold = Schemas['CreditHold'];
|
|
9
|
+
export type SubscriptionSummary = Schemas['SubscriptionSummary'];
|
|
10
|
+
export type Grant = Schemas['Grant'];
|
|
11
|
+
export type RevenueTransaction = Schemas['RevenueTransaction'];
|
|
12
|
+
/** An entry in the pull feed (`GET /v1/events`); `payload` is the webhook body. */
|
|
13
|
+
export type FeedEvent = Schemas['Event'];
|
|
14
|
+
export type Problem = Schemas['Problem'];
|
|
15
|
+
type Method = 'get' | 'post' | 'patch' | 'delete';
|
|
16
|
+
type Op<P extends keyof paths, M extends Method> = NonNullable<paths[P][M]>;
|
|
17
|
+
type Json<R> = R extends {
|
|
18
|
+
content: {
|
|
19
|
+
'application/json': infer B;
|
|
20
|
+
};
|
|
21
|
+
} ? B : undefined;
|
|
22
|
+
type Ok<R> = R extends {
|
|
23
|
+
200: infer X;
|
|
24
|
+
} ? X : R extends {
|
|
25
|
+
201: infer X;
|
|
26
|
+
} ? X : never;
|
|
27
|
+
/** JSON request body of an operation. */
|
|
28
|
+
export type BodyOf<P extends keyof paths, M extends Method> = Op<P, M> extends {
|
|
29
|
+
requestBody: {
|
|
30
|
+
content: {
|
|
31
|
+
'application/json': infer B;
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
} ? B : Op<P, M> extends {
|
|
35
|
+
requestBody?: {
|
|
36
|
+
content: {
|
|
37
|
+
'application/json': infer B;
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
} ? B : never;
|
|
41
|
+
/** Query parameters of an operation. */
|
|
42
|
+
export type QueryOf<P extends keyof paths, M extends Method> = NonNullable<Op<P, M>['parameters']['query']>;
|
|
43
|
+
/** Success response of an operation (200 or 201). */
|
|
44
|
+
export type ResponseOf<P extends keyof paths, M extends Method> = Json<Ok<Op<P, M>['responses']>>;
|
|
45
|
+
export type CustomerEntitlements = ResponseOf<'/v1/customers/{id}/entitlements', 'get'>;
|
|
46
|
+
export type AliasResult = ResponseOf<'/v1/customers/{id}/alias', 'post'>;
|
|
47
|
+
export type CustomerUpdate = BodyOf<'/v1/customers/{id}', 'patch'>;
|
|
48
|
+
export type CustomerCredits = ResponseOf<'/v1/customers/{id}/credits', 'get'>;
|
|
49
|
+
export type CreditDebitResult = ResponseOf<'/v1/customers/{id}/credits/{type}/debit', 'post'>;
|
|
50
|
+
export type GrantCreate = BodyOf<'/v1/customers/{id}/grants', 'post'>;
|
|
51
|
+
export type EventsPage = ResponseOf<'/v1/events', 'get'>;
|
|
52
|
+
export type RevenueTransactionsPage = ResponseOf<'/v1/revenue/transactions', 'get'>;
|
|
53
|
+
export type CheckoutSession = ResponseOf<'/v1/checkout-sessions', 'post'>;
|
|
54
|
+
export type PaymentIntent = ResponseOf<'/v1/payment-intents', 'post'>;
|
|
55
|
+
export type ReceiptResult = ResponseOf<'/v1/receipts', 'post'>;
|
|
56
|
+
export type SubscriptionChange = BodyOf<'/v1/subscriptions/{id}/change', 'post'>;
|
|
57
|
+
export type SubscriptionAnchor = BodyOf<'/v1/subscriptions/{id}/anchor', 'post'>;
|
|
58
|
+
/** Outbound event types: every ledger event type plus the dashboard's `test`. */
|
|
59
|
+
export declare const WEBHOOK_EVENT_TYPES: readonly ["subscription.started", "trial.started", "trial.converted", "trial.canceled", "subscription.renewed", "subscription.plan_changed", "subscription.product_changed", "subscription.cancel_scheduled", "subscription.uncanceled", "subscription.billing_issue", "subscription.recovered", "subscription.paused", "subscription.resumed", "subscription.price_increase", "subscription.extended", "subscription.revoked", "subscription.expired", "purchase.completed", "refund.issued", "dispute.opened", "dispute.closed", "grant.created", "grant.revoked", "entitlement.granted", "entitlement.revoked", "credits.granted", "credits.debited", "credits.expired", "credits.clawed_back", "customer.aliased", "customer.merged", "customer.deleted", "subscription.anchor_changed", "purchase.transferred", "purchase.shared", "test"];
|
|
60
|
+
export type KnownWebhookEventType = (typeof WEBHOOK_EVENT_TYPES)[number];
|
|
61
|
+
/** Known types autocomplete; new ones may arrive without a version bump (additive changes). */
|
|
62
|
+
export type WebhookEventType = KnownWebhookEventType | (string & {});
|
|
63
|
+
/**
|
|
64
|
+
* A webhook body. `customer` is the full customer state at the end of the transaction
|
|
65
|
+
* that caused the event, or null for `test` events.
|
|
66
|
+
*/
|
|
67
|
+
export interface WebhookEvent {
|
|
68
|
+
id: string;
|
|
69
|
+
type: WebhookEventType;
|
|
70
|
+
/** Payload version, currently `2026-10-25`. */
|
|
71
|
+
version: string;
|
|
72
|
+
created_at: string;
|
|
73
|
+
occurred_at: string;
|
|
74
|
+
app_id: string;
|
|
75
|
+
environment: Environment;
|
|
76
|
+
data: {
|
|
77
|
+
[key: string]: unknown;
|
|
78
|
+
};
|
|
79
|
+
customer: CustomerState | null;
|
|
80
|
+
}
|
|
81
|
+
export {};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export const WEBHOOK_EVENT_TYPES = [
|
|
2
|
+
'subscription.started',
|
|
3
|
+
'trial.started',
|
|
4
|
+
'trial.converted',
|
|
5
|
+
'trial.canceled',
|
|
6
|
+
'subscription.renewed',
|
|
7
|
+
'subscription.plan_changed',
|
|
8
|
+
'subscription.product_changed',
|
|
9
|
+
'subscription.cancel_scheduled',
|
|
10
|
+
'subscription.uncanceled',
|
|
11
|
+
'subscription.billing_issue',
|
|
12
|
+
'subscription.recovered',
|
|
13
|
+
'subscription.paused',
|
|
14
|
+
'subscription.resumed',
|
|
15
|
+
'subscription.price_increase',
|
|
16
|
+
'subscription.extended',
|
|
17
|
+
'subscription.revoked',
|
|
18
|
+
'subscription.expired',
|
|
19
|
+
'purchase.completed',
|
|
20
|
+
'refund.issued',
|
|
21
|
+
'dispute.opened',
|
|
22
|
+
'dispute.closed',
|
|
23
|
+
'grant.created',
|
|
24
|
+
'grant.revoked',
|
|
25
|
+
'entitlement.granted',
|
|
26
|
+
'entitlement.revoked',
|
|
27
|
+
'credits.granted',
|
|
28
|
+
'credits.debited',
|
|
29
|
+
'credits.expired',
|
|
30
|
+
'credits.clawed_back',
|
|
31
|
+
'customer.aliased',
|
|
32
|
+
'customer.merged',
|
|
33
|
+
'customer.deleted',
|
|
34
|
+
'subscription.anchor_changed',
|
|
35
|
+
'purchase.transferred',
|
|
36
|
+
'purchase.shared',
|
|
37
|
+
'test',
|
|
38
|
+
];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { WebhookEvent } from './types.js';
|
|
2
|
+
export declare const SIGNATURE_HEADER = "tenth-signature";
|
|
3
|
+
export interface VerifyWebhookInput {
|
|
4
|
+
/** The raw request body, exactly as received. Not a parsed or re-serialized object. */
|
|
5
|
+
payload: string | Buffer;
|
|
6
|
+
/** The `Tenth-Signature` header. */
|
|
7
|
+
header: string | string[] | undefined;
|
|
8
|
+
/** The endpoint's signing secret, or several while rotating (old and new both pass). */
|
|
9
|
+
secret: string | readonly string[];
|
|
10
|
+
/** Largest allowed clock difference, either direction. Defaults to 300. */
|
|
11
|
+
toleranceSeconds?: number;
|
|
12
|
+
/** For tests. */
|
|
13
|
+
now?: Date;
|
|
14
|
+
}
|
|
15
|
+
/** Returns the event when the signature is valid; throws {@link TenthWebhookError} otherwise. */
|
|
16
|
+
export declare function verifyWebhook(input: VerifyWebhookInput): WebhookEvent;
|
package/dist/webhook.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { TenthError, TenthWebhookError } from './errors.js';
|
|
3
|
+
export const SIGNATURE_HEADER = 'tenth-signature';
|
|
4
|
+
const MAX_HEADER_LENGTH = 4096;
|
|
5
|
+
const SIGNATURE_RE = /^[0-9a-f]{64}$/;
|
|
6
|
+
const TIMESTAMP_RE = /^\d{1,12}$/;
|
|
7
|
+
export function verifyWebhook(input) {
|
|
8
|
+
const { payload } = input;
|
|
9
|
+
if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) {
|
|
10
|
+
throw new TenthWebhookError('payload_not_raw', 'Pass the raw request body (string or Buffer), not a parsed object: re-serializing changes the bytes that were signed.');
|
|
11
|
+
}
|
|
12
|
+
const secrets = (typeof input.secret === 'string' ? [input.secret] : [...input.secret]).filter((s) => typeof s === 'string' && s.length > 0);
|
|
13
|
+
if (secrets.length === 0) {
|
|
14
|
+
throw new TenthError('invalid_argument', 'A webhook signing secret is required.');
|
|
15
|
+
}
|
|
16
|
+
const tolerance = input.toleranceSeconds ?? 300;
|
|
17
|
+
if (!Number.isInteger(tolerance) || tolerance < 1) {
|
|
18
|
+
throw new TenthError('invalid_argument', 'toleranceSeconds must be a positive integer.');
|
|
19
|
+
}
|
|
20
|
+
const { timestamp, signatures } = parseHeader(input.header);
|
|
21
|
+
const now = Math.floor((input.now?.getTime() ?? Date.now()) / 1000);
|
|
22
|
+
if (now - timestamp > tolerance) {
|
|
23
|
+
throw new TenthWebhookError('timestamp_too_old', 'The webhook timestamp is too old.');
|
|
24
|
+
}
|
|
25
|
+
if (timestamp - now > tolerance) {
|
|
26
|
+
throw new TenthWebhookError('timestamp_in_future', 'The webhook timestamp is in the future.');
|
|
27
|
+
}
|
|
28
|
+
let matched = false;
|
|
29
|
+
for (const secret of secrets) {
|
|
30
|
+
const expected = createHmac('sha256', secret).update(`${timestamp}.`).update(payload).digest();
|
|
31
|
+
for (const signature of signatures) {
|
|
32
|
+
if (timingSafeEqual(expected, signature))
|
|
33
|
+
matched = true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (!matched) {
|
|
37
|
+
throw new TenthWebhookError('signature_mismatch', 'No webhook signature matched.');
|
|
38
|
+
}
|
|
39
|
+
let event;
|
|
40
|
+
try {
|
|
41
|
+
event = JSON.parse(typeof payload === 'string' ? payload : payload.toString('utf8'));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new TenthWebhookError('invalid_payload', 'The webhook body is not JSON.');
|
|
45
|
+
}
|
|
46
|
+
if (!event || typeof event !== 'object' || Array.isArray(event)) {
|
|
47
|
+
throw new TenthWebhookError('invalid_payload', 'The webhook body is not an event object.');
|
|
48
|
+
}
|
|
49
|
+
return event;
|
|
50
|
+
}
|
|
51
|
+
function parseHeader(raw) {
|
|
52
|
+
const header = Array.isArray(raw) ? raw[0] : raw;
|
|
53
|
+
if (typeof header !== 'string' || header.trim().length === 0) {
|
|
54
|
+
throw new TenthWebhookError('missing_header', 'The Tenth-Signature header is missing.');
|
|
55
|
+
}
|
|
56
|
+
if (header.length > MAX_HEADER_LENGTH) {
|
|
57
|
+
throw new TenthWebhookError('malformed_header', 'The Tenth-Signature header is too long.');
|
|
58
|
+
}
|
|
59
|
+
let timestamp;
|
|
60
|
+
const signatures = [];
|
|
61
|
+
for (const part of header.split(',')) {
|
|
62
|
+
const i = part.indexOf('=');
|
|
63
|
+
if (i < 1) {
|
|
64
|
+
throw new TenthWebhookError('malformed_header', 'The Tenth-Signature header is malformed.');
|
|
65
|
+
}
|
|
66
|
+
const key = part.slice(0, i).trim();
|
|
67
|
+
const value = part.slice(i + 1).trim();
|
|
68
|
+
if (key === 't') {
|
|
69
|
+
if (timestamp !== undefined || !TIMESTAMP_RE.test(value)) {
|
|
70
|
+
throw new TenthWebhookError('malformed_header', 'The Tenth-Signature timestamp is malformed.');
|
|
71
|
+
}
|
|
72
|
+
timestamp = Number(value);
|
|
73
|
+
}
|
|
74
|
+
else if (key === 'v1') {
|
|
75
|
+
if (!SIGNATURE_RE.test(value)) {
|
|
76
|
+
throw new TenthWebhookError('malformed_header', 'A Tenth-Signature v1 value is malformed.');
|
|
77
|
+
}
|
|
78
|
+
signatures.push(Buffer.from(value, 'hex'));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (timestamp === undefined || signatures.length === 0) {
|
|
82
|
+
throw new TenthWebhookError('malformed_header', 'The Tenth-Signature header needs t= and at least one v1=.');
|
|
83
|
+
}
|
|
84
|
+
return { timestamp, signatures };
|
|
85
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tenthbilling/node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "Tenth server SDK: entitlement checks, credits, grants, subscriptions, webhooks and customer tokens",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Tenth",
|
|
8
|
+
"homepage": "https://tenthbilling.com/docs/node",
|
|
9
|
+
"keywords": [
|
|
10
|
+
"tenth",
|
|
11
|
+
"billing",
|
|
12
|
+
"subscriptions",
|
|
13
|
+
"entitlements",
|
|
14
|
+
"credits",
|
|
15
|
+
"webhooks",
|
|
16
|
+
"stripe"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./package.json": "./package.json"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist",
|
|
31
|
+
"README.md"
|
|
32
|
+
],
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=24"
|
|
35
|
+
},
|
|
36
|
+
"sideEffects": false,
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@tenthbilling/shared": "0.0.0"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "node ../../scripts/packages/clean-dist.mjs && tsc -p tsconfig.build.json && tsc -p tsconfig.build.json --declaration --emitDeclarationOnly --removeComments false",
|
|
42
|
+
"lint": "eslint src",
|
|
43
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
44
|
+
"test": "vitest run --passWithNoTests"
|
|
45
|
+
},
|
|
46
|
+
"types": "./dist/index.d.ts"
|
|
6
47
|
}
|