@clikgate/node 0.0.0-stage → 2.0.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.
- package/CHANGELOG.md +136 -0
- package/LICENSE +21 -0
- package/README.md +311 -2
- package/SECURITY.md +34 -0
- package/dist/cjs/ads-hashing.d.ts +37 -0
- package/dist/cjs/ads-hashing.js +67 -0
- package/dist/cjs/click-ids.d.ts +184 -0
- package/dist/cjs/click-ids.js +535 -0
- package/dist/cjs/client.d.ts +191 -0
- package/dist/cjs/client.js +291 -0
- package/dist/cjs/config.d.ts +12 -0
- package/dist/cjs/config.js +87 -0
- package/dist/cjs/core.d.ts +15 -0
- package/dist/cjs/core.js +100 -0
- package/dist/cjs/customer-id.d.ts +26 -0
- package/dist/cjs/customer-id.js +52 -0
- package/dist/cjs/enums.d.ts +48 -0
- package/dist/cjs/enums.js +47 -0
- package/dist/cjs/errors.d.ts +117 -0
- package/dist/cjs/errors.js +257 -0
- package/dist/cjs/express.d.ts +49 -0
- package/dist/cjs/express.js +44 -0
- package/dist/cjs/fastify.d.ts +47 -0
- package/dist/cjs/fastify.js +35 -0
- package/dist/cjs/generated/index.d.ts +17793 -0
- package/dist/cjs/generated/index.js +8896 -0
- package/dist/cjs/goals.d.ts +116 -0
- package/dist/cjs/goals.js +381 -0
- package/dist/cjs/guard.d.ts +17 -0
- package/dist/cjs/guard.js +40 -0
- package/dist/cjs/http.d.ts +16 -0
- package/dist/cjs/http.js +148 -0
- package/dist/cjs/identity.d.ts +42 -0
- package/dist/cjs/identity.js +133 -0
- package/dist/cjs/index.d.ts +34 -0
- package/dist/cjs/index.js +70 -0
- package/dist/cjs/known-customers.d.ts +45 -0
- package/dist/cjs/known-customers.js +95 -0
- package/dist/cjs/logger.d.ts +9 -0
- package/dist/cjs/logger.js +8 -0
- package/dist/cjs/money.d.ts +16 -0
- package/dist/cjs/money.js +51 -0
- package/dist/cjs/next.d.ts +81 -0
- package/dist/cjs/next.js +103 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/payments.d.ts +174 -0
- package/dist/cjs/payments.js +485 -0
- package/dist/cjs/resources.d.ts +109 -0
- package/dist/cjs/resources.js +189 -0
- package/dist/cjs/shutdown.d.ts +2 -0
- package/dist/cjs/shutdown.js +51 -0
- package/dist/cjs/transport.d.ts +14 -0
- package/dist/cjs/transport.js +204 -0
- package/dist/cjs/types.d.ts +218 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/user-agent.d.ts +1 -0
- package/dist/cjs/user-agent.js +53 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +36 -0
- package/dist/cjs/webhooks.js +108 -0
- package/dist/esm/ads-hashing.d.ts +37 -0
- package/dist/esm/ads-hashing.js +62 -0
- package/dist/esm/click-ids.d.ts +184 -0
- package/dist/esm/click-ids.js +526 -0
- package/dist/esm/client.d.ts +191 -0
- package/dist/esm/client.js +287 -0
- package/dist/esm/config.d.ts +12 -0
- package/dist/esm/config.js +82 -0
- package/dist/esm/core.d.ts +15 -0
- package/dist/esm/core.js +96 -0
- package/dist/esm/customer-id.d.ts +26 -0
- package/dist/esm/customer-id.js +47 -0
- package/dist/esm/enums.d.ts +48 -0
- package/dist/esm/enums.js +44 -0
- package/dist/esm/errors.d.ts +117 -0
- package/dist/esm/errors.js +234 -0
- package/dist/esm/express.d.ts +49 -0
- package/dist/esm/express.js +40 -0
- package/dist/esm/fastify.d.ts +47 -0
- package/dist/esm/fastify.js +32 -0
- package/dist/esm/generated/index.d.ts +17793 -0
- package/dist/esm/generated/index.js +8833 -0
- package/dist/esm/goals.d.ts +116 -0
- package/dist/esm/goals.js +371 -0
- package/dist/esm/guard.d.ts +17 -0
- package/dist/esm/guard.js +36 -0
- package/dist/esm/http.d.ts +16 -0
- package/dist/esm/http.js +138 -0
- package/dist/esm/identity.d.ts +42 -0
- package/dist/esm/identity.js +125 -0
- package/dist/esm/index.d.ts +34 -0
- package/dist/esm/index.js +23 -0
- package/dist/esm/known-customers.d.ts +45 -0
- package/dist/esm/known-customers.js +90 -0
- package/dist/esm/logger.d.ts +9 -0
- package/dist/esm/logger.js +5 -0
- package/dist/esm/money.d.ts +16 -0
- package/dist/esm/money.js +48 -0
- package/dist/esm/next.d.ts +81 -0
- package/dist/esm/next.js +96 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/payments.d.ts +174 -0
- package/dist/esm/payments.js +476 -0
- package/dist/esm/resources.d.ts +109 -0
- package/dist/esm/resources.js +183 -0
- package/dist/esm/shutdown.d.ts +2 -0
- package/dist/esm/shutdown.js +47 -0
- package/dist/esm/transport.d.ts +14 -0
- package/dist/esm/transport.js +166 -0
- package/dist/esm/types.d.ts +218 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/user-agent.d.ts +1 -0
- package/dist/esm/user-agent.js +16 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +36 -0
- package/dist/esm/webhooks.js +105 -0
- package/package.json +128 -4
|
@@ -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,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
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
/** The click ID format: a prefixed ULID, `clk_` + 26 uppercase Crockford characters. */
|
|
3
|
+
export declare const CLICK_ID_PATTERN: RegExp;
|
|
4
|
+
/** The header a caller (e.g. your mobile app or BFF) can use to pass the click ID. */
|
|
5
|
+
export declare const CLICK_ID_HEADER = "clikgate-click-id";
|
|
6
|
+
/**
|
|
7
|
+
* Anything request-like: Node/Express/Connect/Fastify requests, Fetch `Request`, Next.js `NextRequest`,
|
|
8
|
+
* or a plain `{ url, headers }` object.
|
|
9
|
+
*/
|
|
10
|
+
export type RequestLike = {
|
|
11
|
+
url?: string;
|
|
12
|
+
originalUrl?: string;
|
|
13
|
+
headers?: unknown;
|
|
14
|
+
nextUrl?: {
|
|
15
|
+
href: string;
|
|
16
|
+
};
|
|
17
|
+
} | {
|
|
18
|
+
url: string;
|
|
19
|
+
headers: {
|
|
20
|
+
get(name: string): string | null;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
/** Anything response-like that can carry `Set-Cookie`: Node `ServerResponse`/Express `res`, Fastify `reply`, Fetch `Response`/`Headers`. */
|
|
24
|
+
export type ResponseLike = object;
|
|
25
|
+
/** Options for the click-ID cookie. */
|
|
26
|
+
export interface PersistOptions {
|
|
27
|
+
/** Lifetime in days (default 30). */
|
|
28
|
+
days?: number;
|
|
29
|
+
/** Add `Secure`. Default: true when the request was HTTPS (or unknown). */
|
|
30
|
+
secure?: boolean;
|
|
31
|
+
/** Cookie domain, e.g. `.example.com` to share across subdomains. */
|
|
32
|
+
domain?: string;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* True when `id` is a Clikgate click ID (`clk_` + 26 characters).
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* clickIds.isValid('clk_01JCK8Z9V7Q4M2N6P8R0S2T4W6'); // true
|
|
39
|
+
*/
|
|
40
|
+
export declare function isValid(id: unknown): id is string;
|
|
41
|
+
/** Click-ID helpers bound to a `click_id_param` (SPEC section 13). */
|
|
42
|
+
export declare class ClickIds {
|
|
43
|
+
private readonly param;
|
|
44
|
+
/** The query parameter name in use (`cgid` unless configured). */
|
|
45
|
+
get paramName(): string;
|
|
46
|
+
/** The cookie name: `_cg_<param>`, the same first-party cookie the web script writes. */
|
|
47
|
+
get cookieName(): string;
|
|
48
|
+
/** {@inheritDoc isValid} */
|
|
49
|
+
isValid(id: unknown): id is string;
|
|
50
|
+
/**
|
|
51
|
+
* Read the click ID from a request: the query parameter, then the `_cg_<param>` cookie, then the
|
|
52
|
+
* `Clikgate-Click-Id` header. Only valid IDs are returned.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* app.post('/signup', (req, res) => {
|
|
56
|
+
* const clickId = clikgate.clickIds.fromRequest(req); // save it with the application
|
|
57
|
+
* });
|
|
58
|
+
*/
|
|
59
|
+
fromRequest(req: RequestLike): string | null;
|
|
60
|
+
/** The click ID and where it was found (query, cookie or header). */
|
|
61
|
+
private locate;
|
|
62
|
+
/**
|
|
63
|
+
* The visitor context to send with a goal (SPEC 13.1): the click ID, how it was kept, and the browser engine and
|
|
64
|
+
* platform parsed from the `User-Agent` here in the SDK (the User-Agent itself is never sent). Spread it into the
|
|
65
|
+
* goal options.
|
|
66
|
+
*
|
|
67
|
+
* - `keptBy` is `server_cookie` when the ID came from the cookie and the `_cg_kept=s` marker is there (your server
|
|
68
|
+
* set it, see {@link keepRoute} and {@link persist}), `script_cookie` for the cookie without the marker, `form`
|
|
69
|
+
* for the `Clikgate-Click-Id` header, and `null` when it came from the URL or there is none.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* app.post('/signup', (req, res) => {
|
|
73
|
+
* clikgate.goal('account_opened', { reference: application.id, ...clikgate.clickIds.context(req) });
|
|
74
|
+
* });
|
|
75
|
+
*/
|
|
76
|
+
context(req: RequestLike): ClickContext;
|
|
77
|
+
/**
|
|
78
|
+
* The `Set-Cookie` value that keeps the click ID: `SameSite=Lax`, `Secure` on HTTPS, not `HttpOnly`
|
|
79
|
+
* (the web script reads it).
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* clikgate.clickIds.cookieHeader(clickId, { days: 30 });
|
|
83
|
+
* // '_cg_cgid=clk_…; Path=/; Max-Age=2592000; SameSite=Lax; Secure'
|
|
84
|
+
*/
|
|
85
|
+
cookieHeader(id: string, options?: PersistOptions): string;
|
|
86
|
+
/**
|
|
87
|
+
* Add the click-ID cookie to a response, keeping any `Set-Cookie` headers already there.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* const clickId = clikgate.clickIds.fromRequest(req);
|
|
91
|
+
* if (clickId) clikgate.clickIds.persist(res, clickId);
|
|
92
|
+
*/
|
|
93
|
+
persist(res: ResponseLike, id: string, options?: PersistOptions): void;
|
|
94
|
+
/**
|
|
95
|
+
* The `/cg/keep` handler (SPEC 13.1): the web script's `data-server-endpoint="/cg/keep"` posts the click ID from the
|
|
96
|
+
* page URL here, and your server sets the `_cg_<param>` cookie (plus the `_cg_kept=s` marker) for `days` days.
|
|
97
|
+
* Safari, and every browser on iPhone, keeps a click ID saved by a script for up to 7 days (sometimes less); a cookie
|
|
98
|
+
* your server sets lasts as long as you choose, up to the browser's limit. Serve it from the same host as your website.
|
|
99
|
+
*
|
|
100
|
+
* Returns a Fetch handler (`(Request) => Promise<Response>`, e.g. a Next.js App Router `POST`), with
|
|
101
|
+
* `.express` (Express/Connect) and `.node` (`node:http`) adapters, and `.handle` for any other framework.
|
|
102
|
+
* Only same-origin `POST`s with a valid, matching click ID are accepted; every answer is `no-store` with an
|
|
103
|
+
* empty body. `secure` defaults to true here.
|
|
104
|
+
*
|
|
105
|
+
* @throws InvalidRequestError `invalid_argument` when `days` is not 1-400.
|
|
106
|
+
* @example
|
|
107
|
+
* // app/cg/keep/route.ts
|
|
108
|
+
* export const POST = clikgate.clickIds.keepRoute();
|
|
109
|
+
* // Express
|
|
110
|
+
* app.all('/cg/keep', clikgate.clickIds.keepRoute({ days: 90 }).express);
|
|
111
|
+
*/
|
|
112
|
+
keepRoute(options?: KeepRouteOptions): KeepRoute;
|
|
113
|
+
/**
|
|
114
|
+
* Find the click ID in a payment provider's payload: Paystack `metadata` (and `custom_fields`),
|
|
115
|
+
* Flutterwave `meta`, Shopify note or cart attributes, WooCommerce order meta, or your own webhook.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* app.post('/paystack/webhook', express.json(), (req, res) => {
|
|
119
|
+
* const clickId = clikgate.clickIds.fromPaymentMetadata(req.body);
|
|
120
|
+
* });
|
|
121
|
+
*/
|
|
122
|
+
fromPaymentMetadata(payload: unknown): string | null;
|
|
123
|
+
}
|
|
124
|
+
/** How the click ID was kept (`kept_by`, SPEC 9.1). */
|
|
125
|
+
export type KeptBy = 'server_cookie' | 'script_cookie' | 'form' | 'payment_metadata' | 'unknown';
|
|
126
|
+
/** The browser engine family (`browser_engine`, SPEC 9.1). */
|
|
127
|
+
export type BrowserEngine = 'webkit_ios' | 'safari_mac' | 'chromium' | 'gecko' | 'other';
|
|
128
|
+
/** The visitor's platform (`platform`, SPEC 9.1). */
|
|
129
|
+
export type Platform = 'ios' | 'android' | 'macos' | 'windows' | 'linux' | 'other';
|
|
130
|
+
/** Every `kept_by` value. */
|
|
131
|
+
export declare const KEPT_BY: readonly KeptBy[];
|
|
132
|
+
/** Every `browser_engine` value. */
|
|
133
|
+
export declare const BROWSER_ENGINES: readonly BrowserEngine[];
|
|
134
|
+
/** Every `platform` value. */
|
|
135
|
+
export declare const PLATFORMS: readonly Platform[];
|
|
136
|
+
/** What `clickIds.context(req)` returns; its keys are goal options, so spread it into a goal. */
|
|
137
|
+
export interface ClickContext {
|
|
138
|
+
clickId: string | null;
|
|
139
|
+
keptBy: KeptBy | null;
|
|
140
|
+
browserEngine: BrowserEngine;
|
|
141
|
+
platform: Platform;
|
|
142
|
+
}
|
|
143
|
+
/** Options for `clickIds.keepRoute()`. */
|
|
144
|
+
export interface KeepRouteOptions {
|
|
145
|
+
/** Cookie lifetime in days, 1-400 (default 30). */
|
|
146
|
+
days?: number;
|
|
147
|
+
/** Add `Secure` (default true). */
|
|
148
|
+
secure?: boolean;
|
|
149
|
+
/** Cookie domain, e.g. `.example.com` to share across subdomains. */
|
|
150
|
+
domain?: string;
|
|
151
|
+
}
|
|
152
|
+
/** A framework-neutral `/cg/keep` request. `readBody` returns the raw body, or `null` when it is over 1024 bytes. */
|
|
153
|
+
export interface KeepInput {
|
|
154
|
+
method: string;
|
|
155
|
+
/** Header names in any case: a plain object, a Node `IncomingHttpHeaders` or a Fetch `Headers`. */
|
|
156
|
+
headers: unknown;
|
|
157
|
+
readBody: () => Promise<Uint8Array | null>;
|
|
158
|
+
/** The request URL, used for the host only when there is no `Host` header. Its query string is never read. */
|
|
159
|
+
url?: string;
|
|
160
|
+
}
|
|
161
|
+
/** A `/cg/keep` answer: the status and the headers to send (the body is always empty). */
|
|
162
|
+
export interface KeepResult {
|
|
163
|
+
status: 204 | 400 | 403 | 405;
|
|
164
|
+
headers: Array<[string, string]>;
|
|
165
|
+
}
|
|
166
|
+
type NodeReq = IncomingMessage & {
|
|
167
|
+
body?: unknown;
|
|
168
|
+
};
|
|
169
|
+
type NodeRes = ServerResponse;
|
|
170
|
+
/** The `/cg/keep` route: a Fetch handler plus framework adapters. */
|
|
171
|
+
export interface KeepRoute {
|
|
172
|
+
(request: Request): Promise<Response>;
|
|
173
|
+
/** Express / Connect: `app.all('/cg/keep', route.express)` (mount it before a body parser, or after one, both work). */
|
|
174
|
+
express: (req: NodeReq, res: NodeRes, next?: (err?: unknown) => void) => void;
|
|
175
|
+
/** Plain `node:http`: `if (req.url === '/cg/keep') return route.node(req, res)`. */
|
|
176
|
+
node: (req: NodeReq, res: NodeRes) => void;
|
|
177
|
+
/** The framework-neutral core, for any other framework. */
|
|
178
|
+
handle: (input: KeepInput) => Promise<KeepResult>;
|
|
179
|
+
}
|
|
180
|
+
/** The marker cookie that tells the web script (and `context()`) that your server kept the click ID. */
|
|
181
|
+
export declare const KEPT_COOKIE = "_cg_kept";
|
|
182
|
+
/** Click-ID helpers with the default parameter (`cgid`), usable without a client. */
|
|
183
|
+
export declare const clickIds: ClickIds;
|
|
184
|
+
export {};
|