Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 21.7 KiB · at 503e839

TSUS v2 diagnostic codes

Generated from packages/cli/src/v2/registry.js by npm run docs. Do not edit by hand; tsus explain <CODE> prints the same text.

v2 checks plain .ts (tsus check --v2). A rule is here only if there is a bug it catches; each entry says which one, citing the search-query experiment (plain strict TS against TSUS v1, judged on 118 hidden tests and 20,400 fuzz pairs), the on-call pilot (docs/v2/tsus-pilot.md in Rebasely), or the risks reviews of AI-written web code kept finding (SQL injection, permission scoping, secrets, untrusted input).

Code Rule
TSUS500 Type error
TSUS501 Non-exhaustive switch or match over a union
TSUS502 null is banned outside boundary files
TSUS503 Truthiness test on an Option that can hold a falsy value
TSUS504 Floating promise
TSUS505 Ignored Result
TSUS506 as casts are banned outside boundary files
TSUS507 Non-null assertions are banned outside boundary files
TSUS508 any is banned outside boundary files
TSUS509 Type-check suppressions are banned
TSUS510 Parameters are read-only by default
TSUS600 Private data read without a Permit
TSUS601 Query built from a string
TSUS602 Permits are minted only in access files
TSUS603 Read the resource from the Permit
TSUS604 Secret stringified, logged or serialized
TSUS605 Untrusted text in HTML without escaping
TSUS606 Untrusted text in an LLM prompt without marking
TSUS607 Untrusted text turned into a plain string

TSUS500 type-error

Type error. v2 runs the project's own TypeScript program with strict and noUncheckedIndexedAccess forced on, and reports every error under one stable code with the original TS code in tsCode. noUncheckedIndexedAccess is the v2 replacement for v1's de facto indexing ban: parts[0] is string | undefined, and a plain === undefined check (allowed in v2) narrows it.

Why it stays: experiment: v1 banned undefined and !, so with no way to test an index the TSUS build wrote parts.slice(0, 1).join("") for parts[0] and a for-loop over a 0-or-1-element array. The same safety is one compiler flag plus an === undefined check.

Rejected:

TypeScript
const firstWord = (s: string): string => {
  const parts = s.split(" ");
  return parts[0].toUpperCase(); // TS2532 under noUncheckedIndexedAccess
};

Accepted:

TypeScript
const firstWord = (s: string): string => {
  const first = s.split(" ")[0];
  return first === undefined ? "" : first.toUpperCase();
};

Hint: Read tsCode and the message; v2 type-checks with strict and noUncheckedIndexedAccess on.

TSUS501 exhaustive-switch

Non-exhaustive switch or match over a union. A switch over a union with no default silently does nothing for a member nobody wrote a case for, and TypeScript only notices when a return type happens to demand it. Adding a variant later is exactly when this bites. match() and matchLiteral() make the same check part of the type of the call.

Why it stays: experiment: the TSUS build's exhaustive match over the query AST and the keyOf total match were the one place reviewers credited v1 with preventing a bug class (A narrowed with as Key after a runtime check). pilot: a literal match replaced a lookup and found the alert classes are a fixed set.

Rejected:

TypeScript
type State = "open" | "closed" | "merged";
const label = (s: State): string => {
  let out = "";
  switch (s) {
    case "open": out = "Open"; break;
    case "closed": out = "Closed"; break;
  }
  return out; // "merged" falls through to ""
};

Accepted:

TypeScript
import { matchLiteral } from "@tsus/v2";
type State = "open" | "closed" | "merged";
const label = (s: State): string =>
  matchLiteral(s, { open: () => "Open", closed: () => "Closed", merged: () => "Merged" });

Hint: Add a case for each missing member, or a default that calls exhaustive(x).

TSUS502 no-null

null is banned outside boundary files. Two absent values means every check has to remember both, and x === undefined passes a null straight through. v2 keeps one, undefined, which is what Option<T> is. Comparisons (m === null after re.exec) stay legal, so libraries that return null need no adapter; only writing null is banned.

Why it stays: experiment: B's api.ts existed to convert null to None and back (51 lines). With Option as T | undefined and null comparisons allowed, that adapter is unnecessary. The one remaining place null is honest, a D1 row, is converted by safeDb.

Rejected:

TypeScript
type User = { readonly email: string | null };
const none: User = { email: null };

Accepted:

TypeScript
import type { Option } from "@tsus/v2";
type User = { readonly email: Option<string> };
const none: User = { email: undefined };

Hint: Use Option (T | undefined). Comparing a library's result with null is fine; producing null is not.

TSUS503 no-falsy-option-test

Truthiness test on an Option that can hold a falsy value. With Option as T | undefined, the narrowing gap is the truthiness test: if (port) is false for 0 and if (name) for "", which is rarely what absent means. The rule fires only where the present value can be falsy (strings, numbers, bigints), not on objects or booleans.

Why it stays: pilot: the watcher's if (!s) return {} and e.environment && ... paths treated an empty string like a missing one; the v1 rewrite had to spell out present() to keep that behavior on purpose. This rule makes the choice explicit without a wrapper type.

Rejected:

TypeScript
import type { Option } from "@tsus/v2";
const portOf = (raw: Option<number>): number => (raw ? raw : 8080); // 0 becomes 8080

Accepted:

TypeScript
import type { Option } from "@tsus/v2";
const portOf = (raw: Option<number>): number => (raw !== undefined ? raw : 8080);

Hint: Compare with undefined (x !== undefined), or use isSome(x).

TSUS504 no-floating-promise

Floating promise. A promise nobody awaits loses its rejection and its ordering: the write may happen after the response, or never. In a Worker the isolate can be torn down before it settles. void p is the explicit opt-out (v1 banned it; v2 keeps it as the visible marker of intent).

Why it stays: risks: unawaited D1 writes and fetches are the classic Workers bug, and they are invisible in review. v1 had this rule (TSUS411) and it costs nothing when code is written correctly.

Rejected:

TypeScript
const save = async (id: string): Promise<void> => {};
const handle = (id: string): string => {
  save(id);
  return "ok";
};

Accepted:

TypeScript
const save = async (id: string): Promise<void> => {};
const handle = async (id: string): Promise<string> => {
  await save(id);
  return "ok";
};

Hint: await it, return it, hand it to ctx.waitUntil, or write void to say it is fire-and-forget.

TSUS505 no-ignored-result

Ignored Result. A function that returns a Result is telling the caller it can fail. Calling it as a statement throws the failure away, which is the same bug as an empty catch.

Why it stays: v1 TSUS412. pilot: spelling the failure paths out as values is what exposed the digest retrying a Claude run every tick while POST /digest failed.

Rejected:

TypeScript
import { Ok, type Result } from "@tsus/v2";
const send = (to: string): Result<true, "bounced"> => Ok(true);
const notify = (): void => {
  send("ops@example.com");
};

Accepted:

TypeScript
import { Ok, type Result } from "@tsus/v2";
const send = (to: string): Result<true, "bounced"> => Ok(true);
const notify = (): string => {
  const r = send("ops@example.com");
  return r.ok ? "sent" : r.error;
};

Hint: Branch on r.ok, matchResult it, or return it.

TSUS506 no-cast

as casts are banned outside boundary files. Every security type in v2 is a brand that only its constructor can make. x as Sql, {} as Permit<...> or s as unknown as string forges one. The cast ban is what makes the brands mean something; boundary files, visible by name, are where outside data is checked and converted.

Why it stays: experiment: A had 11 casts, all safe today but none checked; B had 0. The casts themselves did not cause a bug, so on correctness alone the rule would go. It stays because without it as Permit defeats the permission rule.

Rejected:

TypeScript
import type { Sql } from "@tsus/v2";
const query = "SELECT * FROM users" as unknown as Sql;

Accepted:

TypeScript
import { sql } from "@tsus/v2";
const query = sql`SELECT * FROM users`;

Hint: Narrow with a check the compiler can see, or move the conversion into a *.boundary.ts file.

TSUS507 no-non-null

Non-null assertions are banned outside boundary files. x! is a cast to the non-nullable type, and with noUncheckedIndexedAccess it is the one-character way to switch the index check back off.

Why it stays: experiment: neither build used !, so it costs nothing. It stays as the other half of noUncheckedIndexedAccess.

Rejected:

TypeScript
const first = (xs: readonly string[]): string => xs[0]!;

Accepted:

TypeScript
const first = (xs: readonly string[]): string => xs[0] ?? "";

Hint: Check for undefined; the compiler narrows after the check.

TSUS508 no-any

any is banned outside boundary files. any is assignable to every brand, so const q: any = userText; db.all(q) would pass the Sql check. unknown keeps the check.

Why it stays: experiment: zero uses in either build, so no friction. It stays for the same reason as the cast ban.

Rejected:

TypeScript
const parse = (raw: string): any => JSON.parse(raw);

Accepted:

TypeScript
const parse = (raw: string): unknown => JSON.parse(raw);

Hint: Use unknown and narrow, or a precise type.

TSUS509 no-ts-suppression

Type-check suppressions are banned. A suppression switches every rule above off for a line or a file with no record of why.

Why it stays: v1 TSUS413; zero uses in the experiment, so no friction.

Rejected:

TypeScript
// @ts-ignore
const n: number = "4";

Accepted:

TypeScript
const n: number = Number("4");

Hint: Fix the error; checked conversions belong in a *.boundary.ts file.

TSUS510 readonly-params

Parameters are read-only by default. A function that sorts, pushes into or writes a field of the array or object it was handed changes its caller's data, which is the bug behind "why did this list reorder". v2 does not ask for readonly on every type (that was friction); it treats every parameter as read-only and lets the signature opt out with Mutable<T>.

Why it stays: experiment: neither build mutated a parameter, so the rule cost nothing there. v1's TSUS409 had the same intent; v2 drops its companions (no parameter reassignment, readonly spelled on every type), which added volume and caught nothing.

Rejected:

TypeScript
const newest = (xs: number[]): number[] => xs.sort((a, b) => b - a);

Accepted:

TypeScript
const newest = (xs: readonly number[]): number[] => xs.toSorted((a, b) => b - a);

Hint: Return a new value, or declare the parameter as Mutable to say the mutation is the point.

TSUS600 permit-required

Private data read without a Permit. A function that reads private data takes Permit<"repo.read", RepoId>. The only way to get one is the access check, so forgetting the check is a missing argument, and passing a hand-made object is a missing brand. This code is the type error TypeScript reports, given a name.

Why it stays: risks: permission scoping was one of the three problems reviews of AI-written Rebasely code kept finding; in the experiment both builds kept pageOf (repo.read) only because the brief said so. v1 could not express it.

Rejected:

TypeScript
import type { Permit } from "@tsus/v2";
type RepoId = string & { readonly __repo: true };
declare const listIssues: (p: Permit<"repo.read", RepoId>) => Promise<readonly string[]>;
declare const repoId: RepoId;
const page = () => listIssues({ action: "repo.read", resource: repoId });

Accepted:

TypeScript
import type { Permit } from "@tsus/v2";
type RepoId = string & { readonly __repo: true };
declare const listIssues: (p: Permit<"repo.read", RepoId>) => Promise<readonly string[]>;
declare const canReadRepo: (user: string, repo: RepoId) => Promise<Permit<"repo.read", RepoId> | undefined>;
const page = async (user: string, repoId: RepoId) => {
  const permit = await canReadRepo(user, repoId);
  return permit === undefined ? [] : listIssues(permit);
};

Hint: Call the access check (in an *.access.ts file) and pass the Permit it returns.

TSUS601 sql-from-strings

Query built from a string. A query whose text includes runtime data is an injection the moment that data comes from a user. SafeDb accepts only Sql, which only the sql tag makes, so concatenation is a type error there; this rule covers what types cannot: a raw prepare(text) on a D1 binding with any text that is not a compile-time constant, and calling sql(...) as a plain function.

Why it stays: risks: SQL injection was the first of the three risk classes. The experiment's builds were both inert to 16 payloads only because they bound every value by hand; nothing would have stopped a slip.

Rejected:

TypeScript
import type { D1Like } from "@tsus/v2";
declare const db: D1Like; // env.DB, a D1 binding
const find = (title: string) => db.prepare(`SELECT * FROM issues WHERE title = '${title}'`).all();

Accepted:

TypeScript
import { sql, type SafeDb } from "@tsus/v2";
declare const db: SafeDb;
const find = (title: string) => db.all(sql`SELECT * FROM issues WHERE title = ${title}`);

Hint: Write the query with sql...: every ${value} becomes a bound parameter.

TSUS602 permit-minting

Permits are minted only in access files. If any module can call issuePermit, any module can skip the check. Keeping the import to files whose name says what they are makes the whole permission model reviewable in one place.

Why it stays: risks: permission scoping. The rule is what makes TSUS600 mean "an access check ran" rather than "someone called a function".

Rejected:

TypeScript
// file: src/issues.ts
import { issuePermit } from "@tsus/v2/authority";
export const anyone = (repo: string) => issuePermit("repo.read", repo);

Accepted:

TypeScript
// file: src/repo.access.ts
import { issuePermit } from "@tsus/v2/authority";
export const canRead = (role: "owner" | "none", repo: string) =>
  role === "owner" ? issuePermit("repo.read", repo) : undefined;

Hint: Move the access check into a file named *.access.ts and export a function that returns the Permit.

TSUS603 permit-resource

Read the resource from the Permit. listIssues(permit, repoId) type-checks with a permit for repo A and an id for repo B: an insecure direct object reference. Taking the id from the permit makes the check and the query talk about the same thing.

Why it stays: risks: permission scoping. In the experiment the scope came from ctx.repoId next to an unrelated check result; a mismatch would have been invisible to both type systems.

Rejected:

TypeScript
import type { Permit } from "@tsus/v2";
type RepoId = string & { readonly __repo: true };
export const listIssues = (p: Permit<"repo.read", RepoId>, repo: RepoId) => repo;

Accepted:

TypeScript
import type { Permit } from "@tsus/v2";
type RepoId = string & { readonly __repo: true };
export const listIssues = (p: Permit<"repo.read", RepoId>) => p.resource;

Hint: Drop the separate id and read permit.resource, so the checked resource is the one queried.

TSUS604 secret-exposure

Secret stringified, logged or serialized. A Secret is not a string, so the type system already stops it where a string is expected. It cannot stop a template literal, +, console.log(env) or JSON.stringify(config), which accept anything; this rule does, including objects that contain a Secret. At runtime a Secret prints as "[secret]" as a backstop.

Why it stays: risks: secrets reaching logs and URLs was the third risk class; v1 had no notion of a secret.

Rejected:

TypeScript
import type { Secret } from "@tsus/v2";
declare const apiKey: Secret;
console.log(`calling the API with ${apiKey}`);

Accepted:

TypeScript
import { reveal, type Secret } from "@tsus/v2";
declare const apiKey: Secret;
const headers = { authorization: `Bearer ${reveal(apiKey)}` };

Hint: Use reveal(secret) at the one call that needs the raw value (an Authorization header), and nowhere else.

TSUS605 untrusted-html

Untrusted text in HTML without escaping. User text inside markup is stored XSS. Untrusted is not a string, but untagged templates and + accept anything, so the checker rejects Untrusted there when the surrounding text is markup, or when it is assigned to innerHTML.

Why it stays: risks: untrusted input was one of the three risk classes; the experiment's judge had to verify by hand that every echo of the query went through `html```.

Rejected:

TypeScript
import type { Untrusted } from "@tsus/v2";
declare const title: Untrusted;
const row = `<li>${title}</li>`;

Accepted:

TypeScript
import { html, type Untrusted } from "@tsus/v2";
declare const title: Untrusted;
const row = html`<li>${title}</li>`;

Hint: Build the markup with html... (it escapes), or escapeHtml(text).

TSUS606 untrusted-prompt

Untrusted text in an LLM prompt without marking. Text a user wrote, pasted into a prompt as if the program wrote it, can give the model instructions (prompt injection). fence() wraps it as <untrusted source=...> data and neutralizes closing tags and role markers inside it, the same markers Rebasely's injection screen looks for. The rule fires on templates and concatenation that build a prompt: assigned to a name like prompt, system or messages, or passed to a model call.

Why it stays: risks: Rebasely screens bug reports for prompt injection before agents read them (packages/shared/injection-screen.ts); nothing in the type system marked where report text entered a prompt.

Rejected:

TypeScript
import type { Untrusted } from "@tsus/v2";
declare const report: Untrusted;
const prompt = `Summarize this bug report: ${report}`;

Accepted:

TypeScript
import { fence, type Untrusted } from "@tsus/v2";
declare const report: Untrusted;
const prompt = `Summarize this bug report: ${fence(report, "bug report")}`;

Hint: Wrap it: fence(text, "bug report"), or build the prompt with prompt..., which rejects Untrusted.

TSUS607 untrusted-string

Untrusted text turned into a plain string. Anything that turns Untrusted into an unmarked string (a template, +, String(), toString()) loses the mark, and the next sink cannot tell. The sinks with their own codes are HTML (TSUS605) and prompts (TSUS606); this is every other place.

Why it stays: risks: untrusted input. The rule is the general case the two named sinks specialize.

Rejected:

TypeScript
import type { Untrusted } from "@tsus/v2";
declare const slug: Untrusted;
const path = "/repos/" + slug;

Accepted:

TypeScript
import { validate, type Untrusted } from "@tsus/v2";
declare const slug: Untrusted;
const safe = validate(slug, /[a-z0-9-]+/);
const path = safe === undefined ? "/" : "/repos/" + safe;

Hint: validate(text, /pattern/) for ids and slugs, escapeHtml for markup, fence for prompts, sql`` for queries.

What happened to v1's rules

v1 v2 Why
TSUS001 no class dropped Style, not a bug class. Neither build in the experiment would have had a bug a class introduced; Rebasely's Durable Objects must be classes.
TSUS002 no null kept, narrowed (TSUS502) Producing null is banned; comparing with null is allowed, so library results need no adapter (the experiment's 51-line api.ts was mostly null conversion).
TSUS003 no undefined dropped undefined is v2's Option. Banning it is what forced parts.slice(0, 1).join("") in the experiment.
TSUS004 no var dropped No bug in either experiment build or the pilot; a style lint.
TSUS005 no throw dropped Workers, D1 and fetch throw; banning throw forced wrappers at every boundary. Result stays available and an ignored one is still an error (TSUS505).
match macro, ? operator (TSUS006, TSUS2xx, TSUS3xx) replaced Not erasable: they needed a new file extension and a compiler. v2 has match()/matchLiteral() functions typed for exhaustiveness and the exhaustive-switch rule (TSUS501); ? has no erasable equivalent and early returns on !r.ok do the job.
TSUS401 no any kept (TSUS508) Zero uses in the experiment; any defeats the brands.
TSUS402 no casts kept (TSUS506) A's 11 casts were all safe, so on correctness alone it would go; it stays because a cast forges Sql and Permit.
TSUS403 no ! kept (TSUS507) The other half of noUncheckedIndexedAccess.
TSUS404 no enum dropped Style. Enums erase poorly (erasableSyntaxOnly rejects them), which tsconfig already reports.
TSUS405 no == / != dropped No bug in the experiment or the pilot; TypeScript already rejects comparisons of unrelated types.
TSUS406 no default export dropped Workers require export default { fetch }; the v1 rule needed a file-level exemption to exist at all.
TSUS407 no parameter reassignment dropped Style; reassigning a local copy does not change the caller's data.
TSUS408 let never reassigned dropped Style; a fix-it, not a bug.
TSUS409 no parameter mutation kept, reshaped (TSUS510) Mutating the caller's data is a bug class; v2 opts out per parameter with Mutable instead of asking for readonly everywhere.
TSUS410 tagged errors only dropped Cost nine examples a retrofit in v1 and caught no bug; matchResult works on any E.
TSUS411 floating promises kept (TSUS504) A real Workers bug class; void p is now the explicit opt-out.
TSUS412 unused Result kept (TSUS505) The pilot's digest retry bug was an unexamined failure.
TSUS413 suppressions kept (TSUS509) Zero uses, no friction, and it guards every other rule.
Option/Result wrapper objects replaced Option is `T