@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.
@@ -1,10 +1,15 @@
1
1
  import { createHmac } from 'node:crypto';
2
+ import { canonicalCustomerId } from './customer-id.js';
2
3
  import { ClikgateServerOnlyError, ConfigurationError, localError } from './errors.js';
3
4
  /** The single secret's environment variable. */
4
5
  export const IDENTITY_SECRET_ENV = 'CLIKGATE_IDENTITY_SECRET';
5
6
  /** The per-app map's environment variable: a JSON object `{"app_…": "cgis_…"}`. */
6
7
  export const IDENTITY_SECRETS_ENV = 'CLIKGATE_IDENTITY_SECRETS';
7
8
  const MAX_CUSTOMER_ID = 255;
9
+ /** 1990-01-01: earlier account dates are refused. */
10
+ const MIN_CUSTOMER_SINCE = 631_152_000;
11
+ /** The clock allowance for an account date after `issuedAt`. */
12
+ const CLOCK_ALLOWANCE = 300;
8
13
  /** @internal True in a browser (window or document) or React Native. */
9
14
  export function isBrowserOrMobile(g = globalThis) {
10
15
  if (typeof g.window !== 'undefined' || typeof g.document !== 'undefined')
@@ -61,6 +66,22 @@ export function signIdentityToken(secret, customerId, issuedAt) {
61
66
  const sig = createHmac('sha256', Buffer.from(secret, 'utf8')).update(Buffer.from(`${customerId}.${issuedAt}`, 'utf8')).digest('base64url');
62
67
  return `${sig}.${issuedAt}`;
63
68
  }
69
+ /**
70
+ * @internal Version 2: the MAC input is
71
+ * `"v2\n" + utf8Length(cid) + ":" + cid + "\n" + issuedAt + "\n" + customerSince`, cid in canonical form.
72
+ */
73
+ export function signIdentityTokenV2(secret, customerId, issuedAt, customerSince) {
74
+ const cid = canonicalCustomerId(customerId);
75
+ const msg = `v2\n${Buffer.byteLength(cid, 'utf8')}:${cid}\n${issuedAt}\n${customerSince}`;
76
+ const sig = createHmac('sha256', Buffer.from(secret, 'utf8')).update(Buffer.from(msg, 'utf8')).digest('base64url');
77
+ return `${sig}.${issuedAt}.${customerSince}`;
78
+ }
79
+ function sinceSeconds(value) {
80
+ const s = value instanceof Date ? Math.floor(value.getTime() / 1000) : value;
81
+ if (typeof s !== 'number' || !Number.isSafeInteger(s))
82
+ throw localError('invalid_argument', 'customerSince must be a Date or whole Unix seconds.', 'customer_since');
83
+ return s;
84
+ }
64
85
  /** @internal createIdentityToken with an explicit secret source (the client's options). */
65
86
  export function createIdentityTokenWith(source, customerId, options = {}) {
66
87
  if (isBrowserOrMobile())
@@ -73,7 +94,16 @@ export function createIdentityTokenWith(source, customerId, options = {}) {
73
94
  const issuedAt = o.issuedAt ?? Math.floor(Date.now() / 1000);
74
95
  if (!Number.isSafeInteger(issuedAt) || issuedAt < 0)
75
96
  throw localError('invalid_argument', 'issuedAt must be whole Unix seconds.', 'issued_at');
76
- return signIdentityToken(resolveSecret(o, source), customerId, issuedAt);
97
+ if (o.customerSince == null)
98
+ return signIdentityToken(resolveSecret(o, source), customerId, issuedAt);
99
+ const since = sinceSeconds(o.customerSince);
100
+ if (since < MIN_CUSTOMER_SINCE || since > issuedAt + CLOCK_ALLOWANCE) {
101
+ throw localError('invalid_argument', 'customerSince must be between 1990 and the time the token is issued.', 'customer_since');
102
+ }
103
+ const cid = canonicalCustomerId(customerId);
104
+ if (cid === '')
105
+ throw 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');
106
+ return signIdentityTokenV2(resolveSecret(o, source), cid, issuedAt, since);
77
107
  }
78
108
  /**
79
109
  * Create an identity token for the signed-in user. Return it in your sign-in and "current user"
@@ -81,11 +111,14 @@ export function createIdentityTokenWith(source, customerId, options = {}) {
81
111
  * secret from `CLIKGATE_IDENTITY_SECRETS` (a JSON map). No network call; no API key needed.
82
112
  *
83
113
  * Throws {@link ClikgateServerOnlyError} in a browser or React Native, `ConfigurationError` when no secret is set,
84
- * and `InvalidRequestError` (`invalid_customer_id`) for an empty or over-long customer ID.
114
+ * `InvalidRequestError` (`invalid_customer_id`) for an empty or over-long customer ID, and `InvalidRequestError`
115
+ * (`invalid_argument`, param `customer_since`) for an account date before 1990 or after the token's issue time.
85
116
  *
86
117
  * @example
87
118
  * import { createIdentityToken } from '@clikgate/node';
88
119
  * res.json({ user, clikgateIdentityToken: createIdentityToken(user.id) });
120
+ * // With the account date (version 2), so existing customers are never counted as referrals or new customers:
121
+ * res.json({ user, clikgateIdentityToken: createIdentityToken(user.id, { customerSince: user.createdAt }) });
89
122
  */
90
123
  export function createIdentityToken(customerId, options = {}) {
91
124
  return createIdentityTokenWith({}, customerId, options);
@@ -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/esm/index.js CHANGED
@@ -12,6 +12,8 @@
12
12
  export { Clikgate } from './client.js';
13
13
  export { ClickIds, clickIds, isValid as isValidClickId, CLICK_ID_PATTERN, CLICK_ID_HEADER, KEPT_COOKIE, KEPT_BY, BROWSER_ENGINES, PLATFORMS, } from './click-ids.js';
14
14
  export { webhooks } from './webhooks.js';
15
+ export { canonicalCustomerId, customerIdWarning, CUSTOMER_ID_MAX_LENGTH } from './customer-id.js';
16
+ export { KNOWN_CUSTOMERS_BATCH } from './known-customers.js';
15
17
  export { createIdentityToken, IDENTITY_SECRET_ENV, IDENTITY_SECRETS_ENV } from './identity.js';
16
18
  export { formatValue } from './money.js';
17
19
  export { hashForAds } from './ads-hashing.js';
@@ -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,90 @@
1
+ import { ConflictError, localError } from './errors.js';
2
+ /** The API's batch size; `import()` splits larger lists. */
3
+ export const KNOWN_CUSTOMERS_BATCH = 10_000;
4
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
5
+ /** @internal The UTC day `YYYY-MM-DD` of a customerSince value. */
6
+ export function sinceDay(value) {
7
+ if (typeof value === 'string') {
8
+ if (!DAY.test(value))
9
+ throw localError('invalid_argument', "customerSince must be 'YYYY-MM-DD', a Date or Unix seconds.", 'customer_since');
10
+ return value;
11
+ }
12
+ const ms = typeof value === 'number' ? value * 1000 : value instanceof Date ? value.getTime() : Number.NaN;
13
+ if (!Number.isFinite(ms) || (typeof value === 'number' && !Number.isSafeInteger(value))) {
14
+ throw localError('invalid_argument', "customerSince must be 'YYYY-MM-DD', a Date or Unix seconds.", 'customer_since');
15
+ }
16
+ return new Date(ms).toISOString().slice(0, 10);
17
+ }
18
+ function privateModeConflict() {
19
+ return new ConflictError({
20
+ message: "Private mode is on: known customers can't be imported or removed.",
21
+ code: 'private_mode_conflict',
22
+ httpStatus: null,
23
+ });
24
+ }
25
+ /** `clikgate.knownCustomers`: import and remove existing customers (scope `people:write`). */
26
+ export class KnownCustomers {
27
+ core;
28
+ /** @internal */
29
+ constructor(core) {
30
+ this.core = core;
31
+ }
32
+ /**
33
+ * Import existing customers (`POST /v1/known-customers/import`), in batches of 10,000. Idempotent per customer ID.
34
+ * Use your own customer IDs, never emails or phone numbers. The result sums every batch; refused rows are counted
35
+ * by reason, never returned.
36
+ *
37
+ * @example
38
+ * const result = await clikgate.knownCustomers.import([{ customerId: 'u_10482', customerSince: '2024-03-02' }]);
39
+ * console.log(result.accepted, result.refused_by_reason);
40
+ */
41
+ async import(customers, requestOptions = {}) {
42
+ if (!Array.isArray(customers))
43
+ throw localError('invalid_argument', 'customers must be an array.', 'customers');
44
+ const rows = customers.map((c, i) => {
45
+ if (!c || typeof c.customerId !== 'string')
46
+ throw localError('invalid_argument', `customers[${i}].customerId must be a string.`, 'customer_id');
47
+ const row = { customer_id: c.customerId };
48
+ if (c.customerSince != null)
49
+ row.customer_since = sinceDay(c.customerSince);
50
+ return row;
51
+ });
52
+ const total = { accepted: 0, refused: 0, refused_by_reason: {} };
53
+ if (rows.length === 0)
54
+ return total;
55
+ if ((await this.core.guardState()).guard)
56
+ throw privateModeConflict();
57
+ const several = rows.length > KNOWN_CUSTOMERS_BATCH;
58
+ for (let i = 0; i < rows.length; i += KNOWN_CUSTOMERS_BATCH) {
59
+ // One idempotency key per batch: a key you pass gets the batch number appended
60
+ const key = requestOptions.idempotencyKey;
61
+ const options = several && key ? { ...requestOptions, idempotencyKey: `${key}-${i / KNOWN_CUSTOMERS_BATCH}` } : requestOptions;
62
+ const { data } = await this.core.requester.request({
63
+ method: 'POST',
64
+ path: '/v1/known-customers/import',
65
+ body: { customers: rows.slice(i, i + KNOWN_CUSTOMERS_BATCH) },
66
+ ...options,
67
+ });
68
+ total.accepted += data.accepted ?? 0;
69
+ total.refused += data.refused ?? 0;
70
+ for (const [reason, n] of Object.entries(data.refused_by_reason ?? {})) {
71
+ total.refused_by_reason[reason] = (total.refused_by_reason[reason] ?? 0) + (n ?? 0);
72
+ }
73
+ }
74
+ return total;
75
+ }
76
+ /**
77
+ * Remove one imported customer (`POST /v1/known-customers/remove`; the ID travels in the body, never in a URL).
78
+ *
79
+ * @example
80
+ * const { removed } = await clikgate.knownCustomers.remove('u_10482');
81
+ */
82
+ async remove(customerId, requestOptions = {}) {
83
+ if (typeof customerId !== 'string' || customerId === '')
84
+ throw localError('invalid_customer_id', 'customerId must be a non-empty string.', 'customer_id');
85
+ if ((await this.core.guardState()).guard)
86
+ throw privateModeConflict();
87
+ const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/known-customers/remove', body: { customer_id: customerId }, ...requestOptions });
88
+ return data;
89
+ }
90
+ }
@@ -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.0";
2
+ export declare const VERSION = "2.0.1";
@@ -1,2 +1,2 @@
1
1
  /** The SDK version (kept equal to package.json by `npm run check:version`). */
2
- export const VERSION = '2.0.0';
2
+ export const VERSION = '2.0.1';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clikgate/node",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "The official Clikgate server SDK for Node.js and TypeScript: send goals in three lines, keep the click ID, verify webhooks, with private mode built in.",
5
5
  "keywords": [
6
6
  "clikgate",