dsh-mask 0.2.20 → 0.2.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +20 -5
- package/CHANGELOG.md +41 -0
- package/README-es.md +18 -14
- package/README-hi.md +18 -14
- package/README-pt.md +18 -14
- package/README-zh.md +16 -12
- package/README.md +18 -14
- package/cordis.patch.yml +7 -0
- package/index.mjs +77 -5
- package/lib/constants.mjs +2 -0
- package/lib/deliver.mjs +111 -0
- package/lib/store.mjs +26 -2
- package/lib/strip.mjs +14 -0
- package/package.json +23 -14
- package/types.d.ts +7 -0
package/ARCHITECTURE.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Overview
|
|
4
4
|
|
|
5
|
-
`dsh-mask` anonymizes PII at the model boundary: it rewrites the messages that enter a step so that phones, emails, ID cards, bank cards, keys, and IPs become `<TYPE_N>` placeholders, and it keeps a `placeholder → original` restore table host-side so those placeholders stay reversible. The restore surface this form ships is the `/mask restore <text>` command plus the exported `RestoreStore` seam; automatically mapping placeholders back in the client UI is the browser half this pure-host form does not ship (see `README.md` Known limitations). The hard invariant is that **the plaintext never enters the session log** — the masked form is what gets logged and sent to the model, so model-visible content reconstructs from the log in placeholder form.
|
|
5
|
+
`dsh-mask` anonymizes PII at the model boundary: it rewrites the messages that enter a step so that phones, emails, ID cards, bank cards, keys, and IPs become `<TYPE_N>` placeholders, and it keeps a `placeholder → original` restore table host-side so those placeholders stay reversible. The restore surface this form ships is the `/mask restore <text>` command plus the exported `RestoreStore` seam; automatically mapping placeholders back in the client UI is the browser half this pure-host form does not ship (see `README.md` Known limitations). The hard invariant is that **the plaintext never enters the session log** — the masked form is what gets logged and sent to the model, so model-visible content reconstructs from the log in placeholder form. That invariant also governs the reveal direction: a command's result text is logged verbatim, so `/mask restore` delivers the restored plaintext as a controlled file and its result carries only the path and the placeholder names (see "Restore delivery").
|
|
6
6
|
|
|
7
7
|
## Roles
|
|
8
8
|
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
| `lib/sanitize.mjs` | Pure display/log redaction (PII entities, secrets, URL credentials, mapping summarization) |
|
|
22
22
|
| `lib/gate.mjs` | Session-event adaptive gate (append only when the host records the type or supports `ignorable`) |
|
|
23
23
|
| `lib/store.mjs` | The restore table: per-session `Stripper` in memory + optional persistence to `storageDomain` |
|
|
24
|
+
| `lib/deliver.mjs` | Restore-result delivery: the controlled plaintext file (one per session, `0700`/`0600`, symlink and ownership checks) that keeps the reveal out of the session log — `node:` built-ins only |
|
|
24
25
|
| `lib/domain.mjs` | The `dsh-mask` storage-domain spec (`restore` table, zod-validated) |
|
|
25
26
|
|
|
26
27
|
## Data flow
|
|
@@ -29,12 +30,25 @@
|
|
|
29
30
|
inbox ──agent/pre-step──▶ maskMessages ──▶ user/message (placeholders) ──▶ model
|
|
30
31
|
│
|
|
31
32
|
└──▶ RestoreStore (memory + dsh_mask/restore)
|
|
32
|
-
response (placeholders) ──restore()──▶
|
|
33
|
+
response (placeholders) ──restore()──▶ /mask restore ──▶ controlled file (never the log)
|
|
33
34
|
```
|
|
34
35
|
|
|
35
36
|
1. **Mask** — the `agent/pre-step` listener calls `next()` first (waterfall discipline), then rewrites the returned decision's messages through the session's `Stripper`. The masked messages are what the loop appends as `user/message`, so the log and the model both see placeholders.
|
|
36
37
|
2. **Record** — the `Stripper` accumulates the mapping and counts in memory; `store.persist(sessionId)` writes the mapping to `dsh_mask/restore` (best-effort, when `persistRestoreTable: true`).
|
|
37
|
-
3. **Restore** — `/mask restore` (and a future client half) call `store.restore(sessionId, text)`, which unmaps placeholders using the in-memory mapping or reloads it from the domain.
|
|
38
|
+
3. **Restore** — `/mask restore` (and a future client half) call `store.restore(sessionId, text)`, which unmaps placeholders using the in-memory mapping or reloads it from the domain. The command handler uses `store.restoreDetailed` so it can report which placeholders matched, then hands the plaintext to `lib/deliver.mjs` instead of returning it.
|
|
39
|
+
|
|
40
|
+
## Restore delivery (why the reveal is a file)
|
|
41
|
+
|
|
42
|
+
The host gives a command handler no way to show text to the user without also logging it:
|
|
43
|
+
|
|
44
|
+
- `@deepseek-ai/dsh-commands`'s `execute()` appends `command/done` with the handler's **verbatim** `result.text` (`packages/interaction/commands/src/index.ts`, typed as verbatim in its `types.ts`). It is a direct log-only append: no turn wraps it, and it never reaches the model.
|
|
45
|
+
- The user-visible command outcome is rendered from **that same event**: the client conversation assembler builds the command node out of `command/run`/`command/done`, and `GenericCommandCard` renders `node.outcome.text`.
|
|
46
|
+
|
|
47
|
+
So `result.text` is simultaneously the transcript and the persistent log, and the host exposes no "log but do not render" or "render but do not log" switch (`recordInput: false` covers only the input side, `command/run.args`). Returning the restored plaintext there — what this plugin did until 0.2.21 — therefore wrote the PII into the session log on every `/mask restore`, which is exactly what the plugin exists to prevent. Redacting the result instead (running it through `redactText`) would keep the leak closed but leave the user staring at `***` for a command whose only purpose is to reveal the original.
|
|
48
|
+
|
|
49
|
+
The chosen design keeps both properties: the plaintext goes to a controlled file under `restoreDir` (default `os.tmpdir()/dsh-mask-restore`), and the result text carries only the path and the placeholder names — both non-PII by construction (the path is the config directory plus a fixed prefix plus a hash of the session id; the placeholders are already in the log by design). One file per session means the number of plaintext copies on disk stays bounded, and the result text says so. Delivery failure fails closed: an error result, never a fallback that echoes the plaintext.
|
|
50
|
+
|
|
51
|
+
The file is deliberately **not** the storage domain's own record: the domain holds the whole session mapping in one JSON record, whereas this file holds exactly the text the user asked to see, at a path the user can open.
|
|
38
52
|
|
|
39
53
|
## Why `agent/pre-step` and not `agent/request`
|
|
40
54
|
|
|
@@ -62,8 +76,8 @@ The `dsh_mask` domain has one `restore` table keyed by session id. Its record ho
|
|
|
62
76
|
|
|
63
77
|
## Safety boundaries
|
|
64
78
|
|
|
65
|
-
- **Plaintext never enters the session log.** The masked form is logged; originals stay in the restore table.
|
|
66
|
-
- **Sanitize before display/log.** `lib/sanitize.mjs` redacts PII, secrets, and URL credentials before any text reaches the model or log; `mask_test
|
|
79
|
+
- **Plaintext never enters the session log.** The masked form is logged; originals stay in the restore table. This covers the reveal direction too: the `/mask restore` result text is logged verbatim by the host, so the plaintext is delivered as a controlled file (see "Restore delivery").
|
|
80
|
+
- **Sanitize before display/log.** `lib/sanitize.mjs` redacts PII, secrets, and URL credentials before any text reaches the model or log; `mask_test`, `/mask status`, and every `/mask` error path never echo originals.
|
|
67
81
|
- **Fail closed.** Unimplemented `mode` (`regex+ner`), `scope` (`tools`), NER-only entities, and out-of-bounds numbers fail loudly at load.
|
|
68
82
|
- **Registrations are effects.** The listener, command, tool, and domain close are all Cordis effects, so stop/hot-reload is reversible.
|
|
69
83
|
|
|
@@ -72,3 +86,4 @@ The `dsh_mask` domain has one `restore` table keyed by session id. Its record ho
|
|
|
72
86
|
- `mode: regex+ner` — external name/address recognition; fails loudly until a recognizer is wired in (the detector Provider seam above is the plug point).
|
|
73
87
|
- `scope: tools` — implemented as `tools/post-execute` result-content masking. Tool-argument rewriting is deliberately NOT offered upstream: `tools/pre-execute`'s `PreToolDecision` has no input rewrite because logged/rendered arguments must match what ran, so `tools` scope masks the other model-visible tool surface (the result content) instead of the arguments.
|
|
74
88
|
- A browser half would consume the restore table to transparently un-mask assistant bubbles; the host-side restore surface (`/mask restore` + `RestoreStore.restore`) ships, and `maskClientEnabled` (default false) is the key reserved for that browser slot pending live slot-catalog verification. The key is declared in the schema and validated at load, but no runtime code reads it yet, so it has no effect until the browser half ships.
|
|
89
|
+
- **A no-argument `/mask restore`** (restore every placeholder of the most recent assistant message) is deliberately not implemented. Two host facts block it: the restore table is a flat per-session `{placeholder: original}` map with **no per-message index**, so "the last assistant message" has to be located in the session event log; and the host deprecated `Session.snapshotEvents()` / `eventAt()` / `ownEvents()` with an explicit "new calls are prohibited" (`deepseek-harness/.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md`), whose sanctioned alternative — keep a projection incrementally from delivered events — is not available across this plugin's declared host corridor (`>=0.1.2-rc.1`). Offering the form would mean shipping a prohibited synchronous read or a host-version-dependent projection seam, so the form is documented as unavailable and `/mask restore` stays text-only (its error text says so).
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.2.22] - 2026-10-18
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- Add a 1280×720 hero and a 960×540, 4-second terminal GIF rendered from the test run; `screenshots.json` is an object array and `capture.json` records the command.
|
|
8
|
+
|
|
3
9
|
All notable changes to this project are documented in this file.
|
|
4
10
|
|
|
5
11
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
@@ -26,6 +32,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
26
32
|
|
|
27
33
|
## [Unreleased]
|
|
28
34
|
|
|
35
|
+
## [0.2.21] - 2026-10-17
|
|
36
|
+
|
|
37
|
+
### Fixed
|
|
38
|
+
|
|
39
|
+
- **`/mask restore` wrote the restored plaintext into the persistent session log.** The
|
|
40
|
+
host logs a command's result verbatim (`command/done.text`, typed as verbatim in
|
|
41
|
+
`@deepseek-ai/dsh-commands`), and the client renders the user-visible command outcome
|
|
42
|
+
from that same event, so the two channels cannot be separated: the result text *is* the
|
|
43
|
+
log. Every `/mask restore <PLACEHOLDER>` therefore persisted the un-masked PII it had
|
|
44
|
+
just revealed, which is precisely what this plugin exists to prevent (the README and
|
|
45
|
+
`ARCHITECTURE.md` both promised the plaintext never reaches the log, and the restore
|
|
46
|
+
table stayed the only plaintext store). The reveal now goes to a controlled file —
|
|
47
|
+
one per session under `restoreDir` (default `os.tmpdir()/dsh-mask-restore`), directory
|
|
48
|
+
`0700`, file `0600`, symlink and ownership checked, overwritten by the next restore —
|
|
49
|
+
and the command result carries only that path and the placeholder names it restored.
|
|
50
|
+
Both are non-PII by construction, so the result stays safe to log and render. Delivery
|
|
51
|
+
failure fails closed: an error result is returned and the plaintext is never echoed as a
|
|
52
|
+
fallback. `/mask` error texts now also pass through `redactText`, since they are logged
|
|
53
|
+
too. `restoreDir` joins the config surface; the manifest declares `filesystem:write`.
|
|
54
|
+
|
|
55
|
+
### Added
|
|
56
|
+
|
|
57
|
+
- `lib/deliver.mjs` (the controlled restore-delivery channel), `Stripper.placeholdersIn`
|
|
58
|
+
and `RestoreStore.restoreDetailed` (report which placeholders a restore matched without
|
|
59
|
+
handling the plaintext twice), and 32 tests covering the delivery path, the fail-closed
|
|
60
|
+
cases, and the "no plaintext in the command result" contract.
|
|
61
|
+
|
|
62
|
+
### Documentation
|
|
63
|
+
|
|
64
|
+
- `README.md` (+ the four translations), `ARCHITECTURE.md` and `cordis.patch.yml` record
|
|
65
|
+
the delivery channel and its reason, and the Known limitations now state why a
|
|
66
|
+
no-argument `/mask restore` (restore every placeholder of the last assistant message) is
|
|
67
|
+
not offered: the restore table has no per-message index, and locating that message needs a
|
|
68
|
+
synchronous session-history read the host prohibits for new callers.
|
|
69
|
+
|
|
29
70
|
## [0.2.18] - 2026-10-05
|
|
30
71
|
|
|
31
72
|
undefined
|
package/README-es.md
CHANGED
|
@@ -41,7 +41,7 @@ Middleware de enmascaramiento de PII para DeepSeek Harness: anonimiza los datos
|
|
|
41
41
|
|
|
42
42
|
Teléfonos, correos, documentos, tarjetas, claves y más se convierten en marcadores de posición en el límite del modelo; el texto plano nunca entra en tu registro de sesión.
|
|
43
43
|
|
|
44
|
-

|
|
45
45
|
|
|
46
46
|

|
|
47
47
|
|
|
@@ -69,13 +69,13 @@ Teléfonos, correos, documentos, tarjetas, claves y más se convierten en marcad
|
|
|
69
69
|
- **Enmascarado antes de la petición** — reescribe los mensajes de `agent/pre-step` para que teléfonos, correos, documentos, tarjetas, claves e IP (opt-in) se vuelvan marcadores como `<PHONE_1>`. El texto enmascarado es lo que se registra y se envía al modelo.
|
|
70
70
|
- **Tabla de restauración** — el mapa `marcador → original` vive solo en memoria y en un dominio de almacenamiento controlado (`dsh_mask`); el texto plano nunca entra en el registro de sesión.
|
|
71
71
|
- **Auditoría sin texto plano** — el evento `mask/applied` solo registra «N valores reemplazados + distribución por tipo».
|
|
72
|
-
- **Comando `/mask`** — `status`, `on`/`off`, `restore <text
|
|
72
|
+
- **Comando `/mask`** — `status`, `on`/`off`, `restore <text>` (desmapea marcadores y entrega el texto plano como archivo, nunca como texto registrable), `help`.
|
|
73
73
|
- **Herramienta `mask_test`** — prueba un fragmento y ve el resultado con marcadores; nunca revela los valores originales.
|
|
74
74
|
|
|
75
75
|
```text
|
|
76
|
-
mensaje de usuario ──agent/pre-step──▶ marcadores ──modelo──▶ marcadores ──restore──▶
|
|
77
|
-
▲
|
|
78
|
-
└──── tabla de restauración (memoria + dsh_mask)
|
|
76
|
+
mensaje de usuario ──agent/pre-step──▶ marcadores ──modelo──▶ marcadores ──restore──▶ archivo controlado
|
|
77
|
+
▲ │
|
|
78
|
+
└──── tabla de restauración (memoria + dsh_mask) ──┘
|
|
79
79
|
```
|
|
80
80
|
|
|
81
81
|
## Quick start
|
|
@@ -102,6 +102,8 @@ dsh --profile web --dump-config | grep -A2 'id: mask'
|
|
|
102
102
|
```
|
|
103
103
|
> /mask status
|
|
104
104
|
> /mask restore <PHONE_1>
|
|
105
|
+
mask: restored 1 placeholder(s): <PHONE_1>
|
|
106
|
+
file: /tmp/dsh-mask-restore/restore-1f0c….txt (mode 0600, one file per session)
|
|
105
107
|
```
|
|
106
108
|
|
|
107
109
|
## Install & uninstall
|
|
@@ -128,6 +130,7 @@ Todas las opciones son campos Schemastery `Config` (modificables desde cordis.ym
|
|
|
128
130
|
| `persistRestoreTable` | `true` | Persiste la tabla en el dominio `dsh_mask` |
|
|
129
131
|
| `maxRestoreEntriesPerSession` | `500` | Tope de entradas por sesión |
|
|
130
132
|
| `maxSessions` | `1000` | Tope de sesiones en memoria |
|
|
133
|
+
| `restoreDir` | `''` | Dónde entrega `/mask restore` el texto plano. Vacío = `os.tmpdir()/dsh-mask-restore`; un valor relativo se resuelve contra el cwd del proceso host. El directorio se crea `0700` y el archivo se escribe `0600`, uno por sesión |
|
|
131
134
|
|
|
132
135
|
## Tools & surfaces
|
|
133
136
|
|
|
@@ -136,20 +139,20 @@ Todas las opciones son campos Schemastery `Config` (modificables desde cordis.ym
|
|
|
136
139
|
| Enmascarado `agent/pre-step` | nunca | Reescribe mensajes a marcadores |
|
|
137
140
|
| `/mask status` | nunca | Estado, total reemplazado, distribución |
|
|
138
141
|
| `/mask on` / `/mask off` | nunca | Alternancia en tiempo de ejecución |
|
|
139
|
-
| `/mask restore <text>` | sí (explícito) | Desmapea marcadores a los valores de esta sesión |
|
|
142
|
+
| `/mask restore <text>` | sí (explícito) | Desmapea marcadores a los valores de esta sesión y los escribe en un archivo controlado (uno por sesión, modo `0600`); el texto del resultado y el registro de sesión solo llevan esa ruta y los nombres de los marcadores |
|
|
140
143
|
| `mask_test` | nunca | Enmascara un fragmento y reporta el resultado |
|
|
141
144
|
|
|
142
145
|
## Permissions & data
|
|
143
146
|
|
|
144
|
-
- **Permisos**: sin red, sin credenciales (`network:none`, `credentials:none`).
|
|
145
|
-
- **Datos**: la tabla `marcador → original` vive en memoria y, con `persistRestoreTable: true`, en el dominio `dsh_mask`; nunca en el registro de sesión.
|
|
147
|
+
- **Permisos**: sin red, sin credenciales (`network:none`, `credentials:none`). El manifest declara `filesystem:write` por el archivo de entrega de `/mask restore`.
|
|
148
|
+
- **Datos**: la tabla `marcador → original` vive en memoria y, con `persistRestoreTable: true`, en el dominio `dsh_mask`; nunca en el registro de sesión. La única otra copia en texto plano es el archivo de entrega que escribe un `/mask restore` explícito (`restoreDir`, modo `0600`, uno por sesión, sobrescrito por la siguiente restauración); nada escribe texto plano en disco de forma implícita.
|
|
146
149
|
- **Registro de sesión**: `mask/applied` se declara en `types.d.ts` y se añade solo cuando el host registra el tipo.
|
|
147
150
|
|
|
148
151
|
## Security boundaries
|
|
149
152
|
|
|
150
|
-
- **El texto plano nunca entra en el registro de sesión.** Lo registrado y enviado es la forma enmascarada; los originales quedan en la tabla de restauración.
|
|
151
|
-
- **Sanitizar antes de mostrar/registrar.** `lib/sanitize.mjs` redacta PII, secretos y credenciales de URL.
|
|
152
|
-
- **Restauración controlada.** `/mask restore` es la única superficie de revelado explícita.
|
|
153
|
+
- **El texto plano nunca entra en el registro de sesión.** Lo registrado y enviado es la forma enmascarada; los originales quedan en la tabla de restauración. La misma regla rige el revelado: el host registra el texto del resultado de un comando **literalmente** y lo usa para renderizar la salida visible, así que `/mask restore` escribe el texto plano en un archivo controlado y solo devuelve la ruta.
|
|
154
|
+
- **Sanitizar antes de mostrar/registrar.** `lib/sanitize.mjs` redacta PII, secretos y credenciales de URL; `mask_test`, `/mask status` y todas las rutas de error de `/mask` nunca muestran originales.
|
|
155
|
+
- **Restauración controlada.** `/mask restore` es la única superficie de revelado explícita. Si falla la entrega, falla cerrado: un error, nunca un respaldo que muestre el texto plano.
|
|
153
156
|
- **Fallo cerrado.** `mode`/`scope`/entidades no implementados y números fuera de rango fallan al cargar.
|
|
154
157
|
- **Registros como efectos.** Listener, comando, herramienta y cierre de dominio son efectos Cordis.
|
|
155
158
|
|
|
@@ -157,7 +160,8 @@ Todas las opciones son campos Schemastery `Config` (modificables desde cordis.ym
|
|
|
157
160
|
|
|
158
161
|
- **Solo regex.** `person` y `address` requieren un reconocedor NER externo; fallan al cargar. Cubierto de serie: teléfono, correo, documento, tarjeta, clave e IP (opt-in).
|
|
159
162
|
- **Patrones específicos de región.** Los detectores `phone` e `id-card` solo reconocen formatos de China continental: `phone` es `1[3-9]` seguido de nueve dígitos, e `id-card` es un documento de residente chino de 18 caracteres (17 dígitos más un dígito o `X`). Los teléfonos y documentos de otros países no se detectan. `email`, `ip` y `key` no dependen de la región; `bank-card` acepta cualquier secuencia de 16-19 dígitos con menor confianza.
|
|
160
|
-
- **La restauración visual necesita una mitad de cliente.** Enmascarar es host-side; desenmascarar burbujas en la UI es una función de navegador que esta forma host puro no incluye. El host conserva la tabla y el seam `RestoreStore` exportado (sus métodos piden un id de sesión), así que una futura mitad de cliente debe consumirlos mediante un remoto del host, no directamente; hoy la superficie de desenmascarado es el comando `/mask restore <text>`, y la clave `maskClientEnabled` se declara y valida pero ningún código en ejecución la lee todavía.
|
|
163
|
+
- **La restauración visual necesita una mitad de cliente.** Enmascarar es host-side; desenmascarar burbujas en la UI es una función de navegador que esta forma host puro no incluye. El host conserva la tabla y el seam `RestoreStore` exportado (sus métodos piden un id de sesión), así que una futura mitad de cliente debe consumirlos mediante un remoto del host, no directamente; hoy la superficie de desenmascarado es el comando `/mask restore <text>`, que entrega el texto plano como archivo porque el resultado de un comando se registra literalmente, y la clave `maskClientEnabled` se declara y valida pero ningún código en ejecución la lee todavía.
|
|
164
|
+
- **No hay `/mask restore` sin argumentos.** Restaurar *todos* los marcadores del último mensaje del asistente no se ofrece, y el comando lo dice si se invoca sin texto. Dos hechos del host lo impiden: la tabla de restauración es un mapa plano `{marcador: original}` por sesión, **sin índice por mensaje**, así que ese mensaje hay que localizarlo en el registro de eventos de la sesión; y el host marcó `Session.snapshotEvents()` / `eventAt()` / `ownEvents()` como obsoletos con un «prohibido llamarlos desde código nuevo», y la única alternativa sancionada (mantener una proyección incremental) no es fiable en el corredor de hosts declarado (`>=0.1.2-rc.1`). Los marcadores siguen restaurándose de uno en uno: `/mask restore <PHONE_1>`.
|
|
161
165
|
- **Eventos en `0.1.7-rc.2`.** El host registra 59 tipos de evento de sesión y ninguno es `mask/*`; su `Session.append` tampoco puede estampar el sobre `ignorable`, así que los appends de auditoría se omiten (las sesiones siguen cargando). La puerta no es silenciosa: la primera negativa de cada sesión registra un aviso visible con el tipo omitido y esta limitación documentada. El append se habilita automáticamente cuando un host registra el tipo o admite el sobre `ignorable`.
|
|
162
166
|
|
|
163
167
|
## Development
|
|
@@ -207,7 +211,7 @@ Evidencia estática: `dsh-plugin-doctor` K10–K13 dan `pass` en todas las compr
|
|
|
207
211
|
|
|
208
212
|
## PerryLink DSH Plugin Family
|
|
209
213
|
|
|
210
|
-
Este proyecto es uno de los **
|
|
214
|
+
Este proyecto es uno de los **34 plugins activamente mantenidos** de DeepSeek Harness de [PerryLink](https://github.com/PerryLink): el registro tiene **42**, de los cuales **5** están congelados y **3** retirados; cada uno conserva su fila abajo, con el motivo en la columna Estado. Si este te ayuda, probablemente los demás también:
|
|
211
215
|
|
|
212
216
|
| Plugin | En una línea | Estado |
|
|
213
217
|
|---|---|---|
|
|
@@ -235,7 +239,7 @@ Este proyecto es uno de los **33 plugins activamente mantenidos** de DeepSeek Ha
|
|
|
235
239
|
| **[dsh-lsp-actions](https://github.com/PerryLink/dsh-lsp-actions)** | LSP diagnostics, formatting, completion, code actions and rename over language servers | |
|
|
236
240
|
| **[dsh-mask](https://github.com/PerryLink/dsh-mask)** | PII masking middleware: anonymize at the model boundary, restore at the display layer | |
|
|
237
241
|
| **[dsh-mcp-panel](https://github.com/PerryLink/dsh-mcp-panel)** | Read-only MCP runtime panel: /mcp command + Settings tab with status, tools and errors | |
|
|
238
|
-
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool |
|
|
242
|
+
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool | |
|
|
239
243
|
| **[dsh-observe](https://github.com/PerryLink/dsh-observe)** | OpenTelemetry and Langfuse observability exporter for DeepSeek Harness. | |
|
|
240
244
|
| **[dsh-output-styles](https://github.com/PerryLink/dsh-output-styles)** | Claude Code outputStyles-equivalent runtime style switching | |
|
|
241
245
|
| **[dsh-permission-rules](https://github.com/PerryLink/dsh-permission-rules)** | Claude Code-style declarative allow/deny/ask permission rules with audit | |
|
package/README-hi.md
CHANGED
|
@@ -41,7 +41,7 @@ DeepSeek Harness के लिए PII मास्किंग मिडलव
|
|
|
41
41
|
|
|
42
42
|
फ़ोन, ईमेल, आईडी कार्ड, बैंक कार्ड, कुंजियाँ आदि मॉडल सीमा पर प्लेसहोल्डर बन जाते हैं; मूल पाठ आपके सत्र लॉग में कभी नहीं जाता।
|
|
43
43
|
|
|
44
|
-

|
|
45
45
|
|
|
46
46
|

|
|
47
47
|
|
|
@@ -69,13 +69,13 @@ DeepSeek Harness के लिए PII मास्किंग मिडलव
|
|
|
69
69
|
- **अनुरोध से पहले मास्किंग** — `agent/pre-step` संदेशों को फिर से लिखता है ताकि फ़ोन, ईमेल, आईडी कार्ड, बैंक कार्ड, कुंजियाँ और IP (opt-in) `<PHONE_1>` जैसे प्लेसहोल्डर बन जाएँ। मास्क किया हुआ पाठ ही लॉग होता है और मॉडल को जाता है।
|
|
70
70
|
- **पुनर्स्थापना तालिका** — `प्लेसहोल्डर → मूल` नक्शा केवल मेमोरी और नियंत्रित स्टोरेज डोमेन (`dsh_mask`) में रहता है; मूल पाठ सत्र लॉग में कभी नहीं जाता।
|
|
71
71
|
- **बिना मूल पाठ की ऑडिट** — `mask/applied` इवेंट केवल «N मान बदले + प्रकार-वितरण» दर्ज करता है।
|
|
72
|
-
- **`/mask` कमांड** — `status`, `on`/`off`, `restore <text
|
|
72
|
+
- **`/mask` कमांड** — `status`, `on`/`off`, `restore <text>` (प्लेसहोल्डर वापस मूल में बदलकर मूल पाठ को फ़ाइल के रूप में सौंपता है, लॉग होने योग्य पाठ के रूप में कभी नहीं), `help`।
|
|
73
73
|
- **`mask_test` टूल** — एक अंश चलाकर प्लेसहोल्डर परिणाम देखें; मूल मान कभी नहीं दिखाता।
|
|
74
74
|
|
|
75
75
|
```text
|
|
76
|
-
उपयोगकर्ता संदेश ──agent/pre-step──▶ प्लेसहोल्डर ──मॉडल──▶ प्लेसहोल्डर ──restore──▶
|
|
77
|
-
|
|
78
|
-
|
|
76
|
+
उपयोगकर्ता संदेश ──agent/pre-step──▶ प्लेसहोल्डर ──मॉडल──▶ प्लेसहोल्डर ──restore──▶ नियंत्रित फ़ाइल
|
|
77
|
+
▲ │
|
|
78
|
+
└──── पुनर्स्थापना तालिका (मेमोरी + dsh_mask) ────────┘
|
|
79
79
|
```
|
|
80
80
|
|
|
81
81
|
## Quick start
|
|
@@ -102,6 +102,8 @@ dsh --profile web --dump-config | grep -A2 'id: mask'
|
|
|
102
102
|
```
|
|
103
103
|
> /mask status
|
|
104
104
|
> /mask restore <PHONE_1>
|
|
105
|
+
mask: restored 1 placeholder(s): <PHONE_1>
|
|
106
|
+
file: /tmp/dsh-mask-restore/restore-1f0c….txt (mode 0600, one file per session)
|
|
105
107
|
```
|
|
106
108
|
|
|
107
109
|
## Install & uninstall
|
|
@@ -128,6 +130,7 @@ dsh --profile web --dump-config | grep -A2 'id: mask'
|
|
|
128
130
|
| `persistRestoreTable` | `true` | तालिका को `dsh_mask` डोमेन में सहेजें |
|
|
129
131
|
| `maxRestoreEntriesPerSession` | `500` | प्रति सत्र प्रविष्टि सीमा |
|
|
130
132
|
| `maxSessions` | `1000` | मेमोरी में सत्र सीमा |
|
|
133
|
+
| `restoreDir` | `''` | `/mask restore` मूल पाठ कहाँ सौंपता है। खाली = `os.tmpdir()/dsh-mask-restore`; सापेक्ष मान host प्रक्रिया के cwd के सापेक्ष हल होता है। डायरेक्टरी `0700` पर बनती है और फ़ाइल `0600` पर लिखी जाती है, प्रति सत्र एक |
|
|
131
134
|
|
|
132
135
|
## Tools & surfaces
|
|
133
136
|
|
|
@@ -136,20 +139,20 @@ dsh --profile web --dump-config | grep -A2 'id: mask'
|
|
|
136
139
|
| `agent/pre-step` मास्किंग | कभी नहीं | संदेशों को प्लेसहोल्डर में बदलता है |
|
|
137
140
|
| `/mask status` | कभी नहीं | स्थिति, कुल बदले, वितरण |
|
|
138
141
|
| `/mask on` / `/mask off` | कभी नहीं | रनटाइम टॉगल |
|
|
139
|
-
| `/mask restore <text>` | हाँ (स्पष्ट) | प्लेसहोल्डर को इस सत्र के मानों में
|
|
142
|
+
| `/mask restore <text>` | हाँ (स्पष्ट) | प्लेसहोल्डर को इस सत्र के मानों में बदलकर नियंत्रित फ़ाइल में लिखता है (प्रति सत्र एक, mode `0600`); परिणाम पाठ और सत्र लॉग में केवल वह पथ और प्लेसहोल्डर नाम जाते हैं |
|
|
140
143
|
| `mask_test` | कभी नहीं | अंश को मास्क कर परिणाम देता है |
|
|
141
144
|
|
|
142
145
|
## Permissions & data
|
|
143
146
|
|
|
144
|
-
- **अनुमतियाँ**: कोई नेटवर्क नहीं, कोई क्रेडेंशियल नहीं (`network:none`, `credentials:none`)।
|
|
145
|
-
- **डेटा**: `प्लेसहोल्डर → मूल` तालिका मेमोरी में और, `persistRestoreTable: true` होने पर, `dsh_mask` डोमेन में रहती है; सत्र लॉग में कभी नहीं।
|
|
147
|
+
- **अनुमतियाँ**: कोई नेटवर्क नहीं, कोई क्रेडेंशियल नहीं (`network:none`, `credentials:none`)। manifest `/mask restore` की डिलीवरी फ़ाइल के लिए `filesystem:write` घोषित करता है।
|
|
148
|
+
- **डेटा**: `प्लेसहोल्डर → मूल` तालिका मेमोरी में और, `persistRestoreTable: true` होने पर, `dsh_mask` डोमेन में रहती है; सत्र लॉग में कभी नहीं। एकमात्र अन्य मूल-पाठ प्रति वह डिलीवरी फ़ाइल है जो स्पष्ट `/mask restore` लिखता है (`restoreDir`, mode `0600`, प्रति सत्र एक, अगली पुनर्स्थापना उसे ओवरराइट करती है); कोई भी पथ चुपचाप मूल पाठ डिस्क पर नहीं लिखता।
|
|
146
149
|
- **सत्र लॉग**: `mask/applied` `types.d.ts` में घोषित है और केवल तब जोड़ा जाता है जब host प्रकार दर्ज करे।
|
|
147
150
|
|
|
148
151
|
## Security boundaries
|
|
149
152
|
|
|
150
|
-
- **मूल पाठ सत्र लॉग में कभी नहीं जाता।** लॉग और मॉडल को मास्क रूप ही जाता है; मूल तालिका में रहते हैं।
|
|
151
|
-
- **दिखाने/लॉग से पहले सैनिटाइज़।** `lib/sanitize.mjs` PII, रहस्य और URL क्रेडेंशियल हटाता
|
|
152
|
-
- **नियंत्रित पुनर्स्थापना।** `/mask restore` एकमात्र स्पष्ट प्रकटीकरण सतह है।
|
|
153
|
+
- **मूल पाठ सत्र लॉग में कभी नहीं जाता।** लॉग और मॉडल को मास्क रूप ही जाता है; मूल तालिका में रहते हैं। यही नियम प्रकटीकरण पर भी लागू है: host कमांड के परिणाम पाठ को **शब्दशः** लॉग करता है और उसी इवेंट से दृश्य आउटपुट बनाता है, इसलिए `/mask restore` मूल पाठ को नियंत्रित फ़ाइल में लिखता है और केवल पथ लौटाता है।
|
|
154
|
+
- **दिखाने/लॉग से पहले सैनिटाइज़।** `lib/sanitize.mjs` PII, रहस्य और URL क्रेडेंशियल हटाता है; `mask_test`, `/mask status` और `/mask` के सभी त्रुटि पथ मूल कभी नहीं दिखाते।
|
|
155
|
+
- **नियंत्रित पुनर्स्थापना।** `/mask restore` एकमात्र स्पष्ट प्रकटीकरण सतह है। डिलीवरी विफल हो तो फेल क्लोज़्ड: त्रुटि, मूल पाठ दिखाने वाला fallback कभी नहीं।
|
|
153
156
|
- **फेल क्लोज़्ड।** अलागू `mode`/`scope`/इकाइयाँ और सीमा से बाहर संख्याएँ लोड पर विफल होती हैं।
|
|
154
157
|
- **पंजीकरण प्रभाव हैं।** listener, कमांड, टूल और डोमेन-बंद सभी Cordis effects हैं।
|
|
155
158
|
|
|
@@ -157,7 +160,8 @@ dsh --profile web --dump-config | grep -A2 'id: mask'
|
|
|
157
160
|
|
|
158
161
|
- **केवल regex।** `person` और `address` को बाहरी NER पहचानकर्ता चाहिए; लोड पर विफल। बॉक्स में: फ़ोन, ईमेल, आईडी कार्ड, बैंक कार्ड, कुंजी और IP (opt-in)।
|
|
159
162
|
- **क्षेत्र-विशिष्ट पैटर्न।** `phone` और `id-card` डिटेक्टर केवल मुख्य भूमि चीन के प्रारूप पहचानते हैं: `phone` = `1[3-9]` के बाद नौ अंक, और `id-card` = 18 वर्णों वाला चीनी निवासी आईडी (17 अंक और एक अंक या `X`)। अन्य देशों के फ़ोन नंबर और राष्ट्रीय पहचान पत्र नहीं पकड़े जाते। `email`, `ip` और `key` क्षेत्र-निरपेक्ष हैं; `bank-card` किसी भी 16-19 अंकों की श्रृंखला को कम विश्वास के साथ स्वीकार करता है।
|
|
160
|
-
- **डिस्प्ले-लेयर पुनर्स्थापना को क्लाइंट आधा चाहिए।** मास्किंग host-side है; UI बुलबुलों को खोलना एक ब्राउज़र-आधा सुविधा है जो यह शुद्ध-host रूप नहीं देता। host तालिका और निर्यातित `RestoreStore` seam रखता है (उसके मेथड को session id चाहिए), इसलिए भविष्य का क्लाइंट आधा उन्हें host remote से लेगा, सीधे नहीं; आज अनमास्किंग का सतह `/mask restore <text>` कमांड है, और `maskClientEnabled` कुंजी schema में घोषित व मान्य होती है पर अभी कोई रनटाइम कोड उसे नहीं पढ़ता।
|
|
163
|
+
- **डिस्प्ले-लेयर पुनर्स्थापना को क्लाइंट आधा चाहिए।** मास्किंग host-side है; UI बुलबुलों को खोलना एक ब्राउज़र-आधा सुविधा है जो यह शुद्ध-host रूप नहीं देता। host तालिका और निर्यातित `RestoreStore` seam रखता है (उसके मेथड को session id चाहिए), इसलिए भविष्य का क्लाइंट आधा उन्हें host remote से लेगा, सीधे नहीं; आज अनमास्किंग का सतह `/mask restore <text>` कमांड है, जो मूल पाठ फ़ाइल के रूप में सौंपता है क्योंकि कमांड परिणाम शब्दशः लॉग होता है, और `maskClientEnabled` कुंजी schema में घोषित व मान्य होती है पर अभी कोई रनटाइम कोड उसे नहीं पढ़ता।
|
|
164
|
+
- **बिना आर्ग्युमेंट `/mask restore` नहीं है।** अंतिम assistant संदेश के *सभी* प्लेसहोल्डर वापस लाना उपलब्ध नहीं है, और बिना पाठ के चलाने पर कमांड यह बता देता है। दो host तथ्य इसे रोकते हैं: पुनर्स्थापना तालिका प्रति सत्र सपाट `{प्लेसहोल्डर: मूल}` नक्शा है, जिसमें **संदेश-वार सूचकांक नहीं** है, इसलिए वह संदेश सत्र इवेंट लॉग में खोजना पड़ता है; और host ने `Session.snapshotEvents()` / `eventAt()` / `ownEvents()` को deprecated कर दिया है और नए कॉलर के लिए मना किया है, जबकि उसका एकमात्र स्वीकृत विकल्प (इवेंट से इंक्रीमेंटल प्रोजेक्शन) इस प्लगइन के घोषित host corridor (`>=0.1.2-rc.1`) पर भरोसेमंद नहीं है। प्लेसहोल्डर एक-एक करके वापस लाए जा सकते हैं: `/mask restore <PHONE_1>`।
|
|
161
165
|
- **`0.1.7-rc.2` पर इवेंट।** host 59 सत्र-इवेंट प्रकार दर्ज करता है और उनमें `mask/*` नहीं है; उसका `Session.append` `ignorable` लिफ़ाफ़ा भी नहीं लगा सकता, इसलिए ऑडिट appends छोड़े जाते हैं (सत्र लोड होते रहते हैं)। गेट मौन नहीं है: प्रत्येक सत्र की पहली अस्वीकृति पर छोड़े गए प्रकार और इस प्रलेखित सीमा के साथ एक दृश्य चेतावनी दर्ज होती है। जब host प्रकार दर्ज करे या `ignorable` लिफ़ाफ़ा स्वीकार करे, append स्वतः सक्षम हो जाता है।
|
|
162
166
|
|
|
163
167
|
## Development
|
|
@@ -207,7 +211,7 @@ PII बेंचमार्क (108 सिंथेटिक नमूनों
|
|
|
207
211
|
|
|
208
212
|
## PerryLink DSH Plugin Family
|
|
209
213
|
|
|
210
|
-
यह प्रोजेक्ट [PerryLink](https://github.com/PerryLink) के DeepSeek Harness प्लगइन परिवार का हिस्सा है — **
|
|
214
|
+
यह प्रोजेक्ट [PerryLink](https://github.com/PerryLink) के DeepSeek Harness प्लगइन परिवार का हिस्सा है — **34 सक्रिय रूप से अनुरक्षित**, कुल सूची **42** है जिसमें **5 फ़्रोज़न** और **3 सेवानिवृत्त** हैं; हर एक की पंक्ति नीचे बनी रहती है, कारण “स्थिति” कॉलम में है। अगर यह उपयोगी लगे, तो अन्य भी मददगार होंगे:
|
|
211
215
|
|
|
212
216
|
| Plugin | एक पंक्ति में | स्थिति |
|
|
213
217
|
|---|---|---|
|
|
@@ -235,7 +239,7 @@ PII बेंचमार्क (108 सिंथेटिक नमूनों
|
|
|
235
239
|
| **[dsh-lsp-actions](https://github.com/PerryLink/dsh-lsp-actions)** | LSP diagnostics, formatting, completion, code actions and rename over language servers | |
|
|
236
240
|
| **[dsh-mask](https://github.com/PerryLink/dsh-mask)** | PII masking middleware: anonymize at the model boundary, restore at the display layer | |
|
|
237
241
|
| **[dsh-mcp-panel](https://github.com/PerryLink/dsh-mcp-panel)** | Read-only MCP runtime panel: /mcp command + Settings tab with status, tools and errors | |
|
|
238
|
-
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool |
|
|
242
|
+
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool | |
|
|
239
243
|
| **[dsh-observe](https://github.com/PerryLink/dsh-observe)** | OpenTelemetry and Langfuse observability exporter for DeepSeek Harness. | |
|
|
240
244
|
| **[dsh-output-styles](https://github.com/PerryLink/dsh-output-styles)** | Claude Code outputStyles-equivalent runtime style switching | |
|
|
241
245
|
| **[dsh-permission-rules](https://github.com/PerryLink/dsh-permission-rules)** | Claude Code-style declarative allow/deny/ask permission rules with audit | |
|
package/README-pt.md
CHANGED
|
@@ -41,7 +41,7 @@ Middleware de mascaramento de PII para o DeepSeek Harness: anonimize dados pesso
|
|
|
41
41
|
|
|
42
42
|
Telefones, e-mails, documentos, cartões, chaves e mais viram marcadores no limite do modelo; o texto simples nunca entra no seu registro de sessão.
|
|
43
43
|
|
|
44
|
-

|
|
45
45
|
|
|
46
46
|

|
|
47
47
|
|
|
@@ -69,13 +69,13 @@ O `dsh-mask` anonimiza dados pessoais **no limite do modelo** e mantém uma tabe
|
|
|
69
69
|
- **Mascaramento antes da requisição** — reescreve mensagens de `agent/pre-step` para que telefones, e-mails, documentos, cartões, chaves e IPs (opt-in) virem marcadores como `<PHONE_1>`. O texto mascarado é o que é registrado e enviado ao modelo.
|
|
70
70
|
- **Tabela de restauração** — o mapa `marcador → original` vive só em memória e num domínio de armazenamento controlado (`dsh_mask`); o texto simples nunca entra no registro de sessão.
|
|
71
71
|
- **Auditoria sem texto simples** — o evento `mask/applied` registra apenas «N valores substituídos + distribuição por tipo».
|
|
72
|
-
- **Comando `/mask`** — `status`, `on`/`off`, `restore <text
|
|
72
|
+
- **Comando `/mask`** — `status`, `on`/`off`, `restore <text>` (desmapeia marcadores e entrega o texto simples como arquivo, nunca como texto registrável), `help`.
|
|
73
73
|
- **Ferramenta `mask_test`** — teste um trecho e veja o resultado com marcadores; nunca revela os originais.
|
|
74
74
|
|
|
75
75
|
```text
|
|
76
|
-
mensagem do usuário ──agent/pre-step──▶ marcadores ──modelo──▶ marcadores ──restore──▶
|
|
77
|
-
▲
|
|
78
|
-
└──── tabela de restauração (memória + dsh_mask)
|
|
76
|
+
mensagem do usuário ──agent/pre-step──▶ marcadores ──modelo──▶ marcadores ──restore──▶ arquivo controlado
|
|
77
|
+
▲ │
|
|
78
|
+
└──── tabela de restauração (memória + dsh_mask) ──┘
|
|
79
79
|
```
|
|
80
80
|
|
|
81
81
|
## Quick start
|
|
@@ -102,6 +102,8 @@ dsh --profile web --dump-config | grep -A2 'id: mask'
|
|
|
102
102
|
```
|
|
103
103
|
> /mask status
|
|
104
104
|
> /mask restore <PHONE_1>
|
|
105
|
+
mask: restored 1 placeholder(s): <PHONE_1>
|
|
106
|
+
file: /tmp/dsh-mask-restore/restore-1f0c….txt (mode 0600, one file per session)
|
|
105
107
|
```
|
|
106
108
|
|
|
107
109
|
## Install & uninstall
|
|
@@ -128,6 +130,7 @@ Todas as opções são campos Schemastery `Config` (alteráveis via cordis.yml).
|
|
|
128
130
|
| `persistRestoreTable` | `true` | Persiste a tabela no domínio `dsh_mask` |
|
|
129
131
|
| `maxRestoreEntriesPerSession` | `500` | Limite de entradas por sessão |
|
|
130
132
|
| `maxSessions` | `1000` | Limite de sessões em memória |
|
|
133
|
+
| `restoreDir` | `''` | Onde o `/mask restore` entrega o texto simples. Vazio = `os.tmpdir()/dsh-mask-restore`; um valor relativo é resolvido contra o cwd do processo host. O diretório é criado `0700` e o arquivo escrito `0600`, um por sessão |
|
|
131
134
|
|
|
132
135
|
## Tools & surfaces
|
|
133
136
|
|
|
@@ -136,20 +139,20 @@ Todas as opções são campos Schemastery `Config` (alteráveis via cordis.yml).
|
|
|
136
139
|
| Mascaramento `agent/pre-step` | nunca | Reescreve mensagens para marcadores |
|
|
137
140
|
| `/mask status` | nunca | Estado, total substituído, distribuição |
|
|
138
141
|
| `/mask on` / `/mask off` | nunca | Alternância em tempo de execução |
|
|
139
|
-
| `/mask restore <text>` | sim (explícito) | Desmapeia marcadores para os valores desta sessão |
|
|
142
|
+
| `/mask restore <text>` | sim (explícito) | Desmapeia marcadores para os valores desta sessão e os escreve num arquivo controlado (um por sessão, modo `0600`); o texto do resultado e o registro de sessão levam apenas esse caminho e os nomes dos marcadores |
|
|
140
143
|
| `mask_test` | nunca | Mascara um trecho e reporta o resultado |
|
|
141
144
|
|
|
142
145
|
## Permissions & data
|
|
143
146
|
|
|
144
|
-
- **Permissões**: sem rede, sem credenciais (`network:none`, `credentials:none`).
|
|
145
|
-
- **Dados**: a tabela `marcador → original` vive em memória e, com `persistRestoreTable: true`, no domínio `dsh_mask`; nunca no registro de sessão.
|
|
147
|
+
- **Permissões**: sem rede, sem credenciais (`network:none`, `credentials:none`). O manifest declara `filesystem:write` por causa do arquivo de entrega do `/mask restore`.
|
|
148
|
+
- **Dados**: a tabela `marcador → original` vive em memória e, com `persistRestoreTable: true`, no domínio `dsh_mask`; nunca no registro de sessão. A única outra cópia em texto simples é o arquivo de entrega que um `/mask restore` explícito escreve (`restoreDir`, modo `0600`, um por sessão, sobrescrito pela próxima restauração); nada escreve texto simples em disco de forma implícita.
|
|
146
149
|
- **Registro de sessão**: `mask/applied` é declarado em `types.d.ts` e anexado só quando o host registra o tipo.
|
|
147
150
|
|
|
148
151
|
## Security boundaries
|
|
149
152
|
|
|
150
|
-
- **Texto simples nunca entra no registro de sessão.** O registrado e enviado é a forma mascarada; os originais ficam na tabela.
|
|
151
|
-
- **Sanitizar antes de exibir/registrar.** `lib/sanitize.mjs` redige PII, segredos e credenciais de URL.
|
|
152
|
-
- **Restauração controlada.** `/mask restore` é a única superfície de revelação explícita.
|
|
153
|
+
- **Texto simples nunca entra no registro de sessão.** O registrado e enviado é a forma mascarada; os originais ficam na tabela. A mesma regra vale para a revelação: o host registra o texto do resultado de um comando **literalmente** e o usa para renderizar a saída visível, então `/mask restore` escreve o texto simples num arquivo controlado e devolve apenas o caminho.
|
|
154
|
+
- **Sanitizar antes de exibir/registrar.** `lib/sanitize.mjs` redige PII, segredos e credenciais de URL; `mask_test`, `/mask status` e todos os caminhos de erro do `/mask` nunca exibem originais.
|
|
155
|
+
- **Restauração controlada.** `/mask restore` é a única superfície de revelação explícita. Se a entrega falhar, falha fechado: um erro, nunca um fallback que exiba o texto simples.
|
|
153
156
|
- **Falha fechada.** `mode`/`scope`/entidades não implementados e números fora de faixa falham ao carregar.
|
|
154
157
|
- **Registros como efeitos.** Listener, comando, ferramenta e fechamento de domínio são efeitos Cordis.
|
|
155
158
|
|
|
@@ -157,7 +160,8 @@ Todas as opções são campos Schemastery `Config` (alteráveis via cordis.yml).
|
|
|
157
160
|
|
|
158
161
|
- **Somente regex.** `person` e `address` exigem um reconhecedor NER externo; falham ao carregar. Coberto de série: telefone, e-mail, documento, cartão, chave e IP (opt-in).
|
|
159
162
|
- **Padrões específicos de região.** Os detectores `phone` e `id-card` reconhecem apenas formatos da China continental: `phone` é `1[3-9]` seguido de nove dígitos, e `id-card` é um documento de residente chinês de 18 caracteres (17 dígitos mais um dígito ou `X`). Telefones e documentos de outros países não são detectados. `email`, `ip` e `key` não dependem da região; `bank-card` aceita qualquer sequência de 16-19 dígitos com menor confiança.
|
|
160
|
-
- **A restauração visual precisa de uma metade de cliente.** Mascarar é host-side; desmascarar bolhas na UI é uma função de navegador que esta forma host puro não inclui. O host mantém a tabela e o seam `RestoreStore` exportado (seus métodos pedem um id de sessão), então uma futura metade de cliente precisa consumi-los por um remoto do host, não diretamente; hoje a superfície de desmascaramento é o comando `/mask restore <text>`, e a chave `maskClientEnabled` é declarada e validada mas nenhum código em execução a lê ainda.
|
|
163
|
+
- **A restauração visual precisa de uma metade de cliente.** Mascarar é host-side; desmascarar bolhas na UI é uma função de navegador que esta forma host puro não inclui. O host mantém a tabela e o seam `RestoreStore` exportado (seus métodos pedem um id de sessão), então uma futura metade de cliente precisa consumi-los por um remoto do host, não diretamente; hoje a superfície de desmascaramento é o comando `/mask restore <text>`, que entrega o texto simples como arquivo porque o resultado de um comando é registrado literalmente, e a chave `maskClientEnabled` é declarada e validada mas nenhum código em execução a lê ainda.
|
|
164
|
+
- **Não há `/mask restore` sem argumentos.** Restaurar *todos* os marcadores da última mensagem do assistente não é oferecido, e o comando diz isso quando invocado sem texto. Dois fatos do host impedem: a tabela de restauração é um mapa plano `{marcador: original}` por sessão, **sem índice por mensagem**, então essa mensagem precisa ser localizada no registro de eventos da sessão; e o host marcou `Session.snapshotEvents()` / `eventAt()` / `ownEvents()` como obsoletos com um «proibido para novos chamadores», e a única alternativa sancionada (manter uma projeção incremental) não é confiável no corredor de hosts declarado (`>=0.1.2-rc.1`). Os marcadores continuam sendo restaurados um a um: `/mask restore <PHONE_1>`.
|
|
161
165
|
- **Eventos em `0.1.7-rc.2`.** O host registra 59 tipos de evento de sessão e nenhum é `mask/*`; seu `Session.append` também não consegue estampar o envelope `ignorable`, então os appends de auditoria são omitidos (sessões continuam carregando). A porta não é silenciosa: a primeira recusa de cada sessão registra um aviso visível com o tipo omitido e esta limitação documentada. O append é habilitado automaticamente quando um host registra o tipo ou aceita o envelope `ignorable`.
|
|
162
166
|
|
|
163
167
|
## Development
|
|
@@ -207,7 +211,7 @@ Evidência estática: `dsh-plugin-doctor` K10–K13 retornam `pass` em todas as
|
|
|
207
211
|
|
|
208
212
|
## PerryLink DSH Plugin Family
|
|
209
213
|
|
|
210
|
-
Este projeto é um dos **
|
|
214
|
+
Este projeto é um dos **34 plugins ativamente mantidos** do DeepSeek Harness da [PerryLink](https://github.com/PerryLink): o registro tem **42**, dos quais **5** estão congelados e **3** aposentados; cada um mantém sua linha abaixo, com o motivo na coluna Status. Se este ajudou você, provavelmente os outros também ajudarão:
|
|
211
215
|
|
|
212
216
|
| Plugin | Em uma linha | Status |
|
|
213
217
|
|---|---|---|
|
|
@@ -235,7 +239,7 @@ Este projeto é um dos **33 plugins ativamente mantidos** do DeepSeek Harness da
|
|
|
235
239
|
| **[dsh-lsp-actions](https://github.com/PerryLink/dsh-lsp-actions)** | LSP diagnostics, formatting, completion, code actions and rename over language servers | |
|
|
236
240
|
| **[dsh-mask](https://github.com/PerryLink/dsh-mask)** | PII masking middleware: anonymize at the model boundary, restore at the display layer | |
|
|
237
241
|
| **[dsh-mcp-panel](https://github.com/PerryLink/dsh-mcp-panel)** | Read-only MCP runtime panel: /mcp command + Settings tab with status, tools and errors | |
|
|
238
|
-
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool |
|
|
242
|
+
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool | |
|
|
239
243
|
| **[dsh-observe](https://github.com/PerryLink/dsh-observe)** | OpenTelemetry and Langfuse observability exporter for DeepSeek Harness. | |
|
|
240
244
|
| **[dsh-output-styles](https://github.com/PerryLink/dsh-output-styles)** | Claude Code outputStyles-equivalent runtime style switching | |
|
|
241
245
|
| **[dsh-permission-rules](https://github.com/PerryLink/dsh-permission-rules)** | Claude Code-style declarative allow/deny/ask permission rules with audit | |
|
package/README-zh.md
CHANGED
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
|
|
42
42
|
电话、邮箱、身份证、银行卡、密钥等在模型边界变成占位符;原文绝不进入会话日志。
|
|
43
43
|
|
|
44
|
-

|
|
45
45
|
|
|
46
46
|

|
|
47
47
|
|
|
@@ -69,11 +69,11 @@
|
|
|
69
69
|
- **请求前遮罩** —— 重写 `agent/pre-step` 消息,使电话、邮箱、身份证、银行卡、密钥(默认开启)与 IP(可选)变成 `<PHONE_1>` 之类的占位符。被遮罩的文本才是落盘并发送给模型的内容。
|
|
70
70
|
- **恢复表** —— `占位符 → 原文` 映射只存内存与受控 storage domain(`dsh_mask`);原文绝不进会话日志。
|
|
71
71
|
- **审计不含明文** —— `mask/applied` 会话事件只记「替换了 N 处 + 类型分布」,不记原文与映射。
|
|
72
|
-
- **`/mask` 命令** —— `status`(计数 + 分布)、`on`/`off`(运行时开关)、`restore <text
|
|
72
|
+
- **`/mask` 命令** —— `status`(计数 + 分布)、`on`/`off`(运行时开关)、`restore <text>`(还原占位符,并把原文交付为文件而不是可落盘的文本)、`help`。
|
|
73
73
|
- **`mask_test` 工具** —— 试跑一段文本看替换效果;绝不回显原文。
|
|
74
74
|
|
|
75
75
|
```text
|
|
76
|
-
用户消息 ──agent/pre-step──▶ 占位符 ──模型──▶ 占位符 ──restore──▶
|
|
76
|
+
用户消息 ──agent/pre-step──▶ 占位符 ──模型──▶ 占位符 ──restore──▶ 受控文件
|
|
77
77
|
▲ │
|
|
78
78
|
└──── 恢复表(内存 + dsh_mask)──────────┘
|
|
79
79
|
```
|
|
@@ -108,6 +108,8 @@ dsh --profile web --dump-config | grep -A2 'id: mask'
|
|
|
108
108
|
```
|
|
109
109
|
> /mask status
|
|
110
110
|
> /mask restore <PHONE_1>
|
|
111
|
+
mask: restored 1 placeholder(s): <PHONE_1>
|
|
112
|
+
file: /tmp/dsh-mask-restore/restore-1f0c….txt (mode 0600, one file per session)
|
|
111
113
|
```
|
|
112
114
|
|
|
113
115
|
## Install & uninstall
|
|
@@ -134,6 +136,7 @@ dsh --profile web --dump-config | grep -A2 'id: mask'
|
|
|
134
136
|
| `persistRestoreTable` | `true` | 把恢复表持久化到受控 `dsh_mask` 领域(`false` = 仅内存) |
|
|
135
137
|
| `maxRestoreEntriesPerSession` | `500` | 每会话恢复条目上限(最旧先逐出) |
|
|
136
138
|
| `maxSessions` | `1000` | 内存会话上限(LRU 逐出,映射按需回载) |
|
|
139
|
+
| `restoreDir` | `''` | `/mask restore` 交付原文的位置。空 = `os.tmpdir()/dsh-mask-restore`;相对值相对宿主进程 cwd 解析。目录按 `0700` 创建、文件按 `0600` 写入,每会话一个文件 |
|
|
137
140
|
|
|
138
141
|
profile patch 覆盖示例:
|
|
139
142
|
|
|
@@ -154,20 +157,20 @@ profile patch 覆盖示例:
|
|
|
154
157
|
| `agent/pre-step` 遮罩 | 永不 | 把消息重写为占位符后再落盘/送模型 |
|
|
155
158
|
| `/mask status` | 永不 | 启用状态、替换总数、类型分布 |
|
|
156
159
|
| `/mask on` / `/mask off` | 永不 | 运行时开关(重启回到 `config.enabled`) |
|
|
157
|
-
| `/mask restore <text>` | 是(显式) |
|
|
160
|
+
| `/mask restore <text>` | 是(显式) | 把占位符还原为本会话存储的值并写进受控文件(每会话一个,mode `0600`);结果文本与会话日志只带该路径与占位符名 |
|
|
158
161
|
| `mask_test` | 永不 | 遮罩一段文本并报告占位符结果 + 计数 |
|
|
159
162
|
|
|
160
163
|
## Permissions & data
|
|
161
164
|
|
|
162
|
-
- **权限**:`dsh-mask` 不做网络请求、不存凭据;只在 `agent/pre-step`
|
|
163
|
-
- **数据**:`占位符 → 原文` 恢复表存内存;`persistRestoreTable: true` 时另存受控 `dsh_mask`
|
|
165
|
+
- **权限**:`dsh-mask` 不做网络请求、不存凭据;只在 `agent/pre-step` 边界读取会话,写入自己的 `dsh_mask` 领域,并写入 `/mask restore` 的交付文件(manifest 正是为此声明 `filesystem:write`)。`dshWorkshop` manifest 还声明 `network:none` 与 `credentials:none`。
|
|
166
|
+
- **数据**:`占位符 → 原文` 恢复表存内存;`persistRestoreTable: true` 时另存受控 `dsh_mask` 领域——绝不写会话日志。唯一另一份原文副本是显式 `/mask restore` 写下的交付文件(`restoreDir`,mode `0600`,每会话一个,下次还原覆盖);没有任何路径会隐式把原文写盘。
|
|
164
167
|
- **会话日志**:`mask/applied` 在 `types.d.ts` 声明,仅在宿主收录该类型时 append(见 Known limitations)。载荷只有计数 + 类型分布。
|
|
165
168
|
|
|
166
169
|
## Security boundaries
|
|
167
170
|
|
|
168
|
-
- **原文绝不进会话日志。**
|
|
169
|
-
- **展示/日志前脱敏。** `lib/sanitize.mjs` 在文本进入模型或日志前打码 PII、密钥与 URL 凭据;`mask_test`
|
|
170
|
-
- **受控还原。** `/mask restore`
|
|
171
|
+
- **原文绝不进会话日志。** 落盘并送模型的是遮罩(占位符)形式,因此模型可见内容可自日志以占位符形式重建;原文留在恢复表。还原方向同理:宿主把命令结果文本**原样**写进日志、并从那一条事件渲染用户可见输出,所以 `/mask restore` 把原文写进受控文件,只回路径。
|
|
172
|
+
- **展示/日志前脱敏。** `lib/sanitize.mjs` 在文本进入模型或日志前打码 PII、密钥与 URL 凭据;`mask_test`、`/mask status` 与所有 `/mask` 错误路径永不回显原文。
|
|
173
|
+
- **受控还原。** `/mask restore` 是唯一的显式还原面,且只读当前会话的映射。失败关闭:交付文件写不出时命令报错,绝不回退成回显原文。
|
|
171
174
|
- **失败关闭。** 未实现的 `mode`(`regex+ner`)、`scope`(`tools`)、NER 实体与越界数值均在加载期响亮失败。
|
|
172
175
|
- **注册即 effect。** 监听器、命令、工具与领域关闭都是 Cordis effect——停止/热重载即可撤销。
|
|
173
176
|
|
|
@@ -175,7 +178,8 @@ profile patch 覆盖示例:
|
|
|
175
178
|
|
|
176
179
|
- **仅正则。** 姓名(`person`)与地址(`address`)识别需要外部 NER 识别器,纯 host 零依赖形态未捆绑;`mode: regex+ner` 与这些实体在加载期响亮失败。开箱即用覆盖电话、邮箱、身份证、银行卡、密钥与(可选)IP。
|
|
177
180
|
- **正则具地域局限。** `phone` 与 `id-card` 只匹配中国大陆格式:`phone` 为 `1[3-9]` 加九位数字,`id-card` 为 18 位中国居民身份证(17 位数字加一位数字或 `X`)。其他国家的电话号码与证件号码不会被检出。`email`、`ip`、`key` 与地域无关;`bank-card` 以较低置信度接受任意 16-19 位数字串。
|
|
178
|
-
- **展示层还原需要浏览器半。** 遮罩完全在 host 侧,但客户端 UI 中透明还原助手气泡属于浏览器半功能,本纯 host 形态未交付。host 侧保留恢复表与已导出的 `RestoreStore` seam(其方法需要会话 id),因此未来的客户端半需经 host 远程面间接消费,而非直接使用;当前的反遮罩入口是 `/mask restore <text>`
|
|
181
|
+
- **展示层还原需要浏览器半。** 遮罩完全在 host 侧,但客户端 UI 中透明还原助手气泡属于浏览器半功能,本纯 host 形态未交付。host 侧保留恢复表与已导出的 `RestoreStore` seam(其方法需要会话 id),因此未来的客户端半需经 host 远程面间接消费,而非直接使用;当前的反遮罩入口是 `/mask restore <text>` 命令,它把原文交付为文件(因为命令结果会被原样记入日志,见「Security boundaries」);`maskClientEnabled` 键会被 schema 声明与校验,但尚无任何运行时代码读取它。
|
|
182
|
+
- **不提供无参 `/mask restore`。** 「还原最近一条助手消息里的全部占位符」这一形态未提供,且无参调用时命令会明确说明。两个宿主事实挡住了它:恢复表是每会话扁平的 `{占位符: 原文}` 映射、**没有按消息的索引**,因此必须去会话事件日志里定位那条消息;而宿主已把 `Session.snapshotEvents()` / `eventAt()` / `ownEvents()` 标为 deprecated 并明令**禁止新调用方**,其唯一被认可的替代(按投递事件增量维护投影)又超出本插件声明的宿主走廊(`>=0.1.2-rc.1`)所能依赖的范围。占位符仍可逐个还原:`/mask restore <PHONE_1>`。
|
|
179
183
|
- **`0.1.7-rc.2` 会话事件。** 宿主收录 59 个会话事件类型,其中没有 `mask/*`;其 `Session.append` 也无法盖章 `ignorable` 信封,因此会话日志审计 append 被跳过(会话仍可加载)。门控不再静默:每个会话首次被拒时打一条可见告警,写明被跳过的事件类型与本限制。宿主收录该类型或支持 `ignorable` 信封后自动开启。
|
|
180
184
|
|
|
181
185
|
## Development
|
|
@@ -225,7 +229,7 @@ PII 基准(108 个合成样本的逐类 P/R/F1)见 [`benchmark/RESULTS.md`](
|
|
|
225
229
|
|
|
226
230
|
## PerryLink DSH Plugin Family
|
|
227
231
|
|
|
228
|
-
本项目是 [PerryLink](https://github.com/PerryLink) 维护的 DeepSeek Harness 插件家族成员:**
|
|
232
|
+
本项目是 [PerryLink](https://github.com/PerryLink) 维护的 DeepSeek Harness 插件家族成员:**34 个活跃维护**,名册共 **42** 个,其中 **5 个已冻结**、**3 个已退役**——每一个都在下表保留自己的行,原因见「状态」列。如果它能帮到你,其他的也会:
|
|
229
233
|
|
|
230
234
|
| Plugin | 一句话 | 状态 |
|
|
231
235
|
|---|---|---|
|
|
@@ -253,7 +257,7 @@ PII 基准(108 个合成样本的逐类 P/R/F1)见 [`benchmark/RESULTS.md`](
|
|
|
253
257
|
| **[dsh-lsp-actions](https://github.com/PerryLink/dsh-lsp-actions)** | LSP diagnostics, formatting, completion, code actions and rename over language servers | |
|
|
254
258
|
| **[dsh-mask](https://github.com/PerryLink/dsh-mask)** | PII masking middleware: anonymize at the model boundary, restore at the display layer | |
|
|
255
259
|
| **[dsh-mcp-panel](https://github.com/PerryLink/dsh-mcp-panel)** | Read-only MCP runtime panel: /mcp command + Settings tab with status, tools and errors | |
|
|
256
|
-
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool |
|
|
260
|
+
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool | |
|
|
257
261
|
| **[dsh-observe](https://github.com/PerryLink/dsh-observe)** | OpenTelemetry and Langfuse observability exporter for DeepSeek Harness. | |
|
|
258
262
|
| **[dsh-output-styles](https://github.com/PerryLink/dsh-output-styles)** | Claude Code outputStyles-equivalent runtime style switching | |
|
|
259
263
|
| **[dsh-permission-rules](https://github.com/PerryLink/dsh-permission-rules)** | Claude Code-style declarative allow/deny/ask permission rules with audit | |
|
package/README.md
CHANGED
|
@@ -42,7 +42,7 @@ PII masking middleware for DeepSeek Harness — anonymize personal data before i
|
|
|
42
42
|
|
|
43
43
|
Phones, emails, ID cards, bank cards, keys, and more become placeholders at the model boundary; the plaintext never enters your session log.
|
|
44
44
|
|
|
45
|
-

|
|
46
46
|
|
|
47
47
|

|
|
48
48
|
|
|
@@ -70,13 +70,13 @@ Phones, emails, ID cards, bank cards, keys, and more become placeholders at the
|
|
|
70
70
|
- **Request-time masking** — `agent/pre-step` messages are rewritten so phones, emails, ID cards, bank cards, and keys (on by default) and IPs (opt-in) become `<PHONE_1>`-style placeholders. The masked text is what gets logged and sent to the model.
|
|
71
71
|
- **Restore table** — the `placeholder → original` map lives only in memory and a controlled storage domain (`dsh_mask`); the plaintext never enters the session log.
|
|
72
72
|
- **Audit, not plaintext** — the `mask/applied` session event records only "replaced N values + type distribution", never the original text or the mapping.
|
|
73
|
-
- **`/mask` command** — `status` (counts + distribution), `on`/`off` (runtime toggle), `restore <text>` (unmap placeholders), `help`.
|
|
73
|
+
- **`/mask` command** — `status` (counts + distribution), `on`/`off` (runtime toggle), `restore <text>` (unmap placeholders and deliver the plaintext as a file, never as logged text), `help`.
|
|
74
74
|
- **`mask_test` tool** — run a snippet through the detector and see the placeholder result; it never reveals the original values.
|
|
75
75
|
|
|
76
76
|
```text
|
|
77
|
-
user message ──agent/pre-step──▶ placeholders ──model──▶ placeholders ──restore──▶
|
|
78
|
-
▲
|
|
79
|
-
└──────── restore table (memory + dsh_mask)
|
|
77
|
+
user message ──agent/pre-step──▶ placeholders ──model──▶ placeholders ──restore──▶ controlled file
|
|
78
|
+
▲ │
|
|
79
|
+
└──────── restore table (memory + dsh_mask) ───────────┘
|
|
80
80
|
```
|
|
81
81
|
|
|
82
82
|
## Quick start
|
|
@@ -109,6 +109,8 @@ Then tailor the entity list in your profile patch:
|
|
|
109
109
|
```
|
|
110
110
|
> /mask status
|
|
111
111
|
> /mask restore <PHONE_1>
|
|
112
|
+
mask: restored 1 placeholder(s): <PHONE_1>
|
|
113
|
+
file: /tmp/dsh-mask-restore/restore-1f0c….txt (mode 0600, one file per session)
|
|
112
114
|
```
|
|
113
115
|
|
|
114
116
|
## Install & uninstall
|
|
@@ -136,6 +138,7 @@ All tunables are Schemastery `Config` fields (changeable from cordis.yml). An id
|
|
|
136
138
|
| `maxRestoreEntriesPerSession` | `500` | Per-session restore entry cap (oldest evicted first) |
|
|
137
139
|
| `maxSessions` | `1000` | In-memory session cap (least-recently-used evicted, mapping reloaded on demand) |
|
|
138
140
|
| `maskClientEnabled` | `false` | Feature flag for the browser half "reveal" bubble (defensive; off by default until the live slot catalog verifies the target slot). The key is schema-declared and validated, but no runtime code reads it yet, so it changes nothing until the browser half ships |
|
|
141
|
+
| `restoreDir` | `''` | Where `/mask restore` delivers the restored plaintext. Empty = `os.tmpdir()/dsh-mask-restore`; a relative value resolves against the host process working directory. The directory is created `0700` and the file written `0600`, one file per session |
|
|
139
142
|
|
|
140
143
|
Example override in your profile patch:
|
|
141
144
|
|
|
@@ -157,20 +160,20 @@ Example override in your profile patch:
|
|
|
157
160
|
| `tools/post-execute` masking | never | Rewrites tool-result text blocks to placeholders before they are logged or fed back to the model (scope: `tools`) |
|
|
158
161
|
| `/mask status` | never | Enabled state, total replaced, type distribution |
|
|
159
162
|
| `/mask on` / `/mask off` | never | Runtime toggle (resets to `config.enabled` on restart) |
|
|
160
|
-
| `/mask restore <text>` | yes (explicit) | Unmaps placeholders back to the values stored for this session |
|
|
163
|
+
| `/mask restore <text>` | yes (explicit) | Unmaps placeholders back to the values stored for this session and writes them to a controlled file (one per session, mode `0600`); the result text and the session log carry only that path and the placeholder names |
|
|
161
164
|
| `mask_test` | never | Masks a snippet and reports the placeholder result + counts |
|
|
162
165
|
|
|
163
166
|
## Permissions & data
|
|
164
167
|
|
|
165
|
-
- **Permissions**: `dsh-mask` performs no network requests and stores no credentials; it
|
|
166
|
-
- **Data**: the `placeholder → original` restore table lives in memory and, when `persistRestoreTable: true`, in the controlled `dsh_mask` storage domain —
|
|
168
|
+
- **Permissions**: `dsh-mask` performs no network requests and stores no credentials; it reads the session at the `agent/pre-step` boundary, writes its own `dsh_mask` storage domain, and writes the `/mask restore` delivery file (the manifest declares `filesystem:write` for exactly that). The `dshWorkshop` manifest also declares `network:none` and `credentials:none`.
|
|
169
|
+
- **Data**: the `placeholder → original` restore table lives in memory and, when `persistRestoreTable: true`, in the controlled `dsh_mask` storage domain — it is never written to the session log. The only other plaintext copy is the delivery file an explicit `/mask restore` writes under `restoreDir` (mode `0600`, one file per session, overwritten by the next restore); nothing writes plaintext to disk implicitly.
|
|
167
170
|
- **Session log**: `mask/applied` is declared in `types.d.ts` and appended only when the host records the type (see Known limitations). Its payload is counts + type distribution only.
|
|
168
171
|
|
|
169
172
|
## Security boundaries
|
|
170
173
|
|
|
171
|
-
- **Plaintext never enters the session log.** The masked (placeholder) form is what gets logged and sent to the model, so model-visible content is reconstructable from the log in placeholder form; the originals stay in the restore table.
|
|
172
|
-
- **Sanitize before display/log.** `lib/sanitize.mjs` redacts PII, secrets, and URL credentials before any text reaches the model or the log; `mask_test
|
|
173
|
-
- **Controlled restore.** `/mask restore` is the single explicit reveal surface, and it only reads the mapping for the active session.
|
|
174
|
+
- **Plaintext never enters the session log.** The masked (placeholder) form is what gets logged and sent to the model, so model-visible content is reconstructable from the log in placeholder form; the originals stay in the restore table. The same rule governs the reveal direction: a command's result text is logged **verbatim** by the host and rendered from that same event, so `/mask restore` writes the plaintext to a controlled file and returns only its path.
|
|
175
|
+
- **Sanitize before display/log.** `lib/sanitize.mjs` redacts PII, secrets, and URL credentials before any text reaches the model or the log; `mask_test`, `/mask status`, and every `/mask` error path never echo originals.
|
|
176
|
+
- **Controlled restore.** `/mask restore` is the single explicit reveal surface, and it only reads the mapping for the active session. Failure fails closed: if the delivery file cannot be written, the command reports an error and never falls back to echoing the plaintext.
|
|
174
177
|
- **Fail closed.** Unimplemented `mode` (`regex+ner`), unknown `scope` values, NER-only entities, and out-of-bounds numbers all fail loudly at load.
|
|
175
178
|
- **Registrations are effects.** The listener, command, tool, and storage-domain close are all Cordis effects — stop/hot-reload removes them.
|
|
176
179
|
|
|
@@ -178,7 +181,8 @@ Example override in your profile patch:
|
|
|
178
181
|
|
|
179
182
|
- **Regex only.** Name (`person`) and address (`address`) recognition needs an external NER recognizer, which the pure-host zero-dependency form does not bundle; `mode: regex+ner` and those entities fail loudly at load. The PII types covered out of the box are phone, email, ID card, bank card, key, and (opt-in) IP.
|
|
180
183
|
- **Region-specific patterns.** The `phone` and `id-card` detectors match mainland-China formats only: `phone` is `1[3-9]` followed by nine digits, and `id-card` is an 18-character Chinese resident ID (17 digits plus a digit or `X`). Phone numbers and national identifiers from other countries are not detected. `email`, `ip`, and `key` are region-agnostic; `bank-card` accepts any 16-19 digit run at a lower confidence score.
|
|
181
|
-
- **Display-layer restore needs a client half.** Masking is fully host-side, but transparently un-masking the assistant bubbles in the client UI is a browser-half feature this pure-host form does not ship. The host side keeps the restore table and the exported `RestoreStore` seam (its methods take a session id), so a future client half would reach them through a host remote rather than directly; today the unmasking surface is the `/mask restore <text>` command, and the `maskClientEnabled` key is validated but read by no runtime code yet.
|
|
184
|
+
- **Display-layer restore needs a client half.** Masking is fully host-side, but transparently un-masking the assistant bubbles in the client UI is a browser-half feature this pure-host form does not ship. The host side keeps the restore table and the exported `RestoreStore` seam (its methods take a session id), so a future client half would reach them through a host remote rather than directly; today the unmasking surface is the `/mask restore <text>` command, which delivers the plaintext as a file because a command result is logged verbatim (see Security boundaries), and the `maskClientEnabled` key is validated but read by no runtime code yet.
|
|
185
|
+
- **No no-argument `/mask restore`.** Restoring *every* placeholder of the most recent assistant message is not offered, and the command says so when invoked without text. Two host facts block it: the restore table is a flat per-session `{placeholder: original}` map with no per-message index, so that message has to be located in the session event log; and the host deprecated `Session.snapshotEvents()` / `eventAt()` / `ownEvents()` with an explicit "new calls are prohibited", leaving an incremental projection as the only sanctioned route — which this plugin's declared host corridor (`>=0.1.2-rc.1`) cannot rely on. Placeholders keep working one at a time instead: `/mask restore <PHONE_1>`.
|
|
182
186
|
- **Session events on `0.1.7-rc.2`.** The harness records 59 session event types and none of them is `mask/*`; its `Session.append` also cannot stamp the `ignorable` envelope, so the session-log audit appends are skipped and sessions keep loading. The gate is not silent about it: the first refusal per session logs one visible warning naming the skipped type and this documented limitation. The plugin enables the append automatically once a host records the type or supports the `ignorable` envelope.
|
|
183
187
|
|
|
184
188
|
## Development
|
|
@@ -228,7 +232,7 @@ Static evidence: `dsh-plugin-doctor` K10–K13 report `pass` for every check on
|
|
|
228
232
|
|
|
229
233
|
## PerryLink DSH Plugin Family
|
|
230
234
|
|
|
231
|
-
This project is one of the **
|
|
235
|
+
This project is one of the **34 actively maintained** DeepSeek Harness plugins from [PerryLink](https://github.com/PerryLink) — the roster is **42**, of which **5** are frozen and **3** retired; every one keeps its row below, with the reason in the Status column. If this one helps you, the others likely will too:
|
|
232
236
|
|
|
233
237
|
| Plugin | One-liner | Status |
|
|
234
238
|
|---|---|---|
|
|
@@ -256,7 +260,7 @@ This project is one of the **33 actively maintained** DeepSeek Harness plugins f
|
|
|
256
260
|
| **[dsh-lsp-actions](https://github.com/PerryLink/dsh-lsp-actions)** | LSP diagnostics, formatting, completion, code actions and rename over language servers | |
|
|
257
261
|
| **[dsh-mask](https://github.com/PerryLink/dsh-mask)** | PII masking middleware: anonymize at the model boundary, restore at the display layer | |
|
|
258
262
|
| **[dsh-mcp-panel](https://github.com/PerryLink/dsh-mcp-panel)** | Read-only MCP runtime panel: /mcp command + Settings tab with status, tools and errors | |
|
|
259
|
-
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool |
|
|
263
|
+
| **[dsh-memento](https://github.com/PerryLink/dsh-memento)** | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool | |
|
|
260
264
|
| **[dsh-observe](https://github.com/PerryLink/dsh-observe)** | OpenTelemetry and Langfuse observability exporter for DeepSeek Harness. | |
|
|
261
265
|
| **[dsh-output-styles](https://github.com/PerryLink/dsh-output-styles)** | Claude Code outputStyles-equivalent runtime style switching | |
|
|
262
266
|
| **[dsh-permission-rules](https://github.com/PerryLink/dsh-permission-rules)** | Claude Code-style declarative allow/deny/ask permission rules with audit | |
|
package/cordis.patch.yml
CHANGED
|
@@ -58,3 +58,10 @@
|
|
|
58
58
|
# already backs it; the client slot ships separately and is off by
|
|
59
59
|
# default until the live slot catalog verifies the target slot.
|
|
60
60
|
maskClientEnabled: false
|
|
61
|
+
# Where /mask restore delivers the restored plaintext. The host writes a
|
|
62
|
+
# command's result (command/done.text) into the session log verbatim,
|
|
63
|
+
# and the client renders that same event, so the plaintext can never
|
|
64
|
+
# live in the result text: it goes to one controlled file per session
|
|
65
|
+
# (mode 0600, overwritten by the next restore) and the result carries
|
|
66
|
+
# the path plus the placeholder names only. Empty = os.tmpdir()/dsh-mask-restore.
|
|
67
|
+
restoreDir: ''
|
package/index.mjs
CHANGED
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
// 日志重建(占位符形式),原文绝不进会话日志。
|
|
8
8
|
// - 恢复表:占位符→原文映射只存内存 + 受控 storageDomain(dsh_mask/restore),
|
|
9
9
|
// 绝不进会话日志明文;/mask restore 与恢复 seam 按需回载。
|
|
10
|
+
// - 还原交付:宿主把命令结果(command/done.text)原样写进持久会话日志,且客户端
|
|
11
|
+
// 用户可见输出就是从同一条事件渲染的(同源,无法分离)⇒ /mask restore 绝不把
|
|
12
|
+
// 明文放进结果文本,而是写进受控文件(lib/deliver.mjs)并把路径回给用户。
|
|
10
13
|
// - 审计:mask/applied 会话事件只记"替换了 N 处 + 类型分布"(log-only,自适应
|
|
11
14
|
// 门),不记明文与映射。
|
|
12
15
|
// - 表面:/mask 命令(status|on|off|restore|help)与 mask_test 工具(试跑一段
|
|
@@ -39,6 +42,8 @@ import { maskMessages, maskContentBlocks } from './lib/mask.mjs'
|
|
|
39
42
|
import { makeEventGate, maybeAppendSessionEvent } from './lib/gate.mjs'
|
|
40
43
|
import { RestoreStore } from './lib/store.mjs'
|
|
41
44
|
import { dshMaskDomainSpec } from './lib/domain.mjs'
|
|
45
|
+
import { deliverPlaintext, resolveRestoreDir } from './lib/deliver.mjs'
|
|
46
|
+
import { redactText } from './lib/sanitize.mjs'
|
|
42
47
|
|
|
43
48
|
export const name = PLUGIN_NAME
|
|
44
49
|
|
|
@@ -96,6 +101,7 @@ export const Config = Schema.object({
|
|
|
96
101
|
maxRestoreEntriesPerSession: Schema.number().default(DEFAULTS.MAX_RESTORE_ENTRIES_PER_SESSION),
|
|
97
102
|
maxSessions: Schema.number().default(DEFAULTS.MAX_SESSIONS),
|
|
98
103
|
maskClientEnabled: Schema.boolean().default(DEFAULTS.MASK_CLIENT_ENABLED),
|
|
104
|
+
restoreDir: Schema.string().default(DEFAULTS.RESTORE_DIR),
|
|
99
105
|
})
|
|
100
106
|
|
|
101
107
|
/**
|
|
@@ -116,9 +122,13 @@ export function resolveConfig(config = {}) {
|
|
|
116
122
|
maxRestoreEntriesPerSession: config.maxRestoreEntriesPerSession ?? DEFAULTS.MAX_RESTORE_ENTRIES_PER_SESSION,
|
|
117
123
|
maxSessions: config.maxSessions ?? DEFAULTS.MAX_SESSIONS,
|
|
118
124
|
maskClientEnabled: config.maskClientEnabled ?? DEFAULTS.MASK_CLIENT_ENABLED,
|
|
125
|
+
restoreDir: config.restoreDir ?? DEFAULTS.RESTORE_DIR,
|
|
119
126
|
}
|
|
120
127
|
if (resolved.enabled === false) return resolved
|
|
121
128
|
|
|
129
|
+
if (typeof resolved.restoreDir !== 'string') {
|
|
130
|
+
throw badConfig('restoreDir must be a string (empty = the OS temp directory)')
|
|
131
|
+
}
|
|
122
132
|
if (resolved.mode === MODES.REGEX_NER) {
|
|
123
133
|
throw nerModeUnsupported(resolved.mode)
|
|
124
134
|
}
|
|
@@ -178,7 +188,37 @@ const HELP_TEXT = [
|
|
|
178
188
|
' status show masking state: enabled, total replaced, type distribution (default)',
|
|
179
189
|
' on enable masking at runtime (config.enabled is the persistent switch)',
|
|
180
190
|
' off disable masking at runtime',
|
|
181
|
-
' restore unmap placeholders in <text> back to the values stored for this session',
|
|
191
|
+
' restore unmap placeholders in <text> back to the values stored for this session and',
|
|
192
|
+
' deliver the plaintext as a file — never in this result text or the session log',
|
|
193
|
+
].join('\n')
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* restore 结果的安全文案(纯函数):只含占位符与落点路径,绝不含还原出的明文。
|
|
197
|
+
* 路径由「配置目录 + 固定前缀 + 会话 id 的 sha256 前 16 位 + .txt」拼成,
|
|
198
|
+
* 不含会话 id、更不含原文,因此可以安全地进日志/转录(这也是它与明文的关键区别)。
|
|
199
|
+
* @param {{placeholders: string[], path: string}} delivery - 占位符与落点。
|
|
200
|
+
* @returns {string} 命令结果文本。
|
|
201
|
+
*/
|
|
202
|
+
export function renderRestore(delivery) {
|
|
203
|
+
return [
|
|
204
|
+
`mask: restored ${delivery.placeholders.length} placeholder(s): ${delivery.placeholders.join(', ')}`,
|
|
205
|
+
` file: ${delivery.path} (mode 0600, one file per session)`,
|
|
206
|
+
' The plaintext is NOT in this text and NOT in the session log: the host records a',
|
|
207
|
+
' command\'s result verbatim, so this command writes the restored text to the file above',
|
|
208
|
+
' instead. Open it to read the plaintext; the next /mask restore overwrites it.',
|
|
209
|
+
].join('\n')
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* restore 无参形态的说明(该形态未实现,见 README「Known limitations」):
|
|
214
|
+
* 定位「最近一条助手消息」需要同步读会话事件史,而宿主已把
|
|
215
|
+
* `Session.snapshotEvents()/eventAt()/ownEvents()` 标为 @deprecated 并禁止新调用方。
|
|
216
|
+
*/
|
|
217
|
+
const RESTORE_NO_ARG_NOTE = [
|
|
218
|
+
' (a no-argument form that would restore every placeholder of the last assistant message is',
|
|
219
|
+
' not offered: the restore table is a flat per-session map with no per-message index, and',
|
|
220
|
+
' locating that message needs a synchronous session-history read the host prohibits for new',
|
|
221
|
+
' callers — see README Known limitations.)',
|
|
182
222
|
].join('\n')
|
|
183
223
|
|
|
184
224
|
/**
|
|
@@ -383,6 +423,19 @@ export function apply(ctx, config = {}) {
|
|
|
383
423
|
name: COMMAND_NAME,
|
|
384
424
|
description: 'PII masking status and controls: status (replaced count + type distribution), on/off (runtime toggle), restore <text> (unmap placeholders to this session\'s values), help.',
|
|
385
425
|
input: { hint: '[status | on | off | restore <text> | help]' },
|
|
426
|
+
// `recordInput: false` —— 输入侧的同类泄漏闸(2026-10-13,用户裁定)。
|
|
427
|
+
//
|
|
428
|
+
// 为什么必须关:宿主把 `parsed.rawInput`(逐字原文)写进 `command/run` 事件的 `args`
|
|
429
|
+
// 字段(dsh-commands `index.ts:376`),而该事件同样进持久会话转录。于是
|
|
430
|
+
// `/mask restore 13812345678`(用户直接粘贴明文)会把 PII 写进日志 —— 与
|
|
431
|
+
// 结果侧那条缺陷同一个洞,只是入口不同。关掉它后 `args` 字段整体缺席(宿主
|
|
432
|
+
// `index.ts:215` 只在显式设置时才带上该键)。
|
|
433
|
+
//
|
|
434
|
+
// 代价(如实记录,勿以为无损):`recordInput` 是**命令级、无子命令粒度**
|
|
435
|
+
// (宿主 `types.ts:75`),所以 `status` / `on` / `off` 的 args 也一并退出转录。
|
|
436
|
+
// 这三条都是无参数或单关键词调用,信息量本来就为零;而恢复映射本身另有
|
|
437
|
+
// 交付文件与 `mask/applied` 审计事件承载,不依赖 args。因此这是净收益。
|
|
438
|
+
recordInput: false,
|
|
386
439
|
async handler(invocation) {
|
|
387
440
|
return handleMaskCommand(invocation)
|
|
388
441
|
},
|
|
@@ -422,14 +475,33 @@ export function apply(ctx, config = {}) {
|
|
|
422
475
|
return { kind: 'error', text: 'mask: restore requires an active session' }
|
|
423
476
|
}
|
|
424
477
|
if (snippet === '') {
|
|
425
|
-
return { kind: 'error', text:
|
|
478
|
+
return { kind: 'error', text: `mask: restore needs text, e.g. /mask restore <PHONE_1>\n${RESTORE_NO_ARG_NOTE}` }
|
|
479
|
+
}
|
|
480
|
+
const { text: restored, placeholders } = await store.restoreDetailed(sessionId, snippet)
|
|
481
|
+
if (placeholders.length === 0) {
|
|
482
|
+
return {
|
|
483
|
+
kind: 'success',
|
|
484
|
+
text: [
|
|
485
|
+
'mask: restore found no placeholder this session knows — nothing was revealed or written.',
|
|
486
|
+
' Pass a placeholder exactly as the model saw it, e.g. /mask restore <PHONE_1>',
|
|
487
|
+
].join('\n'),
|
|
488
|
+
}
|
|
426
489
|
}
|
|
427
|
-
|
|
428
|
-
|
|
490
|
+
// 安全缺陷修复点:宿主把 result.text 原样写进持久会话日志(command/done),
|
|
491
|
+
// 客户端又从同一条事件渲染用户可见输出 ⇒ 结果文本既是转录也是日志。
|
|
492
|
+
// 因此明文绝不进结果文本,只进受控文件,结果里只回路径 + 占位符名。
|
|
493
|
+
const delivery = await deliverPlaintext({
|
|
494
|
+
dir: resolveRestoreDir(resolved.restoreDir),
|
|
495
|
+
sessionId,
|
|
496
|
+
text: restored,
|
|
497
|
+
})
|
|
498
|
+
return { kind: 'success', text: renderRestore({ placeholders, path: delivery.path }) }
|
|
429
499
|
}
|
|
430
500
|
return { kind: 'success', text: HELP_TEXT }
|
|
431
501
|
} catch (error) {
|
|
432
|
-
|
|
502
|
+
// 失败关闭:交付失败也绝不回退到「把明文放进结果文本」。错误消息同样过
|
|
503
|
+
// redactText(ARCHITECTURE「Sanitize before display/log」),因为它同样会进日志。
|
|
504
|
+
const message = redactText(`mask: ${actionKey} failed: ${messageOf(error)}`)
|
|
433
505
|
logger.error(message)
|
|
434
506
|
return { kind: 'error', text: message }
|
|
435
507
|
}
|
package/lib/constants.mjs
CHANGED
|
@@ -80,6 +80,8 @@ export const DEFAULTS = Object.freeze({
|
|
|
80
80
|
MAX_RESTORE_ENTRIES_PER_SESSION: 500,
|
|
81
81
|
MAX_SESSIONS: 1000,
|
|
82
82
|
MASK_CLIENT_ENABLED: false,
|
|
83
|
+
// 还原结果交付目录;空串 = os.tmpdir()/dsh-mask-restore(见 lib/deliver.mjs)。
|
|
84
|
+
RESTORE_DIR: '',
|
|
83
85
|
})
|
|
84
86
|
|
|
85
87
|
// 配置字段合法性边界(加载期校验,越界响亮失败)。
|
package/lib/deliver.mjs
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// lib/deliver.mjs — 还原结果的受控明文交付(唯一的非日志用户可见通道,零 DSH 依赖)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要这个模块:宿主把命令结果**原样**写进持久会话日志,并且用户可见的命令
|
|
4
|
+
// 输出正是从那条日志事件渲染出来的(两条通道同源,无法分离):
|
|
5
|
+
// - 落盘:dsh-commands `execute()` → `appendLifecycle(session, 'command/done', {text: result.text})`
|
|
6
|
+
// (`types.ts` 的 `command/done` 声明明说 text 是处理器结果的 verbatim 文本)。
|
|
7
|
+
// - 渲染:client `ui-chat` 的 command 节点由 `command/done` 事件构造,`GenericCommandCard`
|
|
8
|
+
// 直接渲染 `node.outcome.text`(即同一条事件的 text)。
|
|
9
|
+
// 所以:命令结果里放什么,就等于往会话日志里放什么,也就等于往用户的转录里放什么;
|
|
10
|
+
// 宿主没有任何「记日志但不渲染」或「渲染但不记日志」的开关(`recordInput` 只管输入侧)。
|
|
11
|
+
// 结论:还原出的明文**绝不可**放进命令结果,只能走这条受控文件通道,把路径回给用户。
|
|
12
|
+
//
|
|
13
|
+
// 落点与收敛:每个会话固定一个文件(文件名 = 会话 id 的 sha256 前 16 位十六进制,
|
|
14
|
+
// 不含会话 id 本身、更不含原文),下一次还原覆盖同一个文件 ⇒ 磁盘上的明文副本数量
|
|
15
|
+
// 有界(每会话至多一份),不会随还原次数累积。
|
|
16
|
+
//
|
|
17
|
+
// 权限与失败关闭:目录 0700、文件 0600(POSIX;Windows 上 chmod 只影响只读位,无害)。
|
|
18
|
+
// 目录与目标文件都先 lstat 并拒绝符号链接,避免把 PII 写进他人预置的软链指向处;
|
|
19
|
+
// 目录属主不是当前用户时拒绝写入。任何一步失败都抛错,由调用方转成不泄露原文的错误
|
|
20
|
+
// 结果——绝不回退到「把明文放进命令结果」。
|
|
21
|
+
|
|
22
|
+
import { createHash } from 'node:crypto'
|
|
23
|
+
import { chmod, lstat, mkdir, writeFile } from 'node:fs/promises'
|
|
24
|
+
import os from 'node:os'
|
|
25
|
+
import path from 'node:path'
|
|
26
|
+
|
|
27
|
+
/** 默认交付目录名(`restoreDir` 配空时的落点,位于系统临时目录下)。 */
|
|
28
|
+
export const RESTORE_DIR_NAME = 'dsh-mask-restore'
|
|
29
|
+
|
|
30
|
+
/** 交付文件名前缀(真正写入前先 lstat 拒绝符号链接)。 */
|
|
31
|
+
export const RESTORE_FILE_PREFIX = 'restore-'
|
|
32
|
+
|
|
33
|
+
/** 0644 会让同机其它用户读到 PII;目录与文件都取最小可读面。 */
|
|
34
|
+
const DIR_MODE = 0o700
|
|
35
|
+
const FILE_MODE = 0o600
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 解析交付目录:配置为空串(默认)时落在 `os.tmpdir()/dsh-mask-restore`,
|
|
39
|
+
* 否则按配置解析为绝对路径(相对路径相对宿主进程 cwd)。
|
|
40
|
+
* 纯函数(除 `os.tmpdir()`/`path.resolve` 的宿主事实外无副作用),便于测试。
|
|
41
|
+
* @param {unknown} configured - `restoreDir` 配置值。
|
|
42
|
+
* @returns {string} 绝对目录路径。
|
|
43
|
+
*/
|
|
44
|
+
export function resolveRestoreDir(configured) {
|
|
45
|
+
const raw = typeof configured === 'string' ? configured.trim() : ''
|
|
46
|
+
return raw === '' ? path.join(os.tmpdir(), RESTORE_DIR_NAME) : path.resolve(raw)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 会话的交付文件路径:`<dir>/restore-<sha256(sessionId)[0:16]>.txt`。
|
|
51
|
+
* 纯函数;同一会话恒定同一个路径(覆盖语义),不同会话互不覆盖。
|
|
52
|
+
* @param {string} dir - 交付目录(`resolveRestoreDir` 的结果)。
|
|
53
|
+
* @param {unknown} sessionId - 会话 id。
|
|
54
|
+
* @returns {string} 交付文件绝对路径。
|
|
55
|
+
*/
|
|
56
|
+
export function restoreFilePath(dir, sessionId) {
|
|
57
|
+
const digest = createHash('sha256').update(String(sessionId ?? '')).digest('hex').slice(0, 16)
|
|
58
|
+
return path.join(dir, `${RESTORE_FILE_PREFIX}${digest}.txt`)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 目标路径必须不是符号链接:否则写入会跟随软链落到他人指定的位置。
|
|
63
|
+
* @param {string} target - 待检查路径。
|
|
64
|
+
* @param {string} what - 错误消息里的对象名。
|
|
65
|
+
* @returns {Promise<import('node:fs').Stats|undefined>} 存在时的 lstat 结果。
|
|
66
|
+
*/
|
|
67
|
+
async function assertNotSymlink(target, what) {
|
|
68
|
+
try {
|
|
69
|
+
const stats = await lstat(target)
|
|
70
|
+
if (stats.isSymbolicLink()) {
|
|
71
|
+
throw new Error(`${what} is a symbolic link: refusing to write plaintext through it`)
|
|
72
|
+
}
|
|
73
|
+
return stats
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (/** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT') return undefined
|
|
76
|
+
throw error
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 把还原出的明文写进受控文件(覆盖本会话上一份)。
|
|
82
|
+
* 绝不返回、也绝不记录明文本身——只返回落点与字节数供结果文本使用。
|
|
83
|
+
* @param {object} options - {dir, sessionId, text}。
|
|
84
|
+
* @param {string} options.dir - 交付目录。
|
|
85
|
+
* @param {unknown} options.sessionId - 会话 id。
|
|
86
|
+
* @param {string} options.text - 还原后的明文(只写入文件,不进任何日志/结果)。
|
|
87
|
+
* @returns {Promise<{path: string, bytes: number}>} 落点与 UTF-8 字节数。
|
|
88
|
+
*/
|
|
89
|
+
export async function deliverPlaintext({ dir, sessionId, text }) {
|
|
90
|
+
const target = restoreFilePath(dir, sessionId)
|
|
91
|
+
// Check the existing entry before mkdir: a dangling symlink makes mkdir throw
|
|
92
|
+
// ENOENT, which would mask the real refusal reason and fail the wrong way.
|
|
93
|
+
await assertNotSymlink(dir, 'restoreDir')
|
|
94
|
+
await mkdir(dir, { recursive: true, mode: DIR_MODE })
|
|
95
|
+
const dirStats = await assertNotSymlink(dir, 'restoreDir')
|
|
96
|
+
if (dirStats === undefined || !dirStats.isDirectory()) {
|
|
97
|
+
throw new Error('restoreDir is not a directory')
|
|
98
|
+
}
|
|
99
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : undefined
|
|
100
|
+
if (uid !== undefined && dirStats.uid !== uid) {
|
|
101
|
+
throw new Error('restoreDir is owned by another user: refusing to write plaintext there')
|
|
102
|
+
}
|
|
103
|
+
// 目录可能早已存在(预置或上次运行),mkdir 的 mode 不会收紧既有权限。
|
|
104
|
+
await chmod(dir, DIR_MODE)
|
|
105
|
+
await assertNotSymlink(target, 'restore file')
|
|
106
|
+
const body = typeof text === 'string' ? text : String(text)
|
|
107
|
+
await writeFile(target, body, { encoding: 'utf8', mode: FILE_MODE, flag: 'w' })
|
|
108
|
+
// 覆盖写不会改既有文件的 mode,显式收紧一次。
|
|
109
|
+
await chmod(target, FILE_MODE)
|
|
110
|
+
return { path: target, bytes: Buffer.byteLength(body, 'utf8') }
|
|
111
|
+
}
|
package/lib/store.mjs
CHANGED
|
@@ -68,12 +68,36 @@ export class RestoreStore {
|
|
|
68
68
|
* @returns {Promise<string>} 还原后的文本。
|
|
69
69
|
*/
|
|
70
70
|
async restore(sessionId, text) {
|
|
71
|
+
const stripper = await this._stripperForRestore(sessionId)
|
|
72
|
+
if (stripper === undefined) return text
|
|
73
|
+
return stripper.restore(text)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 还原并报告本次涉及的占位符(供命令结果只写占位符、不写明文)。
|
|
78
|
+
* 与 {@link restore} 同源同语义:命中集合与替换用的映射完全一致。
|
|
79
|
+
* @param {string} sessionId - 会话 id。
|
|
80
|
+
* @param {string} text - 含占位符文本。
|
|
81
|
+
* @returns {Promise<{text: string, placeholders: string[]}>} 还原文本 + 命中的占位符(长度降序)。
|
|
82
|
+
*/
|
|
83
|
+
async restoreDetailed(sessionId, text) {
|
|
84
|
+
const stripper = await this._stripperForRestore(sessionId)
|
|
85
|
+
if (stripper === undefined) return { text, placeholders: [] }
|
|
86
|
+
return { text: stripper.restore(text), placeholders: stripper.placeholdersIn(text) }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 取会话脱敏器,内存未命中且 persist 开启时从领域回载(restore 与
|
|
91
|
+
* restoreDetailed 的唯一差异只是返回值,故共用这一段)。
|
|
92
|
+
* @param {string} sessionId - 会话 id。
|
|
93
|
+
* @returns {Promise<import('./strip.mjs').Stripper|undefined>} 脱敏器或 undefined。
|
|
94
|
+
*/
|
|
95
|
+
async _stripperForRestore(sessionId) {
|
|
71
96
|
let stripper = this.strippers.get(sessionId)
|
|
72
97
|
if (stripper === undefined && this.persistEnabled && this.domainPromise !== null) {
|
|
73
98
|
stripper = await this._load(sessionId)
|
|
74
99
|
}
|
|
75
|
-
|
|
76
|
-
return stripper.restore(text)
|
|
100
|
+
return stripper
|
|
77
101
|
}
|
|
78
102
|
|
|
79
103
|
/**
|
package/lib/strip.mjs
CHANGED
|
@@ -132,6 +132,20 @@ export class Stripper {
|
|
|
132
132
|
return result
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
+
/**
|
|
136
|
+
* 文本中出现的、本会话已知的占位符(按 `restore()` 的替换顺序:长度降序)。
|
|
137
|
+
* 只读、不改文本、绝不返回原文——用于把「这次还原涉及哪些占位符」安全地
|
|
138
|
+
* 写进用户可见结果(占位符本身已按设计存在于模型可见的日志里)。
|
|
139
|
+
* @param {unknown} text - 含占位符的文本。
|
|
140
|
+
* @returns {string[]} 命中的占位符(去重,长度降序)。
|
|
141
|
+
*/
|
|
142
|
+
placeholdersIn(text) {
|
|
143
|
+
if (typeof text !== 'string' || text.length === 0) return []
|
|
144
|
+
return [...this.placeholderMap.keys()]
|
|
145
|
+
.sort((a, b) => b.length - a.length)
|
|
146
|
+
.filter(placeholder => text.includes(placeholder))
|
|
147
|
+
}
|
|
148
|
+
|
|
135
149
|
/** @returns {Record<string, string>} {占位符: 原文} 只读副本。 */
|
|
136
150
|
mapping() {
|
|
137
151
|
return Object.fromEntries(this.placeholderMap)
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-mask",
|
|
3
3
|
"description": "PII masking middleware for DeepSeek Harness: regex-detect and replace phones, emails, ID cards, bank cards, keys, and (opt-in) IPs with placeholders before they reach the model, keep the restore table host-side (memory plus a controlled storage domain, never the session log) with the /mask restore command and the exported RestoreStore seam, and expose /mask status and the mask_test tool. Name and address recognition needs an external NER recognizer, which this pure-host form does not bundle: mode \"regex+ner\" and the person/address entities fail loudly at load. The phone and ID-card detectors match mainland-China formats only.",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.22",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/PerryLink/dsh-mask.git"
|
|
@@ -63,6 +63,7 @@
|
|
|
63
63
|
},
|
|
64
64
|
"permissions": [
|
|
65
65
|
"filesystem:read",
|
|
66
|
+
"filesystem:write",
|
|
66
67
|
"storage-domain:read",
|
|
67
68
|
"storage-domain:write",
|
|
68
69
|
"session-log:read",
|
|
@@ -70,14 +71,21 @@
|
|
|
70
71
|
"network:none"
|
|
71
72
|
],
|
|
72
73
|
"compatibility": {
|
|
73
|
-
"dshVersions": [
|
|
74
|
-
"0.2
|
|
74
|
+
"dshVersions": [
|
|
75
|
+
"0.1.2-rc.1",
|
|
76
|
+
"0.1.5-rc.2",
|
|
77
|
+
"0.1.7-alpha.2",
|
|
78
|
+
"0.1.7-rc.1",
|
|
79
|
+
"0.1.7-rc.2",
|
|
80
|
+
"0.2.1-alpha.1",
|
|
81
|
+
"0.2.1-rc.2"
|
|
82
|
+
]
|
|
75
83
|
},
|
|
76
84
|
"capability": {
|
|
77
85
|
"id": "mask",
|
|
78
86
|
"kind": "command",
|
|
79
87
|
"invocation": "/mask status",
|
|
80
|
-
"expected": "the /mask command is registered on the commands service: status reports masked counts and type distribution, on/off toggles masking at runtime, restore <text> unmaps placeholders back to the values stored for this session; mask_test tool masks a snippet and reports the placeholder result"
|
|
88
|
+
"expected": "the /mask command is registered on the commands service: status reports masked counts and type distribution, on/off toggles masking at runtime, restore <text> unmaps placeholders back to the values stored for this session and delivers the plaintext as a controlled file whose path (never the plaintext) is what the command result and the session log carry; mask_test tool masks a snippet and reports the placeholder result"
|
|
81
89
|
},
|
|
82
90
|
"evidence": {
|
|
83
91
|
"install": null,
|
|
@@ -100,22 +108,23 @@
|
|
|
100
108
|
"zod": "^4.4.3"
|
|
101
109
|
},
|
|
102
110
|
"devDependencies": {
|
|
103
|
-
"@deepseek-ai/dsh-attachment": "0.2.1-
|
|
111
|
+
"@deepseek-ai/dsh-attachment": "0.2.1-rc.2",
|
|
104
112
|
"@deepseek-ai/cordis": "^4.0.5-alpha.1",
|
|
105
113
|
"@deepseek-ai/cordis-plugin-include": "^1.0.10-alpha.1",
|
|
106
114
|
"@deepseek-ai/cordis-plugin-loader": "^1.0.6-alpha.1",
|
|
107
|
-
"@deepseek-ai/dsh-agent": "0.2.1-
|
|
108
|
-
"@deepseek-ai/dsh-commands": "0.2.1-
|
|
109
|
-
"@deepseek-ai/dsh-session": "0.2.1-
|
|
110
|
-
"@deepseek-ai/dsh-storage": "0.2.1-
|
|
111
|
-
"@deepseek-ai/dsh-storage-domain": "0.2.1-
|
|
112
|
-
"@deepseek-ai/dsh-storage-json": "0.2.1-
|
|
113
|
-
"@deepseek-ai/dsh-system-prompt": "0.2.1-
|
|
114
|
-
"@deepseek-ai/dsh-tools": "0.2.1-
|
|
115
|
+
"@deepseek-ai/dsh-agent": "0.2.1-rc.2",
|
|
116
|
+
"@deepseek-ai/dsh-commands": "0.2.1-rc.2",
|
|
117
|
+
"@deepseek-ai/dsh-session": "0.2.1-rc.2",
|
|
118
|
+
"@deepseek-ai/dsh-storage": "0.2.1-rc.2",
|
|
119
|
+
"@deepseek-ai/dsh-storage-domain": "0.2.1-rc.2",
|
|
120
|
+
"@deepseek-ai/dsh-storage-json": "0.2.1-rc.2",
|
|
121
|
+
"@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2",
|
|
122
|
+
"@deepseek-ai/dsh-tools": "0.2.1-rc.2",
|
|
115
123
|
"@deepseek-ai/schemastery": "^3.18.5-alpha.1",
|
|
116
124
|
"@types/node": "^22.19.0",
|
|
117
125
|
"oxlint": "0.18.1",
|
|
118
|
-
"typescript": "^5.9.0"
|
|
126
|
+
"typescript": "^5.9.0",
|
|
127
|
+
"@deepseek-ai/dsh-working-directory": "0.2.1-rc.2"
|
|
119
128
|
},
|
|
120
129
|
"scripts": {
|
|
121
130
|
"typecheck": "tsc -p tsconfig.check.json",
|
package/types.d.ts
CHANGED
|
@@ -42,6 +42,13 @@ export interface Config {
|
|
|
42
42
|
maxSessions?: number
|
|
43
43
|
/** 浏览器半自动还原气泡开关(防御性 client slot;默认 false,未启用前对 UI 无副作用)。 */
|
|
44
44
|
maskClientEnabled?: boolean
|
|
45
|
+
/**
|
|
46
|
+
* `/mask restore` 明文交付目录(默认空串 = `os.tmpdir()/dsh-mask-restore`)。
|
|
47
|
+
* 宿主把命令结果原样写进会话日志、客户端又从同一条事件渲染用户可见输出,
|
|
48
|
+
* `restore` 的明文因此绝不放进结果文本,只写进该目录下的受控文件
|
|
49
|
+
* (每会话一个,mode 0600,下次还原覆盖),结果文本只回路径与占位符名。
|
|
50
|
+
*/
|
|
51
|
+
restoreDir?: string
|
|
45
52
|
}
|
|
46
53
|
|
|
47
54
|
/** mask_test 工具规范结果。 */
|