@clikgate/node 2.0.0 → 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 +10 -0
- package/README.md +11 -0
- package/dist/cjs/client.d.ts +16 -0
- package/dist/cjs/client.js +25 -0
- package/dist/cjs/customer-id.d.ts +26 -0
- package/dist/cjs/customer-id.js +52 -0
- package/dist/cjs/enums.js +1 -1
- package/dist/cjs/errors.d.ts +1 -1
- package/dist/cjs/generated/index.d.ts +265 -6
- package/dist/cjs/generated/index.js +83 -3
- package/dist/cjs/identity.d.ts +12 -2
- package/dist/cjs/identity.js +36 -2
- package/dist/cjs/index.d.ts +2 -0
- package/dist/cjs/index.js +7 -1
- package/dist/cjs/known-customers.d.ts +45 -0
- package/dist/cjs/known-customers.js +95 -0
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/esm/client.d.ts +16 -0
- package/dist/esm/client.js +25 -0
- package/dist/esm/customer-id.d.ts +26 -0
- package/dist/esm/customer-id.js +47 -0
- package/dist/esm/enums.js +1 -1
- package/dist/esm/errors.d.ts +1 -1
- package/dist/esm/generated/index.d.ts +265 -6
- package/dist/esm/generated/index.js +80 -1
- package/dist/esm/identity.d.ts +12 -2
- package/dist/esm/identity.js +35 -2
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/known-customers.d.ts +45 -0
- package/dist/esm/known-customers.js +90 -0
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/package.json +1 -1
package/dist/cjs/identity.js
CHANGED
|
@@ -3,15 +3,21 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.IDENTITY_SECRETS_ENV = exports.IDENTITY_SECRET_ENV = void 0;
|
|
4
4
|
exports.isBrowserOrMobile = isBrowserOrMobile;
|
|
5
5
|
exports.signIdentityToken = signIdentityToken;
|
|
6
|
+
exports.signIdentityTokenV2 = signIdentityTokenV2;
|
|
6
7
|
exports.createIdentityTokenWith = createIdentityTokenWith;
|
|
7
8
|
exports.createIdentityToken = createIdentityToken;
|
|
8
9
|
const node_crypto_1 = require("node:crypto");
|
|
10
|
+
const customer_id_js_1 = require("./customer-id.js");
|
|
9
11
|
const errors_js_1 = require("./errors.js");
|
|
10
12
|
/** The single secret's environment variable. */
|
|
11
13
|
exports.IDENTITY_SECRET_ENV = 'CLIKGATE_IDENTITY_SECRET';
|
|
12
14
|
/** The per-app map's environment variable: a JSON object `{"app_…": "cgis_…"}`. */
|
|
13
15
|
exports.IDENTITY_SECRETS_ENV = 'CLIKGATE_IDENTITY_SECRETS';
|
|
14
16
|
const MAX_CUSTOMER_ID = 255;
|
|
17
|
+
/** 1990-01-01: earlier account dates are refused. */
|
|
18
|
+
const MIN_CUSTOMER_SINCE = 631_152_000;
|
|
19
|
+
/** The clock allowance for an account date after `issuedAt`. */
|
|
20
|
+
const CLOCK_ALLOWANCE = 300;
|
|
15
21
|
/** @internal True in a browser (window or document) or React Native. */
|
|
16
22
|
function isBrowserOrMobile(g = globalThis) {
|
|
17
23
|
if (typeof g.window !== 'undefined' || typeof g.document !== 'undefined')
|
|
@@ -68,6 +74,22 @@ function signIdentityToken(secret, customerId, issuedAt) {
|
|
|
68
74
|
const sig = (0, node_crypto_1.createHmac)('sha256', Buffer.from(secret, 'utf8')).update(Buffer.from(`${customerId}.${issuedAt}`, 'utf8')).digest('base64url');
|
|
69
75
|
return `${sig}.${issuedAt}`;
|
|
70
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* @internal Version 2: the MAC input is
|
|
79
|
+
* `"v2\n" + utf8Length(cid) + ":" + cid + "\n" + issuedAt + "\n" + customerSince`, cid in canonical form.
|
|
80
|
+
*/
|
|
81
|
+
function signIdentityTokenV2(secret, customerId, issuedAt, customerSince) {
|
|
82
|
+
const cid = (0, customer_id_js_1.canonicalCustomerId)(customerId);
|
|
83
|
+
const msg = `v2\n${Buffer.byteLength(cid, 'utf8')}:${cid}\n${issuedAt}\n${customerSince}`;
|
|
84
|
+
const sig = (0, node_crypto_1.createHmac)('sha256', Buffer.from(secret, 'utf8')).update(Buffer.from(msg, 'utf8')).digest('base64url');
|
|
85
|
+
return `${sig}.${issuedAt}.${customerSince}`;
|
|
86
|
+
}
|
|
87
|
+
function sinceSeconds(value) {
|
|
88
|
+
const s = value instanceof Date ? Math.floor(value.getTime() / 1000) : value;
|
|
89
|
+
if (typeof s !== 'number' || !Number.isSafeInteger(s))
|
|
90
|
+
throw (0, errors_js_1.localError)('invalid_argument', 'customerSince must be a Date or whole Unix seconds.', 'customer_since');
|
|
91
|
+
return s;
|
|
92
|
+
}
|
|
71
93
|
/** @internal createIdentityToken with an explicit secret source (the client's options). */
|
|
72
94
|
function createIdentityTokenWith(source, customerId, options = {}) {
|
|
73
95
|
if (isBrowserOrMobile())
|
|
@@ -80,7 +102,16 @@ function createIdentityTokenWith(source, customerId, options = {}) {
|
|
|
80
102
|
const issuedAt = o.issuedAt ?? Math.floor(Date.now() / 1000);
|
|
81
103
|
if (!Number.isSafeInteger(issuedAt) || issuedAt < 0)
|
|
82
104
|
throw (0, errors_js_1.localError)('invalid_argument', 'issuedAt must be whole Unix seconds.', 'issued_at');
|
|
83
|
-
|
|
105
|
+
if (o.customerSince == null)
|
|
106
|
+
return signIdentityToken(resolveSecret(o, source), customerId, issuedAt);
|
|
107
|
+
const since = sinceSeconds(o.customerSince);
|
|
108
|
+
if (since < MIN_CUSTOMER_SINCE || since > issuedAt + CLOCK_ALLOWANCE) {
|
|
109
|
+
throw (0, errors_js_1.localError)('invalid_argument', 'customerSince must be between 1990 and the time the token is issued.', 'customer_since');
|
|
110
|
+
}
|
|
111
|
+
const cid = (0, customer_id_js_1.canonicalCustomerId)(customerId);
|
|
112
|
+
if (cid === '')
|
|
113
|
+
throw (0, errors_js_1.localError)('invalid_customer_id', 'customerId must be your own user ID as a string of 1-255 characters (never an email or phone number).', 'customer_id');
|
|
114
|
+
return signIdentityTokenV2(resolveSecret(o, source), cid, issuedAt, since);
|
|
84
115
|
}
|
|
85
116
|
/**
|
|
86
117
|
* Create an identity token for the signed-in user. Return it in your sign-in and "current user"
|
|
@@ -88,11 +119,14 @@ function createIdentityTokenWith(source, customerId, options = {}) {
|
|
|
88
119
|
* secret from `CLIKGATE_IDENTITY_SECRETS` (a JSON map). No network call; no API key needed.
|
|
89
120
|
*
|
|
90
121
|
* Throws {@link ClikgateServerOnlyError} in a browser or React Native, `ConfigurationError` when no secret is set,
|
|
91
|
-
*
|
|
122
|
+
* `InvalidRequestError` (`invalid_customer_id`) for an empty or over-long customer ID, and `InvalidRequestError`
|
|
123
|
+
* (`invalid_argument`, param `customer_since`) for an account date before 1990 or after the token's issue time.
|
|
92
124
|
*
|
|
93
125
|
* @example
|
|
94
126
|
* import { createIdentityToken } from '@clikgate/node';
|
|
95
127
|
* res.json({ user, clikgateIdentityToken: createIdentityToken(user.id) });
|
|
128
|
+
* // With the account date (version 2), so existing customers are never counted as referrals or new customers:
|
|
129
|
+
* res.json({ user, clikgateIdentityToken: createIdentityToken(user.id, { customerSince: user.createdAt }) });
|
|
96
130
|
*/
|
|
97
131
|
function createIdentityToken(customerId, options = {}) {
|
|
98
132
|
return createIdentityTokenWith({}, customerId, options);
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
export { Clikgate, type ClikgateOptions, type IdentifyUserParams, type PersonIdentified } from './client.js';
|
|
13
13
|
export { ClickIds, clickIds, isValid as isValidClickId, CLICK_ID_PATTERN, CLICK_ID_HEADER, KEPT_COOKIE, KEPT_BY, BROWSER_ENGINES, PLATFORMS, type PersistOptions, type RequestLike, type ResponseLike, type KeptBy, type BrowserEngine, type Platform, type ClickContext, type KeepRoute, type KeepRouteOptions, type KeepInput, type KeepResult, } from './click-ids.js';
|
|
14
14
|
export { webhooks, type VerifyOptions, type RawBody } from './webhooks.js';
|
|
15
|
+
export { canonicalCustomerId, customerIdWarning, CUSTOMER_ID_MAX_LENGTH, type CustomerIdWarning } from './customer-id.js';
|
|
16
|
+
export { KNOWN_CUSTOMERS_BATCH, type KnownCustomers, type KnownCustomer, type KnownCustomerRefusal, type KnownCustomersImportResult } from './known-customers.js';
|
|
15
17
|
export { createIdentityToken, IDENTITY_SECRET_ENV, IDENTITY_SECRETS_ENV, type IdentityTokenOptions } from './identity.js';
|
|
16
18
|
export { formatValue, type MoneyInput } from './money.js';
|
|
17
19
|
export { hashForAds, type HashForAdsInput, type HashedIdentifiers } from './ads-hashing.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.VERSION = exports.ClikgateServerOnlyError = exports.SignatureVerificationError = exports.TimeoutError = exports.NetworkError = exports.ServerError = exports.RateLimitError = exports.IdempotencyError = exports.LinkLockedError = exports.ConflictError = exports.NotFoundError = exports.PrivateModeFieldRejectedError = exports.InvalidRequestError = exports.PermissionError = exports.AuthenticationError = exports.ConfigurationError = exports.ClikgateError = exports.buildFromStripe = exports.buildFromMonnify = exports.buildFromFlutterwave = exports.buildFromPaystack = exports.Provider = exports.GoalStatus = exports.GoalKind = exports.hashForAds = exports.formatValue = exports.IDENTITY_SECRETS_ENV = exports.IDENTITY_SECRET_ENV = exports.createIdentityToken = exports.webhooks = exports.PLATFORMS = exports.BROWSER_ENGINES = exports.KEPT_BY = exports.KEPT_COOKIE = exports.CLICK_ID_HEADER = exports.CLICK_ID_PATTERN = exports.isValidClickId = exports.clickIds = exports.ClickIds = exports.Clikgate = void 0;
|
|
3
|
+
exports.VERSION = exports.ClikgateServerOnlyError = exports.SignatureVerificationError = exports.TimeoutError = exports.NetworkError = exports.ServerError = exports.RateLimitError = exports.IdempotencyError = exports.LinkLockedError = exports.ConflictError = exports.NotFoundError = exports.PrivateModeFieldRejectedError = exports.InvalidRequestError = exports.PermissionError = exports.AuthenticationError = exports.ConfigurationError = exports.ClikgateError = exports.buildFromStripe = exports.buildFromMonnify = exports.buildFromFlutterwave = exports.buildFromPaystack = exports.Provider = exports.GoalStatus = exports.GoalKind = exports.hashForAds = exports.formatValue = exports.IDENTITY_SECRETS_ENV = exports.IDENTITY_SECRET_ENV = exports.createIdentityToken = exports.KNOWN_CUSTOMERS_BATCH = exports.CUSTOMER_ID_MAX_LENGTH = exports.customerIdWarning = exports.canonicalCustomerId = exports.webhooks = exports.PLATFORMS = exports.BROWSER_ENGINES = exports.KEPT_BY = exports.KEPT_COOKIE = exports.CLICK_ID_HEADER = exports.CLICK_ID_PATTERN = exports.isValidClickId = exports.clickIds = exports.ClickIds = exports.Clikgate = void 0;
|
|
4
4
|
/**
|
|
5
5
|
* The official Clikgate server SDK for Node.js and TypeScript.
|
|
6
6
|
*
|
|
@@ -26,6 +26,12 @@ Object.defineProperty(exports, "BROWSER_ENGINES", { enumerable: true, get: funct
|
|
|
26
26
|
Object.defineProperty(exports, "PLATFORMS", { enumerable: true, get: function () { return click_ids_js_1.PLATFORMS; } });
|
|
27
27
|
var webhooks_js_1 = require("./webhooks.js");
|
|
28
28
|
Object.defineProperty(exports, "webhooks", { enumerable: true, get: function () { return webhooks_js_1.webhooks; } });
|
|
29
|
+
var customer_id_js_1 = require("./customer-id.js");
|
|
30
|
+
Object.defineProperty(exports, "canonicalCustomerId", { enumerable: true, get: function () { return customer_id_js_1.canonicalCustomerId; } });
|
|
31
|
+
Object.defineProperty(exports, "customerIdWarning", { enumerable: true, get: function () { return customer_id_js_1.customerIdWarning; } });
|
|
32
|
+
Object.defineProperty(exports, "CUSTOMER_ID_MAX_LENGTH", { enumerable: true, get: function () { return customer_id_js_1.CUSTOMER_ID_MAX_LENGTH; } });
|
|
33
|
+
var known_customers_js_1 = require("./known-customers.js");
|
|
34
|
+
Object.defineProperty(exports, "KNOWN_CUSTOMERS_BATCH", { enumerable: true, get: function () { return known_customers_js_1.KNOWN_CUSTOMERS_BATCH; } });
|
|
29
35
|
var identity_js_1 = require("./identity.js");
|
|
30
36
|
Object.defineProperty(exports, "createIdentityToken", { enumerable: true, get: function () { return identity_js_1.createIdentityToken; } });
|
|
31
37
|
Object.defineProperty(exports, "IDENTITY_SECRET_ENV", { enumerable: true, get: function () { return identity_js_1.IDENTITY_SECRET_ENV; } });
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { RequestOptions } from './http.js';
|
|
2
|
+
/**
|
|
3
|
+
* Known customers: people who were already your customers before you added Clikgate. Clikgate uses
|
|
4
|
+
* them so an existing customer is never counted as a referral or a new customer. It stores a keyed fingerprint of
|
|
5
|
+
* each ID, not the ID itself. Not available in private mode.
|
|
6
|
+
*/
|
|
7
|
+
/** One existing customer: your customer ID and, optionally, when they became a customer. */
|
|
8
|
+
export interface KnownCustomer {
|
|
9
|
+
customerId: string;
|
|
10
|
+
/** When they became a customer: `'YYYY-MM-DD'`, a `Date` or Unix seconds. Only the UTC day is sent. */
|
|
11
|
+
customerSince?: string | Date | number | null;
|
|
12
|
+
}
|
|
13
|
+
/** Why rows were refused. Counts only: the API never returns the refused IDs. */
|
|
14
|
+
export type KnownCustomerRefusal = 'looks_like_email' | 'looks_like_phone' | 'looks_like_national_id' | 'empty' | 'too_long' | 'bad_date' | 'date_out_of_range';
|
|
15
|
+
/** The answer of `knownCustomers.import()`, summed over every batch. */
|
|
16
|
+
export interface KnownCustomersImportResult {
|
|
17
|
+
accepted: number;
|
|
18
|
+
refused: number;
|
|
19
|
+
refused_by_reason: Partial<Record<KnownCustomerRefusal | string, number>>;
|
|
20
|
+
}
|
|
21
|
+
/** The API's batch size; `import()` splits larger lists. */
|
|
22
|
+
export declare const KNOWN_CUSTOMERS_BATCH = 10000;
|
|
23
|
+
/** `clikgate.knownCustomers`: import and remove existing customers (scope `people:write`). */
|
|
24
|
+
export declare class KnownCustomers {
|
|
25
|
+
private readonly core;
|
|
26
|
+
/**
|
|
27
|
+
* Import existing customers (`POST /v1/known-customers/import`), in batches of 10,000. Idempotent per customer ID.
|
|
28
|
+
* Use your own customer IDs, never emails or phone numbers. The result sums every batch; refused rows are counted
|
|
29
|
+
* by reason, never returned.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* const result = await clikgate.knownCustomers.import([{ customerId: 'u_10482', customerSince: '2024-03-02' }]);
|
|
33
|
+
* console.log(result.accepted, result.refused_by_reason);
|
|
34
|
+
*/
|
|
35
|
+
import(customers: readonly KnownCustomer[], requestOptions?: RequestOptions): Promise<KnownCustomersImportResult>;
|
|
36
|
+
/**
|
|
37
|
+
* Remove one imported customer (`POST /v1/known-customers/remove`; the ID travels in the body, never in a URL).
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* const { removed } = await clikgate.knownCustomers.remove('u_10482');
|
|
41
|
+
*/
|
|
42
|
+
remove(customerId: string, requestOptions?: RequestOptions): Promise<{
|
|
43
|
+
removed: boolean;
|
|
44
|
+
}>;
|
|
45
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.KnownCustomers = exports.KNOWN_CUSTOMERS_BATCH = void 0;
|
|
4
|
+
exports.sinceDay = sinceDay;
|
|
5
|
+
const errors_js_1 = require("./errors.js");
|
|
6
|
+
/** The API's batch size; `import()` splits larger lists. */
|
|
7
|
+
exports.KNOWN_CUSTOMERS_BATCH = 10_000;
|
|
8
|
+
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
9
|
+
/** @internal The UTC day `YYYY-MM-DD` of a customerSince value. */
|
|
10
|
+
function sinceDay(value) {
|
|
11
|
+
if (typeof value === 'string') {
|
|
12
|
+
if (!DAY.test(value))
|
|
13
|
+
throw (0, errors_js_1.localError)('invalid_argument', "customerSince must be 'YYYY-MM-DD', a Date or Unix seconds.", 'customer_since');
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
const ms = typeof value === 'number' ? value * 1000 : value instanceof Date ? value.getTime() : Number.NaN;
|
|
17
|
+
if (!Number.isFinite(ms) || (typeof value === 'number' && !Number.isSafeInteger(value))) {
|
|
18
|
+
throw (0, errors_js_1.localError)('invalid_argument', "customerSince must be 'YYYY-MM-DD', a Date or Unix seconds.", 'customer_since');
|
|
19
|
+
}
|
|
20
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
21
|
+
}
|
|
22
|
+
function privateModeConflict() {
|
|
23
|
+
return new errors_js_1.ConflictError({
|
|
24
|
+
message: "Private mode is on: known customers can't be imported or removed.",
|
|
25
|
+
code: 'private_mode_conflict',
|
|
26
|
+
httpStatus: null,
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/** `clikgate.knownCustomers`: import and remove existing customers (scope `people:write`). */
|
|
30
|
+
class KnownCustomers {
|
|
31
|
+
core;
|
|
32
|
+
/** @internal */
|
|
33
|
+
constructor(core) {
|
|
34
|
+
this.core = core;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Import existing customers (`POST /v1/known-customers/import`), in batches of 10,000. Idempotent per customer ID.
|
|
38
|
+
* Use your own customer IDs, never emails or phone numbers. The result sums every batch; refused rows are counted
|
|
39
|
+
* by reason, never returned.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* const result = await clikgate.knownCustomers.import([{ customerId: 'u_10482', customerSince: '2024-03-02' }]);
|
|
43
|
+
* console.log(result.accepted, result.refused_by_reason);
|
|
44
|
+
*/
|
|
45
|
+
async import(customers, requestOptions = {}) {
|
|
46
|
+
if (!Array.isArray(customers))
|
|
47
|
+
throw (0, errors_js_1.localError)('invalid_argument', 'customers must be an array.', 'customers');
|
|
48
|
+
const rows = customers.map((c, i) => {
|
|
49
|
+
if (!c || typeof c.customerId !== 'string')
|
|
50
|
+
throw (0, errors_js_1.localError)('invalid_argument', `customers[${i}].customerId must be a string.`, 'customer_id');
|
|
51
|
+
const row = { customer_id: c.customerId };
|
|
52
|
+
if (c.customerSince != null)
|
|
53
|
+
row.customer_since = sinceDay(c.customerSince);
|
|
54
|
+
return row;
|
|
55
|
+
});
|
|
56
|
+
const total = { accepted: 0, refused: 0, refused_by_reason: {} };
|
|
57
|
+
if (rows.length === 0)
|
|
58
|
+
return total;
|
|
59
|
+
if ((await this.core.guardState()).guard)
|
|
60
|
+
throw privateModeConflict();
|
|
61
|
+
const several = rows.length > exports.KNOWN_CUSTOMERS_BATCH;
|
|
62
|
+
for (let i = 0; i < rows.length; i += exports.KNOWN_CUSTOMERS_BATCH) {
|
|
63
|
+
// One idempotency key per batch: a key you pass gets the batch number appended
|
|
64
|
+
const key = requestOptions.idempotencyKey;
|
|
65
|
+
const options = several && key ? { ...requestOptions, idempotencyKey: `${key}-${i / exports.KNOWN_CUSTOMERS_BATCH}` } : requestOptions;
|
|
66
|
+
const { data } = await this.core.requester.request({
|
|
67
|
+
method: 'POST',
|
|
68
|
+
path: '/v1/known-customers/import',
|
|
69
|
+
body: { customers: rows.slice(i, i + exports.KNOWN_CUSTOMERS_BATCH) },
|
|
70
|
+
...options,
|
|
71
|
+
});
|
|
72
|
+
total.accepted += data.accepted ?? 0;
|
|
73
|
+
total.refused += data.refused ?? 0;
|
|
74
|
+
for (const [reason, n] of Object.entries(data.refused_by_reason ?? {})) {
|
|
75
|
+
total.refused_by_reason[reason] = (total.refused_by_reason[reason] ?? 0) + (n ?? 0);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return total;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Remove one imported customer (`POST /v1/known-customers/remove`; the ID travels in the body, never in a URL).
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* const { removed } = await clikgate.knownCustomers.remove('u_10482');
|
|
85
|
+
*/
|
|
86
|
+
async remove(customerId, requestOptions = {}) {
|
|
87
|
+
if (typeof customerId !== 'string' || customerId === '')
|
|
88
|
+
throw (0, errors_js_1.localError)('invalid_customer_id', 'customerId must be a non-empty string.', 'customer_id');
|
|
89
|
+
if ((await this.core.guardState()).guard)
|
|
90
|
+
throw privateModeConflict();
|
|
91
|
+
const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/known-customers/remove', body: { customer_id: customerId }, ...requestOptions });
|
|
92
|
+
return data;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
exports.KnownCustomers = KnownCustomers;
|
package/dist/cjs/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** The SDK version (kept equal to package.json by `npm run check:version`). */
|
|
2
|
-
export declare const VERSION = "2.0.
|
|
2
|
+
export declare const VERSION = "2.0.1";
|
package/dist/cjs/version.js
CHANGED
package/dist/esm/client.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { Goals, type GoalOptions } from './goals.js';
|
|
|
7
7
|
import { type Clock } from './http.js';
|
|
8
8
|
import { type Logger } from './logger.js';
|
|
9
9
|
import { Payments } from './payments.js';
|
|
10
|
+
import { KnownCustomers } from './known-customers.js';
|
|
10
11
|
import { Clicks, Conversions, Links } from './resources.js';
|
|
11
12
|
import { type FetchLike } from './transport.js';
|
|
12
13
|
import type { ServerSdkConfig } from './types.js';
|
|
@@ -23,6 +24,13 @@ export interface IdentifyUserParams {
|
|
|
23
24
|
customerId?: string | null;
|
|
24
25
|
/** A label your team sees instead of the click ID (1–80 characters, `''` clears it). */
|
|
25
26
|
label?: string | null;
|
|
27
|
+
/**
|
|
28
|
+
* When this customer became your customer: `'YYYY-MM-DD'`, an ISO 8601 date-time with offset, a
|
|
29
|
+
* `Date` or Unix seconds. Needs `customerId`. Clikgate keeps the earliest date it gets. Not in private mode.
|
|
30
|
+
*/
|
|
31
|
+
customerSince?: string | Date | number | null;
|
|
32
|
+
/** `true` lets `customerSince` move a wrong date later (audit-logged). Default: the earliest date is kept. */
|
|
33
|
+
customerSinceReplace?: boolean | null;
|
|
26
34
|
}
|
|
27
35
|
/** The answer of `identifyUser()`. */
|
|
28
36
|
export interface PersonIdentified {
|
|
@@ -30,6 +38,10 @@ export interface PersonIdentified {
|
|
|
30
38
|
person_id: string;
|
|
31
39
|
/** `plan`: below Growth the label isn't stored; `lower_rank`: a label your team set was kept. */
|
|
32
40
|
label_ignored: 'plan' | 'lower_rank' | null;
|
|
41
|
+
/** Why `customerSince` wasn't used: `unverified` or `invalid`. */
|
|
42
|
+
customer_since_ignored?: 'unverified' | 'invalid' | null;
|
|
43
|
+
/** The customer ID looks like an email, phone number or national ID: use your own user ID instead. */
|
|
44
|
+
customer_id_warning?: 'looks_like_email' | 'looks_like_phone' | 'looks_like_national_id' | null;
|
|
33
45
|
}
|
|
34
46
|
export interface ClikgateOptions {
|
|
35
47
|
/** `cg_live_…` or `cg_test_…`. Default: `process.env.CLIKGATE_API_KEY`. The mode comes from the prefix. */
|
|
@@ -92,6 +104,8 @@ export declare class Clikgate {
|
|
|
92
104
|
readonly links: Links;
|
|
93
105
|
/** Clicks. */
|
|
94
106
|
readonly clicks: Clicks;
|
|
107
|
+
/** Existing customers from before you added Clikgate: `import()` and `remove()`. */
|
|
108
|
+
readonly knownCustomers: KnownCustomers;
|
|
95
109
|
/** Click-ID helpers using this client's `clickIdParam` (or the organisation's from config). */
|
|
96
110
|
readonly clickIds: ClickIds;
|
|
97
111
|
/** Every API-key operation, generated from openapi.json ("advanced"). */
|
|
@@ -134,6 +148,8 @@ export declare class Clikgate {
|
|
|
134
148
|
* customer. `label` is what your team sees instead of the click ID (1–80 characters, `''` clears it; Growth and
|
|
135
149
|
* up). Always verified (your server), so it also satisfies a referral program's `require_identity_token`.
|
|
136
150
|
* In private mode `customerId` is refused locally (the guard) and `label` needs "Allow labels in private mode".
|
|
151
|
+
* `customerSince` is when they became your customer, so existing customers are never counted as
|
|
152
|
+
* referrals or new customers; it is refused in private mode too.
|
|
137
153
|
*
|
|
138
154
|
* Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app reads
|
|
139
155
|
* `getInstallationId()` and sends it in its sign-in request; your server calls this with
|
package/dist/esm/client.js
CHANGED
|
@@ -9,11 +9,24 @@ import { GoalQueue, Goals, asClikgateError, buildGoalWire, checkBeforeSend } fro
|
|
|
9
9
|
import { Requester, systemClock } from './http.js';
|
|
10
10
|
import { consoleLogger } from './logger.js';
|
|
11
11
|
import { Payments } from './payments.js';
|
|
12
|
+
import { KnownCustomers } from './known-customers.js';
|
|
12
13
|
import { Clicks, Conversions, Links } from './resources.js';
|
|
13
14
|
import { registerShutdown, unregisterShutdown } from './shutdown.js';
|
|
14
15
|
import { fetchTransport, nodeTransport } from './transport.js';
|
|
15
16
|
import { userAgent } from './user-agent.js';
|
|
16
17
|
import { webhooks } from './webhooks.js';
|
|
18
|
+
/** @internal The wire form of identifyUser's customerSince. */
|
|
19
|
+
function sinceWire(value) {
|
|
20
|
+
if (typeof value === 'string') {
|
|
21
|
+
if (!/^\d{4}-\d{2}-\d{2}(T.+)?$/.test(value))
|
|
22
|
+
throw localError('invalid_argument', "customerSince must be 'YYYY-MM-DD', an ISO 8601 date-time, a Date or Unix seconds.", 'customer_since');
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
const ms = value instanceof Date ? value.getTime() : typeof value === 'number' && Number.isSafeInteger(value) ? value * 1000 : Number.NaN;
|
|
26
|
+
if (!Number.isFinite(ms))
|
|
27
|
+
throw localError('invalid_argument', "customerSince must be 'YYYY-MM-DD', an ISO 8601 date-time, a Date or Unix seconds.", 'customer_since');
|
|
28
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
29
|
+
}
|
|
17
30
|
const KEY = /^cg_(live|test)_[A-Za-z0-9_]+$/;
|
|
18
31
|
const PARAM = /^[A-Za-z0-9_]{1,32}$/;
|
|
19
32
|
const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
@@ -54,6 +67,8 @@ export class Clikgate {
|
|
|
54
67
|
links;
|
|
55
68
|
/** Clicks. */
|
|
56
69
|
clicks;
|
|
70
|
+
/** Existing customers from before you added Clikgate: `import()` and `remove()`. */
|
|
71
|
+
knownCustomers;
|
|
57
72
|
/** Click-ID helpers using this client's `clickIdParam` (or the organisation's from config). */
|
|
58
73
|
clickIds;
|
|
59
74
|
/** Every API-key operation, generated from openapi.json ("advanced"). */
|
|
@@ -113,6 +128,7 @@ export class Clikgate {
|
|
|
113
128
|
this.payments = new Payments(this.core);
|
|
114
129
|
this.links = new Links(this.core);
|
|
115
130
|
this.clicks = new Clicks(this.core);
|
|
131
|
+
this.knownCustomers = new KnownCustomers(this.core);
|
|
116
132
|
const explicitParam = options.clickIdParam;
|
|
117
133
|
this.clickIds = new ClickIds(() => explicitParam ?? configCache.peek()?.click_id_param ?? 'cgid');
|
|
118
134
|
this.api = new ApiClient(requester);
|
|
@@ -185,6 +201,8 @@ export class Clikgate {
|
|
|
185
201
|
* customer. `label` is what your team sees instead of the click ID (1–80 characters, `''` clears it; Growth and
|
|
186
202
|
* up). Always verified (your server), so it also satisfies a referral program's `require_identity_token`.
|
|
187
203
|
* In private mode `customerId` is refused locally (the guard) and `label` needs "Allow labels in private mode".
|
|
204
|
+
* `customerSince` is when they became your customer, so existing customers are never counted as
|
|
205
|
+
* referrals or new customers; it is refused in private mode too.
|
|
188
206
|
*
|
|
189
207
|
* Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app reads
|
|
190
208
|
* `getInstallationId()` and sends it in its sign-in request; your server calls this with
|
|
@@ -214,6 +232,13 @@ export class Clikgate {
|
|
|
214
232
|
body.customer_id = p.customerId;
|
|
215
233
|
if (p.label != null)
|
|
216
234
|
body.label = p.label;
|
|
235
|
+
if (p.customerSince != null) {
|
|
236
|
+
if (p.customerId == null)
|
|
237
|
+
throw localError('invalid_request', 'customerSince needs customerId.', 'customer_since');
|
|
238
|
+
body.customer_since = sinceWire(p.customerSince);
|
|
239
|
+
}
|
|
240
|
+
if (p.customerSinceReplace === true)
|
|
241
|
+
body.customer_since_replace = true;
|
|
217
242
|
const state = await this.core.guardState();
|
|
218
243
|
if (state.guard)
|
|
219
244
|
guardPayload('identify', body);
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Your customer IDs, in one canonical form: the same form the API stores and checks, so an ID
|
|
3
|
+
* sent from your server, an import and an identity token always match.
|
|
4
|
+
*
|
|
5
|
+
* - canonical form: Unicode NFC, trimmed of Unicode whitespace (and U+FEFF) at both ends, case kept;
|
|
6
|
+
* - warnings (first match wins): `empty`, `too_long` (more than 128 characters), `looks_like_email`,
|
|
7
|
+
* `looks_like_national_id` (exactly 11 digits, unless `allow11DigitIds`), `looks_like_phone`.
|
|
8
|
+
*
|
|
9
|
+
* Use your own stable user ID (for example `u_10482`), never an email, phone number, BVN or NIN.
|
|
10
|
+
*/
|
|
11
|
+
/** The longest customer ID kept as a known customer, in Unicode code points. */
|
|
12
|
+
export declare const CUSTOMER_ID_MAX_LENGTH = 128;
|
|
13
|
+
/** Why a customer ID can't be used as a known customer (the API's refusal reasons for the same checks). */
|
|
14
|
+
export type CustomerIdWarning = 'empty' | 'too_long' | 'looks_like_email' | 'looks_like_national_id' | 'looks_like_phone';
|
|
15
|
+
/** The canonical form of a customer ID: NFC, trimmed, case kept. */
|
|
16
|
+
export declare function canonicalCustomerId(customerId: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* Why Clikgate wouldn't keep this ID as a known customer, or `null` when it's fine.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* customerIdWarning('ada@example.com'); // 'looks_like_email'
|
|
22
|
+
* customerIdWarning('u_10482'); // null
|
|
23
|
+
*/
|
|
24
|
+
export declare function customerIdWarning(customerId: string, options?: {
|
|
25
|
+
allow11DigitIds?: boolean;
|
|
26
|
+
}): CustomerIdWarning | null;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Your customer IDs, in one canonical form: the same form the API stores and checks, so an ID
|
|
3
|
+
* sent from your server, an import and an identity token always match.
|
|
4
|
+
*
|
|
5
|
+
* - canonical form: Unicode NFC, trimmed of Unicode whitespace (and U+FEFF) at both ends, case kept;
|
|
6
|
+
* - warnings (first match wins): `empty`, `too_long` (more than 128 characters), `looks_like_email`,
|
|
7
|
+
* `looks_like_national_id` (exactly 11 digits, unless `allow11DigitIds`), `looks_like_phone`.
|
|
8
|
+
*
|
|
9
|
+
* Use your own stable user ID (for example `u_10482`), never an email, phone number, BVN or NIN.
|
|
10
|
+
*/
|
|
11
|
+
/** Unicode White_Space characters plus U+FEFF (the byte-order mark). */
|
|
12
|
+
const TRIM = '\t\n\u000b\u000c\r \u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
|
|
13
|
+
/** The longest customer ID kept as a known customer, in Unicode code points. */
|
|
14
|
+
export const CUSTOMER_ID_MAX_LENGTH = 128;
|
|
15
|
+
/** The canonical form of a customer ID: NFC, trimmed, case kept. */
|
|
16
|
+
export function canonicalCustomerId(customerId) {
|
|
17
|
+
const s = customerId.normalize('NFC');
|
|
18
|
+
let start = 0;
|
|
19
|
+
let end = s.length;
|
|
20
|
+
while (start < end && TRIM.includes(s[start]))
|
|
21
|
+
start++;
|
|
22
|
+
while (end > start && TRIM.includes(s[end - 1]))
|
|
23
|
+
end--;
|
|
24
|
+
return s.slice(start, end);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Why Clikgate wouldn't keep this ID as a known customer, or `null` when it's fine.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* customerIdWarning('ada@example.com'); // 'looks_like_email'
|
|
31
|
+
* customerIdWarning('u_10482'); // null
|
|
32
|
+
*/
|
|
33
|
+
export function customerIdWarning(customerId, options = {}) {
|
|
34
|
+
const cid = canonicalCustomerId(customerId);
|
|
35
|
+
if (cid === '')
|
|
36
|
+
return 'empty';
|
|
37
|
+
if ([...cid].length > CUSTOMER_ID_MAX_LENGTH)
|
|
38
|
+
return 'too_long';
|
|
39
|
+
const at = cid.indexOf('@');
|
|
40
|
+
if (at >= 0 && cid.slice(at + 1).includes('.'))
|
|
41
|
+
return 'looks_like_email';
|
|
42
|
+
if (/^[0-9]{11}$/.test(cid))
|
|
43
|
+
return options.allow11DigitIds ? null : 'looks_like_national_id';
|
|
44
|
+
if (/^\+?[0-9]{10,15}$/.test(cid.replace(/[ -]/g, '')))
|
|
45
|
+
return 'looks_like_phone';
|
|
46
|
+
return null;
|
|
47
|
+
}
|
package/dist/esm/enums.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Generated by server/codegen/generate.mjs from openapi.json (GoalKind, GoalStatus, Provider). Do not edit by hand.
|
|
2
|
-
// Source sha256
|
|
2
|
+
// Source sha256 86cb28d5c8c70cb6793d1c9145f99790d749cc09b447fa0f702d4c9cbbeeabd8.
|
|
3
3
|
/** A goal's kind, set in the goal's settings (never in a goal call): `standard` or `payment`. */
|
|
4
4
|
export const GoalKind = {
|
|
5
5
|
Standard: 'standard',
|
package/dist/esm/errors.d.ts
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* }
|
|
13
13
|
*/
|
|
14
14
|
/** Error codes with documented meaning (SPEC section 5). Other codes can appear; `code` is a plain string. */
|
|
15
|
-
export type KnownErrorCode = 'invalid_goal_key' | 'invalid_reference' | 'invalid_value' | 'click_id_and_code' | 'batch_too_large' | 'batch_empty' | 'invalid_argument' | 'invalid_click_id' | 'queue_full' | 'client_closed' | 'missing_api_key' | 'invalid_api_key' | 'invalid_option' | 'network_error' | 'timeout' | 'unexpected_status' | 'rate_limit_exceeded' | 'private_mode_field_rejected' | 'link_locked' | 'idempotency_key_reused' | 'idempotency_request_in_progress' | 'goal_archived' | 'goal_not_found' | 'value_required' | 'value_not_allowed' | 'domain_mode_mismatch' | 'https_required' | 'destination_not_allowlisted' | 'test_destination_not_allowed' | 'test_link_limit_reached' | 'plan_limit_reached' | 'plan_upgrade_required' | 'plan_feature_unavailable' | 'feature_disabled' | 'invalid_provider' | 'unknown_provider' | 'code_not_supported' | 'payment_goal_needs_confirmation' | 'unknown_goal' | 'cli_scope' | 'missing_signature' | 'malformed_signature' | 'timestamp_outside_tolerance' | 'no_matching_signature' | 'invalid_payload' | 'server_only' | 'invalid_customer_id' | 'missing_identity_secret' | 'invalid_identity_secrets';
|
|
15
|
+
export type KnownErrorCode = 'invalid_goal_key' | 'invalid_reference' | 'invalid_value' | 'click_id_and_code' | 'batch_too_large' | 'batch_empty' | 'invalid_argument' | 'invalid_click_id' | 'queue_full' | 'client_closed' | 'missing_api_key' | 'invalid_api_key' | 'invalid_option' | 'network_error' | 'timeout' | 'unexpected_status' | 'rate_limit_exceeded' | 'private_mode_field_rejected' | 'private_mode_conflict' | 'link_locked' | 'idempotency_key_reused' | 'idempotency_request_in_progress' | 'goal_archived' | 'goal_not_found' | 'value_required' | 'value_not_allowed' | 'domain_mode_mismatch' | 'https_required' | 'destination_not_allowlisted' | 'test_destination_not_allowed' | 'test_link_limit_reached' | 'plan_limit_reached' | 'plan_upgrade_required' | 'plan_feature_unavailable' | 'feature_disabled' | 'invalid_provider' | 'unknown_provider' | 'code_not_supported' | 'payment_goal_needs_confirmation' | 'unknown_goal' | 'cli_scope' | 'missing_signature' | 'malformed_signature' | 'timestamp_outside_tolerance' | 'no_matching_signature' | 'invalid_payload' | 'server_only' | 'invalid_customer_id' | 'missing_identity_secret' | 'invalid_identity_secrets';
|
|
16
16
|
/** Fields every Clikgate error carries. */
|
|
17
17
|
export interface ClikgateErrorInit {
|
|
18
18
|
message: string;
|