cursedbelt-server 4.60.0 → 4.61.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/events/actions.d.ts +5 -0
- package/dist/server/events/actions.js +23 -2
- package/dist/server/events/sink.js +7 -1
- package/dist/server/events/views.d.ts +8 -4
- package/dist/server/events/views.js +7 -7
- package/dist/server/metrics/normalizeRoute.d.ts +9 -2
- package/dist/server/metrics/normalizeRoute.js +6 -2
- package/package.json +2 -2
- package/src/server/events/actions.spec.ts +81 -0
- package/src/server/events/actions.ts +37 -2
- package/src/server/events/sink.spec.ts +17 -4
- package/src/server/events/sink.ts +8 -1
- package/src/server/events/views.ts +8 -9
- package/src/server/jobs/polling.spec.ts +1 -1
- package/src/server/metrics/normalizeRoute.spec.ts +19 -0
- package/src/server/metrics/normalizeRoute.ts +18 -4
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
* writes nothing (the requests layer already counts it). A 5xx on a matched rule also writes an
|
|
12
12
|
* `error` point named after the action — "an act that failed in front of the person".
|
|
13
13
|
*
|
|
14
|
+
* 🔴 A gate that answers first leaves no matched route, so the request's own path is matched against
|
|
15
|
+
* the table segment by segment (`:x` is any one segment): the mount's promise, "before the gate, so
|
|
16
|
+
* a refused call is recorded as refused", has to hold for `/api/assets/9/reactions/smile`, not only
|
|
17
|
+
* for an id that happens to look like one (forge task 4250).
|
|
18
|
+
*
|
|
14
19
|
* Only after `next()`: the point carries the response status, the elapsed ms and, when the rule
|
|
15
20
|
* says so, the bytes the request carried (`Content-Length`) or the response sent — never the body.
|
|
16
21
|
*/
|
|
@@ -10,6 +10,26 @@ export function matchServerAction(rules, method, route) {
|
|
|
10
10
|
return rule;
|
|
11
11
|
return null;
|
|
12
12
|
}
|
|
13
|
+
const segmentsOf = (path) => path.split("/").filter(Boolean);
|
|
14
|
+
const isParameter = (segment) => segment.startsWith(":");
|
|
15
|
+
function parseRules(rules) {
|
|
16
|
+
const parsed = rules.map((rule) => {
|
|
17
|
+
const segments = segmentsOf(rule.route);
|
|
18
|
+
return { rule, method: rule.method.toUpperCase(), segments, literals: segments.filter((s) => !isParameter(s)).length };
|
|
19
|
+
});
|
|
20
|
+
return parsed.sort((a, b) => b.literals - a.literals);
|
|
21
|
+
}
|
|
22
|
+
/** The rule a path no handler answered falls under: what `/api/:x/share` would have matched. */
|
|
23
|
+
function ruleOfPath(rules, method, path) {
|
|
24
|
+
const segments = segmentsOf(path);
|
|
25
|
+
for (const { rule, method: ruleMethod, segments: pattern } of rules) {
|
|
26
|
+
if (ruleMethod !== method.toUpperCase() || pattern.length !== segments.length)
|
|
27
|
+
continue;
|
|
28
|
+
if (pattern.every((part, i) => isParameter(part) || part === segments[i]))
|
|
29
|
+
return rule;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
13
33
|
function contentLength(headers) {
|
|
14
34
|
const raw = headers?.get("content-length");
|
|
15
35
|
const n = raw ? Number(raw) : 0;
|
|
@@ -20,14 +40,15 @@ export function serverActions(events, rules, options = {}) {
|
|
|
20
40
|
const index = new Map();
|
|
21
41
|
for (const rule of rules)
|
|
22
42
|
index.set(ruleKey(rule.method, rule.route), rule);
|
|
43
|
+
const parsed = parseRules(rules);
|
|
23
44
|
return async (c, next) => {
|
|
24
45
|
const started = now();
|
|
25
46
|
await next();
|
|
26
47
|
if (!events.bound)
|
|
27
48
|
return;
|
|
28
49
|
try {
|
|
29
|
-
const { method, route } = normalizeRoute(c);
|
|
30
|
-
const rule = index.get(ruleKey(method, route));
|
|
50
|
+
const { method, route, unmatchedPath } = normalizeRoute(c);
|
|
51
|
+
const rule = unmatchedPath === undefined ? index.get(ruleKey(method, route)) : ruleOfPath(parsed, method, unmatchedPath);
|
|
31
52
|
if (!rule)
|
|
32
53
|
return;
|
|
33
54
|
const status = c.res.status;
|
|
@@ -8,6 +8,12 @@ export const DEFAULT_SMOKE_ACCOUNTS = ["smoke@auth.local"];
|
|
|
8
8
|
* no production registry, so a point they make is a walk's — `smoke`, never a person.
|
|
9
9
|
*/
|
|
10
10
|
const STAGE_SEED_ACCOUNT = /^stage-(?:owner|user-\d+-[0-9a-f]+)@cursedalchemy\.com$/;
|
|
11
|
+
/**
|
|
12
|
+
* The User-Agent `cursedops`'s deploy smokes send on every request (`SMOKE_USER_AGENT` there). A
|
|
13
|
+
* production smoke walks the routes signed out, so without this each deploy reads as one more
|
|
14
|
+
* anonymous visitor acting on every route (forge task 4234).
|
|
15
|
+
*/
|
|
16
|
+
const SMOKE_USER_AGENT = /^cursedops-smoke\//i;
|
|
11
17
|
/** Is this actor id a deploy smoke's or a stage walk's? `smokeAccounts` adds an app's own. */
|
|
12
18
|
export function isSmokeAccount(id, smokeAccounts = DEFAULT_SMOKE_ACCOUNTS) {
|
|
13
19
|
const lower = id.trim().toLowerCase();
|
|
@@ -37,7 +43,7 @@ export function resolveActorKind(input) {
|
|
|
37
43
|
const id = actor?.id?.trim().toLowerCase() ?? "";
|
|
38
44
|
if (isSmokeAccount(id, input.smokeAccounts))
|
|
39
45
|
return "smoke";
|
|
40
|
-
if (facts.serviceToken)
|
|
46
|
+
if (facts.serviceToken || SMOKE_USER_AGENT.test(facts.userAgent))
|
|
41
47
|
return "smoke";
|
|
42
48
|
if (isBotUserAgent(facts.userAgent))
|
|
43
49
|
return "bot";
|
|
@@ -11,14 +11,18 @@ export interface HtmlNavigation {
|
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
13
|
* The view this request is, or null when it is not an HTML navigation. `routeOf` maps the path to
|
|
14
|
-
* a pattern (`/` → `"/"`, `/docs/abc` → `"/docs/:id"`)
|
|
15
|
-
*
|
|
14
|
+
* a pattern (`/` → `"/"`, `/docs/abc` → `"/docs/:id"`), or null when the path is no view at all.
|
|
15
|
+
*
|
|
16
|
+
* 🔴 It is required, and it must be a CLOSED list: a SPA's shell answers 200 for every path, so
|
|
17
|
+
* anything derived from the path itself lets a scanner's `/wp-admin` (or a private word in a typed
|
|
18
|
+
* URL) become an `index1` value and a place on the Users page (forge task 4251). A path the app does
|
|
19
|
+
* not know maps to one word.
|
|
16
20
|
*/
|
|
17
|
-
export declare function htmlNavigationOf(request: Request, status: number, routeOf
|
|
21
|
+
export declare function htmlNavigationOf(request: Request, status: number, routeOf: (pathname: string) => string | null): HtmlNavigation | null;
|
|
18
22
|
/** Record the view an HTML navigation is, when it is one. Returns whether it was. */
|
|
19
23
|
export declare function recordHtmlView(events: EventSink, request: Request, status: number, fields: {
|
|
20
24
|
purpose: EventFields["purpose"];
|
|
21
25
|
actor?: EventActor | null;
|
|
22
26
|
public?: boolean;
|
|
23
27
|
tenant?: string;
|
|
24
|
-
}, routeOf
|
|
28
|
+
}, routeOf: (pathname: string) => string | null): boolean;
|
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
const NEVER_A_VIEW = /^\/(api\/|assets\/|healthz$|\.well-known\/|_)/;
|
|
2
2
|
/**
|
|
3
3
|
* The view this request is, or null when it is not an HTML navigation. `routeOf` maps the path to
|
|
4
|
-
* a pattern (`/` → `"/"`, `/docs/abc` → `"/docs/:id"`)
|
|
5
|
-
*
|
|
4
|
+
* a pattern (`/` → `"/"`, `/docs/abc` → `"/docs/:id"`), or null when the path is no view at all.
|
|
5
|
+
*
|
|
6
|
+
* 🔴 It is required, and it must be a CLOSED list: a SPA's shell answers 200 for every path, so
|
|
7
|
+
* anything derived from the path itself lets a scanner's `/wp-admin` (or a private word in a typed
|
|
8
|
+
* URL) become an `index1` value and a place on the Users page (forge task 4251). A path the app does
|
|
9
|
+
* not know maps to one word.
|
|
6
10
|
*/
|
|
7
|
-
export function htmlNavigationOf(request, status, routeOf
|
|
11
|
+
export function htmlNavigationOf(request, status, routeOf) {
|
|
8
12
|
if (request.method !== "GET" || status !== 200)
|
|
9
13
|
return null;
|
|
10
14
|
if (!(request.headers.get("accept") ?? "").includes("text/html"))
|
|
@@ -18,10 +22,6 @@ export function htmlNavigationOf(request, status, routeOf = firstSegment) {
|
|
|
18
22
|
const route = routeOf(pathname);
|
|
19
23
|
return route ? { route } : null;
|
|
20
24
|
}
|
|
21
|
-
function firstSegment(pathname) {
|
|
22
|
-
const first = pathname.split("/").filter(Boolean)[0];
|
|
23
|
-
return first ? `/${first}` : "/";
|
|
24
|
-
}
|
|
25
25
|
/** Record the view an HTML navigation is, when it is one. Returns whether it was. */
|
|
26
26
|
export function recordHtmlView(events, request, status, fields, routeOf) {
|
|
27
27
|
const navigation = htmlNavigationOf(request, status, routeOf);
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
|
-
export
|
|
2
|
+
export interface NormalizedRoute {
|
|
3
3
|
method: string;
|
|
4
4
|
route: string;
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The request's own path (a ctgr twin undone) when `route` is NOT a matched pattern: a gate
|
|
7
|
+
* answered before any handler ran, or nothing was found. Absent when `route` is the real pattern.
|
|
8
|
+
* High cardinality, and it can hold an id: for matching against known routes, never for a label.
|
|
9
|
+
*/
|
|
10
|
+
unmatchedPath?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function normalizeRoute(c: Context): NormalizedRoute;
|
|
@@ -46,13 +46,17 @@ export function normalizeRoute(c) {
|
|
|
46
46
|
catch {
|
|
47
47
|
matched = undefined;
|
|
48
48
|
}
|
|
49
|
-
|
|
49
|
+
const pattern = matched && !matched.includes('*') ? matched : undefined;
|
|
50
|
+
const path = c.req.path.split('?')[0];
|
|
51
|
+
let route = pattern ?? (collapsePath(path) || '/');
|
|
52
|
+
let unmatchedPath = pattern ? undefined : path;
|
|
50
53
|
// Map a ctgr GET-twin back to its real verb + url:
|
|
51
54
|
// /api/ctgrch/notes/:id → PATCH /api/notes/:id
|
|
52
55
|
const ctgr = route.match(/\/ctgr([a-z]{2})(?=\/|$)/i);
|
|
53
56
|
if (ctgr) {
|
|
54
57
|
method = CTGR_METHOD[ctgr[1].toLowerCase()] ?? method;
|
|
55
58
|
route = route.replace(/\/ctgr[a-z]{2}/i, '') || '/';
|
|
59
|
+
unmatchedPath = unmatchedPath?.replace(/\/ctgr[a-z]{2}/i, '') || unmatchedPath;
|
|
56
60
|
}
|
|
57
|
-
return { method, route };
|
|
61
|
+
return { method, route, ...(unmatchedPath === undefined ? {} : { unmatchedPath }) };
|
|
58
62
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursedbelt-server",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.61.0",
|
|
4
4
|
"license": "ISC",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
|
|
@@ -423,7 +423,7 @@
|
|
|
423
423
|
"@node-rs/argon2": "^2.0.2",
|
|
424
424
|
"@types/bun": "^1.3.14",
|
|
425
425
|
"@types/node": "^24",
|
|
426
|
-
"cursedbelt": "^5.
|
|
426
|
+
"cursedbelt": "^5.108.0",
|
|
427
427
|
"hono": "4.12.28",
|
|
428
428
|
"kysely": "^0.28.17",
|
|
429
429
|
"kysely-bun-sqlite": "^0.4.0",
|
|
@@ -30,6 +30,8 @@ function harness(status = 200) {
|
|
|
30
30
|
app.use(
|
|
31
31
|
"/api/*",
|
|
32
32
|
serverActions(events, RULES, {
|
|
33
|
+
// Its own clock, or `ms` is the real one: 1 instead of 0 on a loaded Mac.
|
|
34
|
+
now: () => 1_000,
|
|
33
35
|
actorOf: () => ({ id: "curt@example.com", label: "Curt", owner: true }),
|
|
34
36
|
valueFor: (_c, rule) => (rule.name === "search" ? 12 : undefined),
|
|
35
37
|
}),
|
|
@@ -119,6 +121,85 @@ describe("serverActions — the API seam that names a state-changing act", () =>
|
|
|
119
121
|
expect(res.status).toBe(200);
|
|
120
122
|
});
|
|
121
123
|
|
|
124
|
+
describe("a gate that answers first, so no handler ran and the route is the mount's wildcard", () => {
|
|
125
|
+
const GATED: ServerActionRule[] = [
|
|
126
|
+
{ method: "POST", route: "/api/lists/:kind/:id", name: "list.add", purpose: "organize" },
|
|
127
|
+
{ method: "PUT", route: "/api/assets/:id/reactions/:emoji", name: "asset.react", purpose: "edit" },
|
|
128
|
+
{ method: "POST", route: "/api/items/:id/share", name: "share", purpose: "share" },
|
|
129
|
+
{ method: "POST", route: "/api/items/:id/:verb", name: "item.act", purpose: "edit" },
|
|
130
|
+
{ method: "POST", route: "/api/items/bulk/share", name: "share.bulk", purpose: "share" },
|
|
131
|
+
{ method: "DELETE", route: "/api/playlists/:id", name: "playlist.delete", purpose: "organize" },
|
|
132
|
+
{ method: "POST", route: "/api/settings/a-literal-word-of-more-than-24-chars", name: "settings", purpose: "edit" },
|
|
133
|
+
];
|
|
134
|
+
|
|
135
|
+
function refused(status = 401) {
|
|
136
|
+
const dataset = fakeDataset();
|
|
137
|
+
const events = createEventSink(dataset, { app: "lists" });
|
|
138
|
+
const app = new Hono();
|
|
139
|
+
// A known actor writes at once; the anonymous hash would make every assertion wait on Web Crypto.
|
|
140
|
+
app.use("/api/*", serverActions(events, GATED, { actorOf: () => ({ id: "curt@example.com" }) }));
|
|
141
|
+
app.use("/api/*", async (c) => c.json({ error: "sign in" }, status as 401));
|
|
142
|
+
return {
|
|
143
|
+
names: () => dataset.points.map((p) => [p.blobs?.[3], p.blobs?.[13]]),
|
|
144
|
+
blobs: () => JSON.stringify(dataset.points),
|
|
145
|
+
send: (method: string, path: string) => app.request(`https://x.test${path}`, { method, headers: { "user-agent": BROWSER } }),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
test.each([
|
|
150
|
+
["POST", "/api/lists/fav/my-slug", "list.add"],
|
|
151
|
+
["PUT", "/api/assets/123/reactions/smile", "asset.react"],
|
|
152
|
+
["POST", "/api/items/my-slug/share", "share"],
|
|
153
|
+
["POST", "/api/items/123/share", "share"],
|
|
154
|
+
])("%s %s is recorded as refused", async (method, path, name) => {
|
|
155
|
+
const { names, send } = refused();
|
|
156
|
+
expect((await send(method, path)).status).toBe(401);
|
|
157
|
+
expect(names()).toEqual([[name, "refused"]]);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("a route pattern, never the path: the slug is in no blob", async () => {
|
|
161
|
+
const { blobs, send } = refused();
|
|
162
|
+
await send("POST", "/api/lists/fav/my-slug");
|
|
163
|
+
expect(blobs()).not.toContain("my-slug");
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test("the most specific rule answers a path two can match, whatever the table's order", async () => {
|
|
167
|
+
const { names, send } = refused();
|
|
168
|
+
await send("POST", "/api/items/bulk/share");
|
|
169
|
+
expect(names()).toEqual([["share.bulk", "refused"]]);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("a word the collapse would turn into :id still matches its literal rule", async () => {
|
|
173
|
+
const { names, send } = refused();
|
|
174
|
+
await send("POST", "/api/settings/a-literal-word-of-more-than-24-chars");
|
|
175
|
+
expect(names()).toEqual([["settings", "refused"]]);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
test("a ctgr GET-twin refused by the gate counts as its real verb", async () => {
|
|
179
|
+
const { names, send } = refused();
|
|
180
|
+
await send("GET", "/api/ctgrte/playlists/my-mix");
|
|
181
|
+
expect(names()).toEqual([["playlist.delete", "refused"]]);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test("a path of no rule's shape, or the wrong verb for one, still writes nothing", async () => {
|
|
185
|
+
const { names, send } = refused();
|
|
186
|
+
await send("GET", "/api/items/my-slug/share");
|
|
187
|
+
await send("POST", "/api/items/my-slug");
|
|
188
|
+
await send("POST", "/api/lists/fav/my-slug/extra");
|
|
189
|
+
expect(names()).toEqual([]);
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test("a handler that ran is matched by its pattern alone: a same-shaped path under another route writes nothing", async () => {
|
|
194
|
+
const dataset = fakeDataset();
|
|
195
|
+
const events = createEventSink(dataset, { app: "lists" });
|
|
196
|
+
const app = new Hono();
|
|
197
|
+
app.use("/api/*", serverActions(events, [{ method: "POST", route: "/api/items/:id/share", name: "share", purpose: "share" }], { actorOf: () => ({ id: "curt@example.com" }) }));
|
|
198
|
+
app.post("/api/items/bulk/share", (c) => c.text("ok"));
|
|
199
|
+
await app.request("https://x.test/api/items/bulk/share", { method: "POST", headers: { "user-agent": BROWSER } });
|
|
200
|
+
expect(dataset.points).toHaveLength(0);
|
|
201
|
+
});
|
|
202
|
+
|
|
122
203
|
test("matchServerAction is case-insensitive on the method and exact on the pattern", () => {
|
|
123
204
|
expect(matchServerAction(RULES, "post", "/api/upload")?.name).toBe("file.upload");
|
|
124
205
|
expect(matchServerAction(RULES, "POST", "/api/upload/")).toBeNull();
|
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
* writes nothing (the requests layer already counts it). A 5xx on a matched rule also writes an
|
|
12
12
|
* `error` point named after the action — "an act that failed in front of the person".
|
|
13
13
|
*
|
|
14
|
+
* 🔴 A gate that answers first leaves no matched route, so the request's own path is matched against
|
|
15
|
+
* the table segment by segment (`:x` is any one segment): the mount's promise, "before the gate, so
|
|
16
|
+
* a refused call is recorded as refused", has to hold for `/api/assets/9/reactions/smile`, not only
|
|
17
|
+
* for an id that happens to look like one (forge task 4250).
|
|
18
|
+
*
|
|
14
19
|
* Only after `next()`: the point carries the response status, the elapsed ms and, when the rule
|
|
15
20
|
* says so, the bytes the request carried (`Content-Length`) or the response sent — never the body.
|
|
16
21
|
*/
|
|
@@ -60,6 +65,35 @@ export function matchServerAction(
|
|
|
60
65
|
return null;
|
|
61
66
|
}
|
|
62
67
|
|
|
68
|
+
interface ParsedRule {
|
|
69
|
+
rule: ServerActionRule;
|
|
70
|
+
method: string;
|
|
71
|
+
segments: string[];
|
|
72
|
+
/** How many segments are words, not parameters: the most specific rule answers a path two can match. */
|
|
73
|
+
literals: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const segmentsOf = (path: string): string[] => path.split("/").filter(Boolean);
|
|
77
|
+
const isParameter = (segment: string): boolean => segment.startsWith(":");
|
|
78
|
+
|
|
79
|
+
function parseRules(rules: readonly ServerActionRule[]): ParsedRule[] {
|
|
80
|
+
const parsed = rules.map((rule) => {
|
|
81
|
+
const segments = segmentsOf(rule.route);
|
|
82
|
+
return { rule, method: rule.method.toUpperCase(), segments, literals: segments.filter((s) => !isParameter(s)).length };
|
|
83
|
+
});
|
|
84
|
+
return parsed.sort((a, b) => b.literals - a.literals);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The rule a path no handler answered falls under: what `/api/:x/share` would have matched. */
|
|
88
|
+
function ruleOfPath(rules: readonly ParsedRule[], method: string, path: string): ServerActionRule | null {
|
|
89
|
+
const segments = segmentsOf(path);
|
|
90
|
+
for (const { rule, method: ruleMethod, segments: pattern } of rules) {
|
|
91
|
+
if (ruleMethod !== method.toUpperCase() || pattern.length !== segments.length) continue;
|
|
92
|
+
if (pattern.every((part, i) => isParameter(part) || part === segments[i])) return rule;
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
63
97
|
function contentLength(headers: Headers | undefined): number {
|
|
64
98
|
const raw = headers?.get("content-length");
|
|
65
99
|
const n = raw ? Number(raw) : 0;
|
|
@@ -74,13 +108,14 @@ export function serverActions(
|
|
|
74
108
|
const now = options.now ?? (() => Date.now());
|
|
75
109
|
const index = new Map<string, ServerActionRule>();
|
|
76
110
|
for (const rule of rules) index.set(ruleKey(rule.method, rule.route), rule);
|
|
111
|
+
const parsed = parseRules(rules);
|
|
77
112
|
return async (c, next) => {
|
|
78
113
|
const started = now();
|
|
79
114
|
await next();
|
|
80
115
|
if (!events.bound) return;
|
|
81
116
|
try {
|
|
82
|
-
const { method, route } = normalizeRoute(c);
|
|
83
|
-
const rule = index.get(ruleKey(method, route));
|
|
117
|
+
const { method, route, unmatchedPath } = normalizeRoute(c);
|
|
118
|
+
const rule = unmatchedPath === undefined ? index.get(ruleKey(method, route)) : ruleOfPath(parsed, method, unmatchedPath);
|
|
84
119
|
if (!rule) return;
|
|
85
120
|
const status = c.res.status;
|
|
86
121
|
const ms = Math.max(0, now() - started);
|
|
@@ -181,6 +181,8 @@ describe("resolveActorKind — the schema's rule, branch by branch", () => {
|
|
|
181
181
|
[{ actor: { id: "Stage-User-12-d2fabd@cursedalchemy.com" }, facts }, "smoke"],
|
|
182
182
|
[{ actor: { id: "stage-owner@example.com", owner: true }, facts }, "owner"],
|
|
183
183
|
[{ actor: { id: "a@b.c" }, facts: { ...facts, serviceToken: true } }, "smoke"],
|
|
184
|
+
[{ actor: null, facts: { ...facts, userAgent: "cursedops-smoke/1" } }, "smoke"],
|
|
185
|
+
[{ actor: null, facts: { ...facts, userAgent: "curl/8.7.1" } }, "anon"],
|
|
184
186
|
[{ actor: { id: "a@b.c" }, facts: { ...facts, userAgent: "bingbot" } }, "bot"],
|
|
185
187
|
[{ actor: { id: "a@b.c", kind: "agent" as const }, facts }, "agent"],
|
|
186
188
|
])("%j → %s", (input, expected) => {
|
|
@@ -199,12 +201,23 @@ describe("requestFacts", () => {
|
|
|
199
201
|
});
|
|
200
202
|
|
|
201
203
|
describe("htmlNavigationOf / recordHtmlView — the public-page view", () => {
|
|
204
|
+
/** The closed list an app hands in: `/fractal/…` is a page, anything else is no page of its. */
|
|
205
|
+
const routeOf = (pathname: string) => (pathname.startsWith("/fractal") ? "/fractal" : pathname === "/" ? "/" : "/unlisted");
|
|
202
206
|
const nav = (url: string, init: RequestInit = {}, status = 200) =>
|
|
203
|
-
htmlNavigationOf(new Request(url, { headers: { accept: "text/html,*/*" }, ...init }), status);
|
|
207
|
+
htmlNavigationOf(new Request(url, { headers: { accept: "text/html,*/*" }, ...init }), status, routeOf);
|
|
204
208
|
|
|
205
209
|
test("a GET 200 that accepts HTML on a page path is a view; its name is a pattern", () => {
|
|
206
210
|
expect(nav("https://patterns.cursedalchemy.com/")).toEqual({ route: "/" });
|
|
207
|
-
expect(nav("https://patterns.cursedalchemy.com/
|
|
211
|
+
expect(nav("https://patterns.cursedalchemy.com/fractal/deep/zoom")).toEqual({ route: "/fractal" });
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
test("the name comes from the app's list, never from the path: a scanner's path is one word", () => {
|
|
215
|
+
expect(nav("https://patterns.cursedalchemy.com/wp-admin")).toEqual({ route: "/unlisted" });
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("a routeOf that answers null writes no view", () => {
|
|
219
|
+
const req = new Request("https://x/", { headers: { accept: "text/html" } });
|
|
220
|
+
expect(htmlNavigationOf(req, 200, () => null)).toBeNull();
|
|
208
221
|
});
|
|
209
222
|
|
|
210
223
|
test("never for /api, /assets, /healthz, a file, a POST, a non-HTML accept or a non-200", () => {
|
|
@@ -222,8 +235,8 @@ describe("htmlNavigationOf / recordHtmlView — the public-page view", () => {
|
|
|
222
235
|
const { defer, settle } = deferred();
|
|
223
236
|
const sink = createEventSink(dataset, { app: "patterns", defer });
|
|
224
237
|
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);
|
|
238
|
+
expect(recordHtmlView(sink, req, 200, { purpose: "land" }, routeOf)).toBe(true);
|
|
239
|
+
expect(recordHtmlView(sink, req, 404, { purpose: "land" }, routeOf)).toBe(false);
|
|
227
240
|
await settle();
|
|
228
241
|
expect(dataset.points).toHaveLength(1);
|
|
229
242
|
expect(dataset.points[0]?.blobs?.slice(2, 5)).toEqual(["view", "/fractal", "/fractal"]);
|
|
@@ -101,6 +101,13 @@ export const DEFAULT_SMOKE_ACCOUNTS: readonly string[] = ["smoke@auth.local"];
|
|
|
101
101
|
*/
|
|
102
102
|
const STAGE_SEED_ACCOUNT = /^stage-(?:owner|user-\d+-[0-9a-f]+)@cursedalchemy\.com$/;
|
|
103
103
|
|
|
104
|
+
/**
|
|
105
|
+
* The User-Agent `cursedops`'s deploy smokes send on every request (`SMOKE_USER_AGENT` there). A
|
|
106
|
+
* production smoke walks the routes signed out, so without this each deploy reads as one more
|
|
107
|
+
* anonymous visitor acting on every route (forge task 4234).
|
|
108
|
+
*/
|
|
109
|
+
const SMOKE_USER_AGENT = /^cursedops-smoke\//i;
|
|
110
|
+
|
|
104
111
|
/** Is this actor id a deploy smoke's or a stage walk's? `smokeAccounts` adds an app's own. */
|
|
105
112
|
export function isSmokeAccount(id: string, smokeAccounts: readonly string[] = DEFAULT_SMOKE_ACCOUNTS): boolean {
|
|
106
113
|
const lower = id.trim().toLowerCase();
|
|
@@ -142,7 +149,7 @@ export function resolveActorKind(input: {
|
|
|
142
149
|
if (actor?.kind) return actor.kind;
|
|
143
150
|
const id = actor?.id?.trim().toLowerCase() ?? "";
|
|
144
151
|
if (isSmokeAccount(id, input.smokeAccounts)) return "smoke";
|
|
145
|
-
if (facts.serviceToken) return "smoke";
|
|
152
|
+
if (facts.serviceToken || SMOKE_USER_AGENT.test(facts.userAgent)) return "smoke";
|
|
146
153
|
if (isBotUserAgent(facts.userAgent)) return "bot";
|
|
147
154
|
if (id) return actor?.owner ? "owner" : "user";
|
|
148
155
|
return "anon";
|
|
@@ -15,13 +15,17 @@ const NEVER_A_VIEW = /^\/(api\/|assets\/|healthz$|\.well-known\/|_)/;
|
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
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"`)
|
|
19
|
-
*
|
|
18
|
+
* a pattern (`/` → `"/"`, `/docs/abc` → `"/docs/:id"`), or null when the path is no view at all.
|
|
19
|
+
*
|
|
20
|
+
* 🔴 It is required, and it must be a CLOSED list: a SPA's shell answers 200 for every path, so
|
|
21
|
+
* anything derived from the path itself lets a scanner's `/wp-admin` (or a private word in a typed
|
|
22
|
+
* URL) become an `index1` value and a place on the Users page (forge task 4251). A path the app does
|
|
23
|
+
* not know maps to one word.
|
|
20
24
|
*/
|
|
21
25
|
export function htmlNavigationOf(
|
|
22
26
|
request: Request,
|
|
23
27
|
status: number,
|
|
24
|
-
routeOf: (pathname: string) => string | null
|
|
28
|
+
routeOf: (pathname: string) => string | null,
|
|
25
29
|
): HtmlNavigation | null {
|
|
26
30
|
if (request.method !== "GET" || status !== 200) return null;
|
|
27
31
|
if (!(request.headers.get("accept") ?? "").includes("text/html")) return null;
|
|
@@ -33,18 +37,13 @@ export function htmlNavigationOf(
|
|
|
33
37
|
return route ? { route } : null;
|
|
34
38
|
}
|
|
35
39
|
|
|
36
|
-
function firstSegment(pathname: string): string {
|
|
37
|
-
const first = pathname.split("/").filter(Boolean)[0];
|
|
38
|
-
return first ? `/${first}` : "/";
|
|
39
|
-
}
|
|
40
|
-
|
|
41
40
|
/** Record the view an HTML navigation is, when it is one. Returns whether it was. */
|
|
42
41
|
export function recordHtmlView(
|
|
43
42
|
events: EventSink,
|
|
44
43
|
request: Request,
|
|
45
44
|
status: number,
|
|
46
45
|
fields: { purpose: EventFields["purpose"]; actor?: EventActor | null; public?: boolean; tenant?: string },
|
|
47
|
-
routeOf
|
|
46
|
+
routeOf: (pathname: string) => string | null,
|
|
48
47
|
): boolean {
|
|
49
48
|
const navigation = htmlNavigationOf(request, status, routeOf);
|
|
50
49
|
if (!navigation) return false;
|
|
@@ -40,6 +40,25 @@ describe('normalizeRoute', () => {
|
|
|
40
40
|
expect(label).toBe('GET /u/:id/blob/:id');
|
|
41
41
|
});
|
|
42
42
|
|
|
43
|
+
test('says the raw path only when the route is not a real pattern, ctgr twin undone', async () => {
|
|
44
|
+
const seen: Array<string | undefined> = [];
|
|
45
|
+
const app = new Hono();
|
|
46
|
+
const gate = (c: import('hono').Context) => {
|
|
47
|
+
seen.push(normalizeRoute(c).unmatchedPath);
|
|
48
|
+
return c.text('');
|
|
49
|
+
};
|
|
50
|
+
app.get('/api/notes/:id', gate);
|
|
51
|
+
app.use('/api/*', async (c, next) => {
|
|
52
|
+
await next();
|
|
53
|
+
if (c.req.path.includes('gated')) seen.push(normalizeRoute(c).unmatchedPath);
|
|
54
|
+
});
|
|
55
|
+
app.use('/api/*', async (c, next) => (c.req.path.includes('gated') ? c.text('no', 401) : next()));
|
|
56
|
+
await app.request('http://x/api/notes/n1');
|
|
57
|
+
await app.request('http://x/api/gated/my-slug');
|
|
58
|
+
await app.request('http://x/api/ctgrte/gated/my-slug');
|
|
59
|
+
expect(seen).toEqual([undefined, '/api/gated/my-slug', '/api/gated/my-slug']);
|
|
60
|
+
});
|
|
61
|
+
|
|
43
62
|
test('maps a ctgr GET-twin back to its real verb + path', async () => {
|
|
44
63
|
const label = await labelFor(
|
|
45
64
|
(app) => app.get('/api/ctgrch/notes/:id', probe),
|
|
@@ -35,7 +35,18 @@ function collapsePath(path: string): string {
|
|
|
35
35
|
return `/${parts.join('/')}`;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
export
|
|
38
|
+
export interface NormalizedRoute {
|
|
39
|
+
method: string;
|
|
40
|
+
route: string;
|
|
41
|
+
/**
|
|
42
|
+
* The request's own path (a ctgr twin undone) when `route` is NOT a matched pattern: a gate
|
|
43
|
+
* answered before any handler ran, or nothing was found. Absent when `route` is the real pattern.
|
|
44
|
+
* High cardinality, and it can hold an id: for matching against known routes, never for a label.
|
|
45
|
+
*/
|
|
46
|
+
unmatchedPath?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function normalizeRoute(c: Context): NormalizedRoute {
|
|
39
50
|
let method = c.req.method;
|
|
40
51
|
|
|
41
52
|
// Hono's matched route pattern (with :params) is the ideal label. A wildcard
|
|
@@ -48,8 +59,10 @@ export function normalizeRoute(c: Context): { method: string; route: string } {
|
|
|
48
59
|
} catch {
|
|
49
60
|
matched = undefined;
|
|
50
61
|
}
|
|
51
|
-
|
|
52
|
-
|
|
62
|
+
const pattern = matched && !matched.includes('*') ? matched : undefined;
|
|
63
|
+
const path = c.req.path.split('?')[0];
|
|
64
|
+
let route = pattern ?? (collapsePath(path) || '/');
|
|
65
|
+
let unmatchedPath = pattern ? undefined : path;
|
|
53
66
|
|
|
54
67
|
// Map a ctgr GET-twin back to its real verb + url:
|
|
55
68
|
// /api/ctgrch/notes/:id → PATCH /api/notes/:id
|
|
@@ -57,7 +70,8 @@ export function normalizeRoute(c: Context): { method: string; route: string } {
|
|
|
57
70
|
if (ctgr) {
|
|
58
71
|
method = CTGR_METHOD[ctgr[1].toLowerCase()] ?? method;
|
|
59
72
|
route = route.replace(/\/ctgr[a-z]{2}/i, '') || '/';
|
|
73
|
+
unmatchedPath = unmatchedPath?.replace(/\/ctgr[a-z]{2}/i, '') || unmatchedPath;
|
|
60
74
|
}
|
|
61
75
|
|
|
62
|
-
return { method, route };
|
|
76
|
+
return { method, route, ...(unmatchedPath === undefined ? {} : { unmatchedPath }) };
|
|
63
77
|
}
|