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.
Files changed (37) hide show
  1. package/dist/server/engagement/api.d.ts +6 -0
  2. package/dist/server/engagement/api.js +3 -0
  3. package/dist/server/engagement/d1.d.ts +7 -0
  4. package/dist/server/engagement/d1.js +4 -0
  5. package/dist/server/engagement/events.d.ts +26 -0
  6. package/dist/server/engagement/events.js +52 -0
  7. package/dist/server/events/actions.d.ts +46 -0
  8. package/dist/server/events/actions.js +62 -0
  9. package/dist/server/events/actor.d.ts +19 -0
  10. package/dist/server/events/actor.js +30 -0
  11. package/dist/server/events/gauge.d.ts +21 -0
  12. package/dist/server/events/gauge.js +60 -0
  13. package/dist/server/events/index.d.ts +14 -0
  14. package/dist/server/events/index.js +14 -0
  15. package/dist/server/events/point.d.ts +77 -0
  16. package/dist/server/events/point.js +149 -0
  17. package/dist/server/events/sink.d.ts +97 -0
  18. package/dist/server/events/sink.js +113 -0
  19. package/dist/server/events/views.d.ts +24 -0
  20. package/dist/server/events/views.js +41 -0
  21. package/package.json +8 -2
  22. package/src/server/bench/cpuBudget.spec.ts +12 -8
  23. package/src/server/engagement/api.ts +8 -0
  24. package/src/server/engagement/d1.ts +9 -0
  25. package/src/server/engagement/events.ts +79 -0
  26. package/src/server/events/actions.spec.ts +126 -0
  27. package/src/server/events/actions.ts +113 -0
  28. package/src/server/events/actor.ts +34 -0
  29. package/src/server/events/gauge.spec.ts +75 -0
  30. package/src/server/events/gauge.ts +81 -0
  31. package/src/server/events/index.ts +47 -0
  32. package/src/server/events/point.spec.ts +145 -0
  33. package/src/server/events/point.ts +197 -0
  34. package/src/server/events/sink.spec.ts +289 -0
  35. package/src/server/events/sink.ts +221 -0
  36. package/src/server/events/views.ts +62 -0
  37. package/src/server/telemetryIsWorkerSafe.spec.ts +23 -0
@@ -0,0 +1,221 @@
1
+ /**
2
+ * `createEventSink(binding, options)` — the one seam an app records user events through.
3
+ *
4
+ * ```ts
5
+ * const events = createEventSink(env.EVENTS, { app: "music", salt: env.EVENTS_SALT, build: env.MUSIC_BUILD_COMMIT,
6
+ * defer: (work) => ctx.waitUntil(work) });
7
+ * events.record(c.req.raw, { kind: "action", name: "file.upload", place: "upload", purpose: "upload",
8
+ * actor: { id: user.email, owner: user.isOwner }, status: 200, ms, bytes });
9
+ * ```
10
+ *
11
+ * `record` is synchronous, never throws, and is never awaited by a caller: a known actor writes
12
+ * at once; an anonymous one hashes first (Web Crypto is async) and writes when the digest lands,
13
+ * which `defer` (a Worker's `ctx.waitUntil`) keeps alive past the response. A write that fails is
14
+ * counted nowhere else — the schema's "a failure must never reach the user".
15
+ *
16
+ * What the request supplies, and the body never does: the address and User-Agent (the anonymous
17
+ * hash, the device, the bot verdict), `request.cf.country`, the Referer HOST for a public view,
18
+ * and whether an Access service token (`cf-access-client-id`) — a deploy smoke — sent it.
19
+ */
20
+ import type { AnalyticsEngineDataset } from "../metrics/telemetrySink.js";
21
+ import { anonymousActor } from "./actor.js";
22
+ import {
23
+ type ActorKind,
24
+ type EventKind,
25
+ type EventOutcome,
26
+ type EventPoint,
27
+ type EventPurpose,
28
+ type EventVia,
29
+ classifyDevice,
30
+ isBotUserAgent,
31
+ outcomeOf,
32
+ referrerHost,
33
+ toEventPoint,
34
+ } from "./point.js";
35
+
36
+ /** The `EVENTS` binding — the same shape as the `AE` binding `requestLogger` writes to. */
37
+ export type EventsDataset = AnalyticsEngineDataset;
38
+
39
+ /** Who did it, as far as the app knows. Absent or `id: null` → the anonymous hash. */
40
+ export interface EventActor {
41
+ /** The stable id the app already uses for the person — the email `requestLogger` writes. */
42
+ id?: string | null;
43
+ /** Human-readable: the display name or email. Default: the id. */
44
+ label?: string | null;
45
+ /** The app owner's own account (`SsoUser.isOwner`). */
46
+ owner?: boolean;
47
+ /** Said outright — `agent` for a bearer/service token, `smoke` for a deploy identity — else resolved. */
48
+ kind?: ActorKind;
49
+ }
50
+
51
+ export interface EventFields {
52
+ kind: EventKind;
53
+ name: string;
54
+ /** The page/view it happened on (a view's own name for a `view`). */
55
+ place?: string;
56
+ purpose: EventPurpose;
57
+ /** Default `web`. */
58
+ via?: EventVia;
59
+ actor?: EventActor | null;
60
+ tenant?: string;
61
+ /** The response status, read as the outcome (`outcomeOf`) unless `outcome` is given. */
62
+ status?: number;
63
+ outcome?: EventOutcome;
64
+ ms?: number;
65
+ bytes?: number;
66
+ value?: number;
67
+ /** A PUBLIC page's view: the Referer host is recorded. Never for anything behind a session. */
68
+ public?: boolean;
69
+ /** Overrides the sink's build stamp for this one point. */
70
+ build?: string;
71
+ }
72
+
73
+ export interface EventSinkOptions {
74
+ /** The registry id — `music`, `family`, `patterns`. */
75
+ app: string;
76
+ /** `EVENTS_SALT`; absent → `LOCAL_EVENTS_SALT` (local dev), and the write still happens. */
77
+ salt?: string | null;
78
+ /** The deploy's build stamp (`<APP>_BUILD_COMMIT`), for blob16. */
79
+ build?: string | null;
80
+ /** Accounts whose activity is a deploy smoke or stage walk. Default: `smoke@auth.local`. */
81
+ smokeAccounts?: readonly string[];
82
+ /** Keeps the anonymous hash's write alive past the response — a Worker's `ctx.waitUntil`. */
83
+ defer?: (work: Promise<unknown>) => void;
84
+ now?: () => number;
85
+ }
86
+
87
+ export interface EventSink {
88
+ /** False when no binding was passed: every `record` is then a no-op. */
89
+ readonly bound: boolean;
90
+ /** Record one event. Synchronous, never throws, never awaited. */
91
+ record(request: Request | null | undefined, fields: EventFields): void;
92
+ }
93
+
94
+ /** The stage walk's account (`apps/auth-stage/scripts/accessWalk.ts` → `SMOKE_ACCOUNT`). */
95
+ export const DEFAULT_SMOKE_ACCOUNTS: readonly string[] = ["smoke@auth.local"];
96
+
97
+ /**
98
+ * The stage registry's seeded accounts (`apps/auth-stage/scripts/seed.ts`): `stage-owner@` and
99
+ * `stage-user-<i>-<seed>@cursedalchemy.com`, which every app's stage walk signs in as. They exist on
100
+ * no production registry, so a point they make is a walk's — `smoke`, never a person.
101
+ */
102
+ const STAGE_SEED_ACCOUNT = /^stage-(?:owner|user-\d+-[0-9a-f]+)@cursedalchemy\.com$/;
103
+
104
+ /** Is this actor id a deploy smoke's or a stage walk's? `smokeAccounts` adds an app's own. */
105
+ export function isSmokeAccount(id: string, smokeAccounts: readonly string[] = DEFAULT_SMOKE_ACCOUNTS): boolean {
106
+ const lower = id.trim().toLowerCase();
107
+ if (lower === "") return false;
108
+ return STAGE_SEED_ACCOUNT.test(lower) || smokeAccounts.some((account) => account.toLowerCase() === lower);
109
+ }
110
+
111
+ /** What one request says about its sender — everything the point takes from headers. */
112
+ export interface RequestFacts {
113
+ ip: string;
114
+ userAgent: string;
115
+ country: string;
116
+ referrer: string;
117
+ /** An Access service token sent it — the deploy smokes' identity. */
118
+ serviceToken: boolean;
119
+ }
120
+
121
+ export function requestFacts(request: Request | null | undefined): RequestFacts {
122
+ if (!request) return { ip: "", userAgent: "", country: "", referrer: "", serviceToken: false };
123
+ const headers = request.headers;
124
+ const forwarded = headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "";
125
+ const cf = (request as { cf?: { country?: unknown } }).cf;
126
+ return {
127
+ ip: headers.get("cf-connecting-ip")?.trim() || forwarded,
128
+ userAgent: headers.get("user-agent") ?? "",
129
+ country: typeof cf?.country === "string" ? cf.country : "",
130
+ referrer: referrerHost(headers.get("referer")),
131
+ serviceToken: headers.has("cf-access-client-id"),
132
+ };
133
+ }
134
+
135
+ /** The schema's actorKind rule, as one pure decision — `sink.spec.ts` pins each branch. */
136
+ export function resolveActorKind(input: {
137
+ actor: EventActor | null | undefined;
138
+ facts: Pick<RequestFacts, "userAgent" | "serviceToken">;
139
+ smokeAccounts: readonly string[];
140
+ }): ActorKind {
141
+ const { actor, facts } = input;
142
+ if (actor?.kind) return actor.kind;
143
+ const id = actor?.id?.trim().toLowerCase() ?? "";
144
+ if (isSmokeAccount(id, input.smokeAccounts)) return "smoke";
145
+ if (facts.serviceToken) return "smoke";
146
+ if (isBotUserAgent(facts.userAgent)) return "bot";
147
+ if (id) return actor?.owner ? "owner" : "user";
148
+ return "anon";
149
+ }
150
+
151
+ export function createEventSink(binding: EventsDataset | null | undefined, options: EventSinkOptions): EventSink {
152
+ const now = options.now ?? (() => Date.now());
153
+ const smokeAccounts = options.smokeAccounts ?? DEFAULT_SMOKE_ACCOUNTS;
154
+ const build = options.build ?? "";
155
+
156
+ const write = (point: EventPoint): void => {
157
+ try {
158
+ binding?.writeDataPoint(toEventPoint(point));
159
+ } catch (error) {
160
+ console.warn(`[events] a ${point.kind}:${point.name} point was not written: ${String(error)}`);
161
+ }
162
+ };
163
+
164
+ return {
165
+ bound: !!binding,
166
+ record(request, fields) {
167
+ if (!binding) return;
168
+ try {
169
+ const facts = requestFacts(request);
170
+ const actorKind = resolveActorKind({ actor: fields.actor, facts, smokeAccounts });
171
+ const id = fields.actor?.id?.trim() ?? "";
172
+ const base: Omit<EventPoint, "actor"> = {
173
+ app: options.app,
174
+ kind: fields.kind,
175
+ name: fields.name,
176
+ place: fields.place ?? "",
177
+ actorKind,
178
+ actorLabel: id ? (fields.actor?.label ?? id) : "",
179
+ tenant: fields.tenant ?? "",
180
+ via: fields.via ?? "web",
181
+ purpose: fields.purpose,
182
+ device: classifyDevice(facts.userAgent),
183
+ country: facts.country,
184
+ outcome: fields.outcome ?? outcomeOf(fields.status),
185
+ referrer: fields.public && fields.kind === "view" ? facts.referrer : "",
186
+ build: fields.build ?? build,
187
+ ms: fields.ms ?? 0,
188
+ bytes: fields.bytes ?? 0,
189
+ value: fields.value ?? 0,
190
+ };
191
+ if (id) {
192
+ write({ ...base, actor: id });
193
+ return;
194
+ }
195
+ // Machine traffic with no address at all (a cron, a gauge) has no identity to hash.
196
+ if (!facts.ip && !facts.userAgent) {
197
+ write({ ...base, actor: "" });
198
+ return;
199
+ }
200
+ const pending = anonymousActor({ ip: facts.ip, userAgent: facts.userAgent, salt: options.salt, now: now() })
201
+ .then((actor) => write({ ...base, actor }))
202
+ .catch((error: unknown) => {
203
+ console.warn(`[events] a ${fields.kind}:${fields.name} point was not written: ${String(error)}`);
204
+ });
205
+ options.defer?.(pending);
206
+ } catch (error) {
207
+ console.warn(`[events] a ${fields.kind}:${fields.name} point was not written: ${String(error)}`);
208
+ }
209
+ },
210
+ };
211
+ }
212
+
213
+ /** One event through a throwaway sink — for a caller with no sink to keep. */
214
+ export function recordEvent(
215
+ binding: EventsDataset | null | undefined,
216
+ request: Request | null | undefined,
217
+ fields: EventFields,
218
+ options: EventSinkOptions,
219
+ ): void {
220
+ createEventSink(binding, options).record(request, fields);
221
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * A server-side `view` for a public page: the schema's rule for prerendered and shell pages —
3
+ * record in the Worker's fetch path on an HTML navigation (GET, `Accept` includes `text/html`,
4
+ * status 200, not `/assets/*`, not `/api/*`, not `/healthz`, not a file), with the anonymous
5
+ * hashed actor or the session's, and the Referer HOST.
6
+ */
7
+ import type { EventActor, EventFields, EventSink } from "./sink.js";
8
+
9
+ export interface HtmlNavigation {
10
+ /** The route PATTERN recorded as the view's name — never the concrete path. */
11
+ route: string;
12
+ }
13
+
14
+ const NEVER_A_VIEW = /^\/(api\/|assets\/|healthz$|\.well-known\/|_)/;
15
+
16
+ /**
17
+ * The view this request is, or null when it is not an HTML navigation. `routeOf` maps the path to
18
+ * a pattern (`/` → `"/"`, `/docs/abc` → `"/docs/:id"`); the default keeps `/` and collapses every
19
+ * other path to its first segment (`/sign-in/anything` → `/sign-in`).
20
+ */
21
+ export function htmlNavigationOf(
22
+ request: Request,
23
+ status: number,
24
+ routeOf: (pathname: string) => string | null = firstSegment,
25
+ ): HtmlNavigation | null {
26
+ if (request.method !== "GET" || status !== 200) return null;
27
+ if (!(request.headers.get("accept") ?? "").includes("text/html")) return null;
28
+ const pathname = new URL(request.url).pathname;
29
+ if (NEVER_A_VIEW.test(pathname)) return null;
30
+ // A file (`/favicon.ico`, `/manifest.webmanifest`) is never a page.
31
+ if (pathname.slice(pathname.lastIndexOf("/") + 1).includes(".")) return null;
32
+ const route = routeOf(pathname);
33
+ return route ? { route } : null;
34
+ }
35
+
36
+ function firstSegment(pathname: string): string {
37
+ const first = pathname.split("/").filter(Boolean)[0];
38
+ return first ? `/${first}` : "/";
39
+ }
40
+
41
+ /** Record the view an HTML navigation is, when it is one. Returns whether it was. */
42
+ export function recordHtmlView(
43
+ events: EventSink,
44
+ request: Request,
45
+ status: number,
46
+ fields: { purpose: EventFields["purpose"]; actor?: EventActor | null; public?: boolean; tenant?: string },
47
+ routeOf?: (pathname: string) => string | null,
48
+ ): boolean {
49
+ const navigation = htmlNavigationOf(request, status, routeOf);
50
+ if (!navigation) return false;
51
+ events.record(request, {
52
+ kind: "view",
53
+ name: navigation.route,
54
+ place: navigation.route,
55
+ purpose: fields.purpose,
56
+ actor: fields.actor ?? null,
57
+ public: fields.public ?? true,
58
+ ...(fields.tenant ? { tenant: fields.tenant } : {}),
59
+ status,
60
+ });
61
+ return true;
62
+ }
@@ -98,6 +98,26 @@ describe('cursedbelt-server/telemetry', () => {
98
98
  });
99
99
  });
100
100
 
101
+ describe('🔴 cursedbelt-server/events — a Worker writes user events through it', () => {
102
+ test('reaches no `bun:` module at runtime — the sink, the point and the hash are all in the graph', () => {
103
+ const { files, bunImports } = runtimeGraph(join(import.meta.dir, 'events', 'index.ts'));
104
+ expect(bunImports).toEqual([]);
105
+ for (const file of ['events/sink.ts', 'events/point.ts', 'events/actor.ts', 'events/views.ts', 'events/actions.ts', 'events/gauge.ts', 'metrics/normalizeRoute.ts']) {
106
+ expect({ file, reached: files.some((f) => f.endsWith(file)) }).toEqual({ file, reached: true });
107
+ }
108
+ // The sink types its binding from the telemetry sink but never runs it: `metricsBuffer` stays out.
109
+ expect(files.some((f) => f.endsWith('metricsBuffer.ts'))).toBe(false);
110
+ });
111
+
112
+ test("its export map's `import` is the real module, not the Bun-only refusal", () => {
113
+ const pkg = JSON.parse(readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')) as {
114
+ exports: Record<string, { import?: string; source?: string }>;
115
+ };
116
+ expect(pkg.exports['./events']?.import).toBe('./dist/server/events/index.js');
117
+ expect(pkg.exports['./events']?.source).toBe('./src/server/events/index.ts');
118
+ });
119
+ });
120
+
101
121
  describe('🔴 cursedbelt-server/engagement/d1 — a Worker mounts it (task 2096)', () => {
102
122
  test('reaches no `bun:` module at runtime — not the store, not the Bun-only barrel', () => {
103
123
  const { files, bunImports } = runtimeGraph(join(import.meta.dir, 'engagement', 'd1.ts'));
@@ -105,6 +125,9 @@ describe('🔴 cursedbelt-server/engagement/d1 — a Worker mounts it (task 2096
105
125
  // Not vacuous: the policy and the manifest rule are both in the graph, and the store is not.
106
126
  expect(files.some((f) => f.endsWith('engagement/policy.ts'))).toBe(true);
107
127
  expect(files.some((f) => f.endsWith('engagement/manifestPlaces.ts'))).toBe(true);
128
+ // The user-event dual-write (4.60.0) rides along; it only TYPES the sink, so the sink stays out.
129
+ expect(files.some((f) => f.endsWith('engagement/events.ts'))).toBe(true);
130
+ expect(files.some((f) => f.endsWith('events/sink.ts'))).toBe(false);
108
131
  expect(files.some((f) => f.endsWith('engagement/store.ts'))).toBe(false);
109
132
  });
110
133