tenjin-cli 0.1.0-alpha.31 → 0.1.0-alpha.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -26
- package/dist/{_esm-MEXZI5DL.js → _esm-BIN7VY2L.js} +128 -132
- package/dist/{alive-J64H46HI.js → alive-GSOWKUOY.js} +13 -6
- package/dist/auto-update-Y24UL56V.js +24 -0
- package/dist/{ccip-7RMRLAGV.js → ccip-DHDFKTQV.js} +2 -2
- package/dist/{chunk-TTNESUPQ.js → chunk-2GP3HRYK.js} +2120 -193
- package/dist/chunk-2GP3HRYK.js.map +1 -0
- package/dist/chunk-2M2VPI2E.js +560 -0
- package/dist/chunk-2M2VPI2E.js.map +1 -0
- package/dist/{chunk-D65GNPS3.js → chunk-2RWB7RKE.js} +288 -108
- package/dist/chunk-2RWB7RKE.js.map +1 -0
- package/dist/{chunk-AGZ7PJKY.js → chunk-36RVGZNY.js} +22 -5
- package/dist/chunk-36RVGZNY.js.map +1 -0
- package/dist/chunk-3AIHRXKO.js +72 -0
- package/dist/chunk-3AIHRXKO.js.map +1 -0
- package/dist/{chunk-S4SAZ7OD.js → chunk-3FMZGI7I.js} +12 -2
- package/dist/{chunk-S4SAZ7OD.js.map → chunk-3FMZGI7I.js.map} +1 -1
- package/dist/chunk-3GNJXKIT.js +198 -0
- package/dist/chunk-3GNJXKIT.js.map +1 -0
- package/dist/{chunk-UQUOVWBG.js → chunk-4K7TQHNP.js} +7 -7
- package/dist/{chunk-A36LQPHV.js → chunk-4LMUQMBH.js} +1 -1
- package/dist/{chunk-A36LQPHV.js.map → chunk-4LMUQMBH.js.map} +1 -1
- package/dist/{chunk-KXQ4UIP7.js → chunk-4USCZ2NI.js} +2 -2
- package/dist/chunk-4YOZGGTZ.js +247 -0
- package/dist/chunk-4YOZGGTZ.js.map +1 -0
- package/dist/chunk-62KNUYWD.js +111 -0
- package/dist/chunk-62KNUYWD.js.map +1 -0
- package/dist/{chunk-POUWHWID.js → chunk-6CMM6YCB.js} +3 -3
- package/dist/{chunk-POUWHWID.js.map → chunk-6CMM6YCB.js.map} +1 -1
- package/dist/{chunk-5MARFNSB.js → chunk-A5GKIG5O.js} +49 -30
- package/dist/chunk-A5GKIG5O.js.map +1 -0
- package/dist/{chunk-YFPY4ONH.js → chunk-AGMVASXZ.js} +4 -4
- package/dist/chunk-BF4XHEQK.js +116 -0
- package/dist/chunk-BF4XHEQK.js.map +1 -0
- package/dist/chunk-BFDQ4WNW.js +119 -0
- package/dist/chunk-BFDQ4WNW.js.map +1 -0
- package/dist/{chunk-P4NH7OUK.js → chunk-C2Q76BVM.js} +49 -50
- package/dist/chunk-C2Q76BVM.js.map +1 -0
- package/dist/chunk-CEXSOI5R.js +808 -0
- package/dist/chunk-CEXSOI5R.js.map +1 -0
- package/dist/{chunk-QSCPK4F5.js → chunk-E7SW44LM.js} +4 -11
- package/dist/chunk-E7SW44LM.js.map +1 -0
- package/dist/chunk-EDJWHDDL.js +33 -0
- package/dist/chunk-EDJWHDDL.js.map +1 -0
- package/dist/chunk-F3ED5WTR.js +13 -0
- package/dist/chunk-F3ED5WTR.js.map +1 -0
- package/dist/{chunk-K72RURN3.js → chunk-FVIGCDSV.js} +2 -2
- package/dist/chunk-FVIGCDSV.js.map +1 -0
- package/dist/{chunk-5K5W4S66.js → chunk-GTTUCOPD.js} +2 -2
- package/dist/{chunk-4ZZO6ULA.js → chunk-HDPUXS3Z.js} +19 -48
- package/dist/chunk-HDPUXS3Z.js.map +1 -0
- package/dist/{chunk-LEFIX6RS.js → chunk-HGGWCP7W.js} +31 -11
- package/dist/chunk-HGGWCP7W.js.map +1 -0
- package/dist/{chunk-ORWL5BSN.js → chunk-HGZEPQUT.js} +2 -2
- package/dist/chunk-HMWYAUA6.js +478 -0
- package/dist/chunk-HMWYAUA6.js.map +1 -0
- package/dist/{chunk-7QKHZQKW.js → chunk-IADZOXKN.js} +39 -6
- package/dist/chunk-IADZOXKN.js.map +1 -0
- package/dist/{chunk-7Q5FDF65.js → chunk-IE7P2BZE.js} +3 -3
- package/dist/{chunk-77TCKDEC.js → chunk-ILNIZ5I2.js} +788 -508
- package/dist/chunk-ILNIZ5I2.js.map +1 -0
- package/dist/{hosts-FWZOV26H.js → chunk-INTFHMU4.js} +79 -24
- package/dist/chunk-INTFHMU4.js.map +1 -0
- package/dist/{chunk-6E5R45ZO.js → chunk-J57UC3DD.js} +4 -4
- package/dist/{chunk-6E5R45ZO.js.map → chunk-J57UC3DD.js.map} +1 -1
- package/dist/chunk-JNJWBTU2.js +3497 -0
- package/dist/chunk-JNJWBTU2.js.map +1 -0
- package/dist/{chunk-7WU4OPLP.js → chunk-KM7RY2ZS.js} +5 -3
- package/dist/{chunk-7WU4OPLP.js.map → chunk-KM7RY2ZS.js.map} +1 -1
- package/dist/chunk-L6JEXB3E.js +293 -0
- package/dist/chunk-L6JEXB3E.js.map +1 -0
- package/dist/chunk-LRW6S53P.js +450 -0
- package/dist/chunk-LRW6S53P.js.map +1 -0
- package/dist/{chunk-UKY4CHNC.js → chunk-LXAYUOXI.js} +24 -11
- package/dist/chunk-LXAYUOXI.js.map +1 -0
- package/dist/{chunk-WJXLQXJY.js → chunk-MPZUYCAP.js} +4 -1
- package/dist/{chunk-WJXLQXJY.js.map → chunk-MPZUYCAP.js.map} +1 -1
- package/dist/chunk-NDGZDTSJ.js +393 -0
- package/dist/chunk-NDGZDTSJ.js.map +1 -0
- package/dist/{chunk-SJLTEINJ.js → chunk-OJNTCYQQ.js} +17 -1
- package/dist/chunk-OJNTCYQQ.js.map +1 -0
- package/dist/{chunk-OHRR5OYM.js → chunk-P3LFTKE7.js} +5 -10
- package/dist/chunk-P3LFTKE7.js.map +1 -0
- package/dist/{chunk-XZKD7DIF.js → chunk-RL5UUDT4.js} +3 -3
- package/dist/{chunk-XZKD7DIF.js.map → chunk-RL5UUDT4.js.map} +1 -1
- package/dist/{chunk-5C32RLTA.js → chunk-RVPYTUP4.js} +20 -5
- package/dist/chunk-RVPYTUP4.js.map +1 -0
- package/dist/{chunk-YVFXE7RR.js → chunk-SNNSAGMT.js} +7279 -2627
- package/dist/chunk-SNNSAGMT.js.map +1 -0
- package/dist/{chunk-WK7F3B2E.js → chunk-SO3XRZPX.js} +3 -3
- package/dist/{chunk-R5LCN54M.js → chunk-TC2WZLSC.js} +13 -17
- package/dist/{chunk-R5LCN54M.js.map → chunk-TC2WZLSC.js.map} +1 -1
- package/dist/{chunk-B7HUUJOK.js → chunk-TKPF35W6.js} +3 -3
- package/dist/{chunk-KXVP2VKA.js → chunk-U3IKUGRP.js} +32 -33
- package/dist/chunk-U3IKUGRP.js.map +1 -0
- package/dist/{chunk-AKWGE6JQ.js → chunk-UUGOUOVT.js} +37 -2
- package/dist/chunk-UUGOUOVT.js.map +1 -0
- package/dist/{chunk-2XLC3AEX.js → chunk-UXZONNEQ.js} +536 -510
- package/dist/chunk-UXZONNEQ.js.map +1 -0
- package/dist/{chunk-7ZRL2LBQ.js → chunk-V2LQLN5H.js} +6 -6
- package/dist/{chunk-NEFNKLBE.js → chunk-WFSPCCVW.js} +1536 -423
- package/dist/chunk-WFSPCCVW.js.map +1 -0
- package/dist/{chunk-27EPWVOY.js → chunk-WXA2BWTE.js} +7 -3
- package/dist/chunk-WXA2BWTE.js.map +1 -0
- package/dist/chunk-WYXUQGOL.js +191 -0
- package/dist/chunk-WYXUQGOL.js.map +1 -0
- package/dist/chunk-X5ZBP3IY.js +97 -0
- package/dist/chunk-X5ZBP3IY.js.map +1 -0
- package/dist/{chunk-MNXS2U45.js → chunk-ZDZERB6L.js} +206 -297
- package/dist/chunk-ZDZERB6L.js.map +1 -0
- package/dist/chunk-ZNNXRNFD.js +113 -0
- package/dist/chunk-ZNNXRNFD.js.map +1 -0
- package/dist/{chunk-FW75G2W4.js → chunk-ZURZHELF.js} +5 -5
- package/dist/{cli-D5OE3URZ.js → cli-E36SPKBW.js} +145 -64
- package/dist/{cli-D5OE3URZ.js.map → cli-E36SPKBW.js.map} +1 -1
- package/dist/{codex-event-PPNVRRDH.js → codex-event-ZO2GEFE6.js} +2 -2
- package/dist/{codex-host-2RJOJW2B.js → codex-host-KECJVTA2.js} +7 -6
- package/dist/codex-install-HQZDGFXW.js +436 -0
- package/dist/codex-install-HQZDGFXW.js.map +1 -0
- package/dist/{config-ZD4OB2DO.js → config-HY2E4GGW.js} +21 -17
- package/dist/doctor-I6XQEKWD.js +1323 -0
- package/dist/doctor-I6XQEKWD.js.map +1 -0
- package/dist/{env-proxy-XL4P73MZ.js → env-proxy-R6ZMLQTT.js} +6 -2
- package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js → ethersCompat-Df4a6QIZ-X6YZWAML.js} +3 -3
- package/dist/{fund-5ITKQGYF.js → fund-2QRO7OJL.js} +43 -37
- package/dist/{fund-5ITKQGYF.js.map → fund-2QRO7OJL.js.map} +1 -1
- package/dist/hook-command-2UBCSZG6.js +43 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
- package/dist/hosts/claude/tenjin/hooks/register.tsx +51 -11
- package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +82 -0
- package/dist/hosts/claude/tenjin/types/index.d.ts +2 -1
- package/dist/hosts/codex/tenjin/.mcp.json +3 -0
- package/dist/hosts/codex/tenjin/hooks/hooks.json +51 -5
- package/dist/hosts-DVQJ32QC.js +38 -0
- package/dist/index.js +32 -11
- package/dist/index.js.map +1 -1
- package/dist/install-ILUX5C4A.js +107 -0
- package/dist/{install-identity-K7EJIQFP.js → install-identity-TZKGY6LQ.js} +11 -10
- package/dist/install-wallet-5M4OTYLX.js +281 -0
- package/dist/install-wallet-5M4OTYLX.js.map +1 -0
- package/dist/isows-native-Q2UDIVPT.js +9 -0
- package/dist/isows-native-Q2UDIVPT.js.map +1 -0
- package/dist/{mcp-3LIJSSJB.js → mcp-LE4DUS22.js} +785 -211
- package/dist/mcp-LE4DUS22.js.map +1 -0
- package/dist/{mine.wasm-6PIT3DK6.js → mine.wasm-QFAHIFPY.js} +2 -2
- package/dist/{mine.wasm-6PIT3DK6.js.map → mine.wasm-QFAHIFPY.js.map} +1 -1
- package/dist/{package-ZKQFDWLE.js → package-IJFGMWEV.js} +4 -2
- package/dist/passphrase-IFTDS3CU.js +44 -0
- package/dist/{paths-POPTXJO6.js → paths-XCSAKISU.js} +10 -2
- package/dist/{pay-WHBERZ3W.js → pay-WCG3IH4R.js} +29 -29
- package/dist/{payments-KVICEKD2.js → payments-HFPPWHTV.js} +15 -14
- package/dist/{payments-KVICEKD2.js.map → payments-HFPPWHTV.js.map} +1 -1
- package/dist/plugin-registration-PZFI5GZW.js +68 -0
- package/dist/{redact-6W23GGJC.js → redact-D7ASVWKL.js} +2 -2
- package/dist/runtime-UZOKSUZX.js +1321 -0
- package/dist/runtime-UZOKSUZX.js.map +1 -0
- package/dist/runtime-fetch-ZSSSK72Y.js +23 -0
- package/dist/runtime-layout-WIDILZ6K.js +25 -0
- package/dist/{send-7G7Y7DLN.js → send-GCVEAQKL.js} +24 -22
- package/dist/{send-7G7Y7DLN.js.map → send-GCVEAQKL.js.map} +1 -1
- package/dist/{status-OF7RH5HM.js → status-HCVAOCN7.js} +55 -25
- package/dist/status-HCVAOCN7.js.map +1 -0
- package/dist/{status-line-XOUE6MPL.js → status-line-OPCXDHL2.js} +10 -9
- package/dist/{status-line-XOUE6MPL.js.map → status-line-OPCXDHL2.js.map} +1 -1
- package/dist/uninstall-BAWRBXXQ.js +481 -0
- package/dist/uninstall-BAWRBXXQ.js.map +1 -0
- package/dist/update-CACXLQLR.js +56 -0
- package/dist/update-CACXLQLR.js.map +1 -0
- package/dist/{usdc-OGOGEHV2.js → usdc-VG4CIOUK.js} +6 -8
- package/dist/usdc-VG4CIOUK.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-S3DA7DFW.js → viemAdapter-By13KInL-DOFTEIJV.js} +3 -3
- package/dist/viemAdapter-By13KInL-DOFTEIJV.js.map +1 -0
- package/dist/wallet-QL4UUXEZ.js +55 -0
- package/dist/wallet-QL4UUXEZ.js.map +1 -0
- package/dist/wallet-kdf-worker.mjs +8 -8
- package/docs/agent-permissions.md +50 -28
- package/docs/safety-model.md +1 -1
- package/docs/troubleshooting.md +72 -1
- package/package.json +17 -4
- package/scripts/installers/install.ps1 +67 -0
- package/scripts/installers/install.sh +68 -0
- package/dist/_esm-C5CRWCYU.js +0 -3737
- package/dist/_esm-C5CRWCYU.js.map +0 -1
- package/dist/ccip-NLCSCHKI.js +0 -19
- package/dist/chunk-27EPWVOY.js.map +0 -1
- package/dist/chunk-2XLC3AEX.js.map +0 -1
- package/dist/chunk-4ZZO6ULA.js.map +0 -1
- package/dist/chunk-5C32RLTA.js.map +0 -1
- package/dist/chunk-5IEP5EGE.js +0 -5332
- package/dist/chunk-5IEP5EGE.js.map +0 -1
- package/dist/chunk-5MARFNSB.js.map +0 -1
- package/dist/chunk-77TCKDEC.js.map +0 -1
- package/dist/chunk-7EKYXMUO.js +0 -7536
- package/dist/chunk-7EKYXMUO.js.map +0 -1
- package/dist/chunk-7QKHZQKW.js.map +0 -1
- package/dist/chunk-AGZ7PJKY.js.map +0 -1
- package/dist/chunk-AKWGE6JQ.js.map +0 -1
- package/dist/chunk-BL3332HQ.js +0 -7611
- package/dist/chunk-BL3332HQ.js.map +0 -1
- package/dist/chunk-D65GNPS3.js.map +0 -1
- package/dist/chunk-EGELTSPU.js +0 -2865
- package/dist/chunk-EGELTSPU.js.map +0 -1
- package/dist/chunk-GA7JETVM.js +0 -150
- package/dist/chunk-GA7JETVM.js.map +0 -1
- package/dist/chunk-I3EQFHCD.js +0 -175
- package/dist/chunk-I3EQFHCD.js.map +0 -1
- package/dist/chunk-K3I7C2MO.js +0 -1185
- package/dist/chunk-K3I7C2MO.js.map +0 -1
- package/dist/chunk-K72RURN3.js.map +0 -1
- package/dist/chunk-KXVP2VKA.js.map +0 -1
- package/dist/chunk-LEFIX6RS.js.map +0 -1
- package/dist/chunk-MNXS2U45.js.map +0 -1
- package/dist/chunk-NEFNKLBE.js.map +0 -1
- package/dist/chunk-OHRR5OYM.js.map +0 -1
- package/dist/chunk-P4NH7OUK.js.map +0 -1
- package/dist/chunk-QSCPK4F5.js.map +0 -1
- package/dist/chunk-SJLTEINJ.js.map +0 -1
- package/dist/chunk-TTNESUPQ.js.map +0 -1
- package/dist/chunk-UKY4CHNC.js.map +0 -1
- package/dist/chunk-V6BSF6OC.js +0 -260
- package/dist/chunk-V6BSF6OC.js.map +0 -1
- package/dist/chunk-YVFXE7RR.js.map +0 -1
- package/dist/codex-install-UUZ6QMBQ.js +0 -221
- package/dist/codex-install-UUZ6QMBQ.js.map +0 -1
- package/dist/doctor-KBR34Q4B.js +0 -601
- package/dist/doctor-KBR34Q4B.js.map +0 -1
- package/dist/hook-command-4TYCHHRL.js +0 -39
- package/dist/hosts-FWZOV26H.js.map +0 -1
- package/dist/install-XWGE4Q7L.js +0 -77
- package/dist/install-wallet-XQ6XFZV4.js +0 -117
- package/dist/install-wallet-XQ6XFZV4.js.map +0 -1
- package/dist/mcp-3LIJSSJB.js.map +0 -1
- package/dist/plugin-registration-5TIA564H.js +0 -54
- package/dist/status-OF7RH5HM.js.map +0 -1
- package/dist/uninstall-JXUAFNDB.js +0 -158
- package/dist/uninstall-JXUAFNDB.js.map +0 -1
- package/dist/update-ZKUERSO2.js +0 -44
- package/dist/wallet-2HA6W4R4.js +0 -43
- /package/dist/{_esm-MEXZI5DL.js.map → _esm-BIN7VY2L.js.map} +0 -0
- /package/dist/{alive-J64H46HI.js.map → alive-GSOWKUOY.js.map} +0 -0
- /package/dist/{ccip-7RMRLAGV.js.map → auto-update-Y24UL56V.js.map} +0 -0
- /package/dist/{ccip-NLCSCHKI.js.map → ccip-DHDFKTQV.js.map} +0 -0
- /package/dist/{chunk-UQUOVWBG.js.map → chunk-4K7TQHNP.js.map} +0 -0
- /package/dist/{chunk-KXQ4UIP7.js.map → chunk-4USCZ2NI.js.map} +0 -0
- /package/dist/{chunk-YFPY4ONH.js.map → chunk-AGMVASXZ.js.map} +0 -0
- /package/dist/{chunk-5K5W4S66.js.map → chunk-GTTUCOPD.js.map} +0 -0
- /package/dist/{chunk-ORWL5BSN.js.map → chunk-HGZEPQUT.js.map} +0 -0
- /package/dist/{chunk-7Q5FDF65.js.map → chunk-IE7P2BZE.js.map} +0 -0
- /package/dist/{chunk-WK7F3B2E.js.map → chunk-SO3XRZPX.js.map} +0 -0
- /package/dist/{chunk-B7HUUJOK.js.map → chunk-TKPF35W6.js.map} +0 -0
- /package/dist/{chunk-7ZRL2LBQ.js.map → chunk-V2LQLN5H.js.map} +0 -0
- /package/dist/{chunk-FW75G2W4.js.map → chunk-ZURZHELF.js.map} +0 -0
- /package/dist/{codex-event-PPNVRRDH.js.map → codex-event-ZO2GEFE6.js.map} +0 -0
- /package/dist/{codex-host-2RJOJW2B.js.map → codex-host-KECJVTA2.js.map} +0 -0
- /package/dist/{config-ZD4OB2DO.js.map → config-HY2E4GGW.js.map} +0 -0
- /package/dist/{env-proxy-XL4P73MZ.js.map → env-proxy-R6ZMLQTT.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js.map → ethersCompat-Df4a6QIZ-X6YZWAML.js.map} +0 -0
- /package/dist/{hook-command-4TYCHHRL.js.map → hook-command-2UBCSZG6.js.map} +0 -0
- /package/dist/{install-XWGE4Q7L.js.map → hosts-DVQJ32QC.js.map} +0 -0
- /package/dist/{install-identity-K7EJIQFP.js.map → install-ILUX5C4A.js.map} +0 -0
- /package/dist/{package-ZKQFDWLE.js.map → install-identity-TZKGY6LQ.js.map} +0 -0
- /package/dist/{paths-POPTXJO6.js.map → package-IJFGMWEV.js.map} +0 -0
- /package/dist/{pay-WHBERZ3W.js.map → passphrase-IFTDS3CU.js.map} +0 -0
- /package/dist/{plugin-registration-5TIA564H.js.map → paths-XCSAKISU.js.map} +0 -0
- /package/dist/{redact-6W23GGJC.js.map → pay-WCG3IH4R.js.map} +0 -0
- /package/dist/{update-ZKUERSO2.js.map → plugin-registration-PZFI5GZW.js.map} +0 -0
- /package/dist/{usdc-OGOGEHV2.js.map → redact-D7ASVWKL.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-S3DA7DFW.js.map → runtime-fetch-ZSSSK72Y.js.map} +0 -0
- /package/dist/{wallet-2HA6W4R4.js.map → runtime-layout-WIDILZ6K.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/redact.ts","../src/lib/redact-rules.json","../src/lib/bip39-wordlist.json"],"sourcesContent":["/**\n * The one redaction module: every surface that decides what text may leave\n * this machine reads the same rule table (`redact-rules.json`) through this\n * file. Two verbs over one table, and the audience is a parameter:\n *\n * `findings(text, scope)` is the deterministic, offline publish scan. Pure:\n * identical input yields an identical `Finding[]`, no network and no model\n * call. It REPORTS, it never rewrites: every finding is a detector id, a tier,\n * offsets and a masked excerpt that never carries the matched secret. Locally\n * a finding is a flag the consent flow shows the agent, which fixes the text or\n * overrides with `--yes`; the server's ingest gate is the one place that\n * refuses (vendor tokens, private keys, seed phrases, DB passwords, bearer\n * headers). `publish` is the marketplace and reports every row; `team` is the\n * team shelf and reports only the rows whose `scopes` include it. WHICH rows\n * is data on the rule, never a list in a caller.\n *\n * `mask(text)` is the query-side verb: for the rows scoped `query` it replaces\n * each match with that row's excerpt (`ghp_…[redacted 36 chars]`,\n * `postgres://app:[redacted]@host`, `PGPASSWORD=[redacted 7 chars]`,\n * `0x…[redacted 64 chars]`) and touches nothing else. The regex rows run\n * first, then the hex-key, PEM and seed-phrase algorithms. Precision first,\n * the way gitleaks and GitHub push protection work: a vendor prefix fires on\n * format alone, the generic assignment rule needs a secret-named word plus `=`\n * or `:`, and entropy is never a trigger. Paths, hosts, IPs, commit SHAs, env\n * names and prose are never touched; a long mixed token in a URL path is\n * (owner policy, tenjin-agent#197 and the 2026-09-04 decision in\n * tenjin-notes/loop-redesign/06-pr-a-redact.md: search availability over\n * scrubbing; measured, the old scrub altered 16% of real prompts to stop two\n * vendor tokens).\n *\n * Two invariants, pinned by redact.fixtures.test.ts and redact.test.ts:\n *\n * REDACTION: a `block` excerpt is masked — a type-identifying prefix plus a\n * redaction count, never the matched secret. `pem-private-key` is the one\n * exception, its excerpt being the armor header. Secret-shaped warns\n * (secret-assignment, customer-identifier, high-entropy-string) are masked too.\n *\n * ReDoS: no pattern may contain a quantified group whose body can also match the\n * group's own separator while a further obligation follows it. Audited against a\n * single line of hundreds of kilobytes, the shape a JSONL transcript record takes.\n *\n * The rule corpus lives as DATA in `redact-rules.json` so the tenjin server-side\n * ingest gate can vendor it verbatim; this file compiles that data and\n * implements the handlers and algorithmic detectors it names. Per-rule\n * attribution is in the data file's `source` field and in NOTICE.md. No pattern\n * set is a runtime dependency: this is a wallet-holding CLI, kept offline with a\n * tight dep tree by design.\n */\n\nimport { createHash } from 'node:crypto';\nimport corpusJson from './redact-rules.json';\nimport wordlistJson from './bip39-wordlist.json';\n\n/** Where a rule applies: masked in hook queries, reported on the public\n * marketplace, reported on a team shelf. A row may carry any combination. */\nexport type Scope = 'query' | 'publish' | 'team';\n/** The audiences `findings()` reports for. */\nexport type ReportScope = Exclude<Scope, 'query'>;\n\nexport type FindingSeverity = 'block' | 'warn';\n\nexport interface Finding {\n /** Stable machine id for the detector, e.g. \"aws-access-key\". */\n check: string;\n severity: FindingSeverity;\n /** 1-based line number of the match (its start line, for multi-line matches). */\n line: number;\n /** [startColumn, endColumn) within `line`, 0-based (the start line for spans). */\n span: [number, number];\n /** Human-readable snippet; masked for every `block` finding. */\n excerpt: string;\n}\n\n/** Contiguous quoted/fenced runs at or above this word count read as copied. */\nconst LONG_QUOTE_WORDS = 80;\n\nexport function findings(text: string, scope: ReportScope): Finding[] {\n const lines = text.split('\\n');\n // EVERY detector runs whatever the scope, and the scope filters the RESULT.\n // The entropy catch-all suppresses itself against the spans the named\n // detectors claimed, and that set has to be the full one: a checksummed\n // wallet address is a publish-only warn, and on a team shelf it must stay\n // silent rather than resurface as high-entropy-string because the detector\n // that knows what it is was switched off.\n const found: Finding[] = [\n ...scanHex64(lines),\n ...scanLineDetectors(lines),\n ...scanPemBlocks(lines),\n ...scanSeedPhrases(lines),\n ...scanEnvDumpBlocks(lines),\n ...scanLongVerbatim(lines),\n ];\n const named = dedupeAndSort(suppressEmailsInDbUris(found));\n const all = dedupeAndSort([...named, ...scanHighEntropy(lines, named)]);\n if (scope === 'publish') return all;\n // Filtered by the EMITTING rule's scopes, never by a list of check names:\n // `checksFor` maps an emitted check (hex32-value) through the rule it comes\n // from, so dropping `team` from a rule's scopes drops everything it emits.\n const keep = CHECKS[scope];\n return all.filter((f) => keep.has(f.check));\n}\n\n/**\n * Replace every match of a `query`-scoped row with that row's masked excerpt.\n * Nothing else changes: no deletion, no squash, no bound. The `skip` handlers\n * apply exactly as they do for `findings()`, so a placeholder or a `$VAR`\n * value is left as written.\n */\nexport function mask(text: string): string {\n // C0 bytes are deleted first (whitespace kept): a control byte inside a name\n // is a splitter, `api_key<0x01>=hunter2` reads as two tokens to every row\n // below, and the hooks' clean() only removes it after the mask has decided.\n // eslint-disable-next-line no-control-regex\n let out = text.replace(/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]/g, '');\n // Table order is mask order: the assignment row is first so a value that is\n // itself a vendor token is taken whole, name kept, and no later row sees a\n // stub to re-match.\n for (const detector of MASK_DETECTORS) {\n out = out.replace(detector.re, (...args: unknown[]) => {\n // replace() hands (match, ...groups, offset, input[, named groups]).\n // Rebuilt as an exec array so a skip can read the text around its match.\n const tail = typeof args.at(-1) === 'object' ? 3 : 2;\n const m = Object.assign(args.slice(0, -tail), {\n index: args.at(-tail) as number,\n input: args.at(-tail + 1) as string,\n }) as unknown as RegExpExecArray;\n return detector.skip?.(m) === true ? m[0] : detector.excerpt(m);\n });\n }\n // The algorithm rows after the regex pass, through the same scanners\n // findings() runs, so a key the publish scan blocks is a key the packet\n // never carries. A value the regex pass already masked no longer matches.\n if (MASKED_ALGORITHMS.has('hex64') || MASKED_ALGORITHMS.has('bip39')) {\n out = out.split('\\n').map(maskLineSpans).join('\\n');\n }\n if (MASKED_ALGORITHMS.has('bip39')) out = maskLooseMnemonics(out);\n return MASKED_ALGORITHMS.has('pemBlock') ? maskPemBlocks(out) : out;\n}\n\n/**\n * One line's hex and seed-phrase spans, each replaced by its finding's\n * excerpt. Built in one left-to-right pass rather than a splice per span: a\n * transcript line can carry thousands of keys. A `hex32-value` is a hash, not\n * a key, and stays as written.\n *\n * A wordlist run longer than the longest recovery phrase is not masked here:\n * a run of common words that long is text a routing decision reads (a repeated\n * word, a pasted list). {@link maskLooseMnemonics} masks any phrase inside it.\n * The publish scan reports the whole run either way.\n */\nfunction maskLineSpans(line: string): string {\n const lines = [line];\n const spans = [\n ...(MASKED_ALGORITHMS.has('hex64') ? scanHex64(lines) : []),\n ...(MASKED_ALGORITHMS.has('bip39') ? scanSeedPhrases(lines) : []),\n ]\n .filter((f) => f.check !== 'hex32-value')\n .filter(\n (f) =>\n f.check !== 'bip39-seed-phrase' ||\n line.slice(f.span[0], f.span[1]).split(/[\\s\"'`]+/).length <= SEED_PHRASE_MAX_WORDS,\n )\n .sort((a, b) => a.span[0] - b.span[0]);\n if (spans.length === 0) return line;\n const parts: string[] = [];\n let cursor = 0;\n for (const f of spans) {\n if (f.span[0] < cursor) continue;\n parts.push(line.slice(cursor, f.span[0]), f.excerpt);\n cursor = f.span[1];\n }\n parts.push(line.slice(cursor));\n return parts.join('');\n}\n\n/**\n * A PEM private key from its BEGIN marker through its END marker, or to the\n * end of the text when the paste has no END line. The armor header is kept as\n * the type marker; everything after it is key material and goes.\n */\nfunction maskPemBlocks(text: string): string {\n let out = '';\n let rest = text;\n for (;;) {\n const begin = PEM_BEGIN.exec(rest);\n if (begin === null) return out + rest;\n const body = begin.index + begin[0].length;\n const end = PEM_END.exec(rest.slice(body));\n const stop = end === null ? rest.length : body + end.index + end[0].length;\n out += rest.slice(0, begin.index) + maskKeeping(rest.slice(begin.index, stop), begin[0].length);\n rest = rest.slice(stop);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Rule corpus: redact-rules.json compiled into executable detectors.\n// ---------------------------------------------------------------------------\n\ninterface RuleExcerpt {\n kind: string;\n keep?: number;\n max?: number;\n head?: number;\n tail?: number;\n handler?: string;\n}\n\ninterface Rule {\n id: string;\n tier: string;\n scopes: string[];\n description: string;\n source: string;\n match: { kind: string; pattern?: string; flags?: string; algorithm?: string };\n excerpt: RuleExcerpt;\n /** Drop the match without a finding (e.g. a placeholder value). */\n skip?: { handler: string };\n}\n\nconst SCOPES: ReadonlySet<string> = new Set(['query', 'publish', 'team']);\n\nconst CORPUS = corpusJson as unknown as {\n schemaVersion: number;\n rules: Rule[];\n publicHexConstants?: Array<{ value: string; name: string }>;\n};\n\n/** Algorithmic detectors this file implements; a corpus entry naming any other fails to compile. */\nconst ALGORITHMS = new Set(['hex64', 'pemBlock', 'bip39', 'envDump', 'entropy', 'longVerbatim']);\n/** The algorithms `mask()` can apply. A `query` row naming any other fails to compile. */\nconst MASKABLE_ALGORITHMS: ReadonlySet<string> = new Set(['hex64', 'pemBlock', 'bip39']);\n\nconst EXCERPT_HANDLERS: Record<string, (m: RegExpExecArray) => string> = {\n googleKey: (m) => maskKeeping(m[0], m[0].startsWith('AIza') ? 4 : 7),\n dbConnectionUri: (m) => `${m[1]}://${m[2]}:[redacted]@${m[4]}`,\n bearerToken: (m) => `Authorization: Bearer [redacted ${m[1]?.length ?? 0} chars]`,\n labeledValue: (m) => `${m[1]}=[redacted ${dequote(m[2] ?? '').length} chars]`,\n localPath: localPathExcerpt,\n};\n\nconst SKIP_HANDLERS: Record<string, (m: RegExpExecArray) => boolean> = {\n exampleDbPassword: (m) => isPlaceholder(m[3] ?? '') || isExamplePassword(m[3] ?? ''),\n placeholderGroup1: (m) => isPlaceholder(m[1] ?? ''),\n nonLiteralValue: skipNonLiteralValue,\n placeholderUsername: (m) => PLACEHOLDER_USERNAME.test(m[1] ?? m[2] ?? ''),\n reservedExampleEmail: (m) => RESERVED_EXAMPLE_DOMAIN.test(m[0]),\n hashLabelled: isLabelledHash,\n};\n\ninterface LineDetector {\n check: string;\n severity: FindingSeverity;\n scopes: ReadonlySet<string>;\n /** Global regex; `lastIndex` is reset per line. */\n re: RegExp;\n /** Build the (possibly masked) excerpt from a single match. */\n excerpt: (m: RegExpExecArray) => string;\n /** Drop this match without a finding (e.g. a placeholder value). */\n skip?: (m: RegExpExecArray) => boolean;\n}\n\n/**\n * Compile the data corpus. Throws rather than degrading: a corpus entry naming a\n * handler this build does not implement is a vendoring mistake, and a scan that\n * silently drops a block-tier detector is worse than one that refuses to start.\n */\nfunction validateScopes(rule: Rule): void {\n if (!Array.isArray(rule.scopes) || rule.scopes.length === 0) {\n throw new Error(`redact-rules.json: rule ${rule.id} has no scopes`);\n }\n for (const scope of rule.scopes) {\n if (!SCOPES.has(scope))\n throw new Error(`redact-rules.json: rule ${rule.id} names unknown scope ${scope}`);\n }\n if (rule.tier !== 'block' && rule.tier !== 'warn') {\n throw new Error(`redact-rules.json: rule ${rule.id} has unknown tier ${String(rule.tier)}`);\n }\n if (!rule.scopes.includes('publish')) {\n throw new Error(`redact-rules.json: rule ${rule.id} reports for team but not publish`);\n }\n // The block tier is reported on every shelf; the server refuses on it.\n if (rule.tier === 'block' && !rule.scopes.includes('team')) {\n throw new Error(`redact-rules.json: block rule ${rule.id} must be scoped to team as well`);\n }\n const maskable =\n rule.match.kind === 'regex' ||\n (rule.match.kind === 'algorithm' && MASKABLE_ALGORITHMS.has(rule.match.algorithm ?? ''));\n if (rule.scopes.includes('query') && !maskable) {\n throw new Error(\n `redact-rules.json: rule ${rule.id} is masked in queries but mask() cannot apply it`,\n );\n }\n}\n\nfunction compileSkip(rule: Rule): ((m: RegExpExecArray) => boolean) | undefined {\n const skip = rule.skip === undefined ? undefined : SKIP_HANDLERS[rule.skip.handler];\n if (rule.skip !== undefined && skip === undefined) {\n throw new Error(`redact-rules.json: rule ${rule.id} names unknown skip ${rule.skip.handler}`);\n }\n return skip;\n}\n\nfunction compileRegex(rule: Rule): RegExp {\n if (rule.match.kind !== 'regex' || rule.match.pattern === undefined) {\n throw new Error(`redact-rules.json: rule ${rule.id} has unknown match kind ${rule.match.kind}`);\n }\n return new RegExp(rule.match.pattern, rule.match.flags ?? 'g');\n}\n\nfunction compileLineDetectors(rules: Rule[]): LineDetector[] {\n const out: LineDetector[] = [];\n for (const rule of rules) {\n if (rule.match.kind === 'algorithm') continue;\n out.push({\n check: rule.id,\n severity: rule.tier as FindingSeverity,\n scopes: new Set(rule.scopes),\n re: compileRegex(rule),\n excerpt: compileExcerpt(rule),\n skip: compileSkip(rule),\n });\n }\n return out;\n}\n\n/**\n * Validate every row once, whatever scope asks first. Throws rather than\n * degrading: a corpus entry naming a handler this build does not implement is\n * a vendoring mistake, and a scan that silently drops a block-tier detector is\n * worse than one that refuses to start.\n */\nfunction validateCorpus(rules: Rule[]): void {\n for (const rule of rules) {\n validateScopes(rule);\n if (rule.match.kind === 'algorithm') {\n if (!ALGORITHMS.has(rule.match.algorithm ?? '')) {\n throw new Error(`redact-rules.json: rule ${rule.id} names unknown algorithm`);\n }\n continue;\n }\n compileRegex(rule);\n }\n // The converse: every algorithm this file implements has exactly one row,\n // because the row's scopes are what let its findings through. A deleted\n // bip39 row would otherwise turn the seed-phrase block into silence.\n for (const algorithm of ALGORITHMS) {\n const rows = rules.filter(\n (r) => r.match.kind === 'algorithm' && r.match.algorithm === algorithm,\n );\n if (rows.length !== 1) {\n throw new Error(\n `redact-rules.json: algorithm ${algorithm} has ${rows.length} rows, needs exactly one`,\n );\n }\n }\n}\n\nfunction compileExcerpt(rule: Rule): (m: RegExpExecArray) => string {\n const policy = rule.excerpt;\n switch (policy.kind) {\n case 'mask': {\n const keep = policy.keep ?? 0;\n return (m) => maskKeeping(m[0], keep);\n }\n case 'verbatim': {\n const max = policy.max;\n return (m) => (max === undefined ? m[0] : truncate(m[0], max));\n }\n case 'abbreviate': {\n const head = policy.head ?? 6;\n const tail = policy.tail ?? 4;\n return (m) => `${m[0].slice(0, head)}…${m[0].slice(-tail)}`;\n }\n case 'custom': {\n const handler = EXCERPT_HANDLERS[policy.handler ?? ''];\n if (handler === undefined) {\n throw new Error(`redact-rules.json: rule ${rule.id} names unknown excerpt handler`);\n }\n return handler;\n }\n default:\n throw new Error(`redact-rules.json: rule ${rule.id} has unknown excerpt kind ${policy.kind}`);\n }\n}\n\nvalidateCorpus(CORPUS.rules);\nconst LINE_DETECTORS: LineDetector[] = compileLineDetectors(CORPUS.rules);\nconst MASK_DETECTORS: LineDetector[] = LINE_DETECTORS.filter((d) => d.scopes.has('query'));\n/** Which algorithm rows `mask()` applies is data on the row, like the regex rows. */\nconst MASKED_ALGORITHMS: ReadonlySet<string> = new Set(\n CORPUS.rules\n .filter((r) => r.match.kind === 'algorithm' && r.scopes.includes('query'))\n .map((r) => r.match.algorithm ?? ''),\n);\n\nfunction scanLineDetectors(lines: string[]): Finding[] {\n const out: Finding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n for (const detector of LINE_DETECTORS) {\n detector.re.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = detector.re.exec(line)) !== null) {\n if (!isSuppressedAsDocs(detector, m) && detector.skip?.(m) !== true) {\n out.push({\n check: detector.check,\n severity: detector.severity,\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: detector.excerpt(m),\n });\n }\n // Every detector pattern matches at least one character, so a global\n // exec() always advances lastIndex — no zero-width-match loop guard needed.\n }\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Suppression: placeholders and reserved example values.\n// ---------------------------------------------------------------------------\n\n/**\n * A match that is documentation scaffolding, not a live value: a run of `x`\n * placeholders, an angle/brace template, or a `your…` label. It exists to cut\n * warn fatigue, because `<YOUR_KEY>`-shaped samples are what teach an operator\n * to stop reading findings.\n *\n * TIER ORDERING INVARIANT — this test is a SUBSTRING test over the whole match,\n * so it may only ever suppress a `warn`. A block finding is non-bypassable by\n * contract, and a substring rule hands the bypass to anyone whose secret merely\n * CONTAINS a placeholder shape: real passwords carry `<`, `>`, `{`, `}` and\n * letter runs, so `postgres://app:Str0ng<Pw>Value@prod-db/main` is a live\n * credential, not a docs sample. Block-tier suppression is per-detector only,\n * and is anchored to the captured secret VALUE (isPlaceholder via the\n * `exampleDbPassword` / `placeholderGroup1` handlers), never to a substring of\n * the match. Pinned by \"the block tier is non-bypassable\" in scan.test.ts.\n */\nconst DOCS_PLACEHOLDER =\n /x{6,}|<[^<>]*>|\\{\\{[^{}]*\\}\\}|\\byour[_-]?(?:key|token|secret|password)\\b/i;\n\nfunction isSuppressedAsDocs(detector: LineDetector, m: RegExpExecArray): boolean {\n return detector.severity === 'warn' && DOCS_PLACEHOLDER.test(m[0]);\n}\n\n// RFC 2606 reserved second-level domains. The reserved .example TLD is NOT\n// included: `alice@corp.example` is the shape a real internal address takes in a\n// sanitized draft, and the email detector is a warn the author should still see.\nconst RESERVED_EXAMPLE_DOMAIN = /@(?:[A-Za-z0-9-]+\\.)*example\\.(?:com|org|net)$/i;\n\n// A home-path username that is a docs placeholder, not a real machine username.\nconst PLACEHOLDER_USERNAME = /^(?:user(?:name)?|you(?:rname)?|example|foo|me|myuser|somebody)$/i;\n\n/**\n * A db-connection-uri already masks the embedded password; the email detector,\n * however, would match `password@host` and echo the password verbatim in its\n * excerpt. Drop any email finding whose span sits inside a db-connection-uri\n * span on the same line so the masking cannot be bypassed.\n */\nfunction suppressEmailsInDbUris(findings: Finding[]): Finding[] {\n const uris = findings.filter((f) => f.check === 'db-connection-uri');\n if (uris.length === 0) return findings;\n return findings.filter(\n (f) =>\n f.check !== 'email' ||\n !uris.some((u) => u.line === f.line && f.span[0] >= u.span[0] && f.span[1] <= u.span[1]),\n );\n}\n\n/**\n * Never echo more than a short, non-secret prefix. The kept prefix is a public\n * type marker (`0x`, `AKIA`, `ghp_`, …), never key material; the rest is dropped.\n */\nfunction maskKeeping(match: string, prefixLen: number): string {\n const prefix = match.slice(0, Math.min(prefixLen, match.length));\n return `${prefix}…[redacted ${match.length - prefix.length} chars]`;\n}\n\nfunction truncate(value: string, max: number): string {\n return value.length > max ? `${value.slice(0, max - 3)}…` : value;\n}\n\nfunction localPathExcerpt(m: RegExpExecArray): string {\n // Splice at the capture's own offsets (d-flag indices): a plain\n // String.replace masks the FIRST occurrence of the username, which for a\n // username that is a substring of the /Users|/home prefix mangles the prefix\n // and echoes the real username.\n const bounds = m.indices?.[1] ?? m.indices?.[2];\n const masked =\n bounds === undefined\n ? m[0]\n : `${m[0].slice(0, bounds[0] - m.index)}[user]${m[0].slice(bounds[1] - m.index)}`;\n return truncate(masked, 60);\n}\n\n// Accepted gaps (owner call, tracked): a mnemonic laid out in a numbered grid\n// (`1. abandon 2. ability` across many short lines) breaks the whitespace-only\n// word run bip39 needs and is NOT detected. An all-lowercase, digit-free literal\n// that is not a BIP-39 run (a diceware passphrase, e.g.\n// PASSWORD=correcthorsebatterystaple) still yields no finding — a dictionary-word\n// run is indistinguishable from prose. Headerless base64/DER private keys are\n// detected only for OpenSSH (its magic is base64-stable); other DER encodings are not.\n\n/**\n * Shared skip for labeled-value detectors (secret-assignment,\n * customer-identifier — one helper so the two cannot drift): drop a value that\n * is a placeholder, a structural path/URL/regex, or — when UNQUOTED only, a\n * quoted string is a literal — a code expression (config.clientSecret,\n * user.account_id, hashAndSalt(input), a bare lowercase identifier).\n */\nfunction skipNonLiteralValue(m: RegExpExecArray): boolean {\n const raw = m[2] ?? '';\n const value = dequote(raw);\n if (isPlaceholder(value) || isStructural(value)) return true;\n return raw === value && isCodeExpression(value);\n}\n\n/** Strip a single matching pair of surrounding quotes from a captured value. */\nfunction dequote(value: string): string {\n const m = /^\"([^\"]*)\"$|^'([^']*)'$/.exec(value);\n return m !== null ? (m[1] ?? m[2] ?? '') : value;\n}\n\n// Placeholder tokens must match the WHOLE value, never merely a prefix: an early\n// prefix-anchored version let real secrets through (mySecretP@ss123,\n// yourCompanyProdKey_abc123, exampleRealKey99) and, because isPlaceholder also\n// gates the block-tier bearer/db-uri detectors, that was a block bypass.\nconst PLACEHOLDER_WORD =\n /^(?:xxx+|example|example-value|placeholder|redacted|changeme|dummy|sample|todo|tbd|none|null|secret|test|\\*+|\\.{3,})$/i;\n// your-/my- style kebab or snake placeholders (your-api-key, my_secret,\n// your-key-here) — lowercase words only, so a camelCase/digit-bearing real value\n// (yourCompanyProdKey_abc123) is NOT treated as a placeholder.\nconst PLACEHOLDER_PREFIX = /^(?:your|my)[-_][a-z]+(?:[-_][a-z]+)*$/i;\n\n/** A secret-assignment value that is an obvious placeholder, not a live secret. */\nfunction isPlaceholder(value: string): boolean {\n if (/^[<${%]/.test(value)) return true; // <your-key>, ${VAR}, {{x}}, %ENV%\n return PLACEHOLDER_WORD.test(value) || PLACEHOLDER_PREFIX.test(value);\n}\n\n/**\n * A right-hand side that is code, not a literal secret: a member/property access\n * (user.password), a call (hashAndSalt(input)), or a bare lowercase/snake-case\n * identifier reference (password, db_password). Only applied to UNQUOTED values —\n * a quoted string is a literal. camelCase / digit-bearing tokens are NOT code\n * (they read as opaque secrets), so a real value still fires.\n */\nfunction isCodeExpression(value: string): boolean {\n // Trailing code punctuation the value capture drags in (process.env.KEY, ).\n const v = value.replace(/[,;]+$/, '');\n if (/^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)+$/.test(v)) return true; // a.b.c\n if (/^[A-Za-z_$][\\w$.]*\\([^)]*\\)$/.test(v)) return true; // f(...)\n // A call truncated at a quoted arg by the value capture: os.environ.get(\n if (/\\($/.test(v)) return true;\n return /^[a-z_$][a-z_$]*$/.test(v); // bare lowercase identifier\n}\n\n/** A structural value (path, URL, or regex literal), not a literal secret. */\nfunction isStructural(value: string): boolean {\n return /^(?:\\.?\\.?\\/|~\\/|https?:\\/\\/|\\^)/.test(value);\n}\n\n// Well-known example/default DB passwords — a connection string using one is a\n// docs snippet, not a leaked credential.\nconst EXAMPLE_PASSWORDS = new Set([\n 'password',\n 'postgres',\n 'mysql',\n 'root',\n 'admin',\n 'changeme',\n 'example',\n 'secret',\n 'test',\n 'guest',\n 'toor',\n]);\n\n/** A db-connection-uri password that is an obvious example/default, not a secret. */\nfunction isExamplePassword(password: string): boolean {\n return EXAMPLE_PASSWORDS.has(password.toLowerCase());\n}\n\n// EVM raw private key (0x + 64 hex) vs. a 32-byte public value. On Base the two\n// are syntactically identical, and a block finding is permanently\n// non-bypassable, so a post quoting a hash, an identifier, or an event topic\n// must not be hard-blocked. A 64-hex demotes to the WARN 'hex32-value' when it\n// sits inside an http(s) URL token, when a hash/identifier label precedes it, or\n// when it is a known public constant. An unlabeled bare 64-hex stays a block\n// 'raw-private-key' (continuing the BlockRun-credited wallet-key scanner): that\n// is the floor, and demotion never silences, so a real key mislabeled `hash`\n// still surfaces for review.\n//\n// The label window is what a replay over 389 published posts (tenjin#723)\n// forced open: every block-tier hit in the live catalog was a public hex\n// constant, and each missed the old rule differently — `hash was 0x…` (a word\n// between label and value), `source_id = 0x…` (an id-class label), and the\n// ERC-20 Transfer topic0 (no label at all). Hence the wider label set, up to TWO\n// short intervening tokens, and the constants set. Two is the bound that keeps\n// the window honest: \"the hash of the private key is 0x…\" is four tokens out and\n// still blocks. The replay's last survivor was markdown: the catalog writes\n// ``hash was `0x…` ``, so the separator class carries backticks and quotes.\n//\n// Only the SEPARATOR classes are permissive. What counts as a LABEL is closed,\n// which is why `` PRIVATE_KEY=`0x…` `` still blocks: no punctuation tolerance\n// can invent a label that is not in the set.\nconst HEX64_RE = /(?<![0-9a-fx])0x[0-9a-fA-F]{64}(?![0-9a-fA-F])/gi;\nconst HASH_LABEL_RE =\n /(?:^|[^a-z0-9])(?:blockhash|txhash|txn|tx|hash|salt|id|topic\\d*|root|digest|commitment)(?:[\\s:=/,._'\"`‘’“”-]*[A-Za-z0-9_]{1,12}){0,2}[\\s:=/,._'\"`‘’“”-]*$/i;\n\n/** Public 64-hex values that are never key material; see redact-rules.json. */\nconst PUBLIC_HEX_CONSTANTS = new Set(\n (CORPUS.publicHexConstants ?? []).map((c) => c.value.toLowerCase()),\n);\n\nfunction scanHex64(lines: string[]): Finding[] {\n const out: Finding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n HEX64_RE.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = HEX64_RE.exec(line)) !== null) {\n const hash = isHashContext(line, m.index, m[0]);\n out.push({\n check: hash ? 'hex32-value' : 'raw-private-key',\n severity: hash ? 'warn' : 'block',\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: hash ? `${m[0].slice(0, 6)}…${m[0].slice(-4)}` : maskKeeping(m[0], 2),\n });\n }\n }\n return out;\n}\n\n/**\n * How far back a label or URL scheme may sit. Bounded so the lookback is O(1)\n * per match rather than a fresh slice of the whole line: a transcript line\n * carrying hundreds of 64-hex values would otherwise be quadratic. A label is\n * relevant within ~40 characters and a scheme+host+path prefix within 256; past\n * that the value stays block, which is the fail-safe direction.\n */\nconst LABEL_LOOKBACK = 256;\n\nfunction isHashContext(line: string, matchIndex: number, match: string): boolean {\n if (PUBLIC_HEX_CONSTANTS.has(match.toLowerCase())) return true;\n const from = Math.max(0, matchIndex - LABEL_LOOKBACK);\n const before = line.slice(from, matchIndex);\n // A truncated window must not start mid-word, or `gridhash` cut to `hash`\n // reads as a label. Underscore is kept: it is the boundary `source_id` needs.\n const labelWindow = from === 0 ? before : before.replace(/^[A-Za-z0-9]+/, '');\n if (HASH_LABEL_RE.test(labelWindow)) return true;\n // The whitespace-delimited token containing the match starts with http(s)://.\n const prefix = /(\\S*)$/.exec(before)?.[1] ?? '';\n return /^https?:\\/\\//.test(line.slice(matchIndex - prefix.length));\n}\n\n/** The hash labels that keep a bare 64-hex or an 88-character base58 run as written. */\nconst BARE_HASH_LABEL_RE =\n /(?:^|[^a-z0-9])(?:tx|txn|txid|hash|sha\\d*|hmac|digest|commit|id|checksum|sig|signature)(?:[\\s:=/,._*'\"`‘’“”-]*[A-Za-z0-9_]{1,12}){0,2}[\\s:=/,._*'\"`‘’“”-]*$/i;\n\n/**\n * A bare key-shaped run that is a hash or a signature by context: a hash label\n * within two tokens before it, or an http(s) URL it sits inside. The same\n * window and URL test the 0x form's demotion uses, with the labels a bare\n * digest or a Solana signature carries.\n */\nfunction isLabelledHash(m: RegExpExecArray): boolean {\n const input = m.input;\n const from = Math.max(0, m.index - LABEL_LOOKBACK);\n const before = input.slice(from, m.index);\n const labelWindow = from === 0 ? before : before.replace(/^[A-Za-z0-9]+/, '');\n if (BARE_HASH_LABEL_RE.test(labelWindow)) return true;\n const prefix = /(\\S*)$/.exec(before)?.[1] ?? '';\n return /^https?:\\/\\//.test(input.slice(m.index - prefix.length));\n}\n\n// gitleaks private-key marker (RSA/EC/OPENSSH/PGP variants, optional BLOCK).\nconst PEM_BEGIN = /-----BEGIN[ A-Z0-9]*PRIVATE KEY(?: BLOCK)?-----/;\nconst PEM_END = /-----END[ A-Z0-9]*PRIVATE KEY(?: BLOCK)?-----/;\n\n/** A PEM private-key block is a single block finding on its BEGIN marker line. */\nfunction scanPemBlocks(lines: string[]): Finding[] {\n const out: Finding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const m = PEM_BEGIN.exec(line);\n if (m !== null) {\n out.push({\n check: 'pem-private-key',\n severity: 'block',\n line: i + 1,\n span: [m.index, m.index + m[0].length],\n excerpt: m[0], // the header marker only — no key material follows on it\n });\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// BIP-39 seed phrases — block. A wallet-adjacent CLI that catches a hex key but\n// not a mnemonic is not protecting the thing that actually loses the funds.\n// ---------------------------------------------------------------------------\n\nconst BIP39_WORDS = new Set((wordlistJson as { words: string }).words.split(' '));\n/** The shortest valid BIP-39 mnemonic. Below this a run is prose, not a phrase. */\nconst SEED_PHRASE_MIN_WORDS = 12;\n/** The longest BIP-39 mnemonic. */\nconst SEED_PHRASE_MAX_WORDS = 24;\nconst SEED_PHRASE_SIZES = [24, 21, 18, 15, 12];\nconst BIP39_INDEX = new Map(\n (wordlistJson as { words: string }).words.split(' ').map((word, index) => [word, index]),\n);\n\n/** What may sit between two words of a loosely written phrase. */\nconst LOOSE_SEPARATOR = /^[\\s,\"'`]+$/;\n\n/**\n * Recovery phrases the strict line scan does not see: any case, words joined\n * by commas, quotes or line breaks (a 6+6 paste), or a phrase inside a longer\n * wordlist run. Only a window that IS a phrase goes, 12 to 24 words whose\n * BIP-39 checksum holds, longest first; everything else stays as written, so\n * a capitalized or comma-separated list of common words is not a false hit.\n * The English wordlist is the only one this build ships.\n */\nfunction maskLooseMnemonics(text: string): string {\n const tokens = [...text.matchAll(/[A-Za-z]+/g)].map((m) => ({\n word: m[0].toLowerCase(),\n start: m.index,\n end: m.index + m[0].length,\n }));\n // A long run repeats itself (a word typed over and over), so each distinct\n // window is hashed once: the pass stays linear on a transcript-length text.\n const checked = new Map<string, boolean>();\n const valid = (window: string[]): boolean => {\n const key = window.join(' ');\n let result = checked.get(key);\n if (result === undefined) checked.set(key, (result = isMnemonic(window)));\n return result;\n };\n const parts: string[] = [];\n let cursor = 0;\n let i = 0;\n while (i < tokens.length) {\n let j = i;\n while (\n j < tokens.length &&\n BIP39_INDEX.has(tokens[j]!.word) &&\n (j === i || LOOSE_SEPARATOR.test(text.slice(tokens[j - 1]!.end, tokens[j]!.start)))\n ) {\n j++;\n }\n if (j === i) {\n i++;\n continue;\n }\n let k = i;\n while (k + SEED_PHRASE_MIN_WORDS <= j) {\n const size = SEED_PHRASE_SIZES.find(\n (n) => k + n <= j && valid(tokens.slice(k, k + n).map((t) => t.word)),\n );\n if (size === undefined) {\n k++;\n continue;\n }\n parts.push(\n text.slice(cursor, tokens[k]!.start),\n `[redacted ${size}-word BIP-39 recovery phrase]`,\n );\n cursor = tokens[k + size - 1]!.end;\n k += size;\n }\n i = j;\n }\n parts.push(text.slice(cursor));\n return parts.join('');\n}\n\n/** BIP-39: 11 bits per word, the last `n / 3` of them a SHA-256 checksum of the rest. */\nfunction isMnemonic(words: string[]): boolean {\n let bits = 0n;\n for (const word of words) bits = (bits << 11n) | BigInt(BIP39_INDEX.get(word) ?? 0);\n const checksumBits = BigInt(words.length / 3);\n const entropyBytes = (words.length * 11 - words.length / 3) / 8;\n const entropy = Buffer.from(\n (bits >> checksumBits).toString(16).padStart(entropyBytes * 2, '0'),\n 'hex',\n );\n const expected = BigInt(createHash('sha256').update(entropy).digest()[0]!) >> (8n - checksumBits);\n return (bits & ((1n << checksumBits) - 1n)) === expected;\n}\n\n/**\n * A run of >=12 consecutive wordlist words separated ONLY by whitespace or\n * quote characters. The rule is what keeps prose out: BIP-39 words are common\n * English, but twelve of them in a row with no punctuation is a phrase, not a\n * sentence. A quote is a separator so the `.env` form counts:\n * `MNEMONIC=\"abandon … about\"` (tenjin-agent#296). Tokens are walked rather\n * than matched by one regex so the span is exact and the pass stays linear on\n * a transcript-length line.\n */\nfunction scanSeedPhrases(lines: string[]): Finding[] {\n const out: Finding[] = [];\n const token = /[^\\s\"'`]+/g;\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n token.lastIndex = 0;\n let runStart = -1;\n let runEnd = -1;\n let runWords = 0;\n let m: RegExpExecArray | null;\n const flush = (): void => {\n if (runWords >= SEED_PHRASE_MIN_WORDS) {\n out.push({\n check: 'bip39-seed-phrase',\n severity: 'block',\n line: i + 1,\n span: [runStart, runEnd],\n excerpt: `[redacted ${runWords}-word BIP-39 recovery phrase]`,\n });\n }\n runWords = 0;\n };\n while ((m = token.exec(line)) !== null) {\n if (BIP39_WORDS.has(m[0])) {\n if (runWords === 0) runStart = m.index;\n runEnd = m.index + m[0].length;\n runWords++;\n } else {\n flush();\n }\n }\n flush();\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// .env dump blocks — warn. One finding per run, naming the KEYS only.\n// ---------------------------------------------------------------------------\n\nconst ENV_LINE = /^\\s*(?:export\\s+)?([A-Z][A-Z0-9_]{2,})=(\\S.*)$/;\n/** Three lines is the shortest run that reads as a file rather than one example. */\nconst ENV_BLOCK_MIN_LINES = 3;\n/** A run of short values is configuration (PORT=3000); a long literal is a payload. */\nconst ENV_SUBSTANTIAL_VALUE = 12;\n\nfunction scanEnvDumpBlocks(lines: string[]): Finding[] {\n const out: Finding[] = [];\n let i = 0;\n while (i < lines.length) {\n const keys: string[] = [];\n let substantial = false;\n const start = i;\n let m: RegExpExecArray | null;\n while (i < lines.length && (m = ENV_LINE.exec(lines[i] ?? '')) !== null) {\n keys.push(m[1] ?? '');\n const value = dequote((m[2] ?? '').trim());\n if (value.length >= ENV_SUBSTANTIAL_VALUE && !isPlaceholder(value) && !isStructural(value)) {\n substantial = true;\n }\n i++;\n }\n if (keys.length >= ENV_BLOCK_MIN_LINES && substantial) {\n const shown = keys.slice(0, 3).join(', ');\n const rest = keys.length - 3;\n out.push({\n check: 'env-dump-block',\n severity: 'warn',\n line: start + 1,\n span: [0, (lines[start] ?? '').length],\n excerpt: `${keys.length} KEY=VALUE lines (${shown}${rest > 0 ? `, +${rest} more` : ''})`,\n });\n }\n if (i === start) i++;\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Generic high-entropy token — warn. The catch-all behind the named shapes.\n// ---------------------------------------------------------------------------\n\n// `/` and `=` are deliberately outside the candidate class: with them in, every\n// long URL path (`com/BackTrackCo/tenjin-agent/issues/45`) and every\n// SHOUTY_KEY=value line reads as one high-entropy token, which is the warn\n// fatigue this detector is supposed to avoid causing. The cost is that a\n// standard-base64 payload is split on its `/` bytes; the credential families\n// that actually carry `/`-bearing base64 (JWT, PEM, OpenSSH) have named detectors.\nconst ENTROPY_CANDIDATE = /[A-Za-z0-9+_-]{32,}/g;\n/** Below this, base62 tokens of this length are not distinguishable from text. */\nconst MIN_ENTROPY_BITS = 3.5;\n/**\n * Random base62 almost never runs more than eight same-case letters; an\n * identifier (getUserProfileByAccountIdentifier) always does. This single test\n * is what keeps long camelCase symbols out of the findings list.\n */\nconst MAX_SAME_CASE_RUN = 8;\n\n/**\n * Long tokens whose character profile reads as key material. Suppressed when the\n * token overlaps a finding a named detector already produced, so a JWT or an AWS\n * key is reported once, by the detector that knows what it is.\n */\nfunction scanHighEntropy(lines: string[], named: Finding[]): Finding[] {\n const out: Finding[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n ENTROPY_CANDIDATE.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = ENTROPY_CANDIDATE.exec(line)) !== null) {\n const token = m[0];\n // Warn tier, so the substring placeholder test is allowed here.\n if (!looksRandom(token) || DOCS_PLACEHOLDER.test(token)) continue;\n const span: [number, number] = [m.index, m.index + token.length];\n if (named.some((f) => f.line === i + 1 && f.span[0] < span[1] && span[0] < f.span[1])) {\n continue;\n }\n out.push({\n check: 'high-entropy-string',\n severity: 'warn',\n line: i + 1,\n span,\n excerpt: maskKeeping(token, 4),\n });\n }\n }\n return out;\n}\n\nfunction looksRandom(token: string): boolean {\n if (!/[a-z]/.test(token) || !/[A-Z]/.test(token) || !/[0-9]/.test(token)) return false;\n if (longestSameCaseRun(token) > MAX_SAME_CASE_RUN) return false;\n return shannonBits(token) >= MIN_ENTROPY_BITS;\n}\n\nfunction longestSameCaseRun(token: string): number {\n let best = 0;\n let run = 0;\n let previous = '';\n for (const ch of token) {\n let kind = '';\n if (/[a-z]/.test(ch)) kind = 'lower';\n else if (/[A-Z]/.test(ch)) kind = 'upper';\n if (kind === '') run = 0;\n else run = kind === previous ? run + 1 : 1;\n previous = kind;\n if (run > best) best = run;\n }\n return best;\n}\n\nfunction shannonBits(token: string): number {\n const counts = new Map<string, number>();\n for (const ch of token) counts.set(ch, (counts.get(ch) ?? 0) + 1);\n let bits = 0;\n for (const n of counts.values()) {\n const p = n / token.length;\n bits -= p * Math.log2(p);\n }\n return bits;\n}\n\n/**\n * `hex32-value` is not a rule id: it is the warn form `scanHex64` demotes\n * `raw-private-key` to in hash context, so it follows that rule's scopes. A\n * team shelf keeps it because the emitting rule is scoped to team, never\n * because anything filters on `finding.check`. Exported for the fixture test\n * that pins the survivor set.\n */\nexport const EMITTED_CHECKS: Readonly<Record<string, string>> = {\n 'hex32-value': 'raw-private-key',\n};\n\n/** Every rule id `findings()` can report for a scope, emitted checks included. */\nexport function checksFor(scope: ReportScope): ReadonlySet<string> {\n const ids = new Set(CORPUS.rules.filter((r) => r.scopes.includes(scope)).map((r) => r.id));\n for (const [check, rule] of Object.entries(EMITTED_CHECKS)) if (ids.has(rule)) ids.add(check);\n return ids;\n}\n\nconst CHECKS: Record<ReportScope, ReadonlySet<string>> = {\n publish: checksFor('publish'),\n team: checksFor('team'),\n};\n\nconst FENCE = /^(\\s*)(`{3,}|~{3,})/;\n\n/**\n * Long verbatim runs — warn (a rights, not a secrets, concern). A fenced code\n * block or a contiguous `>` blockquote whose content reaches LONG_QUOTE_WORDS\n * reads as copied third-party material. Reported once on the run's first line.\n */\nfunction scanLongVerbatim(lines: string[]): Finding[] {\n const out: Finding[] = [];\n let i = 0;\n while (i < lines.length) {\n const line = lines[i] ?? '';\n const fence = FENCE.exec(line);\n if (fence !== null) {\n const marker = fence[2] ?? '```';\n const start = i;\n const body: string[] = [];\n i++;\n while (i < lines.length && !closesFence(lines[i] ?? '', marker)) {\n body.push(lines[i] ?? '');\n i++;\n }\n i++; // consume the closing fence (or run off the end)\n pushIfLong(out, body, start, line);\n continue;\n }\n if (/^\\s*>/.test(line)) {\n const start = i;\n const body: string[] = [];\n while (i < lines.length && /^\\s*>/.test(lines[i] ?? '')) {\n body.push((lines[i] ?? '').replace(/^\\s*>\\s?/, ''));\n i++;\n }\n pushIfLong(out, body, start, lines[start] ?? '');\n continue;\n }\n i++;\n }\n return out;\n}\n\nfunction closesFence(line: string, marker: string): boolean {\n const m = FENCE.exec(line);\n return m !== null && (m[2] ?? '').startsWith(marker);\n}\n\nfunction pushIfLong(out: Finding[], body: string[], startLine: number, firstLine: string): void {\n const text = body.join(' ').trim();\n const words = text.length === 0 ? 0 : text.split(/\\s+/).length;\n if (words < LONG_QUOTE_WORDS) return;\n out.push({\n check: 'long-verbatim-quote',\n severity: 'warn',\n line: startLine + 1,\n span: [0, firstLine.length],\n excerpt: truncate(text, 60),\n });\n}\n\n/**\n * Deterministic order: line, then start column, then check name. Exact duplicate\n * spans of the same check (e.g. two detectors on the same offset) collapse to one.\n */\nfunction dedupeAndSort(findings: Finding[]): Finding[] {\n const seen = new Set<string>();\n const unique = findings.filter((f) => {\n const key = `${f.check}:${f.line}:${f.span[0]}:${f.span[1]}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n return unique.sort(\n (a, b) => a.line - b.line || a.span[0] - b.span[0] || a.check.localeCompare(b.check),\n );\n}\n","{\n \"schemaVersion\": 1,\n \"note\": \"One rule table for every redaction surface in the CLI (src/lib/redact.ts), kept as data so the tenjin server-side ingest gate can vendor it verbatim. Every row is one detector: `id` is the stable finding `check`, `tier` is the finding severity, `match` is a JS regex or the name of an algorithmic detector a consumer must implement, `excerpt` is the masked-excerpt policy (never the secret), `skip` names a suppression predicate. `scopes` says where the row applies: `publish` (reported on the public marketplace), `team` (reported on a team shelf), `query` (its matches are replaced by the excerpt in hook queries and router packets by `mask()`; regex rows, plus the `hex64`, `pemBlock` and `bip39` algorithm rows). Precision first, as gitleaks and GitHub push protection do: a block row fires on a vendor prefix or an unambiguous shape, the generic `secret-assignment` row needs a secret-named word plus `=` or `:`, and entropy is never a trigger for a query. Table order is mask() order (the assignment row runs first, see its description). Several entries may share an `id`; they are one detector expressed as more than one pattern. Patterns adapted from gitleaks are MIT and attributed in NOTICE.md.\",\n \"publicHexConstants\": [\n {\n \"value\": \"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\",\n \"name\": \"topic0 ERC-20 / ERC-721 Transfer\"\n },\n {\n \"value\": \"0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925\",\n \"name\": \"topic0 ERC-20 / ERC-721 Approval\"\n },\n {\n \"value\": \"0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31\",\n \"name\": \"topic0 ERC-721 / ERC-1155 ApprovalForAll\"\n },\n {\n \"value\": \"0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62\",\n \"name\": \"topic0 ERC-1155 TransferSingle\"\n },\n {\n \"value\": \"0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb\",\n \"name\": \"topic0 ERC-1155 TransferBatch\"\n },\n {\n \"value\": \"0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0\",\n \"name\": \"topic0 Ownable OwnershipTransferred\"\n },\n {\n \"value\": \"0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c\",\n \"name\": \"topic0 WETH Deposit\"\n },\n {\n \"value\": \"0x7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65\",\n \"name\": \"topic0 WETH Withdrawal\"\n },\n {\n \"value\": \"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc\",\n \"name\": \"EIP-1967 implementation storage slot\"\n },\n {\n \"value\": \"0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103\",\n \"name\": \"EIP-1967 admin storage slot\"\n },\n {\n \"value\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\",\n \"name\": \"keccak256 of the empty string\"\n },\n {\n \"value\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"name\": \"the zero hash\"\n }\n ],\n \"excerptPolicies\": {\n \"mask\": \"Keep the first `keep` characters (a public type marker) and replace the rest with a redaction count.\",\n \"verbatim\": \"Echo the match, truncated to `max` characters when set. Only for non-secret matches.\",\n \"abbreviate\": \"Keep `head` leading and `tail` trailing characters joined by an ellipsis.\",\n \"custom\": \"Consumer-implemented builder named by `handler`.\"\n },\n \"rules\": [\n {\n \"id\": \"secret-assignment\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Secret-named assignment (API_KEY=, password:, token=) with a literal value. The JSON-quoted form (\\\"password\\\": \\\"...\\\") is the third row, not a quote read here: reading a quote after this name turned ordinary config keys into findings ({\\\"credentials\\\": \\\"include\\\"}, {\\\"max_tokens\\\": 128000}, {\\\"tokenizer\\\": \\\"cl100k_base\\\"}, review round 6). The separator class is [ \\\\t] rather than \\\\s so a heading line (`## Token:`) never swallows the next line when mask() runs over whole text. FIRST IN THE TABLE ON PURPOSE: mask() applies rows in table order, and a value that is itself a vendor token (`OPENAI_API_KEY=sk-...`) must be taken whole by this row, name kept, before a vendor row could leave a stub for this row to re-match.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b([A-Za-z0-9_]*(?:API[_-]?KEY|SECRET|ACCESS[_-]?KEY|SUBSCRIPTION[_-]?KEY|PRIVATE[_-]?KEY|PASSW(?:OR)?D|TOKEN|CREDENTIALS?|AUTH[_-]?TOKEN)[A-Za-z0-9_]*)[ \\\\t]*[:=][ \\\\t]*(\\\"[^\\\"]{6,}\\\"|'[^']{6,}'|[^\\\\s\\\"']{6,})\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"labeledValue\"\n },\n \"skip\": {\n \"handler\": \"nonLiteralValue\"\n }\n },\n {\n \"id\": \"secret-assignment\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Secret-named command-line flag with a SPACE-separated literal value (--api-key <v>, --token <v>): the one credential position the assignment form above cannot see, since it needs `=` or `:` after the name. `X-Api-Key: <v>` and `--api-key=<v>` already match above (Api-Key, api-key) and are deliberately not repeated here, so one value yields one finding. For the shapes a recorded command line takes (tenjin-agent#281): a hex-only key has no vendor prefix, and bare hex is deliberately never reported so a commit SHA still syncs, so the credential POSITION is the signal.\",\n \"source\": \"tenjin (closes tenjin-agent#281)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(--(?:[a-z0-9]+-)*(?:api[_-]?key|api[_-]?token|access[_-]?key|access[_-]?token|auth[_-]?token|secret[_-]?key|private[_-]?key|subscription[_-]?key|credentials?|secret|token|password|passwd))[ \\\\t]+(\\\"[^\\\"]{6,}\\\"|'[^']{6,}'|[^\\\\s\\\"']{6,})\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"labeledValue\"\n },\n \"skip\": {\n \"handler\": \"nonLiteralValue\"\n }\n },\n {\n \"id\": \"secret-assignment\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Quoted secret name before `:` or `=` with a quoted value (\\\"password\\\": \\\"...\\\", 'api_key' = '...'), the JSON and YAML form of the first row (tenjin-agent#296). Narrower than the first row on purpose, so the review-round-6 config keys stay clean: the name must END in the secret word (no `max_tokens`, `tokenizer`, `passwordHash`), and the value must be quoted and carry a letter and a digit (no `128000`, no `\\\"include\\\"`). A letters-only quoted password is an accepted miss.\",\n \"source\": \"tenjin (tenjin-agent#296)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<=[\\\"'])([A-Za-z0-9_-]*(?:API[_-]?KEY|SECRET|ACCESS[_-]?KEY|SUBSCRIPTION[_-]?KEY|PRIVATE[_-]?KEY|PASSW(?:OR)?D|TOKEN|CREDENTIALS?|AUTH[_-]?TOKEN))[\\\"'][ \\\\t]*[:=][ \\\\t]*(\\\"(?=[^\\\"]*\\\\d)(?=[^\\\"]*[A-Za-z])[^\\\"]{6,}\\\"|'(?=[^']*\\\\d)(?=[^']*[A-Za-z])[^']{6,}')\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"labeledValue\"\n },\n \"skip\": {\n \"handler\": \"nonLiteralValue\"\n }\n },\n {\n \"id\": \"aws-access-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"AWS access key id (AKIA/ASIA/ABIA/ACCA/A3T prefixes).\",\n \"source\": \"gitleaks:aws-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"jwt\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"JSON Web Token: three base64url segments whose header starts eyJ.\",\n \"source\": \"gitleaks:jwt\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\beyJ[A-Za-z0-9_-]{5,}\\\\.eyJ[A-Za-z0-9_-]{5,}\\\\.[A-Za-z0-9_-]{5,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 3\n }\n },\n {\n \"id\": \"github-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"GitHub classic PAT/OAuth/app/refresh token or fine-grained PAT (github_pat_).\",\n \"source\": \"gitleaks:github-pat + github-fine-grained-pat\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:gh[posru]_[0-9A-Za-z]{36}|github_pat_[0-9A-Za-z_]{82})\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"slack-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Slack bot/user/app/refresh/legacy token.\",\n \"source\": \"gitleaks:slack-*-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bxox[baprs]-[0-9A-Za-z-]{10,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 5\n }\n },\n {\n \"id\": \"stripe-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Stripe live or test secret/restricted key.\",\n \"source\": \"gitleaks:stripe-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b[sr]k_(?:live|test)_[0-9A-Za-z]{10,99}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 8\n }\n },\n {\n \"id\": \"anthropic-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Anthropic API key (sk-ant-).\",\n \"source\": \"gitleaks:anthropic-api-key\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bsk-ant-[0-9A-Za-z_-]{20,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 7\n }\n },\n {\n \"id\": \"openai-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"OpenAI key: classic sk- plus sk-proj-/sk-svcacct-/sk-admin-. The body must carry a digit so sk- kebab identifiers do not hard-block. Project, service-account and admin keys carry `_` and `-` throughout the body, so the prefixed branch takes the wider class and its own trailing guard; the bare branch keeps the digit requirement and its own guard. The guards live INSIDE each branch: a shared guard outside the alternation made a classic key followed by `-old` fail outright (review round 6).\",\n \"source\": \"gitleaks:openai-api-key\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bsk-(?!ant-)(?:(?:proj|svcacct|admin)-[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])|(?=[0-9A-Za-z]*[0-9])[0-9A-Za-z]{20,}(?![0-9A-Za-z]))\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 3\n }\n },\n {\n \"id\": \"google-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Google API key (AIza) or OAuth client secret (GOCSPX-).\",\n \"source\": \"gitleaks:gcp-api-key + gcp-oauth-client-secret\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:AIza[0-9A-Za-z_-]{35}|GOCSPX-[0-9A-Za-z_-]{20,})\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"googleKey\"\n }\n },\n {\n \"id\": \"npm-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"npm access token.\",\n \"source\": \"gitleaks:npm-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bnpm_[0-9A-Za-z]{36}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"supabase-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Supabase personal access token (sbp_) or secret/publishable API key (sb_*_).\",\n \"source\": \"gitleaks:supabase-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bsbp_[0-9a-f]{40}\\\\b|\\\\bsb_(?:secret|publishable)_[0-9A-Za-z_-]{20,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"twilio-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Twilio API key SID (SK + 32 lowercase hex).\",\n \"source\": \"gitleaks:twilio-api-key\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bSK[0-9a-f]{32}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 2\n }\n },\n {\n \"id\": \"sendgrid-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"SendGrid API key (SG.<id>.<secret>).\",\n \"source\": \"gitleaks:sendgrid-api-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bSG\\\\.[0-9A-Za-z_-]{16,32}\\\\.[0-9A-Za-z_-]{16,64}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 3\n }\n },\n {\n \"id\": \"huggingface-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Hugging Face user access token (hf_).\",\n \"source\": \"gitleaks:huggingface-access-token\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bhf_[0-9A-Za-z]{30,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 3\n }\n },\n {\n \"id\": \"vercel-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Vercel Blob read/write store token.\",\n \"source\": \"tenjin (shape from the Vercel Blob docs)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bvercel_blob_[a-z]{2}_[0-9A-Za-z_]{24,}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 12\n }\n },\n {\n \"id\": \"vercel-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Vercel platform token (vcp_/vci_/vca_/vcr_/vck_ prefixes).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-vercel\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:vcp|vci|vca|vcr|vck)_[0-9A-Za-z]{20,60}(?![0-9A-Za-z])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"notion-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Notion integration token (ntn_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-notion\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bntn_[0-9]{11}[0-9A-Za-z]{35}(?![0-9A-Za-z])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"linear-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Linear API key (lin_api_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-linear\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\blin_api_[0-9A-Za-z_]{32,128}(?![0-9A-Za-z_])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 8\n }\n },\n {\n \"id\": \"figma-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Figma personal access token (figd_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-figma\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bfigd_[0-9A-Za-z_-]{40,200}(?![0-9A-Za-z_-])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 5\n }\n },\n {\n \"id\": \"gitlab-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"GitLab personal access token (glpat-).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-gitlab\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bglpat-[0-9A-Za-z_-]{20,128}(?![0-9A-Za-z_-])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 6\n }\n },\n {\n \"id\": \"docker-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Docker Hub personal access token (dckr_pat_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-docker\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bdckr_pat_[0-9A-Za-z_-]{27}(?![0-9A-Za-z_-])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 9\n }\n },\n {\n \"id\": \"cloudflare-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Cloudflare API key or account/user token (cfk_/cfut_/cfat_).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-cloudflare\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:cfk|cfut|cfat)_[0-9A-Za-z]{40}[0-9a-f]{8}(?![0-9A-Za-z])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"databricks-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Databricks personal access token (dapi).\",\n \"source\": \"secretlint:@secretlint/secretlint-rule-databricks\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bdapi[0-9A-Fa-f]{32}(?:-[0-9])?(?![0-9A-Fa-f])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 4\n }\n },\n {\n \"id\": \"openssh-private-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"OpenSSH private key body pasted without its PEM framing (base64 of the openssh-key-v1 magic).\",\n \"source\": \"gitleaks:private-key (framing-free variant)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bb3BlbnNzaC1rZXktdjEA[0-9A-Za-z+/=]{20,}\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 8\n }\n },\n {\n \"id\": \"totp-uri\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"otpauth:// TOTP/HOTP provisioning URI; its secret= parameter is a live second factor.\",\n \"source\": \"tenjin (RFC-style otpauth key URI)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\botpauth:\\\\/\\\\/[ht]otp\\\\/[^\\\\s\\\"'`<>)\\\\]]+\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 15\n }\n },\n {\n \"id\": \"db-connection-uri\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Basic-auth style URI with an embedded password (scheme://user:pass@host), including database connection strings. The scheme run is length-bounded: unbounded, it backtracks quadratically across a transcript-length dotted-token line that never reaches ://. The user may be empty: `redis://:password@host` is the standard Redis form.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b([a-z][a-z0-9+.-]{0,31}):\\\\/\\\\/([^\\\\s:@/]*):([^\\\\s@/]+)@([^\\\\s/:]+)\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"dbConnectionUri\"\n },\n \"skip\": {\n \"handler\": \"exampleDbPassword\"\n }\n },\n {\n \"id\": \"bearer-token\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Authorization: Bearer header carrying a live token.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bAuthorization:\\\\s*Bearer\\\\s+(\\\\S{8,})\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"bearerToken\"\n },\n \"skip\": {\n \"handler\": \"placeholderGroup1\"\n }\n },\n {\n \"id\": \"basic-auth-header\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\"],\n \"description\": \"Authorization: Basic header: the base64 of user:password, under the entropy floor and on no vendor prefix (tenjin-agent#296). The header name is a bounded lookbehind behind a shape lookahead, so the mask keeps it, replaces the credential alone, and a whitespace run stays linear.\",\n \"source\": \"tenjin (tenjin-agent#296)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?=[A-Za-z0-9+/]{8})(?<=\\\\bAuthorization:[ \\\\t]{0,16}Basic[ \\\\t]{1,16})[A-Za-z0-9+/]{8,}={0,2}(?![A-Za-z0-9+/=])\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 0\n }\n },\n {\n \"id\": \"curl-user-credential\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\"],\n \"description\": \"curl -u / --user user:password on one command (tenjin-agent#296): the password is masked and the command and user kept. Anchored on `curl` within 200 characters of the flag on the same pipeline segment, so `docker run -u 1000:1000` never matches. A `$VAR`, a placeholder or a bare lowercase word is skipped as the assignment row skips it.\",\n \"source\": \"tenjin (tenjin-agent#296)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(\\\\bcurl\\\\b[^\\\\n|;&]{0,200}?[ \\\\t](?:-u|--user)(?:[ \\\\t]+|=)[\\\"']?[^\\\\s:\\\"']{1,64}):([^\\\\s\\\"']+)\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"labeledValue\"\n },\n \"skip\": {\n \"handler\": \"nonLiteralValue\"\n }\n },\n {\n \"id\": \"url-query-credential\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\"],\n \"description\": \"Credential-named query parameter on a URL (?key=, &api_key=, ?token=, ?sig=, ?password=): the value is masked and the name kept. The value class stops at `&`, `#`, whitespace, quotes and brackets, so a value another row already replaced with `[redacted …]` is not masked twice.\",\n \"source\": \"tenjin (tenjin-agent#388)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"([?&](?:key|apikey|api_key|api-key|token|access_token|auth|secret|client_secret|sig|signature|password|pwd))=([^&#\\\\s\\\"'<>\\\\[\\\\]]+)\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"labeledValue\"\n }\n },\n {\n \"id\": \"url-path-credential\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\"],\n \"description\": \"A path segment of 24 or more [A-Za-z0-9_-] characters that mixes letters and digits, on an http(s) URL: the shape a webhook secret or a signed-link token takes. A CDN hash or a content id in a path masks too; in a query that costs one routing offer. Four exclusions, each from a measured miss: a segment with two hyphenated words (an article slug), a 40-hex git commit after a git path marker (/commit/, /commits/, /blob/, /tree/, /raw/, /compare/) or on a git host (github.com, gitlab.com, bitbucket.org, codeberg.org), since elsewhere a 40-hex segment is a node key (https://<name>.quiknode.pro/<40 hex>/), a 0x-prefixed 64-hex (the hex64 row already calls a 64-hex inside a URL a hash), a UUID, and a URL character class that stops at quotes, brackets and commas, so one match never spans two URLs in a JSON string. The segment must be whole (a `.` or `%` inside it is a filename or an encoded slug, not a token). The shape lookahead runs before the scheme lookbehind, and the lookbehind is bounded, so a line of short segments stays linear.\",\n \"source\": \"tenjin (tenjin-agent#388)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\/(?=[\\\\w-]{24})(?<=\\\\bhttps?:\\\\/\\\\/[^\\\\s?#\\\"'`<>()\\\\[\\\\]{},]{1,2048}\\\\/)(?=[\\\\w-]*[A-Za-z])(?=[\\\\w-]*\\\\d)(?![\\\\w-]*?(?<![A-Za-z])[A-Za-z]{3,}-[A-Za-z]{3})(?!(?:0x[0-9a-f]{64}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?![\\\\w-]))(?!(?=[0-9a-f]{40}(?![\\\\w-]))(?<=\\\\/(?:commit|commits|blob|tree|raw|compare)\\\\/|\\\\bhttps?:\\\\/\\\\/(?:www\\\\.)?(?:github\\\\.com|gitlab\\\\.com|bitbucket\\\\.org|codeberg\\\\.org)\\\\/[^\\\\s?#\\\"'`<>()\\\\[\\\\]{},]{0,2048}))[\\\\w-]{24,}(?=[.;:!]*(?:[\\\\/?#\\\\s\\\"'<>(),\\\\[\\\\]{}`]|$))\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 1\n }\n },\n {\n \"id\": \"bare-hex-key\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\"],\n \"description\": \"64 hex with no 0x, the shape a private key takes when a tool exports it bare (tenjin-agent#388). A hash label within two tokens before it (tx, txn, txid, hash, sha, sha256, hmac, digest, commit, id, checksum, sig, signature, across markdown emphasis) or an http(s) URL around it makes it a hash and it is kept, the same downgrade the 0x form has. A 128-hex run (sha512) is not a 64-hex run and never matches.\",\n \"source\": \"tenjin (tenjin-agent#388)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<![0-9A-Za-z])[0-9a-fA-F]{64}(?![0-9A-Za-z])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 0\n },\n \"skip\": {\n \"handler\": \"hashLabelled\"\n }\n },\n {\n \"id\": \"bare-hex-key\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\"],\n \"description\": \"A 64-hex key split into two 32-hex halves by one space or one newline, with an optional 0x on the first half. Bounded to exactly two adjacent halves: a third 32-hex run before or after (a list of MD5 sums) keeps the whole list as written, and a hash label keeps it as for the row above.\",\n \"source\": \"tenjin (tenjin-agent#388)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<![0-9A-Za-z])(?<![0-9a-fA-F]{32}[ \\\\n])(?:0x)?[0-9a-fA-F]{32}[ \\\\n][0-9a-fA-F]{32}(?![0-9A-Za-z])(?![ \\\\n][0-9a-fA-F]{32})\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 0\n },\n \"skip\": {\n \"handler\": \"hashLabelled\"\n }\n },\n {\n \"id\": \"solana-secret-key\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\"],\n \"description\": \"An 87 or 88 character base58 run: a Solana keypair's 64-byte secret key as a wallet exports it (tenjin-agent#388). A transaction signature has the same shape, so a tx or sig label before it or an http(s) URL around it keeps it, as for bare-hex-key. A 32-byte public key is 43 or 44 characters and never matches.\",\n \"source\": \"tenjin (tenjin-agent#388)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<![1-9A-HJ-NP-Za-km-z])[1-9A-HJ-NP-Za-km-z]{87,88}(?![1-9A-HJ-NP-Za-km-z])\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 0\n },\n \"skip\": {\n \"handler\": \"hashLabelled\"\n }\n },\n {\n \"id\": \"solana-secret-key\",\n \"tier\": \"warn\",\n \"scopes\": [\"query\", \"publish\"],\n \"description\": \"A JSON array of exactly 64 integers from 0 to 255: the solana-keygen keypair file.\",\n \"source\": \"tenjin (tenjin-agent#388)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\[\\\\s*(?:(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\s*,\\\\s*){63}(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\s*\\\\]\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"mask\",\n \"keep\": 1\n }\n },\n {\n \"id\": \"wallet-address\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"EVM account/contract address (0x + 40 hex).\",\n \"source\": \"blockrun-mcp (wallet-key leak scanner)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<![0-9a-fx])0x[0-9a-fA-F]{40}(?![0-9a-fA-F])\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"abbreviate\",\n \"head\": 6,\n \"tail\": 4\n }\n },\n {\n \"id\": \"confidential-marker\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Document classification legend (CONFIDENTIAL stamp, INTERNAL USE ONLY, DO NOT DISTRIBUTE). Case-sensitive: marker-shaped, not word-in-phrase.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:STRICTLY|COMPANY|HIGHLY)\\\\s+CONFIDENTIAL\\\\b|(?<![A-Z]{2,}[ \\\\t]+)\\\\bCONFIDENTIAL\\\\b|\\\\bCONFIDENTIAL\\\\b(?![ \\\\t]+[A-Z]{2,})|\\\\bConfidential(?=\\\\s*(?:[-:.,;–—]|$))|\\\\b(?:INTERNAL|Internal)(?:\\\\s+(?:USE|Use))?\\\\s+(?:ONLY|Only)\\\\b|\\\\b(?:DO\\\\s+NOT\\\\s+DISTRIBUTE|Do\\\\s+Not\\\\s+Distribute)\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"internal-hostname\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Hostname on a private-use suffix (.internal, .corp, .local, .lan, .intranet). Label count and label length are bounded: an unbounded (label\\\\.)+ run is quadratic on a transcript-length line of dotted digits.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:[a-z0-9-]{1,63}\\\\.){1,6}(?:internal|corp|local|lan|intranet)\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"private-network-endpoint\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"RFC1918 / link-local IPv4 endpoint (10/8, 172.16/12, 192.168/16, 169.254/16).\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<![\\\\d.])(?:10\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)|172\\\\.(?:1[6-9]|2\\\\d|3[01])\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)|192\\\\.168\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)|169\\\\.254\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d))(?::\\\\d{2,5})?(?!\\\\.?\\\\d)\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"private-network-endpoint\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Loopback / wildcard-bind development endpoint. Scheme or port required so prose about localhost does not warn.\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"https?:\\\\/\\\\/(?:localhost|127\\\\.0\\\\.0\\\\.1|0\\\\.0\\\\.0\\\\.0|\\\\[::1\\\\])(?::\\\\d{2,5})?(?:\\\\/[^\\\\s\\\"'`<>?&)\\\\]]*)?|\\\\b(?:localhost|127\\\\.0\\\\.0\\\\.1|0\\\\.0\\\\.0\\\\.0):\\\\d{2,5}\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"collaboration-url\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Link into a collaboration workspace (Google Docs/Drive, Notion, Figma, Slack archives, Linear, Jira/Confluence): the target is usually access-controlled.\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"https?:\\\\/\\\\/(?:docs\\\\.google\\\\.com|drive\\\\.google\\\\.com|(?:[a-z0-9-]+\\\\.)?notion\\\\.(?:so|site)|(?:www\\\\.)?figma\\\\.com|(?:[a-z0-9-]+\\\\.)?slack\\\\.com\\\\/archives|linear\\\\.app|[a-z0-9-]+\\\\.atlassian\\\\.net)(?:\\\\/[^\\\\s\\\"'`<>?&)\\\\]]*)?\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"cloud-resource-id\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"AWS ARN: names an account, region, and resource.\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\barn:aws[0-9a-z-]*:[0-9a-z-]+:[0-9a-z-]*:\\\\d{0,12}:[^\\\\s\\\"'`<>,)\\\\]]+\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"cloud-resource-id\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"GCP fully-qualified resource name (projects/<id>/<collection>/<name>).\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bprojects\\\\/[a-z][a-z0-9-]{4,28}[a-z0-9]\\\\/(?:locations|topics|subscriptions|secrets|instances|serviceAccounts|datasets|buckets|zones|keyRings|clusters|jobs|models)\\\\/[^\\\\s\\\"'`<>,)\\\\]]+\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"cloud-resource-id\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Azure resource id: /subscriptions/<guid>/resourceGroups/<name>/...\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\/subscriptions\\\\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\\\/resourceGroups\\\\/[^\\\\s\\\"'`<>,)\\\\]/]+(?:\\\\/[^\\\\s\\\"'`<>,)\\\\]]*)?\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"cloud-resource-id\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Cloud object-storage location (s3://, gs://, or an S3/Azure Blob/GCS bucket hostname).\",\n \"source\": \"tenjin (closes tenjin-agent#45)\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:s3|gs):\\\\/\\\\/[a-z0-9][a-z0-9._-]{2,62}(?:\\\\/[^\\\\s\\\"'`<>,?&)\\\\]]*)?|\\\\b[a-z0-9][a-z0-9.-]{1,62}\\\\.(?:s3(?:[.-][a-z0-9-]+)?\\\\.amazonaws\\\\.com|blob\\\\.core\\\\.windows\\\\.net|storage\\\\.googleapis\\\\.com)\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\",\n \"max\": 80\n }\n },\n {\n \"id\": \"local-path\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Home-anchored local filesystem path: leaks the machine username and private project layout.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?:(?<![\\\\w.-])\\\\/(?:Users|home)\\\\/([A-Za-z0-9._-]+)(?:\\\\/[^\\\\s\\\"'`)\\\\]}>:,;?&/]+)+|\\\\b[A-Za-z]:\\\\\\\\[Uu]sers\\\\\\\\([^\\\\\\\\\\\\s\\\"']+)(?:\\\\\\\\[^\\\\\\\\\\\\s\\\"']+)+)\",\n \"flags\": \"dg\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"localPath\"\n },\n \"skip\": {\n \"handler\": \"placeholderUsername\"\n }\n },\n {\n \"id\": \"customer-identifier\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Labeled customer/account/tenant identifier with a literal value.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b((?:customer|client|account|tenant|subscriber)[ _-]?(?:id|number|no))\\\\b\\\\s*[:=#]\\\\s*(\\\"[^\\\"]{2,}\\\"|'[^']{2,}'|[A-Za-z0-9][A-Za-z0-9._-]{2,})\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"labeledValue\"\n },\n \"skip\": {\n \"handler\": \"nonLiteralValue\"\n }\n },\n {\n \"id\": \"paid-content-marker\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Third-party rights legend suggesting copied licensed material. Legend shapes only: bare paywall vocabulary is this marketplace’s own subject matter.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\ball rights reserved\\\\b|\\\\b(?:reprinted|reproduced|used) with permission\\\\b|\\\\bnot for (?:redistribution|republication)\\\\b|\\\\bdo not (?:redistribute|republish)\\\\b|(?:©|\\\\(c\\\\)|copyright)\\\\s*(?:19|20)\\\\d{2}\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"embedded-instruction\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Injection-shaped imperative captured from a prompt or tool output.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b(?:ignore|disregard|forget)\\\\s+(?:all\\\\s+|any\\\\s+)?(?:previous|prior|above|earlier|preceding)\\\\s+(?:instructions?|prompts?|context|messages?)\\\\b|\\\\bdo not (?:reveal|disclose|mention) (?:this|these|the above)\\\\b\",\n \"flags\": \"gi\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"embedded-instruction\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Hidden-prompt document header. Case-sensitive: the all-caps header form is the injection-typed one.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\bBEGIN (?:SYSTEM|HIDDEN) (?:PROMPT|INSTRUCTIONS)\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"email\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Email address (PII), subsuming corporate-domain addresses. Lengths follow the RFC limits so the local part and the domain cannot backtrack against each other: unbounded, the pair is quadratic on a transcript-length line.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"\\\\b[A-Za-z0-9._%+-]{1,64}@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\\\.){1,8}[A-Za-z]{2,24}\\\\b\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n },\n \"skip\": {\n \"handler\": \"reservedExampleEmail\"\n }\n },\n {\n \"id\": \"phone\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Telephone number (PII).\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"regex\",\n \"pattern\": \"(?<!\\\\d)(?:\\\\+?\\\\d{1,2}[\\\\s.-]?)?(?:\\\\(\\\\d{3}\\\\)|\\\\d{3})[\\\\s.-]\\\\d{3}[\\\\s.-]\\\\d{4}(?!\\\\d)\",\n \"flags\": \"g\"\n },\n \"excerpt\": {\n \"kind\": \"verbatim\"\n }\n },\n {\n \"id\": \"raw-private-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"0x + 64 hex with no hash context. Demoted to the warn detector hex32-value when a hash/identifier label precedes it (within two intervening tokens, across markdown and quote punctuation), when it sits inside an http(s) URL, or when it is one of the publicHexConstants below. An unlabeled bare 64-hex stays block: that is the floor.\",\n \"source\": \"blockrun-mcp (wallet-key leak scanner)\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"hex64\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"hex64\"\n }\n },\n {\n \"id\": \"pem-private-key\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"PEM private-key armor (-----BEGIN ... PRIVATE KEY-----), RSA/EC/OPENSSH/PGP variants.\",\n \"source\": \"gitleaks:private-key\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"pemBlock\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"pemBlock\"\n }\n },\n {\n \"id\": \"bip39-seed-phrase\",\n \"tier\": \"block\",\n \"scopes\": [\"query\", \"publish\", \"team\"],\n \"description\": \"Twelve or more consecutive BIP-39 English wordlist words separated only by whitespace or quote characters, so a quoted `.env` value (MNEMONIC=\\\"abandon ... about\\\") counts (tenjin-agent#296): a wallet recovery phrase.\",\n \"source\": \"tenjin; wordlist from BIP-0039 (see NOTICE.md)\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"bip39\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"bip39\"\n }\n },\n {\n \"id\": \"env-dump-block\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Three or more consecutive SHOUTY_KEY=value lines carrying at least one substantial literal: a pasted .env file.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"envDump\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"envDump\"\n }\n },\n {\n \"id\": \"high-entropy-string\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Catch-all for unknown credential formats: a long mixed-case alphanumeric token whose Shannon entropy and case-run profile match random key material rather than an identifier.\",\n \"source\": \"tenjin (entropy heuristic in the spirit of gitleaks entropy gating)\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"entropy\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"entropy\"\n }\n },\n {\n \"id\": \"long-verbatim-quote\",\n \"tier\": \"warn\",\n \"scopes\": [\"publish\"],\n \"description\": \"Fenced block or blockquote run long enough to read as copied third-party material.\",\n \"source\": \"tenjin\",\n \"match\": {\n \"kind\": \"algorithm\",\n \"algorithm\": \"longVerbatim\"\n },\n \"excerpt\": {\n \"kind\": \"custom\",\n \"handler\": \"longVerbatim\"\n }\n }\n ]\n}\n","{\n \"source\": \"BIP-0039 English wordlist (bitcoin/bips), as distributed by @scure/bip39 (MIT). Vendored as data, not as a dependency: see NOTICE.md.\",\n \"count\": 2048,\n \"words\": \"abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo\"\n}\n"],"mappings":";;;AAiDA,S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O,oBAAI,IAAY;AAC7B,QAAM,SAASA,UAAS,OAAO,CAAC,MAAM;AACpC,UAAM,MAAM,GAAG,EAAE,KAAK,IAAI,EAAE,IAAI,IAAI,EAAE,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AAC1D,QAAI,KAAK,IAAI,GAAG,EAAG,QAAO;AAC1B,SAAK,IAAI,GAAG;AACZ,WAAO;AAAA,EACT,CAAC;AACD,SAAO,OAAO;AAAA,IACZ,CAAC,GAAG,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,EAAE,MAAM,cAAc,EAAE,KAAK;AAAA,EACrF;AACF;","names":["findings"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/client-meta.ts","../src/lib/http.ts"],"sourcesContent":["import pkg from '../../package.json';\nimport { PRODUCTION_ORIGIN } from './production-origin';\n\n/**\n * The RFC 9110 product token naming this CLI. It leads every User-Agent the\n * shared transport sends, because the server's `parseUserAgentProduct()` (tenjin\n * PR #544) attributes on the FIRST product only and the CLI is the user agent\n * that constructed and sent the request.\n */\nexport const TENJIN_PRODUCT = `tenjin-cli/${pkg.version}`;\n\n/** The product NAME alone, which is what identifies a copy of us in a handoff. */\nexport const TENJIN_PRODUCT_NAME = 'tenjin-cli';\n\n/**\n * The product the WebSearch hook leads with, so a ridealong query is separable\n * from a deliberate `tenjin search`. Leading is the mechanism: the server\n * attributes on the FIRST User-Agent product, landing here in `client_name`.\n *\n * The separation is the deliverable, not any one consumer: whatever judges hook\n * demand needs these populations distinguishable at ingest (tenjin#704,\n * tenjin-agent#179). A rename breaks no filter today, it merges them again. */\nexport const WEBSEARCH_HOOK_PRODUCT_NAME = 'tenjin-websearch-hook';\nexport const WEBSEARCH_HOOK_PRODUCT = `${WEBSEARCH_HOOK_PRODUCT_NAME}/${pkg.version}`;\n\n/** Every identity of ours a handoff may carry, which composition drops rather\n * than duplicate, whichever product is leading. */\nexport const OWN_PRODUCT_NAMES = [TENJIN_PRODUCT_NAME, WEBSEARCH_HOOK_PRODUCT_NAME];\n\n/**\n * The identifying comment. It rides LAST so a caller's products keep the order\n * they were handed off in, and so stripping it is enough to recover the caller's\n * sequence from an already-composed field (see `composeUserAgent`).\n */\nexport const TENJIN_COMMENT = `(+${PRODUCTION_ORIGIN})`;\n\n/**\n * The CLI's identity on every HTTP request, sent as the standard `User-Agent`\n * header from the shared transport (`http.ts`). `X-Tenjin-Client` is retired and\n * this CLI sends it nowhere.\n */\nexport const TENJIN_USER_AGENT = `${TENJIN_PRODUCT} ${TENJIN_COMMENT}`;\n\n/** The same field for the WebSearch hook, which identifies as its own product. */\nexport const WEBSEARCH_HOOK_USER_AGENT = `${WEBSEARCH_HOOK_PRODUCT} ${TENJIN_COMMENT}`;\n\n/** The handoff seam for an agent that launches the CLI as a subprocess. */\nexport const CALLER_USER_AGENT_ENV = 'TENJIN_CALLER_USER_AGENT';\n\n/** The server's bound: a longer field is discarded whole, never truncated. */\nexport const USER_AGENT_MAX_LENGTH = 512;\n\n/**\n * One RFC 9110 product: a token, optionally `/token`. The handoff accepts a\n * sequence of these and nothing else (no comments, no free text), which is what\n * structurally keeps a user, wallet, session, hostname, or machine identifier\n * out of the field rather than a blocklist that has to guess at one.\n */\nexport const PRODUCT_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+)?$/;\n\n/** Printable ASCII, the only range the server parses; also excludes CR/LF/tab. */\nexport const PRINTABLE_ASCII_RE = /^[\\x20-\\x7e]*$/;\n\nexport interface ComposeUserAgentInput {\n /** A caller's product sequence, passed programmatically; wins over the env. */\n caller?: string | undefined;\n /** Environment seam; defaults to `process.env`. */\n env?: NodeJS.ProcessEnv;\n /** The product to lead with; the WebSearch hook passes its own. */\n product?: string;\n}\n\n/**\n * Compose the field the transport sends: the Tenjin product, then the caller's\n * products in their original order, then the Tenjin comment. The handoff is\n * SELF-REPORTED TELEMETRY and never trusted policy input; nothing here or on the\n * server may read it to decide entitlement, spend, or trust.\n *\n * Idempotent by construction: the caller value is decomposed into tokens, our own\n * product and comment are dropped from it, and the field is rebuilt from\n * `TENJIN_PRODUCT`, so re-composing an already-composed field (a retry, a nested\n * helper, an agent re-exporting the env it received) yields the same string\n * rather than a second `tenjin-cli` token. Caller products survive byte for byte.\n *\n * Rejection is total, never partial: a non-printable, non-product, or overlong\n * handoff is OMITTED and the Tenjin identity travels alone, because truncating a\n * product token would mint a different, false identity.\n */\nexport function composeUserAgent(input: ComposeUserAgentInput = {}): string {\n const product = input.product ?? TENJIN_PRODUCT;\n const alone = `${product} ${TENJIN_COMMENT}`;\n const raw = input.caller ?? (input.env ?? process.env)[CALLER_USER_AGENT_ENV];\n const products = callerProducts(raw);\n if (products.length === 0) return alone;\n const composed = `${product} ${products.join(' ')} ${TENJIN_COMMENT}`;\n return composed.length <= USER_AGENT_MAX_LENGTH ? composed : alone;\n}\n\n/** The caller's products, or none at all when any part of the handoff is unusable. */\nfunction callerProducts(raw: string | undefined): string[] {\n if (raw === undefined || !PRINTABLE_ASCII_RE.test(raw)) return [];\n // Printable ASCII leaves the space as the only whitespace, so it is the only\n // separator a product sequence can have.\n const tokens = raw.split(' ').filter((token) => token.length > 0 && !isOwnIdentity(token));\n return tokens.every((token) => PRODUCT_RE.test(token)) ? tokens : [];\n}\n\n/**\n * Our own identity inside a caller value, matched case-insensitively: a product\n * token is case-sensitive to the server, but a copy of ours in any casing is\n * still a duplicate identity, and dropping it is what makes composition total.\n */\nfunction isOwnIdentity(token: string): boolean {\n const lower = token.toLowerCase();\n // Both sides are lowered: comparing a lowered token against a constant that is\n // merely all-lowercase TODAY would break silently the day either gains a\n // capital, and it fails safe (the stale copy stops matching, then fails\n // PRODUCT_RE, and the whole handoff drops), so nothing would notice.\n if (lower === TENJIN_COMMENT.toLowerCase()) return true;\n return OWN_PRODUCT_NAMES.some((name) => {\n const own = name.toLowerCase();\n return lower === own || lower.startsWith(`${own}/`);\n });\n}\n","import { CliError } from './errors';\nimport { composeUserAgent } from './client-meta';\n\n/**\n * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `search`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers, merged onto the User-Agent this module always sends. */\n headers?: Record<string, string>;\n /** The team shelf's bypass secret and its origin; see {@link ShelfBypass}. */\n bypass?: ShelfBypass;\n /**\n * INTERNAL. A caller's own product sequence, composed BEHIND the CLI's\n * identity (see `composeUserAgent`). The package ships a `bin` and no\n * `exports` map, so this is not a supported seam for code outside this repo:\n * the documented handoff is the `TENJIN_CALLER_USER_AGENT` environment\n * variable, which is what a subprocess launcher sets and what this falls back\n * to. Kept as an option so an in-repo caller can pass a value the environment\n * does not carry.\n */\n callerUserAgent?: string;\n}\n\n/**\n * The team shelf's Vercel \"Protection Bypass for Automation\" header.\n *\n * A door key for a protected preview deployment, not a credential of anyone's:\n * it gets a request past Deployment Protection and authenticates nobody. It is\n * NOT in {@link CREDENTIAL_HEADERS}, whose members are wallet-signed material a\n * redirect target could REPLAY — this one cannot be replayed into a signature.\n * It is still a secret, and DISCLOSING it is the whole harm: whoever holds it\n * walks into the team shelf. So it pins redirects exactly as a signed header\n * does (see {@link carriesBypassKey}), and where it may go is decided here and\n * nowhere else.\n */\nexport const SHELF_BYPASS_HEADER = 'x-vercel-protection-bypass';\n\n/**\n * A bypass secret and the origin it belongs to.\n *\n * THE ORIGIN IS PART OF THE VALUE, and that is the whole design. The CLI talks\n * to two shelves in team mode — the team's own deployment and the public\n * marketplace — and a caller that decides \"this request is to the team shelf, so\n * attach the key\" is a caller that eventually gets it wrong once. So callers\n * pass the pair and this transport does the compare: the header is attached from\n * the REQUEST URL, so a request to any other host cannot carry it, whatever the\n * call site believed.\n */\nexport interface ShelfBypass {\n /** `URL.origin` of the shelf the secret opens (the configured `baseUrl`). */\n origin: string;\n secret: string;\n}\n\n/** The bypass header for `url`, or nothing. Exported for the hook-script mirror\n * test, which runs the generated copy of this rule against this one. */\nexport function shelfBypassHeaders(\n url: string,\n bypass: ShelfBypass | undefined,\n): Record<string, string> {\n if (bypass === undefined || bypass.secret.length === 0) return {};\n let origin: string;\n try {\n origin = new URL(url).origin;\n } catch {\n return {};\n }\n if (origin !== bypass.origin) return {};\n return { [SHELF_BYPASS_HEADER]: bypass.secret };\n}\n\n/**\n * Whether the request being assembled actually carries the door key.\n *\n * A request that carries it MUST NOT follow a redirect. `fetch`'s default\n * `redirect: 'follow'` re-sends request headers verbatim to the new host (Node\n * strips only `Authorization`), so a single 3xx anywhere on the shelf origin —\n * the Vercel Authentication interstitial a rotated bypass secret gets, a domain\n * alias, a CDN rule — would hand the team shelf's key to whatever `Location`\n * names. Nothing else is needed to walk in afterwards, so the key never leaves\n * the origin it was paired with, not even one hop.\n *\n * Read off the BUILT headers rather than off `opts.bypass`, for the same reason\n * {@link CREDENTIAL_HEADERS} is matched by name: attaching the secret is what\n * arms the protection, so an off-origin request (which gets no header) keeps\n * ordinary transport and a call site cannot forget to ask for the pin.\n */\nfunction carriesBypassKey(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => name.toLowerCase() === SHELF_BYPASS_HEADER);\n}\n\n/** The anonymous install id: a random UUID minted once per data dir. */\nexport const INSTALL_ID_HEADER = 'tenjin-install-id';\n\n/**\n * Who is using the router, for Tenjin's own request telemetry: an anonymous\n * install id, random and tied to nothing but the data dir.\n *\n * Same shape as {@link ShelfBypass}, for the same reason: the transport decides\n * where it goes, from the REQUEST URL, so a call site cannot send it to a\n * provider by believing it is talking to Tenjin. `pay` runs over this transport\n * to third-party sellers, and none of them gets the header.\n *\n * Process-wide rather than a per-call option because it is not a per-call\n * decision: every request to Tenjin carries it, and threading it through forty\n * call sites is forty chances to forget one. Set only by the two process entries\n * (the CLI's `index.ts` and the daemon), so an in-process test that never sets\n * it sends exactly what it always did.\n *\n * Redirects are left to the request's usual transport: an unpinned request\n * follows them as `fetch` does, headers and all. Tenjin's origins redirect only\n * to Tenjin's own hosts, and the id is not a credential, so it is not worth the\n * redirect pin the bypass key and signed headers get.\n */\nexport interface TenjinIdentity {\n /** The origins that are Tenjin's own for this process. */\n origins: () => Promise<readonly string[]>;\n /** The install id; absent when it could not be read or created. */\n installId: () => Promise<string | undefined>;\n}\n\nlet tenjinIdentity: TenjinIdentity | undefined;\n\nexport function setTenjinIdentity(identity: TenjinIdentity | undefined): void {\n tenjinIdentity = identity;\n}\n\n/**\n * The telemetry headers for `url`, or nothing. NEVER THROWS: a data dir that\n * cannot be read costs the request its telemetry and nothing else.\n */\nexport async function tenjinIdentityHeaders(url: string): Promise<Record<string, string>> {\n const identity = tenjinIdentity;\n if (identity === undefined) return {};\n try {\n if (!(await identity.origins()).includes(new URL(url).origin)) return {};\n const id = await identity.installId();\n return id !== undefined ? { [INSTALL_ID_HEADER]: id } : {};\n } catch {\n return {};\n }\n}\n\n/**\n * The one place the identity is written for anything that can import it; both\n * transports funnel their Headers through it, so a third entry point on this\n * side cannot ship without it. `.set` on a Headers\n * object is what makes this total: a caller header spelled `User-Agent` in any\n * case lands in the same slot and is overwritten, never duplicated, so a\n * call-specific header cannot erase the composed field or add a second one.\n */\nfunction applyUserAgent(headers: Headers, callerUserAgent?: string): Headers {\n headers.set('user-agent', composeUserAgent({ caller: callerUserAgent }));\n return headers;\n}\n\n/** The same write for `fetchJson`'s plain-object headers; Headers.entries() is lowercase-keyed. */\nfunction withUserAgent(\n callerHeaders?: Record<string, string>,\n callerUserAgent?: string,\n): Record<string, string> {\n return Object.fromEntries(\n applyUserAgent(new Headers(callerHeaders ?? {}), callerUserAgent).entries(),\n );\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json' | 'blocked-redirect' | 'oversized-header';\n status?: number;\n requestId?: string;\n message: string;\n /**\n * On `invalid-json`, and on `http` when the status is 401/403: the response\n * looks like an access-protection or sign-in page rather than an API answer.\n * See {@link accessGateSignals} for what \"looks like\" means. Callers use it to\n * point at the missing credential instead of at the base URL, which is the one\n * setting that was already correct (#218).\n */\n gateSuspected?: boolean;\n /**\n * Present (true) only where the response left the host that was asked for:\n * `gateSuspected`'s STRONGER signal (the final URL's host differs), or, on\n * `blocked-redirect`, a `Location` that resolves to another host. An HTML\n * content-type alone proves a page came back, not who sent it, and a 3xx\n * alone proves only that the URL moved; leaving the host is what lets a\n * caller name access protection outright.\n */\n gateOffOrigin?: boolean;\n /**\n * On `network`: the layer the error chain names, when it names one. The\n * origin never answered, so a caller that blames it (or its base URL) gives\n * the wrong fix. See {@link transportFailure}.\n */\n transport?: TransportFailure;\n /**\n * On a `timeout` that came after the response headers did (`httpRequest`\n * only): a case-insensitive lookup over them. A seller can name where a long\n * job's result will be with its first byte, and only the body ran out of time.\n */\n header?: (name: string) => string | undefined;\n}\n\n/** Which layer refused a request that never reached the origin. */\nexport interface TransportFailure {\n layer: 'proxy' | 'dns' | 'tls' | 'connect';\n /** The socket's own error code, for every layer but `proxy`. */\n code?: string;\n /** What the proxy answered to `CONNECT`, for `proxy` only. */\n proxyStatus?: number;\n}\n\n/**\n * Does this response read as a protection page rather than as an API answer?\n *\n * Two independent signals, reported separately because they prove different\n * amounts (the caller's wording must not outrun the evidence):\n *\n * - an HTML content-type, because a Vercel Deployment Protection interstitial\n * and every sign-in wall answer with a page;\n * - a final URL whose host is not the one asked for, because a gate that\n * redirects to sign in lands the probe on another host and `fetch` follows it\n * silently on the unpinned requests this function serves.\n *\n * Decided HERE because this transport is the only place holding the `Response`;\n * a caller re-deriving it from the failure message would be guessing. An\n * unreadable final URL is NOT suspicion: `res.url` is empty on a synthesized\n * Response, so only a host that reads AND differs counts.\n */\nfunction accessGateSignals(\n requestedUrl: string,\n res: Response,\n): { gateSuspected: boolean; gateOffOrigin?: true } {\n const html = /^\\s*text\\/html\\b/i.test(res.headers.get('content-type') ?? '');\n let offOrigin = false;\n if (res.url.length > 0) {\n try {\n offOrigin = new URL(requestedUrl).host !== new URL(res.url).host;\n } catch {\n offOrigin = false;\n }\n }\n return {\n gateSuspected: html || offOrigin,\n ...(offOrigin ? { gateOffOrigin: true as const } : {}),\n };\n}\n\n/**\n * Does an unfollowed 3xx point off the host that was asked for?\n *\n * The pinned branch never follows, so `res.url` is still the requested URL and\n * `Location` is the only evidence about where the hop went. That distinction\n * carries the whole verdict downstream: a gate's sign-in interstitial lands on\n * another host, while an `http://` base URL that 301s to https, or a host\n * normalising to its canonical name, does not, and reading either as a refused\n * credential blames the wrong setting. A relative target resolves against the\n * request, so it is same-host by construction; a missing or unparseable one is\n * NOT an off-host claim.\n */\nfunction redirectLeavesHost(requestedUrl: string, location: string | null): boolean {\n if (location === null || location.length === 0) return false;\n try {\n return new URL(requestedUrl).host !== new URL(location, requestedUrl).host;\n } catch {\n return false;\n }\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect. `resource-ref`\n * pins the invariant — \"nothing signed may leave for a host the user did not\n * configure\" — but `assertOnBaseOrigin` only checks the URL the caller asked\n * for, and `fetch`'s default `redirect: 'follow'` re-sends request headers\n * verbatim to the new host (Node strips only `Authorization`). A 3xx anywhere on\n * the configured origin would therefore hand a signature BOUND TO THE REAL\n * DOMAIN to whoever `Location` points at, replayable against it for the\n * signature's lifetime.\n *\n * Detected by header NAME rather than by a caller-supplied \"this is signed\" flag\n * so the protection cannot be forgotten at a call site: attaching the credential\n * is what arms it. Matched case-insensitively. Kept as literals so the base\n * transport keeps its single dependency; `http.test.ts` pins them against the\n * real constants in `lib/siwx` and the x402 payment headers.\n *\n * All three wallet-signed families this CLI sends are here: the SIWX auth\n * header, the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance even\n * though `read-client` pins v2), and `tenjin-session-delegation` — a REUSABLE\n * session-lifetime SIWX signature `session-key` attaches to every session-signed\n * write, which makes it the most replayable credential of the set. The RFC 9421\n * `Signature`/`Signature-Input` pair riding alongside it is deliberately absent:\n * it covers method, URL, and body digest, so it is not usefully replayable at\n * another host.\n */\nconst CREDENTIAL_HEADERS = new Set([\n 'sign-in-with-x',\n 'payment-signature',\n 'x-payment',\n 'tenjin-session-delegation',\n]);\n\nfunction carriesSignedMaterial(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));\n}\n\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n // `new Headers` throws on a malformed caller header, so building them stays\n // inside the catch that turns any pre-flight refusal into the same\n // discriminated network failure a dead socket gets.\n let pinned = false;\n try {\n const headers = withUserAgent(\n { ...opts.headers, ...shelfBypassHeaders(url, opts.bypass) },\n opts.callerUserAgent,\n );\n // fetchJson sends no signed material — doctor's probes and the contract\n // checks are anonymous — so the door key is the one thing here worth\n // pinning, and it pins the same way it does in httpRequest.\n pinned = carriesBypassKey(headers);\n res = await doFetch(url, {\n signal: controller.signal,\n headers: { ...headers, ...(await tenjinIdentityHeaders(url)) },\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED, ahead of the ordinary non-2xx branch, so an unfollowed 3xx is\n // never reported as a plain HTTP status a caller might retry by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n // Where it pointed, not that it pointed: only a hop that leaves the host\n // asked for is evidence about the key. Same-host 3xx happens to a base\n // URL that needs fixing, with a perfectly good key.\n ...(redirectLeavesHost(url, res.headers.get('location'))\n ? { gateOffOrigin: true as const }\n : {}),\n message:\n `Request to ${url} was redirected (${res.status}) while carrying the team shelf's ` +\n 'bypass key; refusing to follow it, because the key opens only the configured origin.',\n };\n }\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n // 401/403 is one of the three shapes deployment protection answers with\n // (200 HTML and a 30x interstitial are the others), so the gate signals\n // ride here too. Other statuses stay unmarked: a 404 or 500 HTML page is\n // an ordinary broken deployment, not a credential problem.\n ...(res.status === 401 || res.status === 403 ? accessGateSignals(url, res) : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n ...accessGateSignals(url, res),\n message: `Response from ${url} was not valid JSON`,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and search/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'DELETE';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** The team shelf's bypass secret and its origin; see {@link ShelfBypass}. */\n bypass?: ShelfBypass;\n /** INTERNAL; see `FetchJsonOptions.callerUserAgent`. */\n callerUserAgent?: string;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n /**\n * A body the CALLER already encoded, sent byte for byte with no content-type\n * of this transport's choosing: the router's provider leg is handed a request\n * the server built, and re-encoding it would make the bytes signed for and\n * the bytes sent two different things. The caller's own `headers` carry the\n * content type. Ignored when `jsonBody` is set.\n */\n rawBody?: string;\n fetchImpl?: typeof fetch;\n /**\n * A caller's own abort, combined with (never replacing) `timeoutMs`. The loop's\n * legs pass the fire's signal here so a harness that closed its socket stops the\n * request in flight; a caller with no such signal is unchanged.\n */\n signal?: AbortSignal;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact (`fetchRead`: the\n * 200 is written to the library as an entitlement record under the\n * server-chosen id/slug), following a cross-origin redirect would let\n * another host's bytes be recorded as if the configured origin served them.\n * Off by default so search/outcome/publish/doctor keep normal transport.\n */\n blockRedirects?: boolean;\n /**\n * Keep a binary body as bytes. A sound, an image or any other non-text\n * payload decoded as text is corrupted, so with this set a response whose\n * content type is not text ({@link isBinaryContentType}) comes back with\n * `bytes` and an empty `text`. The router's provider leg sets it; every other\n * caller reads text as before.\n */\n binaryBody?: boolean;\n /** The cap on such a body; over it the response is a failure, never a\n * buffer that grows without bound. Defaults to {@link MAX_BINARY_BODY_BYTES}. */\n maxBinaryBytes?: number;\n /**\n * Send no install id, and mint none. For a request that checks the network\n * rather than uses Tenjin (the reachability probe), so it never counts as an\n * install in request telemetry.\n */\n anonymous?: boolean;\n}\n\n/** The same cap the router's linked-media download uses. */\nexport const MAX_BINARY_BODY_BYTES = 200 * 1024 * 1024;\n\n/**\n * The body's bytes, read chunk by chunk and abandoned the moment they pass\n * `max`; null over the cap. A declared length over it is refused unread.\n */\nasync function readCapped(res: Response, max: number): Promise<Uint8Array | null> {\n const declared = Number(res.headers.get('content-length') ?? '0');\n if (Number.isFinite(declared) && declared > max) {\n await res.body?.cancel().catch(() => undefined);\n return null;\n }\n if (res.body === null) return new Uint8Array();\n const reader = res.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > max) {\n await reader.cancel().catch(() => undefined);\n return null;\n }\n chunks.push(value);\n }\n return new Uint8Array(Buffer.concat(chunks));\n}\n\n/**\n * A content type whose body is not text: anything that is not `text/*` and\n * not a JSON, XML, JavaScript, YAML or form type. An absent header is text, as\n * it always was here.\n */\nexport function isBinaryContentType(contentType: string | undefined): boolean {\n const type = (contentType ?? '').split(';')[0]!.trim().toLowerCase();\n if (type.length === 0) return false;\n if (type.startsWith('text/')) return false;\n return !/(?:json|xml|javascript|ecmascript|yaml|x-www-form-urlencoded)/.test(type);\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n /** The raw body text; what a non-JSON endpoint actually said (`pay` delivers it). */\n text: string;\n /** The body's bytes, only for a binary body read with `binaryBody`; `text`\n * is then empty. */\n bytes?: Uint8Array;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\n/** The wire form of one request: what to send, and whether it may follow a redirect. */\ninterface PreparedRequest {\n ok: true;\n headers: Record<string, string>;\n body: string | undefined;\n signed: boolean;\n bypassed: boolean;\n pinned: boolean;\n}\n\n/**\n * Assemble the request and DERIVE its redirect decision from the headers that\n * were actually built, in one place and one pass. The redirect flags are\n * returned rather than assigned, so they have no value until the headers do:\n * there is no state in which `pinned` is readable but not yet computed, which\n * is what would let a signed request follow a 3xx to another host. Anything\n * that refuses here (`new Headers` throws on a malformed caller header) becomes\n * the same discriminated failure a dead socket does, because this transport\n * documents a returned failure for every refusal, not an exception.\n */\nfunction prepareRequest(url: string, opts: HttpRequestOptions): PreparedRequest | FetchJsonFailure {\n try {\n let body: string | undefined;\n // The bypass rides in with the caller's headers rather than being set after\n // them, so a caller cannot spell it a second way and win the slot.\n const merged = new Headers({ ...opts.headers, ...shelfBypassHeaders(url, opts.bypass) });\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n merged.set('content-type', 'application/json');\n } else if (opts.rawBody !== undefined) {\n body = opts.rawBody;\n }\n const wantsAccept = opts.method === 'POST' || opts.method === 'PUT' || body !== undefined;\n if (wantsAccept && !merged.has('accept')) merged.set('accept', 'application/json');\n // An `accept`/`content-type` set here wins the slot regardless of how a\n // caller cased its own copy.\n const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());\n\n // Signed requests opt out of redirect following entirely; see CREDENTIAL_HEADERS.\n // So does a request carrying the team shelf's bypass key: it cannot be\n // replayed, but a 3xx would DISCLOSE it, and that is the whole harm (see\n // carriesBypassKey). A caller can also pin an unsigned, keyless request\n // (blockRedirects) when the response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n const bypassed = carriesBypassKey(headers);\n return {\n ok: true,\n headers,\n body,\n signed,\n bypassed,\n pinned: signed || bypassed || opts.blockRedirects === true,\n };\n } catch (err) {\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n };\n }\n}\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n // The caller's abort is combined with the timeout rather than chosen between:\n // whichever fires first ends the request, and `timedOut` still says which.\n const signal =\n opts.signal === undefined\n ? controller.signal\n : AbortSignal.any([controller.signal, opts.signal]);\n\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, bypassed, pinned } = prepared;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers:\n opts.anonymous === true ? headers : { ...headers, ...(await tenjinIdentityHeaders(url)) },\n body,\n signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (isHeaderOverflow(err)) return oversizedHeaderFailure(url);\n const transport = transportFailure(err);\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n ...(transport !== undefined ? { transport } : {}),\n };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED on a redirect the request was not allowed to follow. This\n // returns a failure rather than the 3xx response so no caller can mistake an\n // unfollowed redirect for a normal status and retry it by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: signed\n ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; ` +\n 'refusing to follow it, because the signature is bound to the configured origin.'\n : bypassed\n ? `Request to ${url} was redirected (${res.status}) while carrying the team shelf's ` +\n 'bypass key; refusing to follow it, because the key opens only the configured origin.'\n : `Request to ${url} was redirected (${res.status}); ` +\n 'refusing to follow it, because the response must come from the configured origin.',\n };\n }\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n let bytes: Uint8Array | undefined;\n try {\n if (opts.binaryBody === true && isBinaryContentType(res.headers.get('content-type') ?? '')) {\n const read = await readCapped(res, opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES);\n if (read === null) {\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} returned a file over the ${Math.round((opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES) / 1_048_576)} MB cap; it was not kept.`,\n };\n }\n bytes = read;\n text = '';\n } else {\n text = await res.text();\n }\n } catch (err) {\n if (timedOut) {\n return {\n ...timeoutFailure(url, opts.timeoutMs),\n header: (name) => res.headers.get(name) ?? undefined,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n text,\n ...(bytes !== undefined ? { bytes } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\n : failure.kind === 'oversized-header'\n ? 'CHALLENGE_TOO_LARGE'\n : 'API_UNREACHABLE';\n // The one failure with a remedy nobody can apply from inside the process, so\n // it names the operator's knob rather than suggesting a retry.\n // The knob, with no claim about payment: a caller that knows its leg passes\n // its own `fix` and says what happened to the money there.\n const fix =\n opts.fix ??\n (failure.kind === 'oversized-header'\n ? 'Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes.'\n : undefined);\n return new CliError(code, failure.message, {\n ...(fix !== undefined ? { fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Does this transport failure mean the response HEADERS were too big for this\n * process to read?\n *\n * Node caps them at 16 KiB unless `--max-http-header-size` says otherwise, and\n * an x402 challenge is a header: a seller that embeds its whole output schema\n * in one can exceed the cap on its own (AnyAPI's is 52 KB, measured\n * 2026-09-22). undici then aborts the request and the generic path reported\n * `fetch failed` with no status and nothing naming the cause, which reads as\n * \"the endpoint is down\" for a seller that is answering perfectly.\n *\n * The message is undici's, matched on its stable text and on the code it\n * attaches; the CAUSE is the one that carries either, so both are checked.\n */\nfunction isHeaderOverflow(err: unknown): boolean {\n const seen = [err, (err as { cause?: unknown } | null)?.cause];\n return seen.some((candidate) => {\n if (candidate === null || typeof candidate !== 'object') return false;\n const code = (candidate as { code?: unknown }).code;\n if (code === 'UND_ERR_HEADERS_OVERFLOW' || code === 'HPE_HEADER_OVERFLOW') return true;\n const message = (candidate as { message?: unknown }).message;\n return typeof message === 'string' && /headers overflow|header overflow/i.test(message);\n });\n}\n\nconst DNS_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'EAI_FAIL', 'EAI_NODATA', 'EAI_NONAME']);\nconst CONNECT_CODES = new Set([\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ETIMEDOUT',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\nconst TLS_CODE = /^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_|SELF_SIGNED_|DEPTH_ZERO_)/;\n/** undici's text when a proxy answers `CONNECT` with anything but 200. */\nconst PROXY_REFUSAL = /Proxy response \\((\\d{3})\\)/;\n\n/**\n * The layer a `fetch failed` came from, read down the `cause` chain. fetch\n * wraps the real error twice: a proxy refusing the tunnel is\n * `TypeError: fetch failed`, then `Request was cancelled.`, then undici's\n * `UND_ERR_ABORTED` with the proxy's status in its message (Node 24.18,\n * measured 2026-10-05). Undefined when no link names a layer.\n */\nexport function transportFailure(err: unknown): TransportFailure | undefined {\n let link: unknown = err;\n for (let depth = 0; depth < 5 && link !== null && typeof link === 'object'; depth += 1) {\n const { code, message, cause } = link as { code?: unknown; message?: unknown; cause?: unknown };\n const proxy = typeof message === 'string' ? PROXY_REFUSAL.exec(message) : null;\n if (proxy !== null) return { layer: 'proxy', proxyStatus: Number(proxy[1]) };\n if (typeof code === 'string') {\n if (DNS_CODES.has(code)) return { layer: 'dns', code };\n if (TLS_CODE.test(code)) return { layer: 'tls', code };\n if (CONNECT_CODES.has(code)) return { layer: 'connect', code };\n }\n link = cause;\n }\n return undefined;\n}\n\n/**\n * The named refusal for that case. NOT a `network` failure: nothing is wrong\n * with the connection, and a caller that retries gets the same 52 KB again.\n *\n * SAYS NOTHING ABOUT PAYMENT. This transport serves the unpaid probe and the\n * paid retry alike and cannot tell them apart, so a message asserting either\n * way is wrong on one of them: it read as \"nothing was sent\" on a leg where a\n * signed authorization had already left. The leg adds that sentence, because\n * the leg is what knows; see `runPay`.\n */\nfunction oversizedHeaderFailure(url: string): FetchJsonFailure {\n let origin = url;\n try {\n origin = new URL(url).origin;\n } catch {\n // Keep the raw string; this is a diagnostic, not a destination.\n }\n return {\n ok: false,\n kind: 'oversized-header',\n message:\n `${origin} answered with a response header block larger than this process will read. ` +\n 'An x402 challenge travels in a header, and a seller that embeds its whole output ' +\n 'schema in one can exceed the limit, so the response could not be read.',\n };\n}\n"],"mappings":";;;;;;;;;;;;AASO,IAAM,iBAAiB,cAAc,gBAAI,OAAO;AAGhD,IAAM,sBAAsB;AAU5B,IAAM,8BAA8B;AACpC,IAAM,yBAAyB,GAAG,2BAA2B,IAAI,gBAAI,OAAO;AAI5E,IAAM,oBAAoB,CAAC,qBAAqB,2BAA2B;AAO3E,IAAM,iBAAiB,KAAK,iBAAiB;AAO7C,IAAM,oBAAoB,GAAG,cAAc,IAAI,cAAc;AAG7D,IAAM,4BAA4B,GAAG,sBAAsB,IAAI,cAAc;AAG7E,IAAM,wBAAwB;AAG9B,IAAM,wBAAwB;AAQ9B,IAAM,aAAa;AAGnB,IAAM,qBAAqB;AA2B3B,SAAS,iBAAiB,QAA+B,CAAC,GAAW;AAC1E,QAAM,UAAU,MAAM,WAAW;AACjC,QAAM,QAAQ,GAAG,OAAO,IAAI,cAAc;AAC1C,QAAM,MAAM,MAAM,WAAW,MAAM,OAAO,QAAQ,KAAK,qBAAqB;AAC5E,QAAM,WAAW,eAAe,GAAG;AACnC,MAAI,SAAS,WAAW,EAAG,QAAO;AAClC,QAAM,WAAW,GAAG,OAAO,IAAI,SAAS,KAAK,GAAG,CAAC,IAAI,cAAc;AACnE,SAAO,SAAS,UAAU,wBAAwB,WAAW;AAC/D;AAGA,SAAS,eAAe,KAAmC;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,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,WAAW;AAEjB,IAAM,gBAAgB;AASf,SAAS,iBAAiB,KAA4C;AAC3E,MAAI,OAAgB;AACpB,WAAS,QAAQ,GAAG,QAAQ,KAAK,SAAS,QAAQ,OAAO,SAAS,UAAU,SAAS,GAAG;AACtF,UAAM,EAAE,MAAM,SAAS,MAAM,IAAI;AACjC,UAAM,QAAQ,OAAO,YAAY,WAAW,cAAc,KAAK,OAAO,IAAI;AAC1E,QAAI,UAAU,KAAM,QAAO,EAAE,OAAO,SAAS,aAAa,OAAO,MAAM,CAAC,CAAC,EAAE;AAC3E,QAAI,OAAO,SAAS,UAAU;AAC5B,UAAI,UAAU,IAAI,IAAI,EAAG,QAAO,EAAE,OAAO,OAAO,KAAK;AACrD,UAAI,SAAS,KAAK,IAAI,EAAG,QAAO,EAAE,OAAO,OAAO,KAAK;AACrD,UAAI,cAAc,IAAI,IAAI,EAAG,QAAO,EAAE,OAAO,WAAW,KAAK;AAAA,IAC/D;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAYA,SAAS,uBAAuB,KAA+B;AAC7D,MAAI,SAAS;AACb,MAAI;AACF,aAAS,IAAI,IAAI,GAAG,EAAE;AAAA,EACxB,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SACE,GAAG,MAAM;AAAA,EAGb;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/hook-tool.ts"],"sourcesContent":["/**\n * THE HOOK EVENT, CARRIED BY AN `mcp_tool` ENTRY. Claude Code calls the `hook`\n * tool of the session's own `tenjin mcp` for each routing leg, with the event's\n * fields substituted into the entry's `input` (`${session_id}` and so on): a\n * string field arrives as written, an object one (`tool_input`,\n * `tool_response`) as its JSON text, a boolean as `true` or `false`, and a\n * field the event lacks as an empty string. This turns that back into the\n * event the handlers already read, and spells the `input` `install` writes.\n */\n\n/** The routing legs, one per hook entry `install` writes. */\nexport const HOOK_KINDS = ['prompt', 'native', 'shortfall', 'agent', 'ask', 'answer'] as const;\nexport type HookKind = (typeof HOOK_KINDS)[number];\n\n/** The tool `tenjin mcp` registers for the hook entries. */\nexport const HOOK_TOOL = 'hook';\n\n/** The event fields each leg reads, as Claude Code names them. */\nconst COMMON = ['hook_event_name', 'session_id', 'transcript_path', 'cwd'] as const;\nconst CALL = ['tool_name', 'tool_input', 'tool_use_id', 'agent_id', 'agent_type'] as const;\n\nconst FIELDS: Record<HookKind, readonly string[]> = {\n prompt: [...COMMON, 'prompt'],\n native: [...COMMON, ...CALL],\n agent: [...COMMON, ...CALL],\n ask: [...COMMON, ...CALL],\n answer: [...COMMON, ...CALL, 'tool_response'],\n shortfall: [...COMMON, ...CALL, 'tool_response', 'error', 'is_interrupt'],\n};\n\n/** Fields whose value is an object or a boolean, sent as JSON text. */\nconst JSON_FIELDS = new Set(['tool_input', 'tool_response', 'is_interrupt']);\n\n/** The `input` of one leg's `mcp_tool` entry. */\nexport function hookToolInput(kind: HookKind): Record<string, string> {\n return Object.fromEntries([\n ['kind', kind],\n ...FIELDS[kind].map((field) => [field, `\\${${field}}`]),\n ]);\n}\n\n/** Every field any leg sends, for the tool's input schema. */\nexport const HOOK_TOOL_FIELDS: readonly string[] = [...new Set(Object.values(FIELDS).flat())];\n\nexport function isHookKind(value: unknown): value is HookKind {\n return typeof value === 'string' && (HOOK_KINDS as readonly string[]).includes(value);\n}\n\n/**\n * The harness event from the tool's arguments: empty fields dropped (the\n * event did not carry them), the JSON ones parsed back. A JSON field that does\n * not parse is kept as the string it is.\n */\nexport function eventFromToolInput(args: Record<string, unknown>): Record<string, unknown> {\n const event: Record<string, unknown> = {};\n for (const field of HOOK_TOOL_FIELDS) {\n const value = args[field];\n if (typeof value !== 'string' || value.length === 0) continue;\n if (!JSON_FIELDS.has(field)) {\n event[field] = value;\n continue;\n }\n try {\n event[field] = JS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