mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 08:47:02 +01:00
* refactor(ai): one reader for a model's JSON answer, not four that disagree
`extractJson` existed four times with three different algorithms, and which
copy a caller reached for decided which model quirks it survived:
digest-producer sliced first `{` to last `}` and never returned null;
frontier/digest handled code fences but not `</think>` leaks; dod-gate handled
`</think>` but not fences (its own comment called itself "a third hand-rolled
copy"); only frontier/propose did both. `parseModelJson` was a fifth and sixth
copy in project-brief and business-plan.
src/lib/ai/model-json.ts is the union of what each knew — strip reasoning,
unwrap a fence (unless the fence holds something else, like a shell snippet),
then scan for the first BALANCED object. The scan is now string-aware, which
fixes a bug every copy shared: a `}` inside a string value closed the object
early, so a DoD verdict whose gap text quoted a brace was silently read as
"met" — the judge's actual answer thrown away by its own reader. A
trailing-comma repair runs only after a strict parse has already failed, so it
can never change the reading of valid JSON.
scripts/test/model-json.ts pins the real shape each of the six callers feeds
it, plus the truncated reply that propose.ts's salvage path depends on
returning null.
Also: `sleep` was defined three times. src/lib/async.ts serves the app and
desktop (which resolves `@/*` to ../src). bridge keeps its own with a comment
saying why — its tsconfig pins `rootDir: "src"`, so nothing outside that
directory can compile into it.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(api): one rate limiter and one JSON POST wrapper
The PIN route kept its own attempts Map beside lib/rate-limit — a second
limiter with the unbounded growth limitkit's bounded store exists to prevent,
and untested, which for a limiter is indistinguishable from one that always
returns true. It now calls checkRateLimit; the 5-per-minute-per-user VALUES
stay in the route, which is the part that is its business.
scripts/test/rate-limit.ts pins both halves. The second half is the one that
matters: getClientIp must read the LAST X-Forwarded-For hop. Six sibling repos
shipped the first-hop version, where the client writes the leftmost value — a
fresh invented hop per request is a fresh bucket per request, so no bucket ever
fills and the limiter cannot be tripped. limitkit 0.2.0 already counts from the
right; nothing else in this repo reads the header at all. The test writes the
bypass out so a regression fails loudly instead of silently.
terminal-transport's postJson was a sixth copy of the fetch boilerplate
lib/api/fetch already wraps. It now composes: the shared postJson plus the
swallow that keeps a dropped keystroke from becoming an unhandled rejection.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(agent-execution): one PTY executor, two ways to spawn
LocalPtyExecutor and SandboxExecutor differed in exactly two places — how the
PTY is born, and what terminate() cleans up afterwards. The other 74 lines
(workspace map, ring buffer, sequence numbers, replay on reconnect, the
running→idle timer, listener isolation) were copied between them, and had
already drifted in their comments. The next fix to the event stream would have
landed in one substrate and not the other, which is a bug you can only see by
flipping LOKI_EXECUTOR.
PtyExecutor owns that half. A backend implements `launch` and, if it owns
anything outside the PTY, `afterTerminate` — SandboxExecutor's docker rm -f is
the only instance. "Both backends behave identically" is now a fact about the
code rather than a claim about two files.
Behaviour is unchanged: both existing suites (test:executor, the real PTY
round-trip including the idle flip and replay; test:sandbox-executor, the
docker argv) pass untouched.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(ui): say the repeated things once — attrs routes, repo pickers, today, PIN forms
Four clones, each a case of a file repeating itself rather than two files
repeating each other:
- /api/people/[id]/attrs and /api/robots/[id]/attrs were the same handler
twice. Attributes live in one table keyed by entity id, so the request IS the
same; the only real difference is that robots first proves the id is a robot
the caller owns, so /api/robots/<a person's id>/attrs cannot write through
the wrong door. That check is now a `guard` parameter, run before the body is
read exactly as before, and responses are byte-identical.
- RepoPicker and RepoMultiPicker each carried the language-colour map, the
/api/github/repos fetch and the row markup. The row takes a `lead` slot
rather than a `multi` flag: the multi picker puts a checkbox in front of the
lock, the single picker puts nothing, and neither component learns about the
other. What selecting MEANS is the only thing they still differ in.
- /today wrote `<Suspense fallback={<CardSkeleton />}>` eleven times and the
same two-column grid four times, which buried what the page is actually
saying — which decisions come first — under its loading mechanics.
- PrivacySettings' three PIN forms shared a submit envelope, a validation pair
and a button row. Each form still owns its fields and its own call.
Rendered output is unchanged in all four; tsc, lint and check:design are green.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor: one site-slug list, one account-fields block, one signed-webhook door
Three more single-definition fixes, each where the duplicate was a door:
- lib/site-cd and lib/hosted-runner/new-site each carried a
character-for-character copy of the reserved-label list and the DNS slug
grammar. That is the shape of duplication that quietly stops being identical:
a label added to one is a door left open in the other. lib/site-slug now owns
both, with no imports of its own so the hosted runner does not pull the
GitHub provisioning graph in just to reject a slug.
scripts/hetzner/new-site.sh keeps its own copy and stays the authority.
- /setup and SignUpForm wrote the same name/password/confirm block twice, down
to the placeholders and autocomplete hints — which matter: a password manager
keys off those, so drift between the two forms is drift in whether saved
credentials work. CreateAccountFields renders the email field only when
sign-up passes one.
- The three /api/orangecat receivers each reassembled the same front door:
refuse if unconfigured, verify the HMAC over the RAW body, then parse and
validate. The ORDER is what matters, not the code — the signature covers the
bytes so it must be checked before anything parses them, and the secret
before that, since with no secret a signed and an unsigned request are the
same request. readSignedOrangeCatBody is now that door; a fourth receiver
gets it right by construction. Responses are byte-identical.
site-cd (43), hosted-new-site (39) and the webhook HMAC contract tests pass
unchanged.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(lib): single definitions for escapeLike, decodeEntities, formatDate, normalizeName
Four helpers that existed twice each. Two of the pairs were not merely
redundant — they disagreed, and in both cases one side was wrong.
- decodeEntities: the atlas copy decoded `&` FIRST, so "&lt;" became
"<" became "<" — text a site had deliberately escaped turned back into
markup. The frontier copy did it last, correctly, and also handled CDATA and
`'`. One function now, `&` last, with a test that states why.
- escapeLike: identical in people.ts and robots.ts, but it is the LIKE-wildcard
escape — without it a search for "100%" matches every row. It now lives in
lib/sql-escape.ts rather than beside the queries, because it is pure string
work and that lets the unit suite run it without a DATABASE_URL. Tested,
including the backslash case, which is the one a "simplification" breaks.
- formatDate: two pages, one name, different output — worse than two names,
because reading one told you nothing about the other. lib/dates now exports
`longDate(value, { weekday })`, which also pins a bare YYYY-MM-DD to UTC noon
so a date column never renders as the previous day west of Greenwich.
- normalizeName: these two are genuinely different jobs (person-name folding vs
project-name matching), so the fix is honest naming, not a merge. The project
one is `normalizeProjectName`; one name meaning two rule sets is a bug
waiting for whoever imports the wrong one.
scripts/test/text-helpers.ts pins escapeLike and decodeEntities, including the
double-decode the consolidation fixed.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* fix(gates): teach the route-auth gate the new guard doors, and leave desktop/ alone
Two gates caught this branch, both correctly.
api-route-auth requires every route to NAME its auth mechanism. Moving the
OrangeCat HMAC check and the attrs guard behind shared helpers meant four
routes stopped naming one. The mechanisms are registered now — a route that
delegates names the delegate — and the helpers are noted as wrappers over
mechanisms already in the list, not as new ones.
Worse, and invisible: the same file derives "which routes authenticate
themselves" from markers in the source, then checks each one is exempt from the
session middleware. With the marker gone it found ZERO routes and reported
success — a check that silently examined nothing, which is the exact failure it
was written to prevent (a signed receiver behind the middleware 401s every
caller and reads like a wrong secret). It now fails when the marker set matches
nothing; proved by mutation — emptying SELF_AUTH_MARKERS fails the gate.
desktop-release-drift refused the `sleep` consolidation there, and it is right
to: desktop/ ships as a versioned release, so any change under it obliges a
version bump and a published Fleet Runner build. Three lines of helper is not
worth asking every machine to update, so desktop/src/main/dispatch.ts is
restored byte-for-byte and the reasoning is recorded in src/lib/async.ts, where
it costs no release.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
98 lines
4.1 KiB
TypeScript
98 lines
4.1 KiB
TypeScript
/**
|
|
* Inline tests for the ONE rate limiter (lib/rate-limit.ts → limitkit).
|
|
*
|
|
* Two things are pinned here, and the second is the reason this file exists.
|
|
*
|
|
* 1. `checkRateLimit` actually trips, counts per key, and separates rules. The
|
|
* PIN route used to hand-roll its own Map beside this; a limiter nobody
|
|
* tests is indistinguishable from a limiter that always returns true.
|
|
*
|
|
* 2. `getClientIp` reads the LAST `X-Forwarded-For` hop, not the first. Six
|
|
* sibling repos shipped the first-hop version, and it is not a cosmetic
|
|
* difference: the leftmost hop is written by the CLIENT, so a fresh random
|
|
* value per request is a fresh bucket per request and no bucket ever fills.
|
|
* A limiter that cannot be tripped is not a limiter. Keyed on the rightmost
|
|
* hop — the one our own proxy wrote — the attacker cannot choose his bucket.
|
|
*
|
|
* Run: npx tsx scripts/test/rate-limit.ts
|
|
*/
|
|
import type { NextRequest } from "next/server";
|
|
import { checkRateLimit, getClientIp } from "@/lib/rate-limit";
|
|
|
|
function assert(condition: boolean, message: string): void {
|
|
if (!condition) throw new Error(message);
|
|
}
|
|
|
|
let passed = 0;
|
|
const check = (label: string, fn: () => void) => {
|
|
fn();
|
|
passed += 1;
|
|
console.log(` ✓ ${label}`);
|
|
};
|
|
|
|
const req = (headers: Record<string, string>): NextRequest =>
|
|
({ headers: new Headers(headers) }) as NextRequest;
|
|
|
|
check("the limiter trips on the hit after the limit", () => {
|
|
const key = `test:trip:${Math.random()}`;
|
|
for (let i = 0; i < 5; i++) {
|
|
assert(checkRateLimit(key, 5, 60_000), `hit ${i + 1} of 5 was refused`);
|
|
}
|
|
assert(!checkRateLimit(key, 5, 60_000), "the 6th hit inside the window was allowed");
|
|
});
|
|
|
|
check("two keys under the same rule count apart", () => {
|
|
const a = `test:a:${Math.random()}`;
|
|
const b = `test:b:${Math.random()}`;
|
|
for (let i = 0; i < 5; i++) checkRateLimit(a, 5, 60_000);
|
|
assert(!checkRateLimit(a, 5, 60_000), "key a did not fill");
|
|
assert(checkRateLimit(b, 5, 60_000), "filling one key throttled an unrelated one");
|
|
});
|
|
|
|
check("the PIN route's rule (5 per minute, per user) is enforceable", () => {
|
|
const userId = `pin:${Math.random()}`;
|
|
const tries = Array.from({ length: 6 }, () => checkRateLimit(userId, 5, 60_000));
|
|
assert(
|
|
tries.filter(Boolean).length === 5,
|
|
`expected 5 of 6 PIN attempts allowed, got ${tries.filter(Boolean).length}`,
|
|
);
|
|
});
|
|
|
|
check("getClientIp takes the LAST forwarded hop, never the client-written first", () => {
|
|
// The attacker controls everything he sends; our proxy appends the address it
|
|
// actually saw. Anything left of that is his to invent.
|
|
const ip = getClientIp(req({ "x-forwarded-for": "1.1.1.1, 2.2.2.2, 203.0.113.9" }));
|
|
assert(ip === "203.0.113.9", `keyed on a client-controlled hop: ${ip}`);
|
|
});
|
|
|
|
check("a spoofed forwarded chain cannot mint a fresh bucket per request", () => {
|
|
// The bypass, written out: same real client, a different invented first hop
|
|
// each time. With a first-hop key every call is a new bucket and the limiter
|
|
// never trips — so this test fails loudly if the extraction ever regresses.
|
|
const rule = 5;
|
|
const seen = new Set<string>();
|
|
for (let i = 0; i < 6; i++) {
|
|
seen.add(getClientIp(req({ "x-forwarded-for": `9.9.9.${i}, 198.51.100.4` })));
|
|
}
|
|
assert(seen.size === 1, `spoofed hops produced ${seen.size} buckets, expected 1`);
|
|
const key = `spoof:${Math.random()}:${[...seen][0]}`;
|
|
const allowed = Array.from({ length: 6 }, () => checkRateLimit(key, rule, 60_000)).filter(
|
|
Boolean,
|
|
);
|
|
assert(allowed.length === rule, `limiter allowed ${allowed.length}, expected ${rule}`);
|
|
});
|
|
|
|
check("a single-hop chain still reads as the client", () => {
|
|
assert(
|
|
getClientIp(req({ "x-forwarded-for": "198.51.100.7" })) === "198.51.100.7",
|
|
"the common one-proxy shape stopped working",
|
|
);
|
|
});
|
|
|
|
check("no forwarded header falls back to x-real-ip, then to a shared bucket", () => {
|
|
assert(getClientIp(req({ "x-real-ip": "203.0.113.2" })) === "203.0.113.2", "x-real-ip ignored");
|
|
assert(getClientIp(req({})) === "unknown", "a header-less request produced a fake address");
|
|
});
|
|
|
|
console.log(`\n✓ rate-limit tests passed (${passed} assertions)`);
|