shroud-privacy 2.0.0

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.
Files changed (45) hide show
  1. package/LICENSE +190 -0
  2. package/NOTICE +7 -0
  3. package/README.md +369 -0
  4. package/dist/audit.d.ts +46 -0
  5. package/dist/audit.js +127 -0
  6. package/dist/canary.d.ts +31 -0
  7. package/dist/canary.js +73 -0
  8. package/dist/config.d.ts +27 -0
  9. package/dist/config.js +123 -0
  10. package/dist/detectors/base.d.ts +8 -0
  11. package/dist/detectors/base.js +2 -0
  12. package/dist/detectors/code.d.ts +25 -0
  13. package/dist/detectors/code.js +144 -0
  14. package/dist/detectors/context.d.ts +31 -0
  15. package/dist/detectors/context.js +357 -0
  16. package/dist/detectors/patterns.d.ts +15 -0
  17. package/dist/detectors/patterns.js +58 -0
  18. package/dist/detectors/regex.d.ts +28 -0
  19. package/dist/detectors/regex.js +955 -0
  20. package/dist/generators/base.d.ts +6 -0
  21. package/dist/generators/base.js +2 -0
  22. package/dist/generators/codes.d.ts +20 -0
  23. package/dist/generators/codes.js +231 -0
  24. package/dist/generators/names.d.ts +29 -0
  25. package/dist/generators/names.js +194 -0
  26. package/dist/generators/network.d.ts +86 -0
  27. package/dist/generators/network.js +477 -0
  28. package/dist/hooks.d.ts +27 -0
  29. package/dist/hooks.js +457 -0
  30. package/dist/index.d.ts +12 -0
  31. package/dist/index.js +58 -0
  32. package/dist/mapping.d.ts +33 -0
  33. package/dist/mapping.js +72 -0
  34. package/dist/obfuscator.d.ts +78 -0
  35. package/dist/obfuscator.js +603 -0
  36. package/dist/redaction.d.ts +26 -0
  37. package/dist/redaction.js +76 -0
  38. package/dist/store.d.ts +40 -0
  39. package/dist/store.js +79 -0
  40. package/dist/types.d.ts +101 -0
  41. package/dist/types.js +35 -0
  42. package/ncg_adapter.py +530 -0
  43. package/openclaw.plugin.json +72 -0
  44. package/package.json +56 -0
  45. package/shroud_bridge.mjs +225 -0
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Walter Keating
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ Shroud — Privacy Obfuscation for AI Agents
2
+ Copyright 2026 Walter Keating
3
+
4
+ This product includes software developed as the Shroud project
5
+ (https://github.com/walterkeating-stack/shroud).
6
+
7
+ Licensed under the Apache License, Version 2.0.
package/README.md ADDED
@@ -0,0 +1,369 @@
1
+ # Shroud — Community Edition
2
+
3
+ Privacy obfuscation plugin for [OpenClaw](https://openclaw.ai). Detects sensitive data (PII, network infrastructure, credentials) and replaces it with deterministic fake values before anything reaches the LLM. Tool calls still work because Shroud deobfuscates on the way back.
4
+
5
+ > **Open-source Community Edition** — free to use under MIT license. [Enterprise Edition](#enterprise-edition) available with additional features for teams.
6
+
7
+ ## What it does
8
+
9
+ 1. **Detects** 100+ entity types: emails, IPs, phones, API keys, hostnames, SNMP communities, BGP ASNs, credit cards, SSNs, file paths, URLs, person/org/location names, VLANs, route-maps, ACLs, OSPF IDs, IBANs, JWTs, PEM certs, GPS coordinates, ICS/SCADA identifiers, Palo Alto/Check Point/Juniper/Fortinet/F5 config secrets, and custom regex patterns.
10
+ 2. **Replaces** each value with a deterministic fake (same input + key = same fake every time). Fakes are format-preserving: IPv4 stays in CGNAT range (`100.64.0.0/10`), IPv6 uses ULA range (`fd00::/8`), emails keep `@domain` structure, credit cards pass Luhn, etc.
11
+ 3. **Deobfuscates** LLM responses and tool parameters so the user sees real values and tools receive real arguments.
12
+ 4. **Audit logs** every obfuscation/deobfuscation event with counts, categories, char deltas, and optional proof hashes — never logging raw sensitive values.
13
+
14
+ ### Hook lifecycle
15
+
16
+ | Hook | Direction | What happens |
17
+ |------|-----------|-------------|
18
+ | `before_prompt_build` | User → LLM | Obfuscate user prompt, prepend privacy context |
19
+ | `before_llm_send` | User → LLM | Obfuscate all messages + install `transformResponse` |
20
+ | `transformResponse` | LLM → User | Deobfuscate LLM output (auto-reply, WhatsApp, etc.) |
21
+ | `before_tool_call` | LLM → Tool | Deobfuscate tool parameters + track tool chain depth |
22
+ | `tool_result_persist` | Tool → History | Obfuscate tool results before storing |
23
+ | `message_sending` | Agent → User | Deobfuscate outbound messages (fallback path) |
24
+
25
+ ## Install
26
+
27
+ ### OpenClaw
28
+
29
+ ```bash
30
+ openclaw plugins install shroud-privacy
31
+ ```
32
+
33
+ That's it. Configure in `~/.openclaw/openclaw.json` under `plugins.entries."shroud-privacy".config`.
34
+
35
+ ### NCG Agent
36
+
37
+ ```bash
38
+ python agent.py plugin install shroud-privacy
39
+ ```
40
+
41
+ Configure in `~/.ncg/ncg.json` under `plugins.entries."shroud-privacy".config`.
42
+
43
+ ### From source (development)
44
+
45
+ ```bash
46
+ git clone https://github.com/walterkeating-stack/shroud.git
47
+ cd shroud
48
+ npm install && npm run build
49
+
50
+ bash deploy-local.sh # → OpenClaw (~/.openclaw/extensions/)
51
+ bash deploy-ncg.sh # → NCG (~/.ncg/extensions/)
52
+ ```
53
+
54
+ ## Configure
55
+
56
+ Both OpenClaw and NCG store Shroud config in the same structure — only the file path differs:
57
+
58
+ | Platform | Config file | Config path |
59
+ |----------|-------------|-------------|
60
+ | OpenClaw | `~/.openclaw/openclaw.json` | `plugins.entries."shroud-privacy".config` |
61
+ | NCG | `~/.ncg/ncg.json` | `plugins.entries."shroud-privacy".config` |
62
+
63
+ ```jsonc
64
+ "shroud-privacy": {
65
+ "enabled": true,
66
+ "config": {
67
+ // Recommended: safe defaults for community use
68
+ "auditEnabled": true // audit log on — see what Shroud is doing
69
+ // "auditIncludeProofHashes": false // off by default (opt-in)
70
+ // "auditMaxFakesSample": 0 // off by default (opt-in)
71
+ // "auditLogFormat": "human" // human-readable single lines
72
+ // "minConfidence": 0.0 // catch everything (default)
73
+ // "secretKey": "" // auto-generated if empty
74
+ // "persistentSalt": "" // set for cross-session consistency
75
+ // "canaryEnabled": false // data leakage tracking (opt-in)
76
+ }
77
+ }
78
+ ```
79
+
80
+ Restart the gateway after config changes:
81
+
82
+ ```bash
83
+ openclaw gateway restart # OpenClaw
84
+ sudo systemctl restart ncg-gateway.service # NCG
85
+ ```
86
+
87
+ ### Safe defaults
88
+
89
+ Out of the box, Shroud:
90
+ - Auto-generates a secret key (per-session unless you set `secretKey`)
91
+ - Detects all entity categories at confidence >= 0.0
92
+ - Logs audit lines (counts + categories) but **not** proof hashes or fake samples
93
+ - Never logs raw values, real→fake mappings, or original text
94
+ - All enterprise features are opt-in and disabled by default
95
+
96
+ To enable proof hashes and fake samples for deeper audit:
97
+
98
+ ```jsonc
99
+ "config": {
100
+ "auditEnabled": true,
101
+ "auditIncludeProofHashes": true,
102
+ "auditHashTruncate": 12,
103
+ "auditMaxFakesSample": 3
104
+ }
105
+ ```
106
+
107
+ ## Config reference
108
+
109
+ ### Core settings
110
+
111
+ | Key | Type | Default | Description |
112
+ |-----|------|---------|-------------|
113
+ | `secretKey` | string | auto | HMAC secret for deterministic mapping |
114
+ | `persistentSalt` | string | `""` | Fixed salt for cross-session consistency |
115
+ | `minConfidence` | number | `0.0` | Minimum detector confidence (0.0–1.0) |
116
+ | `allowlist` | string[] | `[]` | Values to never obfuscate |
117
+ | `denylist` | string[] | `[]` | Values to always obfuscate |
118
+ | `canaryEnabled` | boolean | `false` | Inject tracking tokens for leak detection |
119
+ | `canaryPrefix` | string | `"SHROUD-CANARY"` | Prefix for canary tokens |
120
+ | `auditEnabled` | boolean | `false` | Enable audit logging |
121
+ | `verboseLogging` | boolean | `false` | Alias for `auditEnabled` |
122
+ | `auditLogFormat` | `"human"` \| `"json"` | `"human"` | Audit output format |
123
+ | `auditIncludeProofHashes` | boolean | `false` | Include salted SHA-256 proof hashes |
124
+ | `auditHashSalt` | string | `""` | Salt for proof hashes |
125
+ | `auditHashTruncate` | number | `12` | Truncate proof hashes to N hex chars |
126
+ | `auditMaxFakesSample` | number | `0` | Include up to N fake values in audit (0 = off) |
127
+ | `logMappings` | boolean | `false` | Log mapping table (debug only) |
128
+ | `customPatterns` | array | `[]` | User-defined regex detection patterns |
129
+ | `detectorOverrides` | object | `{}` | Override built-in rules: disable or change confidence per rule name |
130
+
131
+ ### Enterprise settings
132
+
133
+ | Key | Type | Default | Description |
134
+ |-----|------|---------|-------------|
135
+ | `tenantId` | string | `""` | Multi-tenant isolation: tenant ID for HMAC keying |
136
+ | `lockedCategories` | string[] | `[]` | Compliance mode: categories that MUST be detected |
137
+ | `maxToolDepth` | number | `10` | Max nested tool call depth before warning |
138
+ | `exposureWindow` | number | `60000` | Sliding window (ms) for exposure rate tracking |
139
+ | `exposureThresholds` | object | `{}` | Per-category max detections per window |
140
+ | `exposureGlobalThreshold` | number | `100` | Global max detections per window |
141
+ | `policyFile` | string | `""` | Path to external JSON policy file (allowlist/denylist with glob/regex) |
142
+ | `redactionLevel` | `"full"` \| `"masked"` \| `"stats"` | `"full"` | Output mode: fake values, partial masking, or category placeholders |
143
+ | `sharedStorePath` | string | `""` | File path for cross-agent shared mapping store |
144
+ | `sharedStoreTtlMs` | number | `5000` | Cache TTL for shared store reads (ms) |
145
+ | `provenanceTagging` | boolean | `false` | Embed `«shroud:category:hash»` markers in output |
146
+ | `sessionHandoff` | boolean | `false` | Enable session export/import tools |
147
+
148
+ ### Key rotation settings
149
+
150
+ | Key | Type | Default | Description |
151
+ |-----|------|---------|-------------|
152
+ | `keys` | array | `[]` | Versioned keys: `[{version, key, createdAt?, expiresAt?, retired?}]` |
153
+ | `activeKeyVersion` | number | `0` | Which key version to use (0 = highest non-expired) |
154
+
155
+ ### SIEM integration settings
156
+
157
+ | Key | Type | Default | Description |
158
+ |-----|------|---------|-------------|
159
+ | `siemWebhooks` | array | `[]` | Webhook endpoints: `[{url, authHeader?, headers?, eventTypes?}]` |
160
+ | `siemBatchSize` | number | `100` | Max events before auto-flush |
161
+ | `siemFlushIntervalMs` | number | `30000` | Flush interval (ms) |
162
+ | `siemMaxRetries` | number | `3` | Max retry attempts per flush |
163
+ | `siemRetryBackoffMs` | number | `1000` | Initial retry backoff (doubles each retry) |
164
+ | `siemEventFormat` | `"json"` \| `"cef"` | `"json"` | Output format for SIEM events |
165
+
166
+ ### Hot-reload, session isolation, and monitoring settings
167
+
168
+ | Key | Type | Default | Description |
169
+ |-----|------|---------|-------------|
170
+ | `hotReload` | boolean | `false` | Watch config files and reload detection rules on change |
171
+ | `customPatternsFile` | string | `""` | Path to custom patterns JSON file to watch |
172
+ | `hotReloadDebounceMs` | number | `1000` | Debounce interval for file change events |
173
+ | `sessionIsolation` | boolean | `false` | Per-session isolated stores and mapping engines |
174
+ | `monitorEnabled` | boolean | `false` | Active monitoring and alerting pipeline |
175
+ | `monitorRateWindowMs` | number | `60000` | Rolling window for rate baseline |
176
+ | `monitorSpikeMultiplier` | number | `3.0` | Alert when rate exceeds baseline × multiplier |
177
+ | `monitorMaxAlerts` | number | `500` | Max alerts to keep in memory |
178
+
179
+ > **Env var overrides:** `SHROUD_SECRET_KEY`, `SHROUD_PERSISTENT_SALT`, `SHROUD_TENANT_ID`, `SHROUD_SHARED_STORE`, `SHROUD_SIEM_WEBHOOK_URL`, `SHROUD_SIEM_WEBHOOK_AUTH`, and `SHROUD_KEYS` (JSON array) override their respective config keys (priority: env var > plugin config > default).
180
+
181
+ ### Detector overrides
182
+
183
+ Disable or tune individual detection rules by name. Rule names match the built-in pattern names (e.g. `email`, `ipv4`, `phone_intl`, `cisco_enable_secret`). See `src/detectors/regex.ts` for the full list.
184
+
185
+ ```jsonc
186
+ "detectorOverrides": {
187
+ "phone_intl": { "enabled": false }, // disable international phone detection
188
+ "file_path_unix": { "confidence": 0.5 }, // lower confidence (filtered by minConfidence)
189
+ "snmp_community": { "confidence": 1.0 } // boost to always match
190
+ }
191
+ ```
192
+
193
+ Rules not listed keep their defaults. Overrides apply to both direct regex detection and code-aware detection.
194
+
195
+ ### Rule hit counters
196
+
197
+ Shroud tracks per-rule match counts for the lifetime of the process. Counters appear in three places:
198
+
199
+ - **`shroud-stats` CLI** — run `node scripts/shroud-stats.mjs` to see all rules with status, confidence, and hit counts. Shows live cumulative stats from the running gateway (NCG or OpenClaw) via `/tmp/shroud-stats.json`. Use `--test "text with PII"` to test detection against sample input.
200
+ - **Audit log lines** — `byRule=regex:email:3,regex:ipv4:2,...` alongside the existing `byCat` field.
201
+ - **`getStats()`** — the `ruleHits` object in the stats response, useful for programmatic access.
202
+
203
+ Counters reset on `reset()` or gateway restart.
204
+
205
+ ## Redaction levels
206
+
207
+ Three output modes for different audiences:
208
+
209
+ - **`full`** (default): Replace with realistic fake values. Best for LLM interaction.
210
+ - **`masked`**: Partial masking (`j***@***.com`, `***-**-1234`). Best for human review.
211
+ - **`stats`**: Category placeholders (`[EMAIL-1]`, `[HOSTNAME-3]`). Best for dashboards.
212
+
213
+ ```jsonc
214
+ "redactionLevel": "masked"
215
+ ```
216
+
217
+ ## Enterprise Edition
218
+
219
+ The **Shroud Enterprise Edition** adds features for teams and regulated environments:
220
+
221
+ - **Multi-tenant isolation** — per-tenant HMAC keying and mapping stores
222
+ - **SIEM integration** — real-time event streaming to webhooks (JSON/CEF)
223
+ - **Key rotation** — rotate secrets without losing existing mappings
224
+ - **Active monitoring** — anomaly detection with alerting pipeline
225
+ - **Policy-as-code** — external JSON policy files with glob/regex rules
226
+ - **Shared store** — cross-agent file-backed mapping synchronization
227
+ - **Compliance mode** — locked category enforcement with audit trail
228
+ - **Exposure tracking** — rate-of-exposure alerting per category
229
+ - **Hot-reload** — live rule updates without restart
230
+ - **Session isolation** — per-session stores and mapping engines
231
+ - **Session handoff** — encrypted export/import for session continuity
232
+ - **Provenance tagging** — invisible audit markers in output
233
+ - **Corpus pre-scanning** — batch obfuscation for RAG pipelines
234
+
235
+ Contact for licensing: https://github.com/walterkeating-stack/shroud
236
+
237
+ ## Detection intelligence
238
+
239
+ Shroud includes a `ContextDetector` that wraps the regex engine with post-detection intelligence:
240
+
241
+ - **Context-aware boosting**: Text blocks containing config keywords (`interface`, `router ospf`, `hostname`) get +10% confidence for detected entities.
242
+ - **Proximity clustering**: When a name, email, and phone appear within 200 characters, each gets a confidence boost.
243
+ - **Hostname propagation**: `hostname FCNETR1` in one place → bare `FCNETR1` detected everywhere in the text.
244
+ - **Learned entities**: Hostnames and infra identifiers seen in previous messages are remembered and detected in future messages without requiring config-line context.
245
+ - **Documentation filtering**: RFC 5737 TEST-NET IPs (192.0.2.x, 198.51.100.x, 203.0.113.x), RFC 3849 IPv6 doc prefix (`2001:db8::/32`), IPv6 loopback (`::1`), `example.com` emails, and well-known placeholders are automatically skipped.
246
+ - **Common word decay**: Words like `permit`, `deny`, `default` that happen to match patterns get 50% confidence reduction.
247
+ - **Recursive deobfuscation**: Up to 3 passes for nested structures (fakes inside JSON-encoded strings).
248
+ - **Subnet-aware deobfuscation**: When an LLM derives network/broadcast addresses from fake host IPs (e.g., computing `.0` or `.255`), Shroud reverse-maps them via the SubnetMapper. Works for both CGNAT (IPv4) and ULA (IPv6) fake ranges, including LLM-compressed IPv6 forms.
249
+
250
+ ## Verify it works
251
+
252
+ After restarting OpenClaw, send a message containing PII (e.g. an email or IP). Then check the logs:
253
+
254
+ ```bash
255
+ tail -f ~/.openclaw/logs/openclaw.log \
256
+ | grep -a --line-buffered '"name":"openclaw"' \
257
+ | grep -a --line-buffered 'shroud.*audit' \
258
+ | grep -oP --line-buffered '\[shroud\]\[audit\][^"]*'
259
+ ```
260
+
261
+ You should see:
262
+
263
+ ```
264
+ [shroud][audit] OBFUSCATE req=dc5f9199cfb0d835 | entities=4 | touched=2/5 | blocks=2 | chars=1200->1218 (delta=+18) | modified=YES | byCat=email:1,ip_address:2,hostname:1
265
+ ```
266
+
267
+ With proof hashes enabled:
268
+
269
+ ```
270
+ [shroud][audit] OBFUSCATE req=a3f1bc9e02d4e7f1 | entities=4 | touched=2/5 | blocks=2 | chars=1200->1218 (delta=+18) | modified=YES | byCat=email:1,ip_address:2,hostname:1 | proof_in=8a3c1f0e2b4d proof_out=f7d2a1c9e084 | fakes=[jsmith@corp.net|100.64.0.12|SW-LAB-01]
271
+ ```
272
+
273
+ With compliance locking:
274
+
275
+ ```
276
+ [shroud][audit] OBFUSCATE req=... | ... | COMPLIANCE_WARN=missing:[credit_card]
277
+ ```
278
+
279
+ ### Audit field reference
280
+
281
+ | Field | Meaning |
282
+ |-------|---------|
283
+ | `req` | Random request ID (hex) — correlates obfuscate ↔ deobfuscate |
284
+ | `entities` | Total entities detected and replaced |
285
+ | `touched` | Messages with replacements / total messages |
286
+ | `blocks` | Content blocks with replacements |
287
+ | `chars` | Input → output character count |
288
+ | `delta` | Character count change (fakes may be longer/shorter) |
289
+ | `modified` | `YES` if text was changed, `NO` if pass-through |
290
+ | `byCat` | Entity counts by category |
291
+ | `byRule` | Entity counts by detector rule |
292
+ | `proof_in` | Truncated salted SHA-256 of input text |
293
+ | `proof_out` | Truncated salted SHA-256 of output text |
294
+ | `fakes` | Sample of fake replacement values (never real values) |
295
+ | `COMPLIANCE_WARN` | Missing locked categories (if compliance mode enabled) |
296
+
297
+ ### Note on log duplication
298
+
299
+ OpenClaw logs each plugin message twice (once under the plugin subsystem logger, once under the parent `openclaw` logger). This is normal OpenClaw behavior. Filter to `"name":"openclaw"` to get one line per event, as shown in the verify command above.
300
+
301
+ ## Development
302
+
303
+ ```bash
304
+ npm install
305
+ npm test # run vitest (303 tests)
306
+ npm run build # compile TypeScript
307
+ npm run lint # type-check without emitting
308
+ ```
309
+
310
+ ### Deploy after changes
311
+
312
+ ```bash
313
+ npm run build
314
+ bash deploy-local.sh # → OpenClaw (~/.openclaw/extensions/shroud-privacy/)
315
+ bash deploy-ncg.sh # → NCG (~/.ncg/extensions/shroud-privacy/)
316
+
317
+ openclaw gateway restart # restart OpenClaw
318
+ sudo systemctl restart ncg-gateway.service # restart NCG
319
+ ```
320
+
321
+ ## Release workflow
322
+
323
+ ### Tagging a release
324
+
325
+ ```bash
326
+ # 1. Update version in package.json and openclaw.plugin.json
327
+ # 2. Update CHANGELOG.md
328
+ # 3. Commit and tag
329
+ git add -A
330
+ git commit -m "Release v1.x.y"
331
+ git tag v1.x.y
332
+ git push && git push --tags
333
+ ```
334
+
335
+ Then create a GitHub Release from the tag (attach the changelog entry as notes).
336
+
337
+ ### npm publish (not published yet — maintainers only)
338
+
339
+ This package is **not published to npm**. The `package.json` is pre-configured so publishing is a single command when the time comes. Do not publish without maintainer approval.
340
+
341
+ ```bash
342
+ # Pre-flight (always run before publishing)
343
+ npm pack --dry-run # verify only dist/, openclaw.plugin.json, LICENSE are included
344
+ npm run prepublishOnly # lint + test + build (runs automatically on npm publish)
345
+
346
+ # One-time setup (when you decide to publish)
347
+ npm login
348
+ npm profile enable-2fa auth-and-writes
349
+
350
+ # Publish
351
+ npm publish # publishConfig.access = "public" is already set
352
+ ```
353
+
354
+ **Security notes:**
355
+ - Enable 2FA for both login and publish (`auth-and-writes`). This prevents token-only takeover.
356
+ - Never commit npm tokens to git. Use `npm login` interactively or set `NPM_TOKEN` as a GitHub Actions secret.
357
+ - Use `npm publish --provenance` in CI to add Sigstore attestation (links the package to the exact source commit).
358
+
359
+ ### CI
360
+
361
+ The repo includes `.github/workflows/ci.yml` which runs lint + test + build on every push and PR. The publish job is present but only triggers on `v*` tags and requires `NPM_TOKEN` as a repository secret — it will no-op until that secret is configured.
362
+
363
+ ## Entity categories
364
+
365
+ `person_name`, `email`, `phone`, `ip_address`, `api_key`, `url`, `org_name`, `location`, `file_path`, `credit_card`, `ssn`, `mac_address`, `hostname`, `snmp_community`, `bgp_asn`, `network_credential`, `vlan_id`, `interface_desc`, `route_map`, `ospf_id`, `acl_name`, `iban`, `national_id`, `jwt`, `ics_identifier`, `gps_coordinate`, `certificate`, `custom`
366
+
367
+ ## License
368
+
369
+ [MIT](LICENSE)
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Tamper-evident audit log for PII detection events (in-memory only).
3
+ *
4
+ * Logs what was detected (category, count, timestamp) WITHOUT storing real values.
5
+ * Uses HMAC chaining for tamper evidence -- each log entry includes a hash of
6
+ * the previous entry, so any modification/deletion is detectable.
7
+ */
8
+ import { DetectedEntity } from "./types.js";
9
+ export interface AuditEntry {
10
+ timestamp: number;
11
+ timestampIso: string;
12
+ eventType: string;
13
+ sessionId: string;
14
+ requestId: string;
15
+ categories: Record<string, number>;
16
+ totalEntities: number;
17
+ textLength: number;
18
+ processingTimeMs: number;
19
+ chainHash: string;
20
+ }
21
+ export declare class AuditLogger {
22
+ private readonly _secret;
23
+ private readonly _sessionId;
24
+ private readonly _maxEntries;
25
+ private _lastHash;
26
+ private _entries;
27
+ private _stats;
28
+ constructor(secretKey: string, maxEntries?: number);
29
+ /** Generate a unique request ID. */
30
+ static generateRequestId(): string;
31
+ /** Log an obfuscation event (no real values stored). */
32
+ logObfuscation(entities: DetectedEntity[], textLength: number, requestId?: string, processingTimeMs?: number): void;
33
+ /** Log a deobfuscation event. */
34
+ logDeobfuscation(replacementsMade: number, requestId?: string, processingTimeMs?: number): void;
35
+ private _writeEntry;
36
+ /** Return aggregate statistics (safe to expose). */
37
+ getStats(): object;
38
+ /**
39
+ * Verify the integrity of the audit log chain.
40
+ * Returns { valid, entriesChecked }.
41
+ */
42
+ verifyChain(): {
43
+ valid: boolean;
44
+ entriesChecked: number;
45
+ };
46
+ }