Skip to content
Back to search

domscribe

Domscribe is a pixel-to-code development tool that bridges the gap between running web applications and their source code.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/patchorbit/domscribe with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/patchorbit/domscribe'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/patchorbit--domscribe/badge.svg)](/listings/patchorbit--domscribe)

HTML

<a href="/listings/patchorbit--domscribe"><img src="/api/listings/patchorbit--domscribe/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npx domscribe init

The setup wizard walks you through two steps:

1. **Connect your coding agent** — select your agent (Claude Code, Copilot, Gemini, Kiro, or others) and the wizard installs the plugin automatically. 2. **Add to your app** — select your framework and bundler, the wizard installs the right package and shows you the config snippet to add.

That's it. Start your dev server and you're ready to go.

> Prefer to set things up manually, or need finer control? See the [manual setup](#manual-setup) instructions below.

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 39 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "domscribe",
  3. "owner": {
  4. "name": "Patch Orbit",
  5. "email": "kaushik@patchorbit.com"
  6. },
  7. "metadata": {
  8. "description": "Domscribe is a pixel-to-code development tool that maps running UI elements to their exact source locations, capturing runtime context (props, state, DOM) for handoff to coding agents via MCP."
  9. },
  10. "plugins": [
  11. {
  12. "name": "domscribe",
  13. "description": "Domscribe is a pixel-to-code development tool that maps running UI elements to their exact source locations, capturing runtime context (props, state, DOM) for handoff to coding agents via MCP.",
  14. "source": "./",
  15. "homepage": "https://github.com/patchorbit/domscribe",
  16. "repository": "https://github.com/patchorbit/domscribe",
  17. "license": "MIT",
  18. "keywords": [
  19. "domscribe",
  20. "pixel-to-code",
  21. "ui-to-code",
  22. "dom-annotation",
  23. "annotation",
  24. "source-mapping",
  25. "runtime-context",
  26. "element-inspector",
  27. "component-inspector",
  28. "mcp",
  29. "model-context-protocol",
  30. "developer-tools",
  31. "devtools",
  32. "react",
  33. "vue",
  34. "nextjs",
  35. "nuxt"
  36. ]
  37. }
  38. ]
  39. }
README.md · README · 461 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <p align="center">
  2. <img src="./docs/logo.png" alt="Domscribe" width="200" />
  3. </p>
  4. <h1 align="center">Domscribe</h1>
  5. <p align="center">
  6. <a href="https://www.npmjs.com/search?q=%40domscribe"><img src="https://img.shields.io/npm/v/%40domscribe/core?label=npm&color=cb3837" alt="npm version" /></a>
  7. <a href="https://github.com/patchorbit/domscribe/actions"><img src="https://img.shields.io/github/actions/workflow/status/patchorbit/domscribe/ci.yml?label=CI" alt="CI status" /></a>
  8. <a href="#"><img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/Narrator/1bedc40fc56874758abd3b7caf4d6748/raw/domscribe-coverage.json" alt="test coverage" /></a>
  9. <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license" /></a>
  10. <img src="https://img.shields.io/badge/TypeScript-5.x-3178c6?logo=typescript&logoColor=white" alt="TypeScript" />
  11. <img src="https://img.shields.io/badge/node-%3E%3D20-417e38?logo=node.js&logoColor=white" alt="Node.js >= 20" />
  12. <a href="https://github.com/patchorbit/domscribe/pulls"><img src="https://img.shields.io/badge/PRs-welcome-brightgreen" alt="PRs welcome" /></a>
  13. </p>
  14. <p align="center">
  15. <a href="https://www.npmjs.com/package/@domscribe/react"><img src="https://img.shields.io/badge/React-61DAFB?style=flat&logo=react&logoColor=black" alt="React" /></a>
  16. <a href="https://www.npmjs.com/package/@domscribe/vue"><img src="https://img.shields.io/badge/Vue-4FC08D?style=flat&logo=vuedotjs&logoColor=white" alt="Vue" /></a>
  17. <a href="https://www.npmjs.com/package/@domscribe/next"><img src="https://img.shields.io/badge/Next.js-000000?style=flat&logo=nextdotjs&logoColor=white" alt="Next.js" /></a>
  18. <a href="https://www.npmjs.com/package/@domscribe/nuxt"><img src="https://img.shields.io/badge/Nuxt-00DC82?style=flat&logo=nuxt&logoColor=white" alt="Nuxt" /></a>
  19. &nbsp;&nbsp;
  20. <a href="https://www.npmjs.com/package/@domscribe/transform"><img src="https://img.shields.io/badge/Vite-646CFF?style=flat&logo=vite&logoColor=white" alt="Vite" /></a>
  21. <a href="https://www.npmjs.com/package/@domscribe/transform"><img src="https://img.shields.io/badge/Webpack-8DD6F9?style=flat&logo=webpack&logoColor=black" alt="Webpack" /></a>
  22. <a href="https://www.npmjs.com/package/@domscribe/transform"><img src="https://img.shields.io/badge/Turbopack-000000?style=flat&logo=turborepo&logoColor=white" alt="Turbopack" /></a>
  23. </p>
  24. <p align="center">
  25. <img src="https://img.shields.io/badge/Claude_Code-d97706?style=flat&logo=anthropic&logoColor=white" alt="Claude Code" />
  26. <img src="https://img.shields.io/badge/GitHub_Copilot-000?style=flat&logo=githubcopilot&logoColor=white" alt="GitHub Copilot" />
  27. <a href="https://cursor.directory/plugins/domscribe"><img src="https://img.shields.io/badge/Cursor-000?style=flat&logo=cursor&logoColor=white" alt="Cursor" /></a>
  28. <a href="https://geminicli.com/extensions/?name=patchorbitdomscribe"><img src="https://img.shields.io/badge/Gemini-4285F4?style=flat&logo=googlegemini&logoColor=white" alt="Gemini" /></a>
  29. <img src="https://img.shields.io/badge/Kiro-a855f7?style=flat&logoColor=white" alt="Kiro" />
  30. </p>
  31. <p align="center">
  32. <a href="https://domscribe.com"><img src="./docs/demo.gif" alt="Domscribe demo — click an element, capture context, resolve to source" /></a>
  33. </p>
  34. ---
  35. **AI coding agents edit your source files blind — they can't see your running frontend, and your frontend can't tell them where to look.**
  36. Domscribe bridges both directions: click a DOM element to tell your agent what to change, or let your agent query any source location to see exactly what it looks like live in the browser. Build-time stable IDs, deep runtime context (props, state, DOM), framework-agnostic, any MCP-compatible agent. Zero production impact.
  37. ---
  38. ## Getting Started
  39. ```bash
  40. npx domscribe init
  41. ```
  42. The setup wizard walks you through two steps:
  43. 1. **Connect your coding agent** — select your agent (Claude Code, Copilot, Gemini, Kiro, or others) and the wizard installs the plugin automatically.
  44. 2. **Add to your app** — select your framework and bundler, the wizard installs the right package and shows you the config snippet to add.
  45. That's it. Start your dev server and you're ready to go.
  46. > Prefer to set things up manually, or need finer control? See the [manual setup](#manual-setup) instructions below.
  47. ---
  48. ## Features
  49. ### Code → UI: Let the agent see the browser
  50. Your agent calls `domscribe.query.bySource` with a file path and line number and gets back the live DOM snapshot, current props, component state, and rendered attributes — directly from the running browser. No human interaction needed.
  51. <p align="center">
  52. <img src="./docs/code-to-ui.png" alt="Code → UI: Let the agent see the browser" width="900" />
  53. </p>
  54. > [!TIP]
  55. > Agents don't spontaneously query runtime state — prompt them explicitly:
  56. > _"Fix the button color — use domscribe to check what CSS classes it has before changing anything."_
  57. > Your dev server must be running with the target page open in the browser.
  58. ### UI → Code: Point and tell
  59. Click any element in the browser overlay, describe the change in plain English, and submit. Domscribe captures the element's source location, runtime context, and your instruction as an annotation. The agent claims it, navigates to the exact file and line, and implements the change. The overlay shows the agent's response in real time via WebSocket.
  60. <p align="center">
  61. <img src="./docs/ui-to-code.png" alt="UI → Code: Point and tell" width="900" />
  62. </p>
  63. ### More
  64. - 🎯 **Build-time stable IDs** — deterministic `data-ds` attributes injected via AST, stable across HMR and fast refresh
  65. - 🧩 **Framework-agnostic** — React 18-19, Vue 3, Next.js 15-16, Nuxt 3+, with an [extensible adapter interface](./packages/domscribe-runtime/CUSTOM_ADAPTERS.md)
  66. - 📦 **Any bundler** — Vite 5-8, Webpack 5, Turbopack (Vite 8 support requires Domscribe 0.7.0 or later)
  67. - 🔍 **Deep runtime capture** — live props, state, and DOM snapshots via React fiber walking and Vue VNode inspection
  68. - 🛡️ **Zero production impact** — all instrumentation stripped in production builds, enforced in CI
  69. - 🔒 **PII redaction** — emails, tokens, and sensitive patterns automatically scrubbed before leaving the browser
  70. - 📁 **Annotations live in your repo** — stored as JSON files in `.domscribe/annotations/`, exposed via REST APIs that MCP wraps for agent access
  71. - 📡 **Real-time feedback** — WebSocket relay pushes agent responses to the browser overlay as they happen
  72. ---
  73. ## Manual Setup
  74. > [!NOTE]
  75. > `npx domscribe init` handles both steps below automatically. Use manual setup only if you need finer control.
  76. Domscribe has two sides: **app-side** (bundler + framework plugins) and **agent-side** (MCP for your coding agent). Both are needed for the full workflow.
  77. ### App-Side — Add to Your Bundler
  78. <details>
  79. <summary><strong>Next.js (15 + 16)</strong> — <code>npm install -D @domscribe/next</code></summary>
  80. ```ts
  81. // next.config.ts
  82. import type { NextConfig } from 'next';
  83. import { withDomscribe } from '@domscribe/next';
  84. const nextConfig: NextConfig = {};
  85. export default withDomscribe()(nextConfig);
  86. ```
  87. </details>
  88. <details>
  89. <summary><strong>Nuxt 3+</strong> — <code>npm install -D @domscribe/nuxt</code></summary>
  90. ```ts
  91. // nuxt.config.ts
  92. export default defineNuxtConfig({
  93. modules: ['@domscribe/nuxt'],
  94. });
  95. ```
  96. </details>
  97. <details>
  98. <summary><strong>React 18–19</strong> — <code>npm install -D @domscribe/react</code></summary>
  99. Vite plugin:
  100. ```ts
  101. // vite.config.ts
  102. import { defineConfig } from 'vite';
  103. import react from '@vitejs/plugin-react';
  104. import { domscribe } from '@domscribe/react/vite';
  105. export default defineConfig({
  106. plugins: [react(), domscribe()],
  107. });
  108. ```
  109. Webpack plugin:
  110. ```js
  111. // webpack.config.js
  112. const { DomscribeWebpackPlugin } = require('@domscribe/react/webpack');
  113. const isDevelopment = process.env.NODE_ENV !== 'production';
  114. module.exports = {
  115. module: {
  116. rules: [
  117. {
  118. test: /\.[jt]sx?$/,
  119. exclude: /node_modules/,
  120. enforce: 'pre',
  121. use: [
  122. {
  123. loader: '@domscribe/transform/webpack-loader',
  124. options: { enabled: isDevelopment },
  125. },
  126. ],
  127. },
  128. ],
  129. },
  130. plugins: [
  131. new DomscribeWebpackPlugin({
  132. enabled: isDevelopment,
  133. overlay: true,
  134. }),
  135. ],
  136. };
  137. ```
  138. </details>
  139. <details>
  140. <summary><strong>Vue 3+</strong> — <code>npm install -D @domscribe/vue</code></summary>
  141. Vite plugin:
  142. ```ts
  143. // vite.config.ts
  144. import { defineConfig } from 'vite';
  145. import vue from '@vitejs/plugin-vue';
  146. import { domscribe } from '@domscribe/vue/vite';
  147. export default defineConfig({
  148. plugins: [vue(), domscribe()],
  149. });
  150. ```
  151. Webpack plugin:
  152. ```js
  153. // webpack.config.js
  154. const { DomscribeWebpackPlugin } = require('@domscribe/vue/webpack');
  155. const isDevelopment = process.env.NODE_ENV !== 'production';
  156. module.exports = {
  157. module: {
  158. rules: [
  159. {
  160. test: /\.[jt]sx?$/,
  161. exclude: /node_modules/,
  162. enforce: 'pre',
  163. use: [
  164. {
  165. loader: '@domscribe/transform/webpack-loader',
  166. options: { enabled: isDevelopment },
  167. },
  168. ],
  169. },
  170. ],
  171. },
  172. plugins: [
  173. new DomscribeWebpackPlugin({
  174. enabled: isDevelopment,
  175. overlay: true,
  176. }),
  177. ],
  178. };
  179. ```
  180. </details>
  181. <details>
  182. <summary><strong>Any framework</strong> — <code>npm install -D @domscribe/transform</code> (DOM→source mapping only, no runtime capture)</summary>
  183. Vite plugin:
  184. ```ts
  185. // vite.config.ts
  186. import { defineConfig } from 'vite';
  187. import { domscribe } from '@domscribe/transform/plugins/vite';
  188. export default defineConfig({
  189. plugins: [domscribe()],
  190. });
  191. ```
  192. Webpack plugin:
  193. ```js
  194. // webpack.config.js
  195. const {
  196. DomscribeWebpackPlugin,
  197. } = require('@domscribe/transform/plugins/webpack');
  198. const isDevelopment = process.env.NODE_ENV !== 'production';
  199. module.exports = {
  200. module: {
  201. rules: [
  202. {
  203. test: /\.[jt]sx?$/,
  204. exclude: /node_modules/,
  205. enforce: 'pre',
  206. use: [
  207. {
  208. loader: '@domscribe/transform/webpack-loader',
  209. options: { enabled: isDevelopment },
  210. },
  211. ],
  212. },
  213. ],
  214. },
  215. plugins: [
  216. new DomscribeWebpackPlugin({
  217. enabled: isDevelopment,
  218. overlay: true,
  219. }),
  220. ],
  221. };
  222. ```
  223. </details>
  224. > **Working examples:** See [`packages/domscribe-test-fixtures/fixtures/`](./packages/domscribe-test-fixtures/fixtures/) for complete app setups across every supported framework and bundler combination.
  225. For plugin configuration options, see the [`@domscribe/transform` README](./packages/domscribe-transform/README.md).
  226. #### Monorepos
  227. If your frontend app is in a subdirectory (e.g. `apps/web`), pass `--app-root` during init:
  228. ```bash
  229. npx domscribe init --app-root apps/web
  230. ```
  231. Or run `npx domscribe init` and follow the prompts — the wizard asks if you're in a monorepo.
  232. This creates a `domscribe.config.json` at your repo root that tells all Domscribe tools where your app lives. CLI commands (`serve`, `stop`, `status`) and agent MCP connections automatically resolve the app root from this config — no extra flags needed.
  233. ### Agent-Side — Connect Your Coding Agent
  234. Domscribe exposes 12 tools and 4 prompts via MCP. Agent plugins bundle the MCP config and a skill file that teaches the agent how to use the tools effectively.
  235. #### Claude Code
  236. ```shell
  237. claude plugin marketplace add patchorbit/domscribe
  238. claude plugin install domscribe@domscribe
  239. ```
  240. #### GitHub Copilot
  241. ```bash
  242. copilot plugin install patchorbit/domscribe
  243. ```
  244. #### Gemini CLI
  245. ```bash
  246. gemini extensions install https://github.com/patchorbit/domscribe
  247. ```
  248. #### Amazon Kiro
  249. Open the Powers panel → **Add power from GitHub** → enter `https://github.com/patchorbit/domscribe/tree/main/domscribe-power`.
  250. #### Cursor
  251. <a href="https://cursor.directory/plugins/domscribe"><img src="https://img.shields.io/badge/Add_to_Cursor-000?style=for-the-badge&logo=cursor&logoColor=white" alt="Add to Cursor" /></a>
  252. #### Any agent (Skills and MCP)
  253. Install the Domscribe skills:
  254. ```sh
  255. npx skills add patchorbit/domscribe
  256. ```
  257. Then add this MCP config to your agent:
  258. ```json
  259. {
  260. "mcpServers": {
  261. "domscribe": {
  262. "type": "stdio",
  263. "command": "npx",
  264. "args": ["-y", "@domscribe/mcp"]
  265. }
  266. }
  267. }
  268. ```
  269. ---
  270. ## How It Works
  271. <p align="center">
  272. <img src="./docs/architecture.png" alt="Domscribe architecture diagram" />
  273. </p>
  274. **1. Inject.** The bundler plugin parses each source file, injects HMR-stable `data-ds` IDs via xxhash64, and records each mapping in `.domscribe/manifest.jsonl`.
  275. **2. Capture.** Framework adapters (React fiber walking, Vue VNode inspection) extract live props, state, and component metadata. The overlay UI lets you click any element and see its full context.
  276. **3. Relay.** A localhost Fastify daemon connects the browser and your agent via REST, WebSocket, and MCP stdio. A file lock prevents duplicate instances across dev server restarts.
  277. **4. Agent.** Your coding agent connects via MCP to **query by source** (see what any line looks like live) or **process annotations** (claim, implement, and respond to UI change requests).
  278. ---
  279. ## Comparison
  280. | Feature | Domscribe | [Stagewise](https://github.com/stagewise-io/stagewise) | [DevInspector MCP](https://github.com/mcpc-tech/dev-inspector-mcp) | [React Grab](https://github.com/aidenybai/react-grab) | [Frontman](https://github.com/frontman-ai/frontman) |
  281. | --------------------- | -------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------ | ----------------------------------------------------- | --------------------------------------------------- |
  282. | Build-time stable IDs | ✅ `data-ds` via AST | ❌ Runtime (CDP) | ❌ No stable IDs | ❌ `_debugSource` | ❌ Runtime framework introspection |
  283. | DOM→source manifest | ✅ JSONL, append-only | ❌ | ❌ | ❌ | ❌ |
  284. | Code→live DOM query | ✅ Agent queries source, gets live runtime | ❌ | ❌ | ❌ | ❌ |
  285. | Runtime props/state | ✅ Fiber + VNode walking | ⚠️ Shallow | ⚠️ DOM-level + JS eval | ❌ HTML + component names only | ⚠️ Props only (framework APIs) |
  286. | Multi-framework | ✅ React · Vue · Next.js · Nuxt · extensible | ⚠️ React only | ✅ React + Vue + Svelte + Solid + Preact | ❌ React only | ⚠️ Next.js + Astro + Vite |
  287. | Multi-bundler | ✅ Vite + Webpack + Turbopack | ❌ N/A (Electron browser) | ✅ Vite + Webpack + Turbopack | ❌ N/A | ❌ Dev server middleware |
  288. | MCP tools | ✅ 12 tools + 4 prompts | ❌ Proprietary protocol (Karton) | ✅ 9 tools | ⚠️ Lightweight add-on | ❌ Internal MCP only |
  289. | Agent-agnostic | ✅ Any MCP client | ❌ Bundled Electron agent | ✅ | ✅ | ❌ Bundled Elixir agent |
  290. | In-app element picker | ✅ Lit shadow DOM | ✅ Built-in browser selector | ✅ Inspector bar | ✅ Hover-to-capture | ✅ Chat interface |
  291. | Source mapping | ✅ Deterministic (AST IDs) | ⚠️ AI-inferred | ⚠️ AST-injected (not stable) | ⚠️ `_debugSource` (workaround needed) | ⚠️ Runtime framework introspection |
  292. | License | ✅ MIT | ⚠️ AGPL | ✅ MIT | ✅ MIT | ⚠️ Apache + AGPL |
  293. No single competitor combines build-time stable IDs, deep runtime capture, bidirectional source↔DOM querying, and an MCP tool surface in a framework-agnostic way.
  294. ---
  295. ## MCP Tools
  296. The agent-facing surface — tools, prompts, wire schemas, and error envelope — is listed below as a human-readable index.
  297. | Tool | Description |
  298. | ----------------------------------- | --------------------------------------------------------------------------------------- |
  299. | `domscribe.query.bySource` | Query a source file + line and get live runtime context (props, state, DOM snapshot) |
  300. | `domscribe.manifest.query` | Find manifest entries by file path, component name, or element ID |
  301. | `domscribe.manifest.stats` | Manifest coverage statistics (entry count, file count, component count, cache hit rate) |
  302. | `domscribe.resolve` | Resolve a `data-ds` element ID to its source location (file, line, col, component) |
  303. | `domscribe.resolve.batch` | Resolve multiple element IDs in one call |
  304. | `domscribe.annotation.process` | Atomically claim the next queued annotation (prevents concurrent agent conflicts) |
  305. | `domscribe.annotation.respond` | Attach agent response and transition to `PROCESSED` |
  306. | `domscribe.annotation.updateStatus` | Manually transition annotation status |
  307. | `domscribe.annotation.get` | Retrieve annotation by ID |
  308. | `domscribe.annotation.list` | List annotations with status/filter options |
  309. | `domscribe.annotation.search` | Full-text search across annotation content |
  310. | `domscribe.verify.baseline` | Capture a pre-edit style/geometry snapshot of a rendered element |
  311. | `domscribe.verify.afterEdit` | Compare the element against the baseline — deterministic verdict + per-property deltas |
  312. | `domscribe.status` | Relay daemon health, manifest stats, queue counts |
  313. See the [`@domscribe/mcp` README](./packages/domscribe-mcp/README.md) for detailed tool schemas, response formats, and prompt definitions.
  314. ---
  315. ## Packages
  316. | Package | Description |
  317. | -------------------------- | ----------------------------------------------------------------------------------- |
  318. | `@domscribe/core` | Zod schemas, RFC 7807 error system, ID generation, PII redaction, constants |
  319. | `@domscribe/manifest` | Append-only JSONL manifest, IDStabilizer (xxhash64), BatchWriter, ManifestCompactor |
  320. | `@domscribe/relay` | Fastify HTTP/WS server, MCP stdio adapter, annotation lifecycle |
  321. | `@domscribe/transform` | Parser-agnostic AST injection (Acorn, Babel, VueSFC), bundler plugins |
  322. | `@domscribe/runtime` | Browser-side ElementTracker, ContextCapturer, BridgeDispatch |
  323. | `@domscribe/overlay` | Lit web components (shadow DOM), element picker, annotation UI |
  324. | `@domscribe/react` | React fiber walking, props/state extraction, Vite + Webpack plugins |
  325. | `@domscribe/vue` | Vue 3 VNode resolution, Composition + Options API support, Vite + Webpack plugins |
  326. | `@domscribe/next` | `withDomscribe()` config wrapper for Next.js 15 + 16 |
  327. | `@domscribe/nuxt` | Nuxt 3+ module with auto-relay and runtime plugin |
  328. | `domscribe` | CLI binary (`domscribe serve`, `status`, `stop`, `init`, `mcp`) |
  329. | `@domscribe/mcp` | Standalone MCP server binary (`domscribe-mcp`) |
  330. | `@domscribe/test-fixtures` | Black-box integration + e2e suite (not published) |
  331. ---
  332. ## Contributing
  333. ```bash
  334. pnpm install
  335. nx run-many -t build test lint typecheck
  336. ```
  337. Conventions are in `.claude/rules/`. PRs welcome.
  338. For an isolated browser replay check through the Docker Node SDK, see the
  339. [Docker Cloud replay smoke test](./docs/docker-cloud-replay.md).
  340. Portable issue-packet CLI commands are being developed on main; see the [source-only handoff guide](./docs/portable-issue-handoff.md) for availability, privacy options and fresh-checkout inspection.
  341. ---
  342. ## License
  343. [MIT](./LICENSE)
packages/domscribe-core/src/privacy/redaction.spec.ts · Bundled script · 1,619 lines · 1 finding marked
  1. /**
  2. * Tests for PII redaction utilities
  3. *
  4. * Tests privacy protection through pattern-based and field-based redaction.
  5. * Follows Arrange-Act-Assert methodology.
  6. */
  7. import { describe, it, expect } from 'vitest';
  8. import {
  9. redactText,
  10. redactObject,
  11. redactPII,
  12. redactSensitiveFields,
  13. } from './redaction.js';
  14. describe('redactText', () => {
  15. describe('Email Redaction', () => {
  16. it('should redact email addresses', () => {
  17. // Arrange
  18. const text = 'Contact me at user@example.com for more info.';
  19. // Act
  20. const result = redactText(text, { patterns: ['email'] });
  21. // Assert
  22. expect(result).toBe('Contact me at [REDACTED] for more info.');
  23. });
  24. it('should redact multiple email addresses', () => {
  25. // Arrange
  26. const text = 'Email alice@example.com or bob@test.org';
  27. // Act
  28. const result = redactText(text, { patterns: ['email'] });
  29. // Assert
  30. expect(result).toBe('Email [REDACTED] or [REDACTED]');
  31. });
  32. it('should redact emails with different TLDs', () => {
  33. // Arrange
  34. const text = 'user@example.co.uk and admin@site.net';
  35. // Act
  36. const result = redactText(text, { patterns: ['email'] });
  37. // Assert
  38. expect(result).toBe('[REDACTED] and [REDACTED]');
  39. });
  40. it('should redact emails with special characters', () => {
  41. // Arrange
  42. const text = 'Email: user.name+tag@example-domain.com';
  43. // Act
  44. const result = redactText(text, { patterns: ['email'] });
  45. // Assert
  46. expect(result).toBe('Email: [REDACTED]');
  47. });
  48. it('should preserve partial email when preservePartial is true', () => {
  49. // Arrange
  50. const text = 'Contact: user@example.com';
  51. // Act
  52. const result = redactText(text, {
  53. patterns: ['email'],
  54. preservePartial: true,
  55. });
  56. // Assert
  57. expect(result).toBe('Contact: [REDACTED].com');
  58. });
  59. it('should not match very short emails', () => {
  60. // Arrange
  61. const text = 'a@b.c';
  62. // Act
  63. const result = redactText(text, {
  64. patterns: ['email'],
  65. preservePartial: true,
  66. });
  67. // Assert
  68. // Note: Email pattern requires minimum 2-char TLD, so very short emails don't match
  69. expect(result).toBe('a@b.c');
  70. });
  71. });
  72. describe('Phone Number Redaction', () => {
  73. it('should redact US phone numbers with dashes', () => {
  74. // Arrange
  75. const text = 'Call me at 123-456-7890';
  76. // Act
  77. const result = redactText(text, { patterns: ['phone'] });
  78. // Assert
  79. expect(result).toBe('Call me at [REDACTED]');
  80. });
  81. it('should redact phone numbers with dots', () => {
  82. // Arrange
  83. const text = 'Phone: 123.456.7890';
  84. // Act
  85. const result = redactText(text, { patterns: ['phone'] });
  86. // Assert
  87. expect(result).toBe('Phone: [REDACTED]');
  88. });
  89. it('should redact phone numbers with spaces', () => {
  90. // Arrange
  91. const text = 'Number: 123 456 7890';
  92. // Act
  93. const result = redactText(text, { patterns: ['phone'] });
  94. // Assert
  95. expect(result).toBe('Number: [REDACTED]');
  96. });
  97. it('should redact phone numbers with parentheses', () => {
  98. // Arrange
  99. const text = 'Call (123) 456-7890';
  100. // Act
  101. const result = redactText(text, { patterns: ['phone'] });
  102. // Assert
  103. expect(result).toBe('Call [REDACTED]');
  104. });
  105. it('should redact international phone numbers', () => {
  106. // Arrange
  107. const text = 'International: +1-123-456-7890';
  108. // Act
  109. const result = redactText(text, { patterns: ['phone'] });
  110. // Assert
  111. expect(result).toBe('International: [REDACTED]');
  112. });
  113. it('should redact multiple phone numbers', () => {
  114. // Arrange
  115. const text = 'Office: 123-456-7890, Mobile: 987-654-3210';
  116. // Act
  117. const result = redactText(text, { patterns: ['phone'] });
  118. // Assert
  119. expect(result).toBe('Office: [REDACTED], Mobile: [REDACTED]');
  120. });
  121. it('should preserve partial phone when preservePartial is true', () => {
  122. // Arrange
  123. const text = 'Call 123-456-7890';
  124. // Act
  125. const result = redactText(text, {
  126. patterns: ['phone'],
  127. preservePartial: true,
  128. });
  129. // Assert
  130. expect(result).toBe('Call [REDACTED]7890');
  131. });
  132. });
  133. describe('Credit Card Redaction', () => {
  134. it('should redact credit card numbers with dashes', () => {
  135. // Arrange
  136. const text = 'Card: 1234-5678-9012-3456';
  137. // Act
  138. const result = redactText(text, { patterns: ['creditCard'] });
  139. // Assert
  140. expect(result).toBe('Card: [REDACTED]');
  141. });
  142. it('should redact credit card numbers with spaces', () => {
  143. // Arrange
  144. const text = 'Card: 1234 5678 9012 3456';
  145. // Act
  146. const result = redactText(text, { patterns: ['creditCard'] });
  147. // Assert
  148. expect(result).toBe('Card: [REDACTED]');
  149. });
  150. it('should redact credit card numbers without separators', () => {
  151. // Arrange
  152. const text = 'Card: 1234567890123456';
  153. // Act
  154. const result = redactText(text, { patterns: ['creditCard'] });
  155. // Assert
  156. expect(result).toBe('Card: [REDACTED]');
  157. });
  158. it('should preserve partial credit card when preservePartial is true', () => {
  159. // Arrange
  160. const text = 'Card: 1234-5678-9012-3456';
  161. // Act
  162. const result = redactText(text, {
  163. patterns: ['creditCard'],
  164. preservePartial: true,
  165. });
  166. // Assert
  167. expect(result).toBe('Card: [REDACTED]3456');
  168. });
  169. });
  170. describe('SSN Redaction', () => {
  171. it('should redact social security numbers', () => {
  172. // Arrange
  173. const text = 'SSN: 123-45-6789';
  174. // Act
  175. const result = redactText(text, { patterns: ['ssn'] });
  176. // Assert
  177. expect(result).toBe('SSN: [REDACTED]');
  178. });
  179. it('should redact multiple SSNs', () => {
  180. // Arrange
  181. const text = 'SSNs: 123-45-6789 and 987-65-4321';
  182. // Act
  183. const result = redactText(text, { patterns: ['ssn'] });
  184. // Assert
  185. expect(result).toBe('SSNs: [REDACTED] and [REDACTED]');
  186. });
  187. it('should preserve partial SSN when preservePartial is true', () => {
  188. // Arrange
  189. const text = 'SSN: 123-45-6789';
  190. // Act
  191. const result = redactText(text, {
  192. patterns: ['ssn'],
  193. preservePartial: true,
  194. });
  195. // Assert
  196. expect(result).toBe('SSN: [REDACTED]6789');
  197. });
  198. });
  199. describe('IP Address Redaction', () => {
  200. it('should redact IPv4 addresses', () => {
  201. // Arrange
  202. const text = 'Server IP: 192.168.1.100';
  203. // Act
  204. const result = redactText(text, { patterns: ['ip'] });
  205. // Assert
  206. expect(result).toBe('Server IP: [REDACTED]');
  207. });
  208. it('should redact multiple IP addresses', () => {
  209. // Arrange
  210. const text = 'From 192.168.1.1 to 10.0.0.1';
  211. // Act
  212. const result = redactText(text, { patterns: ['ip'] });
  213. // Assert
  214. expect(result).toBe('From [REDACTED] to [REDACTED]');
  215. });
  216. it('should redact localhost IP', () => {
  217. // Arrange
  218. const text = 'Localhost: 127.0.0.1';
  219. // Act
  220. const result = redactText(text, { patterns: ['ip'] });
  221. // Assert
  222. expect(result).toBe('Localhost: [REDACTED]');
  223. });
  224. });
  225. describe('API Key Redaction', () => {
  226. it('should redact API keys', () => {
  227. // Arrange
  228. const text = 'API Key: sk_live_1234567890abcdefghijklmnopqrstuvwxyz';
  229. // Act
  230. const result = redactText(text, { patterns: ['apiKey'] });
  231. // Assert
  232. expect(result).toBe('API Key: [REDACTED]');
  233. });
  234. it('should redact multiple API keys', () => {
  235. // Arrange
  236. const text =
  237. 'Keys: abcdef1234567890abcdef1234567890 and xyz1234567890xyz1234567890xyzabc';
  238. // Act
  239. const result = redactText(text, { patterns: ['apiKey'] });
  240. // Assert
  241. expect(result).toBe('Keys: [REDACTED] and [REDACTED]');
  242. });
  243. it('should preserve partial API key when preservePartial is true', () => {
  244. // Arrange
  245. const text = 'Key: sk_live_1234567890abcdefghijklmnopqrstuvwxyz';
  246. // Act
  247. const result = redactText(text, {
  248. patterns: ['apiKey'],
  249. preservePartial: true,
  250. });
  251. // Assert
  252. expect(result).toContain('[REDACTED]');
  253. expect(result).toContain('wxyz');
  254. });
  255. });
  256. describe('JWT Redaction', () => {
  257. it('should redact JWT tokens', () => {
  258. // Arrange
  259. const text =
  260. 'Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
    • Dismissed after review: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
    • Line 340 on GitHub
  261. // Act
  262. const result = redactText(text, { patterns: ['jwt'] });
  263. // Assert
  264. expect(result).toBe('Token: [REDACTED]');
  265. });
  266. it('should redact multiple JWT tokens', () => {
  267. // Arrange
  268. const text =
  269. 'Tokens: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.abc123 and eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIifQ.xyz456';
  270. // Act
  271. const result = redactText(text, { patterns: ['jwt'] });
  272. // Assert
  273. expect(result).toBe('Tokens: [REDACTED] and [REDACTED]');
  274. });
  275. });
  276. describe('Multiple Patterns', () => {
  277. it('should redact multiple PII types in same text', () => {
  278. // Arrange
  279. const text =
  280. 'Email user@example.com, Phone 123-456-7890, Card 1234-5678-9012-3456';
  281. // Act
  282. const result = redactText(text, {
  283. patterns: ['email', 'phone', 'creditCard'],
  284. });
  285. // Assert
  286. expect(result).toBe(
  287. 'Email [REDACTED], Phone [REDACTED], Card [REDACTED]',
  288. );
  289. });
  290. it('should apply all patterns by default', () => {
  291. // Arrange
  292. const text =
  293. 'Email: user@example.com, IP: 192.168.1.1, Phone: 123-456-7890';
  294. // Act
  295. const result = redactText(text);
  296. // Assert
  297. expect(result).toBe(
  298. 'Email: [REDACTED], IP: [REDACTED], Phone: [REDACTED]',
  299. );
  300. });
  301. it('should handle text with no PII', () => {
  302. // Arrange
  303. const text = 'Hello world, this is a test message.';
  304. // Act
  305. const result = redactText(text);
  306. // Assert
  307. expect(result).toBe('Hello world, this is a test message.');
  308. });
  309. });
  310. describe('Custom Patterns', () => {
  311. it('should apply custom regex patterns', () => {
  312. // Arrange
  313. const text = 'Employee ID: EMP12345';
  314. const customPattern = /EMP\d{5}/g;
  315. // Act
  316. const result = redactText(text, {
  317. patterns: [],
  318. customPatterns: [customPattern],
  319. });
  320. // Assert
  321. expect(result).toBe('Employee ID: [REDACTED]');
  322. });
  323. it('should apply multiple custom patterns', () => {
  324. // Arrange
  325. const text = 'Order #ORD123 and Invoice #INV456';
  326. const orderPattern = /ORD\d{3}/g;
  327. const invoicePattern = /INV\d{3}/g;
  328. // Act
  329. const result = redactText(text, {
  330. patterns: [],
  331. customPatterns: [orderPattern, invoicePattern],
  332. });
  333. // Assert
  334. expect(result).toBe('Order #[REDACTED] and Invoice #[REDACTED]');
  335. });
  336. it('should combine built-in and custom patterns', () => {
  337. // Arrange
  338. const text = 'Email user@example.com, Employee EMP12345';
  339. const employeePattern = /EMP\d{5}/g;
  340. // Act
  341. const result = redactText(text, {
  342. patterns: ['email'],
  343. customPatterns: [employeePattern],
  344. });
  345. // Assert
  346. expect(result).toBe('Email [REDACTED], Employee [REDACTED]');
  347. });
  348. });
  349. describe('Custom Replacement', () => {
  350. it('should use custom replacement string', () => {
  351. // Arrange
  352. const text = 'Email: user@example.com';
  353. // Act
  354. const result = redactText(text, {
  355. patterns: ['email'],
  356. replacement: '***',
  357. });
  358. // Assert
  359. expect(result).toBe('Email: ***');
  360. });
  361. it('should use custom replacement for multiple redactions', () => {
  362. // Arrange
  363. const text = 'Email alice@test.com and bob@test.org';
  364. // Act
  365. const result = redactText(text, {
  366. patterns: ['email'],
  367. replacement: '[HIDDEN]',
  368. });
  369. // Assert
  370. expect(result).toBe('Email [HIDDEN] and [HIDDEN]');
  371. });
  372. it('should apply custom replacement with preservePartial', () => {
  373. // Arrange
  374. const text = 'Phone: 123-456-7890';
  375. // Act
  376. const result = redactText(text, {
  377. patterns: ['phone'],
  378. replacement: 'XXX',
  379. preservePartial: true,
  380. });
  381. // Assert
  382. expect(result).toBe('Phone: XXX7890');
  383. });
  384. });
  385. describe('Edge Cases', () => {
  386. it('should handle empty string', () => {
  387. // Arrange
  388. const text = '';
  389. // Act
  390. const result = redactText(text);
  391. // Assert
  392. expect(result).toBe('');
  393. });
  394. it('should handle string with only whitespace', () => {
  395. // Arrange
  396. const text = ' \n\t ';
  397. // Act
  398. const result = redactText(text);
  399. // Assert
  400. expect(result).toBe(' \n\t ');
  401. });
  402. it('should handle text with special characters', () => {
  403. // Arrange
  404. const text = 'Contact: user@example.com! (or 123-456-7890?)';
  405. // Act
  406. const result = redactText(text, {
  407. patterns: ['email', 'phone'],
  408. });
  409. // Assert
  410. expect(result).toBe('Contact: [REDACTED]! (or [REDACTED]?)');
  411. });
  412. it('should handle text with unicode characters', () => {
  413. // Arrange
  414. const text = 'Correo: usuario@ejemplo.com 📧';
  415. // Act
  416. const result = redactText(text, { patterns: ['email'] });
  417. // Assert
  418. expect(result).toBe('Correo: [REDACTED] 📧');
  419. });
  420. it('should handle empty patterns array', () => {
  421. // Arrange
  422. const text = 'Email: user@example.com';
  423. // Act
  424. const result = redactText(text, { patterns: [] });
  425. // Assert
  426. expect(result).toBe('Email: user@example.com');
  427. });
  428. });
  429. describe('PreservePartial Edge Cases', () => {
  430. it('should not preserve partial for 4-character matches', () => {
  431. // Arrange
  432. const text = 'Code: 1234';
  433. // Act
  434. const result = redactText(text, {
  435. customPatterns: [/\d{4}/g],
  436. preservePartial: true,
  437. });
  438. // Assert
  439. expect(result).toBe('Code: [REDACTED]');
  440. });
  441. it('should not preserve partial for custom patterns', () => {
  442. // Arrange
  443. const text = 'Code: 12345';
  444. // Act
  445. const result = redactText(text, {
  446. customPatterns: [/\d{5}/g],
  447. preservePartial: true,
  448. });
  449. // Assert
  450. // Note: preservePartial only applies to built-in patterns, not custom patterns
  451. expect(result).toBe('Code: [REDACTED]');
  452. });
  453. });
  454. });
  455. describe('redactObject', () => {
  456. describe('Primitives', () => {
  457. it('should handle null', () => {
  458. // Arrange
  459. const value = null;
  460. // Act
  461. const result = redactObject(value);
  462. // Assert
  463. expect(result).toBeNull();
  464. });
  465. it('should handle undefined', () => {
  466. // Arrange
  467. const value = undefined;
  468. // Act
  469. const result = redactObject(value);
  470. // Assert
  471. expect(result).toBeUndefined();
  472. });
  473. it('should handle numbers', () => {
  474. // Arrange
  475. const value = 42;
  476. // Act
  477. const result = redactObject(value);
  478. // Assert
  479. expect(result).toBe(42);
  480. });
  481. it('should handle booleans', () => {
  482. // Arrange
  483. const trueValue = true;
  484. const falseValue = false;
  485. // Act
  486. const trueResult = redactObject(trueValue);
  487. const falseResult = redactObject(falseValue);
  488. // Assert
  489. expect(trueResult).toBe(true);
  490. expect(falseResult).toBe(false);
  491. });
  492. });
  493. describe('Strings', () => {
  494. it('should redact PII in strings', () => {
  495. // Arrange
  496. const value = 'Contact me at user@example.com';
  497. // Act
  498. const result = redactObject(value, { patterns: ['email'] });
  499. // Assert
  500. expect(result).toBe('Contact me at [REDACTED]');
  501. });
  502. it('should handle empty strings', () => {
  503. // Arrange
  504. const value = '';
  505. // Act
  506. const result = redactObject(value);
  507. // Assert
  508. expect(result).toBe('');
  509. });
  510. });
  511. describe('Arrays', () => {
  512. it('should redact PII in array elements', () => {
  513. // Arrange
  514. const value = [
  515. 'Email: user@example.com',
  516. 'Phone: 123-456-7890',
  517. 'No PII here',
  518. ];
  519. // Act
  520. const result = redactObject(value, {
  521. patterns: ['email', 'phone'],
  522. });
  523. // Assert
  524. expect(result).toEqual([
  525. 'Email: [REDACTED]',
  526. 'Phone: [REDACTED]',
  527. 'No PII here',
  528. ]);
  529. });
  530. it('should handle empty arrays', () => {
  531. // Arrange
  532. const value: unknown[] = [];
  533. // Act
  534. const result = redactObject(value);
  535. // Assert
  536. expect(result).toEqual([]);
  537. });
  538. it('should handle nested arrays', () => {
  539. // Arrange
  540. const value = [['Email: user@example.com'], ['Phone: 123-456-7890']];
  541. // Act
  542. const result = redactObject(value, {
  543. patterns: ['email', 'phone'],
  544. });
  545. // Assert
  546. expect(result).toEqual([['Email: [REDACTED]'], ['Phone: [REDACTED]']]);
  547. });
  548. it('should handle arrays with mixed types', () => {
  549. // Arrange
  550. const value = [
  551. 'user@example.com',
  552. 42,
  553. true,
  554. null,
  555. { email: 'admin@test.com' },
  556. ];
  557. // Act
  558. const result = redactObject(value, { patterns: ['email'] });
  559. // Assert
  560. expect(result).toEqual([
  561. '[REDACTED]',
  562. 42,
  563. true,
  564. null,
  565. { email: '[REDACTED]' },
  566. ]);
  567. });
  568. });
  569. describe('Objects', () => {
  570. it('should redact PII in object values', () => {
  571. // Arrange
  572. const value = {
  573. email: 'user@example.com',
  574. phone: '123-456-7890',
  575. name: 'Alice',
  576. };
  577. // Act
  578. const result = redactObject(value, {
  579. patterns: ['email', 'phone'],
  580. });
  581. // Assert
  582. expect(result).toEqual({
  583. email: '[REDACTED]',
  584. phone: '[REDACTED]',
  585. name: 'Alice',
  586. });
  587. });
  588. it('should handle empty objects', () => {
  589. // Arrange
  590. const value = {};
  591. // Act
  592. const result = redactObject(value);
  593. // Assert
  594. expect(result).toEqual({});
  595. });
  596. it('should handle nested objects', () => {
  597. // Arrange
  598. const value = {
  599. user: {
  600. email: 'user@example.com',
  601. contact: {
  602. phone: '123-456-7890',
  603. },
  604. },
  605. };
  606. // Act
  607. const result = redactObject(value, {
  608. patterns: ['email', 'phone'],
  609. });
  610. // Assert
  611. expect(result).toEqual({
  612. user: {
  613. email: '[REDACTED]',
  614. contact: {
  615. phone: '[REDACTED]',
  616. },
  617. },
  618. });
  619. });
  620. it('should only redact own properties', () => {
  621. // Arrange
  622. const proto = { inherited: 'user@example.com' };
  623. const value = Object.create(proto);
  624. value.own = 'admin@test.com';
  625. // Act
  626. const result = redactObject(value, { patterns: ['email'] });
  627. // Assert
  628. expect(result).toEqual({
  629. own: '[REDACTED]',
  630. });
  631. });
  632. });
  633. describe('Complex Structures', () => {
  634. it('should redact deeply nested structures', () => {
  635. // Arrange
  636. const value = {
  637. level1: {
  638. level2: {
  639. level3: {
  640. email: 'user@example.com',
  641. data: ['phone: 123-456-7890'],
  642. },
  643. },
  644. },
  645. };
  646. // Act
  647. const result = redactObject(value, {
  648. patterns: ['email', 'phone'],
  649. });
  650. // Assert
  651. expect(result).toEqual({
  652. level1: {
  653. level2: {
  654. level3: {
  655. email: '[REDACTED]',
  656. data: ['phone: [REDACTED]'],
  657. },
  658. },
  659. },
  660. });
  661. });
  662. it('should handle objects with arrays of objects', () => {
  663. // Arrange
  664. const value = {
  665. users: [
  666. { email: 'alice@test.com', name: 'Alice' },
  667. { email: 'bob@test.com', name: 'Bob' },
  668. ],
  669. };
  670. // Act
  671. const result = redactObject(value, { patterns: ['email'] });
  672. // Assert
  673. expect(result).toEqual({
  674. users: [
  675. { email: '[REDACTED]', name: 'Alice' },
  676. { email: '[REDACTED]', name: 'Bob' },
  677. ],
  678. });
  679. });
  680. it('should handle arrays of nested objects', () => {
  681. // Arrange
  682. const value = [
  683. {
  684. profile: {
  685. email: 'user1@test.com',
  686. },
  687. },
  688. {
  689. profile: {
  690. email: 'user2@test.com',
  691. },
  692. },
  693. ];
  694. // Act
  695. const result = redactObject(value, { patterns: ['email'] });
  696. // Assert
  697. expect(result).toEqual([
  698. {
  699. profile: {
  700. email: '[REDACTED]',
  701. },
  702. },
  703. {
  704. profile: {
  705. email: '[REDACTED]',
  706. },
  707. },
  708. ]);
  709. });
  710. });
  711. describe('Non-Plain Objects', () => {
  712. it('should serialize Date objects as empty objects', () => {
  713. // Arrange
  714. const value = new Date('2025-01-01');
  715. // Act
  716. const result = redactObject(value);
  717. // Assert
  718. // Note: Date objects have no enumerable properties, so they serialize to {}
  719. expect(result).toEqual({});
  720. });
  721. it('should serialize RegExp objects as empty objects', () => {
  722. // Arrange
  723. const value = /test/gi;
  724. // Act
  725. const result = redactObject(value);
  726. // Assert
  727. // Note: RegExp objects have no enumerable properties, so they serialize to {}
  728. expect(result).toEqual({});
  729. });
  730. it('should serialize Map objects as empty objects', () => {
  731. // Arrange
  732. const value = new Map([['key', 'value']]);
  733. // Act
  734. const result = redactObject(value);
  735. // Assert
  736. // Note: Map objects have no enumerable properties, so they serialize to {}
  737. expect(result).toEqual({});
  738. });
  739. it('should serialize Set objects as empty objects', () => {
  740. // Arrange
  741. const value = new Set([1, 2, 3]);
  742. // Act
  743. const result = redactObject(value);
  744. // Assert
  745. // Note: Set objects have no enumerable properties, so they serialize to {}
  746. expect(result).toEqual({});
  747. });
  748. });
  749. describe('Options Propagation', () => {
  750. it('should apply custom replacement throughout object', () => {
  751. // Arrange
  752. const value = {
  753. a: 'user@example.com',
  754. b: ['admin@test.com'],
  755. c: { d: 'info@site.org' },
  756. };
  757. // Act
  758. const result = redactObject(value, {
  759. patterns: ['email'],
  760. replacement: '***',
  761. });
  762. // Assert
  763. expect(result).toEqual({
  764. a: '***',
  765. b: ['***'],
  766. c: { d: '***' },
  767. });
  768. });
  769. it('should apply preservePartial throughout object', () => {
  770. // Arrange
  771. const value = {
  772. email1: 'user@example.com',
  773. nested: {
  774. email2: 'admin@test.com',
  775. },
  776. };
  777. // Act
  778. const result = redactObject(value, {
  779. patterns: ['email'],
  780. preservePartial: true,
  781. });
  782. // Assert
  783. expect(result).toEqual({
  784. email1: '[REDACTED].com',
  785. nested: {
  786. email2: '[REDACTED].com',
  787. },
  788. });
  789. });
  790. });
  791. });
  792. describe('redactPII', () => {
  793. it('should redact common PII types', () => {
  794. // Arrange
  795. const value = {
  796. email: 'user@example.com',
  797. phone: '123-456-7890',
  798. creditCard: '1234-5678-9012-3456',
  799. ssn: '123-45-6789',
  800. ip: '192.168.1.1',
  801. apiKey: 'sk_live_1234567890abcdefghijklmnopqrstuvwxyz',
  802. jwt: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.abc123',
  803. };
  804. // Act
  805. const result = redactPII(value);
  806. // Assert
  807. expect(result).toEqual({
  808. email: '[REDACTED]',
  809. phone: '[REDACTED]',
  810. creditCard: '[REDACTED]',
  811. ssn: '[REDACTED]',
  812. ip: '[REDACTED]',
  813. apiKey: '[REDACTED]',
  814. jwt: '[REDACTED]',
  815. });
  816. });
  817. it('should handle nested structures', () => {
  818. // Arrange
  819. const value = {
  820. user: {
  821. email: 'user@example.com',
  822. contact: {
  823. phone: '123-456-7890',
  824. },
  825. },
  826. };
  827. // Act
  828. const result = redactPII(value);
  829. // Assert
  830. expect(result).toEqual({
  831. user: {
  832. email: '[REDACTED]',
  833. contact: {
  834. phone: '[REDACTED]',
  835. },
  836. },
  837. });
  838. });
  839. it('should handle arrays', () => {
  840. // Arrange
  841. const value = ['user@example.com', '123-456-7890', 'Safe text'];
  842. // Act
  843. const result = redactPII(value);
  844. // Assert
  845. expect(result).toEqual(['[REDACTED]', '[REDACTED]', 'Safe text']);
  846. });
  847. it('should handle null and undefined', () => {
  848. // Arrange
  849. const nullValue = null;
  850. const undefinedValue = undefined;
  851. // Act
  852. const nullResult = redactPII(nullValue);
  853. const undefinedResult = redactPII(undefinedValue);
  854. // Assert
  855. expect(nullResult).toBeNull();
  856. expect(undefinedResult).toBeUndefined();
  857. });
  858. });
  859. describe('redactSensitiveFields', () => {
  860. describe('Built-in Sensitive Fields', () => {
  861. it('should redact password field', () => {
  862. // Arrange
  863. const value = {
  864. username: 'alice',
  865. password: 'secret123',
  866. email: 'alice@example.com',
  867. };
  868. // Act
  869. const result = redactSensitiveFields(value);
  870. // Assert
  871. expect(result).toEqual({
  872. username: 'alice',
  873. password: '[REDACTED]',
  874. email: 'alice@example.com',
  875. });
  876. });
  877. it('should redact token field', () => {
  878. // Arrange
  879. const value = {
  880. token: 'abc123xyz',
  881. data: 'public',
  882. };
  883. // Act
  884. const result = redactSensitiveFields(value);
  885. // Assert
  886. expect(result).toEqual({
  887. token: '[REDACTED]',
  888. data: 'public',
  889. });
  890. });
  891. it('should redact apikey field', () => {
  892. // Arrange
  893. const value = {
  894. apikey: 'sk_live_123',
  895. name: 'Service',
  896. };
  897. // Act
  898. const result = redactSensitiveFields(value);
  899. // Assert
  900. expect(result).toEqual({
  901. apikey: '[REDACTED]',
  902. name: 'Service',
  903. });
  904. });
  905. it('should redact all built-in sensitive fields', () => {
  906. // Arrange
  907. const value = {
  908. password: 'pass123',
  909. passwd: 'pass456',
  910. pwd: 'pass789',
  911. secret: 'secret123',
  912. token: 'token123',
  913. apikey: 'key123',
  914. api_key: 'key456',
  915. authtoken: 'auth123',
  916. auth_token: 'auth456',
  917. accesstoken: 'access123',
  918. access_token: 'access456',
  919. refreshtoken: 'refresh123',
  920. refresh_token: 'refresh456',
  921. privatekey: 'private123',
  922. private_key: 'private456',
  923. creditcard: '1234',
  924. credit_card: '5678',
  925. cardnumber: '9012',
  926. card_number: '3456',
  927. cvv: '123',
  928. ssn: '789',
  929. social_security: '456',
  930. };
  931. // Act
  932. const result = redactSensitiveFields(value);
  933. // Assert
  934. const allKeys = Object.keys(value);
  935. for (const key of allKeys) {
  936. expect(result).toHaveProperty(key, '[REDACTED]');
  937. }
  938. });
  939. });
  940. describe('Case Insensitivity', () => {
  941. it('should redact fields regardless of case', () => {
  942. // Arrange
  943. const value = {
  944. PASSWORD: 'secret1',
  945. Password: 'secret2',
  946. password: 'secret3',
  947. pAsSwOrD: 'secret4',
  948. };
  949. // Act
  950. const result = redactSensitiveFields(value);
  951. // Assert
  952. expect(result).toEqual({
  953. PASSWORD: '[REDACTED]',
  954. Password: '[REDACTED]',
  955. password: '[REDACTED]',
  956. pAsSwOrD: '[REDACTED]',
  957. });
  958. });
  959. it('should preserve original case in keys', () => {
  960. // Arrange
  961. const value = {
  962. PASSWORD: 'secret1',
  963. Token: 'secret2',
  964. OtherData: 'public',
  965. };
  966. // Act
  967. const result = redactSensitiveFields(value);
  968. // Assert
  969. // Note: Sensitive field matching is case-insensitive but preserves original key names
  970. expect(result).toEqual({
  971. PASSWORD: '[REDACTED]',
  972. Token: '[REDACTED]',
  973. OtherData: 'public',
  974. });
  975. });
  976. });
  977. describe('Custom Sensitive Fields', () => {
  978. it('should redact additional custom fields', () => {
  979. // Arrange
  980. const value = {
  981. userId: '12345',
  982. sessionId: 'abc123',
  983. password: 'secret',
  984. };
  985. // Act
  986. const result = redactSensitiveFields(value, ['userId', 'sessionId']);
  987. // Assert
  988. expect(result).toEqual({
  989. userId: '[REDACTED]',
  990. sessionId: '[REDACTED]',
  991. password: '[REDACTED]',
  992. });
  993. });
  994. it('should handle custom fields with mixed case', () => {
  995. // Arrange
  996. const value = {
  997. CustomField: 'sensitive',
  998. OtherField: 'public',
  999. };
  1000. // Act
  1001. const result = redactSensitiveFields(value, ['customfield']);
  1002. // Assert
  1003. expect(result).toEqual({
  1004. CustomField: '[REDACTED]',
  1005. OtherField: 'public',
  1006. });
  1007. });
  1008. });
  1009. describe('Nested Objects', () => {
  1010. it('should redact sensitive fields in nested objects', () => {
  1011. // Arrange
  1012. const value = {
  1013. user: {
  1014. name: 'Alice',
  1015. password: 'secret123',
  1016. profile: {
  1017. token: 'abc123',
  1018. },
  1019. },
  1020. };
  1021. // Act
  1022. const result = redactSensitiveFields(value);
  1023. // Assert
  1024. expect(result).toEqual({
  1025. user: {
  1026. name: 'Alice',
  1027. password: '[REDACTED]',
  1028. profile: {
  1029. token: '[REDACTED]',
  1030. },
  1031. },
  1032. });
  1033. });
  1034. it('should propagate custom fields to nested objects', () => {
  1035. // Arrange
  1036. const value = {
  1037. level1: {
  1038. customSecret: 'value1',
  1039. level2: {
  1040. customSecret: 'value2',
  1041. },
  1042. },
  1043. };
  1044. // Act
  1045. const result = redactSensitiveFields(value, ['customSecret']);
  1046. // Assert
  1047. expect(result).toEqual({
  1048. level1: {
  1049. customSecret: '[REDACTED]',
  1050. level2: {
  1051. customSecret: '[REDACTED]',
  1052. },
  1053. },
  1054. });
  1055. });
  1056. });
  1057. describe('Arrays', () => {
  1058. it('should redact sensitive fields in array elements', () => {
  1059. // Arrange
  1060. const value = [
  1061. { name: 'Alice', password: 'pass1' },
  1062. { name: 'Bob', password: 'pass2' },
  1063. ];
  1064. // Act
  1065. const result = redactSensitiveFields(value);
  1066. // Assert
  1067. expect(result).toEqual([
  1068. { name: 'Alice', password: '[REDACTED]' },
  1069. { name: 'Bob', password: '[REDACTED]' },
  1070. ]);
  1071. });
  1072. it('should propagate custom fields to array elements', () => {
  1073. // Arrange
  1074. const value = [
  1075. { id: '1', secret: 'value1' },
  1076. { id: '2', secret: 'value2' },
  1077. ];
  1078. // Act
  1079. const result = redactSensitiveFields(value, ['secret']);
  1080. // Assert
  1081. expect(result).toEqual([
  1082. { id: '1', secret: '[REDACTED]' },
  1083. { id: '2', secret: '[REDACTED]' },
  1084. ]);
  1085. });
  1086. });
  1087. describe('Primitives and Non-Objects', () => {
  1088. it('should handle null', () => {
  1089. // Arrange
  1090. const value = null;
  1091. // Act
  1092. const result = redactSensitiveFields(value);
  1093. // Assert
  1094. expect(result).toBeNull();
  1095. });
  1096. it('should handle undefined', () => {
  1097. // Arrange
  1098. const value = undefined;
  1099. // Act
  1100. const result = redactSensitiveFields(value);
  1101. // Assert
  1102. expect(result).toBeUndefined();
  1103. });
  1104. it('should handle numbers', () => {
  1105. // Arrange
  1106. const value = 42;
  1107. // Act
  1108. const result = redactSensitiveFields(value);
  1109. // Assert
  1110. expect(result).toBe(42);
  1111. });
  1112. it('should handle strings', () => {
  1113. // Arrange
  1114. const value = 'plain string';
  1115. // Act
  1116. const result = redactSensitiveFields(value);
  1117. // Assert
  1118. expect(result).toBe('plain string');
  1119. });
  1120. it('should handle booleans', () => {
  1121. // Arrange
  1122. const trueValue = true;
  1123. const falseValue = false;
  1124. // Act
  1125. const trueResult = redactSensitiveFields(trueValue);
  1126. const falseResult = redactSensitiveFields(falseValue);
  1127. // Assert
  1128. expect(trueResult).toBe(true);
  1129. expect(falseResult).toBe(false);
  1130. });
  1131. });
  1132. describe('Non-Plain Objects', () => {
  1133. it('should serialize Date objects as empty objects', () => {
  1134. // Arrange
  1135. const value = new Date('2025-01-01');
  1136. // Act
  1137. const result = redactSensitiveFields(value);
  1138. // Assert
  1139. // Note: Date objects have no enumerable properties, so they serialize to {}
  1140. expect(result).toEqual({});
  1141. });
  1142. it('should serialize RegExp objects as empty objects', () => {
  1143. // Arrange
  1144. const value = /test/gi;
  1145. // Act
  1146. const result = redactSensitiveFields(value);
  1147. // Assert
  1148. // Note: RegExp objects have no enumerable properties, so they serialize to {}
  1149. expect(result).toEqual({});
  1150. });
  1151. });
  1152. describe('Edge Cases', () => {
  1153. it('should handle empty objects', () => {
  1154. // Arrange
  1155. const value = {};
  1156. // Act
  1157. const result = redactSensitiveFields(value);
  1158. // Assert
  1159. expect(result).toEqual({});
  1160. });
  1161. it('should handle empty arrays', () => {
  1162. // Arrange
  1163. const value: unknown[] = [];
  1164. // Act
  1165. const result = redactSensitiveFields(value);
  1166. // Assert
  1167. expect(result).toEqual([]);
  1168. });
  1169. it('should handle objects with only non-sensitive fields', () => {
  1170. // Arrange
  1171. const value = {
  1172. name: 'Alice',
  1173. age: 30,
  1174. city: 'NYC',
  1175. };
  1176. // Act
  1177. const result = redactSensitiveFields(value);
  1178. // Assert
  1179. expect(result).toEqual({
  1180. name: 'Alice',
  1181. age: 30,
  1182. city: 'NYC',
  1183. });
  1184. });
  1185. it('should handle empty custom fields array', () => {
  1186. // Arrange
  1187. const value = {
  1188. password: 'secret',
  1189. custom: 'value',
  1190. };
  1191. // Act
  1192. const result = redactSensitiveFields(value, []);
  1193. // Assert
  1194. expect(result).toEqual({
  1195. password: '[REDACTED]',
  1196. custom: 'value',
  1197. });
  1198. });
  1199. });
  1200. });
  1201. describe('Integration Scenarios', () => {
  1202. it('should combine pattern-based and field-based redaction', () => {
  1203. // Arrange
  1204. const data = {
  1205. user: {
  1206. email: 'user@example.com',
  1207. password: 'secret123',
  1208. phone: '123-456-7890',
  1209. },
  1210. metadata: {
  1211. ip: '192.168.1.1',
  1212. token: 'abc123xyz',
  1213. },
  1214. };
  1215. // Act - First redact by patterns
  1216. const piiRedacted = redactPII(data);
  1217. // Then redact sensitive fields
  1218. const result = redactSensitiveFields(piiRedacted);
  1219. // Assert
  1220. expect(result).toEqual({
  1221. user: {
  1222. email: '[REDACTED]',
  1223. password: '[REDACTED]',
  1224. phone: '[REDACTED]',
  1225. },
  1226. metadata: {
  1227. ip: '[REDACTED]',
  1228. token: '[REDACTED]',
  1229. },
  1230. });
  1231. });
  1232. it('should handle React component props', () => {
  1233. // Arrange
  1234. const props = {
  1235. onClick: 'function () {}',
  1236. userEmail: 'user@example.com',
  1237. apiToken: 'sk_live_1234567890abcdefghijklmnopqrstuvwxyz',
  1238. displayName: 'Alice',
  1239. };
  1240. // Act
  1241. const result = redactObject(props, { patterns: ['email', 'apiKey'] });
  1242. // Assert
  1243. expect(result).toEqual({
  1244. onClick: 'function () {}',
  1245. userEmail: '[REDACTED]',
  1246. apiToken: '[REDACTED]',
  1247. displayName: 'Alice',
  1248. });
  1249. });
  1250. it('should handle Vue component state', () => {
  1251. // Arrange
  1252. const state = {
  1253. user: {
  1254. credentials: {
  1255. username: 'alice',
  1256. password: 'secret123',
  1257. },
  1258. contact: {
  1259. email: 'alice@example.com',
  1260. phone: '123-456-7890',
  1261. },
  1262. },
  1263. };
  1264. // Act
  1265. const result = redactSensitiveFields(redactPII(state));
  1266. // Assert
  1267. expect(result).toEqual({
  1268. user: {
  1269. credentials: {
  1270. username: 'alice',
  1271. password: '[REDACTED]',
  1272. },
  1273. contact: {
  1274. email: '[REDACTED]',
  1275. phone: '[REDACTED]',
  1276. },
  1277. },
  1278. });
  1279. });
  1280. it('should handle API response data', () => {
  1281. // Arrange
  1282. const response = {
  1283. users: [
  1284. {
  1285. id: 1,
  1286. email: 'user1@example.com',
  1287. apiKey: 'sk_live_user1key123456789012345678',
  1288. },
  1289. {
  1290. id: 2,
  1291. email: 'user2@example.com',
  1292. apiKey: 'sk_live_user2key987654321098765432',
  1293. },
  1294. ],
  1295. metadata: {
  1296. serverIp: '192.168.1.100',
  1297. jwt: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.abc123',
  1298. },
  1299. };
  1300. // Act
  1301. const result = redactObject(redactSensitiveFields(response), {
  1302. patterns: ['email', 'apiKey', 'ip', 'jwt'],
  1303. });
  1304. // Assert
  1305. expect(result).toEqual({
  1306. users: [
  1307. {
  1308. id: 1,
  1309. email: '[REDACTED]',
  1310. apiKey: '[REDACTED]',
  1311. },
  1312. {
  1313. id: 2,
  1314. email: '[REDACTED]',
  1315. apiKey: '[REDACTED]',
  1316. },
  1317. ],
  1318. metadata: {
  1319. serverIp: '[REDACTED]',
  1320. jwt: '[REDACTED]',
  1321. },
  1322. });
  1323. });
  1324. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.