@loyaltte/node 0.0.0-stage → 0.1.1

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,206 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { ApiError, ConnectionError, LoyaltteError, errorForStatus } from "./errors.js";
3
+ import { VERSION } from "./version.js";
4
+ /** From `x-retry` in the OpenAPI spec (contract/rules/server.json). */
5
+ export const RETRY = {
6
+ baseMs: 1000,
7
+ maxMs: 60_000,
8
+ multiplier: 2,
9
+ maxAttempts: 8,
10
+ statuses: new Set([408, 425, 429, 500, 502, 503, 504]),
11
+ /** Across one call's retries: a bad Retry-After must not park a worker for hours. */
12
+ maxTotalSleepMs: 300_000,
13
+ };
14
+ const NEVER_SENT = new Set([
15
+ "ECONNREFUSED",
16
+ "ENOTFOUND",
17
+ "EAI_AGAIN",
18
+ "ENETUNREACH",
19
+ "EHOSTUNREACH",
20
+ "UND_ERR_CONNECT_TIMEOUT",
21
+ ]);
22
+ const errorCode = (error) => {
23
+ const code = error?.cause?.code;
24
+ return typeof code === "string" ? code : undefined;
25
+ };
26
+ /** The certificate was refused: never retried, however the operation is classed. */
27
+ function isCertificateFailure(error) {
28
+ const code = errorCode(error);
29
+ return (code !== undefined &&
30
+ (code.startsWith("ERR_TLS_") ||
31
+ /^(CERT_|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|UNABLE_TO_(VERIFY_LEAF|GET_ISSUER|GET_LOCAL_ISSUER)|HOSTNAME_MISMATCH)/.test(code)));
32
+ }
33
+ /** The request certainly never reached the server (no connection was made). */
34
+ function neverSent(error) {
35
+ const code = error?.cause?.code;
36
+ return typeof code === "string" && NEVER_SENT.has(code);
37
+ }
38
+ function parseRetryAfter(value) {
39
+ if (value === null || !/^\s*\d+(\.\d+)?\s*$/.test(value))
40
+ return null;
41
+ return Number(value);
42
+ }
43
+ /** The jittered backoff before the next try; `attempt` is 1 for the first retry. */
44
+ export function backoffMs(attempt, random = Math.random) {
45
+ const cap = Math.min(RETRY.maxMs, RETRY.baseMs * RETRY.multiplier ** (attempt - 1));
46
+ return Math.floor(random() * cap);
47
+ }
48
+ /**
49
+ * Sends the requests. The secret key lives only in a private field: it is never a property, never printed, never
50
+ * in an error. Nothing here logs.
51
+ */
52
+ export class Transport {
53
+ #secretKey;
54
+ #config;
55
+ constructor({ secretKey, ...config }) {
56
+ this.#secretKey = secretKey;
57
+ this.#config = config;
58
+ }
59
+ async request(operation, input = {}) {
60
+ try {
61
+ return await this.#attempts(operation, input);
62
+ }
63
+ catch (error) {
64
+ // After a raised error the caller can resend with this key and stay safe (a bill or return may have been
65
+ // recorded before the reply was lost).
66
+ if (error instanceof LoyaltteError && input.idempotencyKey !== undefined)
67
+ error.idempotencyKey = input.idempotencyKey;
68
+ throw error;
69
+ }
70
+ }
71
+ async #attempts(operation, input) {
72
+ const { baseUrl, timeoutMs, maxRetries, fetch, sleep } = this.#config;
73
+ const query = Object.entries(input.query ?? {}).filter(([, v]) => v !== undefined);
74
+ const url = `${baseUrl}${operation.path}${query.length ? `?${new URLSearchParams(query).toString()}` : ""}`;
75
+ const body = input.body === undefined ? undefined : JSON.stringify(input.body);
76
+ const headers = {
77
+ Authorization: `Bearer ${this.#secretKey}`,
78
+ "X-Loyaltte-SDK": `node/${VERSION}`,
79
+ Accept: "application/json",
80
+ };
81
+ if (body !== undefined)
82
+ headers["Content-Type"] = "application/json";
83
+ // One key per call, the same on every attempt: that is what makes a retry after a lost reply safe.
84
+ if (input.idempotencyKey !== undefined)
85
+ headers["Idempotency-Key"] = input.idempotencyKey;
86
+ let slept = 0; // ms waited so far in this call: capped at RETRY.maxTotalSleepMs
87
+ for (let attempt = 1;; attempt += 1) {
88
+ const retriesLeft = attempt <= maxRetries && slept < RETRY.maxTotalSleepMs;
89
+ let response;
90
+ let text;
91
+ // A plain timer (not AbortSignal.timeout, whose timer is unref'd on Node 18) so the timeout always fires,
92
+ // covering the body read too; cleared as soon as the attempt ends.
93
+ const controller = new AbortController();
94
+ const timer = setTimeout(() => controller.abort(new DOMException("The request timed out.", "TimeoutError")), timeoutMs);
95
+ try {
96
+ response = await fetch(url, {
97
+ method: operation.method,
98
+ headers,
99
+ body,
100
+ redirect: "error", // never follow a redirect with the key attached
101
+ signal: controller.signal,
102
+ });
103
+ text = await response.text();
104
+ }
105
+ catch (error) {
106
+ if (isCertificateFailure(error))
107
+ throw new ConnectionError({
108
+ message: "TLS certificate verification failed; refusing to send the request.",
109
+ code: "TLS_VERIFICATION_FAILED",
110
+ cause: { name: "TlsError", code: errorCode(error) },
111
+ });
112
+ const retryable = operation.retry === "refused-only" ? neverSent(error) : true;
113
+ if (retryable && retriesLeft) {
114
+ slept += await this.#wait(sleep, backoffMs(attempt), slept);
115
+ continue;
116
+ }
117
+ throw this.#connectionError(error);
118
+ }
119
+ finally {
120
+ clearTimeout(timer);
121
+ }
122
+ if (response.ok)
123
+ return this.#parse(response, text);
124
+ const failure = this.#failure(response, text);
125
+ const status = response.status;
126
+ const asked = status === 429 || status === 503 ? failure.retryAfter : null;
127
+ // Not safe to repeat unless the server certainly did nothing: for these POSTs that is a 429 that says when.
128
+ const retryable = RETRY.statuses.has(status) &&
129
+ (operation.retry !== "refused-only" || (status === 429 && asked !== null));
130
+ if (retryable && retriesLeft) {
131
+ // A Retry-After longer than what is left of the budget ends the call with this error: no early retry.
132
+ if (asked !== null && asked * 1000 > RETRY.maxTotalSleepMs - slept)
133
+ throw failure;
134
+ const jitter = backoffMs(attempt);
135
+ slept += await this.#wait(sleep, asked === null ? jitter : Math.max(asked * 1000, jitter), slept);
136
+ continue;
137
+ }
138
+ throw failure;
139
+ }
140
+ }
141
+ /** Sleeps `ms` (at most what is left of the call's budget) and says how long that was. */
142
+ async #wait(sleep, ms, slept) {
143
+ const wait = Math.max(0, Math.min(ms, RETRY.maxTotalSleepMs - slept));
144
+ await sleep(wait);
145
+ return wait;
146
+ }
147
+ #parse(response, text) {
148
+ try {
149
+ return JSON.parse(text);
150
+ }
151
+ catch {
152
+ throw new ApiError({
153
+ message: "Loyaltte answered with something that isn't JSON.",
154
+ status: response.status,
155
+ code: "INVALID_RESPONSE",
156
+ requestId: response.headers.get("x-request-id"),
157
+ });
158
+ }
159
+ }
160
+ #failure(response, text) {
161
+ const status = response.status;
162
+ let detail = null;
163
+ try {
164
+ const parsed = JSON.parse(text);
165
+ if (parsed && typeof parsed === "object" && parsed.error && typeof parsed.error === "object")
166
+ detail = parsed.error;
167
+ }
168
+ catch {
169
+ // not JSON: use the status below
170
+ }
171
+ const text2 = (v) => (typeof v === "string" && v ? v : null);
172
+ const fields = detail?.fields && typeof detail.fields === "object" && !Array.isArray(detail.fields)
173
+ ? detail.fields
174
+ : null;
175
+ const Type = errorForStatus(status);
176
+ return new Type({
177
+ status,
178
+ code: this.#redact(text2(detail?.code) ?? `HTTP_${status}`),
179
+ message: this.#redact(text2(detail?.message) ?? (response.statusText || `HTTP ${status}`)),
180
+ fields: fields && JSON.parse(this.#redact(JSON.stringify(fields))),
181
+ requestId: this.#redactOrNull(text2(detail?.requestId) ?? response.headers.get("x-request-id")),
182
+ retryAfter: parseRetryAfter(response.headers.get("retry-after")),
183
+ });
184
+ }
185
+ /** Belt and braces: whatever text reaches an error, the key itself never does. */
186
+ #redact(text) {
187
+ return text.split(this.#secretKey).join("[redacted key]");
188
+ }
189
+ #redactOrNull(text) {
190
+ return text === null ? null : this.#redact(text);
191
+ }
192
+ #connectionError(error) {
193
+ const name = error?.name;
194
+ const code = error?.cause?.code;
195
+ const timedOut = name === "TimeoutError" || name === "AbortError";
196
+ return new ConnectionError({
197
+ message: timedOut
198
+ ? `Loyaltte did not answer within ${this.#config.timeoutMs} ms.`
199
+ : `Could not reach Loyaltte${typeof code === "string" ? ` (${code})` : ""}.`,
200
+ code: timedOut ? "TIMEOUT" : "CONNECTION_FAILED",
201
+ // Only what is safe to show: a custom fetch's error could carry the request, headers included.
202
+ cause: { name: String(name ?? "Error"), code: typeof code === "string" ? code : undefined },
203
+ });
204
+ }
205
+ }
206
+ export const newIdempotencyKey = () => randomUUID();
@@ -0,0 +1,195 @@
1
+ /** A decimal amount in rupees as text, like `"4200.00"`. Never a number: floats lose paise. */
2
+ export type Money = string;
3
+ export interface KeyInfo {
4
+ key_id: string;
5
+ /** `live` or `test`. */
6
+ mode: "live" | "test";
7
+ /** The permissions this key holds, e.g. `bills:write`. */
8
+ scopes: string[];
9
+ account: {
10
+ id: string;
11
+ name: string;
12
+ };
13
+ /** The ids of the stores this key may use. */
14
+ stores: string[];
15
+ }
16
+ /** Say who a customer is: any one of these. */
17
+ export interface CustomerRef {
18
+ phone?: string | null;
19
+ customer_id?: string | null;
20
+ external_id?: string | null;
21
+ email?: string | null;
22
+ }
23
+ export interface ServerEvent {
24
+ /** Your id for the event; a resend with the same id is counted once. */
25
+ id?: string;
26
+ /** `page_viewed`, `product_viewed`, `cart_updated`, `checkout_started` or your own name. */
27
+ type: string;
28
+ /** ISO 8601; not older than 7 days. */
29
+ occurred_at?: string;
30
+ /** The visitor (8-128 letters, digits or . _ : -). */
31
+ anonymous_id?: string;
32
+ customer?: {
33
+ phone?: string;
34
+ email?: string;
35
+ external_id?: string;
36
+ };
37
+ properties?: Record<string, unknown>;
38
+ }
39
+ export interface EventsResult {
40
+ accepted: number;
41
+ duplicates: number;
42
+ rejected: {
43
+ index: number;
44
+ id?: string;
45
+ reason: string;
46
+ }[];
47
+ dropped_properties: unknown[];
48
+ }
49
+ export interface IdentifyParams {
50
+ /** The visitor's anonymous id. */
51
+ anonymous_id: string;
52
+ /** At least one of these says which customer. */
53
+ phone?: string;
54
+ email?: string;
55
+ external_id?: string;
56
+ }
57
+ export interface IdentifyResult {
58
+ status: string;
59
+ /** How many of the visitor's earlier events became the customer's. */
60
+ earlier_events: number;
61
+ }
62
+ export interface LookupParams {
63
+ phone?: string;
64
+ email?: string;
65
+ external_id?: string;
66
+ }
67
+ export interface Customer {
68
+ id: string;
69
+ name: string | null;
70
+ phone: string | null;
71
+ email: string | null;
72
+ external_ids: string[];
73
+ member: boolean;
74
+ program: string | null;
75
+ tier: string | null;
76
+ points_balance: number;
77
+ points_value: Money;
78
+ lifetime_spend: Money;
79
+ visits: number;
80
+ last_visit_at: string | null;
81
+ joined_at: string | null;
82
+ consent: Record<string, string>;
83
+ }
84
+ export interface LookupResult {
85
+ found: boolean;
86
+ customer: Customer | null;
87
+ }
88
+ export interface CustomerResult {
89
+ customer: Customer;
90
+ }
91
+ export interface Points {
92
+ customer_id: string;
93
+ balance: number;
94
+ lifetime_earned: number;
95
+ lifetime_redeemed: number;
96
+ /** Points expiring in the next 30 days. */
97
+ expiring_soon: number;
98
+ }
99
+ export interface BillLine {
100
+ amount: Money;
101
+ name?: string;
102
+ sku?: string | null;
103
+ category?: string | null;
104
+ quantity?: string | number;
105
+ }
106
+ export interface BillPreviewParams {
107
+ store_id: string;
108
+ amount: Money;
109
+ /** Leave out for a walk-in. */
110
+ customer?: CustomerRef | null;
111
+ items?: BillLine[];
112
+ redeem_points?: number;
113
+ voucher_code?: string | null;
114
+ bill_number?: string | null;
115
+ /** ISO 8601 with a timezone offset; at most 7 days in the past and 5 minutes ahead. */
116
+ occurred_at?: string | null;
117
+ ebill_consent?: boolean | null;
118
+ how_identified?: "phone" | "qr" | "member_code" | "pos" | null;
119
+ }
120
+ export interface BillParams extends BillPreviewParams {
121
+ /** Unique per bill: the same bill again returns the first receipt with `replayed: true`. */
122
+ bill_number: string;
123
+ }
124
+ export interface BillPreview {
125
+ customer_found: boolean;
126
+ member: boolean;
127
+ subtotal: Money;
128
+ voucher: unknown;
129
+ points_balance: number;
130
+ max_redeemable_points: number;
131
+ point_value: Money;
132
+ redeem_points: number;
133
+ points_discount: Money;
134
+ payable: Money;
135
+ earn: {
136
+ points: number;
137
+ };
138
+ program_here: boolean;
139
+ program_note: string | null;
140
+ referral: unknown;
141
+ /** Anything that would stop the bill going through. */
142
+ problems: unknown[];
143
+ limit_reached: boolean;
144
+ points_left_today: number | null;
145
+ ebill: unknown;
146
+ }
147
+ export interface Bill {
148
+ bill_id: string;
149
+ bill_number: string;
150
+ customer_id: string | null;
151
+ voucher: unknown;
152
+ points_discount: Money;
153
+ /** True when this is the first receipt again (a retry or a repeat), nothing new was recorded. */
154
+ replayed: boolean;
155
+ subtotal: Money;
156
+ discount: Money;
157
+ payable: Money;
158
+ points_earned: number;
159
+ points_spent: number;
160
+ referral_points: number;
161
+ points_balance: number;
162
+ earn: {
163
+ points: number;
164
+ };
165
+ }
166
+ export interface ReturnParams {
167
+ /** The original bill. */
168
+ bill_number: string;
169
+ /** Unique per return. */
170
+ return_number: string;
171
+ /** The amount returned, in rupees. */
172
+ amount: Money;
173
+ }
174
+ export interface BillReturn {
175
+ bill_id: string;
176
+ bill_number: string;
177
+ customer_id: string | null;
178
+ customer_name: string | null;
179
+ replayed: boolean;
180
+ returned_amount: Money;
181
+ points_taken_back: number;
182
+ points_given_back: number;
183
+ points_balance: number;
184
+ }
185
+ /** A webhook from Loyaltte, after `constructEvent` has verified it. */
186
+ export interface WebhookEvent<T = Record<string, unknown>> {
187
+ /** Unique per event: ignore one you have handled. */
188
+ id: string;
189
+ /** e.g. `purchase.completed`. */
190
+ type: string;
191
+ created_at: string;
192
+ account_id: string;
193
+ /** Always has `customer_id` and `store_id` (either may be null); never a phone number or email. */
194
+ data: T;
195
+ }
@@ -0,0 +1,2 @@
1
+ // Hand-written from packages/sdk-spec/openapi.yaml ("Server API"). Money is always a decimal STRING ("4200.00").
2
+ export {};
@@ -0,0 +1,2 @@
1
+ /** The SDK's own version: sent as `X-Loyaltte-SDK: node/<version>` on every call. Kept equal to package.json. */
2
+ export declare const VERSION = "0.1.1";
@@ -0,0 +1,2 @@
1
+ /** The SDK's own version: sent as `X-Loyaltte-SDK: node/<version>` on every call. Kept equal to package.json. */
2
+ export const VERSION = "0.1.1";
@@ -0,0 +1,27 @@
1
+ import type { WebhookEvent } from "./types.js";
2
+ export interface VerifyParams {
3
+ /** The signing secret (`whsec_…`). During a rotation pass `secrets` instead. */
4
+ secret?: string;
5
+ /** Every signing secret you currently hold (two during a rotation). */
6
+ secrets?: string[];
7
+ /** The `Loyaltte-Signature` header: `t=<unix seconds>,v1=<hex>[,v1=<hex>]`. */
8
+ header: string | null | undefined;
9
+ /** The request body exactly as received: a Buffer or the raw string, never parsed-and-stringified JSON. */
10
+ rawBody: string | Buffer | Uint8Array;
11
+ /** How far `t` may be from now, in seconds. Default 300. */
12
+ toleranceSeconds?: number;
13
+ /** Unix seconds to treat as now (tests). */
14
+ now?: number;
15
+ }
16
+ /**
17
+ * Checks a webhook's signature. Never throws: a header it can't read, a stale timestamp or a wrong signature is
18
+ * `false`. The signature is the hex HMAC-SHA256, keyed with the signing secret, of `<t>.` plus the raw body;
19
+ * any `v1` in the header may match (a rotation sends two); the comparison is constant time.
20
+ */
21
+ export declare function verify(params: VerifyParams): boolean;
22
+ /** Verifies the signature and returns the parsed event; throws `WebhookSignatureError` when it can't be trusted. */
23
+ export declare function constructEvent<T = Record<string, unknown>>(params: VerifyParams): WebhookEvent<T>;
24
+ export declare const webhooks: {
25
+ verify: typeof verify;
26
+ constructEvent: typeof constructEvent;
27
+ };
@@ -0,0 +1,66 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { WebhookSignatureError } from "./errors.js";
3
+ const HEX64 = /^[0-9a-fA-F]{64}$/;
4
+ const DIGITS = /^\d{1,15}$/;
5
+ /**
6
+ * Checks a webhook's signature. Never throws: a header it can't read, a stale timestamp or a wrong signature is
7
+ * `false`. The signature is the hex HMAC-SHA256, keyed with the signing secret, of `<t>.` plus the raw body;
8
+ * any `v1` in the header may match (a rotation sends two); the comparison is constant time.
9
+ */
10
+ export function verify(params) {
11
+ try {
12
+ const { header, rawBody, toleranceSeconds = 300 } = params;
13
+ const secrets = [
14
+ ...(Array.isArray(params.secrets) ? params.secrets : []),
15
+ ...(params.secret ? [params.secret] : []),
16
+ ].filter((s) => typeof s === "string" && s !== "");
17
+ if (typeof header !== "string" || secrets.length === 0)
18
+ return false;
19
+ if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0)
20
+ return false; // never "accept everything"
21
+ const pairs = header.split(",").map((part) => {
22
+ const at = part.indexOf("=");
23
+ return at < 0 ? [part.trim(), ""] : [part.slice(0, at).trim(), part.slice(at + 1).trim()];
24
+ });
25
+ const stamps = pairs.filter(([k]) => k === "t").map(([, v]) => v);
26
+ const t = stamps[0];
27
+ if (stamps.length !== 1 || t === undefined || !DIGITS.test(t))
28
+ return false;
29
+ const now = params.now ?? Math.floor(Date.now() / 1000);
30
+ if (!Number.isFinite(now))
31
+ return false;
32
+ if (Math.abs(now - Number(t)) > toleranceSeconds)
33
+ return false;
34
+ const body = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : Buffer.from(rawBody);
35
+ const given = pairs
36
+ .filter(([k, v]) => k === "v1" && HEX64.test(v ?? ""))
37
+ .map(([, v]) => Buffer.from(v, "hex"));
38
+ let matched = false;
39
+ for (const secret of secrets) {
40
+ const expected = createHmac("sha256", secret).update(`${t}.`).update(body).digest();
41
+ // every comparison runs, so the time doesn't say which one matched
42
+ for (const candidate of given)
43
+ if (timingSafeEqual(candidate, expected))
44
+ matched = true;
45
+ }
46
+ return matched;
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ /** Verifies the signature and returns the parsed event; throws `WebhookSignatureError` when it can't be trusted. */
53
+ export function constructEvent(params) {
54
+ if (!verify(params))
55
+ throw new WebhookSignatureError();
56
+ const text = typeof params.rawBody === "string"
57
+ ? params.rawBody
58
+ : Buffer.from(params.rawBody).toString("utf8");
59
+ try {
60
+ return JSON.parse(text);
61
+ }
62
+ catch {
63
+ throw new WebhookSignatureError("The webhook body is signed but is not JSON.");
64
+ }
65
+ }
66
+ export const webhooks = { verify, constructEvent };
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@loyaltte/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Loyaltte for Node.js servers: record bills and returns exactly once, look up customers and points, send events, sign customers in for the app SDKs, and verify webhooks. Zero dependencies.",
5
+ "license": "MIT",
6
+ "homepage": "https://developers.loyaltte.com/",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/loyaltte/sdks.git",
10
+ "directory": "packages/sdk-node"
11
+ },
12
+ "keywords": [
13
+ "loyaltte",
14
+ "loyalty",
15
+ "sdk",
16
+ "webhooks"
17
+ ],
18
+ "main": "./dist/cjs/index.js",
19
+ "module": "./dist/esm/index.js",
20
+ "types": "./dist/cjs/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "import": {
24
+ "types": "./dist/esm/index.d.ts",
25
+ "default": "./dist/esm/index.js"
26
+ },
27
+ "require": {
28
+ "types": "./dist/cjs/index.d.ts",
29
+ "default": "./dist/cjs/index.js"
30
+ }
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "sideEffects": false,
35
+ "engines": {
36
+ "node": ">=18"
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "devDependencies": {
44
+ "@eslint/js": "^9.18.0",
45
+ "@types/node": "^22.10.0",
46
+ "eslint": "^9.18.0",
47
+ "typescript": "^5.7.3",
48
+ "typescript-eslint": "^8.20.0"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public",
52
+ "provenance": true
53
+ },
54
+ "scripts": {
55
+ "build": "node scripts/build.mjs",
56
+ "type-check": "tsc --noEmit",
57
+ "lint": "eslint src test scripts",
58
+ "test": "node scripts/build.mjs && node scripts/test.mjs"
59
+ }
6
60
  }