cursedbelt-server 4.59.0 → 4.60.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/dist/server/engagement/api.d.ts +6 -0
- package/dist/server/engagement/api.js +3 -0
- package/dist/server/engagement/d1.d.ts +7 -0
- package/dist/server/engagement/d1.js +4 -0
- package/dist/server/engagement/events.d.ts +26 -0
- package/dist/server/engagement/events.js +52 -0
- package/dist/server/events/actions.d.ts +46 -0
- package/dist/server/events/actions.js +62 -0
- package/dist/server/events/actor.d.ts +19 -0
- package/dist/server/events/actor.js +30 -0
- package/dist/server/events/gauge.d.ts +21 -0
- package/dist/server/events/gauge.js +60 -0
- package/dist/server/events/index.d.ts +14 -0
- package/dist/server/events/index.js +14 -0
- package/dist/server/events/point.d.ts +77 -0
- package/dist/server/events/point.js +149 -0
- package/dist/server/events/sink.d.ts +97 -0
- package/dist/server/events/sink.js +113 -0
- package/dist/server/events/views.d.ts +24 -0
- package/dist/server/events/views.js +41 -0
- package/package.json +8 -2
- package/src/server/bench/cpuBudget.spec.ts +12 -8
- package/src/server/engagement/api.ts +8 -0
- package/src/server/engagement/d1.ts +9 -0
- package/src/server/engagement/events.ts +79 -0
- package/src/server/events/actions.spec.ts +126 -0
- package/src/server/events/actions.ts +113 -0
- package/src/server/events/actor.ts +34 -0
- package/src/server/events/gauge.spec.ts +75 -0
- package/src/server/events/gauge.ts +81 -0
- package/src/server/events/index.ts +47 -0
- package/src/server/events/point.spec.ts +145 -0
- package/src/server/events/point.ts +197 -0
- package/src/server/events/sink.spec.ts +289 -0
- package/src/server/events/sink.ts +221 -0
- package/src/server/events/views.ts +62 -0
- package/src/server/telemetryIsWorkerSafe.spec.ts +23 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { ANON_PREFIX, LOCAL_EVENTS_SALT, anonymousActor, anonymousActorInput } from "./actor.js";
|
|
3
|
+
import { classifyDevice, type EventPoint, isBotUserAgent, outcomeOf, referrerHost, toEventPoint, truncateUtf8, utcDay } from "./point.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The wire format is the whole contract: the collector reads `blob7` and means `actorKind`
|
|
7
|
+
* everywhere, in every workspace. A position that moves is a silent corruption of every chart.
|
|
8
|
+
*/
|
|
9
|
+
const EVENT: EventPoint = {
|
|
10
|
+
app: "music",
|
|
11
|
+
kind: "action",
|
|
12
|
+
name: "file.upload",
|
|
13
|
+
place: "upload",
|
|
14
|
+
actor: "someone@example.com",
|
|
15
|
+
actorKind: "user",
|
|
16
|
+
actorLabel: "Someone",
|
|
17
|
+
tenant: "",
|
|
18
|
+
via: "web",
|
|
19
|
+
purpose: "upload",
|
|
20
|
+
device: "desktop",
|
|
21
|
+
country: "US",
|
|
22
|
+
outcome: "ok",
|
|
23
|
+
referrer: "",
|
|
24
|
+
build: "abc1234",
|
|
25
|
+
ms: 412,
|
|
26
|
+
bytes: 1_048_576,
|
|
27
|
+
value: 3,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
describe("🔴 toEventPoint — the schema's exact layout", () => {
|
|
31
|
+
test("index1 = kind:name; blobs 1..16 and doubles 1..4 in the documented order", () => {
|
|
32
|
+
expect(toEventPoint(EVENT)).toEqual({
|
|
33
|
+
indexes: ["action:file.upload"],
|
|
34
|
+
blobs: [
|
|
35
|
+
"e1",
|
|
36
|
+
"music",
|
|
37
|
+
"action",
|
|
38
|
+
"file.upload",
|
|
39
|
+
"upload",
|
|
40
|
+
"someone@example.com",
|
|
41
|
+
"user",
|
|
42
|
+
"Someone",
|
|
43
|
+
"",
|
|
44
|
+
"web",
|
|
45
|
+
"upload",
|
|
46
|
+
"desktop",
|
|
47
|
+
"US",
|
|
48
|
+
"ok",
|
|
49
|
+
"",
|
|
50
|
+
"abc1234",
|
|
51
|
+
],
|
|
52
|
+
doubles: [1, 412, 1_048_576, 3],
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("a non-finite double reads 0, never NaN — a positional array cannot hold a null", () => {
|
|
57
|
+
expect(toEventPoint({ ...EVENT, ms: Number.NaN, bytes: Number.POSITIVE_INFINITY }).doubles).toEqual([1, 0, 0, 3]);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("the index is cut to 96 BYTES without splitting a code point", () => {
|
|
61
|
+
const name = "é".repeat(80);
|
|
62
|
+
const [index] = toEventPoint({ ...EVENT, name }).indexes;
|
|
63
|
+
expect(new TextEncoder().encode(index).length).toBeLessThanOrEqual(96);
|
|
64
|
+
expect(index.startsWith("action:é")).toBe(true);
|
|
65
|
+
expect(index.includes("�")).toBe(false);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("truncateUtf8 counts bytes, not UTF-16 units", () => {
|
|
69
|
+
expect(truncateUtf8("abc", 2)).toBe("ab");
|
|
70
|
+
expect(truncateUtf8("ééé", 3)).toBe("é");
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
describe("classification — the closed vocabularies", () => {
|
|
75
|
+
test("device: phone before tablet, tablet before desktop, tools are `other`, crawlers are `bot`", () => {
|
|
76
|
+
expect(classifyDevice("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148 Safari/604.1")).toBe("phone");
|
|
77
|
+
expect(classifyDevice("Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/120 Mobile Safari/537.36")).toBe("phone");
|
|
78
|
+
expect(classifyDevice("Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Safari/604.1")).toBe("tablet");
|
|
79
|
+
expect(classifyDevice("Mozilla/5.0 (Linux; Android 14; SM-X910) AppleWebKit/537.36 Chrome/120 Safari/537.36")).toBe("tablet");
|
|
80
|
+
expect(classifyDevice("Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 Chrome/120 Safari/537.36")).toBe("desktop");
|
|
81
|
+
expect(classifyDevice("curl/8.4.0")).toBe("other");
|
|
82
|
+
expect(classifyDevice("Bun/1.3.1")).toBe("other");
|
|
83
|
+
expect(classifyDevice("python-requests/2.31")).toBe("other");
|
|
84
|
+
expect(classifyDevice("")).toBe("other");
|
|
85
|
+
expect(classifyDevice(null)).toBe("other");
|
|
86
|
+
expect(classifyDevice("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")).toBe("bot");
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("bot: every word the schema lists, case-insensitively", () => {
|
|
90
|
+
for (const ua of ["Googlebot/2.1", "bingbot/2.0", "SomeBot", "a crawler", "Spider", "Yahoo! Slurp", "LinkPreview", "facebookexternalhit/1.1", "HeadlessChrome/120"]) {
|
|
91
|
+
expect({ ua, bot: isBotUserAgent(ua) }).toEqual({ ua, bot: true });
|
|
92
|
+
}
|
|
93
|
+
expect(isBotUserAgent("Mozilla/5.0 (Macintosh) Safari/605.1.15")).toBe(false);
|
|
94
|
+
expect(isBotUserAgent("")).toBe(false);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test("outcome: ok | fail (4xx) | refused (401/403) | error (5xx)", () => {
|
|
98
|
+
expect(outcomeOf(200)).toBe("ok");
|
|
99
|
+
expect(outcomeOf(204)).toBe("ok");
|
|
100
|
+
expect(outcomeOf(302)).toBe("ok");
|
|
101
|
+
expect(outcomeOf(400)).toBe("fail");
|
|
102
|
+
expect(outcomeOf(404)).toBe("fail");
|
|
103
|
+
expect(outcomeOf(429)).toBe("fail");
|
|
104
|
+
expect(outcomeOf(401)).toBe("refused");
|
|
105
|
+
expect(outcomeOf(403)).toBe("refused");
|
|
106
|
+
expect(outcomeOf(500)).toBe("error");
|
|
107
|
+
expect(outcomeOf(503)).toBe("error");
|
|
108
|
+
expect(outcomeOf(undefined)).toBe("ok");
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test("referrer: the host only — never a path, a query or a malformed value", () => {
|
|
112
|
+
expect(referrerHost("https://news.ycombinator.com/item?id=1&q=secret")).toBe("news.ycombinator.com");
|
|
113
|
+
expect(referrerHost("HTTPS://Example.COM/")).toBe("example.com");
|
|
114
|
+
expect(referrerHost("not a url")).toBe("");
|
|
115
|
+
expect(referrerHost(null)).toBe("");
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("utcDay is the UTC calendar day, not the Mac's", () => {
|
|
119
|
+
expect(utcDay(Date.UTC(2026, 9, 31, 23, 59, 59))).toBe("2026-10-31");
|
|
120
|
+
expect(utcDay(Date.UTC(2026, 10, 1, 0, 0, 0))).toBe("2026-11-01");
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
describe("🔴 the anonymous actor — daily, salted, unlinkable", () => {
|
|
125
|
+
const input = { ip: "203.0.113.9", userAgent: "Mozilla/5.0", salt: "s", now: Date.UTC(2026, 9, 31, 12) };
|
|
126
|
+
|
|
127
|
+
test("hashes exactly `utcDay|ip|ua|salt`", () => {
|
|
128
|
+
expect(anonymousActorInput(input)).toBe("2026-10-31|203.0.113.9|Mozilla/5.0|s");
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test("is `anon:` + 16 hex of sha256, stable within a day and different the next", async () => {
|
|
132
|
+
const today = await anonymousActor(input);
|
|
133
|
+
expect(today).toMatch(/^anon:[0-9a-f]{16}$/);
|
|
134
|
+
expect(await anonymousActor(input)).toBe(today);
|
|
135
|
+
expect(await anonymousActor({ ...input, now: input.now + 86_400_000 })).not.toBe(today);
|
|
136
|
+
expect(await anonymousActor({ ...input, salt: "t" })).not.toBe(today);
|
|
137
|
+
expect(await anonymousActor({ ...input, ip: "203.0.113.10" })).not.toBe(today);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("a missing salt falls back to the local constant — the write still happens", async () => {
|
|
141
|
+
expect(await anonymousActor({ ...input, salt: undefined })).toBe(await anonymousActor({ ...input, salt: LOCAL_EVENTS_SALT }));
|
|
142
|
+
expect(await anonymousActor({ ...input, salt: "" })).toBe(await anonymousActor({ ...input, salt: LOCAL_EVENTS_SALT }));
|
|
143
|
+
expect(ANON_PREFIX).toBe("anon:");
|
|
144
|
+
});
|
|
145
|
+
});
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The user-event data point — the ONE schema every app in every workspace writes to its own
|
|
3
|
+
* `<app>_events` Analytics Engine dataset (the event schema, v1, 2026-10-31). A collector on the
|
|
4
|
+
* Mac reads every dataset through the account's SQL API, so nothing here is read back by an app.
|
|
5
|
+
*
|
|
6
|
+
* 🔴 **The layout is a WIRE FORMAT.** Analytics Engine columns are positional (`blob1`,
|
|
7
|
+
* `double1`, …) and the collector's queries name them by position: append only, never reorder,
|
|
8
|
+
* never repurpose. `point.spec.ts` pins every position.
|
|
9
|
+
*
|
|
10
|
+
* ```
|
|
11
|
+
* index1 = `${kind}:${name}`, ≤96 bytes
|
|
12
|
+
* blob1 = "e1" (schema) blob2 = app blob3 = kind blob4 = name
|
|
13
|
+
* blob5 = place blob6 = actor blob7 = actorKind blob8 = actorLabel
|
|
14
|
+
* blob9 = tenant blob10 = via blob11 = purpose blob12 = device
|
|
15
|
+
* blob13 = country blob14 = outcome blob15 = referrer blob16 = build
|
|
16
|
+
* double1 = 1 (count) double2 = ms double3 = bytes double4 = value
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* Every vocabulary below is CLOSED: the collector groups by these words, and a new one is a
|
|
20
|
+
* schema change for every workspace, not a local choice. Nothing private goes in a blob — no
|
|
21
|
+
* titles, file names, query strings, search terms, raw addresses: a place is a route PATTERN.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export const EVENT_SCHEMA = "e1";
|
|
25
|
+
|
|
26
|
+
export type EventKind = "view" | "action" | "auth" | "storage" | "error";
|
|
27
|
+
export const EVENT_KINDS: readonly EventKind[] = ["view", "action", "auth", "storage", "error"];
|
|
28
|
+
|
|
29
|
+
export type ActorKind = "owner" | "user" | "anon" | "agent" | "smoke" | "bot";
|
|
30
|
+
export const ACTOR_KINDS: readonly ActorKind[] = ["owner", "user", "anon", "agent", "smoke", "bot"];
|
|
31
|
+
|
|
32
|
+
export type EventVia = "web" | "api" | "mcp" | "agent" | "cli" | "cron" | "hook";
|
|
33
|
+
export const EVENT_VIAS: readonly EventVia[] = ["web", "api", "mcp", "agent", "cli", "cron", "hook"];
|
|
34
|
+
|
|
35
|
+
export type EventPurpose =
|
|
36
|
+
| "read"
|
|
37
|
+
| "create"
|
|
38
|
+
| "edit"
|
|
39
|
+
| "organize"
|
|
40
|
+
| "search"
|
|
41
|
+
| "ask"
|
|
42
|
+
| "share"
|
|
43
|
+
| "play"
|
|
44
|
+
| "upload"
|
|
45
|
+
| "download"
|
|
46
|
+
| "account"
|
|
47
|
+
| "admin"
|
|
48
|
+
| "support"
|
|
49
|
+
| "land";
|
|
50
|
+
export const EVENT_PURPOSES: readonly EventPurpose[] = [
|
|
51
|
+
"read",
|
|
52
|
+
"create",
|
|
53
|
+
"edit",
|
|
54
|
+
"organize",
|
|
55
|
+
"search",
|
|
56
|
+
"ask",
|
|
57
|
+
"share",
|
|
58
|
+
"play",
|
|
59
|
+
"upload",
|
|
60
|
+
"download",
|
|
61
|
+
"account",
|
|
62
|
+
"admin",
|
|
63
|
+
"support",
|
|
64
|
+
"land",
|
|
65
|
+
];
|
|
66
|
+
|
|
67
|
+
export type EventDevice = "desktop" | "phone" | "tablet" | "bot" | "other";
|
|
68
|
+
export type EventOutcome = "ok" | "fail" | "refused" | "error";
|
|
69
|
+
|
|
70
|
+
/** One event, fully resolved — what {@link toEventPoint} lays out. `''` means unknown or n/a. */
|
|
71
|
+
export interface EventPoint {
|
|
72
|
+
app: string;
|
|
73
|
+
kind: EventKind;
|
|
74
|
+
name: string;
|
|
75
|
+
place: string;
|
|
76
|
+
actor: string;
|
|
77
|
+
actorKind: ActorKind;
|
|
78
|
+
actorLabel: string;
|
|
79
|
+
tenant: string;
|
|
80
|
+
via: EventVia;
|
|
81
|
+
purpose: EventPurpose;
|
|
82
|
+
device: EventDevice;
|
|
83
|
+
country: string;
|
|
84
|
+
outcome: EventOutcome;
|
|
85
|
+
referrer: string;
|
|
86
|
+
build: string;
|
|
87
|
+
ms: number;
|
|
88
|
+
bytes: number;
|
|
89
|
+
value: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The platform's index limit; a blob is capped well under the 5,120-byte total for 16 of them. */
|
|
93
|
+
const INDEX_MAX_BYTES = 96;
|
|
94
|
+
const BLOB_MAX_BYTES = 256;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Truncate to at most `maxBytes` UTF-8 bytes without splitting a code point — `String.slice`
|
|
98
|
+
* counts UTF-16 units, so a name with one multi-byte character can be ≤96 chars and still exceed
|
|
99
|
+
* the 96-BYTE index limit. (The same rule `metrics/telemetrySink.ts` keeps for its index.)
|
|
100
|
+
*/
|
|
101
|
+
export function truncateUtf8(value: string, maxBytes: number): string {
|
|
102
|
+
const encoded = new TextEncoder().encode(value);
|
|
103
|
+
if (encoded.length <= maxBytes) return value;
|
|
104
|
+
return new TextDecoder("utf-8", { fatal: false }).decode(encoded.subarray(0, maxBytes)).replace(/�+$/, "");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const finite = (value: number | null | undefined): number =>
|
|
108
|
+
typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
109
|
+
|
|
110
|
+
const blob = (value: string | null | undefined): string => truncateUtf8(value ?? "", BLOB_MAX_BYTES);
|
|
111
|
+
|
|
112
|
+
/** The documented layout above, as data. Exported so the spec asserts the wire format itself. */
|
|
113
|
+
export function toEventPoint(event: EventPoint): { indexes: string[]; blobs: string[]; doubles: number[] } {
|
|
114
|
+
const name = blob(event.name);
|
|
115
|
+
return {
|
|
116
|
+
indexes: [truncateUtf8(`${event.kind}:${name}`, INDEX_MAX_BYTES)],
|
|
117
|
+
blobs: [
|
|
118
|
+
EVENT_SCHEMA,
|
|
119
|
+
blob(event.app),
|
|
120
|
+
event.kind,
|
|
121
|
+
name,
|
|
122
|
+
blob(event.place),
|
|
123
|
+
blob(event.actor),
|
|
124
|
+
event.actorKind,
|
|
125
|
+
blob(event.actorLabel),
|
|
126
|
+
blob(event.tenant),
|
|
127
|
+
event.via,
|
|
128
|
+
event.purpose,
|
|
129
|
+
event.device,
|
|
130
|
+
blob(event.country),
|
|
131
|
+
event.outcome,
|
|
132
|
+
blob(event.referrer),
|
|
133
|
+
blob(event.build),
|
|
134
|
+
],
|
|
135
|
+
doubles: [1, finite(event.ms), finite(event.bytes), finite(event.value)],
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The schema's crawler words, matched case-insensitively anywhere in the User-Agent. */
|
|
140
|
+
export const BOT_USER_AGENT_WORDS: readonly string[] = [
|
|
141
|
+
"googlebot",
|
|
142
|
+
"bingbot",
|
|
143
|
+
"bot",
|
|
144
|
+
"crawl",
|
|
145
|
+
"spider",
|
|
146
|
+
"slurp",
|
|
147
|
+
"preview",
|
|
148
|
+
"facebookexternalhit",
|
|
149
|
+
"headless",
|
|
150
|
+
];
|
|
151
|
+
|
|
152
|
+
const BOT_RE = new RegExp(BOT_USER_AGENT_WORDS.join("|"), "i");
|
|
153
|
+
/** A tool, not a browser and not a crawler: the schema's `other` device. */
|
|
154
|
+
const TOOL_RE = /^(curl|wget|bun|node|python|go-http-client|okhttp|java|libwww|httpie)\b|\b(python-requests|undici|axios)\b/i;
|
|
155
|
+
const PHONE_RE = /\b(iphone|ipod|windows phone|mobile)\b/i;
|
|
156
|
+
const TABLET_RE = /\b(ipad|tablet|kindle|silk|playbook)\b/i;
|
|
157
|
+
|
|
158
|
+
export function isBotUserAgent(userAgent: string | null | undefined): boolean {
|
|
159
|
+
return !!userAgent && BOT_RE.test(userAgent);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The schema's device classes, from the User-Agent alone. */
|
|
163
|
+
export function classifyDevice(userAgent: string | null | undefined): EventDevice {
|
|
164
|
+
const ua = (userAgent ?? "").trim();
|
|
165
|
+
if (!ua) return "other";
|
|
166
|
+
if (isBotUserAgent(ua)) return "bot";
|
|
167
|
+
if (TOOL_RE.test(ua)) return "other";
|
|
168
|
+
// An Android tablet says `Android` without `Mobile`; a phone says both — so phones first.
|
|
169
|
+
if (PHONE_RE.test(ua)) return "phone";
|
|
170
|
+
if (TABLET_RE.test(ua) || /\bandroid\b/i.test(ua)) return "tablet";
|
|
171
|
+
if (/\b(mozilla|opera|safari|chrome|firefox|edge)\b/i.test(ua)) return "desktop";
|
|
172
|
+
return "other";
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** `ok` | `fail` (4xx) | `refused` (401/403) | `error` (5xx), from a response status. */
|
|
176
|
+
export function outcomeOf(status: number | null | undefined): EventOutcome {
|
|
177
|
+
if (typeof status !== "number" || !Number.isFinite(status)) return "ok";
|
|
178
|
+
if (status === 401 || status === 403) return "refused";
|
|
179
|
+
if (status >= 500) return "error";
|
|
180
|
+
if (status >= 400) return "fail";
|
|
181
|
+
return "ok";
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The Referer's HOST and nothing else — never a path, never a query. `''` when absent or unparsable. */
|
|
185
|
+
export function referrerHost(referer: string | null | undefined): string {
|
|
186
|
+
if (!referer) return "";
|
|
187
|
+
try {
|
|
188
|
+
return new URL(referer).hostname.toLowerCase();
|
|
189
|
+
} catch {
|
|
190
|
+
return "";
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** `YYYY-MM-DD` in UTC — the day an anonymous actor's hash rotates on. */
|
|
195
|
+
export function utcDay(ms: number): string {
|
|
196
|
+
return new Date(ms).toISOString().slice(0, 10); // tz:utc — the schema's day: the anonymous hash rotates at UTC midnight
|
|
197
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { Hono } from "hono";
|
|
3
|
+
import { actionPurpose, placePurpose } from "../engagement/events.js";
|
|
4
|
+
import type { EventsDataset } from "./sink.js";
|
|
5
|
+
import { createEventSink, recordEvent, requestFacts, resolveActorKind } from "./sink.js";
|
|
6
|
+
import { htmlNavigationOf, recordHtmlView } from "./views.js";
|
|
7
|
+
|
|
8
|
+
type Point = Parameters<EventsDataset["writeDataPoint"]>[0];
|
|
9
|
+
|
|
10
|
+
function fakeDataset(): EventsDataset & { points: Point[] } {
|
|
11
|
+
const points: Point[] = [];
|
|
12
|
+
return {
|
|
13
|
+
points,
|
|
14
|
+
writeDataPoint(point) {
|
|
15
|
+
points.push(point);
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const BROWSER = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 Chrome/120 Safari/537.36";
|
|
21
|
+
|
|
22
|
+
function request(init: { headers?: Record<string, string>; cf?: Record<string, unknown>; method?: string; url?: string } = {}): Request {
|
|
23
|
+
const req = new Request(init.url ?? "https://music.cursedalchemy.com/api/upload", {
|
|
24
|
+
method: init.method ?? "POST",
|
|
25
|
+
headers: { "user-agent": BROWSER, "cf-connecting-ip": "203.0.113.9", ...init.headers },
|
|
26
|
+
});
|
|
27
|
+
if (init.cf) Object.defineProperty(req, "cf", { value: init.cf });
|
|
28
|
+
return req;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Everything the sink defers — a Worker's `ctx.waitUntil` — awaited, so a test sees the write. */
|
|
32
|
+
function deferred(): { defer: (work: Promise<unknown>) => void; settle: () => Promise<void> } {
|
|
33
|
+
const pending: Promise<unknown>[] = [];
|
|
34
|
+
return {
|
|
35
|
+
defer: (work) => {
|
|
36
|
+
pending.push(work);
|
|
37
|
+
},
|
|
38
|
+
settle: async () => {
|
|
39
|
+
await Promise.all(pending);
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
describe("createEventSink", () => {
|
|
45
|
+
test("a known actor writes synchronously, with the request's country, device and outcome", () => {
|
|
46
|
+
const dataset = fakeDataset();
|
|
47
|
+
const sink = createEventSink(dataset, { app: "music", build: "abc1234" });
|
|
48
|
+
sink.record(request({ cf: { country: "US" } }), {
|
|
49
|
+
kind: "action",
|
|
50
|
+
name: "file.upload",
|
|
51
|
+
place: "upload",
|
|
52
|
+
purpose: "upload",
|
|
53
|
+
actor: { id: "someone@example.com", label: "Someone" },
|
|
54
|
+
status: 200,
|
|
55
|
+
ms: 12,
|
|
56
|
+
bytes: 2048,
|
|
57
|
+
});
|
|
58
|
+
expect(dataset.points).toHaveLength(1);
|
|
59
|
+
const [point] = dataset.points;
|
|
60
|
+
expect(point?.indexes).toEqual(["action:file.upload"]);
|
|
61
|
+
expect(point?.blobs).toEqual([
|
|
62
|
+
"e1",
|
|
63
|
+
"music",
|
|
64
|
+
"action",
|
|
65
|
+
"file.upload",
|
|
66
|
+
"upload",
|
|
67
|
+
"someone@example.com",
|
|
68
|
+
"user",
|
|
69
|
+
"Someone",
|
|
70
|
+
"",
|
|
71
|
+
"web",
|
|
72
|
+
"upload",
|
|
73
|
+
"desktop",
|
|
74
|
+
"US",
|
|
75
|
+
"ok",
|
|
76
|
+
"",
|
|
77
|
+
"abc1234",
|
|
78
|
+
]);
|
|
79
|
+
expect(point?.doubles).toEqual([1, 12, 2048, 0]);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("the owner's account is `owner`; a bearer caller says `agent` outright", () => {
|
|
83
|
+
const dataset = fakeDataset();
|
|
84
|
+
const sink = createEventSink(dataset, { app: "family" });
|
|
85
|
+
sink.record(request(), { kind: "action", name: "note.save", purpose: "edit", actor: { id: "owner@example.com", owner: true } });
|
|
86
|
+
sink.record(request(), { kind: "action", name: "tree.read", purpose: "read", via: "api", actor: { id: "photos", kind: "agent" } });
|
|
87
|
+
expect(dataset.points.map((p) => p.blobs?.[6])).toEqual(["owner", "agent"]);
|
|
88
|
+
expect(dataset.points[1]?.blobs?.[9]).toBe("api");
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("an anonymous visitor is hashed off the response path and written when the digest lands", async () => {
|
|
92
|
+
const dataset = fakeDataset();
|
|
93
|
+
const { defer, settle } = deferred();
|
|
94
|
+
const sink = createEventSink(dataset, { app: "patterns", salt: "s", defer });
|
|
95
|
+
sink.record(request({ method: "GET", url: "https://patterns.cursedalchemy.com/", headers: { referer: "https://news.ycombinator.com/item?id=1" } }), {
|
|
96
|
+
kind: "view",
|
|
97
|
+
name: "/",
|
|
98
|
+
place: "/",
|
|
99
|
+
purpose: "land",
|
|
100
|
+
public: true,
|
|
101
|
+
status: 200,
|
|
102
|
+
});
|
|
103
|
+
expect(dataset.points).toHaveLength(0);
|
|
104
|
+
await settle();
|
|
105
|
+
expect(dataset.points).toHaveLength(1);
|
|
106
|
+
const [point] = dataset.points;
|
|
107
|
+
expect(point?.blobs?.[5]).toMatch(/^anon:[0-9a-f]{16}$/);
|
|
108
|
+
expect(point?.blobs?.[6]).toBe("anon");
|
|
109
|
+
expect(point?.blobs?.[7]).toBe("");
|
|
110
|
+
expect(point?.blobs?.[14]).toBe("news.ycombinator.com");
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("the Referer host is recorded for a PUBLIC view only — never behind a session, never for an action", async () => {
|
|
114
|
+
const dataset = fakeDataset();
|
|
115
|
+
const { defer, settle } = deferred();
|
|
116
|
+
const sink = createEventSink(dataset, { app: "patterns", defer });
|
|
117
|
+
const req = request({ method: "GET", headers: { referer: "https://example.com/x" } });
|
|
118
|
+
sink.record(req, { kind: "view", name: "/", purpose: "read", actor: { id: "a@b.c" } });
|
|
119
|
+
sink.record(req, { kind: "action", name: "x", purpose: "edit", public: true });
|
|
120
|
+
await settle();
|
|
121
|
+
expect(dataset.points.map((p) => p.blobs?.[14])).toEqual(["", ""]);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("a crawler is `bot` on both the device and the actorKind", async () => {
|
|
125
|
+
const dataset = fakeDataset();
|
|
126
|
+
const { defer, settle } = deferred();
|
|
127
|
+
createEventSink(dataset, { app: "patterns", defer }).record(request({ headers: { "user-agent": "Mozilla/5.0 (compatible; Googlebot/2.1)" } }), {
|
|
128
|
+
kind: "view",
|
|
129
|
+
name: "/",
|
|
130
|
+
purpose: "land",
|
|
131
|
+
});
|
|
132
|
+
await settle();
|
|
133
|
+
expect(dataset.points[0]?.blobs?.[6]).toBe("bot");
|
|
134
|
+
expect(dataset.points[0]?.blobs?.[11]).toBe("bot");
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test("the stage walk's account and an Access service token are `smoke`, never dropped", () => {
|
|
138
|
+
const dataset = fakeDataset();
|
|
139
|
+
const sink = createEventSink(dataset, { app: "music" });
|
|
140
|
+
sink.record(request(), { kind: "view", name: "home", purpose: "read", actor: { id: "smoke@auth.local" } });
|
|
141
|
+
sink.record(request({ headers: { "cf-access-client-id": "x" } }), { kind: "action", name: "x", purpose: "edit", actor: { id: "a@b.c" } });
|
|
142
|
+
expect(dataset.points.map((p) => p.blobs?.[6])).toEqual(["smoke", "smoke"]);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test("machine traffic with no address and no User-Agent has an empty actor — a gauge from a cron", () => {
|
|
146
|
+
const dataset = fakeDataset();
|
|
147
|
+
createEventSink(dataset, { app: "family" }).record(null, { kind: "storage", name: "bytes", purpose: "upload", via: "cron", bytes: 10, actor: { id: "" } });
|
|
148
|
+
expect(dataset.points[0]?.blobs?.[5]).toBe("");
|
|
149
|
+
expect(dataset.points[0]?.blobs?.[6]).toBe("anon");
|
|
150
|
+
expect(dataset.points[0]?.doubles).toEqual([1, 0, 10, 0]);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test("🔴 a binding that throws never reaches the caller, and no binding is a silent no-op", () => {
|
|
154
|
+
const broken: EventsDataset = {
|
|
155
|
+
writeDataPoint() {
|
|
156
|
+
throw new Error("quota");
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
expect(() => createEventSink(broken, { app: "music" }).record(request(), { kind: "action", name: "x", purpose: "edit", actor: { id: "a" } })).not.toThrow();
|
|
160
|
+
const unbound = createEventSink(undefined, { app: "music" });
|
|
161
|
+
expect(unbound.bound).toBe(false);
|
|
162
|
+
expect(() => unbound.record(request(), { kind: "action", name: "x", purpose: "edit" })).not.toThrow();
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("recordEvent is one point through a throwaway sink", () => {
|
|
166
|
+
const dataset = fakeDataset();
|
|
167
|
+
recordEvent(dataset, request(), { kind: "auth", name: "signin", purpose: "account", actor: { id: "a@b.c" } }, { app: "auth" });
|
|
168
|
+
expect(dataset.points[0]?.indexes).toEqual(["auth:signin"]);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
describe("resolveActorKind — the schema's rule, branch by branch", () => {
|
|
173
|
+
const facts = { userAgent: BROWSER, serviceToken: false };
|
|
174
|
+
const smokeAccounts = ["smoke@auth.local"];
|
|
175
|
+
test.each([
|
|
176
|
+
[{ actor: { id: "a@b.c" }, facts }, "user"],
|
|
177
|
+
[{ actor: { id: "a@b.c", owner: true }, facts }, "owner"],
|
|
178
|
+
[{ actor: null, facts }, "anon"],
|
|
179
|
+
[{ actor: { id: "SMOKE@auth.local" }, facts }, "smoke"],
|
|
180
|
+
[{ actor: { id: "stage-owner@cursedalchemy.com", owner: true }, facts }, "smoke"],
|
|
181
|
+
[{ actor: { id: "Stage-User-12-d2fabd@cursedalchemy.com" }, facts }, "smoke"],
|
|
182
|
+
[{ actor: { id: "stage-owner@example.com", owner: true }, facts }, "owner"],
|
|
183
|
+
[{ actor: { id: "a@b.c" }, facts: { ...facts, serviceToken: true } }, "smoke"],
|
|
184
|
+
[{ actor: { id: "a@b.c" }, facts: { ...facts, userAgent: "bingbot" } }, "bot"],
|
|
185
|
+
[{ actor: { id: "a@b.c", kind: "agent" as const }, facts }, "agent"],
|
|
186
|
+
])("%j → %s", (input, expected) => {
|
|
187
|
+
expect(resolveActorKind({ ...input, smokeAccounts })).toBe(expected);
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
describe("requestFacts", () => {
|
|
192
|
+
test("reads the edge's address first, then the first forwarded hop; country from request.cf", () => {
|
|
193
|
+
const facts = requestFacts(request({ headers: { "x-forwarded-for": "198.51.100.1, 10.0.0.1" }, cf: { country: "DE" } }));
|
|
194
|
+
expect(facts).toEqual({ ip: "203.0.113.9", userAgent: BROWSER, country: "DE", referrer: "", serviceToken: false });
|
|
195
|
+
const hop = new Request("https://x/", { headers: { "x-forwarded-for": "198.51.100.1, 10.0.0.1" } });
|
|
196
|
+
expect(requestFacts(hop).ip).toBe("198.51.100.1");
|
|
197
|
+
expect(requestFacts(null).ip).toBe("");
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
describe("htmlNavigationOf / recordHtmlView — the public-page view", () => {
|
|
202
|
+
const nav = (url: string, init: RequestInit = {}, status = 200) =>
|
|
203
|
+
htmlNavigationOf(new Request(url, { headers: { accept: "text/html,*/*" }, ...init }), status);
|
|
204
|
+
|
|
205
|
+
test("a GET 200 that accepts HTML on a page path is a view; its name is a pattern", () => {
|
|
206
|
+
expect(nav("https://patterns.cursedalchemy.com/")).toEqual({ route: "/" });
|
|
207
|
+
expect(nav("https://patterns.cursedalchemy.com/mandelbrot/deep/zoom")).toEqual({ route: "/mandelbrot" });
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
test("never for /api, /assets, /healthz, a file, a POST, a non-HTML accept or a non-200", () => {
|
|
211
|
+
expect(nav("https://x/api/events")).toBeNull();
|
|
212
|
+
expect(nav("https://x/assets/index-abc.js")).toBeNull();
|
|
213
|
+
expect(nav("https://x/healthz")).toBeNull();
|
|
214
|
+
expect(nav("https://x/favicon.ico")).toBeNull();
|
|
215
|
+
expect(nav("https://x/", { method: "POST" })).toBeNull();
|
|
216
|
+
expect(nav("https://x/", { headers: { accept: "application/json" } })).toBeNull();
|
|
217
|
+
expect(nav("https://x/", {}, 404)).toBeNull();
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
test("recordHtmlView writes a public `view` with the pattern as both name and place", async () => {
|
|
221
|
+
const dataset = fakeDataset();
|
|
222
|
+
const { defer, settle } = deferred();
|
|
223
|
+
const sink = createEventSink(dataset, { app: "patterns", defer });
|
|
224
|
+
const req = new Request("https://patterns.cursedalchemy.com/fractal/x", { headers: { accept: "text/html", "user-agent": BROWSER, referer: "https://t.co/abc" } });
|
|
225
|
+
expect(recordHtmlView(sink, req, 200, { purpose: "land" })).toBe(true);
|
|
226
|
+
expect(recordHtmlView(sink, req, 404, { purpose: "land" })).toBe(false);
|
|
227
|
+
await settle();
|
|
228
|
+
expect(dataset.points).toHaveLength(1);
|
|
229
|
+
expect(dataset.points[0]?.blobs?.slice(2, 5)).toEqual(["view", "/fractal", "/fractal"]);
|
|
230
|
+
expect(dataset.points[0]?.blobs?.[10]).toBe("land");
|
|
231
|
+
expect(dataset.points[0]?.blobs?.[14]).toBe("t.co");
|
|
232
|
+
});
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
describe("the engagement bridge's purposes", () => {
|
|
236
|
+
test("a place: the app's map first, then the schema's defaults, then `read`", () => {
|
|
237
|
+
expect(placePurpose("upload", { upload: "upload" })).toBe("upload");
|
|
238
|
+
expect(placePurpose("sign-in")).toBe("account");
|
|
239
|
+
expect(placePurpose("settings")).toBe("account");
|
|
240
|
+
expect(placePurpose("admin-users")).toBe("admin");
|
|
241
|
+
expect(placePurpose("help")).toBe("support");
|
|
242
|
+
expect(placePurpose("search")).toBe("search");
|
|
243
|
+
expect(placePurpose("timeline")).toBe("read");
|
|
244
|
+
});
|
|
245
|
+
test("an action: the app's map, else `edit`", () => {
|
|
246
|
+
expect(actionPurpose("play", { play: "play" })).toBe("play");
|
|
247
|
+
expect(actionPurpose("like")).toBe("edit");
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
describe("the D1 recorder's dual write", () => {
|
|
252
|
+
test("an accepted view and an accepted action each become one point; a 401 writes nothing", async () => {
|
|
253
|
+
const { createD1EngagementRecorder } = await import("../engagement/d1.js");
|
|
254
|
+
const dataset = fakeDataset();
|
|
255
|
+
const sink = createEventSink(dataset, { app: "music" });
|
|
256
|
+
const statements: string[] = [];
|
|
257
|
+
const stmt = (sql: string) => ({
|
|
258
|
+
bind: () => stmt(sql),
|
|
259
|
+
first: async () => null,
|
|
260
|
+
run: async () => ({}),
|
|
261
|
+
all: async () => ({ results: [] }),
|
|
262
|
+
sql,
|
|
263
|
+
});
|
|
264
|
+
const db = { prepare: (sql: string) => stmt(sql), batch: async (list: unknown[]) => list.map(() => ({})), exec: async () => ({}) };
|
|
265
|
+
const app = new Hono();
|
|
266
|
+
let user: string | null = "someone@example.com";
|
|
267
|
+
app.route(
|
|
268
|
+
"/api/engagement",
|
|
269
|
+
createD1EngagementRecorder({
|
|
270
|
+
db: db as never,
|
|
271
|
+
places: [{ id: "home", label: "" }, { id: "upload", label: "" }],
|
|
272
|
+
actions: [{ id: "play", label: "" }],
|
|
273
|
+
resolveUser: () => user,
|
|
274
|
+
events: { sink, purposes: { upload: "upload" }, actionPurposes: { play: "play" }, actorOf: () => ({ id: "someone@example.com", owner: true }) },
|
|
275
|
+
}),
|
|
276
|
+
);
|
|
277
|
+
const post = (path: string, body: unknown) =>
|
|
278
|
+
app.request(path, { method: "POST", body: JSON.stringify(body), headers: { "content-type": "application/json", "user-agent": BROWSER } });
|
|
279
|
+
expect((await post("/api/engagement/view", { place: "upload" })).status).toBe(200);
|
|
280
|
+
expect((await post("/api/engagement/action", { place: "home", action: "play" })).status).toBe(200);
|
|
281
|
+
user = null;
|
|
282
|
+
expect((await post("/api/engagement/view", { place: "home" })).status).toBe(401);
|
|
283
|
+
expect(dataset.points.map((p) => [p.indexes?.[0], p.blobs?.[4], p.blobs?.[6], p.blobs?.[10]])).toEqual([
|
|
284
|
+
["view:upload", "upload", "owner", "upload"],
|
|
285
|
+
["action:play", "home", "owner", "play"],
|
|
286
|
+
]);
|
|
287
|
+
void statements;
|
|
288
|
+
});
|
|
289
|
+
});
|