Skip to main content
Glama

🛡️ SecureGateway (formerly SecureMCP)

Same project, new name. See the 1.0.0 rename and clean-install notes.

Local Multilingual Masking · Subscription Gateway · Trusted Restoration

17개 자연어·24개 코드 언어를 로컬에서 마스킹하고, 도구 실행과 사용자 화면에서 원문을 복원하는 개인정보 보호 도구

Version Python Platforms CI MCP License


English · 한국어 안내 · Supported Versions · Quick Start · 설치·운영 가이드 · Features · Architecture · Documentation

Language guides / 언어별 안내: English · 한국어 · Español · Français · Português · Deutsch · Bahasa Indonesia · Türkçe · Русский · हिन्दी · मराठी · বাংলা · اردو · العربية · తెలుగు · 简体中文 · 日本語


Repeatable privacy and actual LLM comprehension evaluation is available through secure-gateway evaluate. See evaluation commands and metric definitions. The offline suite uses synthetic data; actual LLM evaluation requires explicit --real-llm and fresh interpretation/grading agents.

English Overview

SecureGateway masks text in 17 natural languages and code in 24 language profiles locally, with session-based restoration. Version 1.2.0 adds offline language adapters, binding-aware identifier aliases, and restart recovery for interrupted audit records. See the language support matrix for explicit language tags, syntax scope, local model dependencies and verification limits. Language support is lexical; it does not promise complete morphology, entity recognition or executable anonymization.

Version 0.5 adds an experimental local subscription gateway for Claude Code and Codex. Run secure-gateway gateway install once, then use claude / codex normally. Requests are masked automatically; responses and local tool arguments are restored automatically. Existing CLI subscription OAuth is forwarded to the original subscription service; API keys are refused. No agent hooks are installed. See subscription gateway for setup, automatic startup, tested versions and the exact protection boundary.

Legacy agent hooks remain optional utilities. They cover selected tool text rather than complete requests; local integration documents their limits.

Other hosts have explicit support levels in the compatibility table. Antigravity provides verified stdio MCP utility integration. SDK 0.1.21 uses a context-owned authenticated bridge to the explicit xAI API gateway; native file reads and restoration are verified offline, with separate API billing. The separate xAI API mode and Grok custom model require opt-in and incur API charges, independently of Claude/Codex or Grok subscriptions.

Mask confidential input before sending it to a provider. Restore responses in your trusted local application and show them to the user there. Model-invoked MCP tool arguments are already visible to the provider; adding this server to Claude Desktop or Cursor does not automatically intercept or protect prompts. Restored originals must not be sent back into the model context. This is heuristic masking, not a proof of anonymity, cryptographic zero knowledge, or regulatory compliance.


Related MCP server: ztds-mcp

Supported Versions

2.7.18 keeps Windows and POSIX process-group, file-lock and buffered-pipe differences in one typed module, so callers no longer rely on type-checking bypasses.

2.7.15 adds private, bounded gateway failure diagnostics and protects HTTP error responses from formatter failures.

2.7.14 aligns privacy tests with the public-word policy and retains observed evaluation errors. The holdout measurement improved the task score from 48.00 to 61.00 / 68; its accepted exposure tradeoff, interrupted primary execution and continuation remain explicit in the report.

2.7.13 preserves authentication-failed snapshots in quarantine before starting a fresh session.

2.7.12 recovers from invalid snapshot envelopes and corrupt reasoning metadata while preserving ambiguous authentication failures.

2.7.11 uses locked dependency environments in CI and documents reproducible installs.

2.7.10 preserves ordinary words and common names by default. Some unregistered person and organization names can be sent without masking; explicitly register confidential terms to protect them. See policy and evaluation limits.

2.7.5 masks opaque part/model identifiers such as TV-592 as one stable alias in prose and data, while preserving executable subtraction. See the identifier boundaries and regression proof.

2.7.4 preserves the primary stream failure when cleanup also fails, adds fixed-category cleanup diagnostics, and verifies exactly-once close and bounded reader ownership. See the stream cleanup proof and limits.

2.7.3 audits production assertions and replaces boundary checks that disappeared under python -O with explicit exceptions, preserving existing error contracts. It documents retained proven internal invariants and verifies normal and optimized execution with targeted subprocess tests. See the assertion audit and validation analysis.

2.7.2 fixes tool-path restoration for digit-leading segments such as 2024_report and 3d_models. It also adds safe diagnostics for failed package lifecycle requests. See the reproduction and installed-artifact checks.

2.7.1은 평가 중 HTTP 오류 응답을 명시적으로 닫도록 수정했습니다. Python 3.14에서 발견된 자원 정리 경고를 해결하며, 기존 평가 점수·원본 기록은 유지합니다.

2.7.0에는 독립적으로 작성한 17개 언어 개발·holdout 세트와 반복 평가 명령을 추가했습니다. 개인정보 보호·공개 어휘 과마스킹·작업 응답 점수를 분리하고, 언어별 3회 이상의 평균과 표본편차를 보고합니다. 정보가 부족한 경우의 질문·조건부 초안도 채점하며, 평가 절차와 한계를 공개합니다. 실제 3회 평가 결과와 채점 복구 기록도 확인할 수 있습니다.

2.6.2는 Windows에서 이전 버전 업그레이드 시험용 아카이브의 원본 바이트를 보존하도록 수정했습니다.

2.6.1은 Windows checkout 시 사전 해시가 달라지는 줄바꿈 문제를 수정하고, 작업 응답 재평가와 실제 MCP 계산 도구의 시험 기록을 추가했습니다.

2.6.0에는 분야별 보호 사전과 관리자 개별 On/Off를 추가했습니다. 방산은 기본 On이며, 하위 구성품·공개 장비/모델·사업명을 포함합니다. 자동차와 반도체는 선택할 수 있습니다. 사전 출처·실제 수량·검수 범위와 설정·보호 정책을 확인하세요. 긴 대화의 캐시 재처리, 별칭 파생 이름의 복원 실패, 256개 대화 이후의 세션 용량 문제도 수정했습니다.

2.4.2에서는 설치 후 바뀐 사용자 설정을 보존하며 게이트웨이를 제거하도록 수정했습니다. 다른 Orca 계정에 동기화된 설정 정리와 gateway uninstall --force-clean 복구도 지원합니다.

2.4.0에는 선택형 로컬 E5 문맥 모델과 MiniLM/E5 비교 검증 절차를 추가했습니다. 산업 용어 오분류가 발견되어 모델 단독으로 미등록 단어를 공개하지 않도록 제한했습니다. 이 조건에서는 문단 이해도 개선이 입증되지 않아 기본값은 비활성화입니다. 설치·비활성화 절차와 측정 결과 및 남은 한계를 확인하세요.

Component

Supported versions / scope

SecureGateway

2.8.0

Python

3.10 · 3.11 · 3.12 · 3.13 · 3.14 in CI; package requires Python ≥ 3.10

Operating systems

Windows · macOS · Linux in CI

Claude Code gateway

2.1.287 / Sonnet 5.5 native fixtures and live subscription file-read/masking/restoration verified in English and Korean

Codex gateway

CLI 0.160.0 / gpt-6.1-sol native fixtures and live ChatGPT subscription file-read/masking/restoration verified in English and Korean

MCP transport

Local stdio; CLI HTTP/SSE transports are disabled

Natural languages

17 natural-language profiles; localized guides and language matrix

Code languages

24 code-language profiles; syntax scope and verification limits

SDK 2.0 migration: TokenMapping identity fields are read-only; occurrence counts remain mutable. See SDK mapping identity.

The CI matrix covers 15 Python/OS combinations. Code-language support describes lexer modes, not compatibility with every language release or compiler. The gateway is experimental. Native fixture tests verify routing/masking/restoration. Both agents passed live subscription tests: native file reads, masked source transmission, model answers and automatic restoration in English and Korean. Claude's attribution and alias compatibility bugs are fixed. The earlier 429 was not subscription exhaustion. This does not certify all-traffic privacy.


Quick Start

Automatic subscription integration

uv tool install .
secure-gateway gateway install
secure-gateway gateway status

Restart Claude Code/Codex and use their normal commands. Setup preserves login caches and registers a hidden user-login startup task. It changes user-wide provider settings; no agent hooks are added. Subscription limits still apply. This is text/code inference protection; images, remote attachments and unsupported payloads are blocked. See gateway guide. For the complete lifecycle, including the local dashboard and login, see 설치·운영 가이드.

설치·실행·관리자 페이지·종료·삭제

아래는 Claude Code / Codex 구독 게이트웨이의 전체 사용 순서입니다. Python 3.10 이상, uv, Git을 준비하고 사용할 에이전트에서 기존 구독 로그인을 완료하세요. 관리자 웹페이지는 게이트웨이에 포함되어 있으며 별도 웹서버를 설치할 필요가 없습니다.

1. 패키지 설치와 최초 설정

git clone https://github.com/mj10612/SecureGateway.git
cd SecureGateway
uv tool install .
secure-gateway gateway install
secure-gateway gateway status

이미 저장소를 내려받았다면 해당 폴더에서 uv tool install .부터 실행하세요. gateway install은 기본적으로 Claude Code와 Codex의 사용자 설정을 백업·변경하고, 게이트웨이를 즉시 백그라운드로 실행하며 운영체제 사용자 로그인 시 자동 시작을 등록합니다. 기존 Claude/ChatGPT 로그인 파일은 변경하지 않습니다. 설치 후 실행 중이던 에이전트를 종료하고 다시 실행해야 새 경로가 적용됩니다.

한 에이전트만 설정하거나 포트를 바꾸려면 최초 설치 때 옵션을 지정하세요.

secure-gateway gateway install --agent codex
# 또는 Claude Code만 설정
secure-gateway gateway install --agent claude
# 기본 포트 38117 대신 다른 포트 사용
secure-gateway gateway install --port 38119

위 예시는 선택지이며 전부 실행할 필요는 없습니다. 기존 설치의 포트를 변경하려면 먼저 gateway uninstall로 설정을 복원한 뒤 원하는 포트로 다시 설치하세요. secure-gateway 명령을 찾지 못한다면 uv tool update-shell을 실행하고 터미널을 다시 여세요.

2. 실행·상태 확인·재시작

최초 설치 후에는 평소처럼 claude / codex를 실행하면 됩니다. 로그인 시 자동 시작된 게이트웨이가 마스킹·중계·복원을 처리합니다. 상태는 다음 명령으로 확인합니다.

secure-gateway gateway status

이 명령은 서버 상태와 설치 파일 변경 여부를 확인합니다. 실제 추론 요청이 게이트웨이를 통과하는지는 에이전트에서 요청을 보낸 뒤 관리자 페이지의 처리 로그로 확인하세요.

수동 실행 또는 진단이 필요하면 기존 백그라운드 프로세스를 먼저 종료한 뒤 실행합니다.

secure-gateway gateway stop
secure-gateway gateway run

gateway run은 현재 터미널에서 계속 실행되며 Ctrl+C로 종료합니다. 이 상태에서 관리자 페이지를 열려면 다른 터미널을 사용하세요. 종료한 게이트웨이를 다시 백그라운드로 실행하려면 설치 설정이 변경되지 않은 상태에서 secure-gateway gateway install을 다시 실행할 수 있습니다.

저장소의 최신 코드로 기존 패키지를 업데이트할 때는 다음 순서를 사용하세요.

secure-gateway gateway stop
uv tool install --force .
secure-gateway gateway install

이후 에이전트를 재시작하세요. 설치 뒤 호스트 설정이 수정됐다면 재설치·제거가 거부될 수 있습니다. 오류가 가리키는 설정과 installation.json의 백업을 검토·병합한 뒤 재시도하세요.

3. 관리자 페이지 실행

게이트웨이가 실행 중일 때 다음 명령으로 기본 브라우저를 엽니다.

secure-gateway gateway admin

기본 주소는 http://127.0.0.1:38117/admin입니다. 설치 시 포트를 변경했다면 해당 포트를 사용하세요. gateway admin은 설정 파일에서 포트를 읽어 올바른 주소를 안내합니다. 브라우저를 자동으로 열지 않고 주소만 확인하려면 다음 명령을 사용하세요.

secure-gateway gateway admin --no-open

이 명령은 게이트웨이를 새로 시작하지 않습니다. 서버가 중지됐다면 먼저 실행하세요.

4. 관리자 로그인과 로그 조회

설정 파일에 토큰이 있다고 자동 로그인되는 것은 아닙니다. 브라우저는 로컬 설정 파일을 읽지 않습니다. 다음 순서로 로그인하세요.

  1. 사용 중인 게이트웨이의 config.json을 로컬 편집기로 엽니다.

  2. JSON의 token 항목 값을 복사합니다. 값 주변의 큰따옴표는 제외합니다.

  3. 관리자 페이지의 관리자 인증 토큰 입력란에 붙여 넣습니다.

  4. 관리자 페이지 열기 버튼을 누릅니다.

운영체제

기본 설정 파일

Windows

%USERPROFILE%\.secure-gateway\gateway\config.json

macOS / Linux

~/.secure-gateway/gateway/config.json

이 토큰은 설치할 때 생성되는 로컬 게이트웨이 접근 토큰입니다. Claude/ChatGPT의 구독 로그인 토큰이나 API 키를 입력하는 것이 아닙니다. 별도의 관리자 계정·비밀번호는 없으며, 설정 파일의 토큰과 일치하면 관리자 로그를 조회할 수 있습니다. 토큰은 URL에 넣거나 다른 사람에게 공유하지 마세요.

토큰은 현재 브라우저 탭의 메모리에만 보관합니다. 브라우저 페이지를 새로고침(F5)하거나 탭을 닫으면 다시 입력해야 하며, 화면의 로그아웃 버튼을 누르면 토큰과 표시된 내역이 지워집니다. 화면 안의 새로고침 버튼은 로그인 상태를 유지하면서 로그만 다시 조회합니다. 로그아웃은 게이트웨이 종료나 SQLite 로그 삭제를 의미하지 않습니다.

관리자 화면에서는 에이전트·제공자·구독/API 인증·결과·시작 일시·익명 계정 ID로 로그를 필터링하고, 각 요청의 모델·목적지·HTTP 상태·전송 시도·처리 시간·바이트 수를 확인할 수 있습니다. Claude 구독, ChatGPT 구독, xAI API 키 경로는 구분됩니다. 전달된 계정 식별자는 익명화하며, 구독 요금제나 결제 계정을 확인할 수 없는 경우에는 확인 불가로 표시합니다.

처리 내역은 config.json 옆의 **logs.sqlite3**에 저장하며 최근 100,000건을 보관합니다. 요청·응답 원문, OAuth 토큰, API 키는 기록하지 않습니다. 재시작 후에도 로그는 유지됩니다. SQLite 로그는 게이트웨이를 종료한 뒤 백업하거나 SQLite 온라인 백업 기능을 사용하세요.

5. 사용자 지정 설정 파일과 xAI API 모드

--config로 설치했다면 이후 명령에서도 같은 설정 파일을 지정해야 합니다. 아래 경로는 실제 사용 중인 경로로 바꾸세요.

secure-gateway gateway install --config ./gateway-state/config.json
secure-gateway gateway status --config ./gateway-state/config.json
secure-gateway gateway admin --config ./gateway-state/config.json
secure-gateway gateway stop --config ./gateway-state/config.json
secure-gateway gateway uninstall --config ./gateway-state/config.json

수동 실행도 gateway run --config ./gateway-state/config.json을 사용합니다. 관리자 로그인에는 이 파일의 token을 사용하고, 로그 DB는 같은 폴더에 저장됩니다.

xAI API 모드는 구독 게이트웨이와 별도로 설정·실행하며 별도 API 요금이 발생합니다. 설치는 Grok / xAI 안내를 따르고, 실행에는 gateway api-run, 제거에는 gateway api-uninstall을 사용하세요. 기본 설정은 ~/.secure-gateway/xai-api/config.json, 기본 포트는 38118입니다. 관리자 화면은 동일한 명령으로 해당 설정 파일을 지정해 엽니다.

secure-gateway gateway admin --config /path/to/xai-api/config.json

강제 치환 단어

관리자 페이지의 강제 치환 단어에 한 줄에 하나씩 입력하고 저장하세요. 대소문자를 구분하며 입력한 문자열을 다른 단어 안에서도 치환합니다. *비밀*, 비밀*, *비밀과 비밀은 모두 비밀 부분을 뜻합니다. 중간 *나 *만 입력하는 것은 지원하지 않습니다. 저장은 새 요청부터 적용되며 진행 중인 요청이 있으면 거부됩니다. 규칙은 로컬 게이트웨이 데이터 폴더에 저장됩니다. 규칙 파일은 게이트웨이 토큰으로 암호화됩니다. 토큰을 잃거나 변경하면 기존 규칙을 읽을 수 없으므로 토큰과 데이터를 함께 안전하게 보관하세요. 필수 프로토콜 필드와 규칙이 충돌하면 안전하게 요청이 차단될 수 있으므로 규칙을 구체적으로 정하세요. 일반 어휘 목록과 강제 치환은 휴리스틱이며 모든 민감 정보를 자동으로 식별하지는 못합니다. 일반 단어와 철자가 같은 이름도 보존될 수 있으므로 보호할 이름은 강제 치환 목록에 넣으세요.

6. 종료·설정 해제·패키지 삭제

원하는 작업

방법

남는 항목

관리자 화면 로그아웃

화면의 로그아웃

게이트웨이는 계속 실행되고 DB 로그는 유지

현재 게이트웨이만 종료

secure-gateway gateway stop 또는 수동 실행 터미널에서 Ctrl+C

에이전트 설정·자동 시작 등록·로컬 데이터 유지

게이트웨이 설정 해제

secure-gateway gateway uninstall

설정 복원 후 로컬 설정 파일·로그·세션 데이터 유지

설치한 패키지 삭제

설정 해제 후 uv tool uninstall secure-gateway

저장소와 로컬 데이터 유지

stop만 실행하면 다음 운영체제 로그인 때 게이트웨이가 다시 시작될 수 있습니다. 종료된 동안에는 게이트웨이를 사용하도록 설정된 에이전트 요청이 실패합니다. 자동 시작 등록을 제거하고 에이전트의 기존 설정으로 돌아가려면 uninstall을 사용하세요.

완전히 사용을 중단할 때의 순서는 다음과 같습니다.

secure-gateway gateway uninstall
uv tool uninstall secure-gateway

uninstall은 실행 중인 게이트웨이를 종료하고, 백업한 에이전트 설정과 자동 시작 파일을 설치 전 상태로 복원합니다. 성공한 뒤 에이전트를 재시작하세요. 설치 후 수정된 파일을 덮어쓰지 않도록 제거가 거부되면 먼저 설정을 검토·병합해야 합니다. 설정 복원이 완료되기 전에 패키지나 백업을 삭제하지 마세요. xAI API 설정도 사용했다면 패키지를 삭제하기 전에 gateway api-uninstall도 실행하세요.

복원은 해당 config.json의 installation.json에 기록된 파일에만 적용됩니다. 설치 때 --config를 사용했다면 제거할 때도 같은 경로를 지정하세요. No active gateway installation found는 복원 기록이 없다는 뜻이며, 다른 계정이나 설정 경로까지 복원됐다는 뜻은 아닙니다. Orca에서 여러 Codex 계정을 사용한다면 각 계정의 CODEX_HOME이 다를 수 있으므로 각 계정의 config.toml도 확인하세요. 설치 기록이 없는 경우 현재 설정과 백업을 따로 보관하고 설치 전 설정과 비교해 필요한 항목만 병합하세요. 백업 자체에 게이트웨이 설정이 들어 있을 수도 있으므로 확인 없이 파일 전체를 덮어쓰지 마세요. 토큰이나 설정 원문은 공개하지 마세요.

복원 확인은 실행 중인 Codex/Claude를 완전히 종료한 후 새로 시작하여 수행하세요. Codex의 해당 계정 설정에 model_provider = "secure_gateway_subscription" 또는 [model_providers.secure_gateway_subscription]이 남아 있다면 해당 계정은 아직 게이트웨이를 참조할 수 있습니다. 기존 공급자 설정은 각자의 설치 전 설정을 기준으로 복원해야 합니다. 레거시 secure-gateway init으로 별도 설치한 훅은 게이트웨이 제거와 별개입니다. 훅 제거 안내를 따라 설치 당시와 같은 에이전트 및 범위에서 제거하세요.

모델이 질문의 핵심을 알 수 없다고 답할 때

게이트웨이는 일반적인 작업 지시어 일부를 그대로 전달하고 대상 이름과 민감한 값은 마스킹합니다. 예를 들어 SecureMCP 삭제해줘에서 대상은 별칭으로 바꾸고 삭제해줘는 유지합니다. 지시어 목록은 완전한 사전이 아니므로 목록에 없는 표현은 가려질 수 있습니다. 복원은 응답에 나온 별칭을 되돌릴 뿐 모델이 보지 못한 의미를 복구하지 못합니다. 이 경우 표현을 바꿔 요청해 보세요. 2.3.0부터 게이트웨이는 로컬 빈도 사전과 검토한 생활 어휘로 일반 문맥을 더 넓게 보존합니다. 이름·분야 용어·강제 치환·기존 비밀 매핑이 우선하며, 코드와 도구 인자 값은 더 엄격하게 처리합니다. 검증 결과와 자료 출처를 확인하세요. 2.3.1은 비교·요약 등의 작업 표현과 순서·부정·조건을 보존하고, 모델에 별칭을 일관된 참조로 사용하도록 안내합니다. 특정 이름을 몰라도 보이는 문맥으로 가능한 작업을 수행하게 합니다. 문단 의미 검증 절차에서 원문을 공개하지 않는 평가 입력을 만들고, 별도 모델의 해석을 원문과 대조할 수 있습니다. 모든 일상 표현을 판별하지는 못합니다. 언어 자동 감지는 공유 문자만으로 언어를 정확히 구분할 수 없으므로 필요하면 config.json의 natural_language를 해당 언어 코드로 지정하고 게이트웨이를 재시작하세요. 이전 실행에서 해당 지시어가 이미 별칭으로 기록됐다면 업데이트 후에도 기존 매핑이 우선합니다. 필요할 때 게이트웨이를 실행한 상태에서 secure-gateway gateway reset --agent codex로 Codex 매핑을 지우고 새 대화를 시작하세요. 초기화하면 이전 대화의 별칭을 복원할 수 없으므로 진행 중인 요청을 끝내고 이전 대화를 더 이상 재개하지 않을 때만 실행하세요.

선택적으로 config.json의 기존 항목을 유지한 채 prose_mode를 uncommon_words로 설정하고 공개해도 되는 단어만 common_words에 추가한 후 게이트웨이를 재시작할 수 있습니다. 설정 예시와 제약을 확인하세요. 이 목록은 완전한 한국어 사전이 아니며 활용형도 자동으로 모두 보존하지 않으므로 문제 해결을 보장하지 않습니다. 목록에 추가한 단어는 제공자에게 보일 수 있으므로 민감한 이름이나 정보를 추가하지 마세요. entities_only도 인식되지 않은 민감 정보를 노출할 수 있고 모든 일반 지시어의 보존을 보장하지 않습니다. 기능이 우선이라면 게이트웨이 설정을 해제하고 직접 사용하되, 그 세션의 입력은 게이트웨이로 보호되지 않습니다.

복구용 설정·SQLite 로그·암호화 세션은 자동으로 삭제하지 않습니다. 제거가 성공하고 게이트웨이가 종료된 것을 확인한 뒤, 데이터까지 삭제하려면 필요한 로그를 먼저 백업하고 해당 데이터 폴더를 수동 삭제하세요.

설치 방식

삭제할 데이터 폴더

기본 구독 게이트웨이

Windows: %USERPROFILE%\.secure-gateway\gateway / macOS·Linux: ~/.secure-gateway/gateway

기본 xAI API 게이트웨이

Windows: %USERPROFILE%\.secure-gateway\xai-api / macOS·Linux: ~/.secure-gateway/xai-api

사용자 지정 설정

지정한 config.json의 부모 폴더에서 SecureGateway 데이터만 삭제

사용자 지정 폴더에 다른 파일이 있다면 폴더 전체를 삭제하지 마세요. 소스 저장소는 패키지 제거와 별개이므로 더 이상 필요하지 않을 때 직접 삭제할 수 있습니다.

자세한 보호 범위와 오류 진단은 게이트웨이 안내를 참고하세요.

Legacy optional agent hooks

uv tool install .
secure-gateway init --agent claude
secure-gateway doctor

Restart Claude Code after installation. Hooks default to the current project; use --global for user-wide registration. See local integration for supported tool fields, installation/removal and limitations.

For Codex:

secure-gateway init --agent codex
secure-gateway doctor --agent codex

Restart Codex and review/trust the installed definitions in /hooks. Project hooks require a trusted project. Codex masks tool results and restores Bash/apply_patch inputs; automatic screen restoration is unavailable. Use secure-gateway restore --agent codex --session-id <id> with masked text on UTF-8 stdin for local display. See Codex integration.

Development installation and demo

uv venv
uv pip install -e ".[dev]"
uv run python -m secure_gateway demo

Trusted local Python API

from secure_gateway import LocalPrivacyClient

# Replace echo with your provider adapter. Only its argument may leave the host.
def provider(masked_payload: str) -> str:
    return masked_payload

with LocalPrivacyClient() as client:
    result = client.request(
        "Patient John Doe received 50mg.", provider,
        sensitive_terms={"John Doe"},
    )
    print(result.unmasked_text)  # Local display only

Features

Feature

Behavior

🌐 English & Korean

Per-word multilingual handling, conservative Korean particle separation and explicit sensitive terms

🧩 Code-aware masking

Language-specific lexer modes for identifiers, literals and comments; numbers preserved by default

🎭 Four surrogate strategies

Bracket, Unicode, delimited pseudoword and random hash representations

🔁 Subscription gateway

Automatic request masking, shared prompt/code aliases, local tool-argument restoration and automatic answer display; existing OAuth, no API-key fallback

📊 Local admin dashboard

Token-authenticated log viewer, routing/account metadata, filters and request details; SQLite storage, no prompt/reply/credential logging

🔌 Local agent hooks

Claude Code and Codex tool-text masking and local execution-argument restoration; Claude Code also supports display-only restoration

🔐 Session management

Stable per-session mappings, operation locks, idle expiry and opt-in encrypted snapshots

🛠️ CLI & Python API

Local masking/restoration, hook diagnostics, statistics and a buffered command wrapper

Masking policies

Mode

Behavior

content_words

Mask content words and detected sensitive spans; keep functional grammar.

entities_only

Mask recognized PII, URLs, secrets, code spans, numbers and capitalized names. Korean and other case-free/non-ASCII words are masked conservatively, including ordinary nouns.

aggressive

Keep a small structural subset of articles/prepositions/conjunctions; mask auxiliaries, adverbs, pronouns and other words.

code_aware

Mask identifiers, literals and comments using the selected lexer; preserve numbers unless explicitly enabled.

English, Korean and mixed input are handled per word. Unicode names remain atomic. Korean particle splitting uses known stems and conservative rules; unknown ambiguous words stay whole. It is not a full morphological analyzer or universal person-name detector. Supply sensitive_terms for domain names, lowercase names, ambiguous names, and custom secrets. custom_preserve / CLI --preserve deliberately exempts selected words; recognized sensitive spans still take precedence. Unknown secret formats and context-dependent names may evade entities_only; inspect the payload or use broader masking. A high masking ratio does not prove absence of sensitive data.

Surrogate strategies

Strategy

Representation

bracket

[ENT_1]

unicode

⟦ENT_1⟧

pseudoword

Explicitly delimited pronounceable words, e.g. ⟪Brivel…⟫

hash

Random 96-bit nonce, independent of the original

Pseudowords use explicit delimiters to avoid collisions with real words and adjacent tokens. Allocation is stable within a session; random strategies intentionally differ between sessions. Keep all surrogate spelling intact. Altered/unknown placeholder candidates are reported in unmatched_surrogates; strict=True rejects them. Free-form deletion or invention by a model cannot always be detected or reconstructed.

Korean restoration

Exact mask/unmask roundtrips keep written particles. For newly generated Korean responses, opt into normalize_particles=True (CLI --normalize-particles) to choose 이/가, 은/는, 을/를, 과/와 and 으로/로 from a restored Hangul stem. Pronunciation of foreign names is not guessed.

Code-aware review representations

Code profiles: python, javascript, typescript, go, rust, java, c, cpp, sql, bash, csharp, powershell, php, kotlin, lua, nasm, swift, ruby, dart, r, nix, gdscript, vbnet, vba. Use explicit --code-language for ambiguous source; see the syntax scope and aliases. SQL identifier comparison can be selected with --sql-dialect standard|postgresql|sqlite. Use explicit language in mask_code (CLI --code-language) for ambiguous snippets. Auto detection is best effort. Keywords are language-specific; builtins and shadowed builtin names are masked. Unicode identifiers, SQL comments/doubled quotes, backticks, Python f-strings and escaped newlines, C++/Rust raw strings and numeric suffixes/separators are covered by tests. Code allocations use ASCII names (smcp_ID_n and smcp_LIT_n inside literals) and, when numeric masking is enabled, random native integer constants for numbers (reserved 732846 prefix plus 12 digits), independently of the text strategy, so byte literals remain valid too. Python output is syntax-checked in tests. Output is an opaque review representation: it need not execute, type-check or preserve f-string/template interpolation behavior. Numeric types/values can change when numeric masking is enabled. This small lexer is not a complete parser for every version of every supported language.


System Architecture

flowchart LR
    Input[Trusted local input] --> Mask[Masking engine]
    Mask -->|Masked payload| Provider[AI provider callback]
    Provider -->|Surrogate response| Restore[Local restoration]
    Restore --> Display[User display]
    Vault[Local session mappings] --- Mask
    Vault --- Restore

The subscription gateway masks configured inference requests before forwarding them and restores responses before the CLI consumes them. The callback path masks its provider argument. Legacy agent hooks use a separate, partial tool-text path; they do not intercept all outgoing context. See the architecture and local integration documents.


CLI and Sessions

python -m secure_gateway mask "Alice from Google" --session-id example --session-file example.enc --json-output
python -m secure_gateway unmask "[ENT_1] from [ENT_2]" --session-id example --session-file example.enc --strict
python -m secure_gateway mask "john doe" --mode entities_only --sensitive-term "john doe"

Use the same hidden password, or SECURE_GATEWAY_SESSION_PASSWORD. CLI files use authenticated Fernet encryption, random salt, PBKDF2-HMAC-SHA256 with 600,000 iterations, atomic writes and a lock over the complete CLI read/modify/write operation. A concurrent writer fails clearly. Marked .lock files are persistent and their OS locks are released after a crash; retain these files. Only legacy empty locks require manual migration after all old writers stop. Files are opt-in; without --session-file, mappings only survive in the current process. Payload schema v2 stores allocations/counters without regenerating mappings. Legacy v1 files remain readable; unknown schema versions fail explicitly. Delete session files after use. Legacy bare pseudoword allocations retain their old ambiguity; start a new session to use the safe delimited representation for every allocation.

Session strategies are immutable; mode records the last-used policy. Creating a duplicate ID fails without changing its TTL or mappings. TTL must be positive and at most one day. The vault sweeps idle expired sessions at most one cleanup interval later (default one second), and checks expiration on access. Clear waits for active operations and invalidates retained references. Library users must use session.operation() for custom mutations; built-in engine operations use the same lock. vault.close() stops cleanup and releases all mapping references. Python cannot promise byte-level memory zeroization. Standalone PrivacySession owners manage lifetime themselves; use SessionVault for scheduled expiry.

Version 0.6 adds UTF-8 stdin and --input-file for mask/unmask, configurable MCP resource limits, and local Hook snapshot diagnostics:

secure-gateway mask --input-file private.txt --session-file example.enc --json-output
secure-gateway state status
secure-gateway state gc             # read-only preview
secure-gateway state gc --apply     # retire expired snapshots; use new conversations
secure-gateway gateway diagnostics

MCP defaults are 1,000 sessions, 100,000 mappings per session, and 16 MiB per input. serve --max-sessions, --mapping-limit, and --input-limit configure them. Gateway defaults admit 32 inference requests globally and eight per provider; JSON configuration keys are max_active_requests and max_provider_requests. See the integration guides for command limits, safe cleanup, and supported schema constraints.

masked_ratio counts masked token occurrences divided by non-whitespace/non-punctuation occurrences. Deprecated privacy_entropy_score is an alias, not information entropy. restored_occurrences counts replacements; restored_unique_tokens counts distinct allocations. restored_tokens_count remains a compatibility alias for replacement occurrences.


MCP Tools Reference

python -m secure_gateway serve supports local stdio only. HTTP/SSE transports are disabled in the CLI; directly exposing the Python server over a network requires host-provided authentication and isolation.

MCP tool

Purpose

mask_text

Mask text with a selected policy and session

mask_code

Create a code review representation using a selected language lexer

create_privacy_session

Create an isolated mapping session

get_session_stats

Return counters without original values or mapping entries

clear_privacy_session

Release the session's mapping references

Local Python unmask_text / unmask_code and CLI unmask are not registered as MCP tools, so a model cannot enumerate mappings via restoration. Resources: privacy://policies, privacy://status. Example desktop configurations are utility setups, not privacy proxies.

Migration from 0.1

Version 0.2 changes pseudoword delimiters, code identifier/number representations, mapping keys (mapping_key(original, token_type, code=...)), sentence-initial entity classification, keyword preservation, and the MCP restoration boundary. Direct store readers should use mapping values or mapping_key. Validate explicitly requested strategies; omitted strategies follow the generator.


한국어 안내 (Korean Overview)

0.5에서는 Claude Code·Codex의 기존 구독 로그인을 유지하는 로컬 게이트웨이를 제공합니다. uv tool install . 설치 후 secure-gateway gateway install을 한 번 실행하고 두 CLI를 재시작하세요. 그 뒤에는 평소처럼 claude / codex를 사용하면 됩니다. 직접 입력·텍스트 코드·도구 결과를 자동으로 마스킹하고, 답변과 로컬 실행 인자는 자동 복원합니다. 함수명·변수명·문자열·숫자·주석을 보존하는 예외는 추가하지 않았습니다. 입력에서 지칭한 함수와 코드의 함수는 같은 치환표를 사용합니다.

기존 로그인 파일은 읽거나 복사하지 않습니다. CLI가 관리하는 OAuth 헤더와 갱신 흐름을 사용하고, API 키 요청은 거부하므로 유료 API로 자동 전환하지 않습니다. 새 Hook을 등록하지 않으며, 운영체제 사용자 로그인 시 백그라운드로 자동 시작하도록 설정합니다. 기존 Hook 방식은 선택 기능으로 남겨 두었습니다. 설치·해제 및 보호 범위를 확인하세요.

Claude Code 2.1.287·Codex 0.160.0의 실제 CLI를 모의 OAuth/로컬 서버로 검증했습니다. 두 CLI 모두 기존 구독 로그인으로 영어·한국어 질문 → 실제 파일 읽기 → 코드 마스킹 전송 → 정상 답변·자동 복원까지 검증했습니다. Claude의 식별 블록·치환명 호환 오류를 수정했으며, 기존 429는 구독 한도 소진이 아니었습니다. 이미지·원격 첨부·미지원 요청은 차단하고, 게이트웨이 밖의 도구 네트워크·텔레메트리까지 보호한다고 주장하지 않습니다.

SecureGateway는 17개 자연어와 혼합 문장을 로컬에서 마스킹하고 복원합니다. --language로 언어를 명시할 수 있으며 자동 판별의 범위와 언어별 제약은 언어 지원 표에 정리했습니다. 클라우드에 요청하기 전에 LocalPrivacyClient 또는 로컬 API/CLI로 원문을 가리고, 응답은 로컬에서만 복원하세요. 모델이 호출하는 MCP 도구의 인자는 이미 제공자에게 전달되어 있으므로, Claude Desktop/Cursor에 서버를 추가하는 것만으로 개인정보가 보호되지는 않습니다. 복원한 원문을 모델 컨텍스트에 다시 넣으면 안 됩니다. MCP 복원 도구는 제거했으며, 기본 CLI 서버는 로컬 stdio만 지원합니다.

영어 대문자 이름과 Unicode 이름을 하나의 토큰으로 처리합니다. 한국어 이름과 일반 명사가 구분되지 않는 entities_only에서는 비기능어를 보수적으로 가립니다. 조사 분리는 알려진 어간과 보수적인 규칙을 사용하며, 모호한 미등록 단어는 통째로 가립니다. 모든 고유명사·비밀값 또는 한국어 형태소를 완벽히 인식하는 도구는 아닙니다. sensitive_terms / --sensitive-term으로 특정 용어를 지정하고, 알 수 없는 민감정보에는 더 넓은 마스킹 정책을 사용하세요.

정확한 왕복 복원에서는 입력 조사를 그대로 유지합니다. 모델이 새로 만든 문장에는 normalize_particles=True / --normalize-particles를 선택하여 받침에 맞는 조사를 보정할 수 있습니다. 영어 이름·약어의 발음은 추측하지 않습니다. --strict는 탐지한 변형·미등록 플레이스홀더의 복원을 거부하지만, 모델이 완전히 삭제한 내용을 재구성하지는 못합니다.

세션 전략은 생성 후 고정되며, 중복 ID 생성은 오류입니다. 만료 세션은 주기적으로 정리하고, 삭제와 진행 중 작업을 잠금으로 조율합니다. 별도 CLI 프로세스 간 복원에는 동일한 암호화 --session-file이 필요합니다. 마스킹 비율은 통계이며 기밀성·익명성·규제 준수의 증명이 아닙니다.


Development

python -m ruff check src tests examples
python -m mypy src
python -m pytest -W error --cov=secure_gateway --cov-report=term-missing --cov-fail-under=85

Documentation

License

Licensed under Apache License 2.0. See LICENSE for details.

Code numeric literals

Code masking preserves numeric literals by default, including their original spelling, base, exponent, separators and suffixes. This keeps indexes, loop bounds and comparison constants useful for code review. Names, strings and comments remain masked. Numeric values inside strings/comments follow their existing literal masking policy; ordinary natural-language number masking and provider protocol controls are unchanged.

To hide sensitive code numbers explicitly:

  • CLI: secure-gateway mask --mode code_aware --mask-numbers ...

  • MCP/Python: pass mask_numbers=True to mask_code, or to mask_text with mode="code_aware" (Python engine/client use MaskMode.CODE_AWARE).

  • Gateway: set "mask_numbers": true in the gateway configuration, or start gateway run --mask-numbers / gateway api-run --mask-numbers. --preserve-numbers overrides a configured opt-in. Both paths default to preservation.

Existing saved numeric aliases still restore. A literal that collides with an existing numeric alias is rejected rather than silently restored to another value; start a fresh session/conversation in that case. Literal numbers in the reserved alias range receive identity mappings so strict restoration and saved sessions remain unambiguous. Switching those particular literals to numeric masking also requires a fresh session. Turning on numeric masking changes values and does not preserve executable behavior.

Restoration budgets and audit retention

Version 1.1.0 adds configurable UTF-8 restoration input/output budgets (16 MiB each by default), plus completed-request audit count/age retention and a default dry-run gateway audit-gc command. See operational limits for configuration, explicit cleanup and SQLite storage semantics.

Selective plain-text vocabulary (1.6.0)

Use --mode uncommon_words to preserve a small offline English/Korean ordinary vocabulary while masking unusual content; extend it with --common-word WORD. Existing modes remain available. See plain-text policy and limitations. Offline audit metadata export is available through gateway audit-export; see bounded export commands.

Version 1.7.0 fixes Java escaped names, Kotlin inline accessors, Bash comment boundaries, SQL CTE/default/returning and key bindings, Hook token boundaries and nesting, and symlink installation handling. It also adds logical mapping/snapshot budgets; see operational policy.

Logging

Gateway process logging defaults to WARNING and can be set with SECURE_GATEWAY_LOG_LEVEL. Library imports do not configure application log handlers. Events exclude request content, credentials, paths, exception text, and tracebacks. CLI output remains user-facing output. See error handling for the logging and exception contract.

Available Tools

5 tools
clear_privacy_sessionB

Wait for active operations, invalidate the session and release mapping references.

Inputs: session_id. Returns: result

create_privacy_sessionC

Create a new session. Duplicate IDs are errors; TTL is 1..86400 seconds.

Inputs: mode, strategy, session_id, ttl_seconds. Returns: result

get_session_statsD

Sanitized metrics. mode means the most recent masking policy.

Inputs: session_id. Returns: result

mask_codeA

Mask identifiers/literals. Set language explicitly when auto detection is ambiguous.

Numbers are preserved by default; mask_numbers=True opts into numeric masking. Supported language profiles are listed in privacy://policies and docs/LANGUAGES.md. SQL dialect: standard (lowercase folding), postgresql, sqlite. Generated code is a review representation; it is not executable anonymization.

Inputs: code (required), language, strategy, session_id, +2 more. Returns: result

mask_textB

Mask text. Tool arguments are provider-visible; pre-mask confidential data locally.

mode: content_words, entities_only, code_aware, aggressive, uncommon_words. strategy: bracket, unicode, pseudoword, hash. language: auto or a supported natural-language tag. sensitive_terms forces explicit words/phrases; custom_preserve opts terms out of masking. common_vocabulary extends the local ordinary-word list in uncommon_words mode. code_language selects a code lexer when mode=code_aware. mask_numbers=True masks code numbers; the default preserves them.

Inputs: text (required), mode, language, strategy, +7 more. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.1/5.0

    Scored across 5 tools

    Disambiguation3/5

    The session lifecycle tools are clearly distinct, but mask_text and mask_code overlap because mask_text explicitly supports a code_aware mode while mask_code is specialized for code. Descriptions help, but an agent may still be unsure which tool to choose for code-like content.

    Naming Consistency5/5

    All tool names use consistent snake_case with a verb_noun pattern: mask_text, mask_code, create_privacy_session, clear_privacy_session, and get_session_stats. The convention is predictable and readable.

    Tool Count5/5

    Five tools is well-scoped for a session-based privacy masking server. Each tool covers a distinct lifecycle or masking operation without obvious filler.

    Completeness4/5

    The set covers session creation, clearing, stats, and both text and code masking. Minor gaps remain around session inspection/listing or updating session configuration, but core workflows are supported.

    Maintenance

    ActivityActive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Enables AI assistants to mask sensitive personal data and project directories before sending to AI, then unmask responses to restore original values using configurable swap sessions.
      7
      MIT
    • A
      license
      B
      quality
      B
      maintenance
      Enables local, in-memory de-identification of PII, PHI, and credentials with deterministic reversible surrogate tokens before LLM transmission, then restores originals from volatile session mappings and audits for exposures without network egress or disk writes.
      5
      115 npm
      1
      Apache 2.0
    • F
      license
      Not graded
      quality
      B
      maintenance
      Enables reversible anonymization of sensitive PII such as SSNs, credit cards, passport numbers, emails, and phone numbers before sending prompts to external LLMs, then restores original values locally using HMAC isolation.
      7
      -