Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

v2: @tsus/v2 (Option as T | undefined, plain-object Result, typed match, Sql, Permit, Secret, Untrusted), tsus check --v2 (TSUS500-607) and tsus audit

Plain .ts, erasable, no macros and no new extension. The library is a .d.ts plus a small runtime;
the brands are unexported unique symbols, so only their constructors (or a cast, banned outside
*.boundary.ts) make them. The checker runs the project's own TypeScript program with strict and
noUncheckedIndexedAccess, names TypeScript's errors by meaning (a missing Permit, a string where
Sql is expected) and adds the rules types cannot express: exhaustive switches, truthiness on
optional strings and numbers, floating promises, ignored Results, casts, parameter mutation,
string-built queries, permit minting outside *.access.ts, Secret and Untrusted in templates,
concatenation, logs, JSON and URLs. tsus audit is report-only over existing .ts. Root tsconfig.json
typechecks the v2 files with erasableSyntaxOnly; esbuild is a dev dependency for the examples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
355e32436e62a90c2fc2d5d20414d63a1537b1dc
Parent b0c0c21 Browse filesHistory

Changed files

15 files changed2,511 additions6 deletionsagainst b0c0c21

  1. Changedpackage-lock.json+494−1
  2. Changedpackage.json+4−1
  3. Changedpackages/cli/bin/tsus.js+24−2
  4. Changedpackages/cli/src/explain.js+43−2
  5. Addedpackages/cli/src/v2/analysis.js+234−0
  6. Addedpackages/cli/src/v2/audit.js+383−0
  7. Addedpackages/cli/src/v2/program.js+69−0
  8. Addedpackages/cli/src/v2/registry.js+354−0
  9. Addedpackages/cli/src/v2/rules.js+430−0
  10. Addedpackages/v2/authority.d.ts+7−0
  11. Addedpackages/v2/authority.js+3−0
  12. Addedpackages/v2/index.d.ts+242−0
  13. Addedpackages/v2/index.js+178−0
  14. Addedpackages/v2/package.json+17−0
  15. Addedtsconfig.json+29−0
Changedpackage-lock.jsonLong diff, collapsed+494−1
@@ -13,9 +13,452 @@
"zod": "^3.23.0"
},
"devDependencies": {
- "@types/node": "^22.20.5"
+ "@types/node": "^22.20.5",
+ "esbuild": "^0.25.10"
}
},
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.10.tgz",
+ "integrity": "sha512-0NFWnA+7l41irNuaSVlLfgNT12caWJVLzp5eAVhZ0z1qpxbockccEt3s+149rE64VUI3Ml2zt8Nv5JVc4QXTsw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.10.tgz",
+ "integrity": "sha512-dQAxF1dW1C3zpeCDc5KqIYuZ1tgAdRXNoZP7vkBIRtKZPYe2xVr/d3SkirklCHudW1B45tGiUlz2pUWDfbDD4w==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.10.tgz",
+ "integrity": "sha512-LSQa7eDahypv/VO6WKohZGPSJDq5OVOo3UoFR1E4t4Gj1W7zEQMUhI+lo81H+DtB+kP+tDgBp+M4oNCwp6kffg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.10.tgz",
+ "integrity": "sha512-MiC9CWdPrfhibcXwr39p9ha1x0lZJ9KaVfvzA0Wxwz9ETX4v5CHfF09bx935nHlhi+MxhA63dKRRQLiVgSUtEg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.10.tgz",
+ "integrity": "sha512-JC74bdXcQEpW9KkV326WpZZjLguSZ3DfS8wrrvPMHgQOIEIG/sPXEN/V8IssoJhbefLRcRqw6RQH2NnpdprtMA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.10.tgz",
+ "integrity": "sha512-tguWg1olF6DGqzws97pKZ8G2L7Ig1vjDmGTwcTuYHbuU6TTjJe5FXbgs5C1BBzHbJ2bo1m3WkQDbWO2PvamRcg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.10.tgz",
+ "integrity": "sha512-3ZioSQSg1HT2N05YxeJWYR+Libe3bREVSdWhEEgExWaDtyFbbXWb49QgPvFH8u03vUPX10JhJPcz7s9t9+boWg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.10.tgz",
+ "integrity": "sha512-LLgJfHJk014Aa4anGDbh8bmI5Lk+QidDmGzuC2D+vP7mv/GeSN+H39zOf7pN5N8p059FcOfs2bVlrRr4SK9WxA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.10.tgz",
+ "integrity": "sha512-oR31GtBTFYCqEBALI9r6WxoU/ZofZl962pouZRTEYECvNF/dtXKku8YXcJkhgK/beU+zedXfIzHijSRapJY3vg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.10.tgz",
+ "integrity": "sha512-5luJWN6YKBsawd5f9i4+c+geYiVEw20FVW5x0v1kEMWNq8UctFjDiMATBxLvmmHA4bf7F6hTRaJgtghFr9iziQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.10.tgz",
+ "integrity": "sha512-NrSCx2Kim3EnnWgS4Txn0QGt0Xipoumb6z6sUtl5bOEZIVKhzfyp/Lyw4C1DIYvzeW/5mWYPBFJU3a/8Yr75DQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.10.tgz",
+ "integrity": "sha512-xoSphrd4AZda8+rUDDfD9J6FUMjrkTz8itpTITM4/xgerAZZcFW7Dv+sun7333IfKxGG8gAq+3NbfEMJfiY+Eg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.10.tgz",
+ "integrity": "sha512-ab6eiuCwoMmYDyTnyptoKkVS3k8fy/1Uvq7Dj5czXI6DF2GqD2ToInBI0SHOp5/X1BdZ26RKc5+qjQNGRBelRA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.10.tgz",
+ "integrity": "sha512-NLinzzOgZQsGpsTkEbdJTCanwA5/wozN9dSgEl12haXJBzMTpssebuXR42bthOF3z7zXFWH1AmvWunUCkBE4EA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.10.tgz",
+ "integrity": "sha512-FE557XdZDrtX8NMIeA8LBJX3dC2M8VGXwfrQWU7LB5SLOajfJIxmSdyL/gU1m64Zs9CBKvm4UAuBp5aJ8OgnrA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.10.tgz",
+ "integrity": "sha512-3BBSbgzuB9ajLoVZk0mGu+EHlBwkusRmeNYdqmznmMc9zGASFjSsxgkNsqmXugpPk00gJ0JNKh/97nxmjctdew==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.10.tgz",
+ "integrity": "sha512-QSX81KhFoZGwenVyPoberggdW1nrQZSvfVDAIUXr3WqLRZGZqWk/P4T8p2SP+de2Sr5HPcvjhcJzEiulKgnxtA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.10.tgz",
+ "integrity": "sha512-AKQM3gfYfSW8XRk8DdMCzaLUFB15dTrZfnX8WXQoOUpUBQ+NaAFCP1kPS/ykbbGYz7rxn0WS48/81l9hFl3u4A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.10.tgz",
+ "integrity": "sha512-7RTytDPGU6fek/hWuN9qQpeGPBZFfB4zZgcz2VK2Z5VpdUxEI8JKYsg3JfO0n/Z1E/6l05n0unDCNc4HnhQGig==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.10.tgz",
+ "integrity": "sha512-5Se0VM9Wtq797YFn+dLimf2Zx6McttsH2olUBsDml+lm0GOCRVebRWUvDtkY4BWYv/3NgzS8b/UM3jQNh5hYyw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.10.tgz",
+ "integrity": "sha512-XkA4frq1TLj4bEMB+2HnI0+4RnjbuGZfet2gs/LNs5Hc7D89ZQBHQ0gL2ND6Lzu1+QVkjp3x1gIcPKzRNP8bXw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.10.tgz",
+ "integrity": "sha512-AVTSBhTX8Y/Fz6OmIVBip9tJzZEUcY8WLh7I59+upa5/GPhh2/aM6bvOMQySspnCCHvFi79kMtdJS1w0DXAeag==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.10.tgz",
+ "integrity": "sha512-fswk3XT0Uf2pGJmOpDB7yknqhVkJQkAQOcW/ccVOtfx05LkbWOaRAtn5SaqXypeKQra1QaEa841PgrSL9ubSPQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.10.tgz",
+ "integrity": "sha512-ah+9b59KDTSfpaCg6VdJoOQvKjI33nTaQr4UluQwW7aEwZQsbMCfTmfEO4VyewOxx4RaDT/xCy9ra2GPWmO7Kw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.10.tgz",
+ "integrity": "sha512-QHPDbKkrGO8/cz9LKVnJU22HOi4pxZnZhhA2HYHez5Pz4JeffhDjf85E57Oyco163GnzNCVkZK0b/n4Y0UHcSw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.10.tgz",
+ "integrity": "sha512-9KpxSVFCu0iK1owoez6aC/s/EdUQLDN3adTxGCqxMVhrPDj6bt5dbrHDXUuq+Bs2vATFBBrQS5vdQ/Ed2P+nbw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@tsus/cli": {
"resolved": "packages/cli",
"link": true
@@ -28,6 +471,10 @@
"resolved": "packages/runtime",
"link": true
},
+ "node_modules/@tsus/v2": {
+ "resolved": "packages/v2",
+ "link": true
+ },
"node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
@@ -38,6 +485,48 @@
"undici-types": "~6.21.0"
}
},
+ "node_modules/esbuild": {
+ "version": "0.25.10",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.10.tgz",
+ "integrity": "sha512-9RiGKvCwaqxO2owP61uQ4BgNborAQskMR6QusfWzQqv7AZOg5oGehdY2pRJMTKuwxd1IDBP4rSbI5lHzU7SMsQ==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.10",
+ "@esbuild/android-arm": "0.25.10",
+ "@esbuild/android-arm64": "0.25.10",
+ "@esbuild/android-x64": "0.25.10",
+ "@esbuild/darwin-arm64": "0.25.10",
+ "@esbuild/darwin-x64": "0.25.10",
+ "@esbuild/freebsd-arm64": "0.25.10",
+ "@esbuild/freebsd-x64": "0.25.10",
+ "@esbuild/linux-arm": "0.25.10",
+ "@esbuild/linux-arm64": "0.25.10",
+ "@esbuild/linux-ia32": "0.25.10",
+ "@esbuild/linux-loong64": "0.25.10",
+ "@esbuild/linux-mips64el": "0.25.10",
+ "@esbuild/linux-ppc64": "0.25.10",
+ "@esbuild/linux-riscv64": "0.25.10",
+ "@esbuild/linux-s390x": "0.25.10",
+ "@esbuild/linux-x64": "0.25.10",
+ "@esbuild/netbsd-arm64": "0.25.10",
+ "@esbuild/netbsd-x64": "0.25.10",
+ "@esbuild/openbsd-arm64": "0.25.10",
+ "@esbuild/openbsd-x64": "0.25.10",
+ "@esbuild/openharmony-arm64": "0.25.10",
+ "@esbuild/sunos-x64": "0.25.10",
+ "@esbuild/win32-arm64": "0.25.10",
+ "@esbuild/win32-ia32": "0.25.10",
+ "@esbuild/win32-x64": "0.25.10"
+ }
+ },
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
@@ -88,6 +577,10 @@
"packages/runtime": {
"name": "@tsus/runtime",
"version": "0.1.0"
+ },
+ "packages/v2": {
+ "name": "@tsus/v2",
+ "version": "0.2.0"
}
}
}
View file
Changedpackage.json+4−1
@@ -9,6 +9,8 @@
"examples": "node scripts/run-examples.mjs",
"docs": "node scripts/docs.mjs",
"docs:check": "node scripts/docs.mjs --check",
+ "typecheck": "tsc -p tsconfig.json && node packages/cli/bin/tsus.js check --v2 examples/60-v2-security-demo/fixed && node packages/cli/bin/tsus.js check --v2 examples/61-v2-basics && node packages/cli/bin/tsus.js check --v2 bench/oncall/v2",
+ "bench": "node bench/oncall/run.ts",
"test": "node scripts/docs.mjs --check && node scripts/run-examples.mjs"
},
"dependencies": {
@@ -16,6 +18,7 @@
"zod": "^3.23.0"
},
"devDependencies": {
- "@types/node": "^22.20.5"
+ "@types/node": "^22.20.5",
+ "esbuild": "^0.25.10"
}
}
View file
Changedpackages/cli/bin/tsus.js+24−2
@@ -3,6 +3,8 @@
// fix edits; human text is a rendering of the same data.
//
// tsus check [dir] [--json]
+// tsus check --v2 [dir] [--json] (v2: plain .ts, see docs/v2/rules.md)
+// tsus audit <file.ts...> [--json] (v2: report-only analysis of existing .ts)
// tsus build [dir] [--json]
// tsus fix [dir] [--unsafe] [--dry-run] [--code TSUSnnn] [--json]
// tsus explain <CODE> [--json] | tsus explain --list
@@ -15,6 +17,9 @@
const USAGE = `usage:
tsus check [dir] [--json] check every .tsus file under dir/src
+ tsus check --v2 [dir] [--json] v2: check the plain .ts files under dir/src (or dir)
+ tsus audit <file.ts...> [--json] [--scope dir] [--permission-fn a,b]
+ v2: report-only findings on existing .ts; changes nothing
tsus build [dir] [--json] check, then compile src/ to dist/
tsus fix [dir] [--unsafe] [--dry-run] [--code TSUSnnn] [--json]
apply the fixes check reports (safe ones by default)
@@ -37,7 +42,8 @@
const i = args.indexOf(name);
return i === -1 ? undefined : args[i + 1];
};
-const positional = args.slice(1).filter((a, i, all) => !a.startsWith("--") && all[i] !== option("--code"));
+const VALUE_FLAGS = ["--code", "--scope", "--permission-fn"];
+const positional = args.slice(1).filter((a, i, all) => !a.startsWith("--") && !VALUE_FLAGS.includes(all[i - 1] ?? ""));
const dirArg = positional[0] ?? ".";
const rootDir = path.resolve(dirArg);
@@ -73,7 +79,23 @@
process.exit(ok ? 0 : 1);
};
-if (command === "check") {
+if (command === "check" && flag("--v2")) {
+ const { checkV2 } = await import("../src/v2/rules.js");
+ report(checkV2(rootDir));
+} else if (command === "audit") {
+ const { auditFiles, renderAudit } = await import("../src/v2/audit.js");
+ if (positional.length === 0) {
+ console.error("usage: tsus audit <file.ts...> [--json] [--scope dir] [--permission-fn a,b]");
+ process.exit(2);
+ }
+ const fns = option("--permission-fn");
+ const result = auditFiles(positional, {
+ scope: option("--scope"),
+ permissionFunctions: fns ? fns.split(",").map((s) => s.trim()).filter(Boolean) : [],
+ });
+ console.log(json ? JSON.stringify(result, null, 2) : renderAudit(result));
+ process.exit(0);
+} else if (command === "check") {
report(checkProject(rootDir));
} else if (command === "build") {
const result = buildProject(rootDir);
View file
Changedpackages/cli/src/explain.js+43−2
@@ -1,6 +1,7 @@
// Renders registry entries for `tsus explain`, docs/rules.md and the code
// table in AGENTS.md. Everything here reads from rules/registry.js.
import { REGISTRY, ruleFor } from "./rules/registry.js";
+import { V2_REGISTRY, V2_RULES, V1_DISPOSITION } from "./v2/registry.js";
const FIX_TEXT = {
safe: "`tsus fix` applies it (behavior is kept).",
@@ -29,14 +30,15 @@
"Good",
indent(rule.good),
"",
+ ...(rule.evidence ? ["Evidence", indent(rule.evidence, " "), ""] : []),
`Hint: ${rule.hint}`,
`Fix: ${FIX_TEXT[rule.fix].replaceAll("`", "")}`,
].join("\n");
export const renderList = () =>
- REGISTRY.map((r) => `${r.code} ${r.name.padEnd(30)} ${r.title}`).join("\n");
+ [...REGISTRY, ...V2_REGISTRY].map((r) => `${r.code} ${r.name.padEnd(30)} ${r.title}`).join("\n");
-export const explain = (code) => ruleFor(code);
+export const explain = (code) => ruleFor(code) ?? V2_RULES.get(code.toUpperCase());
const mdFence = (code) => "```ts\n" + code + "\n```";
@@ -75,4 +77,43 @@
"| Code | Rule | Fix |",
"|---|---|---|",
...REGISTRY.map((r) => `| ${r.code} | ${r.title} | ${r.fix} |`),
+ ].join("\n");
+
+// docs/v2/rules.md: every v2 code with the reason it stays, then what happened to each v1 rule.
+export const renderV2RulesDoc = () =>
+ [
+ "# 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 |",
+ "|---|---|",
+ ...V2_REGISTRY.map((r) => `| ${r.code} | ${r.title} |`),
+ "",
+ ...V2_REGISTRY.flatMap((rule) => [
+ `## ${rule.code} ${rule.name}`,
+ "",
+ `**${rule.title}.** ${rule.why}`,
+ "",
+ `**Why it stays:** ${rule.evidence}`,
+ "",
+ "Rejected:",
+ "",
+ mdFence(rule.bad),
+ "",
+ "Accepted:",
+ "",
+ mdFence(rule.good),
+ "",
+ `Hint: ${rule.hint}`,
+ "",
+ ]),
+ "## What happened to v1's rules",
+ "",
+ "| v1 | v2 | Why |",
+ "|---|---|---|",
+ ...V1_DISPOSITION.map(([rule, fate, why]) => `| ${rule} | ${fate} | ${why} |`),
+ "",
].join("\n");
View file
Addedpackages/cli/src/v2/analysis.js+234−0
@@ -0,0 +1,234 @@
+// Type and syntax helpers shared by the v2 checker (rules.js) and `tsus audit` (audit.js).
+import ts from "typescript";
+
+// --- brands -----------------------------------------------------------------------------------
+//
+// @tsus/v2 brands its types with `unique symbol` keys (index.d.ts). TypeScript names such a
+// property `__@<SymbolName>@<id>`, which is how the checker recognizes the types structurally,
+// through aliases, intersections and generic instantiations.
+const BRAND = /^__@(SqlBrand|PermitBrand|SecretBrand|UntrustedBrand|SafeHtmlBrand|FencedBrand)@\d+$/;
+
+const constituents = (type) => (type.isUnion() ? type.types : [type]);
+
+export const brandsOf = (checker, type) => {
+ const out = new Set();
+ for (const t of constituents(type)) {
+ for (const p of checker.getPropertiesOfType(checker.getApparentType(t))) {
+ const m = BRAND.exec(String(p.escapedName));
+ if (m) out.add(m[1].replace("Brand", ""));
+ }
+ }
+ return out;
+};
+
+export const hasBrand = (checker, type, brand) => brandsOf(checker, type).has(brand);
+
+// True when the type, or a property of it (to `depth` levels), carries the brand: what
+// JSON.stringify(x) or console.log(x) would expose.
+export const containsBrand = (checker, type, brand, depth = 3, seen = new Set()) => {
+ if (hasBrand(checker, type, brand)) return true;
+ if (depth === 0 || seen.has(type)) return false;
+ seen.add(type);
+ for (const t of constituents(type)) {
+ if (!(t.flags & ts.TypeFlags.Object)) continue;
+ if (checker.isArrayType(t) || checker.isTupleType(t)) {
+ for (const arg of checker.getTypeArguments(t)) if (containsBrand(checker, arg, brand, depth - 1, seen)) return true;
+ continue;
+ }
+ const props = checker.getPropertiesOfType(t);
+ if (props.length > 60) continue;
+ for (const p of props) {
+ if (BRAND.test(String(p.escapedName))) continue;
+ const decl = p.valueDeclaration ?? p.declarations?.[0];
+ if (!decl) continue;
+ // Methods and functions do not serialize.
+ if (ts.isMethodDeclaration(decl) || ts.isMethodSignature(decl)) continue;
+ const pt = checker.getTypeOfSymbolAtLocation(p, decl);
+ if (pt.getCallSignatures().length > 0) continue;
+ if (containsBrand(checker, pt, brand, depth - 1, seen)) return true;
+ }
+ }
+ return false;
+};
+
+// --- shapes -----------------------------------------------------------------------------------
+
+export const isThenable = (checker, type) =>
+ constituents(type).some((t) => {
+ const then = checker.getPropertyOfType(checker.getApparentType(t), "then");
+ return then !== undefined && checker.getTypeOfSymbol(then).getCallSignatures().length > 0;
+ });
+
+export const awaitedType = (checker, type) => (checker.getAwaitedType ? checker.getAwaitedType(type) ?? type : type);
+
+// A v2 Result (`{ ok: true, value } | { ok: false, error }`), recognized structurally.
+export const isResultType = (checker, type) => {
+ const parts = constituents(type).filter((t) => !(t.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)));
+ if (parts.length < 2) return false;
+ let ok = false;
+ let err = false;
+ for (const t of parts) {
+ const flag = checker.getPropertyOfType(t, "ok");
+ if (!flag) return false;
+ const ft = checker.getTypeOfSymbol(flag);
+ if (ft.flags & ts.TypeFlags.BooleanLiteral) {
+ const name = checker.typeToString(ft);
+ if (name === "true" && checker.getPropertyOfType(t, "value")) ok = true;
+ else if (name === "false" && checker.getPropertyOfType(t, "error")) err = true;
+ else return false;
+ } else {
+ return false;
+ }
+ }
+ return ok && err;
+};
+
+// The finite set of literal values a type can hold, or undefined when it is not finite.
+export const literalMembers = (checker, type) => {
+ const out = [];
+ for (const t of constituents(type)) {
+ if (t.flags & ts.TypeFlags.StringLiteral) out.push(JSON.stringify(t.value));
+ else if (t.flags & ts.TypeFlags.NumberLiteral) out.push(String(t.value));
+ else if (t.flags & ts.TypeFlags.BooleanLiteral) out.push(checker.typeToString(t));
+ else if (t.flags & ts.TypeFlags.EnumLiteral && t.value !== undefined) out.push(typeof t.value === "string" ? JSON.stringify(t.value) : String(t.value));
+ else if (t.flags & ts.TypeFlags.Undefined) out.push("undefined");
+ else if (t.flags & ts.TypeFlags.Null) out.push("null");
+ else return undefined;
+ }
+ return out.length > 1 || (out.length === 1 && out[0] !== "undefined") ? out : undefined;
+};
+
+const FALSY_PRONE = ts.TypeFlags.String | ts.TypeFlags.Number | ts.TypeFlags.BigInt;
+
+// An optional value whose present value can be falsy: `string | undefined`, `number | null`,
+// `"" | "x" | undefined`. A truthiness test treats "" and 0 like absent.
+export const falsyGap = (checker, type, kinds = FALSY_PRONE) => {
+ const parts = constituents(type);
+ const nullish = parts.some((t) => t.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null));
+ if (!nullish) return undefined;
+ for (const t of parts) {
+ if (t.flags & kinds) return checker.typeToString(t);
+ if (t.flags & ts.TypeFlags.StringLiteral && t.value === "" && kinds & ts.TypeFlags.String) return '""';
+ if (t.flags & ts.TypeFlags.NumberLiteral && t.value === 0 && kinds & ts.TypeFlags.Number) return "0";
+ }
+ return undefined;
+};
+
+// --- constant strings ---------------------------------------------------------------------------
+//
+// A query string is constant when every piece of it is program text: string literals, templates
+// and concatenations of constants, consts initialized with constants, and anything whose type is a
+// string literal (or a union of them: a value picked from a fixed set). A query that is not
+// constant is built at runtime from something else, which is where injection comes from.
+export const nonConstantParts = (checker, expr, seen = new Set()) => {
+ const e = skipParens(expr);
+ if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e) || ts.isNumericLiteral(e)) return [];
+ if (ts.isTemplateExpression(e)) return e.templateSpans.flatMap((s) => nonConstantParts(checker, s.expression, seen));
+ if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.PlusToken) {
+ return [...nonConstantParts(checker, e.left, seen), ...nonConstantParts(checker, e.right, seen)];
+ }
+ if (ts.isConditionalExpression(e)) return [...nonConstantParts(checker, e.whenTrue, seen), ...nonConstantParts(checker, e.whenFalse, seen)];
+ const type = checker.getTypeAtLocation(e);
+ if (constituents(type).every((t) => t.flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral))) return [];
+ if (constituents(type).every((t) => t.flags & (ts.TypeFlags.NumberLike | ts.TypeFlags.BooleanLike))) return [];
+ if (ts.isIdentifier(e) || ts.isPropertyAccessExpression(e)) {
+ const init = constInitializer(checker, e);
+ if (init && !seen.has(init)) {
+ seen.add(init);
+ return nonConstantParts(checker, init, seen);
+ }
+ }
+ // A placeholder list: xs.map(() => "?").join(", "). Its length depends on data, its text does not.
+ if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && e.expression.name.text === "join" && e.arguments.every((a) => nonConstantParts(checker, a, seen).length === 0)) {
+ const inner = skipParens(e.expression.expression);
+ if (ts.isCallExpression(inner) && ts.isPropertyAccessExpression(inner.expression) && inner.expression.name.text === "map" && inner.arguments[0]) {
+ const cb = skipParens(inner.arguments[0]);
+ if ((ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)) && !ts.isBlock(cb.body) && nonConstantParts(checker, cb.body, seen).length === 0) return [];
+ }
+ }
+ // [constants].join(constant)
+ if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && e.expression.name.text === "join") {
+ const target = skipParens(e.expression.expression);
+ if (ts.isArrayLiteralExpression(target)) {
+ return [...target.elements.flatMap((el) => nonConstantParts(checker, el, seen)), ...e.arguments.flatMap((a) => nonConstantParts(checker, a, seen))];
+ }
+ }
+ return [e];
+};
+
+export const skipParens = (e) => {
+ let n = e;
+ while (ts.isParenthesizedExpression(n) || ts.isAsExpression(n) || ts.isSatisfiesExpression?.(n) || ts.isNonNullExpression(n)) n = n.expression;
+ return n;
+};
+
+const resolveSymbol = (checker, node) => {
+ let sym = checker.getSymbolAtLocation(node);
+ if (sym && sym.flags & ts.SymbolFlags.Alias) sym = checker.getAliasedSymbol(sym);
+ return sym;
+};
+
+// The initializer of a `const` (or of a property of a const object literal) the expression names.
+const constInitializer = (checker, e) => {
+ const sym = resolveSymbol(checker, ts.isPropertyAccessExpression(e) ? e.name : e);
+ const decl = sym?.valueDeclaration;
+ if (!decl) return undefined;
+ if (ts.isVariableDeclaration(decl) && decl.initializer && ts.isVariableDeclarationList(decl.parent) && decl.parent.flags & ts.NodeFlags.Const) {
+ return decl.initializer;
+ }
+ if (ts.isPropertyAssignment(decl) && ts.isObjectLiteralExpression(decl.parent)) {
+ let owner = decl.parent.parent;
+ while (owner && (ts.isAsExpression(owner) || ts.isParenthesizedExpression(owner) || ts.isSatisfiesExpression?.(owner))) owner = owner.parent;
+ if (owner && ts.isVariableDeclaration(owner) && owner.parent.flags & ts.NodeFlags.Const) return decl.initializer;
+ }
+ return undefined;
+};
+
+// Static text that reads as SQL: a statement keyword, a clause keyword, or a placeholder next to
+// an operator. Used to tell a query being assembled from other strings.
+export const SQL_TEXT = /\b(SELECT|INSERT INTO|UPDATE|DELETE FROM)\b|\b(WHERE|FROM|JOIN|ORDER BY|GROUP BY)\b|\b(AND|OR|NOT|LIKE|IN|IS)\b[^\n]*\?|\?\s*(AND|OR)\b/;
+
+// --- calls --------------------------------------------------------------------------------------
+
+export const calleeName = (call) => {
+ const c = skipParens(call.expression);
+ if (ts.isIdentifier(c)) return c.text;
+ if (ts.isPropertyAccessExpression(c)) return c.name.text;
+ return "";
+};
+
+export const calleeText = (call, sf) => skipParens(call.expression).getText(sf);
+
+export const isLogCall = (call, sf) => {
+ const text = calleeText(call, sf);
+ return /^console\.\w+$/.test(text) || /(^|\.)(log|logger|logEvent)$/.test(text) || /(^|\.)(log|logger)\.(info|warn|error|debug|trace|log)$/.test(text);
+};
+
+export const position = (sf, node) => {
+ const start = node.getStart(sf);
+ const end = node.getEnd();
+ const a = sf.getLineAndCharacterOfPosition(start);
+ const b = sf.getLineAndCharacterOfPosition(end);
+ return { start, end, line: a.line + 1, col: a.character + 1, endLine: b.line + 1, endCol: b.character + 1 };
+};
+
+export const isBoundaryFile = (fileName) => /\.boundary\.(ts|mts|tsx)$/.test(fileName);
+export const isAccessFile = (fileName) => /\.access\.(ts|mts|tsx)$/.test(fileName);
+
+export const enclosingFunction = (node) => {
+ for (let n = node.parent; n; n = n.parent) if (ts.isFunctionLike(n)) return n;
+ return undefined;
+};
+
+export const functionName = (fn, sf) => {
+ if (!fn) return "<module>";
+ if (fn.name && (ts.isIdentifier(fn.name) || ts.isStringLiteral(fn.name))) return fn.name.text;
+ const p = fn.parent;
+ if (p && ts.isVariableDeclaration(p) && ts.isIdentifier(p.name)) return p.name.text;
+ if (p && ts.isPropertyAssignment(p)) return p.name.getText(sf);
+ if (p && ts.isCallExpression(p)) {
+ const callee = calleeText(p, sf).replace(/\s+/g, " ");
+ return `<callback of ${callee.length > 40 ? `...${callee.slice(-37)}` : callee}>`;
+ }
+ return "<anonymous>";
+};
View file
Addedpackages/cli/src/v2/audit.js+383−0
@@ -0,0 +1,383 @@
+// `tsus audit <file.ts...>`: report-only analysis of existing plain TypeScript. It reads the
+// project's own tsconfig so types resolve, never writes a file, and lists, ranked, the places
+// where the bug classes v2 targets can hide:
+//
+// high string-built SQL a query whose text is not a compile-time constant
+// high unchecked permission a function that reads the database, reachable from an entry
+// point (no callers, or passed around as a value) along a path
+// on which no permission check runs
+// medium ignored promise a promise statement nobody awaits, returns or handles
+// medium swallowed error an empty catch, or a .catch handler that drops the error
+// medium non-exhaustive switch a switch over a finite union with no default, missing members
+// medium implicit null (index) an index read that is undefined-unsafe under noUncheckedIndexedAccess
+// low swallowed error a catch that neither uses, logs nor rethrows the error
+// low implicit null a truthiness test on an optional string or number, or a ! assertion
+// low cast an `as` assertion (medium for as any and double casts)
+//
+// Every finding is a lead, not a verdict: the report says what was seen and why it was flagged.
+import path from "node:path";
+import fs from "node:fs";
+import ts from "typescript";
+import { SQL_TEXT, calleeName, calleeText, falsyGap, functionName, isThenable, literalMembers, nonConstantParts, position, skipParens } from "./analysis.js";
+import { createProgram, findConfigFor, listTsFiles, optionsFrom } from "./program.js";
+
+const SEVERITY = { high: 0, medium: 1, low: 2 };
+const CATEGORY_ORDER = ["string-built-sql", "unchecked-permission", "ignored-promise", "swallowed-error", "non-exhaustive-switch", "implicit-null", "cast"];
+
+// Names that look like a permission check. Generic on purpose; --permission-fn adds a project's own.
+const PERMISSION_NAME = /^(authori[sz]e\w*|can[A-Z]\w*|require[A-Z]\w*|assert[A-Z]\w*|ensure[A-Z]\w*|check\w*(Access|Permission|Auth)\w*|is(Owner|Admin|Member)\w*|decide\w*|\w*[Pp]ermi(t|ssion)s?\w*|\w*Access)$/;
+
+const UNCHECKED_INDEX_CODES = new Set([2532, 18048, 2345, 2322, 2339, 18047, 2538, 2769]);
+
+const DB_METHODS = new Set(["prepare", "exec", "batch"]);
+const dbReceiver = (checker, expr) => {
+ const t = checker.getApparentType(checker.getTypeAtLocation(expr));
+ return checker.getPropertyOfType(t, "prepare") !== undefined && (checker.getPropertyOfType(t, "batch") !== undefined || checker.getPropertyOfType(t, "exec") !== undefined);
+};
+
+const isDbCall = (checker, call) =>
+ ts.isPropertyAccessExpression(call.expression) && DB_METHODS.has(call.expression.name.text) && dbReceiver(checker, call.expression.expression);
+
+// True when the template is (part of) the argument of a database call, reported there instead.
+const queryArgument = (checker, node) => {
+ for (let n = node, p = node.parent; p; n = p, p = p.parent) {
+ if (ts.isParenthesizedExpression(p) || (ts.isBinaryExpression(p) && p.operatorToken.kind === ts.SyntaxKind.PlusToken) || ts.isConditionalExpression(p)) continue;
+ return ts.isCallExpression(p) && p.arguments[0] === n && isDbCall(checker, p);
+ }
+ return false;
+};
+
+const resolve = (checker, node) => {
+ let sym = checker.getSymbolAtLocation(node);
+ if (sym && sym.flags & ts.SymbolFlags.Alias) sym = checker.getAliasedSymbol(sym);
+ return sym;
+};
+
+const functionOfSymbol = (sym) => {
+ const decl = sym?.valueDeclaration;
+ if (!decl) return undefined;
+ if (ts.isFunctionDeclaration(decl) || ts.isMethodDeclaration(decl) || ts.isFunctionExpression(decl) || ts.isArrowFunction(decl)) return decl.body ? decl : undefined;
+ if ((ts.isVariableDeclaration(decl) || ts.isPropertyAssignment(decl) || ts.isPropertyDeclaration(decl)) && decl.initializer) {
+ const init = skipParens(decl.initializer);
+ if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) return init;
+ }
+ return undefined;
+};
+
+const enclosingFn = (node) => {
+ for (let n = node.parent; n; n = n.parent) if (ts.isFunctionLike(n) && n.body) return n;
+ return undefined;
+};
+
+// The call graph the permission analysis walks: every function in scope, the calls it makes (with
+// where they are in its body), the checks it calls, and whether it touches the database. A
+// function defined inside another counts as called by it at its definition (callbacks, helpers).
+//
+// "Checked" means: the function that reads calls something named like a check (anywhere: filtering
+// the rows it read counts), or a helper that does (a function that does not touch the database
+// itself); or else every caller does so before the call that leads to the read. A check in a
+// caller that runs after that call, or another data function's check of its own rows, does not
+// count.
+const buildCallGraph = (program, checker, scopeFiles, permissionName) => {
+ const nodes = new Map();
+ const info = (fn) => {
+ let i = nodes.get(fn);
+ if (!i) {
+ i = { fn, calls: [], sites: [], checks: [], db: false, escapes: false };
+ nodes.set(fn, i);
+ }
+ return i;
+ };
+ for (const sf of program.getSourceFiles()) {
+ if (!scopeFiles.has(path.resolve(sf.fileName))) continue;
+ const visit = (node) => {
+ if (ts.isFunctionLike(node) && node.body) {
+ info(node);
+ const parent = enclosingFn(node);
+ if (parent) {
+ info(parent).calls.push({ callee: node, pos: node.getStart(sf) });
+ info(node).sites.push({ caller: parent, pos: node.getStart(sf) });
+ }
+ }
+ if (ts.isCallExpression(node)) {
+ const owner = enclosingFn(node) ?? sf;
+ const pos = node.getStart(sf);
+ const name = calleeName(node);
+ if (permissionName(name)) info(owner).checks.push({ name, pos });
+ if (isDbCall(checker, node)) info(owner).db = true;
+ const target = skipParens(node.expression);
+ const callee = functionOfSymbol(resolve(checker, ts.isPropertyAccessExpression(target) ? target.name : target));
+ if (callee) {
+ info(owner).calls.push({ callee, pos });
+ info(callee).sites.push({ caller: owner, pos });
+ }
+ } else if (ts.isIdentifier(node)) {
+ // A function used as a value (a route table entry, a callback): its callers are unknown.
+ const p = node.parent;
+ const declaring = (ts.isVariableDeclaration(p) || ts.isFunctionDeclaration(p) || ts.isPropertyAssignment(p) || ts.isImportSpecifier(p) || ts.isExportSpecifier(p) || ts.isParameter(p) || ts.isMethodDeclaration(p)) && p.name === node;
+ const called = (ts.isCallExpression(p) && p.expression === node) || (ts.isPropertyAccessExpression(p) && p.name === node && ts.isCallExpression(p.parent) && p.parent.expression === p);
+ if (!declaring && !called && !ts.isImportClause(p)) {
+ const callee = functionOfSymbol(resolve(checker, node));
+ if (callee && callee !== enclosingFn(node)) info(callee).escapes = true;
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ }
+ // Whether a helper performs a check somewhere in its body (through other helpers).
+ const memo = new Map();
+ const helperChecks = (fn, stack = new Set()) => {
+ if (memo.has(fn)) return memo.get(fn);
+ const i = nodes.get(fn);
+ if (!i || i.db || stack.has(fn)) return undefined;
+ stack.add(fn);
+ let w;
+ if (i.checks.length > 0) w = [`${i.checks[0].name}()`];
+ else {
+ for (const c of i.calls) {
+ const sub = helperChecks(c.callee, stack);
+ if (sub) {
+ w = [fnLabel(c.callee), ...sub].filter((x, k, all) => k === 0 || x !== all[k - 1]);
+ break;
+ }
+ }
+ }
+ stack.delete(fn);
+ memo.set(fn, w);
+ return w;
+ };
+ // The check that runs in fn before pos, as a witness chain, or undefined.
+ const checkedBefore = (fn, pos) => {
+ const i = nodes.get(fn);
+ if (!i) return undefined;
+ const direct = i.checks.find((c) => c.pos < pos);
+ if (direct) return [fnLabel(fn), `${direct.name}()`];
+ for (const c of i.calls) {
+ if (c.pos >= pos) continue;
+ const w = helperChecks(c.callee);
+ if (w) return [fnLabel(fn), ...(w[0].endsWith("()") ? w : [fnLabel(c.callee), ...w].slice(1))];
+ }
+ return undefined;
+ };
+ const isEntry = (i) => i.sites.length === 0 || i.escapes || i.sites.some((s) => ts.isSourceFile(s.caller));
+ // A path from an entry to (fn, pos) on which no check runs first, or undefined.
+ const uncheckedPath = (fn, pos, stack = new Set()) => {
+ if (checkedBefore(fn, pos) || stack.has(fn)) return undefined;
+ // The check itself reads the database to decide (a role, a visibility flag).
+ if (permissionName(functionName(fn, fn.getSourceFile()))) return undefined;
+ const i = nodes.get(fn);
+ if (!i || isEntry(i)) return [fn];
+ stack.add(fn);
+ for (const s of i.sites) {
+ const p = uncheckedPath(s.caller, s.pos, stack);
+ if (p) {
+ stack.delete(fn);
+ return [...p, fn];
+ }
+ }
+ stack.delete(fn);
+ return undefined;
+ };
+ // How (fn, pos) is checked on every path: here, or at each call site in turn.
+ const coverage = (fn, pos, depth = 0) => {
+ const here = checkedBefore(fn, pos);
+ if (here) return here.join(" -> ");
+ const i = nodes.get(fn);
+ if (!i || depth > 3) return "checked further up";
+ return [...new Set(i.sites.map((s) => coverage(s.caller, s.pos, depth + 1)))].join("; ");
+ };
+ return { nodes, uncheckedPath, coverage };
+};
+
+function fnLabel(fn) {
+ const sf = fn.getSourceFile();
+ const { line } = position(sf, fn);
+ return `${functionName(fn, sf)} (${path.basename(sf.fileName)}:${line})`;
+}
+
+const defaultScope = (target) => {
+ for (let d = path.dirname(target); ; d = path.dirname(d)) {
+ if (fs.existsSync(path.join(d, "package.json"))) return fs.existsSync(path.join(d, "src")) ? path.join(d, "src") : d;
+ if (path.dirname(d) === d) return path.dirname(target);
+ }
+};
+
+export const auditFiles = (inputs, { scope, permissionFunctions = [] } = {}) => {
+ const targets = inputs.map((f) => path.resolve(f)).filter((f) => fs.existsSync(f));
+ if (targets.length === 0) return { files: [], findings: [], summary: {} };
+ const configPath = findConfigFor(targets[0]);
+ // The call graph needs the callers too: by default every .ts file of the package the first
+ // target lives in (src/ of the nearest directory above it with a package.json).
+ const scopeDir = scope ? path.resolve(scope) : defaultScope(targets[0]);
+ const scopeFiles = [...new Set([...listTsFiles(scopeDir), ...targets])];
+ // The project's options, with noUncheckedIndexedAccess off; a second program with it on shows
+ // the index reads that assume a value is there.
+ const options = { ...optionsFrom(configPath), noUncheckedIndexedAccess: false };
+ const program = createProgram(scopeFiles, options);
+ const checker = program.getTypeChecker();
+ const indexProgram = createProgram(scopeFiles, { ...options, noUncheckedIndexedAccess: true }, program);
+ const extra = new Set(permissionFunctions);
+ const permissionName = (n) => extra.has(n) || PERMISSION_NAME.test(n);
+ const graph = buildCallGraph(program, checker, new Set(scopeFiles.map((f) => path.resolve(f))), permissionName);
+ const base = path.dirname(configPath ?? targets[0]);
+
+ const findings = [];
+ const checkedAccess = [];
+ for (const target of targets) {
+ const sf = program.getSourceFile(target);
+ if (!sf) continue;
+ const file = path.relative(base, sf.fileName);
+ const add = (severity, category, node, message, detail) =>
+ findings.push({ severity, category, file, ...position(sf, node), function: functionName(enclosingFn(node), sf), message, ...(detail ? { detail } : {}) });
+
+ // Implicit null paths that only noUncheckedIndexedAccess sees.
+ if (indexProgram) {
+ const before = new Set(program.getSemanticDiagnostics(sf).map((d) => `${d.start}:${d.code}`));
+ const isf = indexProgram.getSourceFile(target);
+ const lines = new Set();
+ for (const d of isf ? indexProgram.getSemanticDiagnostics(isf) : []) {
+ if (before.has(`${d.start}:${d.code}`) || !UNCHECKED_INDEX_CODES.has(d.code) || d.start === undefined) continue;
+ // One finding per line: a single unchecked read cascades into several errors.
+ const line = sf.getLineAndCharacterOfPosition(d.start).line;
+ if (lines.has(line)) continue;
+ lines.add(line);
+ const start = d.start;
+ const node = { getStart: () => start, getEnd: () => start + (d.length ?? 0), parent: undefined };
+ const inner = findNode(sf, start);
+ findings.push({ severity: "medium", category: "implicit-null", file, ...position(sf, node), function: functionName(inner ? enclosingFn(inner) : undefined, sf), message: "an index read is used as if it were always present", detail: `TS${d.code}: ${ts.flattenDiagnosticMessageText(d.messageText, " ").slice(0, 200)}` });
+ }
+ }
+
+ // Templates that feed a query reported at its database call are not reported again.
+ const feedsQuery = new Set();
+ const prepass = (node) => {
+ if (ts.isCallExpression(node) && isDbCall(checker, node) && node.arguments[0]) nonConstantParts(checker, node.arguments[0], feedsQuery);
+ ts.forEachChild(node, prepass);
+ };
+ prepass(sf);
+ const permissionReported = new Set();
+ const visit = (node) => {
+ if (ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) {
+ const typeText = node.type.getText(sf);
+ if (typeText !== "const") {
+ const inner = skipParens(node.expression);
+ const double = ts.isAsExpression(node.expression) || (ts.isParenthesizedExpression(node.expression) && ts.isAsExpression(inner));
+ const sev = typeText === "any" || double ? "medium" : "low";
+ add(sev, "cast", node, `cast to ${typeText.replace(/\s+/g, " ").slice(0, 80)}${double ? " (double cast)" : ""}`, `from ${checker.typeToString(checker.getTypeAtLocation(node.expression)).slice(0, 120)}`);
+ }
+ } else if (ts.isNonNullExpression(node)) {
+ add("low", "implicit-null", node, `non-null assertion ${node.getText(sf).slice(0, 60)}`);
+ } else if (ts.isSwitchStatement(node) && !node.caseBlock.clauses.some((c) => ts.isDefaultClause(c))) {
+ const members = literalMembers(checker, checker.getTypeAtLocation(node.expression));
+ if (members) {
+ const covered = new Set(node.caseBlock.clauses.flatMap((c) => literalMembers(checker, checker.getTypeAtLocation(c.expression)) ?? []));
+ const missing = members.filter((m) => !covered.has(m));
+ if (missing.length) add("medium", "non-exhaustive-switch", node.expression, `switch over ${node.expression.getText(sf)} has no default and misses ${missing.join(", ")}`);
+ }
+ } else if (ts.isCatchClause(node)) {
+ const stmts = node.block.statements;
+ const v = node.variableDeclaration?.name;
+ const text = node.block.getText(sf);
+ const uses = v && ts.isIdentifier(v) ? new RegExp(`\\b${v.text}\\b`).test(text) : false;
+ const logs = /\b(console\.\w+|log\w*|logger|report\w*|captureException|throw)\b/.test(text);
+ if (stmts.length === 0) add("medium", "swallowed-error", node, "empty catch: the error is dropped");
+ else if (!uses && !logs) add("low", "swallowed-error", node, "catch neither uses, logs nor rethrows the error", text.replace(/\s+/g, " ").slice(0, 120));
+ } else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "catch" && node.arguments[0]) {
+ const h = skipParens(node.arguments[0]);
+ if (ts.isArrowFunction(h) || ts.isFunctionExpression(h)) {
+ const bodyText = h.body.getText(sf);
+ const param = h.parameters[0]?.name;
+ const uses = param && ts.isIdentifier(param) ? new RegExp(`\\b${param.text}\\b`).test(bodyText) : false;
+ const logs = /\b(console\.\w+|log\w*|logger|report\w*|throw)\b/.test(bodyText);
+ const empty = ts.isBlock(h.body) && h.body.statements.length === 0;
+ if (empty) add("medium", "swallowed-error", node.expression.name, ".catch(() => {}) drops the error");
+ else if (!uses && !logs) add("low", "swallowed-error", node.expression.name, ".catch handler replaces the error without looking at it", bodyText.replace(/\s+/g, " ").slice(0, 120));
+ }
+ } else if (ts.isExpressionStatement(node)) {
+ const e = skipParens(node.expression);
+ const assignment = ts.isBinaryExpression(e) && e.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && e.operatorToken.kind <= ts.SyntaxKind.LastAssignment;
+ const handled = ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && (e.expression.name.text === "catch" || (e.expression.name.text === "then" && e.arguments.length >= 2));
+ if (!ts.isVoidExpression(e) && !ts.isAwaitExpression(e) && !assignment && !handled && isThenable(checker, checker.getTypeAtLocation(e))) {
+ add("medium", "ignored-promise", e, `promise not awaited: ${e.getText(sf).replace(/\s+/g, " ").slice(0, 80)}`);
+ }
+ } else if (ts.isIfStatement(node) || ts.isWhileStatement(node) || ts.isConditionalExpression(node) || (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.ExclamationToken) || (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken)) {
+ const tested = ts.isIfStatement(node) || ts.isWhileStatement(node) ? node.expression : ts.isConditionalExpression(node) ? node.condition : ts.isPrefixUnaryExpression(node) ? node.operand : node.left;
+ const e = skipParens(tested);
+ const compound = ts.isBinaryExpression(e) && (e.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken || e.operatorToken.kind === ts.SyntaxKind.BarBarToken);
+ if (!compound && !(ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.ExclamationToken)) {
+ const gap = falsyGap(checker, checker.getTypeAtLocation(e));
+ if (gap) add("low", "implicit-null", e, `truthiness test on ${e.getText(sf).slice(0, 60)}: a present ${gap} that is falsy reads as absent`);
+ }
+ }
+ if (ts.isTemplateExpression(node) && !ts.isTaggedTemplateExpression(node.parent) && SQL_TEXT.test([node.head.text, ...node.templateSpans.map((x) => x.literal.text)].join(" ")) && !queryArgument(checker, node) && !feedsQuery.has(node)) {
+ const parts = nonConstantParts(checker, node);
+ if (parts.length > 0) {
+ add("medium", "string-built-sql", node, "SQL text assembled in a template; it reaches a query elsewhere", `dynamic parts: ${parts.map((p) => p.getText(sf).replace(/\s+/g, " ").slice(0, 60)).join(" | ")}`);
+ }
+ }
+ if (ts.isCallExpression(node) && isDbCall(checker, node)) {
+ if (node.expression.name.text !== "batch" && node.arguments[0]) {
+ const parts = nonConstantParts(checker, node.arguments[0]);
+ if (parts.length > 0) {
+ add("high", "string-built-sql", node.arguments[0], `query text built at runtime (${calleeText(node, sf)})`, `dynamic parts: ${parts.map((p) => p.getText(sf).replace(/\s+/g, " ").slice(0, 60)).join(" | ")}`);
+ }
+ }
+ const fn = enclosingFn(node);
+ if (fn && !permissionReported.has(fn)) {
+ permissionReported.add(fn);
+ // In the function that reads, a check anywhere counts (filtering the rows it read is a
+ // check); in its callers, the check must come before the call.
+ const at = Number.MAX_SAFE_INTEGER;
+ const p = graph.uncheckedPath(fn, at);
+ if (!p) checkedAccess.push({ file, line: position(sf, node).line, function: functionName(fn, sf), checkedBy: graph.coverage(fn, at) });
+ if (p) {
+ const entry = graph.nodes.get(p[0]);
+ const why = entry?.escapes ? "is passed around as a value" : entry?.sites.length ? "runs at module load" : "has no callers in scope";
+ add("high", "unchecked-permission", node, `database access with no permission check before it on the path ${p.map(fnLabel).join(" -> ")}`, `the entry ${fnLabel(p[0])} ${why}`);
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ }
+ findings.sort((a, b) => SEVERITY[a.severity] - SEVERITY[b.severity] || CATEGORY_ORDER.indexOf(a.category) - CATEGORY_ORDER.indexOf(b.category) || (a.file < b.file ? -1 : a.file > b.file ? 1 : a.start - b.start));
+ findings.forEach((f, i) => (f.rank = i + 1));
+ const summary = {};
+ for (const f of findings) summary[`${f.severity} ${f.category}`] = (summary[`${f.severity} ${f.category}`] ?? 0) + 1;
+ return {
+ config: configPath ? path.relative(process.cwd(), configPath) : undefined,
+ scope: path.relative(process.cwd(), scopeDir) || ".",
+ files: targets.map((t) => path.relative(base, t)),
+ findings: findings.map(({ start, end, endLine, endCol, ...rest }) => rest),
+ summary,
+ // Database access the permission analysis considered checked, with the check it found.
+ checkedAccess,
+ };
+};
+
+const findNode = (sf, pos) => {
+ let found;
+ const visit = (n) => {
+ if (n.getStart(sf) <= pos && pos < n.getEnd()) {
+ found = n;
+ ts.forEachChild(n, visit);
+ }
+ };
+ ts.forEachChild(sf, visit);
+ return found;
+};
+
+export const renderAudit = (r) => {
+ const lines = [`tsus audit: ${r.files.length} file(s), ${r.findings.length} finding(s); report only, nothing was changed`];
+ if (r.config) lines.push(`types from ${r.config}; callers searched in ${r.scope}`);
+ for (const f of r.findings) {
+ lines.push(`${String(f.rank).padStart(3)}. ${f.severity.padEnd(6)} ${f.category.padEnd(21)} ${f.file}:${f.line}:${f.col} (${f.function}) ${f.message}`);
+ if (f.detail) lines.push(` ${f.detail}`);
+ }
+ lines.push("", "summary:");
+ for (const [k, n] of Object.entries(r.summary)) lines.push(` ${String(n).padStart(3)} ${k}`);
+ if (r.checkedAccess?.length) lines.push(` ${String(r.checkedAccess.length).padStart(3)} database accesses found behind a permission check (--json lists each and the check)`);
+ return lines.join("\n");
+};
View file
Addedpackages/cli/src/v2/program.js+69−0
@@ -0,0 +1,69 @@
+// Builds the ts.Program that v2's checker and `tsus audit` analyze: plain .ts files, the
+// project's own tsconfig when there is one (so its types and paths resolve), and, for the
+// checker, the options v2 requires on top (strict, noUncheckedIndexedAccess).
+import fs from "node:fs";
+import path from "node:path";
+import ts from "typescript";
+
+export const DEFAULT_OPTIONS = {
+ strict: true,
+ noEmit: true,
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ allowImportingTsExtensions: true,
+ skipLibCheck: true,
+ lib: ["lib.es2023.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts"],
+};
+
+// What v2 turns on whatever the project says.
+export const V2_OPTIONS = { strict: true, noUncheckedIndexedAccess: true, noEmit: true };
+
+const SKIP_DIRS = new Set(["node_modules", "dist", ".git", ".wrangler", ".examples-tmp"]);
+
+export const listTsFiles = (dir) => {
+ const out = [];
+ const walk = (d) => {
+ for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
+ if (entry.isDirectory()) {
+ if (!SKIP_DIRS.has(entry.name)) walk(path.join(d, entry.name));
+ } else if (/\.(ts|mts|tsx)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
+ out.push(path.join(d, entry.name));
+ }
+ }
+ };
+ walk(dir);
+ return out.sort();
+};
+
+const parseConfig = (configPath) => {
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
+ if (read.error) return undefined;
+ return ts.parseJsonConfigFileContent(read.config, ts.sys, path.dirname(configPath), undefined, configPath);
+};
+
+// The tsconfig that covers `file`: walking up from its directory, the first directory with any
+// tsconfig*.json, and in it the config whose file list includes the file (else tsconfig.json).
+export const findConfigFor = (file) => {
+ const abs = path.resolve(file);
+ for (let dir = path.dirname(abs); ; dir = path.dirname(dir)) {
+ const configs = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^tsconfig.*\.json$/.test(f)).sort() : [];
+ if (configs.length > 0) {
+ for (const name of configs) {
+ const parsed = parseConfig(path.join(dir, name));
+ if (parsed && parsed.fileNames.some((f) => path.resolve(f) === abs)) return path.join(dir, name);
+ }
+ if (configs.includes("tsconfig.json")) return path.join(dir, "tsconfig.json");
+ }
+ if (path.dirname(dir) === dir) return undefined;
+ }
+};
+
+export const optionsFrom = (configPath) => {
+ if (!configPath) return { ...DEFAULT_OPTIONS };
+ const parsed = parseConfig(configPath);
+ return parsed ? { ...parsed.options, noEmit: true } : { ...DEFAULT_OPTIONS };
+};
+
+export const createProgram = (rootNames, options, oldProgram) =>
+ ts.createProgram({ rootNames, options, oldProgram });
View file
Addedpackages/cli/src/v2/registry.js+354−0
@@ -0,0 +1,354 @@
+// Every TSUS v2 code: what `tsus check --v2` reports on plain .ts files, with the reason the
+// rule is in v2 at all. docs/v2/rules.md is generated from this file (npm run docs), and
+// `tsus explain` reads it, so the docs cannot drift from the checker.
+//
+// The `evidence` field is the point of v2: a rule stays only when there is a bug it catches. The
+// sources it cites:
+// experiment: the judge's report on the search-query feature built twice from one spec, plain
+// strict TS (A) against TSUS v1 (B): a tie on correctness, B +28% tool calls,
+// +65% code, a 51-line adapter, and zero diagnostics from the v1 checker.
+// pilot: the on-call watcher's decision rules rewritten in v1 (rebasely docs/v2/tsus-pilot.md):
+// the rewrite exposed real bugs; Option/Result wrappers cost 2 to 6x on the hot path.
+// risks: the risks the review of AI-written Rebasely code kept finding: SQL injection,
+// permission scoping, secrets and untrusted input. v1 had nothing for any of them.
+
+const ENTRIES = [
+ {
+ code: "TSUS500",
+ name: "type-error",
+ title: "Type error",
+ message: "TypeScript error",
+ hint: "Read tsCode and the message; v2 type-checks with strict and noUncheckedIndexedAccess on.",
+ why: "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.",
+ evidence: "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.",
+ bad: `const firstWord = (s: string): string => {
+ const parts = s.split(" ");
+ return parts[0].toUpperCase(); // TS2532 under noUncheckedIndexedAccess
+};`,
+ good: `const firstWord = (s: string): string => {
+ const first = s.split(" ")[0];
+ return first === undefined ? "" : first.toUpperCase();
+};`,
+ fix: "none",
+ },
+ {
+ code: "TSUS501",
+ name: "exhaustive-switch",
+ title: "Non-exhaustive switch or match over a union",
+ message: "this switch over a finite union has no default and misses some members",
+ hint: "Add a case for each missing member, or a default that calls exhaustive(x).",
+ why: "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.",
+ evidence: "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.",
+ bad: `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 ""
+};`,
+ good: `import { matchLiteral } from "@tsus/v2";
+type State = "open" | "closed" | "merged";
+const label = (s: State): string =>
+ matchLiteral(s, { open: () => "Open", closed: () => "Closed", merged: () => "Merged" });`,
+ fix: "none",
+ },
+ {
+ code: "TSUS502",
+ name: "no-null",
+ title: "null is banned outside boundary files",
+ message: "null as a value or in a type is banned outside *.boundary.ts files",
+ hint: "Use Option<T> (T | undefined). Comparing a library's result with null is fine; producing null is not.",
+ why: "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.",
+ evidence: "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`.",
+ bad: `type User = { readonly email: string | null };
+const none: User = { email: null };`,
+ good: `import type { Option } from "@tsus/v2";
+type User = { readonly email: Option<string> };
+const none: User = { email: undefined };`,
+ fix: "none",
+ },
+ {
+ code: "TSUS503",
+ name: "no-falsy-option-test",
+ title: "Truthiness test on an Option that can hold a falsy value",
+ message: "a truthiness test on an optional string or number treats \"\" or 0 as absent",
+ hint: "Compare with undefined (x !== undefined), or use isSome(x).",
+ why: "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.",
+ evidence: "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.",
+ bad: `import type { Option } from "@tsus/v2";
+const portOf = (raw: Option<number>): number => (raw ? raw : 8080); // 0 becomes 8080`,
+ good: `import type { Option } from "@tsus/v2";
+const portOf = (raw: Option<number>): number => (raw !== undefined ? raw : 8080);`,
+ fix: "none",
+ },
+ {
+ code: "TSUS504",
+ name: "no-floating-promise",
+ title: "Floating promise",
+ message: "this promise is neither awaited, returned, nor passed on",
+ hint: "await it, return it, hand it to ctx.waitUntil, or write void to say it is fire-and-forget.",
+ why: "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).",
+ evidence: "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.",
+ bad: `const save = async (id: string): Promise<void> => {};
+const handle = (id: string): string => {
+ save(id);
+ return "ok";
+};`,
+ good: `const save = async (id: string): Promise<void> => {};
+const handle = async (id: string): Promise<string> => {
+ await save(id);
+ return "ok";
+};`,
+ fix: "none",
+ },
+ {
+ code: "TSUS505",
+ name: "no-ignored-result",
+ title: "Ignored Result",
+ message: "this Result is discarded without looking at ok",
+ hint: "Branch on r.ok, matchResult it, or return it.",
+ why: "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.",
+ evidence: "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.",
+ bad: `import { Ok, type Result } from "@tsus/v2";
+const send = (to: string): Result<true, "bounced"> => Ok(true);
+const notify = (): void => {
+ send("ops@example.com");
+};`,
+ good: `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;
+};`,
+ fix: "none",
+ },
+ {
+ code: "TSUS506",
+ name: "no-cast",
+ title: "as casts are banned outside boundary files",
+ message: "type assertions are banned outside *.boundary.ts files (as const is fine)",
+ hint: "Narrow with a check the compiler can see, or move the conversion into a *.boundary.ts file.",
+ why: "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.",
+ evidence: "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.",
+ bad: `import type { Sql } from "@tsus/v2";
+const query = "SELECT * FROM users" as unknown as Sql;`,
+ good: `import { sql } from "@tsus/v2";
+const query = sql\`SELECT * FROM users\`;`,
+ fix: "none",
+ },
+ {
+ code: "TSUS507",
+ name: "no-non-null",
+ title: "Non-null assertions are banned outside boundary files",
+ message: "the non-null assertion ! is banned outside *.boundary.ts files",
+ hint: "Check for undefined; the compiler narrows after the check.",
+ why: "`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.",
+ evidence: "experiment: neither build used `!`, so it costs nothing. It stays as the other half of noUncheckedIndexedAccess.",
+ bad: `const first = (xs: readonly string[]): string => xs[0]!;`,
+ good: `const first = (xs: readonly string[]): string => xs[0] ?? "";`,
+ fix: "none",
+ },
+ {
+ code: "TSUS508",
+ name: "no-any",
+ title: "any is banned outside boundary files",
+ message: "an explicit any is banned outside *.boundary.ts files",
+ hint: "Use unknown and narrow, or a precise type.",
+ why: "`any` is assignable to every brand, so `const q: any = userText; db.all(q)` would pass the Sql check. `unknown` keeps the check.",
+ evidence: "experiment: zero uses in either build, so no friction. It stays for the same reason as the cast ban.",
+ bad: `const parse = (raw: string): any => JSON.parse(raw);`,
+ good: `const parse = (raw: string): unknown => JSON.parse(raw);`,
+ fix: "none",
+ },
+ {
+ code: "TSUS509",
+ name: "no-ts-suppression",
+ title: "Type-check suppressions are banned",
+ message: "@ts-ignore, @ts-expect-error and @ts-nocheck are banned",
+ hint: "Fix the error; checked conversions belong in a *.boundary.ts file.",
+ why: "A suppression switches every rule above off for a line or a file with no record of why.",
+ evidence: "v1 TSUS413; zero uses in the experiment, so no friction.",
+ bad: `// @ts-ignore
+const n: number = "4";`,
+ good: `const n: number = Number("4");`,
+ fix: "none",
+ },
+ {
+ code: "TSUS510",
+ name: "readonly-params",
+ title: "Parameters are read-only by default",
+ message: "this mutates a parameter, which is read-only unless its type is Mutable<...>",
+ hint: "Return a new value, or declare the parameter as Mutable<T> to say the mutation is the point.",
+ why: "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>`.",
+ evidence: "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.",
+ bad: `const newest = (xs: number[]): number[] => xs.sort((a, b) => b - a);`,
+ good: `const newest = (xs: readonly number[]): number[] => xs.toSorted((a, b) => b - a);`,
+ fix: "none",
+ },
+ {
+ code: "TSUS600",
+ name: "permit-required",
+ title: "Private data read without a Permit",
+ message: "this data-access function needs a Permit, and none was given",
+ hint: "Call the access check (in an *.access.ts file) and pass the Permit it returns.",
+ why: "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.",
+ evidence: "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.",
+ bad: `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 });`,
+ good: `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);
+};`,
+ fix: "none",
+ },
+ {
+ code: "TSUS601",
+ name: "sql-from-strings",
+ title: "Query built from a string",
+ message: "a query is built from a non-constant string instead of the sql tag",
+ hint: "Write the query with sql`...`: every ${value} becomes a bound parameter.",
+ why: "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.",
+ evidence: "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.",
+ bad: `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();`,
+ good: `import { sql, type SafeDb } from "@tsus/v2";
+declare const db: SafeDb;
+const find = (title: string) => db.all(sql\`SELECT * FROM issues WHERE title = \${title}\`);`,
+ fix: "none",
+ },
+ {
+ code: "TSUS602",
+ name: "permit-minting",
+ title: "Permits are minted only in access files",
+ message: "@tsus/v2/authority may only be imported by *.access.ts files",
+ hint: "Move the access check into a file named *.access.ts and export a function that returns the Permit.",
+ why: "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.",
+ evidence: "risks: permission scoping. The rule is what makes TSUS600 mean \"an access check ran\" rather than \"someone called a function\".",
+ bad: `// file: src/issues.ts
+import { issuePermit } from "@tsus/v2/authority";
+export const anyone = (repo: string) => issuePermit("repo.read", repo);`,
+ good: `// 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;`,
+ fix: "none",
+ },
+ {
+ code: "TSUS603",
+ name: "permit-resource",
+ title: "Read the resource from the Permit",
+ message: "this function takes a Permit and, separately, an id of the same type",
+ hint: "Drop the separate id and read permit.resource, so the checked resource is the one queried.",
+ why: "`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.",
+ evidence: "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.",
+ bad: `import type { Permit } from "@tsus/v2";
+type RepoId = string & { readonly __repo: true };
+export const listIssues = (p: Permit<"repo.read", RepoId>, repo: RepoId) => repo;`,
+ good: `import type { Permit } from "@tsus/v2";
+type RepoId = string & { readonly __repo: true };
+export const listIssues = (p: Permit<"repo.read", RepoId>) => p.resource;`,
+ fix: "none",
+ },
+ {
+ code: "TSUS604",
+ name: "secret-exposure",
+ title: "Secret stringified, logged or serialized",
+ message: "a Secret reaches a string, a log, a URL, JSON or a response",
+ hint: "Use reveal(secret) at the one call that needs the raw value (an Authorization header), and nowhere else.",
+ why: "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.",
+ evidence: "risks: secrets reaching logs and URLs was the third risk class; v1 had no notion of a secret.",
+ bad: `import type { Secret } from "@tsus/v2";
+declare const apiKey: Secret;
+console.log(\`calling the API with \${apiKey}\`);`,
+ good: `import { reveal, type Secret } from "@tsus/v2";
+declare const apiKey: Secret;
+const headers = { authorization: \`Bearer \${reveal(apiKey)}\` };`,
+ fix: "none",
+ },
+ {
+ code: "TSUS605",
+ name: "untrusted-html",
+ title: "Untrusted text in HTML without escaping",
+ message: "Untrusted text is put into HTML without escaping",
+ hint: "Build the markup with html`...` (it escapes), or escapeHtml(text).",
+ why: "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.",
+ evidence: "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```.",
+ bad: `import type { Untrusted } from "@tsus/v2";
+declare const title: Untrusted;
+const row = \`<li>\${title}</li>\`;`,
+ good: `import { html, type Untrusted } from "@tsus/v2";
+declare const title: Untrusted;
+const row = html\`<li>\${title}</li>\`;`,
+ fix: "none",
+ },
+ {
+ code: "TSUS606",
+ name: "untrusted-prompt",
+ title: "Untrusted text in an LLM prompt without marking",
+ message: "Untrusted text is put into a prompt without fence()",
+ hint: "Wrap it: fence(text, \"bug report\"), or build the prompt with prompt`...`, which rejects Untrusted.",
+ why: "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.",
+ evidence: "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.",
+ bad: `import type { Untrusted } from "@tsus/v2";
+declare const report: Untrusted;
+const prompt = \`Summarize this bug report: \${report}\`;`,
+ good: `import { fence, type Untrusted } from "@tsus/v2";
+declare const report: Untrusted;
+const prompt = \`Summarize this bug report: \${fence(report, "bug report")}\`;`,
+ fix: "none",
+ },
+ {
+ code: "TSUS607",
+ name: "untrusted-string",
+ title: "Untrusted text turned into a plain string",
+ message: "Untrusted text is stringified without validate, escapeHtml, fence or sql",
+ hint: "validate(text, /pattern/) for ids and slugs, escapeHtml for markup, fence for prompts, sql`` for queries.",
+ why: "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.",
+ evidence: "risks: untrusted input. The rule is the general case the two named sinks specialize.",
+ bad: `import type { Untrusted } from "@tsus/v2";
+declare const slug: Untrusted;
+const path = "/repos/" + slug;`,
+ good: `import { validate, type Untrusted } from "@tsus/v2";
+declare const slug: Untrusted;
+const safe = validate(slug, /[a-z0-9-]+/);
+const path = safe === undefined ? "/" : "/repos/" + safe;`,
+ fix: "none",
+ },
+];
+
+export const V2_REGISTRY = ENTRIES;
+export const V2_RULES = new Map(ENTRIES.map((r) => [r.code, r]));
+
+// Every v1 rule and macro, and what v2 does with it. Rendered into docs/v2/rules.md.
+export const V1_DISPOSITION = [
+ ["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<T> 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 | undefined` (no allocation); Result is `{ ok, value | error }`. The pilot measured the v1 wrappers at 2 to 6x on the hot path."],
+];
View file
Addedpackages/cli/src/v2/rules.jsLong diff, collapsed+430−0
@@ -0,0 +1,430 @@
+// The v2 checker: `tsus check --v2 [dir]`. Plain .ts in, diagnostics out; nothing is rewritten
+// or compiled, so whatever builds the project today (tsc, esbuild, wrangler, node's type
+// stripping) keeps building it. Each rule is documented, with the reason it exists, in
+// registry.js and docs/v2/rules.md.
+import fs from "node:fs";
+import path from "node:path";
+import ts from "typescript";
+import { V2_RULES } from "./registry.js";
+import {
+ SQL_TEXT, brandsOf, calleeName, calleeText, containsBrand, falsyGap, hasBrand, isAccessFile, isBoundaryFile, isLogCall,
+ isResultType, isThenable, literalMembers, nonConstantParts, position, skipParens,
+} from "./analysis.js";
+import { V2_OPTIONS, createProgram, findConfigFor, listTsFiles, optionsFrom } from "./program.js";
+
+const LIBRARY = "@tsus/v2";
+const AUTHORITY = "@tsus/v2/authority";
+const LIBRARY_TAGS = new Set(["sql", "html", "prompt"]);
+const MATCHERS = new Set(["match", "matchLiteral", "matchOption", "matchResult"]);
+const ARRAY_MUTATORS = new Set(["push", "pop", "shift", "unshift", "splice", "sort", "reverse", "fill", "copyWithin"]);
+const COLLECTION_MUTATORS = new Set(["set", "delete", "clear", "add"]);
+const ASSIGNMENT_OPS = new Set([
+ ts.SyntaxKind.EqualsToken, ts.SyntaxKind.PlusEqualsToken, ts.SyntaxKind.MinusEqualsToken, ts.SyntaxKind.AsteriskEqualsToken,
+ ts.SyntaxKind.SlashEqualsToken, ts.SyntaxKind.PercentEqualsToken, ts.SyntaxKind.AmpersandAmpersandEqualsToken,
+ ts.SyntaxKind.BarBarEqualsToken, ts.SyntaxKind.QuestionQuestionEqualsToken, ts.SyntaxKind.AmpersandEqualsToken,
+ ts.SyntaxKind.BarEqualsToken, ts.SyntaxKind.CaretEqualsToken, ts.SyntaxKind.LessThanLessThanEqualsToken,
+ ts.SyntaxKind.GreaterThanGreaterThanEqualsToken, ts.SyntaxKind.AsteriskAsteriskEqualsToken,
+]);
+
+const HTML_TEXT = /<[a-zA-Z!/]/;
+const PROMPT_NAME = /prompt|system|instruction|messages?$|^content$|^input$/i;
+const PROMPT_CALL = /prompt|complete|chat|generate|messages\.create|(^|\.)run$|(^|\.)ask$/i;
+
+export const diagnostic = (code, sf, node, detail, rootDir) => {
+ const rule = V2_RULES.get(code);
+ return {
+ code,
+ message: detail ? `${rule.message}: ${detail}` : rule.message,
+ hint: rule.hint,
+ file: path.relative(rootDir, sf.fileName),
+ ...position(sf, node),
+ explain: `tsus explain ${code}`,
+ fix: null,
+ };
+};
+
+// --- TypeScript's own errors, named ---------------------------------------------------------
+
+const flatten = (m) => ts.flattenDiagnosticMessageText(m, "\n");
+
+const nodeAt = (sf, pos) => {
+ let found = sf;
+ const visit = (n) => {
+ if (n.getStart(sf) <= pos && pos < n.getEnd()) {
+ found = n;
+ ts.forEachChild(n, visit);
+ }
+ };
+ ts.forEachChild(sf, visit);
+ return found;
+};
+
+// A call missing the argument a Permit parameter needs (TS2554 names no type).
+const missingPermit = (sf, d, checker) => {
+ if (d.code !== 2554 || d.start === undefined) return false;
+ for (let n = nodeAt(sf, d.start); n; n = n.parent) {
+ if (ts.isCallExpression(n)) {
+ const sig = checker.getResolvedSignature(n);
+ const params = sig ? sig.getParameters() : [];
+ return params.slice(n.arguments.length).some((p) => hasBrand(checker, checker.getTypeOfSymbol(p), "Permit"));
+ }
+ }
+ return false;
+};
+
+const classifyTs = (sf, d, checker) => {
+ const text = flatten(d.messageText);
+ if (missingPermit(sf, d, checker)) return "TSUS600";
+ if (/\bPermit</.test(text)) return "TSUS600";
+ if (/'Sql'/.test(text)) return "TSUS601";
+ if (/\bSecret</.test(text)) return "TSUS604";
+ if (/\bUntrusted</.test(text)) return "TSUS607";
+ if (d.start !== undefined) {
+ for (let n = nodeAt(sf, d.start); n; n = n.parent) {
+ if (ts.isCallExpression(n) && MATCHERS.has(calleeName(n)) && n.arguments.some((a) => a.getStart(sf) <= d.start && d.start < a.getEnd())) {
+ return "TSUS501";
+ }
+ }
+ }
+ return "TSUS500";
+};
+
+const tsDiagnostic = (sf, d, rootDir, checker) => {
+ const code = classifyTs(sf, d, checker);
+ const start = d.start ?? 0;
+ const end = start + (d.length ?? 0);
+ const a = sf.getLineAndCharacterOfPosition(start);
+ const b = sf.getLineAndCharacterOfPosition(end);
+ const rule = V2_RULES.get(code);
+ return {
+ code,
+ tsCode: d.code,
+ message: code === "TSUS500" ? flatten(d.messageText) : `${rule.message}: ${flatten(d.messageText)}`,
+ hint: rule.hint,
+ file: path.relative(rootDir, sf.fileName),
+ start, end, line: a.line + 1, col: a.character + 1, endLine: b.line + 1, endCol: b.character + 1,
+ explain: `tsus explain ${code}`,
+ fix: null,
+ };
+};
+
+// --- the rules ------------------------------------------------------------------------------
+
+const rootIdentifier = (expr) => {
+ let e = skipParens(expr);
+ while (ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e) || ts.isCallExpression(e)) e = skipParens(e.expression);
+ return ts.isIdentifier(e) ? e : undefined;
+};
+
+// Where a template or concatenation holding Untrusted text ends up: html, prompt, or other.
+const untrustedSink = (node, sf) => {
+ let top = node;
+ while (top.parent && (ts.isParenthesizedExpression(top.parent) || (ts.isBinaryExpression(top.parent) && top.parent.operatorToken.kind === ts.SyntaxKind.PlusToken))) top = top.parent;
+ const statics = [];
+ const collect = (n) => {
+ if (ts.isTemplateExpression(n)) {
+ statics.push(n.head.text, ...n.templateSpans.map((s) => s.literal.text));
+ n.templateSpans.forEach((s) => collect(s.expression));
+ } else if (ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n)) statics.push(n.text);
+ else if (ts.isBinaryExpression(n) || ts.isParenthesizedExpression(n)) ts.forEachChild(n, collect);
+ };
+ collect(top);
+ if (HTML_TEXT.test(statics.join(""))) return "TSUS605";
+ if (SQL_TEXT.test(statics.join(" "))) return "TSUS601";
+ // Climb through the places a string passes on its way to a sink.
+ for (let n = top, p = top.parent; p; n = p, p = p.parent) {
+ if (ts.isParenthesizedExpression(p) || ts.isArrayLiteralExpression(p) || ts.isConditionalExpression(p) || ts.isObjectLiteralExpression(p)) continue;
+ if (ts.isBinaryExpression(p) && p.operatorToken.kind === ts.SyntaxKind.PlusToken) continue;
+ if (ts.isPropertyAccessExpression(p) && p.name.text === "join") continue;
+ if (ts.isCallExpression(p) && p.expression === n) continue;
+ if (ts.isVariableDeclaration(p) && ts.isIdentifier(p.name)) return PROMPT_NAME.test(p.name.text) ? "TSUS606" : "TSUS607";
+ if (ts.isPropertyAssignment(p)) {
+ const name = p.name.getText(sf).replace(/["']/g, "");
+ if (/^(innerHTML|outerHTML)$/.test(name)) return "TSUS605";
+ if (PROMPT_NAME.test(name)) return "TSUS606";
+ continue;
+ }
+ if (ts.isBinaryExpression(p) && ASSIGNMENT_OPS.has(p.operatorToken.kind)) {
+ const target = p.left.getText(sf);
+ if (/\.(innerHTML|outerHTML)$/.test(target)) return "TSUS605";
+ return PROMPT_NAME.test(target.split(".").pop() ?? "") ? "TSUS606" : "TSUS607";
+ }
+ if (ts.isCallExpression(p) || ts.isNewExpression(p)) {
+ const callee = p.expression.getText(sf);
+ if (/insertAdjacentHTML|document\.write/.test(callee)) return "TSUS605";
+ if (PROMPT_CALL.test(callee)) return "TSUS606";
+ return "TSUS607";
+ }
+ if (ts.isReturnStatement(p) || ts.isArrowFunction(p)) {
+ for (let f = p; f; f = f.parent) {
+ if (ts.isFunctionLike(f)) {
+ const name = f.name ? f.name.getText(sf) : f.parent && ts.isVariableDeclaration(f.parent) ? f.parent.name.getText(sf) : "";
+ return PROMPT_NAME.test(name) || /prompt/i.test(name) ? "TSUS606" : "TSUS607";
+ }
+ }
+ }
+ break;
+ }
+ return "TSUS607";
+};
+
+const isLibraryImport = (checker, ident, name) => {
+ const sym = checker.getSymbolAtLocation(ident);
+ if (!sym || !(sym.flags & ts.SymbolFlags.Alias)) return false;
+ const decl = sym.declarations?.[0];
+ const imp = decl && (ts.isImportSpecifier(decl) ? decl.parent.parent.parent : undefined);
+ const spec = imp && ts.isImportDeclaration(imp) && ts.isStringLiteral(imp.moduleSpecifier) ? imp.moduleSpecifier.text : "";
+ const imported = decl && ts.isImportSpecifier(decl) ? (decl.propertyName ?? decl.name).text : "";
+ return spec === LIBRARY && imported === name;
+};
+
+const DB_RECEIVER = (checker, expr) => {
+ const t = checker.getTypeAtLocation(expr);
+ const has = (n) => checker.getPropertyOfType(checker.getApparentType(t), n) !== undefined;
+ return has("prepare") && (has("batch") || has("exec") || has("transaction"));
+};
+
+export const runRules = (sf, checker, rootDir) => {
+ const out = [];
+ const boundary = isBoundaryFile(sf.fileName);
+ const access = isAccessFile(sf.fileName);
+ const reported = new Set();
+ const report = (code, node, detail) => {
+ const key = `${code}:${node.getStart(sf)}:${node.getEnd()}`;
+ if (reported.has(key)) return;
+ reported.add(key);
+ out.push(diagnostic(code, sf, node, detail, rootDir));
+ };
+ const typeOf = (n) => checker.getTypeAtLocation(n);
+ const brands = (n) => brandsOf(checker, typeOf(n));
+
+ // TSUS509: suppressions, anywhere (boundary files too).
+ for (const m of sf.text.matchAll(/\/\/\s*@ts-(ignore|expect-error|nocheck)\b|\/\*+\s*@ts-(ignore|expect-error|nocheck)\b/g)) {
+ const start = m.index ?? 0;
+ const node = { getStart: () => start, getEnd: () => start + m[0].length };
+ out.push(diagnostic("TSUS509", sf, node, m[0].replace(/^\/[/*]+\s*/, ""), rootDir));
+ }
+
+ // TSUS503: a truthiness test on an optional string or number.
+ const condition = (expr) => {
+ const e = skipParens(expr);
+ if (ts.isBinaryExpression(e) && (e.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken || e.operatorToken.kind === ts.SyntaxKind.BarBarToken)) {
+ condition(e.left);
+ condition(e.right);
+ return;
+ }
+ if (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.ExclamationToken) {
+ condition(e.operand);
+ return;
+ }
+ const gap = falsyGap(checker, typeOf(e));
+ if (gap) report("TSUS503", e, `${e.getText(sf)} is optional and a present ${gap} can be falsy`);
+ };
+
+ const secretOrUntrusted = (exprNode, sinkNode, what) => {
+ const b = brands(exprNode);
+ if (b.has("Secret")) report("TSUS604", exprNode, `${exprNode.getText(sf)} in ${what}`);
+ if (b.has("Untrusted")) {
+ const code = sinkNode ? untrustedSink(sinkNode, sf) : "TSUS607";
+ report(code, exprNode, `${exprNode.getText(sf)} in ${what}`);
+ }
+ };
+ const deepSecret = (arg, what) => {
+ if (containsBrand(checker, typeOf(arg), "Secret")) report("TSUS604", arg, `${arg.getText(sf)} in ${what}`);
+ };
+
+ const checkSwitch = (node) => {
+ if (node.caseBlock.clauses.some((c) => ts.isDefaultClause(c))) return;
+ const members = literalMembers(checker, typeOf(node.expression));
+ if (!members) return;
+ const covered = new Set();
+ for (const c of node.caseBlock.clauses) {
+ const m = literalMembers(checker, typeOf(c.expression));
+ if (m && m.length === 1) covered.add(m[0]);
+ else if (c.expression.kind === ts.SyntaxKind.UndefinedKeyword || (ts.isIdentifier(c.expression) && c.expression.text === "undefined")) covered.add("undefined");
+ }
+ const missing = members.filter((m) => !covered.has(m));
+ if (missing.length > 0) report("TSUS501", node.expression, `missing ${missing.join(", ")}`);
+ };
+
+ const checkParams = (fn) => {
+ // TSUS603: a Permit next to a separate id of its resource type.
+ const params = fn.parameters.map((p) => ({ p, type: typeOf(p) }));
+ for (const { p, type } of params) {
+ if (!hasBrand(checker, type, "Permit")) continue;
+ const res = checker.getPropertyOfType(type, "resource");
+ if (!res) continue;
+ const resType = checker.getTypeOfSymbol(res);
+ if (resType.flags & (ts.TypeFlags.String | ts.TypeFlags.Number | ts.TypeFlags.Any | ts.TypeFlags.Unknown)) continue;
+ for (const other of params) {
+ if (other.p === p) continue;
+ if (checker.isTypeAssignableTo(other.type, resType) && checker.isTypeAssignableTo(resType, other.type)) {
+ report("TSUS603", other.p, `${other.p.name.getText(sf)} duplicates ${p.name.getText(sf)}.resource`);
+ }
+ }
+ }
+ // TSUS510: parameters are read-only unless declared Mutable<...>.
+ if (!fn.body) return;
+ const symbols = new Map();
+ for (const { p, type } of params) {
+ if (p.type && /^Mutable\s*</.test(p.type.getText(sf))) continue;
+ if (!(type.flags & ts.TypeFlags.Object) && !type.isUnionOrIntersection()) continue;
+ const add = (name) => {
+ if (ts.isIdentifier(name)) {
+ const s = checker.getSymbolAtLocation(name);
+ if (s) symbols.set(s, name.text);
+ } else for (const el of name.elements) if (!ts.isOmittedExpression(el)) add(el.name);
+ };
+ add(p.name);
+ }
+ if (symbols.size === 0) return;
+ const rootParam = (expr) => {
+ const id = rootIdentifier(expr);
+ const s = id && checker.getSymbolAtLocation(id);
+ return s && symbols.has(s) ? symbols.get(s) : undefined;
+ };
+ const isAccess = (e) => ts.isPropertyAccessExpression(skipParens(e)) || ts.isElementAccessExpression(skipParens(e));
+ const visit = (n) => {
+ if (ts.isBinaryExpression(n) && ASSIGNMENT_OPS.has(n.operatorToken.kind) && isAccess(n.left)) {
+ const name = rootParam(n.left);
+ if (name) report("TSUS510", n.left, `writes ${n.left.getText(sf)} (parameter ${name})`);
+ } else if ((ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) && (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken) && isAccess(n.operand)) {
+ const name = rootParam(n.operand);
+ if (name) report("TSUS510", n.operand, `writes ${n.operand.getText(sf)} (parameter ${name})`);
+ } else if (ts.isDeleteExpression(n)) {
+ const name = rootParam(n.expression);
+ if (name) report("TSUS510", n.expression, `deletes ${n.expression.getText(sf)} (parameter ${name})`);
+ } else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression)) {
+ const method = n.expression.name.text;
+ const recv = n.expression.expression;
+ const t = typeOf(recv);
+ const isArray = checker.isArrayType(t);
+ const sym = t.getSymbol();
+ const isCollection = sym && /^(Map|Set|WeakMap|WeakSet)$/.test(sym.getName());
+ if ((isArray && ARRAY_MUTATORS.has(method)) || (isCollection && COLLECTION_MUTATORS.has(method))) {
+ const name = rootParam(recv);
+ if (name) report("TSUS510", n, `${recv.getText(sf)}.${method}() mutates parameter ${name}`);
+ }
+ if (n.expression.getText(sf) === "Object.assign" && n.arguments[0]) {
+ const name = rootParam(n.arguments[0]);
+ if (name) report("TSUS510", n, `Object.assign into parameter ${name}`);
+ }
+ }
+ ts.forEachChild(n, visit);
+ };
+ visit(fn.body);
+ };
+
+ const visit = (node) => {
+ switch (node.kind) {
+ case ts.SyntaxKind.NullKeyword: {
+ const p = node.parent;
+ const comparison = ts.isBinaryExpression(p) && [ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken, ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken].includes(p.operatorToken.kind);
+ if (!boundary && !comparison) report("TSUS502", node, ts.isLiteralTypeNode(p) ? "null in a type" : "null as a value");
+ break;
+ }
+ case ts.SyntaxKind.AnyKeyword:
+ if (!boundary) report("TSUS508", node);
+ break;
+ default:
+ break;
+ }
+ if (ts.isAsExpression(node) && !boundary) {
+ const isConst = ts.isTypeReferenceNode(node.type) && node.type.typeName.getText(sf) === "const";
+ if (!isConst) report("TSUS506", node, `as ${node.type.getText(sf)}`);
+ } else if (ts.isTypeAssertionExpression(node) && !boundary) {
+ report("TSUS506", node, `<${node.type.getText(sf)}>`);
+ } else if (ts.isNonNullExpression(node) && !boundary) {
+ report("TSUS507", node, node.getText(sf));
+ } else if (ts.isSwitchStatement(node)) {
+ checkSwitch(node);
+ } else if (ts.isExpressionStatement(node)) {
+ const e = skipParens(node.expression);
+ const assignment = ts.isBinaryExpression(e) && ASSIGNMENT_OPS.has(e.operatorToken.kind);
+ if (!ts.isVoidExpression(e) && !assignment && !ts.isDeleteExpression(e)) {
+ const t = typeOf(e);
+ const handled = ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && (e.expression.name.text === "catch" || (e.expression.name.text === "then" && e.arguments.length >= 2));
+ if (!ts.isAwaitExpression(e) && isThenable(checker, t) && !handled) report("TSUS504", e, e.getText(sf).slice(0, 80));
+ else if (isResultType(checker, t)) report("TSUS505", e, e.getText(sf).slice(0, 80));
+ }
+ } else if (ts.isIfStatement(node) || ts.isWhileStatement(node) || ts.isDoStatement(node)) {
+ condition(node.expression);
+ } else if (ts.isForStatement(node) && node.condition) {
+ condition(node.condition);
+ } else if (ts.isConditionalExpression(node)) {
+ condition(node.condition);
+ } else if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.ExclamationToken) {
+ condition(node.operand);
+ } else if (ts.isBinaryExpression(node)) {
+ const op = node.operatorToken.kind;
+ if (op === ts.SyntaxKind.AmpersandAmpersandToken) condition(node.left);
+ if (op === ts.SyntaxKind.BarBarToken) {
+ const gap = falsyGap(checker, typeOf(node.left), ts.TypeFlags.Number | ts.TypeFlags.BigInt);
+ if (gap) report("TSUS503", node.left, `${node.left.getText(sf)} || ... replaces a present ${gap} 0 too`);
+ }
+ if (op === ts.SyntaxKind.PlusToken || op === ts.SyntaxKind.PlusEqualsToken) {
+ const stringy = (n) => typeOf(n).flags & ts.TypeFlags.StringLike;
+ if (stringy(node) || stringy(node.left) || stringy(node.right)) {
+ for (const side of [node.left, node.right]) {
+ if (ts.isBinaryExpression(skipParens(side)) && skipParens(side).operatorToken.kind === ts.SyntaxKind.PlusToken) continue;
+ secretOrUntrusted(side, node, "string concatenation");
+ }
+ }
+ }
+ } else if (ts.isTemplateExpression(node)) {
+ const tag = ts.isTaggedTemplateExpression(node.parent) ? node.parent.tag : undefined;
+ const libraryTag = tag && ts.isIdentifier(tag) && LIBRARY_TAGS.has(tag.text) && isLibraryImport(checker, tag, tag.text);
+ if (!libraryTag) for (const span of node.templateSpans) secretOrUntrusted(span.expression, node, tag ? `the ${tag.getText(sf)} template` : "a template literal");
+ } else if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && node.moduleSpecifier.text === AUTHORITY && !access) {
+ report("TSUS602", node.moduleSpecifier, path.basename(sf.fileName));
+ } else if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
+ const callee = calleeText(node, sf);
+ const name = calleeName(node);
+ const args = node.arguments ?? [];
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "sql" && isLibraryImport(checker, node.expression, "sql")) {
+ report("TSUS601", node, "sql called as a function; use it as a tag: sql`...`");
+ }
+ // Boundary files are exempt: a driver adapter passes Sql text through to the raw driver.
+ if (!boundary && ts.isCallExpression(node) && (name === "prepare" || name === "exec") && ts.isPropertyAccessExpression(node.expression) && args[0] && DB_RECEIVER(checker, node.expression.expression)) {
+ if (!hasBrand(checker, typeOf(args[0]), "Sql")) {
+ const parts = nonConstantParts(checker, args[0]);
+ if (parts.length > 0) report("TSUS601", args[0], `built from ${parts.map((p) => p.getText(sf)).slice(0, 4).join(", ")}`);
+ }
+ }
+ if (callee === "String" && args[0]) secretOrUntrusted(args[0], undefined, "String()");
+ if (ts.isCallExpression(node) && name === "toString" && ts.isPropertyAccessExpression(node.expression)) secretOrUntrusted(node.expression.expression, undefined, "toString()");
+ if (callee === "JSON.stringify" && args[0]) deepSecret(args[0], "JSON.stringify");
+ if (ts.isCallExpression(node) && isLogCall(node, sf)) for (const a of args) deepSecret(a, `a log call (${callee})`);
+ if (/^(URL|URLSearchParams|Response|Request)$/.test(callee) || /^(fetch|Response\.json|Response\.redirect)$/.test(callee) || /searchParams\.(set|append)$/.test(callee)) {
+ for (const a of args) deepSecret(a, callee);
+ }
+ }
+ if (ts.isFunctionLike(node) && node.parameters) checkParams(node);
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ return out;
+};
+
+// --- the command ----------------------------------------------------------------------------
+
+export const checkV2 = (target, { files } = {}) => {
+ const rootDir = path.resolve(target);
+ const roots = files ? files.map((f) => path.resolve(f)) : listTsFiles(fsDir(rootDir));
+ const configPath = roots[0] ? findConfigFor(roots[0]) : undefined;
+ const options = { ...optionsFrom(configPath), ...V2_OPTIONS };
+ const program = createProgram(roots, options);
+ const checker = program.getTypeChecker();
+ const rootSet = new Set(roots);
+ const diagnostics = [];
+ for (const sf of program.getSourceFiles()) {
+ if (!rootSet.has(path.resolve(sf.fileName))) continue;
+ for (const d of [...program.getSyntacticDiagnostics(sf), ...program.getSemanticDiagnostics(sf)]) diagnostics.push(tsDiagnostic(sf, d, rootDir, checker));
+ diagnostics.push(...runRules(sf, checker, rootDir));
+ }
+ diagnostics.sort((a, b) => (a.file === b.file ? a.start - b.start : a.file < b.file ? -1 : 1));
+ return { diagnostics, files: roots.map((f) => path.relative(rootDir, f)) };
+};
+
+// `tsus check --v2 dir` checks dir/src when it exists, else dir.
+const fsDir = (rootDir) => (fs.existsSync(path.join(rootDir, "src")) ? path.join(rootDir, "src") : rootDir);
View file
Addedpackages/v2/authority.d.ts+7−0
@@ -0,0 +1,7 @@
+// @tsus/v2/authority: the one place a Permit is made. The checker allows this import only in
+// files named *.access.ts (TSUS602), so every Permit in a program traces back to an access check
+// someone can review in one place.
+import type { Permit } from "./index.js";
+
+/** Records that an access check allowed `action` on `resource`. Call it only after the check. */
+export declare function issuePermit<const A extends string, R>(action: A, resource: R): Permit<A, R>;
View file
Addedpackages/v2/authority.js+3−0
@@ -0,0 +1,3 @@
+import { __issuePermit } from "./index.js";
+
+export const issuePermit = (action, resource) => __issuePermit(action, resource);
View file
Addedpackages/v2/index.d.ts+242−0
@@ -0,0 +1,242 @@
+// @tsus/v2: the type library of TypeScript-Ultra-Strict v2.
+//
+// Everything here is ordinary TypeScript that erases: there is no macro and no new file
+// extension, so esbuild, wrangler and node's type stripping handle files that use it unchanged.
+// What the types cannot express, the checker enforces (`tsus check --v2`, codes TSUS5xx/TSUS6xx).
+// The brands below are `unique symbol` keys that are declared but not exported, so no code
+// outside this file can write a literal of a branded type: a Sql, a Permit, a Secret or an
+// Untrusted value only comes from the function that makes it, or from a cast, and casts are
+// banned outside *.boundary.ts files (TSUS506).
+
+// --- Option ---------------------------------------------------------------------------------
+
+/**
+ * A value that may be absent. It is `T | undefined` underneath: no wrapper object, no
+ * allocation, nothing to unwrap. The checker makes it safe: `null` is banned outside boundary
+ * files (TSUS502), so there is one absent value, and a truthiness test on an Option whose value
+ * can itself be falsy (`if (name)` on an `Option<string>`) is an error (TSUS503), so "" and 0 are
+ * never mistaken for absent.
+ */
+export type Option<T> = T | undefined;
+
+/** True when the Option holds a value. Same as `o !== undefined`. */
+export declare function isSome<T>(o: Option<T>): o is T;
+/** True when the Option is absent. Same as `o === undefined`. */
+export declare function isNone<T>(o: Option<T>): o is undefined;
+/** The boundary conversion: `null` and `undefined` become `undefined`. */
+export declare function fromNullable<T>(value: T | null | undefined): Option<T>;
+/** Exhaustive two-armed match over an Option. */
+export declare function matchOption<T, S, N>(o: Option<T>, arms: { readonly some: (value: T) => S; readonly none: () => N }): S | N;
+
+// --- Result ---------------------------------------------------------------------------------
+
+/** The success half of a Result: a plain frozen-shape object, `{ ok: true, value }`. */
+export type Ok<T> = { readonly ok: true; readonly value: T };
+/** The failure half of a Result: `{ ok: false, error }`. */
+export type Err<E> = { readonly ok: false; readonly error: E };
+/**
+ * A computation that succeeded with a T or failed with an E. A plain tagged object, so it costs
+ * one small allocation and narrows with `if (r.ok)`. An unused Result is an error (TSUS505).
+ */
+export type Result<T, E> = Ok<T> | Err<E>;
+
+/** `const` keeps literal types (`Err({ kind: "missing" })` is `Err<{ readonly kind: "missing" }>`). */
+export declare function Ok<const T>(value: T): Ok<T>;
+export declare function Err<const E>(error: E): Err<E>;
+/** Exhaustive two-armed match over a Result. */
+export declare function matchResult<T, E, A, B>(r: Result<T, E>, arms: { readonly ok: (value: T) => A; readonly err: (error: E) => B }): A | B;
+/** Runs f, turning a throw into Err(the thrown value). */
+export declare function tryCatch<T>(f: () => T): Result<T, unknown>;
+/** Awaits f(), turning a rejection into Err(the reason). */
+export declare function tryAsync<T>(f: () => Promise<T>): Promise<Result<T, unknown>>;
+
+// --- match ----------------------------------------------------------------------------------
+
+type Key = string | number;
+type IsFinite<T> = [T] extends [never] ? false : string extends T ? false : number extends T ? false : true;
+type ArmResult<A> = { [P in keyof A]: A[P] extends (...args: never[]) => infer R ? R : never }[keyof A];
+type NoExtra<A, Allowed> = A & { readonly [X in Exclude<keyof A, Allowed>]: never };
+
+/** The arms of a match over the union V discriminated by its field K: one per value of V[K]. */
+// The arms return `any` in the constraint only: when the arms are wrong, TypeScript falls back to
+// the constraint, and an `unknown` there would add a second, misleading error at every use of the
+// match. When they are right, the result is the union of what the arms really return.
+export type TagArms<V, K extends keyof V> = {
+ readonly [P in V[K] & Key]: (variant: Extract<V, { readonly [_ in K]: P }>) => any;
+};
+
+/**
+ * Exhaustive match over a discriminated union, by its discriminant field:
+ *
+ * match(shape, "kind", {
+ * circle: (c) => Math.PI * c.r ** 2,
+ * square: (s) => s.side ** 2,
+ * })
+ *
+ * Every value of `shape.kind` needs an arm (a missing one is a type error), an arm the union
+ * cannot hold is a type error, and each arm's parameter is narrowed to its variant. The result is
+ * the union of the arms' results. A plain function call: no macro, nothing to compile.
+ */
+export declare function match<V, const K extends keyof V, A extends TagArms<V, K>>(
+ value: V,
+ key: K,
+ arms: IsFinite<V[K]> extends true ? NoExtra<A, V[K]> : "match: the discriminant must be a finite union of literals",
+): ArmResult<A>;
+
+/**
+ * Exhaustive match over a finite union of string or number literals:
+ *
+ * matchLiteral(method, { GET: () => read(), POST: () => write() })
+ *
+ * A plain `string` subject is rejected: narrow it first, or use a switch with a default.
+ */
+export declare function matchLiteral<V extends Key, A extends { readonly [P in V]: (value: P) => any }>(
+ value: V,
+ arms: IsFinite<V> extends true ? NoExtra<A, V> : "matchLiteral: the subject must be a finite union of literals",
+): ArmResult<A>;
+
+/** For the default branch of a switch the checker proved exhaustive: a type error if it is reachable. */
+export declare function exhaustive(value: never): never;
+
+/** Marks a parameter as mutable on purpose. Parameters are read-only by default (TSUS510). */
+export type Mutable<T> = T;
+
+// --- Sql ------------------------------------------------------------------------------------
+
+declare const SqlBrand: unique symbol;
+declare const UntrustedBrand: unique symbol;
+
+/** A value a query binds as a parameter. `undefined` binds as SQL NULL, booleans as 1 and 0. */
+export type SqlValue = string | number | bigint | boolean | undefined | ArrayBuffer | Uint8Array | Untrusted;
+
+/**
+ * A query whose text was written by the program and whose values are bound parameters. It can
+ * only be made by the `sql` tag (or composed from other Sql values), so a database adapter that
+ * accepts only Sql cannot receive a string built from user input.
+ */
+export interface Sql {
+ readonly text: string;
+ readonly params: readonly SqlValue[];
+ readonly [SqlBrand]: true;
+}
+
+/**
+ * The only way to make a Sql: a tagged template. Every `${value}` becomes a `?` placeholder and
+ * a bound parameter; a nested Sql is spliced in with its own parameters.
+ *
+ * sql`SELECT id, title FROM issues WHERE repo_id = ${repoId} AND title LIKE ${pattern}`
+ */
+export declare function sql(strings: TemplateStringsArray, ...values: readonly (SqlValue | Sql)[]): Sql;
+export declare namespace sql {
+ /** Joins fragments, by default with ", ". */
+ function join(parts: readonly Sql[], separator?: Sql): Sql;
+ /** A column or table name chosen by the program: only a string literal type is accepted. */
+ function ident<const N extends string>(name: string extends N ? never : N): Sql;
+ /** The empty fragment. */
+ const empty: Sql;
+}
+
+/** The part of a Cloudflare D1 binding the adapter uses (structurally typed, no import needed). */
+export interface D1StatementLike {
+ bind(...values: unknown[]): D1StatementLike;
+ all<T = Record<string, unknown>>(): Promise<{ results: T[] }>;
+ first<T = Record<string, unknown>>(): Promise<T | null>;
+ run(): Promise<{ meta?: { changes?: number } }>;
+}
+export interface D1Like {
+ prepare(query: string): D1StatementLike;
+ batch?(statements: D1StatementLike[]): Promise<{ results: unknown[] }[]>;
+}
+
+/** A database handle that accepts only Sql. Rows come back with SQL NULL as `undefined`. */
+export interface SafeDb {
+ all<R>(query: Sql): Promise<readonly R[]>;
+ first<R>(query: Sql): Promise<Option<R>>;
+ run(query: Sql): Promise<{ readonly changes: number }>;
+ batch(queries: readonly Sql[]): Promise<readonly (readonly unknown[])[]>;
+}
+/** Wraps a D1 binding (or anything shaped like one). */
+export declare function safeDb(db: D1Like): SafeDb;
+
+// --- Permit ---------------------------------------------------------------------------------
+
+declare const PermitBrand: unique symbol;
+
+/**
+ * Proof that an access check allowed `action` on `resource`. Only `issuePermit` from
+ * `@tsus/v2/authority` makes one, and the checker allows that import only in `*.access.ts`
+ * files (TSUS602), the designated access-check modules. A function that reads private data takes
+ * a Permit and reads the resource id from it (TSUS603), so it cannot be called without a check
+ * and cannot be pointed at a different resource than the one that was checked.
+ */
+export interface Permit<A extends string, R> {
+ readonly action: A;
+ readonly resource: R;
+ readonly [PermitBrand]: true;
+}
+/** Runtime defense in depth: true only for a Permit that issuePermit made. */
+export declare function isGenuinePermit(value: unknown): boolean;
+
+// --- Secret ---------------------------------------------------------------------------------
+
+declare const SecretBrand: unique symbol;
+
+/**
+ * A value that must not leave the program by accident. It is not a string, so it cannot be
+ * passed where one is expected; `reveal()` is the one explicit way out. At runtime it prints and
+ * serializes as "[secret]" (String, templates, JSON.stringify, console.log, node:util inspect),
+ * and the checker rejects it in templates, concatenation, logs, URLs, JSON and Response bodies
+ * (TSUS604), so the redaction is a backstop, not the plan.
+ */
+export interface Secret<T = string> {
+ readonly [SecretBrand]: T;
+ toString(): "[secret]";
+ toJSON(): "[secret]";
+}
+export declare function secret<T>(value: T): Secret<T>;
+/** The explicit way to use a secret: at the call that needs the raw value, and nowhere else. */
+export declare function reveal<T>(s: Secret<T>): T;
+
+// --- Untrusted ------------------------------------------------------------------------------
+
+/**
+ * Text that came from a user (a form field, a query parameter, a bug report). It is the raw
+ * string at runtime, so marking costs nothing, but its type is not a string: it cannot reach a
+ * string sink without going through `escapeHtml`/`html` (HTML), `sql` (a bound parameter),
+ * `fence` (an LLM prompt) or `validate` (a pattern). The checker rejects it in untagged
+ * templates and concatenation (TSUS605 HTML, TSUS606 prompts, TSUS607 anything else).
+ */
+export interface Untrusted<T extends string = string> {
+ readonly [UntrustedBrand]: T;
+}
+/** Marks text as user-provided. */
+export declare function untrusted(text: string): Untrusted;
+/** The length of the text, without letting it out. */
+export declare function untrustedLength(text: Untrusted): number;
+/** Transforms the text and keeps it marked (trim, lowercase, slice). */
+export declare function mapUntrusted(text: Untrusted, f: (raw: string) => string): Untrusted;
+/** The text as a plain string when the whole of it matches `pattern` (an id, a slug, a number). */
+export declare function validate(text: Untrusted, pattern: RegExp): Option<string>;
+
+declare const SafeHtmlBrand: unique symbol;
+/** HTML whose every interpolation was escaped. `.html` is the markup, for a Response body. */
+export interface SafeHtml {
+ readonly html: string;
+ readonly [SafeHtmlBrand]: true;
+}
+export type HtmlValue = SafeHtml | Untrusted | string | number | boolean | undefined | readonly HtmlValue[];
+/** Escapes & < > " ' in text. */
+export declare function escapeHtml(text: Untrusted | string): SafeHtml;
+/** HTML template: every interpolation is escaped unless it is already SafeHtml. */
+export declare function html(strings: TemplateStringsArray, ...values: readonly HtmlValue[]): SafeHtml;
+
+declare const FencedBrand: unique symbol;
+/** Untrusted text wrapped as data for an LLM prompt. */
+export type Fenced = string & { readonly [FencedBrand]: true };
+/**
+ * Wraps user text for a prompt as `<untrusted source="...">...</untrusted>`, with any closing tag
+ * or role marker inside it neutralized, so the model is told where the user's words begin and end.
+ */
+export declare function fence(text: Untrusted, source: string): Fenced;
+/** Prompt template: interpolations must be program text or Fenced; Untrusted is a type error. */
+export declare function prompt(strings: TemplateStringsArray, ...values: readonly (string | number | Fenced)[]): string;
View file
Addedpackages/v2/index.js+178−0
@@ -0,0 +1,178 @@
+// @tsus/v2 runtime. Small on purpose: Option is `T | undefined` and needs no code at all, a Result
+// is a two-field object, and match is one property lookup and a call. Types: index.d.ts.
+
+// --- Option ---
+export const isSome = (o) => o !== undefined;
+export const isNone = (o) => o === undefined;
+export const fromNullable = (v) => (v === null ? undefined : v);
+export const matchOption = (o, arms) => (o === undefined ? arms.none() : arms.some(o));
+
+// --- Result ---
+export const Ok = (value) => ({ ok: true, value });
+export const Err = (error) => ({ ok: false, error });
+export const matchResult = (r, arms) => (r.ok ? arms.ok(r.value) : arms.err(r.error));
+export const tryCatch = (f) => {
+ try {
+ return Ok(f());
+ } catch (e) {
+ return Err(e);
+ }
+};
+export const tryAsync = async (f) => {
+ try {
+ return Ok(await f());
+ } catch (e) {
+ return Err(e);
+ }
+};
+
+// --- match ---
+const noArm = (what) => {
+ throw new TypeError(`TSUS100: no match arm for ${String(what)} (the checker was bypassed)`);
+};
+export const match = (value, key, arms) => {
+ const arm = arms[value[key]];
+ return arm === undefined ? noArm(value[key]) : arm(value);
+};
+export const matchLiteral = (value, arms) => {
+ const arm = arms[value];
+ return arm === undefined ? noArm(value) : arm(value);
+};
+export const exhaustive = (value) => noArm(value);
+
+// --- Sql ---
+const SQL = Symbol("tsus.sql");
+const isSql = (v) => typeof v === "object" && v !== null && v[SQL] === true;
+const makeSql = (text, params) => Object.freeze({ text, params: Object.freeze(params), [SQL]: true });
+
+export const sql = (strings, ...values) => {
+ // A template's strings array is frozen and carries .raw; a hand-built array is refused, so a
+ // string cannot be smuggled in as the "static" part.
+ if (!Array.isArray(strings) || !Object.isFrozen(strings) || !Array.isArray(strings.raw)) {
+ throw new TypeError("sql must be used as a tagged template: sql`...`");
+ }
+ let text = strings[0];
+ const params = [];
+ for (let i = 0; i < values.length; i += 1) {
+ const v = values[i];
+ if (isSql(v)) {
+ text += v.text;
+ for (const p of v.params) params.push(p);
+ } else {
+ text += "?";
+ params.push(v);
+ }
+ text += strings[i + 1];
+ }
+ return makeSql(text, params);
+};
+const COMMA = makeSql(", ", []);
+sql.empty = makeSql("", []);
+sql.join = (parts, separator = COMMA) => {
+ let text = "";
+ const params = [];
+ parts.forEach((part, i) => {
+ if (i > 0) {
+ text += separator.text;
+ for (const p of separator.params) params.push(p);
+ }
+ text += part.text;
+ for (const p of part.params) params.push(p);
+ });
+ return makeSql(text, params);
+};
+sql.ident = (name) => {
+ if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(name)) {
+ throw new TypeError(`sql.ident: not an identifier: ${JSON.stringify(name)}`);
+ }
+ return makeSql(`"${name.replace(".", '"."')}"`, []);
+};
+
+const bindable = (v) => (v === undefined ? null : typeof v === "boolean" ? (v ? 1 : 0) : v);
+const nullsOut = (row) => {
+ for (const k in row) if (row[k] === null) row[k] = undefined;
+ return row;
+};
+const prepared = (db, q) => {
+ if (!isSql(q)) throw new TypeError("SafeDb accepts only Sql made by the sql tag");
+ const s = db.prepare(q.text);
+ return q.params.length === 0 ? s : s.bind(...q.params.map(bindable));
+};
+export const safeDb = (db) => ({
+ all: async (q) => (await prepared(db, q).all()).results.map(nullsOut),
+ first: async (q) => {
+ const row = await prepared(db, q).first();
+ return row === null ? undefined : nullsOut(row);
+ },
+ run: async (q) => ({ changes: (await prepared(db, q).run()).meta?.changes ?? 0 }),
+ batch: async (qs) => (await db.batch(qs.map((q) => prepared(db, q)))).map((r) => r.results.map(nullsOut)),
+});
+
+// --- Permit ---
+const PERMITS = new WeakSet();
+// Used by @tsus/v2/authority only; not declared in index.d.ts.
+export const __issuePermit = (action, resource) => {
+ const p = Object.freeze({ action, resource });
+ PERMITS.add(p);
+ return p;
+};
+export const isGenuinePermit = (v) => typeof v === "object" && v !== null && PERMITS.has(v);
+
+// --- Secret ---
+const SECRETS = new WeakMap();
+const REDACTED = "[secret]";
+const inspect = Symbol.for("nodejs.util.inspect.custom");
+export const secret = (value) => {
+ const s = Object.freeze({
+ toString: () => REDACTED,
+ toJSON: () => REDACTED,
+ [Symbol.toPrimitive]: () => REDACTED,
+ [inspect]: () => REDACTED,
+ });
+ SECRETS.set(s, value);
+ return s;
+};
+export const reveal = (s) => {
+ if (!SECRETS.has(s)) throw new TypeError("reveal: not a Secret");
+ return SECRETS.get(s);
+};
+
+// --- Untrusted ---
+// An Untrusted is the raw string at runtime; the type is what keeps it out of sinks.
+export const untrusted = (text) => text;
+export const untrustedLength = (text) => text.length;
+export const mapUntrusted = (text, f) => f(text);
+export const validate = (text, pattern) => {
+ const m = new RegExp(pattern.source, pattern.flags.replace("g", "").replace("y", "")).exec(text);
+ return m !== null && m.index === 0 && m[0].length === text.length ? text : undefined;
+};
+
+const HTML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
+const SAFE_HTML = Symbol("tsus.html");
+const escapeText = (text) => String(text).replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
+const safeHtml = (s) => Object.freeze({ html: s, toString: () => s, [SAFE_HTML]: true });
+export const escapeHtml = (text) => safeHtml(escapeText(text));
+const htmlPart = (v) => {
+ if (v === undefined || v === false) return "";
+ if (Array.isArray(v)) return v.map(htmlPart).join("");
+ if (typeof v === "object" && v !== null && v[SAFE_HTML] === true) return v.html;
+ return escapeText(v);
+};
+export const html = (strings, ...values) => {
+ let out = strings[0];
+ for (let i = 0; i < values.length; i += 1) out += htmlPart(values[i]) + strings[i + 1];
+ return safeHtml(out);
+};
+
+// The markers Rebasely's injection screen treats as framing tricks (packages/shared/injection-screen.ts).
+const ROLE_MARKERS = /<\/?\s*(untrusted|system|assistant|user|human)\b[^>]*>|<\|im_(start|end)\|>|\[\/?INST\]/gi;
+export const fence = (text, source) => {
+ const body = String(text).replace(ROLE_MARKERS, (m) => m.replace(/</g, "&lt;").replace(/\[/g, "&#91;"));
+ const label = String(source).replace(/["<>\n]/g, " ");
+ return `<untrusted source="${label}">\n${body}\n</untrusted>`;
+};
+export const prompt = (strings, ...values) => {
+ let out = strings[0];
+ for (let i = 0; i < values.length; i += 1) out += String(values[i]) + strings[i + 1];
+ return out;
+};
View file
Addedpackages/v2/package.json+17−0
@@ -0,0 +1,17 @@
+{
+ "name": "@tsus/v2",
+ "version": "0.2.0",
+ "type": "module",
+ "description": "TSUS v2: a tiny, erasable type library for plain .ts (Option, Result, match, Sql, Permit, Secret, Untrusted). The checker lives in @tsus/cli (tsus check --v2, tsus audit).",
+ "sideEffects": false,
+ "exports": {
+ ".": {
+ "types": "./index.d.ts",
+ "default": "./index.js"
+ },
+ "./authority": {
+ "types": "./authority.d.ts",
+ "default": "./authority.js"
+ }
+ }
+}
View file
Addedtsconfig.json+29−0
@@ -0,0 +1,29 @@
+{
+ // `npm run typecheck`: the v2 type library and every v2 .ts file that is supposed to compile,
+ // under the strictest erasable settings. Files with planted bugs (examples/60-v2-security-demo/v2,
+ // examples/62-v2-rejected) are left out on purpose, as is the legacy file the audit example reads
+ // (examples/63-v2-audit, written for strict without noUncheckedIndexedAccess); the example runner
+ // checks all three.
+ "compilerOptions": {
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "erasableSyntaxOnly": true,
+ "verbatimModuleSyntax": true,
+ "target": "es2022",
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "noEmit": true,
+ "skipLibCheck": false,
+ "lib": ["es2023", "dom", "dom.iterable"],
+ "types": ["node"]
+ },
+ "include": [
+ "packages/v2/*.d.ts",
+ "examples/60-v2-security-demo/plain/src",
+ "examples/60-v2-security-demo/fixed/src",
+ "examples/60-v2-security-demo/harness",
+ "examples/61-v2-basics/src",
+ "bench/oncall"
+ ]
+}
View file

Checks

No checks reported for this commit.

Runs

No runs for this commit.