[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79P7DST31TGY7SGDS30WG9F":3,"skill-same:01M79P7DST31TGY7SGDS30WG9F":43},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M79P7DST31TGY7SGDS30WG9F","javascript-and-typescript-security-cheat-sheet",null,"JunMystery\u002FAgent-Guidance","JunMystery","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F161468934?v=4","01M79MTMV8F0BY8NK1A92RA8A0","Jun","01M79MTMWCFBKPHN5B25E6V20B",0,"MIT","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fjavascript-and-typescript-security-cheat-sheet\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# JavaScript and TypeScript Security Cheat Sheet\n\n## Introduction\n\nThis cheat sheet lists secure development practices for JavaScript and TypeScript that apply everywhere the language runs: browsers, hybrid apps, server-side Node.js, and any other runtime that implements the language ([MDN JavaScript](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FJavaScript)). It covers language-level pitfalls (dynamic code execution, prototype pollution, regular expressions), client-side sinks, and TypeScript-specific false confidence. Rules that are equally valid on the client and the server are stated once here; backend and runtime hardening stays in the [Node.js Security Cheat Sheet](Nodejs_Security_Cheat_Sheet.md), which this sheet links to instead of duplicating.\n\n## Related Cheat Sheets (Top-Level Links)\n\n- [Node.js Security Cheat Sheet](Nodejs_Security_Cheat_Sheet.md) - backend and runtime guidance.\n- [Cross Site Scripting Prevention Cheat Sheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md) - output encoding rules per context.\n- [DOM based XSS Prevention Cheat Sheet](DOM_based_XSS_Prevention_Cheat_Sheet.md) - client-side XSS sinks and sources.\n- [Third Party JavaScript Management Cheat Sheet](Third_Party_Javascript_Management_Cheat_Sheet.md) - managing external scripts.\n- [Transport Layer Security Cheat Sheet](Transport_Layer_Security_Cheat_Sheet.md) - TLS configuration.\n- [OWASP Cheat Sheet Series index](https:\u002F\u002Fcheatsheetseries.owasp.org\u002F) - start here for the full catalog.\n\n## Dangerous Language Surface\n\n### `eval`, `Function`, and `with`\n\nNever build code from strings. See [MDN's eval guidance](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FJavaScript\u002FReference\u002FGlobal_Objects\u002Feval). `eval` and `new Function` execute arbitrary code with the current runtime's privileges, so any attacker-influenced input reaching them is code injection ([CWE-94](https:\u002F\u002Fcwe.mitre.org\u002Fdata\u002Fdefinitions\u002F94.html)). In browsers, `setTimeout` and `setInterval` with a string argument compile it the same way through implied `eval`.\n\n- Parse data with `JSON.parse`, never `eval`.\n- Replace dynamic dispatch with static maps of functions instead of constructing calls from names.\n- Do not use the `with` statement. It makes scope unpredictable, is forbidden in strict mode, and blocks engine optimizations.\n- Enforce this statically with the `no-eval`, `no-implied-eval`, and `no-new-func` lint rules.\n- In browsers, block string compilation with an enforced Content Security Policy whose `script-src` directive, or `default-src` fallback, omits both `'unsafe-eval'` and `'trusted-types-eval'`. A report-only policy does not block execution ([CSP `EnsureCSPDoesNotBlockStringCompilation`](https:\u002F\u002Fw3c.github.io\u002Fwebappsec-csp\u002F#can-compile-strings)).\n- CSP is a browser-side control and does not apply to server-side runtimes, so the lint rules remain the primary enforcement everywhere.\n\n### Evil Regex (ReDoS)\n\nNested quantifiers such as `(a+)+`, and repeated ambiguous alternatives such as `^(a|aa)*$`, can make matching take exponential time on crafted input, consuming CPU and potentially blocking the executing thread or event loop ([CWE-1333](https:\u002F\u002Fcwe.mitre.org\u002Fdata\u002Fdefinitions\u002F1333.html)). Whether a pattern is actually exploitable depends on the surrounding expression and the failing input, not just the quantified group.\n\n- Prefer well-tested validators over hand-written patterns for emails, URLs, and similar inputs.\n- Keep patterns linear: avoid nested quantifiers and ambiguous alternation over the same characters.\n- Cap untrusted input length before matching, and reject rather than sanitize when input does not match.\n- For the attack mechanics and detection tooling, see the [OWASP ReDoS guidance](https:\u002F\u002Fowasp.org\u002Fwww-community\u002Fattacks\u002FRegular_expression_Denial_of_Service_-_ReDoS); use linear-time patterns as the primary control and input-length caps as defense in depth.\n\n### Strict Mode\n\nShip ES modules (strict by default) or declare `'use strict'`, as described in [MDN's strict mode documentation](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FJavaScript\u002FReference\u002FStrict_mode). Strict mode turns silent mistakes into errors: assignment to undeclared variables throws, `this` stays `undefined` in plain functions instead of becoming the global object, and `with` is rejected. It does not fix injection, XSS, or prototype pollution; treat it as hygiene, not a security boundary.\n\n## Object and Property Safety (Including Prototype Pollution)\n\nPrototype pollution ([CWE-1321](https:\u002F\u002Fcwe.mitre.org\u002Fdata\u002Fdefinitions\u002F1321.html)) occurs when attacker-controlled keys such as `__proto__`, `constructor`, or `prototype` reach a recursive merge or path setter and modify an object's prototype. This can alter the behavior of objects that inherit from that prototype. These are the JavaScript-specific essentials only; the full protection guidance lives in the dedicated [Prototype Pollution Prevention Cheat Sheet](Prototype_Pollution_Prevention_Cheat_Sheet.md).\n\n- Never pass untrusted input to a recursive merge or `set-by-path` helper, and reject the key segments `__proto__`, `constructor`, and `prototype` before writing.\n- Use a `Map` with `set`, `get`, and `has` for untrusted dictionary keys, keeping entries separate from object properties ([MDN prototype pollution defenses](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FSecurity\u002FAttacks\u002FPrototype_pollution#use_map_and_set_instead)). If an object is required, create it with `Object.create(null)` so it has no prototype.\n- Validate parsed or copied untrusted data against a schema before use, and drop `__proto__` keys first: `Object.assign` applies them through the prototype setter and mutates the target's prototype, while spread creates a silent own property.\n\n## DOM Sinks and Output Context\n\nInjecting attacker-controlled strings into HTML, script, or URL contexts is cross-site scripting ([CWE-79](https:\u002F\u002Fcwe.mitre.org\u002Fdata\u002Fdefinitions\u002F79.html)). Follow the [Cross Site Scripting Prevention Cheat Sheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md) for per-context encoding and the [DOM based XSS Prevention Cheat Sheet](DOM_based_XSS_Prevention_Cheat_Sheet.md) for client-side sources and sinks.\n\n- Build DOM with `textContent` and `createElement` instead of `innerHTML` or `insertAdjacentHTML`.\n- When HTML must be rendered, sanitize with a maintained allowlist sanitizer and enforce [Trusted Types](https:\u002F\u002Fw3c.github.io\u002Ftrusted-types\u002Fdist\u002Fspec\u002F) with no permissive default policy.\n- Framework auto-escaping has explicit bypasses that must never receive untrusted input: React `dangerouslySetInnerHTML`, Vue `v-html`, and Angular `bypassSecurityTrustHtml` and its siblings.\n\n## Async Error Handling, Messaging, and Origin Checks\n\nNot every promise failure is a defect. An *expected* failure is part of a function's contract, such as a lookup that returns `null` for a missing key or a parse that throws on malformed input; handle it where the caller decides what to do, with a `try`\u002F`catch` around `await` or a `.catch` on the terminal link of the chain, and return a typed result or a documented error. An *unhandled* rejection is a promise that rejects with no handler attached, so the failure propagates past the call site and is usually a bug: browsers report it in the console and fire an `unhandledrejection` event, while Node.js behavior depends on its unhandled-rejection mode and may terminate the process ([MDN promise rejection events](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FJavaScript\u002FGuide\u002FUsing_promises#promise_rejection_events)). Keep promise chains flat with a terminal error handler so genuinely unexpected rejections stay visible, and do not silence them with an empty `catch`. Server-side specifics live in the [Node.js Security Cheat Sheet](Nodejs_Security_Cheat_Sheet.md) and are not repeated here.\n\nFor `postMessage`, the receiver must verify `event.origin` against an explicit allowlist, check `event.source` when a conversation partner is expected, and validate `event.data` against the expected schema before acting on it. The sender must pass an exact `targetOrigin`, never `\"*\"` for sensitive data ([MDN postMessage](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002FWindow\u002FpostMessage)). Prefer narrow `MessageChannel` ports over broadcast messaging where the design allows it.\n\n## TypeScript-Specific Caveats\n\nTypes are erased at runtime, so TypeScript alone enforces nothing against a malicious or malformed caller.\n\n- Treat `any` as a hole in every check. `unknown` is the safe default for values of unknown type, because it forces you to narrow before use, whereas `any` disables type checking for that value ([TypeScript Handbook: `unknown`](https:\u002F\u002Fwww.typescriptlang.org\u002Fdocs\u002Fhandbook\u002F2\u002Ffunctions.html#unknown)).\n- Type assertions (`as`) and non-null assertions (`!`) silence the compiler without changing runtime values; do not use them on untrusted data.\n- Enable `strict` in `tsconfig.json` (plus `noUncheckedIndexedAccess` where affordable) to catch accidental unsafety in your own code. It is a code-quality control, not a trust boundary.\n- Validate at every trust boundary (network responses, `postMessage` payloads, storage reads) with a runtime schema validator. The validated type should flow from the schema, not from a parallel hand-written interface.\n\n## Linting and Dependency Tooling\n\n- Lint with [`typescript-eslint`](https:\u002F\u002Ftypescript-eslint.io\u002F) recommended sets plus `no-eval`, `no-implied-eval`, and `no-new-func`. Keep dependencies updated so new rules apply.\n- Pin versions with a lockfile, review dependency changes, and monitor advisories. Frontend dependency-review specifics overlap with the [Node.js Security Cheat Sheet](Nodejs_Security_Cheat_Sheet.md).\n- For third-party scripts loaded from a CDN, pin a Subresource Integrity hash with `crossorigin` handling per the [Third Party JavaScript Management Cheat Sheet](Third_Party_Javascript_Management_Cheat_Sheet.md).\n\n## References\n\n- [MDN: Window.postMessage](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002FWindow\u002FpostMessage)\n- [TypeScript Handbook: unknown](https:\u002F\u002Fwww.typescriptlang.org\u002Fdocs\u002Fhandbook\u002F2\u002Ffunctions.html#unknown)\n- [W3C Trusted Types](https:\u002F\u002Fw3c.github.io\u002Ftrusted-types\u002Fdist\u002Fspec\u002F)\n",{},"main","5d0a87185c0e172c3901e2a6e5916b6d544b8b94","skills\u002Fjavascript-and-typescript-security-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance","https:\u002F\u002Fgithub.com\u002FJunMystery","AI is the typist, I am the architect. Building efficient, secure, and user-centric products through disciplined AI prompt engineering.","2026-11-13 17:41:25",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add JunMystery\u002FAgent-Guidance --skill javascript-and-typescript-security-cheat-sheet",{"tool":35,"command":36},"bunx","bunx skills add JunMystery\u002FAgent-Guidance --skill javascript-and-typescript-security-cheat-sheet",{"tool":38,"command":39},"pnpm","pnpm dlx skills add JunMystery\u002FAgent-Guidance --skill javascript-and-typescript-security-cheat-sheet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fjavascript-and-typescript-security-cheat-sheet\u002FSKILL.md",true,[],[44,50,56,62,68,74],{"skillNo":45,"name":46,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":47,"categories":48,"keywords":49,"publishedAt":18},"01M79QR1E309VJ6CTQKB32AWWA","zero-trust-architecture-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-architecture-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M79QQV7GHYR02DYGN41S23WN","xss-filter-evasion-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxss-filter-evasion-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M79QQNSN7YB8XB61FFSCS3WH","xs-leaks-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxs-leaks-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M79QQHZZJKFDY9132G5A65C2","xpath-injection-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxpath-injection-prevention-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M79QQB9ZSD3DJG8658EHQXR1","xml-security-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-security-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M79QQ60WKV7PFMXWT9CW8PM6","xml-external-entity-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-external-entity-prevention-cheat-sheet\u002FSKILL.md",[],[]]