@clikgate/node 0.0.0-stage → 2.0.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/LICENSE +21 -0
  3. package/README.md +300 -2
  4. package/SECURITY.md +34 -0
  5. package/dist/cjs/ads-hashing.d.ts +37 -0
  6. package/dist/cjs/ads-hashing.js +67 -0
  7. package/dist/cjs/click-ids.d.ts +184 -0
  8. package/dist/cjs/click-ids.js +535 -0
  9. package/dist/cjs/client.d.ts +175 -0
  10. package/dist/cjs/client.js +266 -0
  11. package/dist/cjs/config.d.ts +12 -0
  12. package/dist/cjs/config.js +87 -0
  13. package/dist/cjs/core.d.ts +15 -0
  14. package/dist/cjs/core.js +100 -0
  15. package/dist/cjs/enums.d.ts +48 -0
  16. package/dist/cjs/enums.js +47 -0
  17. package/dist/cjs/errors.d.ts +117 -0
  18. package/dist/cjs/errors.js +257 -0
  19. package/dist/cjs/express.d.ts +49 -0
  20. package/dist/cjs/express.js +44 -0
  21. package/dist/cjs/fastify.d.ts +47 -0
  22. package/dist/cjs/fastify.js +35 -0
  23. package/dist/cjs/generated/index.d.ts +17534 -0
  24. package/dist/cjs/generated/index.js +8816 -0
  25. package/dist/cjs/goals.d.ts +116 -0
  26. package/dist/cjs/goals.js +381 -0
  27. package/dist/cjs/guard.d.ts +17 -0
  28. package/dist/cjs/guard.js +40 -0
  29. package/dist/cjs/http.d.ts +16 -0
  30. package/dist/cjs/http.js +148 -0
  31. package/dist/cjs/identity.d.ts +32 -0
  32. package/dist/cjs/identity.js +99 -0
  33. package/dist/cjs/index.d.ts +32 -0
  34. package/dist/cjs/index.js +64 -0
  35. package/dist/cjs/logger.d.ts +9 -0
  36. package/dist/cjs/logger.js +8 -0
  37. package/dist/cjs/money.d.ts +16 -0
  38. package/dist/cjs/money.js +51 -0
  39. package/dist/cjs/next.d.ts +81 -0
  40. package/dist/cjs/next.js +103 -0
  41. package/dist/cjs/package.json +1 -0
  42. package/dist/cjs/payments.d.ts +174 -0
  43. package/dist/cjs/payments.js +485 -0
  44. package/dist/cjs/resources.d.ts +109 -0
  45. package/dist/cjs/resources.js +189 -0
  46. package/dist/cjs/shutdown.d.ts +2 -0
  47. package/dist/cjs/shutdown.js +51 -0
  48. package/dist/cjs/transport.d.ts +14 -0
  49. package/dist/cjs/transport.js +204 -0
  50. package/dist/cjs/types.d.ts +218 -0
  51. package/dist/cjs/types.js +2 -0
  52. package/dist/cjs/user-agent.d.ts +1 -0
  53. package/dist/cjs/user-agent.js +53 -0
  54. package/dist/cjs/version.d.ts +2 -0
  55. package/dist/cjs/version.js +5 -0
  56. package/dist/cjs/webhooks.d.ts +36 -0
  57. package/dist/cjs/webhooks.js +108 -0
  58. package/dist/esm/ads-hashing.d.ts +37 -0
  59. package/dist/esm/ads-hashing.js +62 -0
  60. package/dist/esm/click-ids.d.ts +184 -0
  61. package/dist/esm/click-ids.js +526 -0
  62. package/dist/esm/client.d.ts +175 -0
  63. package/dist/esm/client.js +262 -0
  64. package/dist/esm/config.d.ts +12 -0
  65. package/dist/esm/config.js +82 -0
  66. package/dist/esm/core.d.ts +15 -0
  67. package/dist/esm/core.js +96 -0
  68. package/dist/esm/enums.d.ts +48 -0
  69. package/dist/esm/enums.js +44 -0
  70. package/dist/esm/errors.d.ts +117 -0
  71. package/dist/esm/errors.js +234 -0
  72. package/dist/esm/express.d.ts +49 -0
  73. package/dist/esm/express.js +40 -0
  74. package/dist/esm/fastify.d.ts +47 -0
  75. package/dist/esm/fastify.js +32 -0
  76. package/dist/esm/generated/index.d.ts +17534 -0
  77. package/dist/esm/generated/index.js +8754 -0
  78. package/dist/esm/goals.d.ts +116 -0
  79. package/dist/esm/goals.js +371 -0
  80. package/dist/esm/guard.d.ts +17 -0
  81. package/dist/esm/guard.js +36 -0
  82. package/dist/esm/http.d.ts +16 -0
  83. package/dist/esm/http.js +138 -0
  84. package/dist/esm/identity.d.ts +32 -0
  85. package/dist/esm/identity.js +92 -0
  86. package/dist/esm/index.d.ts +32 -0
  87. package/dist/esm/index.js +21 -0
  88. package/dist/esm/logger.d.ts +9 -0
  89. package/dist/esm/logger.js +5 -0
  90. package/dist/esm/money.d.ts +16 -0
  91. package/dist/esm/money.js +48 -0
  92. package/dist/esm/next.d.ts +81 -0
  93. package/dist/esm/next.js +96 -0
  94. package/dist/esm/package.json +1 -0
  95. package/dist/esm/payments.d.ts +174 -0
  96. package/dist/esm/payments.js +476 -0
  97. package/dist/esm/resources.d.ts +109 -0
  98. package/dist/esm/resources.js +183 -0
  99. package/dist/esm/shutdown.d.ts +2 -0
  100. package/dist/esm/shutdown.js +47 -0
  101. package/dist/esm/transport.d.ts +14 -0
  102. package/dist/esm/transport.js +166 -0
  103. package/dist/esm/types.d.ts +218 -0
  104. package/dist/esm/types.js +1 -0
  105. package/dist/esm/user-agent.d.ts +1 -0
  106. package/dist/esm/user-agent.js +16 -0
  107. package/dist/esm/version.d.ts +2 -0
  108. package/dist/esm/version.js +2 -0
  109. package/dist/esm/webhooks.d.ts +36 -0
  110. package/dist/esm/webhooks.js +105 -0
  111. package/package.json +128 -4
@@ -0,0 +1,218 @@
1
+ import type { GoalKind, GoalStatus, Provider } from './enums.js';
2
+ /** Wire objects returned by the hand-written resources. Keys are as the API sends them (snake_case). */
3
+ /** Where a goal event was attributed. */
4
+ export interface GoalAttribution {
5
+ link_id: string | null;
6
+ campaign_id: string | null;
7
+ clicked_at: string | null;
8
+ }
9
+ /** A goal event (`POST /v1/goals/events`). */
10
+ export interface GoalEvent {
11
+ object: 'goal_event';
12
+ /** `cnv_…`; a Payment goal waiting for its report has its confirmation id (`pcf_…`). */
13
+ id: string;
14
+ /** The outcome: `counted`, `waiting` (a Payment goal waiting for its confirmation) or `refused`. Compare with `GoalStatus`. */
15
+ status: GoalStatus;
16
+ /** `null` when counted; else why, e.g. `waiting_for_confirmation`, `already_counted_for_click`, `rejected_bot`. */
17
+ reason: string | null;
18
+ /** The goal's kind (set in the goal's settings): `standard` or `payment`. */
19
+ goal_kind?: GoalKind;
20
+ /** Whether this event counts in totals: `status === 'counted'`. */
21
+ counted: boolean;
22
+ /** `true` when a value was dropped (browsers and apps can't set a Payment goal's value). */
23
+ value_ignored?: boolean;
24
+ /** The event's attribution state: `attributed`, `unattributed`, `rejected_bot`, … (`null` while a Payment goal waits). */
25
+ event_status?: string | null;
26
+ goal: string;
27
+ /** Your reference; `null` in private mode. */
28
+ reference: string | null;
29
+ /** Normal units as a decimal string, e.g. `"2000000"`. Never a float. */
30
+ value: string | null;
31
+ /**
32
+ * The same amount in the currency's minor units (kobo, cents), e.g. `200000000`. `null` without a value.
33
+ * Prefer `value` for exact amounts: minor units above 2^53 lose precision as a JS number.
34
+ */
35
+ value_minor?: number | null;
36
+ currency: string | null;
37
+ reversed_value?: string | null;
38
+ /** `reversed_value` in minor units; `null` when nothing was reversed. */
39
+ reversed_value_minor?: number | null;
40
+ first_for_click: boolean | null;
41
+ is_first: boolean | null;
42
+ unattributed_reason?: string | null;
43
+ duplicate_of_id?: string | null;
44
+ attributed_to: GoalAttribution | null;
45
+ /** A Payment goal sent by your server: the confirmation it became. `null` otherwise. */
46
+ payment?: GoalPayment | null;
47
+ occurred_at: string;
48
+ received_at: string;
49
+ livemode: boolean;
50
+ [key: string]: unknown;
51
+ }
52
+ /** The confirmation a Payment goal sent by your server became. */
53
+ export interface GoalPayment {
54
+ /** `pcf_…` */
55
+ confirmation_id: string;
56
+ /** `matched`, `waiting_for_report`, `counted_without_report`, `duplicate`, … (new values can appear). */
57
+ match_status: string;
58
+ /** The browser's or app's report it matched (`prp_…`), or `null`. */
59
+ report_id: string | null;
60
+ /** The provider (a `Provider` value, or a newer gateway's key). */
61
+ provider: Provider | (string & {});
62
+ [key: string]: unknown;
63
+ }
64
+ /** One item of a batch result. */
65
+ export interface GoalBatchItem {
66
+ index: number;
67
+ ok: boolean;
68
+ status: number;
69
+ goal_event?: GoalEvent | null;
70
+ error?: {
71
+ type?: string;
72
+ code?: string;
73
+ message?: string;
74
+ param?: string | null;
75
+ [key: string]: unknown;
76
+ } | null;
77
+ }
78
+ /** `POST /v1/goals/events/batch` result: one item per event, in order. */
79
+ export interface GoalBatchResult {
80
+ object: 'list';
81
+ data: GoalBatchItem[];
82
+ }
83
+ /** A non-blocking finding on a link, e.g. `no_preview`. */
84
+ export interface LinkWarning {
85
+ code: string;
86
+ message: string;
87
+ param?: string | null;
88
+ }
89
+ /** A link (`/v1/links`). Only the most used fields are typed; the rest are kept. */
90
+ export interface Link {
91
+ object: 'link';
92
+ id: string;
93
+ short_url: string;
94
+ domain: string;
95
+ slug: string;
96
+ status: string;
97
+ destination_url: string;
98
+ fallback_url: string | null;
99
+ title: string | null;
100
+ og_title: string | null;
101
+ og_image_url: string | null;
102
+ tags: string[];
103
+ metadata: Record<string, unknown>;
104
+ /** Non-blocking warnings, e.g. `no_preview`. */
105
+ warnings: LinkWarning[];
106
+ /** `"premium"` on `ciz.to` links, else `null`. */
107
+ domain_badge?: 'premium' | null;
108
+ /** True when destination, fallback and deep-link changes are refused (`409 link_locked`). */
109
+ locked?: boolean;
110
+ created_at: string;
111
+ updated_at: string;
112
+ livemode: boolean;
113
+ [key: string]: unknown;
114
+ }
115
+ /** A pending destination change awaiting a second person's approval (`202` on update). */
116
+ export interface LinkChangeRequest {
117
+ object: 'link_change_request';
118
+ id: string;
119
+ link_id: string;
120
+ requested_by: string;
121
+ /** Who asked for the change: `user`, `key`, `client` or `cli` (a plain string; new values can appear). */
122
+ requested_by_type: string;
123
+ from_url: string;
124
+ to_url: string;
125
+ status: 'pending' | 'approved' | 'rejected' | 'expired';
126
+ decided_by: string | null;
127
+ decided_at: string | null;
128
+ /** The approver's or rejecter's note, once decided. */
129
+ decision_note: string | null;
130
+ created_at: string;
131
+ expires_at: string;
132
+ /** `true` for live-environment data, `false` for test mode. */
133
+ livemode: boolean;
134
+ [key: string]: unknown;
135
+ }
136
+ /** The result of `links.update`: applied now, or waiting for approval. */
137
+ export type LinkUpdateResult = {
138
+ applied: true;
139
+ link: Link;
140
+ change_request: null;
141
+ warnings: LinkWarning[];
142
+ } | {
143
+ applied: false;
144
+ link: null;
145
+ change_request: LinkChangeRequest;
146
+ warnings: LinkWarning[];
147
+ };
148
+ /** A click (`/v1/clicks/{id}`). */
149
+ export interface Click {
150
+ object: 'click';
151
+ id: string;
152
+ occurred_at: string;
153
+ link: {
154
+ id: string;
155
+ [key: string]: unknown;
156
+ } | null;
157
+ campaign: {
158
+ id: string;
159
+ [key: string]: unknown;
160
+ } | null;
161
+ country?: string | null;
162
+ device_type?: string | null;
163
+ is_suspected_bot: boolean;
164
+ livemode: boolean;
165
+ [key: string]: unknown;
166
+ }
167
+ /** A conversion (older API). */
168
+ export interface Conversion {
169
+ object: 'conversion';
170
+ id: string;
171
+ status?: string;
172
+ [key: string]: unknown;
173
+ }
174
+ /** One page of a list. */
175
+ export interface ListPage<T> {
176
+ object: 'list';
177
+ data: T[];
178
+ has_more: boolean;
179
+ next_cursor: string | null;
180
+ }
181
+ /** A goal as `GET /v1/server-sdk/config` describes it. */
182
+ export interface ConfigGoal {
183
+ key: string;
184
+ value_mode: 'none' | 'optional' | 'required';
185
+ default_currency: string | null;
186
+ }
187
+ /** `GET /v1/server-sdk/config`. */
188
+ export interface ServerSdkConfig {
189
+ mode: 'live' | 'test';
190
+ organization_id: string;
191
+ private_mode: boolean;
192
+ click_id_param: string;
193
+ goals: ConfigGoal[];
194
+ minimum_sdk_versions: Partial<Record<'node' | 'python' | 'php' | 'java' | 'dotnet', string>>;
195
+ [key: string]: unknown;
196
+ }
197
+ /** A webhook event. */
198
+ export interface WebhookEvent<T = Record<string, unknown>> {
199
+ id: string;
200
+ object: 'event';
201
+ /** e.g. `goal.completed`, `link.destination_changed`, `subscription.updated`. */
202
+ type: string;
203
+ api_version: string;
204
+ created_at: string;
205
+ organization_id: string;
206
+ livemode: boolean;
207
+ data: {
208
+ object: T;
209
+ previous_attributes?: Record<string, unknown> | null;
210
+ [key: string]: unknown;
211
+ };
212
+ [key: string]: unknown;
213
+ }
214
+ /** QR code bytes. */
215
+ export interface QrCode {
216
+ contentType: string;
217
+ data: Uint8Array;
218
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.sanitise = sanitise;
37
+ exports.userAgent = userAgent;
38
+ const os = __importStar(require("node:os"));
39
+ const version_js_1 = require("./version.js");
40
+ const ARCH = { x64: 'x64', arm64: 'arm64', ia32: 'x86', arm: 'arm' };
41
+ const OS = { win32: 'windows' };
42
+ /** @internal Versions must match `^[0-9][0-9A-Za-z.+-]{0,39}$` for the backend parser (SPEC section 4). */
43
+ function sanitise(version) {
44
+ return version.replace(/^v/, '').replace(/[^0-9A-Za-z.+-]/g, '-').slice(0, 40);
45
+ }
46
+ /**
47
+ * @internal `clikgate-node/<v> (node <v>; <os> <arch>)` (SPEC section 4). This is the only telemetry.
48
+ */
49
+ function userAgent(platform = os.platform(), arch = process.arch, nodeVersion = process.versions.node) {
50
+ const osName = (OS[platform] ?? platform).toLowerCase();
51
+ const archName = ARCH[arch] ?? arch.toLowerCase().replace(/\s+/g, '');
52
+ return `clikgate-node/${sanitise(version_js_1.VERSION)} (node ${sanitise(nodeVersion)}; ${osName} ${archName})`;
53
+ }
@@ -0,0 +1,2 @@
1
+ /** The SDK version (kept equal to package.json by `npm run check:version`). */
2
+ export declare const VERSION = "2.0.0";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSION = void 0;
4
+ /** The SDK version (kept equal to package.json by `npm run check:version`). */
5
+ exports.VERSION = '2.0.0';
@@ -0,0 +1,36 @@
1
+ import type { WebhookEvent } from './types.js';
2
+ /** Options for webhook verification. */
3
+ export interface VerifyOptions {
4
+ /** Maximum age (and future skew) of the signature timestamp, in seconds. Default 300. `0` disables the check (tests only). */
5
+ tolerance?: number;
6
+ /** The current time in unix seconds (for tests). Default: now. */
7
+ now?: number;
8
+ }
9
+ /** The raw request body exactly as received. */
10
+ export type RawBody = string | Uint8Array | ArrayBuffer;
11
+ /**
12
+ * Webhook verification: `Clikgate-Signature: t=<unix>,v1=<hex>`,
13
+ * `hex = HMAC-SHA256(secret, "<t>." + raw body)`. No API key or client needed.
14
+ */
15
+ export declare const webhooks: {
16
+ /**
17
+ * Verify a delivery and return the parsed event. Throws {@link SignatureVerificationError}.
18
+ *
19
+ * @example
20
+ * import express from 'express';
21
+ * import { webhooks } from '@clikgate/node';
22
+ * app.post('/webhooks/clikgate', express.raw({ type: 'application/json' }), (req, res) => {
23
+ * const event = webhooks.verify(req.body, req.get('Clikgate-Signature'), process.env.CLIKGATE_WEBHOOK_SECRET!);
24
+ * if (event.type === 'goal.completed') { … } // dedupe on event.id: delivery is at-least-once
25
+ * res.sendStatus(200);
26
+ * });
27
+ */
28
+ verify<T = Record<string, unknown>>(rawBody: RawBody, signatureHeader: string | null | undefined, secret: string, options?: VerifyOptions): WebhookEvent<T>;
29
+ /**
30
+ * Like {@link webhooks.verify}, accepting any of several secrets (while you rotate your own).
31
+ *
32
+ * @example
33
+ * const event = webhooks.verifyAny(req.body, req.get('Clikgate-Signature'), [newSecret, oldSecret]);
34
+ */
35
+ verifyAny<T = Record<string, unknown>>(rawBody: RawBody, signatureHeader: string | null | undefined, secrets: string[], options?: VerifyOptions): WebhookEvent<T>;
36
+ };
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.webhooks = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const errors_js_1 = require("./errors.js");
6
+ const fail = (code, message) => new errors_js_1.SignatureVerificationError({ message, code });
7
+ function toBytes(raw) {
8
+ if (typeof raw === 'string')
9
+ return new TextEncoder().encode(raw);
10
+ if (raw instanceof Uint8Array)
11
+ return raw;
12
+ if (raw instanceof ArrayBuffer)
13
+ return new Uint8Array(raw);
14
+ throw fail('invalid_payload', 'Pass the raw request body (a string or Buffer), not parsed JSON: re-serialising changes the bytes Clikgate signed.');
15
+ }
16
+ function parseHeader(header) {
17
+ if (typeof header !== 'string' || header.trim() === '')
18
+ throw fail('missing_signature', 'The Clikgate-Signature header is missing.');
19
+ let t = null;
20
+ let bad = false;
21
+ const v1 = [];
22
+ for (const part of header.split(',')) {
23
+ const p = part.trim();
24
+ const eq = p.indexOf('=');
25
+ if (eq < 0)
26
+ continue;
27
+ const key = p.slice(0, eq).trim();
28
+ const value = p.slice(eq + 1).trim();
29
+ if (key === 't') {
30
+ if (/^\d+$/.test(value))
31
+ t = Number(value);
32
+ else
33
+ bad = true;
34
+ }
35
+ else if (key === 'v1')
36
+ v1.push(value);
37
+ }
38
+ if (bad || t === null || v1.length === 0)
39
+ throw fail('malformed_signature', 'The Clikgate-Signature header is malformed (expected t=<unix seconds>,v1=<hex>).');
40
+ return { t, v1 };
41
+ }
42
+ function safeEqualHex(a, b) {
43
+ const x = Buffer.from(a, 'utf8');
44
+ const y = Buffer.from(b, 'utf8');
45
+ if (x.length !== y.length)
46
+ return false;
47
+ return (0, node_crypto_1.timingSafeEqual)(x, y);
48
+ }
49
+ function verifyWith(rawBody, signatureHeader, secrets, options) {
50
+ const body = toBytes(rawBody);
51
+ const { t, v1 } = parseHeader(signatureHeader);
52
+ const tolerance = options.tolerance ?? 300;
53
+ const now = options.now ?? Math.floor(Date.now() / 1000);
54
+ if (tolerance > 0 && Math.abs(now - t) > tolerance) {
55
+ throw fail('timestamp_outside_tolerance', `The signature timestamp is more than ${tolerance} s from now; the request may be a replay, or this server's clock is wrong.`);
56
+ }
57
+ const matched = secrets.some((secret) => {
58
+ const expected = (0, node_crypto_1.createHmac)('sha256', secret).update(`${t}.`).update(body).digest('hex');
59
+ return v1.some((candidate) => safeEqualHex(expected, candidate));
60
+ });
61
+ if (!matched)
62
+ throw fail('no_matching_signature', 'No signature matches: check the endpoint secret, and that you pass the raw body.');
63
+ let event;
64
+ try {
65
+ event = JSON.parse(new TextDecoder().decode(body));
66
+ }
67
+ catch {
68
+ throw fail('invalid_payload', 'The body is not JSON.');
69
+ }
70
+ if (!event || typeof event !== 'object' || Array.isArray(event))
71
+ throw fail('invalid_payload', 'The body is not an event object.');
72
+ return event;
73
+ }
74
+ /**
75
+ * Webhook verification: `Clikgate-Signature: t=<unix>,v1=<hex>`,
76
+ * `hex = HMAC-SHA256(secret, "<t>." + raw body)`. No API key or client needed.
77
+ */
78
+ exports.webhooks = {
79
+ /**
80
+ * Verify a delivery and return the parsed event. Throws {@link SignatureVerificationError}.
81
+ *
82
+ * @example
83
+ * import express from 'express';
84
+ * import { webhooks } from '@clikgate/node';
85
+ * app.post('/webhooks/clikgate', express.raw({ type: 'application/json' }), (req, res) => {
86
+ * const event = webhooks.verify(req.body, req.get('Clikgate-Signature'), process.env.CLIKGATE_WEBHOOK_SECRET!);
87
+ * if (event.type === 'goal.completed') { … } // dedupe on event.id: delivery is at-least-once
88
+ * res.sendStatus(200);
89
+ * });
90
+ */
91
+ verify(rawBody, signatureHeader, secret, options = {}) {
92
+ if (typeof secret !== 'string' || secret.length === 0)
93
+ throw (0, errors_js_1.localError)('invalid_argument', 'secret must be the endpoint secret (whsec_…).', 'secret');
94
+ return verifyWith(rawBody, signatureHeader, [secret], options);
95
+ },
96
+ /**
97
+ * Like {@link webhooks.verify}, accepting any of several secrets (while you rotate your own).
98
+ *
99
+ * @example
100
+ * const event = webhooks.verifyAny(req.body, req.get('Clikgate-Signature'), [newSecret, oldSecret]);
101
+ */
102
+ verifyAny(rawBody, signatureHeader, secrets, options = {}) {
103
+ if (!Array.isArray(secrets) || secrets.length === 0 || secrets.some((s) => typeof s !== 'string' || s.length === 0)) {
104
+ throw (0, errors_js_1.localError)('invalid_argument', 'secrets must be a non-empty list of endpoint secrets.', 'secrets');
105
+ }
106
+ return verifyWith(rawBody, signatureHeader, secrets, options);
107
+ },
108
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Hashed email and phone for ad network matching. The values Clikgate accepts as
3
+ * `hashed_email`, `hashed_phone_e164` and `hashed_phone_digits`: SHA-256 as 64 lowercase hex characters.
4
+ */
5
+ export interface HashedIdentifiers {
6
+ /** SHA-256 of the email, trimmed and lowercased. */
7
+ hashedEmail?: string;
8
+ /** SHA-256 of the phone in E.164 with the `+` (`+2348031234567`). */
9
+ hashedPhoneE164?: string;
10
+ /** SHA-256 of the phone digits with the country code, no `+` (`2348031234567`). */
11
+ hashedPhoneDigits?: string;
12
+ }
13
+ /** Input of {@link hashForAds}. Leave a field out (or null) to hash only the other one. */
14
+ export interface HashForAdsInput {
15
+ /** The customer's email. */
16
+ email?: string | null;
17
+ /** The customer's phone, with its country code (`+234 803 123 4567` or `00234…`). */
18
+ phone?: string | null;
19
+ }
20
+ /**
21
+ * Normalise and hash an email and / or phone on your own server, for a goal's ad network matching
22
+ * (`hashedEmail`, `hashedPhoneE164`, `hashedPhoneDigits`). Pure and offline. In private mode Clikgate never
23
+ * hashes for you: hash on your server with this helper and send only the hashes.
24
+ *
25
+ * - email: trimmed and lowercased; it must contain `@`.
26
+ * - phone: must include its country code (start with `+` or `00`); spaces and punctuation are removed, and the
27
+ * result must be 7–15 digits starting with 1–9. A national number such as `0803 123 4567` is refused.
28
+ *
29
+ * @throws {InvalidRequestError} `invalid_argument` (param `email` or `phone`); the input is never in the message.
30
+ * @example
31
+ * clikgate.goal('account_opened', {
32
+ * reference: 'APP-55231',
33
+ * clickId,
34
+ * ...hashForAds({ email: customer.email, phone: customer.phone }), // e.g. '+234 803 123 4567'
35
+ * });
36
+ */
37
+ export declare function hashForAds(input: HashForAdsInput): HashedIdentifiers;
@@ -0,0 +1,62 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { localError } from './errors.js';
3
+ /** @internal The wire fields and their option names. */
4
+ export const HASHED_FIELDS = [
5
+ ['hashed_email', 'hashedEmail'],
6
+ ['hashed_phone_e164', 'hashedPhoneE164'],
7
+ ['hashed_phone_digits', 'hashedPhoneDigits'],
8
+ ];
9
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
10
+ const sha256 = (value) => createHash('sha256').update(value, 'utf8').digest('hex');
11
+ /**
12
+ * Normalise and hash an email and / or phone on your own server, for a goal's ad network matching
13
+ * (`hashedEmail`, `hashedPhoneE164`, `hashedPhoneDigits`). Pure and offline. In private mode Clikgate never
14
+ * hashes for you: hash on your server with this helper and send only the hashes.
15
+ *
16
+ * - email: trimmed and lowercased; it must contain `@`.
17
+ * - phone: must include its country code (start with `+` or `00`); spaces and punctuation are removed, and the
18
+ * result must be 7–15 digits starting with 1–9. A national number such as `0803 123 4567` is refused.
19
+ *
20
+ * @throws {InvalidRequestError} `invalid_argument` (param `email` or `phone`); the input is never in the message.
21
+ * @example
22
+ * clikgate.goal('account_opened', {
23
+ * reference: 'APP-55231',
24
+ * clickId,
25
+ * ...hashForAds({ email: customer.email, phone: customer.phone }), // e.g. '+234 803 123 4567'
26
+ * });
27
+ */
28
+ export function hashForAds(input) {
29
+ const out = {};
30
+ const { email, phone } = input ?? {};
31
+ if (email != null) {
32
+ const value = typeof email === 'string' ? email.trim().toLowerCase() : '';
33
+ if (!value.includes('@'))
34
+ throw localError('invalid_argument', 'email must be an email address (it contains @).', 'email');
35
+ out.hashedEmail = sha256(value);
36
+ }
37
+ if (phone != null) {
38
+ const trimmed = typeof phone === 'string' ? phone.trim() : '';
39
+ let digits = trimmed.replace(/\D/g, '');
40
+ if (trimmed.startsWith('00'))
41
+ digits = digits.slice(2);
42
+ else if (!trimmed.startsWith('+'))
43
+ digits = '';
44
+ if (!/^[1-9]\d{6,14}$/.test(digits)) {
45
+ throw localError('invalid_argument', 'phone must include its country code, e.g. "+234 803 123 4567" (7-15 digits after the +).', 'phone');
46
+ }
47
+ out.hashedPhoneE164 = sha256(`+${digits}`);
48
+ out.hashedPhoneDigits = sha256(digits);
49
+ }
50
+ return out;
51
+ }
52
+ /** @internal Refuse a hashed wire field that isn't 64 lowercase hex characters (the value is never echoed). */
53
+ export function checkHashedFields(wire) {
54
+ for (const [field] of HASHED_FIELDS) {
55
+ const v = wire[field];
56
+ if (v == null)
57
+ continue;
58
+ if (typeof v !== 'string' || !SHA256_HEX.test(v)) {
59
+ throw localError('invalid_hashed_identifier', `${field} must be a SHA-256 hash as 64 lowercase hex characters (use hashForAds).`, field);
60
+ }
61
+ }
62
+ }