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.
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
Markdown
[](/listings/patchorbit--domscribe)HTML
<a href="/listings/patchorbit--domscribe"><img src="/api/listings/patchorbit--domscribe/badge.svg" alt="findsafeskills safety rating" /></a>Install
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.
- {
- "name": "domscribe",
- "owner": {
- "name": "Patch Orbit",
- "email": "kaushik@patchorbit.com"
- },
- "metadata": {
- "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."
- },
- "plugins": [
- {
- "name": "domscribe",
- "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.",
- "source": "./",
- "homepage": "https://github.com/patchorbit/domscribe",
- "repository": "https://github.com/patchorbit/domscribe",
- "license": "MIT",
- "keywords": [
- "domscribe",
- "pixel-to-code",
- "ui-to-code",
- "dom-annotation",
- "annotation",
- "source-mapping",
- "runtime-context",
- "element-inspector",
- "component-inspector",
- "mcp",
- "model-context-protocol",
- "developer-tools",
- "devtools",
- "react",
- "vue",
- "nextjs",
- "nuxt"
- ]
- }
- ]
- }
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.
- <p align="center">
- <img src="./docs/logo.png" alt="Domscribe" width="200" />
- </p>
- <h1 align="center">Domscribe</h1>
- <p align="center">
- <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>
- <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>
- <a href="#"><img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/Narrator/1bedc40fc56874758abd3b7caf4d6748/raw/domscribe-coverage.json" alt="test coverage" /></a>
- <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license" /></a>
- <img src="https://img.shields.io/badge/TypeScript-5.x-3178c6?logo=typescript&logoColor=white" alt="TypeScript" />
- <img src="https://img.shields.io/badge/node-%3E%3D20-417e38?logo=node.js&logoColor=white" alt="Node.js >= 20" />
- <a href="https://github.com/patchorbit/domscribe/pulls"><img src="https://img.shields.io/badge/PRs-welcome-brightgreen" alt="PRs welcome" /></a>
- </p>
- <p align="center">
- <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>
- <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>
- <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>
- <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>
-
- <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>
- <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>
- <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>
- </p>
- <p align="center">
- <img src="https://img.shields.io/badge/Claude_Code-d97706?style=flat&logo=anthropic&logoColor=white" alt="Claude Code" />
- <img src="https://img.shields.io/badge/GitHub_Copilot-000?style=flat&logo=githubcopilot&logoColor=white" alt="GitHub Copilot" />
- <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>
- <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>
- <img src="https://img.shields.io/badge/Kiro-a855f7?style=flat&logoColor=white" alt="Kiro" />
- </p>
- <p align="center">
- <a href="https://domscribe.com"><img src="./docs/demo.gif" alt="Domscribe demo — click an element, capture context, resolve to source" /></a>
- </p>
- ---
- **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.**
- 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.
- ---
- ## Getting Started
- ```bash
- 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.
- ---
- ## Features
- ### Code → UI: Let the agent see the browser
- 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.
- <p align="center">
- <img src="./docs/code-to-ui.png" alt="Code → UI: Let the agent see the browser" width="900" />
- </p>
- > [!TIP]
- > Agents don't spontaneously query runtime state — prompt them explicitly:
- > _"Fix the button color — use domscribe to check what CSS classes it has before changing anything."_
- > Your dev server must be running with the target page open in the browser.
- ### UI → Code: Point and tell
- 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.
- <p align="center">
- <img src="./docs/ui-to-code.png" alt="UI → Code: Point and tell" width="900" />
- </p>
- ### More
- - 🎯 **Build-time stable IDs** — deterministic `data-ds` attributes injected via AST, stable across HMR and fast refresh
- - 🧩 **Framework-agnostic** — React 18-19, Vue 3, Next.js 15-16, Nuxt 3+, with an [extensible adapter interface](./packages/domscribe-runtime/CUSTOM_ADAPTERS.md)
- - 📦 **Any bundler** — Vite 5-8, Webpack 5, Turbopack (Vite 8 support requires Domscribe 0.7.0 or later)
- - 🔍 **Deep runtime capture** — live props, state, and DOM snapshots via React fiber walking and Vue VNode inspection
- - 🛡️ **Zero production impact** — all instrumentation stripped in production builds, enforced in CI
- - 🔒 **PII redaction** — emails, tokens, and sensitive patterns automatically scrubbed before leaving the browser
- - 📁 **Annotations live in your repo** — stored as JSON files in `.domscribe/annotations/`, exposed via REST APIs that MCP wraps for agent access
- - 📡 **Real-time feedback** — WebSocket relay pushes agent responses to the browser overlay as they happen
- ---
- ## Manual Setup
- > [!NOTE]
- > `npx domscribe init` handles both steps below automatically. Use manual setup only if you need finer control.
- Domscribe has two sides: **app-side** (bundler + framework plugins) and **agent-side** (MCP for your coding agent). Both are needed for the full workflow.
- ### App-Side — Add to Your Bundler
- <details>
- <summary><strong>Next.js (15 + 16)</strong> — <code>npm install -D @domscribe/next</code></summary>
- ```ts
- // next.config.ts
- import type { NextConfig } from 'next';
- import { withDomscribe } from '@domscribe/next';
- const nextConfig: NextConfig = {};
- export default withDomscribe()(nextConfig);
- ```
- </details>
- <details>
- <summary><strong>Nuxt 3+</strong> — <code>npm install -D @domscribe/nuxt</code></summary>
- ```ts
- // nuxt.config.ts
- export default defineNuxtConfig({
- modules: ['@domscribe/nuxt'],
- });
- ```
- </details>
- <details>
- <summary><strong>React 18–19</strong> — <code>npm install -D @domscribe/react</code></summary>
- Vite plugin:
- ```ts
- // vite.config.ts
- import { defineConfig } from 'vite';
- import react from '@vitejs/plugin-react';
- import { domscribe } from '@domscribe/react/vite';
- export default defineConfig({
- plugins: [react(), domscribe()],
- });
- ```
- Webpack plugin:
- ```js
- // webpack.config.js
- const { DomscribeWebpackPlugin } = require('@domscribe/react/webpack');
- const isDevelopment = process.env.NODE_ENV !== 'production';
- module.exports = {
- module: {
- rules: [
- {
- test: /\.[jt]sx?$/,
- exclude: /node_modules/,
- enforce: 'pre',
- use: [
- {
- loader: '@domscribe/transform/webpack-loader',
- options: { enabled: isDevelopment },
- },
- ],
- },
- ],
- },
- plugins: [
- new DomscribeWebpackPlugin({
- enabled: isDevelopment,
- overlay: true,
- }),
- ],
- };
- ```
- </details>
- <details>
- <summary><strong>Vue 3+</strong> — <code>npm install -D @domscribe/vue</code></summary>
- Vite plugin:
- ```ts
- // vite.config.ts
- import { defineConfig } from 'vite';
- import vue from '@vitejs/plugin-vue';
- import { domscribe } from '@domscribe/vue/vite';
- export default defineConfig({
- plugins: [vue(), domscribe()],
- });
- ```
- Webpack plugin:
- ```js
- // webpack.config.js
- const { DomscribeWebpackPlugin } = require('@domscribe/vue/webpack');
- const isDevelopment = process.env.NODE_ENV !== 'production';
- module.exports = {
- module: {
- rules: [
- {
- test: /\.[jt]sx?$/,
- exclude: /node_modules/,
- enforce: 'pre',
- use: [
- {
- loader: '@domscribe/transform/webpack-loader',
- options: { enabled: isDevelopment },
- },
- ],
- },
- ],
- },
- plugins: [
- new DomscribeWebpackPlugin({
- enabled: isDevelopment,
- overlay: true,
- }),
- ],
- };
- ```
- </details>
- <details>
- <summary><strong>Any framework</strong> — <code>npm install -D @domscribe/transform</code> (DOM→source mapping only, no runtime capture)</summary>
- Vite plugin:
- ```ts
- // vite.config.ts
- import { defineConfig } from 'vite';
- import { domscribe } from '@domscribe/transform/plugins/vite';
- export default defineConfig({
- plugins: [domscribe()],
- });
- ```
- Webpack plugin:
- ```js
- // webpack.config.js
- const {
- DomscribeWebpackPlugin,
- } = require('@domscribe/transform/plugins/webpack');
- const isDevelopment = process.env.NODE_ENV !== 'production';
- module.exports = {
- module: {
- rules: [
- {
- test: /\.[jt]sx?$/,
- exclude: /node_modules/,
- enforce: 'pre',
- use: [
- {
- loader: '@domscribe/transform/webpack-loader',
- options: { enabled: isDevelopment },
- },
- ],
- },
- ],
- },
- plugins: [
- new DomscribeWebpackPlugin({
- enabled: isDevelopment,
- overlay: true,
- }),
- ],
- };
- ```
- </details>
- > **Working examples:** See [`packages/domscribe-test-fixtures/fixtures/`](./packages/domscribe-test-fixtures/fixtures/) for complete app setups across every supported framework and bundler combination.
- For plugin configuration options, see the [`@domscribe/transform` README](./packages/domscribe-transform/README.md).
- #### Monorepos
- If your frontend app is in a subdirectory (e.g. `apps/web`), pass `--app-root` during init:
- ```bash
- npx domscribe init --app-root apps/web
- ```
- Or run `npx domscribe init` and follow the prompts — the wizard asks if you're in a monorepo.
- 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.
- ### Agent-Side — Connect Your Coding Agent
- 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.
- #### Claude Code
- ```shell
- claude plugin marketplace add patchorbit/domscribe
- claude plugin install domscribe@domscribe
- ```
- #### GitHub Copilot
- ```bash
- copilot plugin install patchorbit/domscribe
- ```
- #### Gemini CLI
- ```bash
- gemini extensions install https://github.com/patchorbit/domscribe
- ```
- #### Amazon Kiro
- Open the Powers panel → **Add power from GitHub** → enter `https://github.com/patchorbit/domscribe/tree/main/domscribe-power`.
- #### Cursor
- <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>
- #### Any agent (Skills and MCP)
- Install the Domscribe skills:
- ```sh
- npx skills add patchorbit/domscribe
- ```
- Then add this MCP config to your agent:
- ```json
- {
- "mcpServers": {
- "domscribe": {
- "type": "stdio",
- "command": "npx",
- "args": ["-y", "@domscribe/mcp"]
- }
- }
- }
- ```
- ---
- ## How It Works
- <p align="center">
- <img src="./docs/architecture.png" alt="Domscribe architecture diagram" />
- </p>
- **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`.
- **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.
- **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.
- **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).
- ---
- ## Comparison
- | 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) |
- | --------------------- | -------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------ | ----------------------------------------------------- | --------------------------------------------------- |
- | Build-time stable IDs | ✅ `data-ds` via AST | ❌ Runtime (CDP) | ❌ No stable IDs | ❌ `_debugSource` | ❌ Runtime framework introspection |
- | DOM→source manifest | ✅ JSONL, append-only | ❌ | ❌ | ❌ | ❌ |
- | Code→live DOM query | ✅ Agent queries source, gets live runtime | ❌ | ❌ | ❌ | ❌ |
- | Runtime props/state | ✅ Fiber + VNode walking | ⚠️ Shallow | ⚠️ DOM-level + JS eval | ❌ HTML + component names only | ⚠️ Props only (framework APIs) |
- | Multi-framework | ✅ React · Vue · Next.js · Nuxt · extensible | ⚠️ React only | ✅ React + Vue + Svelte + Solid + Preact | ❌ React only | ⚠️ Next.js + Astro + Vite |
- | Multi-bundler | ✅ Vite + Webpack + Turbopack | ❌ N/A (Electron browser) | ✅ Vite + Webpack + Turbopack | ❌ N/A | ❌ Dev server middleware |
- | MCP tools | ✅ 12 tools + 4 prompts | ❌ Proprietary protocol (Karton) | ✅ 9 tools | ⚠️ Lightweight add-on | ❌ Internal MCP only |
- | Agent-agnostic | ✅ Any MCP client | ❌ Bundled Electron agent | ✅ | ✅ | ❌ Bundled Elixir agent |
- | In-app element picker | ✅ Lit shadow DOM | ✅ Built-in browser selector | ✅ Inspector bar | ✅ Hover-to-capture | ✅ Chat interface |
- | Source mapping | ✅ Deterministic (AST IDs) | ⚠️ AI-inferred | ⚠️ AST-injected (not stable) | ⚠️ `_debugSource` (workaround needed) | ⚠️ Runtime framework introspection |
- | License | ✅ MIT | ⚠️ AGPL | ✅ MIT | ✅ MIT | ⚠️ Apache + AGPL |
- 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.
- ---
- ## MCP Tools
- The agent-facing surface — tools, prompts, wire schemas, and error envelope — is listed below as a human-readable index.
- | Tool | Description |
- | ----------------------------------- | --------------------------------------------------------------------------------------- |
- | `domscribe.query.bySource` | Query a source file + line and get live runtime context (props, state, DOM snapshot) |
- | `domscribe.manifest.query` | Find manifest entries by file path, component name, or element ID |
- | `domscribe.manifest.stats` | Manifest coverage statistics (entry count, file count, component count, cache hit rate) |
- | `domscribe.resolve` | Resolve a `data-ds` element ID to its source location (file, line, col, component) |
- | `domscribe.resolve.batch` | Resolve multiple element IDs in one call |
- | `domscribe.annotation.process` | Atomically claim the next queued annotation (prevents concurrent agent conflicts) |
- | `domscribe.annotation.respond` | Attach agent response and transition to `PROCESSED` |
- | `domscribe.annotation.updateStatus` | Manually transition annotation status |
- | `domscribe.annotation.get` | Retrieve annotation by ID |
- | `domscribe.annotation.list` | List annotations with status/filter options |
- | `domscribe.annotation.search` | Full-text search across annotation content |
- | `domscribe.verify.baseline` | Capture a pre-edit style/geometry snapshot of a rendered element |
- | `domscribe.verify.afterEdit` | Compare the element against the baseline — deterministic verdict + per-property deltas |
- | `domscribe.status` | Relay daemon health, manifest stats, queue counts |
- See the [`@domscribe/mcp` README](./packages/domscribe-mcp/README.md) for detailed tool schemas, response formats, and prompt definitions.
- ---
- ## Packages
- | Package | Description |
- | -------------------------- | ----------------------------------------------------------------------------------- |
- | `@domscribe/core` | Zod schemas, RFC 7807 error system, ID generation, PII redaction, constants |
- | `@domscribe/manifest` | Append-only JSONL manifest, IDStabilizer (xxhash64), BatchWriter, ManifestCompactor |
- | `@domscribe/relay` | Fastify HTTP/WS server, MCP stdio adapter, annotation lifecycle |
- | `@domscribe/transform` | Parser-agnostic AST injection (Acorn, Babel, VueSFC), bundler plugins |
- | `@domscribe/runtime` | Browser-side ElementTracker, ContextCapturer, BridgeDispatch |
- | `@domscribe/overlay` | Lit web components (shadow DOM), element picker, annotation UI |
- | `@domscribe/react` | React fiber walking, props/state extraction, Vite + Webpack plugins |
- | `@domscribe/vue` | Vue 3 VNode resolution, Composition + Options API support, Vite + Webpack plugins |
- | `@domscribe/next` | `withDomscribe()` config wrapper for Next.js 15 + 16 |
- | `@domscribe/nuxt` | Nuxt 3+ module with auto-relay and runtime plugin |
- | `domscribe` | CLI binary (`domscribe serve`, `status`, `stop`, `init`, `mcp`) |
- | `@domscribe/mcp` | Standalone MCP server binary (`domscribe-mcp`) |
- | `@domscribe/test-fixtures` | Black-box integration + e2e suite (not published) |
- ---
- ## Contributing
- ```bash
- pnpm install
- nx run-many -t build test lint typecheck
- ```
- Conventions are in `.claude/rules/`. PRs welcome.
- For an isolated browser replay check through the Docker Node SDK, see the
- [Docker Cloud replay smoke test](./docs/docker-cloud-replay.md).
- 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.
- ---
- ## License
- [MIT](./LICENSE)
packages/domscribe-core/src/privacy/redaction.spec.ts · Bundled script · 1,619 lines · 1 finding marked
- /**
- * Tests for PII redaction utilities
- *
- * Tests privacy protection through pattern-based and field-based redaction.
- * Follows Arrange-Act-Assert methodology.
- */
- import { describe, it, expect } from 'vitest';
- import {
- redactText,
- redactObject,
- redactPII,
- redactSensitiveFields,
- } from './redaction.js';
- describe('redactText', () => {
- describe('Email Redaction', () => {
- it('should redact email addresses', () => {
- // Arrange
- const text = 'Contact me at user@example.com for more info.';
- // Act
- const result = redactText(text, { patterns: ['email'] });
- // Assert
- expect(result).toBe('Contact me at [REDACTED] for more info.');
- });
- it('should redact multiple email addresses', () => {
- // Arrange
- const text = 'Email alice@example.com or bob@test.org';
- // Act
- const result = redactText(text, { patterns: ['email'] });
- // Assert
- expect(result).toBe('Email [REDACTED] or [REDACTED]');
- });
- it('should redact emails with different TLDs', () => {
- // Arrange
- const text = 'user@example.co.uk and admin@site.net';
- // Act
- const result = redactText(text, { patterns: ['email'] });
- // Assert
- expect(result).toBe('[REDACTED] and [REDACTED]');
- });
- it('should redact emails with special characters', () => {
- // Arrange
- const text = 'Email: user.name+tag@example-domain.com';
- // Act
- const result = redactText(text, { patterns: ['email'] });
- // Assert
- expect(result).toBe('Email: [REDACTED]');
- });
- it('should preserve partial email when preservePartial is true', () => {
- // Arrange
- const text = 'Contact: user@example.com';
- // Act
- const result = redactText(text, {
- patterns: ['email'],
- preservePartial: true,
- });
- // Assert
- expect(result).toBe('Contact: [REDACTED].com');
- });
- it('should not match very short emails', () => {
- // Arrange
- const text = 'a@b.c';
- // Act
- const result = redactText(text, {
- patterns: ['email'],
- preservePartial: true,
- });
- // Assert
- // Note: Email pattern requires minimum 2-char TLD, so very short emails don't match
- expect(result).toBe('a@b.c');
- });
- });
- describe('Phone Number Redaction', () => {
- it('should redact US phone numbers with dashes', () => {
- // Arrange
- const text = 'Call me at 123-456-7890';
- // Act
- const result = redactText(text, { patterns: ['phone'] });
- // Assert
- expect(result).toBe('Call me at [REDACTED]');
- });
- it('should redact phone numbers with dots', () => {
- // Arrange
- const text = 'Phone: 123.456.7890';
- // Act
- const result = redactText(text, { patterns: ['phone'] });
- // Assert
- expect(result).toBe('Phone: [REDACTED]');
- });
- it('should redact phone numbers with spaces', () => {
- // Arrange
- const text = 'Number: 123 456 7890';
- // Act
- const result = redactText(text, { patterns: ['phone'] });
- // Assert
- expect(result).toBe('Number: [REDACTED]');
- });
- it('should redact phone numbers with parentheses', () => {
- // Arrange
- const text = 'Call (123) 456-7890';
- // Act
- const result = redactText(text, { patterns: ['phone'] });
- // Assert
- expect(result).toBe('Call [REDACTED]');
- });
- it('should redact international phone numbers', () => {
- // Arrange
- const text = 'International: +1-123-456-7890';
- // Act
- const result = redactText(text, { patterns: ['phone'] });
- // Assert
- expect(result).toBe('International: [REDACTED]');
- });
- it('should redact multiple phone numbers', () => {
- // Arrange
- const text = 'Office: 123-456-7890, Mobile: 987-654-3210';
- // Act
- const result = redactText(text, { patterns: ['phone'] });
- // Assert
- expect(result).toBe('Office: [REDACTED], Mobile: [REDACTED]');
- });
- it('should preserve partial phone when preservePartial is true', () => {
- // Arrange
- const text = 'Call 123-456-7890';
- // Act
- const result = redactText(text, {
- patterns: ['phone'],
- preservePartial: true,
- });
- // Assert
- expect(result).toBe('Call [REDACTED]7890');
- });
- });
- describe('Credit Card Redaction', () => {
- it('should redact credit card numbers with dashes', () => {
- // Arrange
- const text = 'Card: 1234-5678-9012-3456';
- // Act
- const result = redactText(text, { patterns: ['creditCard'] });
- // Assert
- expect(result).toBe('Card: [REDACTED]');
- });
- it('should redact credit card numbers with spaces', () => {
- // Arrange
- const text = 'Card: 1234 5678 9012 3456';
- // Act
- const result = redactText(text, { patterns: ['creditCard'] });
- // Assert
- expect(result).toBe('Card: [REDACTED]');
- });
- it('should redact credit card numbers without separators', () => {
- // Arrange
- const text = 'Card: 1234567890123456';
- // Act
- const result = redactText(text, { patterns: ['creditCard'] });
- // Assert
- expect(result).toBe('Card: [REDACTED]');
- });
- it('should preserve partial credit card when preservePartial is true', () => {
- // Arrange
- const text = 'Card: 1234-5678-9012-3456';
- // Act
- const result = redactText(text, {
- patterns: ['creditCard'],
- preservePartial: true,
- });
- // Assert
- expect(result).toBe('Card: [REDACTED]3456');
- });
- });
- describe('SSN Redaction', () => {
- it('should redact social security numbers', () => {
- // Arrange
- const text = 'SSN: 123-45-6789';
- // Act
- const result = redactText(text, { patterns: ['ssn'] });
- // Assert
- expect(result).toBe('SSN: [REDACTED]');
- });
- it('should redact multiple SSNs', () => {
- // Arrange
- const text = 'SSNs: 123-45-6789 and 987-65-4321';
- // Act
- const result = redactText(text, { patterns: ['ssn'] });
- // Assert
- expect(result).toBe('SSNs: [REDACTED] and [REDACTED]');
- });
- it('should preserve partial SSN when preservePartial is true', () => {
- // Arrange
- const text = 'SSN: 123-45-6789';
- // Act
- const result = redactText(text, {
- patterns: ['ssn'],
- preservePartial: true,
- });
- // Assert
- expect(result).toBe('SSN: [REDACTED]6789');
- });
- });
- describe('IP Address Redaction', () => {
- it('should redact IPv4 addresses', () => {
- // Arrange
- const text = 'Server IP: 192.168.1.100';
- // Act
- const result = redactText(text, { patterns: ['ip'] });
- // Assert
- expect(result).toBe('Server IP: [REDACTED]');
- });
- it('should redact multiple IP addresses', () => {
- // Arrange
- const text = 'From 192.168.1.1 to 10.0.0.1';
- // Act
- const result = redactText(text, { patterns: ['ip'] });
- // Assert
- expect(result).toBe('From [REDACTED] to [REDACTED]');
- });
- it('should redact localhost IP', () => {
- // Arrange
- const text = 'Localhost: 127.0.0.1';
- // Act
- const result = redactText(text, { patterns: ['ip'] });
- // Assert
- expect(result).toBe('Localhost: [REDACTED]');
- });
- });
- describe('API Key Redaction', () => {
- it('should redact API keys', () => {
- // Arrange
- const text = 'API Key: sk_live_1234567890abcdefghijklmnopqrstuvwxyz';
- // Act
- const result = redactText(text, { patterns: ['apiKey'] });
- // Assert
- expect(result).toBe('API Key: [REDACTED]');
- });
- it('should redact multiple API keys', () => {
- // Arrange
- const text =
- 'Keys: abcdef1234567890abcdef1234567890 and xyz1234567890xyz1234567890xyzabc';
- // Act
- const result = redactText(text, { patterns: ['apiKey'] });
- // Assert
- expect(result).toBe('Keys: [REDACTED] and [REDACTED]');
- });
- it('should preserve partial API key when preservePartial is true', () => {
- // Arrange
- const text = 'Key: sk_live_1234567890abcdefghijklmnopqrstuvwxyz';
- // Act
- const result = redactText(text, {
- patterns: ['apiKey'],
- preservePartial: true,
- });
- // Assert
- expect(result).toContain('[REDACTED]');
- expect(result).toContain('wxyz');
- });
- });
- describe('JWT Redaction', () => {
- it('should redact JWT tokens', () => {
- // Arrange
- const text =
- '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
- // Act
- const result = redactText(text, { patterns: ['jwt'] });
- // Assert
- expect(result).toBe('Token: [REDACTED]');
- });
- it('should redact multiple JWT tokens', () => {
- // Arrange
- const text =
- 'Tokens: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.abc123 and eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIifQ.xyz456';
- // Act
- const result = redactText(text, { patterns: ['jwt'] });
- // Assert
- expect(result).toBe('Tokens: [REDACTED] and [REDACTED]');
- });
- });
- describe('Multiple Patterns', () => {
- it('should redact multiple PII types in same text', () => {
- // Arrange
- const text =
- 'Email user@example.com, Phone 123-456-7890, Card 1234-5678-9012-3456';
- // Act
- const result = redactText(text, {
- patterns: ['email', 'phone', 'creditCard'],
- });
- // Assert
- expect(result).toBe(
- 'Email [REDACTED], Phone [REDACTED], Card [REDACTED]',
- );
- });
- it('should apply all patterns by default', () => {
- // Arrange
- const text =
- 'Email: user@example.com, IP: 192.168.1.1, Phone: 123-456-7890';
- // Act
- const result = redactText(text);
- // Assert
- expect(result).toBe(
- 'Email: [REDACTED], IP: [REDACTED], Phone: [REDACTED]',
- );
- });
- it('should handle text with no PII', () => {
- // Arrange
- const text = 'Hello world, this is a test message.';
- // Act
- const result = redactText(text);
- // Assert
- expect(result).toBe('Hello world, this is a test message.');
- });
- });
- describe('Custom Patterns', () => {
- it('should apply custom regex patterns', () => {
- // Arrange
- const text = 'Employee ID: EMP12345';
- const customPattern = /EMP\d{5}/g;
- // Act
- const result = redactText(text, {
- patterns: [],
- customPatterns: [customPattern],
- });
- // Assert
- expect(result).toBe('Employee ID: [REDACTED]');
- });
- it('should apply multiple custom patterns', () => {
- // Arrange
- const text = 'Order #ORD123 and Invoice #INV456';
- const orderPattern = /ORD\d{3}/g;
- const invoicePattern = /INV\d{3}/g;
- // Act
- const result = redactText(text, {
- patterns: [],
- customPatterns: [orderPattern, invoicePattern],
- });
- // Assert
- expect(result).toBe('Order #[REDACTED] and Invoice #[REDACTED]');
- });
- it('should combine built-in and custom patterns', () => {
- // Arrange
- const text = 'Email user@example.com, Employee EMP12345';
- const employeePattern = /EMP\d{5}/g;
- // Act
- const result = redactText(text, {
- patterns: ['email'],
- customPatterns: [employeePattern],
- });
- // Assert
- expect(result).toBe('Email [REDACTED], Employee [REDACTED]');
- });
- });
- describe('Custom Replacement', () => {
- it('should use custom replacement string', () => {
- // Arrange
- const text = 'Email: user@example.com';
- // Act
- const result = redactText(text, {
- patterns: ['email'],
- replacement: '***',
- });
- // Assert
- expect(result).toBe('Email: ***');
- });
- it('should use custom replacement for multiple redactions', () => {
- // Arrange
- const text = 'Email alice@test.com and bob@test.org';
- // Act
- const result = redactText(text, {
- patterns: ['email'],
- replacement: '[HIDDEN]',
- });
- // Assert
- expect(result).toBe('Email [HIDDEN] and [HIDDEN]');
- });
- it('should apply custom replacement with preservePartial', () => {
- // Arrange
- const text = 'Phone: 123-456-7890';
- // Act
- const result = redactText(text, {
- patterns: ['phone'],
- replacement: 'XXX',
- preservePartial: true,
- });
- // Assert
- expect(result).toBe('Phone: XXX7890');
- });
- });
- describe('Edge Cases', () => {
- it('should handle empty string', () => {
- // Arrange
- const text = '';
- // Act
- const result = redactText(text);
- // Assert
- expect(result).toBe('');
- });
- it('should handle string with only whitespace', () => {
- // Arrange
- const text = ' \n\t ';
- // Act
- const result = redactText(text);
- // Assert
- expect(result).toBe(' \n\t ');
- });
- it('should handle text with special characters', () => {
- // Arrange
- const text = 'Contact: user@example.com! (or 123-456-7890?)';
- // Act
- const result = redactText(text, {
- patterns: ['email', 'phone'],
- });
- // Assert
- expect(result).toBe('Contact: [REDACTED]! (or [REDACTED]?)');
- });
- it('should handle text with unicode characters', () => {
- // Arrange
- const text = 'Correo: usuario@ejemplo.com 📧';
- // Act
- const result = redactText(text, { patterns: ['email'] });
- // Assert
- expect(result).toBe('Correo: [REDACTED] 📧');
- });
- it('should handle empty patterns array', () => {
- // Arrange
- const text = 'Email: user@example.com';
- // Act
- const result = redactText(text, { patterns: [] });
- // Assert
- expect(result).toBe('Email: user@example.com');
- });
- });
- describe('PreservePartial Edge Cases', () => {
- it('should not preserve partial for 4-character matches', () => {
- // Arrange
- const text = 'Code: 1234';
- // Act
- const result = redactText(text, {
- customPatterns: [/\d{4}/g],
- preservePartial: true,
- });
- // Assert
- expect(result).toBe('Code: [REDACTED]');
- });
- it('should not preserve partial for custom patterns', () => {
- // Arrange
- const text = 'Code: 12345';
- // Act
- const result = redactText(text, {
- customPatterns: [/\d{5}/g],
- preservePartial: true,
- });
- // Assert
- // Note: preservePartial only applies to built-in patterns, not custom patterns
- expect(result).toBe('Code: [REDACTED]');
- });
- });
- });
- describe('redactObject', () => {
- describe('Primitives', () => {
- it('should handle null', () => {
- // Arrange
- const value = null;
- // Act
- const result = redactObject(value);
- // Assert
- expect(result).toBeNull();
- });
- it('should handle undefined', () => {
- // Arrange
- const value = undefined;
- // Act
- const result = redactObject(value);
- // Assert
- expect(result).toBeUndefined();
- });
- it('should handle numbers', () => {
- // Arrange
- const value = 42;
- // Act
- const result = redactObject(value);
- // Assert
- expect(result).toBe(42);
- });
- it('should handle booleans', () => {
- // Arrange
- const trueValue = true;
- const falseValue = false;
- // Act
- const trueResult = redactObject(trueValue);
- const falseResult = redactObject(falseValue);
- // Assert
- expect(trueResult).toBe(true);
- expect(falseResult).toBe(false);
- });
- });
- describe('Strings', () => {
- it('should redact PII in strings', () => {
- // Arrange
- const value = 'Contact me at user@example.com';
- // Act
- const result = redactObject(value, { patterns: ['email'] });
- // Assert
- expect(result).toBe('Contact me at [REDACTED]');
- });
- it('should handle empty strings', () => {
- // Arrange
- const value = '';
- // Act
- const result = redactObject(value);
- // Assert
- expect(result).toBe('');
- });
- });
- describe('Arrays', () => {
- it('should redact PII in array elements', () => {
- // Arrange
- const value = [
- 'Email: user@example.com',
- 'Phone: 123-456-7890',
- 'No PII here',
- ];
- // Act
- const result = redactObject(value, {
- patterns: ['email', 'phone'],
- });
- // Assert
- expect(result).toEqual([
- 'Email: [REDACTED]',
- 'Phone: [REDACTED]',
- 'No PII here',
- ]);
- });
- it('should handle empty arrays', () => {
- // Arrange
- const value: unknown[] = [];
- // Act
- const result = redactObject(value);
- // Assert
- expect(result).toEqual([]);
- });
- it('should handle nested arrays', () => {
- // Arrange
- const value = [['Email: user@example.com'], ['Phone: 123-456-7890']];
- // Act
- const result = redactObject(value, {
- patterns: ['email', 'phone'],
- });
- // Assert
- expect(result).toEqual([['Email: [REDACTED]'], ['Phone: [REDACTED]']]);
- });
- it('should handle arrays with mixed types', () => {
- // Arrange
- const value = [
- 'user@example.com',
- 42,
- true,
- null,
- { email: 'admin@test.com' },
- ];
- // Act
- const result = redactObject(value, { patterns: ['email'] });
- // Assert
- expect(result).toEqual([
- '[REDACTED]',
- 42,
- true,
- null,
- { email: '[REDACTED]' },
- ]);
- });
- });
- describe('Objects', () => {
- it('should redact PII in object values', () => {
- // Arrange
- const value = {
- email: 'user@example.com',
- phone: '123-456-7890',
- name: 'Alice',
- };
- // Act
- const result = redactObject(value, {
- patterns: ['email', 'phone'],
- });
- // Assert
- expect(result).toEqual({
- email: '[REDACTED]',
- phone: '[REDACTED]',
- name: 'Alice',
- });
- });
- it('should handle empty objects', () => {
- // Arrange
- const value = {};
- // Act
- const result = redactObject(value);
- // Assert
- expect(result).toEqual({});
- });
- it('should handle nested objects', () => {
- // Arrange
- const value = {
- user: {
- email: 'user@example.com',
- contact: {
- phone: '123-456-7890',
- },
- },
- };
- // Act
- const result = redactObject(value, {
- patterns: ['email', 'phone'],
- });
- // Assert
- expect(result).toEqual({
- user: {
- email: '[REDACTED]',
- contact: {
- phone: '[REDACTED]',
- },
- },
- });
- });
- it('should only redact own properties', () => {
- // Arrange
- const proto = { inherited: 'user@example.com' };
- const value = Object.create(proto);
- value.own = 'admin@test.com';
- // Act
- const result = redactObject(value, { patterns: ['email'] });
- // Assert
- expect(result).toEqual({
- own: '[REDACTED]',
- });
- });
- });
- describe('Complex Structures', () => {
- it('should redact deeply nested structures', () => {
- // Arrange
- const value = {
- level1: {
- level2: {
- level3: {
- email: 'user@example.com',
- data: ['phone: 123-456-7890'],
- },
- },
- },
- };
- // Act
- const result = redactObject(value, {
- patterns: ['email', 'phone'],
- });
- // Assert
- expect(result).toEqual({
- level1: {
- level2: {
- level3: {
- email: '[REDACTED]',
- data: ['phone: [REDACTED]'],
- },
- },
- },
- });
- });
- it('should handle objects with arrays of objects', () => {
- // Arrange
- const value = {
- users: [
- { email: 'alice@test.com', name: 'Alice' },
- { email: 'bob@test.com', name: 'Bob' },
- ],
- };
- // Act
- const result = redactObject(value, { patterns: ['email'] });
- // Assert
- expect(result).toEqual({
- users: [
- { email: '[REDACTED]', name: 'Alice' },
- { email: '[REDACTED]', name: 'Bob' },
- ],
- });
- });
- it('should handle arrays of nested objects', () => {
- // Arrange
- const value = [
- {
- profile: {
- email: 'user1@test.com',
- },
- },
- {
- profile: {
- email: 'user2@test.com',
- },
- },
- ];
- // Act
- const result = redactObject(value, { patterns: ['email'] });
- // Assert
- expect(result).toEqual([
- {
- profile: {
- email: '[REDACTED]',
- },
- },
- {
- profile: {
- email: '[REDACTED]',
- },
- },
- ]);
- });
- });
- describe('Non-Plain Objects', () => {
- it('should serialize Date objects as empty objects', () => {
- // Arrange
- const value = new Date('2025-01-01');
- // Act
- const result = redactObject(value);
- // Assert
- // Note: Date objects have no enumerable properties, so they serialize to {}
- expect(result).toEqual({});
- });
- it('should serialize RegExp objects as empty objects', () => {
- // Arrange
- const value = /test/gi;
- // Act
- const result = redactObject(value);
- // Assert
- // Note: RegExp objects have no enumerable properties, so they serialize to {}
- expect(result).toEqual({});
- });
- it('should serialize Map objects as empty objects', () => {
- // Arrange
- const value = new Map([['key', 'value']]);
- // Act
- const result = redactObject(value);
- // Assert
- // Note: Map objects have no enumerable properties, so they serialize to {}
- expect(result).toEqual({});
- });
- it('should serialize Set objects as empty objects', () => {
- // Arrange
- const value = new Set([1, 2, 3]);
- // Act
- const result = redactObject(value);
- // Assert
- // Note: Set objects have no enumerable properties, so they serialize to {}
- expect(result).toEqual({});
- });
- });
- describe('Options Propagation', () => {
- it('should apply custom replacement throughout object', () => {
- // Arrange
- const value = {
- a: 'user@example.com',
- b: ['admin@test.com'],
- c: { d: 'info@site.org' },
- };
- // Act
- const result = redactObject(value, {
- patterns: ['email'],
- replacement: '***',
- });
- // Assert
- expect(result).toEqual({
- a: '***',
- b: ['***'],
- c: { d: '***' },
- });
- });
- it('should apply preservePartial throughout object', () => {
- // Arrange
- const value = {
- email1: 'user@example.com',
- nested: {
- email2: 'admin@test.com',
- },
- };
- // Act
- const result = redactObject(value, {
- patterns: ['email'],
- preservePartial: true,
- });
- // Assert
- expect(result).toEqual({
- email1: '[REDACTED].com',
- nested: {
- email2: '[REDACTED].com',
- },
- });
- });
- });
- });
- describe('redactPII', () => {
- it('should redact common PII types', () => {
- // Arrange
- const value = {
- email: 'user@example.com',
- phone: '123-456-7890',
- creditCard: '1234-5678-9012-3456',
- ssn: '123-45-6789',
- ip: '192.168.1.1',
- apiKey: 'sk_live_1234567890abcdefghijklmnopqrstuvwxyz',
- jwt: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.abc123',
- };
- // Act
- const result = redactPII(value);
- // Assert
- expect(result).toEqual({
- email: '[REDACTED]',
- phone: '[REDACTED]',
- creditCard: '[REDACTED]',
- ssn: '[REDACTED]',
- ip: '[REDACTED]',
- apiKey: '[REDACTED]',
- jwt: '[REDACTED]',
- });
- });
- it('should handle nested structures', () => {
- // Arrange
- const value = {
- user: {
- email: 'user@example.com',
- contact: {
- phone: '123-456-7890',
- },
- },
- };
- // Act
- const result = redactPII(value);
- // Assert
- expect(result).toEqual({
- user: {
- email: '[REDACTED]',
- contact: {
- phone: '[REDACTED]',
- },
- },
- });
- });
- it('should handle arrays', () => {
- // Arrange
- const value = ['user@example.com', '123-456-7890', 'Safe text'];
- // Act
- const result = redactPII(value);
- // Assert
- expect(result).toEqual(['[REDACTED]', '[REDACTED]', 'Safe text']);
- });
- it('should handle null and undefined', () => {
- // Arrange
- const nullValue = null;
- const undefinedValue = undefined;
- // Act
- const nullResult = redactPII(nullValue);
- const undefinedResult = redactPII(undefinedValue);
- // Assert
- expect(nullResult).toBeNull();
- expect(undefinedResult).toBeUndefined();
- });
- });
- describe('redactSensitiveFields', () => {
- describe('Built-in Sensitive Fields', () => {
- it('should redact password field', () => {
- // Arrange
- const value = {
- username: 'alice',
- password: 'secret123',
- email: 'alice@example.com',
- };
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toEqual({
- username: 'alice',
- password: '[REDACTED]',
- email: 'alice@example.com',
- });
- });
- it('should redact token field', () => {
- // Arrange
- const value = {
- token: 'abc123xyz',
- data: 'public',
- };
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toEqual({
- token: '[REDACTED]',
- data: 'public',
- });
- });
- it('should redact apikey field', () => {
- // Arrange
- const value = {
- apikey: 'sk_live_123',
- name: 'Service',
- };
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toEqual({
- apikey: '[REDACTED]',
- name: 'Service',
- });
- });
- it('should redact all built-in sensitive fields', () => {
- // Arrange
- const value = {
- password: 'pass123',
- passwd: 'pass456',
- pwd: 'pass789',
- secret: 'secret123',
- token: 'token123',
- apikey: 'key123',
- api_key: 'key456',
- authtoken: 'auth123',
- auth_token: 'auth456',
- accesstoken: 'access123',
- access_token: 'access456',
- refreshtoken: 'refresh123',
- refresh_token: 'refresh456',
- privatekey: 'private123',
- private_key: 'private456',
- creditcard: '1234',
- credit_card: '5678',
- cardnumber: '9012',
- card_number: '3456',
- cvv: '123',
- ssn: '789',
- social_security: '456',
- };
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- const allKeys = Object.keys(value);
- for (const key of allKeys) {
- expect(result).toHaveProperty(key, '[REDACTED]');
- }
- });
- });
- describe('Case Insensitivity', () => {
- it('should redact fields regardless of case', () => {
- // Arrange
- const value = {
- PASSWORD: 'secret1',
- Password: 'secret2',
- password: 'secret3',
- pAsSwOrD: 'secret4',
- };
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toEqual({
- PASSWORD: '[REDACTED]',
- Password: '[REDACTED]',
- password: '[REDACTED]',
- pAsSwOrD: '[REDACTED]',
- });
- });
- it('should preserve original case in keys', () => {
- // Arrange
- const value = {
- PASSWORD: 'secret1',
- Token: 'secret2',
- OtherData: 'public',
- };
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- // Note: Sensitive field matching is case-insensitive but preserves original key names
- expect(result).toEqual({
- PASSWORD: '[REDACTED]',
- Token: '[REDACTED]',
- OtherData: 'public',
- });
- });
- });
- describe('Custom Sensitive Fields', () => {
- it('should redact additional custom fields', () => {
- // Arrange
- const value = {
- userId: '12345',
- sessionId: 'abc123',
- password: 'secret',
- };
- // Act
- const result = redactSensitiveFields(value, ['userId', 'sessionId']);
- // Assert
- expect(result).toEqual({
- userId: '[REDACTED]',
- sessionId: '[REDACTED]',
- password: '[REDACTED]',
- });
- });
- it('should handle custom fields with mixed case', () => {
- // Arrange
- const value = {
- CustomField: 'sensitive',
- OtherField: 'public',
- };
- // Act
- const result = redactSensitiveFields(value, ['customfield']);
- // Assert
- expect(result).toEqual({
- CustomField: '[REDACTED]',
- OtherField: 'public',
- });
- });
- });
- describe('Nested Objects', () => {
- it('should redact sensitive fields in nested objects', () => {
- // Arrange
- const value = {
- user: {
- name: 'Alice',
- password: 'secret123',
- profile: {
- token: 'abc123',
- },
- },
- };
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toEqual({
- user: {
- name: 'Alice',
- password: '[REDACTED]',
- profile: {
- token: '[REDACTED]',
- },
- },
- });
- });
- it('should propagate custom fields to nested objects', () => {
- // Arrange
- const value = {
- level1: {
- customSecret: 'value1',
- level2: {
- customSecret: 'value2',
- },
- },
- };
- // Act
- const result = redactSensitiveFields(value, ['customSecret']);
- // Assert
- expect(result).toEqual({
- level1: {
- customSecret: '[REDACTED]',
- level2: {
- customSecret: '[REDACTED]',
- },
- },
- });
- });
- });
- describe('Arrays', () => {
- it('should redact sensitive fields in array elements', () => {
- // Arrange
- const value = [
- { name: 'Alice', password: 'pass1' },
- { name: 'Bob', password: 'pass2' },
- ];
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toEqual([
- { name: 'Alice', password: '[REDACTED]' },
- { name: 'Bob', password: '[REDACTED]' },
- ]);
- });
- it('should propagate custom fields to array elements', () => {
- // Arrange
- const value = [
- { id: '1', secret: 'value1' },
- { id: '2', secret: 'value2' },
- ];
- // Act
- const result = redactSensitiveFields(value, ['secret']);
- // Assert
- expect(result).toEqual([
- { id: '1', secret: '[REDACTED]' },
- { id: '2', secret: '[REDACTED]' },
- ]);
- });
- });
- describe('Primitives and Non-Objects', () => {
- it('should handle null', () => {
- // Arrange
- const value = null;
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toBeNull();
- });
- it('should handle undefined', () => {
- // Arrange
- const value = undefined;
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toBeUndefined();
- });
- it('should handle numbers', () => {
- // Arrange
- const value = 42;
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toBe(42);
- });
- it('should handle strings', () => {
- // Arrange
- const value = 'plain string';
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toBe('plain string');
- });
- it('should handle booleans', () => {
- // Arrange
- const trueValue = true;
- const falseValue = false;
- // Act
- const trueResult = redactSensitiveFields(trueValue);
- const falseResult = redactSensitiveFields(falseValue);
- // Assert
- expect(trueResult).toBe(true);
- expect(falseResult).toBe(false);
- });
- });
- describe('Non-Plain Objects', () => {
- it('should serialize Date objects as empty objects', () => {
- // Arrange
- const value = new Date('2025-01-01');
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- // Note: Date objects have no enumerable properties, so they serialize to {}
- expect(result).toEqual({});
- });
- it('should serialize RegExp objects as empty objects', () => {
- // Arrange
- const value = /test/gi;
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- // Note: RegExp objects have no enumerable properties, so they serialize to {}
- expect(result).toEqual({});
- });
- });
- describe('Edge Cases', () => {
- it('should handle empty objects', () => {
- // Arrange
- const value = {};
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toEqual({});
- });
- it('should handle empty arrays', () => {
- // Arrange
- const value: unknown[] = [];
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toEqual([]);
- });
- it('should handle objects with only non-sensitive fields', () => {
- // Arrange
- const value = {
- name: 'Alice',
- age: 30,
- city: 'NYC',
- };
- // Act
- const result = redactSensitiveFields(value);
- // Assert
- expect(result).toEqual({
- name: 'Alice',
- age: 30,
- city: 'NYC',
- });
- });
- it('should handle empty custom fields array', () => {
- // Arrange
- const value = {
- password: 'secret',
- custom: 'value',
- };
- // Act
- const result = redactSensitiveFields(value, []);
- // Assert
- expect(result).toEqual({
- password: '[REDACTED]',
- custom: 'value',
- });
- });
- });
- });
- describe('Integration Scenarios', () => {
- it('should combine pattern-based and field-based redaction', () => {
- // Arrange
- const data = {
- user: {
- email: 'user@example.com',
- password: 'secret123',
- phone: '123-456-7890',
- },
- metadata: {
- ip: '192.168.1.1',
- token: 'abc123xyz',
- },
- };
- // Act - First redact by patterns
- const piiRedacted = redactPII(data);
- // Then redact sensitive fields
- const result = redactSensitiveFields(piiRedacted);
- // Assert
- expect(result).toEqual({
- user: {
- email: '[REDACTED]',
- password: '[REDACTED]',
- phone: '[REDACTED]',
- },
- metadata: {
- ip: '[REDACTED]',
- token: '[REDACTED]',
- },
- });
- });
- it('should handle React component props', () => {
- // Arrange
- const props = {
- onClick: 'function () {}',
- userEmail: 'user@example.com',
- apiToken: 'sk_live_1234567890abcdefghijklmnopqrstuvwxyz',
- displayName: 'Alice',
- };
- // Act
- const result = redactObject(props, { patterns: ['email', 'apiKey'] });
- // Assert
- expect(result).toEqual({
- onClick: 'function () {}',
- userEmail: '[REDACTED]',
- apiToken: '[REDACTED]',
- displayName: 'Alice',
- });
- });
- it('should handle Vue component state', () => {
- // Arrange
- const state = {
- user: {
- credentials: {
- username: 'alice',
- password: 'secret123',
- },
- contact: {
- email: 'alice@example.com',
- phone: '123-456-7890',
- },
- },
- };
- // Act
- const result = redactSensitiveFields(redactPII(state));
- // Assert
- expect(result).toEqual({
- user: {
- credentials: {
- username: 'alice',
- password: '[REDACTED]',
- },
- contact: {
- email: '[REDACTED]',
- phone: '[REDACTED]',
- },
- },
- });
- });
- it('should handle API response data', () => {
- // Arrange
- const response = {
- users: [
- {
- id: 1,
- email: 'user1@example.com',
- apiKey: 'sk_live_user1key123456789012345678',
- },
- {
- id: 2,
- email: 'user2@example.com',
- apiKey: 'sk_live_user2key987654321098765432',
- },
- ],
- metadata: {
- serverIp: '192.168.1.100',
- jwt: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.abc123',
- },
- };
- // Act
- const result = redactObject(redactSensitiveFields(response), {
- patterns: ['email', 'apiKey', 'ip', 'jwt'],
- });
- // Assert
- expect(result).toEqual({
- users: [
- {
- id: 1,
- email: '[REDACTED]',
- apiKey: '[REDACTED]',
- },
- {
- id: 2,
- email: '[REDACTED]',
- apiKey: '[REDACTED]',
- },
- ],
- metadata: {
- serverIp: '[REDACTED]',
- jwt: '[REDACTED]',
- },
- });
- });
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.