@aifinpay/analytics 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CoinSecurities (SECCO)
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,89 @@
1
- # Temporary Holding Version
1
+ # @aifinpay/analytics
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
+ Telemetry for AiFinPay SDK packages. **On unless turned off** with
4
+ `AIFINPAY_TELEMETRY=off`. Zero runtime dependencies: `node:fetch`, `node:fs`
5
+ and `node:crypto` only.
6
+
7
+ This package owns the whole telemetry contract — the environment
8
+ variables that turn it off, the install id, payload sanitization, transport and the event
9
+ schema — so there is one network surface to review. Consumer packages
10
+ (`@aifinpay/agent`, `@aifinpay/mcp`, …) only call `emit()`.
11
+
12
+ ## Turning it off
13
+
14
+ | `AIFINPAY_TELEMETRY` | What happens |
15
+ | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
16
+ | unset or empty | Runtime events are sent. A random install id is stored at `~/.aifinpay/.telemetry-id`. |
17
+ | `on` | The same, and it wins over `DO_NOT_TRACK` and `CI`. |
18
+ | `read-only` | Runtime events are sent, but nothing is written to disk: an existing install id is reused, else a per-process id. |
19
+ | `off`, `0`, `false`, `no` (any case) | Nothing is sent, nothing is written. |
20
+ | `install` | Only the one-shot `agent_sdk_install_completed` event from the postinstall script. Runtime events stay off. |
21
+ | anything else | Off: a typo never turns sending on. |
22
+
23
+ Unless the value is `on` or `read-only`, `DO_NOT_TRACK=1` (or `true`) and a
24
+ `CI` variable other than empty, `false` or `0` also turn it off. The first
25
+ run that stores an install id without an explicit `on` prints one line to
26
+ stderr, never to stdout; if the id file cannot be written, the run sends with
27
+ a per-process id and prints nothing. Nothing is sent at install time unless
28
+ `AIFINPAY_TELEMETRY=install`.
29
+
30
+ `AIFINPAY_TELEMETRY_URL` overrides the destination (default
31
+ `https://api.aifinpay.io/v1/agent`). It must be HTTPS, or HTTP on
32
+ loopback for local development. An unusable value disables sending — it never
33
+ falls back to the default.
34
+
35
+ ## What is sent
36
+
37
+ ```json
38
+ {
39
+ "schema_version": 1,
40
+ "install_id": "8f2c…-uuid",
41
+ "mode": "on",
42
+ "events": [{ "name": "settlement_execute_confirmed", "ts": 1792000000, "payload": { "network": "polygon" } }]
43
+ }
44
+ ```
45
+
46
+ Headers: `AIFP-Telemetry-Schema`, `AIFP-Telemetry-Install`,
47
+ `AIFP-Telemetry-Mode`, `AIFP-Telemetry-User-Agent` (package and Node version).
48
+ Only names in the schema catalog (`EVENT_NAMES`) are sent; anything else is
49
+ dropped locally.
50
+
51
+ ## Payload sanitization
52
+
53
+ Every payload passes through a scrubber before it is queued. It removes seed
54
+ phrases, private keys (hex and base58), JWTs, bearer tokens and signature-sized
55
+ hex blobs; shortens addresses to first-4/last-4; reduces URLs to their origin;
56
+ and replaces any field whose name looks like a credential (`privateKey`,
57
+ `passphrase`, `token`, …). Errors are reduced to their class name. Payloads are
58
+ bounded (depth 4, 32 keys, 32 array items, 256-character strings) and an event
59
+ over 4 KB is dropped.
60
+
61
+ ## Behaviour
62
+
63
+ - `emit()` is synchronous for the caller and never throws. Sending happens on
64
+ a microtask, in batches of at most 64 events and about 90 KB (the
65
+ gateway's body limit is 100 KB).
66
+ - Bounded queue of 256 events; when full, new events are dropped.
67
+ - Each POST waits at most 1.5 s and is retried at most once, only after a
68
+ network error, timeout, 429 or 5xx. Redirects are refused.
69
+ - No timers: an idle process exits as if this package were absent. Call
70
+ `await shutdown()` before exit to flush what is queued.
71
+
72
+ ```ts
73
+ import { emit, shutdown } from "@aifinpay/analytics";
74
+
75
+ emit("unified_call_succeeded", { network: "polygon", ms: 412 });
76
+ await shutdown();
77
+ ```
78
+
79
+ ## Resetting the install id
80
+
81
+ Delete `~/.aifinpay/.telemetry-id`. The next run that sends creates a new random
82
+ id. The id is never derived from the machine or user and is never logged.
83
+
84
+ ## Threat model (summary)
85
+
86
+ The package sends only what consumers pass to `emit()`, after sanitization,
87
+ only while it is not turned off, only to an HTTPS destination. The postinstall
88
+ script loads nothing unless `AIFINPAY_TELEMETRY=install` and always exits 0.
89
+ See [docs/adr/0001-telemetry.md](docs/adr/0001-telemetry.md).
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Fire-and-forget emitter. `emit()` is synchronous, never throws and never
3
+ * blocks the caller: it validates, sanitizes and enqueues, and a microtask
4
+ * flushes the queue in batches. The queue is bounded; when it is full new
5
+ * events are dropped — telemetry loses data before it costs the host memory.
6
+ * No timers are created, so an idle process exits exactly as it would without
7
+ * this package.
8
+ */
9
+ import { type TelemetryMode } from "./env.js";
10
+ export type EventName = string;
11
+ export type EventPayload = Record<string, unknown>;
12
+ export interface EmitOptions {
13
+ /** Only for payloads this package's own callers already sanitized. */
14
+ skipSanitize?: boolean;
15
+ schemaVersion?: number;
16
+ }
17
+ export interface TelemetryConfig {
18
+ /** null disables sending (an invalid AIFINPAY_TELEMETRY_URL produces null). */
19
+ url: string | null;
20
+ schemaVersion: number;
21
+ timeoutMs: number;
22
+ maxRetries: number;
23
+ queueSize: number;
24
+ mode: TelemetryMode;
25
+ }
26
+ /** The gateway accepts at most 64 events per POST (AIFINP-240). */
27
+ export declare const MAX_BATCH = 64;
28
+ /** The gateway refuses a serialized event over 4 KB with 413. */
29
+ export declare const MAX_EVENT_BYTES = 4096;
30
+ /** The gateway's JSON body limit is 100 KB; 64 large events would exceed it. */
31
+ export declare const MAX_BATCH_BYTES = 90000;
32
+ export declare function configure(next: Partial<TelemetryConfig>): void;
33
+ /** True when runtime events would actually be sent. */
34
+ export declare function isEnabled(): boolean;
35
+ export declare function emit(name: EventName, payload?: EventPayload, opts?: EmitOptions): void;
36
+ /** Flush what is queued and wait for in-flight sends. Call before process exit. */
37
+ export declare function shutdown(): Promise<void>;
38
+ //# sourceMappingURL=emitter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emitter.d.ts","sourceRoot":"","sources":["../src/emitter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAqE,KAAK,aAAa,EAAE,MAAM,UAAU,CAAC;AAOjH,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC;AAC/B,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEnD,MAAM,WAAW,WAAW;IAC1B,sEAAsE;IACtE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,+EAA+E;IAC/E,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,aAAa,CAAC;CACrB;AAED,mEAAmE;AACnE,eAAO,MAAM,SAAS,KAAK,CAAC;AAC5B,iEAAiE;AACjE,eAAO,MAAM,eAAe,OAAO,CAAC;AACpC,gFAAgF;AAChF,eAAO,MAAM,eAAe,QAAS,CAAC;AA2BtC,wBAAgB,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,eAAe,CAAC,GAAG,IAAI,CAY9D;AAMD,uDAAuD;AACvD,wBAAgB,SAAS,IAAI,OAAO,CAGnC;AAQD,wBAAgB,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,GAAE,YAAiB,EAAE,IAAI,GAAE,WAAgB,GAAG,IAAI,CAuB9F;AA4CD,mFAAmF;AACnF,wBAAsB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAI9C"}
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Fire-and-forget emitter. `emit()` is synchronous, never throws and never
3
+ * blocks the caller: it validates, sanitizes and enqueues, and a microtask
4
+ * flushes the queue in batches. The queue is bounded; when it is full new
5
+ * events are dropped — telemetry loses data before it costs the host memory.
6
+ * No timers are created, so an idle process exits exactly as it would without
7
+ * this package.
8
+ */
9
+ import { resolveMode, runtimeEnabled, urlFromEnv, validTelemetryUrl, MODES } from "./env.js";
10
+ import { loadInstallId } from "./identity.js";
11
+ import { sanitizePayload } from "./sanitize.js";
12
+ import { isKnownEvent } from "./schema.js";
13
+ import { sendBatch } from "./transport.js";
14
+ import { AIFINPAY_TELEMETRY_SCHEMA_VERSION } from "./version.js";
15
+ /** The gateway accepts at most 64 events per POST (AIFINP-240). */
16
+ export const MAX_BATCH = 64;
17
+ /** The gateway refuses a serialized event over 4 KB with 413. */
18
+ export const MAX_EVENT_BYTES = 4096;
19
+ /** The gateway's JSON body limit is 100 KB; 64 large events would exceed it. */
20
+ export const MAX_BATCH_BYTES = 90_000;
21
+ const INSTALL_EVENT = "agent_sdk_install_completed";
22
+ const DEFAULT_ON_NOTICE = "AiFinPay sends usage events with a random install id: no wallet addresses, URLs or amounts. Turn off: AIFINPAY_TELEMETRY=off";
23
+ let config = null;
24
+ let queue = [];
25
+ let scheduled = false;
26
+ let inflight = Promise.resolve();
27
+ let installId = null;
28
+ let onByDefault = false;
29
+ function current() {
30
+ if (config)
31
+ return config;
32
+ const resolved = resolveMode();
33
+ onByDefault = resolved.byDefault;
34
+ config = {
35
+ url: urlFromEnv(),
36
+ schemaVersion: AIFINPAY_TELEMETRY_SCHEMA_VERSION,
37
+ timeoutMs: 1500,
38
+ maxRetries: 1,
39
+ queueSize: 256,
40
+ mode: resolved.mode,
41
+ };
42
+ return config;
43
+ }
44
+ export function configure(next) {
45
+ const base = current();
46
+ const merged = { ...base, ...next };
47
+ if (next.url !== undefined)
48
+ merged.url = next.url === null ? null : validTelemetryUrl(next.url);
49
+ if (!MODES.includes(merged.mode))
50
+ merged.mode = "off";
51
+ merged.timeoutMs = clampInt(merged.timeoutMs, 1, 1500, base.timeoutMs);
52
+ merged.maxRetries = clampInt(merged.maxRetries, 0, 1, base.maxRetries);
53
+ merged.queueSize = clampInt(merged.queueSize, 1, 256, base.queueSize);
54
+ merged.schemaVersion = clampInt(merged.schemaVersion, 1, Number.MAX_SAFE_INTEGER, base.schemaVersion);
55
+ if (next.mode !== undefined)
56
+ onByDefault = false;
57
+ if (merged.mode !== base.mode)
58
+ installId = null;
59
+ config = merged;
60
+ }
61
+ function clampInt(value, min, max, fallback) {
62
+ return Number.isInteger(value) ? Math.min(max, Math.max(min, value)) : fallback;
63
+ }
64
+ /** True when runtime events would actually be sent. */
65
+ export function isEnabled() {
66
+ const cfg = current();
67
+ return runtimeEnabled(cfg.mode) && cfg.url !== null;
68
+ }
69
+ function allowed(name, mode) {
70
+ // The install event has its own consent level; it is never a runtime event.
71
+ if (name === INSTALL_EVENT)
72
+ return mode === "install";
73
+ return runtimeEnabled(mode);
74
+ }
75
+ export function emit(name, payload = {}, opts = {}) {
76
+ try {
77
+ const cfg = current();
78
+ if (cfg.url === null || !allowed(name, cfg.mode) || !isKnownEvent(name))
79
+ return;
80
+ if (queue.length >= cfg.queueSize)
81
+ return;
82
+ const safe = opts.skipSanitize && payload && typeof payload === "object" && !Array.isArray(payload)
83
+ ? payload
84
+ : sanitizePayload(payload);
85
+ const event = { name, ts: Math.floor(Date.now() / 1000), payload: safe };
86
+ const bytes = Buffer.byteLength(JSON.stringify(event));
87
+ if (bytes > MAX_EVENT_BYTES)
88
+ return;
89
+ queue.push({ event, schemaVersion: opts.schemaVersion ?? cfg.schemaVersion, bytes });
90
+ if (!scheduled) {
91
+ scheduled = true;
92
+ queueMicrotask(() => {
93
+ scheduled = false;
94
+ inflight = inflight.then(flush, flush);
95
+ });
96
+ }
97
+ }
98
+ catch {
99
+ // Telemetry never surfaces an error to the host.
100
+ }
101
+ }
102
+ async function flush() {
103
+ while (queue.length) {
104
+ const cfg = current();
105
+ if (cfg.url === null || cfg.mode === "off") {
106
+ queue = [];
107
+ return;
108
+ }
109
+ // One schema version per POST: the header and the body must agree.
110
+ const version = queue[0].schemaVersion;
111
+ let take = 0;
112
+ let bytes = 0;
113
+ while (take < queue.length && take < MAX_BATCH && queue[take].schemaVersion === version) {
114
+ bytes += queue[take].bytes;
115
+ if (take > 0 && bytes > MAX_BATCH_BYTES)
116
+ break;
117
+ take++;
118
+ }
119
+ const events = queue.splice(0, take).map((item) => item.event);
120
+ try {
121
+ installId ??= resolveId(cfg.mode);
122
+ await sendBatch({ schema_version: version, install_id: installId, mode: cfg.mode, events }, { url: cfg.url, timeoutMs: cfg.timeoutMs, maxRetries: cfg.maxRetries });
123
+ }
124
+ catch {
125
+ // dropped; see sendBatch for the retry policy
126
+ }
127
+ }
128
+ }
129
+ function resolveId(mode) {
130
+ const { id, created } = loadInstallId({ persist: mode !== "read-only" });
131
+ // Told once per install: only the run that wrote the id file prints it, never to stdout.
132
+ if (created && onByDefault && mode === "on") {
133
+ try {
134
+ process.stderr.write(DEFAULT_ON_NOTICE + "\n");
135
+ }
136
+ catch {
137
+ // a closed stderr must not cost the batch
138
+ }
139
+ }
140
+ return id;
141
+ }
142
+ /** Flush what is queued and wait for in-flight sends. Call before process exit. */
143
+ export async function shutdown() {
144
+ await new Promise((resolve) => queueMicrotask(resolve));
145
+ inflight = inflight.then(flush, flush);
146
+ await inflight;
147
+ }
148
+ //# sourceMappingURL=emitter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emitter.js","sourceRoot":"","sources":["../src/emitter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,UAAU,EAAE,iBAAiB,EAAE,KAAK,EAAsB,MAAM,UAAU,CAAC;AACjH,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAkB,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,iCAAiC,EAAE,MAAM,cAAc,CAAC;AAqBjE,mEAAmE;AACnE,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAC5B,iEAAiE;AACjE,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,CAAC;AACpC,gFAAgF;AAChF,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC;AACtC,MAAM,aAAa,GAAG,6BAA6B,CAAC;AACpD,MAAM,iBAAiB,GACrB,8HAA8H,CAAC;AAEjI,IAAI,MAAM,GAA2B,IAAI,CAAC;AAC1C,IAAI,KAAK,GAAsE,EAAE,CAAC;AAClF,IAAI,SAAS,GAAG,KAAK,CAAC;AACtB,IAAI,QAAQ,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;AAChD,IAAI,SAAS,GAAkB,IAAI,CAAC;AACpC,IAAI,WAAW,GAAG,KAAK,CAAC;AAExB,SAAS,O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AAI,CAAC;YACH,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAAC;QACjD,CAAC;QAAC,MAAM,CAAC;YACP,0CAA0C;QAC5C,CAAC;IACH,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAED,mFAAmF;AACnF,MAAM,CAAC,KAAK,UAAU,QAAQ;IAC5B,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;IAC9D,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACvC,MAAM,QAAQ,CAAC;AACjB,CAAC"}
package/dist/env.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The consent contract. Telemetry is ON unless turned off.
3
+ *
4
+ * on (default when AIFINPAY_TELEMETRY is unset or empty) runtime
5
+ * events are sent; the install id is persisted.
6
+ * read-only runtime events are sent, but nothing is ever written to disk:
7
+ * an existing install id is reused, otherwise a per-process id.
8
+ * install only the one-shot `agent_sdk_install_completed` event from the
9
+ * postinstall script. Runtime `emit()` stays silent — this level
10
+ * must not leak into `on`.
11
+ * off `off`, `0`, `false`, `no`, or any unrecognised value.
12
+ *
13
+ * DO_NOT_TRACK=1|true and a CI environment also mean off, unless the value is
14
+ * explicitly `on` or `read-only`.
15
+ */
16
+ export type TelemetryMode = "off" | "on" | "read-only" | "install";
17
+ export declare const MODES: readonly TelemetryMode[];
18
+ export declare const DEFAULT_TELEMETRY_URL = "https://api.aifinpay.io/v1/agent";
19
+ export interface ResolvedMode {
20
+ mode: TelemetryMode;
21
+ /** True when the mode is `on` only because nothing turned it off. */
22
+ byDefault: boolean;
23
+ }
24
+ export declare function resolveMode(env?: NodeJS.ProcessEnv): ResolvedMode;
25
+ export declare function modeFromEnv(env?: NodeJS.ProcessEnv): TelemetryMode;
26
+ /** HTTPS only, except loopback for local development. An unusable override
27
+ * returns null and disables sending rather than falling back to the default:
28
+ * the user asked for a different destination, so we must not pick one. */
29
+ export declare function urlFromEnv(env?: NodeJS.ProcessEnv): string | null;
30
+ export declare function validTelemetryUrl(raw: string): string | null;
31
+ /** Runtime events are allowed only in `on` and `read-only`. */
32
+ export declare function runtimeEnabled(mode: TelemetryMode): boolean;
33
+ //# sourceMappingURL=env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,aAAa,GAAG,KAAK,GAAG,IAAI,GAAG,WAAW,GAAG,SAAS,CAAC;AAEnE,eAAO,MAAM,KAAK,EAAE,SAAS,aAAa,EAA0C,CAAC;AACrF,eAAO,MAAM,qBAAqB,qCAAqC,CAAC;AAExE,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,aAAa,CAAC;IACpB,qEAAqE;IACrE,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,wBAAgB,WAAW,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,YAAY,CAO9E;AAED,wBAAgB,WAAW,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,aAAa,CAE/E;AAYD;;2EAE2E;AAC3E,wBAAgB,UAAU,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,MAAM,GAAG,IAAI,CAG9E;AAED,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAW5D;AAED,+DAA+D;AAC/D,wBAAgB,cAAc,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAE3D"}
package/dist/env.js ADDED
@@ -0,0 +1,52 @@
1
+ export const MODES = ["off", "on", "read-only", "install"];
2
+ export const DEFAULT_TELEMETRY_URL = "https://api.aifinpay.io/v1/agent";
3
+ export function resolveMode(env = process.env) {
4
+ const raw = (env.AIFINPAY_TELEMETRY ?? "").trim().toLowerCase();
5
+ if (raw === "on" || raw === "read-only")
6
+ return { mode: raw, byDefault: false };
7
+ if (doNotTrack(env) || inCi(env))
8
+ return { mode: "off", byDefault: false };
9
+ if (raw === "install")
10
+ return { mode: "install", byDefault: false };
11
+ if (raw === "")
12
+ return { mode: "on", byDefault: true };
13
+ return { mode: "off", byDefault: false };
14
+ }
15
+ export function modeFromEnv(env = process.env) {
16
+ return resolveMode(env).mode;
17
+ }
18
+ function doNotTrack(env) {
19
+ const value = (env.DO_NOT_TRACK ?? "").trim().toLowerCase();
20
+ return value === "1" || value === "true";
21
+ }
22
+ function inCi(env) {
23
+ const value = (env.CI ?? "").trim().toLowerCase();
24
+ return value !== "" && value !== "false" && value !== "0";
25
+ }
26
+ /** HTTPS only, except loopback for local development. An unusable override
27
+ * returns null and disables sending rather than falling back to the default:
28
+ * the user asked for a different destination, so we must not pick one. */
29
+ export function urlFromEnv(env = process.env) {
30
+ const raw = env.AIFINPAY_TELEMETRY_URL?.trim();
31
+ return raw ? validTelemetryUrl(raw) : DEFAULT_TELEMETRY_URL;
32
+ }
33
+ export function validTelemetryUrl(raw) {
34
+ let url;
35
+ try {
36
+ url = new URL(raw);
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ if (url.username || url.password)
42
+ return null;
43
+ if (url.protocol === "https:")
44
+ return url.toString();
45
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
46
+ return url.protocol === "http:" && loopback ? url.toString() : null;
47
+ }
48
+ /** Runtime events are allowed only in `on` and `read-only`. */
49
+ export function runtimeEnabled(mode) {
50
+ return mode === "on" || mode === "read-only";
51
+ }
52
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":"AAiBA,MAAM,CAAC,MAAM,KAAK,GAA6B,CAAC,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;AACrF,MAAM,CAAC,MAAM,qBAA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C;IAClD,OAAO,KAAK,KAAK,EAAE,IAAI,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC;AAC5D,CAAC;AAED;;2EAE2E;AAC3E,MAAM,UAAU,UAAU,CAAC,GAAG,GAAsB,OAAO,CAAC,GAAG;IAC7D,MAAM,GAAG,GAAG,GAAG,CAAC,sBAAsB,EAAE,IAAI,EAAE,CAAC;IAC/C,OAAO,GAAG,CAAC,CAAC,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,qBAAqB,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,GAAW;IAC3C,IAAI,GAAQ,CAAC;IACb,IAAI,CAAC;QACH,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC9C,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;IACrD,MAAM,QAAQ,GAAG,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC5E,OAAO,GAAG,CAAC,QAAQ,KAAK,OAAO,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACtE,CAAC;AAED,+DAA+D;AAC/D,MAAM,UAAU,cAAc,CAAC,IAAmB;IAChD,OAAO,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,WAAW,CAAC;AAC/C,CAAC"}
@@ -0,0 +1,20 @@
1
+ export declare function identityPath(home?: string): string;
2
+ export interface InstallId {
3
+ id: string;
4
+ /** True only when this call wrote the id file. */
5
+ created: boolean;
6
+ }
7
+ /**
8
+ * `persist: false` (read-only mode) never touches the disk beyond one read.
9
+ * A present but unreadable or malformed file is left alone — we do not
10
+ * overwrite something we did not write — and this process gets an ephemeral id.
11
+ */
12
+ export declare function loadInstallId({ persist, home }: {
13
+ persist: boolean;
14
+ home?: string;
15
+ }): InstallId;
16
+ export declare function resolveInstallId(opts: {
17
+ persist: boolean;
18
+ home?: string;
19
+ }): string;
20
+ //# sourceMappingURL=identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAeA,wBAAgB,YAAY,CAAC,IAAI,GAAE,MAAkB,GAAG,MAAM,CAE7D;AAWD,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,kDAAkD;IAClD,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAc/F;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAElF"}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The per-install id: a random UUID at ~/.aifinpay/.telemetry-id, created by
3
+ * the first run that sends and never derived from anything about the machine or user.
4
+ * Deleting the file resets it. The id is never logged.
5
+ *
6
+ * File rules follow the keystore rules in the root AGENTS.md: directory 700,
7
+ * file 600, created exclusively so two processes cannot both write it.
8
+ */
9
+ import { randomUUID } from "node:crypto";
10
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join } from "node:path";
13
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
14
+ export function identityPath(home = homedir()) {
15
+ return join(home, ".aifinpay", ".telemetry-id");
16
+ }
17
+ function readId(path) {
18
+ try {
19
+ const value = readFileSync(path, "utf8").trim();
20
+ return UUID_RE.test(value) ? value : null;
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
26
+ /**
27
+ * `persist: false` (read-only mode) never touches the disk beyond one read.
28
+ * A present but unreadable or malformed file is left alone — we do not
29
+ * overwrite something we did not write — and this process gets an ephemeral id.
30
+ */
31
+ export function loadInstallId({ persist, home }) {
32
+ const path = identityPath(home);
33
+ const existing = readId(path);
34
+ if (existing)
35
+ return { id: existing, created: false };
36
+ const fresh = randomUUID();
37
+ if (!persist)
38
+ return { id: fresh, created: false };
39
+ try {
40
+ mkdirSync(join(path, ".."), { recursive: true, mode: 0o700 });
41
+ writeFileSync(path, fresh + "\n", { mode: 0o600, flag: "wx" });
42
+ return { id: fresh, created: true };
43
+ }
44
+ catch {
45
+ // Lost a creation race, or the file exists but is not ours to repair.
46
+ return { id: readId(path) ?? fresh, created: false };
47
+ }
48
+ }
49
+ export function resolveInstallId(opts) {
50
+ return loadInstallId(opts).id;
51
+ }
52
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.js","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,MAAM,OAAO,GAAG,uEAAuE,CAAC;AAExF,MAAM,UAAU,YAAY,CAAC,IAAI,GAAW,OAAO,EAAE;IACnD,OAAO,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,eAAe,CAAC,CAAC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AAC;AACH,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,IAAyC;IACxE,OAAO,aAAa,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;AAChC,CAAC"}
@@ -0,0 +1,6 @@
1
+ export { emit, configure, shutdown, isEnabled, MAX_BATCH, MAX_EVENT_BYTES, MAX_BATCH_BYTES } from "./emitter.js";
2
+ export type { EventName, EventPayload, EmitOptions, TelemetryConfig } from "./emitter.js";
3
+ export { DEFAULT_TELEMETRY_URL, type TelemetryMode } from "./env.js";
4
+ export { EVENT_NAMES, isKnownEvent } from "./schema.js";
5
+ export { AIFINPAY_TELEMETRY_SCHEMA_VERSION } from "./version.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACjH,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC1F,OAAO,EAAE,qBAAqB,EAAE,KAAK,aAAa,EAAE,MAAM,UAAU,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,iCAAiC,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { emit, configure, shutdown, isEnabled, MAX_BATCH, MAX_EVENT_BYTES, MAX_BATCH_BYTES } from "./emitter.js";
2
+ export { DEFAULT_TELEMETRY_URL } from "./env.js";
3
+ export { EVENT_NAMES, isKnownEvent } from "./schema.js";
4
+ export { AIFINPAY_TELEMETRY_SCHEMA_VERSION } from "./version.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEjH,OAAO,EAAE,qBAAqB,EAAsB,MAAM,UAAU,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,iCAAiC,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,9 @@
1
+ export declare function sanitizeString(input: string): string;
2
+ export type SafeValue = string | number | boolean | null | SafeValue[] | {
3
+ [key: string]: SafeValue;
4
+ };
5
+ /** Top-level payloads are plain objects; anything else becomes `{}`. */
6
+ export declare function sanitizePayload(payload: unknown): {
7
+ [key: string]: SafeValue;
8
+ };
9
+ //# sourceMappingURL=sanitize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitize.d.ts","sourceRoot":"","sources":["../src/sanitize.ts"],"names":[],"mappings":"AAgDA,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOpD;AAED,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,EAAE,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AA8CtG,wEAAwE;AACxE,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAG9E"}
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Red-team payload scrubber. Every event payload passes through here before it
3
+ * is queued, so a careless call site cannot ship a secret. It errs towards
4
+ * over-redaction: a lost debugging detail is cheap, a leaked seed is not.
5
+ *
6
+ * Strings:
7
+ * - BIP-39-shaped phrases (12+ short lowercase words) → [redacted:seed]
8
+ * - JWTs (eyJ….….…) → [redacted:jwt]
9
+ * - "Bearer …" values → [redacted:bearer]
10
+ * - hex blobs ≥ 64 bytes (signatures, keypairs) → [redacted:hex]
11
+ * - 0x + 64 hex (EVM private key / 32-byte secret) → [redacted:key]
12
+ * - base58 80–90 chars (Solana secret key) → [redacted:key]
13
+ * - URLs → origin only (no path, no query)
14
+ * - secret-looking query params left over → value redacted
15
+ * - 0x + 40 hex (EVM address) → 0x1234…abcd
16
+ * - base58 32–44 chars (Solana address) → Abcd…wxyz
17
+ * Keys: a property whose name looks like a credential is replaced by
18
+ * [redacted:field] whatever its value.
19
+ */
20
+ const MAX_DEPTH = 4;
21
+ const MAX_KEYS = 32;
22
+ const MAX_ARRAY = 32;
23
+ const MAX_STRING = 256;
24
+ const SECRET_KEY_RE = /(secret|seed|mnemonic|passphrase|password|private[_-]?key|privkey|api[_-]?key|token|authorization|cookie|signature|keystore)/i;
25
+ const RULES = [
26
+ [/\b[a-z]{3,8}(?:\s+[a-z]{3,8}){11,23}\b/g, "[redacted:seed]"],
27
+ [/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g, "[redacted:jwt]"],
28
+ [/\bBearer\s+[^\s,;]+/gi, "[redacted:bearer]"],
29
+ [/\b(?:0x)?[0-9a-fA-F]{128,}\b/g, "[redacted:hex]"],
30
+ [/\b0x[0-9a-fA-F]{64}\b/g, "[redacted:key]"],
31
+ [/\b[1-9A-HJ-NP-Za-km-z]{80,90}\b/g, "[redacted:key]"],
32
+ [/\bhttps?:\/\/[^\s"'<>]+/gi, (match) => originOf(match)],
33
+ [/([?&](?:key|seed|secret|passphrase|token|password|api_key|apikey|signature)=)[^&\s#]*/gi, "$1[redacted]"],
34
+ [/\b0x[0-9a-fA-F]{40}\b/g, (match) => `${match.slice(0, 6)}…${match.slice(-4)}`],
35
+ [/\b[1-9A-HJ-NP-Za-km-z]{32,44}\b/g, (match) => `${match.slice(0, 4)}…${match.slice(-4)}`],
36
+ ];
37
+ function originOf(raw) {
38
+ try {
39
+ return new URL(raw).origin;
40
+ }
41
+ catch {
42
+ return "[redacted:url]";
43
+ }
44
+ }
45
+ export function sanitizeString(input) {
46
+ let out = input.length > MAX_STRING * 4 ? input.slice(0, MAX_STRING * 4) : input;
47
+ for (const [pattern, replacement] of RULES) {
48
+ out =
49
+ typeof replacement === "string" ? out.replace(pattern, replacement) : out.replace(pattern, (m) => replacement(m));
50
+ }
51
+ return out.length > MAX_STRING ? out.slice(0, MAX_STRING) + "…" : out;
52
+ }
53
+ function sanitizeValue(value, depth) {
54
+ if (value === null)
55
+ return null;
56
+ switch (typeof value) {
57
+ case "string":
58
+ return sanitizeString(value);
59
+ case "number":
60
+ return Number.isFinite(value) ? value : null;
61
+ case "boolean":
62
+ return value;
63
+ case "bigint":
64
+ return value.toString();
65
+ case "object":
66
+ break;
67
+ default:
68
+ return undefined; // functions, symbols, undefined
69
+ }
70
+ if (depth >= MAX_DEPTH)
71
+ return "[truncated]";
72
+ if (Array.isArray(value)) {
73
+ return value
74
+ .slice(0, MAX_ARRAY)
75
+ .map((item) => sanitizeValue(item, depth + 1))
76
+ .filter((item) => item !== undefined);
77
+ }
78
+ if (value instanceof Uint8Array || value instanceof ArrayBuffer)
79
+ return "[redacted:bytes]";
80
+ if (value instanceof Date)
81
+ return Number.isFinite(value.getTime()) ? value.toISOString() : null;
82
+ // Error class only: messages routinely embed URLs, addresses and bodies.
83
+ if (value instanceof Error)
84
+ return { class: sanitizeString(value.name) };
85
+ return sanitizeObject(value, depth);
86
+ }
87
+ function sanitizeObject(value, depth) {
88
+ const out = {};
89
+ for (const key of Object.keys(value).slice(0, MAX_KEYS)) {
90
+ const safeKey = sanitizeString(key).slice(0, 64);
91
+ if (SECRET_KEY_RE.test(key)) {
92
+ out[safeKey] = "[redacted:field]";
93
+ continue;
94
+ }
95
+ const item = sanitizeValue(value[key], depth + 1);
96
+ if (item !== undefined)
97
+ out[safeKey] = item;
98
+ }
99
+ return out;
100
+ }
101
+ /** Top-level payloads are plain objects; anything else becomes `{}`. */
102
+ export function sanitizePayload(payload) {
103
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
104
+ return {};
105
+ return sanitizeObject(payload, 0);
106
+ }
107
+ //# sourceMappingURL=sanitize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitize.js","sourceRoot":"","sources":["../src/sanitize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,QAAQ,GAAG,EAAE,CAAC;AACpB,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,UAAU,GAAG,GAAG,CAAC;AAEvB,MAAM,aAAa,GACjB,+HAA+H,CAAC;AAElI,MAAM,KAAK,GAA0D;IACnE,CAAC,yCAAyC,EAAE,iBAAiB,CAAC;IAC9D,CAAC,sDAAsD,EAAE,gBAAgB,CAAC;IAC1E,CAAC,uBAAuB,EAAE,mBAAmB,CAAC;IAC9C,CAAC,+BAA+B,EAAE,gBAAgB,CAAC;IACnD,CAAC,wBAAwB,EAAE,gBAAgB,CAAC;IAC5C,CAAC,kCAAkC,EAAE,gBAAgB,CAAC;IACtD,CAAC,2BAA2B,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzD,CAAC,yFAAyF,EAAE,cAAc,CAAC;IAC3G,CAAC,wBAAwB,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAChF,CAAC,kCAAkC,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;CAC3F,CAAC;AAEF,SAAS,Q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AAC,CAAC;QACjD,IAAI,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAC5B,GAAG,CAAC,OAAO,CAAC,GAAG,kBAAkB,CAAC;YAClC,SAAS;QACX,CAAC;QACD,MAAM,IAAI,GAAG,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;QAClD,IAAI,IAAI,KAAK,SAAS;YAAE,GAAG,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IAC9C,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,eAAe,CAAC,OAAgB;IAC9C,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO,EAAE,CAAC;IACjF,OAAO,cAAc,CAAC,OAAkC,EAAE,CAAC,CAAC,CAAC;AAC/D,CAAC"}
@@ -0,0 +1,3 @@
1
+ export declare const EVENT_NAMES: ReadonlySet<string>;
2
+ export declare function isKnownEvent(name: unknown): name is string;
3
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,WAAW,EAAE,WAAW,CAAC,MAAM,CA4E1C,CAAC;AAEH,wBAAgB,YAAY,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,MAAM,CAE1D"}
package/dist/schema.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Schema v1 event catalog. The telemetry gateway refuses any other name with
3
+ * `400 unknown_event`, so the SDK drops unknown names locally instead of
4
+ * sending a batch that would be rejected whole. Adding a name is additive and
5
+ * needs the gateway's list updated in the same release; renaming or removing
6
+ * one is a breaking change (ADR 0001, 90-day freeze window).
7
+ */
8
+ const expand = (prefix, suffixes) => suffixes.map((s) => `${prefix}_${s}`);
9
+ export const EVENT_NAMES = new Set([
10
+ // Install / first run
11
+ "agent_sdk_install_completed",
12
+ "agent_sdk_first_invocation",
13
+ // Identity / Agent Passport
14
+ ...expand("passport_resolve", ["started", "succeeded", "failed"]),
15
+ ...expand("passport_issue", ["started", "succeeded", "failed"]),
16
+ ...expand("passport_wallet_binding", ["challenge_requested", "confirmed", "failed"]),
17
+ ...expand("passport_issuer_signature", ["verified", "invalid"]),
18
+ // Settlement
19
+ ...expand("settlement", [
20
+ "invoice_validated",
21
+ "route_pin_validated",
22
+ "route_verified_onchain",
23
+ "execute_started",
24
+ "execute_dispatched",
25
+ "execute_confirmed",
26
+ "execute_failed",
27
+ ]),
28
+ ...expand("v14_call", ["validated", "submittable", "rejected"]),
29
+ // Unified surface
30
+ ...expand("unified", [
31
+ "agent_constructed",
32
+ "session_started",
33
+ "session_expired",
34
+ "quote_requested",
35
+ "quote_returned",
36
+ "call_started",
37
+ "call_succeeded",
38
+ "call_failed",
39
+ ]),
40
+ "budget_cap_exceeded",
41
+ // AIFP-1 merchant paywall
42
+ ...expand("aifp1", [
43
+ "challenge_received",
44
+ "quote_obtained",
45
+ "payment_authorized",
46
+ "pay_succeeded",
47
+ "pay_failed",
48
+ "receipt_cached_hit",
49
+ "receipt_cached_miss",
50
+ "recovery_attempted",
51
+ "recovery_succeeded",
52
+ "recovery_failed",
53
+ ]),
54
+ // Cross-chain bridge
55
+ ...expand("bridge", [
56
+ "quote_requested",
57
+ "quote_returned",
58
+ "execute_started",
59
+ "execute_dispatched",
60
+ "execute_arrived",
61
+ "execute_failed",
62
+ ]),
63
+ // Splitter / deployment resolution
64
+ ...expand("splitter_route", ["resolved", "not_found", "not_settling"]),
65
+ ...expand("deployment", ["resolved", "fallback", "disabled", "version_unavailable"]),
66
+ "no_deployment",
67
+ "dev_network_used",
68
+ // Wallet
69
+ ...expand("wallet", ["derived_standard", "derived_legacy_solana", "load_succeeded", "load_failed", "decrypt_failed"]),
70
+ "external_wallet_attached",
71
+ // Spend ledger
72
+ ...expand("spend_ledger", ["initialized", "appended", "overflow_blocked"]),
73
+ // History / quota
74
+ "agent_history_fetched",
75
+ ...expand("quota_check", ["within", "exceeded"]),
76
+ // Legacy facilitators
77
+ ...expand("facilitator", ["detected", "unsupported"]),
78
+ ...expand("x402", ["challenge_seen", "settled", "failed"]),
79
+ // Errors and recovery
80
+ "runtime_verify_failed",
81
+ "payment_too_expensive",
82
+ "funding_timeout",
83
+ "seat_not_found",
84
+ "safe_error_shaped",
85
+ ]);
86
+ export function isKnownEvent(name) {
87
+ return typeof name === "string" && EVENT_NAMES.has(name);
88
+ }
89
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,MAAM,GAAG,CAAC,MAAc,EAAE,QAAkB,EAAY,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,CAAC;AAEvG,MAAM,CAAC,MAAM,WAAW,GAAwB,IAAI,GAAG,CAAC;IACtD,sBAAsB;IACtB,6BAA6B;IAC7B,4BAA4B;IAC5B,4BAA4B;IAC5B,GAAG,MAAM,CAAC,kBAAkB,EAAE,CAAC,SAAS,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;IACjE,GAAG,MAAM,CAAC,gBAAgB,EAAE,CAAC,SAAS,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;IAC/D,GAAG,MAAM,CAAC,yBAAyB,EAAE,CAAC,qBAAqB,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;IACpF,GAAG,MAAM,CAAC,2BAA2B,EAAE,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;IAC/D,aAAa;IACb,GAAG,MAAM,CAAC,YAAY,EAAE;QACtB,mBAAmB;QACnB,qBAAqB;QACrB,wBAAwB;QACxB,iBAAi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AU,CAAC,CAAC;IAChD,sBAAsB;IACtB,GAAG,MAAM,CAAC,aAAa,EAAE,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC;IACrD,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,gBAAgB,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;IAC1D,sBAAsB;IACtB,uBAAuB;IACvB,uBAAuB;IACvB,iBAAiB;IACjB,gBAAgB;IAChB,mBAAmB;CACpB,CAAC,CAAC;AAEH,MAAM,UAAU,YAAY,CAAC,IAAa;IACxC,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAC3D,CAAC"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * One POST per batch to the telemetry gateway. Telemetry must never slow down
3
+ * or break the SDK that carries it, so this never throws, waits at most
4
+ * `timeoutMs` per attempt and retries at most `maxRetries` times — only for
5
+ * outcomes another attempt could change (network error, timeout, 429, 5xx).
6
+ * A 4xx is final: the gateway judged the batch, sending it again is noise.
7
+ */
8
+ import type { TelemetryMode } from "./env.js";
9
+ export interface WireEvent {
10
+ name: string;
11
+ /** Unix seconds. */
12
+ ts: number;
13
+ payload: Record<string, unknown>;
14
+ }
15
+ export interface Batch {
16
+ schema_version: number;
17
+ install_id: string;
18
+ mode: TelemetryMode;
19
+ events: WireEvent[];
20
+ }
21
+ export interface TransportOptions {
22
+ url: string;
23
+ timeoutMs: number;
24
+ maxRetries: number;
25
+ }
26
+ export declare const USER_AGENT: string;
27
+ /** Resolves true when the gateway acknowledged the batch with a 2xx. */
28
+ export declare function sendBatch(batch: Batch, options: TransportOptions): Promise<boolean>;
29
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAG9C,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,oBAAoB;IACpB,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED,MAAM,WAAW,KAAK;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,aAAa,CAAC;IACpB,MAAM,EAAE,SAAS,EAAE,CAAC;CACrB;AAED,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,UAAU,QAA2E,CAAC;AAEnG,wEAAwE;AACxE,wBAAsB,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CA0BzF"}
@@ -0,0 +1,34 @@
1
+ import { PACKAGE_VERSION } from "./version.js";
2
+ export const USER_AGENT = `@aifinpay/analytics/${PACKAGE_VERSION} (node ${process.versions.node})`;
3
+ /** Resolves true when the gateway acknowledged the batch with a 2xx. */
4
+ export async function sendBatch(batch, options) {
5
+ const body = JSON.stringify(batch);
6
+ for (let attempt = 0; attempt <= options.maxRetries; attempt++) {
7
+ try {
8
+ const response = await fetch(options.url, {
9
+ method: "POST",
10
+ headers: {
11
+ "Content-Type": "application/json",
12
+ "AIFP-Telemetry-Schema": String(batch.schema_version),
13
+ "AIFP-Telemetry-Install": batch.install_id,
14
+ "AIFP-Telemetry-Mode": batch.mode,
15
+ "AIFP-Telemetry-User-Agent": USER_AGENT,
16
+ },
17
+ body,
18
+ // A redirect could hand the batch to a host the user never configured.
19
+ redirect: "error",
20
+ signal: AbortSignal.timeout(options.timeoutMs),
21
+ });
22
+ await response.body?.cancel().catch(() => { });
23
+ if (response.ok)
24
+ return true;
25
+ if (response.status !== 429 && response.status < 500)
26
+ return false;
27
+ }
28
+ catch {
29
+ // network error, timeout or refused redirect — retry if budget remains
30
+ }
31
+ }
32
+ return false;
33
+ }
34
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAsB/C,MAAM,CAAC,MAAM,UAAU,GAAG,uBAAuB,eAAe,UAAU,OAAO,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC;AAEnG,wEAAwE;AACxE,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,KAAY,EAAE,OAAyB;IACrE,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACnC,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,OAAO,CAAC,UAAU,EAAE,OAAO,EAAE,EAAE,CAAC;QAC/D,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE;gBACxC,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE;oBACP,cAAc,EAAE,kBAAkB;oBAClC,uBAAuB,EAAE,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC;oBACrD,wBAAwB,EAAE,KAAK,CAAC,UAAU;oBAC1C,qBAAqB,EAAE,KAAK,CAAC,IAAI;oBACjC,2BAA2B,EAAE,UAAU;iBACxC;gBACD,IAAI;gBACJ,uEAAuE;gBACvE,QAAQ,EAAE,OAAO;gBACjB,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC;aAC/C,CAAC,CAAC;YACH,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAC9C,IAAI,QAAQ,CAAC,EAAE;gBAAE,OAAO,IAAI,CAAC;YAC7B,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAC,MAAM,GAAG,GAAG;gBAAE,OAAO,KAAK,CAAC;QACrE,CAAC;QAAC,MAAM,CAAC;YACP,uEAAuE;QACzE,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,6 @@
1
+ /** Wire schema version sent as `AIFP-Telemetry-Schema` and in every batch body.
2
+ * A breaking change waits at least 90 days after the previous one (ADR 0001). */
3
+ export declare const AIFINPAY_TELEMETRY_SCHEMA_VERSION = 1;
4
+ /** This package's own version, reported in `AIFP-Telemetry-User-Agent`. */
5
+ export declare const PACKAGE_VERSION = "0.2.0";
6
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA;kFACkF;AAClF,eAAO,MAAM,iCAAiC,IAAI,CAAC;AAEnD,2EAA2E;AAC3E,eAAO,MAAM,eAAe,UAAU,CAAC"}
@@ -0,0 +1,6 @@
1
+ /** Wire schema version sent as `AIFP-Telemetry-Schema` and in every batch body.
2
+ * A breaking change waits at least 90 days after the previous one (ADR 0001). */
3
+ export const AIFINPAY_TELEMETRY_SCHEMA_VERSION = 1;
4
+ /** This package's own version, reported in `AIFP-Telemetry-User-Agent`. */
5
+ export const PACKAGE_VERSION = "0.2.0";
6
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA;kFACkF;AAClF,MAAM,CAAC,MAAM,iCAAiC,GAAG,CAAC,CAAC;AAEnD,2EAA2E;AAC3E,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@aifinpay/analytics",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Zero-dependency SDK telemetry for AiFinPay packages \u2014 on unless turned off, sanitized, fire-and-forget.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "scripts/postinstall.js",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.json",
22
+ "test": "vitest run",
23
+ "postinstall": "node scripts/postinstall.js",
24
+ "prepublishOnly": "npm run build",
25
+ "format": "prettier --write \"**/*.{js,mjs,cjs,ts,json,md}\"",
26
+ "format:check": "prettier --check \"**/*.{js,mjs,cjs,ts,json,md}\""
27
+ },
28
+ "keywords": [
29
+ "aifinpay",
30
+ "telemetry",
31
+ "analytics"
32
+ ],
33
+ "author": "CoinSecurities (SECCO) <contact@aifinpay.io>",
34
+ "license": "MIT",
35
+ "homepage": "https://github.com/AiFinPay/sdk#readme",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/AiFinPay/sdk.git",
39
+ "directory": "analytics"
40
+ },
41
+ "bugs": "https://github.com/AiFinPay/sdk/issues",
42
+ "dependencies": {},
43
+ "devDependencies": {
44
+ "@types/node": "^20.0.0",
45
+ "prettier": "^3.9.6",
46
+ "typescript": "^7.0.2",
47
+ "vitest": "^4.1.5"
48
+ },
49
+ "engines": {
50
+ "node": ">=22"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ }
55
+ }
@@ -0,0 +1,21 @@
1
+ // One-shot install event. Runs at `npm install` time, so it has its own consent
2
+ // level: it does anything only when AIFINPAY_TELEMETRY=install. Any other value
3
+ // (including unset) returns before the package is even loaded. It must never
4
+ // fail an install: every error is swallowed and the exit code is always 0.
5
+ if (process.env.AIFINPAY_TELEMETRY?.trim().toLowerCase() === "install") {
6
+ try {
7
+ const { emit, shutdown } = await import("../dist/index.js");
8
+ const ua = process.env.npm_config_user_agent ?? "";
9
+ emit("agent_sdk_install_completed", {
10
+ package_manager: ua.split("/")[0] || "unknown",
11
+ package_version: process.env.npm_package_version ?? null,
12
+ node_version: process.versions.node,
13
+ os: process.platform,
14
+ arch: process.arch,
15
+ ci: Boolean(process.env.CI),
16
+ });
17
+ await shutdown();
18
+ } catch {
19
+ // dist missing (source checkout) or network down — never break the install
20
+ }
21
+ }