@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.
Files changed (119) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/LICENSE +21 -0
  3. package/README.md +311 -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 +191 -0
  10. package/dist/cjs/client.js +291 -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/customer-id.d.ts +26 -0
  16. package/dist/cjs/customer-id.js +52 -0
  17. package/dist/cjs/enums.d.ts +48 -0
  18. package/dist/cjs/enums.js +47 -0
  19. package/dist/cjs/errors.d.ts +117 -0
  20. package/dist/cjs/errors.js +257 -0
  21. package/dist/cjs/express.d.ts +49 -0
  22. package/dist/cjs/express.js +44 -0
  23. package/dist/cjs/fastify.d.ts +47 -0
  24. package/dist/cjs/fastify.js +35 -0
  25. package/dist/cjs/generated/index.d.ts +17793 -0
  26. package/dist/cjs/generated/index.js +8896 -0
  27. package/dist/cjs/goals.d.ts +116 -0
  28. package/dist/cjs/goals.js +381 -0
  29. package/dist/cjs/guard.d.ts +17 -0
  30. package/dist/cjs/guard.js +40 -0
  31. package/dist/cjs/http.d.ts +16 -0
  32. package/dist/cjs/http.js +148 -0
  33. package/dist/cjs/identity.d.ts +42 -0
  34. package/dist/cjs/identity.js +133 -0
  35. package/dist/cjs/index.d.ts +34 -0
  36. package/dist/cjs/index.js +70 -0
  37. package/dist/cjs/known-customers.d.ts +45 -0
  38. package/dist/cjs/known-customers.js +95 -0
  39. package/dist/cjs/logger.d.ts +9 -0
  40. package/dist/cjs/logger.js +8 -0
  41. package/dist/cjs/money.d.ts +16 -0
  42. package/dist/cjs/money.js +51 -0
  43. package/dist/cjs/next.d.ts +81 -0
  44. package/dist/cjs/next.js +103 -0
  45. package/dist/cjs/package.json +1 -0
  46. package/dist/cjs/payments.d.ts +174 -0
  47. package/dist/cjs/payments.js +485 -0
  48. package/dist/cjs/resources.d.ts +109 -0
  49. package/dist/cjs/resources.js +189 -0
  50. package/dist/cjs/shutdown.d.ts +2 -0
  51. package/dist/cjs/shutdown.js +51 -0
  52. package/dist/cjs/transport.d.ts +14 -0
  53. package/dist/cjs/transport.js +204 -0
  54. package/dist/cjs/types.d.ts +218 -0
  55. package/dist/cjs/types.js +2 -0
  56. package/dist/cjs/user-agent.d.ts +1 -0
  57. package/dist/cjs/user-agent.js +53 -0
  58. package/dist/cjs/version.d.ts +2 -0
  59. package/dist/cjs/version.js +5 -0
  60. package/dist/cjs/webhooks.d.ts +36 -0
  61. package/dist/cjs/webhooks.js +108 -0
  62. package/dist/esm/ads-hashing.d.ts +37 -0
  63. package/dist/esm/ads-hashing.js +62 -0
  64. package/dist/esm/click-ids.d.ts +184 -0
  65. package/dist/esm/click-ids.js +526 -0
  66. package/dist/esm/client.d.ts +191 -0
  67. package/dist/esm/client.js +287 -0
  68. package/dist/esm/config.d.ts +12 -0
  69. package/dist/esm/config.js +82 -0
  70. package/dist/esm/core.d.ts +15 -0
  71. package/dist/esm/core.js +96 -0
  72. package/dist/esm/customer-id.d.ts +26 -0
  73. package/dist/esm/customer-id.js +47 -0
  74. package/dist/esm/enums.d.ts +48 -0
  75. package/dist/esm/enums.js +44 -0
  76. package/dist/esm/errors.d.ts +117 -0
  77. package/dist/esm/errors.js +234 -0
  78. package/dist/esm/express.d.ts +49 -0
  79. package/dist/esm/express.js +40 -0
  80. package/dist/esm/fastify.d.ts +47 -0
  81. package/dist/esm/fastify.js +32 -0
  82. package/dist/esm/generated/index.d.ts +17793 -0
  83. package/dist/esm/generated/index.js +8833 -0
  84. package/dist/esm/goals.d.ts +116 -0
  85. package/dist/esm/goals.js +371 -0
  86. package/dist/esm/guard.d.ts +17 -0
  87. package/dist/esm/guard.js +36 -0
  88. package/dist/esm/http.d.ts +16 -0
  89. package/dist/esm/http.js +138 -0
  90. package/dist/esm/identity.d.ts +42 -0
  91. package/dist/esm/identity.js +125 -0
  92. package/dist/esm/index.d.ts +34 -0
  93. package/dist/esm/index.js +23 -0
  94. package/dist/esm/known-customers.d.ts +45 -0
  95. package/dist/esm/known-customers.js +90 -0
  96. package/dist/esm/logger.d.ts +9 -0
  97. package/dist/esm/logger.js +5 -0
  98. package/dist/esm/money.d.ts +16 -0
  99. package/dist/esm/money.js +48 -0
  100. package/dist/esm/next.d.ts +81 -0
  101. package/dist/esm/next.js +96 -0
  102. package/dist/esm/package.json +1 -0
  103. package/dist/esm/payments.d.ts +174 -0
  104. package/dist/esm/payments.js +476 -0
  105. package/dist/esm/resources.d.ts +109 -0
  106. package/dist/esm/resources.js +183 -0
  107. package/dist/esm/shutdown.d.ts +2 -0
  108. package/dist/esm/shutdown.js +47 -0
  109. package/dist/esm/transport.d.ts +14 -0
  110. package/dist/esm/transport.js +166 -0
  111. package/dist/esm/types.d.ts +218 -0
  112. package/dist/esm/types.js +1 -0
  113. package/dist/esm/user-agent.d.ts +1 -0
  114. package/dist/esm/user-agent.js +16 -0
  115. package/dist/esm/version.d.ts +2 -0
  116. package/dist/esm/version.js +2 -0
  117. package/dist/esm/webhooks.d.ts +36 -0
  118. package/dist/esm/webhooks.js +105 -0
  119. package/package.json +128 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,136 @@
1
+ # Changelog: @clikgate/node
2
+
3
+ All notable changes to this package. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package uses [semantic versioning](https://semver.org/). Deprecations are announced at least 6 months ahead, and Node versions are dropped only after their end of life.
4
+
5
+
6
+ ## [2.0.1] - unreleased
7
+
8
+ ### Existing users
9
+
10
+ - **Added:** `createIdentityToken(customerId, { customerSince })` (also `clikgate.createIdentityToken`): with an account date (`Date` or Unix seconds) the token is version 2, `signature.issuedAt.customerSince`, so Clikgate can tell a customer from before you added Clikgate from a new one (referrals, new customers). Account dates before 1990 or after the issue time are a local `invalid_argument` (param `customer_since`). Tested against the shared version 2 vectors.
11
+ - **Added:** `identifyUser({ customerId, customerSince, customerSinceReplace })`: the account date from your server (`'YYYY-MM-DD'`, an ISO 8601 date-time, a `Date` or Unix seconds). `PersonIdentified` gains `customer_since_ignored` and `customer_id_warning`.
12
+ - **Added:** `clikgate.knownCustomers.import(customers)` (batches of 10,000, counts summed; refused rows counted by reason, never returned) and `clikgate.knownCustomers.remove(customerId)`.
13
+ - **Added:** `canonicalCustomerId()` and `customerIdWarning()`: the canonical customer ID (NFC, trimmed) and why an ID looks like an email, phone number or national ID, against the shared vectors.
14
+ - Refused in private mode: the guard refuses `customer_since`, and known customers raise a conflict with code `private_mode_conflict` before any request. Customer IDs and dates are never logged. Guide: https://clikgate.com/docs/identify-users.
15
+
16
+ ## [2.0.0] - unreleased
17
+
18
+ ### Breaking: track() removed in favour of goal()
19
+
20
+ - **Removed:** `track()` and app events are gone from Clikgate in favour of one method, `goal()`, for anything that happens in an app, website or server. A name that isn't set up as a goal yet still arrives (status `received`) and shows in the dashboard under "Seen from your app and website", ready to be counted. In this SDK that removes the generated app events resource (details under "Identity tokens, one goal() method" below): send `goal()` instead.
21
+
22
+ ### Strict goal names
23
+ - With the organisation's "Allow unknown goal names" off, the API refuses a goal name that isn't set up with `422 unknown_goal`, and an archived goal with `422 goal_archived`. Both are `InvalidRequestError` (`ClikgateError.code` is the reason) and final: never retried, never re-queued; background `goal()` passes them to `onError` as dropped. The SDK never checks names itself and never remembers the refusal.
24
+ - A `422` answered with the refusal body `{"status": "refused", "reason": ...}` (no error envelope) now maps to that reason instead of `http_422`; the body is the error's raw object. `KnownErrorCode` gains `unknown_goal`.
25
+ - With debug logging on (a `logger` with a `debug` method), each refusal logs "Goal `{name}` isn't set up in Clikgate" with the goal name only.
26
+
27
+ ### Identity tokens, one goal() method
28
+
29
+ - **Added:** `createIdentityToken(customerId, { appId?, secret?, issuedAt? })` (top-level export, no API key needed) and `clikgate.createIdentityToken(customerId, { appId? })`: `base64url_nopad(HMAC_SHA256(secret, customerId + "." + issuedAt)) + "." + issuedAt`, the signer Clikgate verifies with, with no network call. The secret comes from `secret`, else (with `appId`) that app's entry in the `identitySecrets` option / `CLIKGATE_IDENTITY_SECRETS` (a JSON object), else the `identitySecret` option / `CLIKGATE_IDENTITY_SECRET`. Errors: `ConfigurationError` (`missing_identity_secret`, `invalid_identity_secrets`), `InvalidRequestError` (`invalid_customer_id`: 1-255 characters; never echoed), and the new `ClikgateServerOnlyError` (`server_only`) when `window`, `document` or React Native (`navigator.product === "ReactNative"`) is detected. Tested against the shared vectors in `server/conformance/vectors/identity-token-vectors.json`. Guide: https://clikgate.com/docs/identify-users.
30
+ - **Docs:** `identifyUser()` documents path B (no secret or token): your server calls `identifyUser({ appId, installationId, customerId, label? })` with the installation ID the app sends at sign-in and at every signed-in app open, and skips the call when there is none.
31
+ - **Added:** `GoalStatus.Received` `received`: `goal()` / `goals.send` with a name that isn't ticked as a goal yet (or an archived goal) answers `200` with `status: "received"` and `reason` `not_counted_yet` (or `goal_archived`). It is a result, like `waiting` and `refused`: never an error and never retried.
32
+ - **Removed (generated API):** the app events resource (`clikgate.api.appEvents`, `AppEventsApi` and its `AppEvent*` / `*EventRule*` types): List App Events (`GET /v1/app-events`), Report App Events (`POST /v1/apps/{app_id}/events`) and the Event rules operations (`/v1/apps/{app_id}/event-rules`). Clikgate has one method for anything that happens in an app, website or server, `goal()`; names not ticked as goals yet show in the dashboard's "Seen from your app and website". No released version ever had them (the generator drops them through `server/codegen/removed.mjs` until the backend's public document no longer lists them).
33
+
34
+ ### Hashed email and phone for ad network matching
35
+
36
+ - **Added:** `hashForAds({ email, phone })` → `HashedIdentifiers` (`hashedEmail`, `hashedPhoneE164`, `hashedPhoneDigits`; only the fields given), to spread into goal options. Pure and offline: the email is trimmed and lowercased (must contain `@`); the phone must start with `+` or `00` and be 7-15 digits starting with 1-9 (E.164). Bad input is a local `invalid_argument` (`param` `email` / `phone`, never echoed).
37
+ - **Added:** goal options `hashedEmail`, `hashedPhoneE164`, `hashedPhoneDigits` (wire `hashed_email`, `hashed_phone_e164`, `hashed_phone_digits`) on `goal()`, `goals.send` and batch events; `conversions.create` takes the same wire fields. A value that isn't 64 lowercase hex characters is a local `invalid_hashed_identifier`. The private-mode guard allows the three fields on goals and conversions (the API accepts them there only while a destination matches by hashed identifiers). In private mode, hash on your own server.
38
+
39
+ ### Keep the click ID longer
40
+
41
+ - **Added:** `clikgate.clickIds.keepRoute({ days = 30, secure = true, domain? })`, the `/cg/keep` route for the web script's `data-server-endpoint="/cg/keep"`: a Fetch handler (`export const POST = clikgate.clickIds.keepRoute()` in a Next.js App Router route) with `.express`, `.node` and `.handle` adapters, and `keepRoute()` from `@clikgate/node/next`. Same-origin `POST` only, a valid click ID matching the page URL's, `no-store`, empty bodies, never a redirect. `days` outside 1-400 is `invalid_argument`.
42
+ - **Added:** `clikgate.clickIds.context(req)` → `{ clickId, keptBy, browserEngine, platform }` for a goal's options (the User-Agent is parsed in the SDK, never sent).
43
+ - **Added:** goal options `keptBy`, `browserEngine` and `platform` (sent as `kept_by`, `browser_engine`, `platform`; unknown values are a local `invalid_argument`), allowed by the private-mode guard. Types `KeptBy`, `BrowserEngine`, `Platform`.
44
+ - **Changed:** `persist()`, the Express/Fastify add-ons and the Next.js proxy also write the `_cg_kept=s` marker cookie (same `Path`, `Max-Age`, `Domain`, `SameSite`, `Secure`), so the web script reports `kept_by: server_cookie`.
45
+
46
+ ### identifyUser, goal labels, App banners
47
+
48
+ - **Added:** `clikgate.identifyUser({ clickId | appId + installationId | customerId, label })` → `POST /v1/people/identify`: at least one reference (a click, an app installation or a customer ID; with a click or installation the customer ID links it). Always verified, so it also satisfies a referral program's `require_identity_token`. Local `invalid_request` without a reference or with half an installation. In private mode the guard refuses the customer ID; `label` passes (the API needs "Allow labels in private mode", else `422 labels_off_in_private_mode`).
49
+ - **Added:** goals take `label` (the person's label, 1-80 characters; Growth and up), allowed by the private-mode guard.
50
+ - **Removed (generated API):** the app server-identify operation (`POST /v1/apps/{app_id}/identify`); use `identifyUser`. The Journeys API is now the App banners API (`AppBannersApi`, `app_banner_id`, `AppBanner*` types, type `full_screen`, webhooks `app_banner.published` / `app_banner.paused`); IDs keep the `jrn_` prefix.
51
+ - **Regenerated** from the current public OpenAPI (523 operations), including the share events, QR, referral map, single sign-on, people, customer cost).
52
+
53
+ ### Breaking
54
+ - **`GoalEvent.status` is now the goal call's outcome**, a `GoalStatus`: `counted`, `waiting` (a Payment goal
55
+ waiting for its confirmation) or `refused`. The attribution state it used to hold (`attributed`, `unattributed`,
56
+ `rejected_bot`, …) moved to the new `event_status`. Check `status === GoalStatus.Counted` (or `counted`) instead of
57
+ `status === 'attributed'`.
58
+ - **Goal kinds replace the goal's `confirmation` setting** in the generated `api.goals.*` types: the goal object has
59
+ `kind` (`GoalKind`) and `suggest_payment` instead of `confirmation`; `createGoal` / `updateGoal` take `kind`, and
60
+ `updateGoal` also `confirm_kind_change` (`409 kind_change_needs_confirmation`). `ApiTypes.GoalStatus` is now the
61
+ goal call's outcome; a goal's lifecycle (`active` / `archived`) is `ApiTypes.GoalState`.
62
+ - Payment features (Payment goals, `payments.confirm` and the helpers) need a Starter plan or above: Free gets
63
+ `PermissionError` `plan_feature_unavailable` (it was `plan_upgrade_required` on the `sales_tracking` feature).
64
+ - `PaymentConfirmParams.provider`, `PaymentConfirmationBody.provider` and `PaymentConfirmation.provider` are typed
65
+ `Provider | string` (was `string`; existing strings still compile).
66
+
67
+ ### Added
68
+ - **Private mode allows `consent`** (the four-purpose consent object) on goals, batch items and conversions, as the API does; it was refused locally before. Payment confirmations also allow the API's structural `refund_id` and `source_plugin` (through `extra`).
69
+ - `conversions.create` returns `Conversion | GoalEvent`: on a Payment goal the API answers with the goal event (`object: 'goal_event'`). Send `provider` and the payment reference there; a server Payment goal has no default provider any more (`422 payment_goal_needs_confirmation` with `missing`).
70
+ - **`GoalKind`, `GoalStatus` and `Provider`**, exported as constants and types (`GoalKind.Payment`,
71
+ `GoalStatus.Counted`, `Provider.Paystack`). They are generated from the API's OpenAPI description, so a new gateway
72
+ shows up as `Provider.<Name>` when the SDK is regenerated.
73
+ - **`provider`** on `goal()`, `goals.send` and batch events: the payment provider of a Payment goal. A provider key
74
+ string works too, for a gateway added after your SDK release. A malformed key is refused locally
75
+ (`invalid_provider`). Private mode allows it.
76
+ - `GoalEvent` gains `goal_kind`, `value_ignored`, `event_status` and `payment` (the confirmation a Payment goal sent
77
+ by your server became), and a `GoalPayment` type.
78
+ - `KnownErrorCode` gains `plan_feature_unavailable`, `invalid_provider`, `unknown_provider`, `code_not_supported` and
79
+ `payment_goal_needs_confirmation`.
80
+ - The generated `api.*` layer is regenerated (473 operations kept): onboarding (`api.onboarding.*`), checklist
81
+ skip and unskip, a link's first click, payment report fields (`primary`, `late_report`, `flags`, `hint`).
82
+ - Forward compatibility: unknown response fields and enum values are kept and never an error (conformance suite
83
+ `compat`).
84
+
85
+ - **Payments confirmed by your server (SPEC section 22).** `payments.confirm({...})` posts
86
+ `POST /v1/payments/confirmations`. `payments.fromPaystack`, `fromFlutterwave`, `fromMonnify` and `fromStripe` read
87
+ only the reference, status, amount, currency, time and `cg_click_id` from the gateway's verified response, and
88
+ send them.
89
+ - `buildFrom*` (also exported as functions) return the body without sending it.
90
+ - Amounts are exact decimals.
91
+ - The private-mode guard has a new kind, `payment_confirmation`.
92
+ - New warning code: `unrecognised_payment_response`.
93
+ - New types: `PaymentConfirmParams`, `PaymentConfirmation`, `PaymentConfirmationBody`, `PaymentHelperOptions`
94
+ and `PaymentStatus`.
95
+ - Conformance suite `payments`.
96
+
97
+ ### Removed
98
+ - Internal planning references in doc comments and in the generated types' descriptions.
99
+
100
+ ### Changed
101
+ - **Fraud rules and the fraud test lab:** the generated `api.*` layer is regenerated (757 operations; 461 kept). New `api.adFraud.fetchFraudRules()` (`GET /v1/fraud/rules`, `FraudRulesDetailResponse`, plans with fraud insights). `FraudSampleResponse` (`createFraudSample`) no longer has `score` or `threshold`, `reasons` is `{rule, name}[]` (`FraudSampleReason`) and `FraudSamplePlanOutcome` has no `threshold`. These are removals from a response type.
102
+
103
+ ## [1.1.0] - unreleased
104
+
105
+ ### Added
106
+ - **Metadata filters:** `metadata` on the typed `api.links.listLinks`, `api.analytics.analyticsSummary`, `analyticsTimeseries`, `topLinks` and `openInAppAnalytics` methods and on `links.list` / `links.listPage`. A map such as `{ seller_id: 'sel_ada' }` is sent as `metadata[seller_id]=sel_ada` (SPEC section 21). The backend reads these from the raw query string, so the codegen adds the parameter (`codegen/filter.mjs`).
107
+ - **Webhook `subscription.updated`:** documented on the webhook event type; it carries the subscription with `add_ons`, `change` and `add_on_key`. `type` stays a plain string, so nothing else changes. Conformance `webhooks.valid.subscription_updated`.
108
+ - The generated `api.*` layer is regenerated from the final backend `openapi.json` (756 operations; 460 kept). `AnalyticsRowResponse.end_goal_value` is a map of decimal strings per currency next to `end_goal_value_minor`.
109
+ - `GoalEvent.value_minor` and `reversed_value_minor`: the amounts in minor units next to `value` and `reversed_value` (decimal strings), as the API returns them.
110
+
111
+ ### Changed
112
+ - `goals.send` and `goal()` in sync mode send a random UUID v4 `Idempotency-Key` per call, reused across that call's retries, instead of `sha256(goal + ":" + reference)`. The API dedupes goal events by goal and reference itself, so a resend still never counts twice. The `idempotencyKey` request option still overrides the key.
113
+
114
+ ## [1.0.0] - unreleased (first release)
115
+
116
+ ### Added
117
+ - `Clikgate` client:
118
+ - `goal()` (background queue with batching, never throws);
119
+ - `goals.send`, `goals.sendBatch` and `goals.reverse`;
120
+ - `flush()`, `close()`, and flush on `beforeExit`, `SIGTERM` and `SIGINT`.
121
+ - `conversions.create` and `conversions.reverse` (older API).
122
+ - `links.create`, `get`, `update` (`202` change requests become `{ applied: false, change_request }`; `409 link_locked` becomes `LinkLockedError`), `list` (auto-paginating) and `listPage`, `qr`, and `domain_badge` and `warnings` on links.
123
+ - `clicks.get`.
124
+ - Click IDs: `clickIds.fromRequest`, `isValid`, `cookieHeader`, `persist` and `fromPaymentMetadata` (Paystack, Flutterwave, Shopify, WooCommerce).
125
+ - Webhooks: `webhooks.verify` and `webhooks.verifyAny`, with a 300 s tolerance and constant-time comparison.
126
+ - The private-mode guard: `privateMode: 'auto' | true | false`; `auto` reads `GET /v1/server-sdk/config`, caches it for 10 minutes and fails closed.
127
+ - Typed errors (SPEC section 5), with `allowed` and `docUrl` (test links), and `requiredPlan` and `limit` (plan and test-link limits).
128
+ - Retries with full-jitter backoff and `Retry-After`. Idempotency keys: `sha256(goal + ":" + reference)` for goals, and a random UUID reused across retries for other calls.
129
+ - Money is always sent as a decimal string, with `formatValue`; numbers that may be inexact log a warning.
130
+ - `clikgate.api.*`: every API-key operation, generated from openapi.json.
131
+ - Add-ons:
132
+ - `@clikgate/node/express` (Express 5 and Connect);
133
+ - `@clikgate/node/fastify` (Fastify 5);
134
+ - `@clikgate/node/next` (Next.js 16 `proxy.ts`, plus legacy `middleware.ts`).
135
+ - Builds: ESM, CJS and `.d.ts`; zero runtime dependencies; Node 18+.
136
+ - Types: `LinkChangeRequest` carries `requested_by_type`, `decision_note` and `livemode` (as the backend's `LinkChangeRequestInfoResponse`), and `KnownErrorCode` includes `https_required` and `destination_not_allowlisted` (link-safety `422`s).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Clikgate
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,312 @@
1
- # Temporary Holding Version
1
+ # @clikgate/node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official Clikgate server SDK for Node.js and TypeScript. It:
4
+
5
+ - sends goals in three lines;
6
+ - keeps the click ID;
7
+ - verifies webhooks;
8
+ - has private mode built in.
9
+
10
+ It has zero runtime dependencies and supports Node 18+, with ESM, CommonJS and TypeScript types.
11
+
12
+ ```bash
13
+ npm install @clikgate/node
14
+ ```
15
+
16
+ ```ts
17
+ import { Clikgate } from '@clikgate/node';
18
+ const clikgate = new Clikgate(); // reads CLIKGATE_API_KEY (cg_live_… or cg_test_…)
19
+ clikgate.goal('account_opened', { clickId, reference: 'APP-55231', value: '2000000' });
20
+ ```
21
+
22
+ Create one client and reuse it. `goal()` is the one method for every goal, Standard or Payment.
23
+
24
+ - **`goal()`** never throws. It queues the event and sends it in the background, in batches, with safe retries.
25
+ - **`goals.send()`** waits for the API and returns the result: `status` is a `GoalStatus` (`counted`, `waiting`,
26
+ `received` or `refused`), with `reason`, `goal_kind` (`GoalKind`), `attributed_to`, … `received` means the name isn't ticked as a goal in the dashboard yet (or the goal is archived): it is stored, not counted, and shows in "Seen from your app and website". Every status is a result, never an error, and none is retried. Goals work on every plan, up to the plan's allowance.
27
+
28
+ ```ts
29
+ import { GoalStatus } from '@clikgate/node';
30
+ const event = await clikgate.goals.send('account_opened', { clickId, reference: 'APP-55231' });
31
+ if (event.status === GoalStatus.Refused) console.log('not counted:', event.reason); // e.g. rejected_bot
32
+ ```
33
+
34
+
35
+ ### Match by hashed email or phone (ad networks)
36
+
37
+ When the business has turned on matching by hashed email or phone for an ad network destination, a goal can carry your own SHA-256 hashes: `hashedEmail`, `hashedPhoneE164` and `hashedPhoneDigits` (sent as `hashed_email`, `hashed_phone_e164`, `hashed_phone_digits`). `hashForAds` makes them on your server (offline, no client needed) and returns only the fields for the values you give:
38
+
39
+ ```ts
40
+ import { hashForAds } from '@clikgate/node';
41
+
42
+ clikgate.goal('account_opened', {
43
+ reference: 'APP-55231',
44
+ clickId,
45
+ ...hashForAds({ email: 'ada.obi@example.com', phone: '+234 803 123 4567' }),
46
+ });
47
+ ```
48
+
49
+ The email is trimmed and lowercased. The phone must include its country code (`+234…` or `00234…`); a national number such as `0803 123 4567` is an `InvalidRequestError` (`invalid_argument`), and the SDK never guesses the country. A hashed value that isn't 64 lowercase hex characters is refused before sending (`invalid_hashed_identifier`). `conversions.create` takes the same wire fields. Hashed values are never logged.
50
+
51
+ In private mode, hash on your own server: Clikgate never hashes for you there.
52
+
53
+ ## Identify your users
54
+
55
+ Two ways to tell Clikgate which of your users is using the app. Full guide: https://clikgate.com/docs/identify-users. The customer ID is your own user ID from your database, never an email, phone number or ID number. Anonymous users don't need either path.
56
+
57
+ **Path A (default): identity token.** Create the identity secret in Apps › your app › Identity secret and store it as `CLIKGATE_IDENTITY_SECRET` on your server only. `createIdentityToken(customerId, { appId? })` (also `clikgate.createIdentityToken()`, with the `identitySecret` / `identitySecrets` options) signs a token with no network call; return it in the responses the app already calls, and the app passes it to the mobile SDK's `identifyUser()`. Tokens last 30 days by default and are never force-refreshed. Throws `ClikgateServerOnlyError` in a browser or React Native.
58
+
59
+ ```ts
60
+ import { createIdentityToken } from '@clikgate/node';
61
+ // sign-in and "current user" responses: one extra field
62
+ res.json({ user, clikgateIdentityToken: createIdentityToken(user.id) }); // reads CLIKGATE_IDENTITY_SECRET
63
+ createIdentityToken(user.id, { appId: 'app_…' }); // several apps: CLIKGATE_IDENTITY_SECRETS
64
+ ```
65
+
66
+ **Path B: installation ID, no secret or token.** The app reads `getInstallationId()` and includes it in its sign-in request; your server calls `identifyUser` with the app ID, installation ID and customer ID, after sign-in and at every signed-in app open. Clikgate accepts installations active in the last 7 days.
67
+
68
+ ```ts
69
+ // The app sends Clikgate.getInstallationId() with its sign-in request (null when tracking is off: skip)
70
+ if (body.installationId) await clikgate.identifyUser({ appId: 'app_…', installationId: body.installationId, customerId: user.id });
71
+ ```
72
+
73
+ ## Customers from before Clikgate
74
+
75
+ Tell Clikgate who was already your customer before you added it, so they are never counted as a referral or a new customer. Send the account's creation date with the identity token (version 2) or from your server, and import the rest of your existing customers once. Use your own customer IDs, never emails or phone numbers: Clikgate stores a keyed fingerprint of each imported ID, not the ID itself. Not available in private mode. Guide: https://clikgate.com/docs/identify-users.
76
+
77
+ ```ts
78
+ res.json({ user, clikgateIdentityToken: createIdentityToken(user.id, { customerSince: user.createdAt }) }); // version 2
79
+ await clikgate.identifyUser({ appId: 'app_…', installationId, customerId: user.id, customerSince: user.createdAt });
80
+ const result = await clikgate.knownCustomers.import([{ customerId: 'u_10482', customerSince: '2024-03-02' }]); // batches of 10,000
81
+ console.log(result.accepted, result.refused_by_reason); // refused rows are counted by reason, never returned
82
+ ```
83
+
84
+ ## People: identify a user and label them
85
+
86
+ Link a click, an app installation or your customer ID to a person, and give them a label your team sees instead of the click ID (1-80 characters; Growth and up). From your server this is always verified. Goals take the same `label`, and `isFirst` from your server is what counts a new customer. Don't put information in labels that your customers wouldn't expect you to keep.
87
+
88
+ ```ts
89
+ await clikgate.identifyUser({ clickId: order.clickId, customerId: 'user_42', label: 'Ada (VIP)' });
90
+ clikgate.goal('account_opened', { clickId, reference: 'APP-55231', isFirst: true, label: 'Ada (VIP)' });
91
+ ```
92
+
93
+ ## Keep the click ID
94
+
95
+ The pattern is: capture it on landing, save it with your own record, then send the goal later from any job.
96
+
97
+ ```ts
98
+ import express from 'express';
99
+ import { clikgateMiddleware } from '@clikgate/node/express';
100
+
101
+ app.use(clikgateMiddleware(clikgate)); // keeps ?cgid=… in the _cg_cgid cookie (the web script's cookie)
102
+ app.post('/signup', (req, res) => {
103
+ db.applications.insert({ id: 'APP-55231', clickId: req.clikgate.clickId });
104
+ });
105
+
106
+ // days later, when the account is approved:
107
+ clikgate.goal('account_opened', { clickId: application.clickId, reference: application.id, value: '2000000', currency: 'NGN' });
108
+ ```
109
+
110
+ - **Fastify:** `await app.register(clikgatePlugin, { client: clikgate })` from `@clikgate/node/fastify`, then read `request.clikgate.clickId`.
111
+ - **Next.js 16+:** in `proxy.ts`, `export { clikgateProxy as proxy } from '@clikgate/node/next'`. Then read it with `getClickId(await cookies())`.
112
+ - **Without a framework:** `clikgate.clickIds.fromRequest(req)` and `clikgate.clickIds.persist(res, clickId)`.
113
+ - **From payment payloads** (Paystack, Flutterwave, Shopify, WooCommerce): `clikgate.clickIds.fromPaymentMetadata(payload)`.
114
+
115
+ ## Keep the click ID longer (Safari)
116
+
117
+ Safari, and every browser on iPhone, keeps a click ID saved by a script for up to 7 days (sometimes less). When your server saves it, it lasts as long as you choose, up to the browser's limit.
118
+
119
+ Add a `/cg/keep` route to your server and tell the web script about it with `data-server-endpoint="/cg/keep"`. When a click ID arrives in the page URL, the script makes one `POST` to that route, and your server sets the `_cg_<param>` cookie (30 days by default, `days` up to 400) plus a small `_cg_kept=s` marker, so goals report `keptBy: 'server_cookie'`.
120
+
121
+ - **Same server:** the route must be served by the same host as the website (the page's own origin, e.g. `https://shop.example.com/cg/keep`), not by another domain or subdomain. A cookie set by another host doesn't get the longer lifetime.
122
+ - **Readable by the page on purpose:** both cookies are not `HttpOnly`, because the web script reads them. They are `SameSite=Lax` and `Secure` (default `true` here; pass `secure: false` only for local `http://` development).
123
+ - **Locked down:** only a same-origin `POST` (`Sec-Fetch-Site: same-origin`, or an `Origin` equal to the request's host) with a valid click ID that matches the page URL's is accepted. Every answer is `Cache-Control: no-store, private` with an empty body; it never redirects, and the input is never echoed or logged. The cookie name comes from your configuration (`clickIdParam`, else `cgid`), never from the request.
124
+
125
+ ```html
126
+ <script src="https://sdk.clikgate.com/v1/static/clikgate.js" data-web-key="cgw_live_…" data-server-endpoint="/cg/keep" async></script>
127
+ ```
128
+
129
+ **Next.js (App Router):**
130
+
131
+ ```ts
132
+ // app/cg/keep/route.ts
133
+ import { clikgate } from '@/lib/clikgate';
134
+ export const POST = clikgate.clickIds.keepRoute(); // or keepRoute({ days: 90 })
135
+
136
+ // proxy.ts (Next.js 16+; middleware.ts before): also keeps ?cgid=… from the query on any page
137
+ export { clikgateProxy as proxy } from '@clikgate/node/next';
138
+ export const config = { matcher: ['/((?!_next/|api/webhooks/).*)'] };
139
+ ```
140
+
141
+ Without a client, `import { keepRoute } from '@clikgate/node/next'` and `export const POST = keepRoute()` uses the same parameter as the proxy (`clickIdParam`, else `CLIKGATE_CLICK_ID_PARAM`, else `cgid`).
142
+
143
+ **Express / Connect** (`app.all` so other methods get the route's own `405`; before or after `express.json()`, both work):
144
+
145
+ ```ts
146
+ app.all('/cg/keep', clikgate.clickIds.keepRoute({ days: 90 }).express);
147
+ ```
148
+
149
+ **Plain `node:http`:** `route.node(req, res)`. Any other framework: `route.handle({ method, headers, readBody })` returns `{ status, headers }`.
150
+
151
+ Then send what you know about how it was kept with the goal. `clickIds.context(req)` returns `{ clickId, keptBy, browserEngine, platform }`; the engine and platform are worked out from the `User-Agent` in the SDK (the User-Agent itself is never sent), and all three are allowed in private mode:
152
+
153
+ ```ts
154
+ clikgate.goal('account_opened', { reference: application.id, ...clikgate.clickIds.context(req) });
155
+ ```
156
+
157
+ `keptBy` is `server_cookie` (your server set the cookie), `script_cookie` (the web script did), `form` (the `Clikgate-Click-Id` header) or `null`; you can also pass `'payment_metadata'` or `'unknown'` yourself. `persist()` and the framework add-ons also write the `_cg_kept=s` marker.
158
+
159
+ ## Money
160
+
161
+ - `value` is in **normal units** (₦2,000,000 is `'2000000'`, never kobo) and is always sent as a decimal string.
162
+ - It accepts a `string`, a `number` or a `bigint`. Pass strings like `'1500.50'` for exact values. A number with decimals works, but logs an `inexact_number` warning.
163
+
164
+ ## Payment goals
165
+
166
+ A goal is **Standard** or **Payment** (`GoalKind.Standard` / `GoalKind.Payment`, set in the goal's settings in the
167
+ dashboard, never in the call). A Payment goal counts only when a trusted source confirms it, with the confirmed amount:
168
+
169
+ 1. Your website or app **reports** it with the same `goal()` call, with `provider` and `reference` (never an amount).
170
+ The result is `waiting` until the payment is confirmed.
171
+ 2. Your server **confirms** it, right after its own verification with the gateway, in one of two ways:
172
+ - send the Payment goal with the confirmed value: it is a trusted confirmation;
173
+ - or pass the gateway's verified response to a helper below.
174
+
175
+ ```ts
176
+ import { Provider } from '@clikgate/node';
177
+ // after your own verification with Paystack:
178
+ await clikgate.goals.send('order_paid', { reference: 'T123456', provider: Provider.Paystack, value: '7500', currency: 'NGN', clickId });
179
+ ```
180
+
181
+ - `provider` is a `Provider` (every gateway in `GET /v1/payment-gateways`, plus `shopify`, `woocommerce` and
182
+ `custom`). A provider key string works too, for a gateway added after your SDK release.
183
+ - `provider` and `reference` are required on a Payment goal (`422 payment_goal_needs_confirmation`, with `missing`,
184
+ otherwise): the SDK can't check this itself, because the kind lives only in the goal's settings.
185
+ - With a `clickId` the goal counts at once. Without one, it is `waiting` until the website's or app's report arrives.
186
+ - A Payment goal needs a Starter plan or above (`PermissionError` `plan_feature_unavailable` on Free).
187
+
188
+ The helpers read the gateway's verified response. Call them **right after your own server has verified the payment
189
+ with the gateway**. Never pass data from the browser or the app. A helper sends only the reference, status, amount,
190
+ currency, time and `cg_click_id`. It never sends customer details, and it never needs your gateway key.
191
+
192
+ ```ts
193
+ // Paystack: after your own GET /transaction/verify/{reference}
194
+ await clikgate.payments.fromPaystack(verifyResponse, { goal: 'order_paid' });
195
+ // Flutterwave: after your own GET /v3/transactions/{id}/verify
196
+ await clikgate.payments.fromFlutterwave(verifyResponse);
197
+ // Monnify: after your own GET /api/v2/transactions/{transactionReference}
198
+ await clikgate.payments.fromMonnify(statusResponse);
199
+ // Stripe: a PaymentIntent you retrieved, or the Checkout Session from a webhook you verified
200
+ await clikgate.payments.fromStripe(paymentIntent);
201
+
202
+ // Any other gateway, or a refund:
203
+ await clikgate.payments.confirm({ provider: Provider.Paystack, reference: 'T_ref_001', status: 'refunded', amount: '2500.00', currency: 'NGN' });
204
+ ```
205
+
206
+ - Amounts are exact decimals, never floats: Paystack's `750000` kobo becomes `"7500"`.
207
+ - The helpers return `null` (and send nothing) when the response has no reference or no known status.
208
+ `buildFromPaystack(...)` and the other builders return the body without sending it.
209
+ - Private mode allows every field these send.
210
+
211
+ ## Webhooks
212
+
213
+ ```ts
214
+ import { webhooks } from '@clikgate/node';
215
+ app.post('/webhooks/clikgate', express.raw({ type: 'application/json' }), (req, res) => {
216
+ const event = webhooks.verify(req.body, req.get('Clikgate-Signature'), process.env.CLIKGATE_WEBHOOK_SECRET!);
217
+ res.sendStatus(200); // deliveries are at-least-once: dedupe on event.id
218
+ });
219
+ ```
220
+
221
+ - Use `webhooks.verifyAny(body, header, [newSecret, oldSecret])` while you rotate your own secrets.
222
+ - Next.js route handlers: pass `await request.text()` as the body.
223
+
224
+ ## Serverless
225
+
226
+ In a serverless function, call `await clikgate.flush()` before returning. Alternatively use `new Clikgate({ sendMode: 'sync' })` with `await clikgate.goals.send(…)`.
227
+
228
+ ## Private mode
229
+
230
+ - With `privateMode: 'auto'` (the default), the SDK reads your organisation's setting from `GET /v1/server-sdk/config` and caches it for 10 minutes.
231
+ - When private mode is on, only `goal`, `clickId`, `code`, `reference`, `value`, `currency`, `provider`, `isFirst`, `occurredAt` and `consent` are sent. Anything else (`metadata`, emails, customer IDs, …) is refused **before sending** with `PrivateModeFieldRejectedError`, which names the field, never its value.
232
+ - References are redacted in logs.
233
+ - If the setting can't be loaded, the SDK assumes private mode is on.
234
+
235
+ ## Links
236
+
237
+ ```ts
238
+ const link = await clikgate.links.create({ destination_url: 'https://example.com/spring', og_title: 'Spring sale', og_image_url: 'https://example.com/og.png' });
239
+ link.warnings; // e.g. [{ code: 'no_preview', … }]
240
+ link.domain_badge; // 'premium' on ciz.to links
241
+
242
+ const result = await clikgate.links.update(link.id, { destination_url: 'https://example.com/summer' });
243
+ if (!result.applied) console.log('waiting for a second approver:', result.change_request.id);
244
+
245
+ for await (const l of clikgate.links.list({ status: 'active' })) console.log(l.short_url);
246
+
247
+ // Filter by your own link metadata (sent as metadata[seller_id]=sel_ada); analytics take it too.
248
+ for await (const l of clikgate.links.list({ metadata: { seller_id: 'sel_ada' } })) console.log(l.metadata);
249
+ const ada = await clikgate.api.analytics.analyticsSummary({ from: '2026-10-01T00:00:00Z', to: '2026-11-01T00:00:00Z', metadata: { seller_id: 'sel_ada' } });
250
+ ```
251
+
252
+ - With a `cg_test_` key, links use `dev.ciz.to`. Their destination may be one of Clikgate's test pages: `clikgate-test:inspect`, `clikgate-test:checkout`, `clikgate-test:app-open` or `clikgate-test:store`.
253
+ - A locked link throws `LinkLockedError`.
254
+
255
+ ## Errors
256
+
257
+ Every error extends `ClikgateError`, with `code`, `httpStatus`, `requestId` and `param`:
258
+
259
+ | Error | When |
260
+ |---|---|
261
+ | `AuthenticationError` | 401 |
262
+ | `PermissionError` | 403: `plan_limit_reached` and `plan_feature_unavailable` (`requiredPlan`), `test_link_limit_reached` (`limit`), `cli_scope`, … |
263
+ | `InvalidRequestError` | 4xx and local validation: `invalid_value`, `invalid_provider`, `unknown_provider`, `domain_mode_mismatch`, `test_destination_not_allowed` (`allowed`, `docUrl`), … |
264
+ | `PrivateModeFieldRejectedError` | private mode refused a field (`field`) |
265
+ | `NotFoundError` | 404 |
266
+ | `ConflictError` / `LinkLockedError` | 409 |
267
+ | `IdempotencyError` | 409 `idempotency_*` |
268
+ | `RateLimitError` | 429, with `retryAfter` |
269
+ | `ServerError` | 5xx |
270
+ | `NetworkError` / `TimeoutError` | the connection failed, or timed out |
271
+ | `SignatureVerificationError` | webhook verification failed |
272
+ | `ConfigurationError` | thrown by the constructor |
273
+
274
+ - **Retries:** network errors, timeouts and HTTP 429, 500, 502, 503 and 504 are retried up to `maxRetries` (default 3), with full-jitter backoff and `Retry-After`.
275
+ - **No double counting:** each goal call sends a random `Idempotency-Key`, reused across its retries, and the API ignores a second event with the same goal and reference, so a retry or a resend never counts twice.
276
+
277
+ ## Options
278
+
279
+ | Option | Default |
280
+ |---|---|
281
+ | `apiKey` | `CLIKGATE_API_KEY` |
282
+ | `baseUrl` | `https://api.clikgate.com` |
283
+ | `timeout` | 10 000 ms |
284
+ | `maxRetries` | 3 |
285
+ | `sendMode` | `'background'` (or `'sync'`) |
286
+ | `privateMode` | `'auto'` |
287
+ | `clickIdParam` | from config, else `cgid` |
288
+ | `logger` | `console`, warnings and errors only |
289
+ | `onError` | — (background failures) |
290
+ | `httpClient` | built-in (a `fetch`-compatible function for mTLS or tracing) |
291
+ | `proxy` | `HTTPS_PROXY` / `NO_PROXY` (or an explicit URL, or `false`) |
292
+ | `batchSize` / `flushInterval` / `maxQueueSize` | 100 / 1000 ms / 10 000 |
293
+ | `shutdownHooks` | `true` |
294
+
295
+ ## Everything else
296
+
297
+ `clikgate.api.<resource>.<operation>()` covers every API-key operation, generated from the OpenAPI spec (for example `clikgate.api.campaigns.listCampaigns()`). It uses the same transport, retries and errors.
298
+
299
+ The behaviour of all five Clikgate server SDKs is defined in [`server/SPEC.md`](../SPEC.md) and checked by the shared conformance suite.
300
+
301
+ ## Development
302
+
303
+ ```bash
304
+ npm ci
305
+ npm run lint && npm run typecheck && npm run typecheck:examples
306
+ npm test # unit tests + the conformance suite against the local mock server
307
+ npm run build # dist/esm, dist/cjs (+ .d.ts)
308
+ npm run check:package # exports resolve from import and require, and the tarball is clean
309
+ npm run generate # regenerate src/generated from server/openapi (needs Java 11+)
310
+ ```
311
+
312
+ Licence: MIT. Security: see [SECURITY.md](SECURITY.md).
package/SECURITY.md ADDED
@@ -0,0 +1,34 @@
1
+ # Security policy: Clikgate server SDKs
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ Email **security@clikgate.com** (trust centre: https://clikgate.com/trust). Please don't open a public issue.
6
+
7
+ - We acknowledge reports within 2 working days and keep you informed until the issue is fixed.
8
+ - Include the package and version, a description, and steps to reproduce.
9
+ - We credit reporters who want to be named.
10
+
11
+ ## Supported versions
12
+
13
+ | Package | Supported |
14
+ |---|---|
15
+ | `@clikgate/node` 1.x | yes |
16
+
17
+ Security fixes go to the latest minor version of each supported major version.
18
+
19
+ ## What the SDK does to stay safe
20
+
21
+ - **No telemetry.** The only identification is the `User-Agent` header (`clikgate-node/<version> (node <version>; <os> <arch>)`).
22
+ - **Never logged:** API keys, webhook secrets, request bodies, values, metadata, and (in private mode) references.
23
+ - **Private mode.** Fields other than the private-mode allow-list are refused **before** anything is sent. When the SDK can't confirm the organisation's setting, it assumes private mode is on.
24
+ - **Webhooks** are verified with HMAC-SHA256 and a constant-time comparison, within a 5-minute replay window.
25
+ - **HTTPS only.** `http://` is accepted only for `localhost`. Redirects are never followed.
26
+ - **Zero runtime dependencies.**
27
+ - **Releases** are published from GitHub Actions with npm trusted publishing (OIDC, no tokens) and npm provenance, with a CycloneDX SBOM attached to each GitHub release.
28
+
29
+ ## Verifying a release
30
+
31
+ ```bash
32
+ npm audit signatures # checks registry signatures and provenance attestations of installed packages
33
+ npm view @clikgate/node@<version> dist.attestations
34
+ ```
@@ -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,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HASHED_FIELDS = void 0;
4
+ exports.hashForAds = hashForAds;
5
+ exports.checkHashedFields = checkHashedFields;
6
+ const node_crypto_1 = require("node:crypto");
7
+ const errors_js_1 = require("./errors.js");
8
+ /** @internal The wire fields and their option names. */
9
+ exports.HASHED_FIELDS = [
10
+ ['hashed_email', 'hashedEmail'],
11
+ ['hashed_phone_e164', 'hashedPhoneE164'],
12
+ ['hashed_phone_digits', 'hashedPhoneDigits'],
13
+ ];
14
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
15
+ const sha256 = (value) => (0, node_crypto_1.createHash)('sha256').update(value, 'utf8').digest('hex');
16
+ /**
17
+ * Normalise and hash an email and / or phone on your own server, for a goal's ad network matching
18
+ * (`hashedEmail`, `hashedPhoneE164`, `hashedPhoneDigits`). Pure and offline. In private mode Clikgate never
19
+ * hashes for you: hash on your server with this helper and send only the hashes.
20
+ *
21
+ * - email: trimmed and lowercased; it must contain `@`.
22
+ * - phone: must include its country code (start with `+` or `00`); spaces and punctuation are removed, and the
23
+ * result must be 7–15 digits starting with 1–9. A national number such as `0803 123 4567` is refused.
24
+ *
25
+ * @throws {InvalidRequestError} `invalid_argument` (param `email` or `phone`); the input is never in the message.
26
+ * @example
27
+ * clikgate.goal('account_opened', {
28
+ * reference: 'APP-55231',
29
+ * clickId,
30
+ * ...hashForAds({ email: customer.email, phone: customer.phone }), // e.g. '+234 803 123 4567'
31
+ * });
32
+ */
33
+ function hashForAds(input) {
34
+ const out = {};
35
+ const { email, phone } = input ?? {};
36
+ if (email != null) {
37
+ const value = typeof email === 'string' ? email.trim().toLowerCase() : '';
38
+ if (!value.includes('@'))
39
+ throw (0, errors_js_1.localError)('invalid_argument', 'email must be an email address (it contains @).', 'email');
40
+ out.hashedEmail = sha256(value);
41
+ }
42
+ if (phone != null) {
43
+ const trimmed = typeof phone === 'string' ? phone.trim() : '';
44
+ let digits = trimmed.replace(/\D/g, '');
45
+ if (trimmed.startsWith('00'))
46
+ digits = digits.slice(2);
47
+ else if (!trimmed.startsWith('+'))
48
+ digits = '';
49
+ if (!/^[1-9]\d{6,14}$/.test(digits)) {
50
+ throw (0, errors_js_1.localError)('invalid_argument', 'phone must include its country code, e.g. "+234 803 123 4567" (7-15 digits after the +).', 'phone');
51
+ }
52
+ out.hashedPhoneE164 = sha256(`+${digits}`);
53
+ out.hashedPhoneDigits = sha256(digits);
54
+ }
55
+ return out;
56
+ }
57
+ /** @internal Refuse a hashed wire field that isn't 64 lowercase hex characters (the value is never echoed). */
58
+ function checkHashedFields(wire) {
59
+ for (const [field] of exports.HASHED_FIELDS) {
60
+ const v = wire[field];
61
+ if (v == null)
62
+ continue;
63
+ if (typeof v !== 'string' || !SHA256_HEX.test(v)) {
64
+ throw (0, errors_js_1.localError)('invalid_hashed_identifier', `${field} must be a SHA-256 hash as 64 lowercase hex characters (use hashForAds).`, field);
65
+ }
66
+ }
67
+ }