Files
loki/scripts/test/public-matcher.ts
CatoandClaude Opus 5 5f4797ea0a fix(notify,install): two silent no-ops found by running the thing (#765)
* feat(approvals): standing approvals + one-tap decisions from Telegram

Asking Loki in Telegram to put an appointment in the calendar did not put an
appointment in the calendar. It sent you to a website.

Three separate causes, all fixed here:

1. THE CHAT HAD NO ROAD TO THE CALENDAR AT ALL. `gog calendar create` is
   blocked on the box by the safety shim, and the fleetcrown skill could only
   decide drafts that already existed — it had no way to create one. So the
   agent hit the shim, read "route it through the approval queue", and passed
   that on as advice. Adds `fc.sh book`, which proposes a structured event
   through /api/actions/propose, and rewrites the shim's refusal to name it.
   The shim still blocks every external Google write; unattended agents have
   gained nothing.

2. THE GATE WAS ON THE WRONG SIDE OF THE REVERSIBILITY LINE. The queue enforced
   "nothing runs that the operator did not TAP", which is stricter than the rule
   it stands for ("nothing runs that the operator did not APPROVE"). For an
   event in your own calendar — private, self-only, undone by deleting it — the
   difference was pure latency (2026-08-04: proposed 14:15, booked 21:02).
   Standing approvals let that yes be given once, in advance, with three rails
   in code rather than in a docblock: eligibility is hard-coded (calendar events
   and commitments only — never anything that reaches another person), the
   payload is re-checked at decision time (guests mean invitations, so those go
   back to the queue), and unknown is never yes (no resolvable time, or a slot
   already past, queues). Default on for calendar events; toggle at /approvals.

3. THE NOTIFICATION HANDED BACK A CHORE. "2 actions are waiting… <url>" states
   a problem and leaves the answer behind a login. Decisions now arrive as a
   card carrying what/when/where plus one-tap Approve / Reject / Edit buttons,
   backed by HMAC links scoped to one action and one verb — so a decision needs
   no session and works when the gateway is down. Still two messages and only
   two: one when a decision is owed, one when the effect really happened.

Also fixes a real data bug: propose_action had no event date fields, so the WHEN
of an appointment had nowhere to go and arrived as prose in `body`, which a Groq
pass then had to guess back — a model re-deriving a value the model one step
earlier knew exactly.

Behaviour that did NOT change: emails, messages, dispatches, and person-book
writes still require a per-item yes, and always will — they are ineligible in
code, and a preference row naming one authorises nothing. Every auto-approval is
audited with `via: standing-rule` and announced, so nothing is done in the
operator's name silently.

Tests pin the parts that must not be trusted: 37 cases on the standing-approval
rails (asserted from the side that hurts — a false `auto: true`), 21 on token
forgery and tampering.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(chat-skill): the chat's whole Loki skill was dead, and unversioned

Found while testing the previous commit end-to-end, and it is the largest of
the reasons appointments never got added.

On 2026-09-14 the product was renamed to Loki and `calendar-drain.env`'s keys
were renamed with it. The chat agent's skill script, which reads that file, was
not — because it lived only on the box, where no gate in this repo could see
it. Since then every command it offers has aborted on its first line:

    line 14: <OLD>_AGENT_TOKEN: <OLD>_AGENT_TOKEN missing in calendar-drain.env

Verified live on bitbaum just now. So from Telegram the operator could not list
the approval queue, could not approve or reject anything, and could not
dispatch — silently, because a skill that errors just makes the agent talk
about something else instead. The only surviving route to a decision was the
website. That is the complaint, and it had a cause older than the UX.

Fixes:

- Renames the skill to `loki` (the retired product name is forbidden in this
  repo by scripts/hetzner/test-no-retired-name.sh — which caught this commit,
  correctly, when the box files were first imported verbatim) and reads the
  env keys the file actually has.
- The installer REMOVES the superseded skill directory rather than leaving it.
  Two skills claiming the same job, one of which cannot run, is how the agent
  kept choosing the broken one.
- The installer now runs `loki.sh pending` as the openclaw user and fails if it
  cannot authenticate. That is the check which would have caught the rename on
  the day it happened: run the thing, as the user who runs it, and require real
  output. Every other verification in that script only asserted that files
  exist, and files existing is exactly what was true throughout the outage.

Also closes a gap in the previous commit: an auto-approved COMMITMENT executed
without telling anyone, while the comments claimed every auto-approval is
announced. Calendar events are announced from where gog succeeds (asynchronous,
on the box); everything else finishes inside enqueueAction, so that is the only
place that knows it finished at all. A standing approval nobody is told about
is not a standing rule, it is a silent one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(install): keep the gog shim parseable, and prove the block still fires

The replacement text I substituted into the shim carried double quotes. It
lands inside `block(){ echo "…" >&2; }` — a double-quoted bash string — so a
quote in the middle of it closes that string early and leaves the shim a
syntax error. Every gog call on the box would then fail, reads included, and
the calendar drain's real bookings with them: an install step meant to improve
an error message would have taken out the calendar entirely.

Caught by tracing the sed against the shim's actual text rather than running
it. Two checks added so the next one is caught by the machine:

- `bash -n` on the shim after the edit — it is a shell script we just modified
  in place, so prove it still parses before trusting anything else about it.
- Actually attempt a calendar write as the openclaw user and require it to be
  REFUSED. The old check grepped for the rule's text, and a rule you can read
  in a file is not a rule you have seen refuse anything.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ui): use tokens this design system actually defines

The new approvals control and decision page reached for `text-brand`,
`accent-brand`, `bg-surface-hover` and `rounded-card`. None of those exist in
globals.css — the real names are `accent-text`, `surface-raised` and the
`radius-*` scale. Tailwind emits nothing for an unknown utility and reports no
error, so the checkbox would have rendered browser-default blue and the hover
state simply would not have happened, on a page whose entire job is to be
tapped once and trusted.

The design check passes either way: it forbids arbitrary values (`bg-[#fff]`),
which is a different failure from naming a token that was never defined. Caught
by grepping whether any other component uses these names — none did, which is
the tell.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(notify,install): two silent no-ops found by running the thing

Both found by exercising the deployed feature end to end rather than reading
it, and both are the same failure: a step that could not succeed, reporting
nothing.

1. A REFUSED TELEGRAM SEND WAS INVISIBLE. sendTelegramMessage reports a bad
   token, a blocked chat or an API error as `{ok:false}` — an ordinary return
   value, not an exception — so the try/catch around it caught the case that
   never happens and ignored the case that does. That matters more here than
   in a normal notification: the confirmation message IS the review mechanism
   for actions a standing rule took without asking. If it stops arriving, the
   operator does not notice Loki went quiet; they notice Loki apparently
   stopped doing things, which is the opposite of what is true. Both senders
   now log a refusal.

2. THE INSTALLER'S CLEANUP STEP CLEANED NOTHING. It globbed the skills
   directory as the ssh user, who cannot traverse the openclaw home: the glob
   matched nothing, the loop ran zero times, and the script printed its success
   banner. The superseded skill was still installed afterwards — the exact
   "two skills claiming one job, one of them broken" state the step exists to
   prevent, left in place by the step that prevents it.

   Fixed by running the loop under sudo, and then ASSERTING no other skill
   ships the old entrypoint. Trusting the loop's own silence is what let the
   first version pass; verified on the box that it now removes the directory
   and that the assertion sees an empty result afterwards.

Verified live on bitbaum after deploying the parent change: booking from the
chat skill returns auto-approved, the drain books it, the row reaches executed,
and the event is really in Google Calendar at the right time. Test event
deleted.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): the one-tap approval link redirected to sign-in

The feature whose entire purpose is "decide from your phone without logging in"
sent you to a login page. Found by tapping it against production, not by
reading it:

    GET /a/<token>  →  302  /sign-in?callbackUrl=/a/<token>

Route auth here is one negative-lookahead regex in src/proxy.ts listing the
prefixes served without a session, and `a/` was not among them. Every unit test
on the token passed throughout — 21 of them — because they tested the TOKEN.
Nothing tested whether the route could be reached, which is the part that was
broken. A signature that verifies perfectly behind a login is worth nothing.

Adds `a/` with the same justification the file already records for `share/task/`:
the minted token IS the credential, the holder has no account by design, and the
link decides exactly one action with one verb (lib/actions/action-link.ts).

THE TRAILING SLASH IS LOAD-BEARING, and that is why this commit also adds a
gate. The list holds bare prefixes, so `a` instead of `a/` would have made
/approvals, /api/*, /agent — every path starting with that letter — publicly
readable, and nothing would have looked broken: the app would have worked
better, with nobody asked to log in. That is the one direction a reviewer will
not notice.

scripts/test/public-matcher.ts reads the real regex out of the real file and
asserts BOTH directions: what must be reachable without a session, and what must
not. Proven by mutation before committing — with `a` in place of `a/`, eight
assertions fail loudly (/approvals, /api/actions/pending, /api/me/preferences
among them). A test that only checked the public list would have passed just as
happily on a regex that made the whole app public.

Verified: pnpm verify green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 08:51:54 -07:00

105 lines
4.7 KiB
TypeScript

// Pins WHICH paths the auth middleware lets through without a session.
//
// WHY THIS EARNS A TEST
// The public surface of this app is one regex in src/proxy.ts — a single
// negative lookahead listing ~45 prefixes. Every entry is a decision to serve
// someone with no account, and the list is edited by hand, by people adding one
// more prefix to make one more link work.
//
// The failure mode is not subtle, it is catastrophic and silent. The entries
// are bare prefixes, so adding `a` instead of `a/` — one character — would make
// `/approvals`, `/api/...`, `/agent`, every path beginning with that letter
// public, and nothing would look broken: the app would still work, better even,
// because nobody would be asked to log in. Exactly the direction a human
// reviewer is least likely to notice.
//
// So this asserts BOTH directions on the real regex, read from the real file:
// the things that must be reachable without a session, and — the point — the
// things that must NOT be. A test that only checked the public list would pass
// happily on a regex that made the whole app public.
import { readFileSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
const REPO = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
const source = readFileSync(join(REPO, "src", "proxy.ts"), "utf8");
// Pull the matcher out of the source rather than re-declaring it here: a copy
// of the pattern in the test is a test of the copy, which is exactly the thing
// that cannot drift with the file it guards.
//
// Anchored on the pattern's own shape rather than on `matcher: [`, because a
// long explanatory comment sits between the two. Failing to FIND the pattern
// exits hard rather than skipping — a test that quietly stops checking is the
// same silent no-op this file exists to catch.
const match = source.match(/"(\/\(\(\?!(?:[^"\\]|\\.)*)"/);
if (!match) {
console.log("✗ could not find the matcher pattern in src/proxy.ts");
process.exit(1);
}
// The source contains a TS string literal, so `\\.` in the file is `\.` in the
// actual regex. Un-escape exactly once to recover the pattern Next.js compiles.
const pattern = match[1].replace(/\\\\/g, "\\");
const matcher = new RegExp(`^${pattern}$`);
/** Next.js runs the auth middleware on paths the matcher MATCHES. */
const isProtected = (path: string) => matcher.test(path);
let pass = 0;
const cases: Array<[string, boolean]> = [];
const check = (name: string, cond: boolean) => {
cases.push([name, cond]);
if (cond) pass++;
};
// ── Public by design ────────────────────────────────────────────────────────
const TOKEN =
"8337d0fe-1bb1-4c40-98e5-4961196b8de2.00000000-0000-0000-0000-000000000001.approve.1789735075045.16YvawjpRnp";
check("a one-tap action link is reachable without a session", !isProtected(`/a/${TOKEN}`));
check("so is a short one", !isProtected("/a/xyz"));
for (const p of [
"/sign-in",
"/claim-feedback",
"/share/task/abc",
"/api/health",
"/api/invitations/abc",
"/blog/some-post",
]) {
check(`${p} stays public`, !isProtected(p));
}
// ── PROTECTED — the direction that matters ──────────────────────────────────
// Each of these begins with "a", and each would become public if the entry were
// written `a` instead of `a/`. This block is the whole reason the file exists.
for (const p of [
"/approvals",
"/approvals?focus=abc",
"/api/actions/pending",
"/api/actions/8337d0fe/decision",
"/api/me/preferences",
"/agent",
"/activity",
"/about",
]) {
check(`${p} still requires a session`, isProtected(p));
}
// And the ordinary app is untouched.
for (const p of ["/today", "/control", "/people", "/settings"]) {
check(`${p} still requires a session`, isProtected(p));
}
// A bare "/a" is not an action link and must not ride the exemption.
check("/a (no token) still requires a session", isProtected("/a"));
// ── The check can still fail ────────────────────────────────────────────────
// A regex that stopped matching anything would pass every "is public" assertion
// above in silence. Prove it still classifies something as protected at all.
check(
"the matcher is not inert (it protects a random deep path)",
isProtected("/some/deep/protected/path"),
);
check("the matcher was parsed, not empty", pattern.length > 100);
for (const [name, ok] of cases) console.log(`${ok ? "✓" : "✗"} ${name}`);
console.log(`\n${pass}/${cases.length} passed`);
if (pass !== cases.length) process.exit(1);