veil-proxy 0.2.0__tar.gz → 0.3.0__tar.gz

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 (50) hide show
  1. veil_proxy-0.3.0/LICENSE +202 -0
  2. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/PKG-INFO +11 -2
  3. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/README.md +6 -1
  4. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/pyproject.toml +7 -2
  5. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/adopt.py +2 -1
  6. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/anthropic.py +29 -6
  7. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/cli.py +86 -21
  8. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/detect.py +98 -17
  9. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/engine.py +5 -3
  10. veil_proxy-0.3.0/veil/filesafe.py +121 -0
  11. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/guard.py +33 -4
  12. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/match.py +39 -0
  13. veil_proxy-0.3.0/veil/mcpdb.py +389 -0
  14. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/proxy.py +12 -2
  15. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/quasi.py +16 -3
  16. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/reseed.py +45 -1
  17. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/responses.py +37 -14
  18. veil_proxy-0.3.0/veil/secretref.py +125 -0
  19. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/shell.py +17 -5
  20. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/sources/__init__.py +21 -6
  21. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/sources/core.py +5 -1
  22. veil_proxy-0.3.0/veil/sources/dynamo.py +105 -0
  23. veil_proxy-0.3.0/veil/sources/git.py +67 -0
  24. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/sources/mongo.py +7 -3
  25. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/sources/sql.py +59 -20
  26. veil_proxy-0.3.0/veil/sources/warehouse.py +204 -0
  27. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/state.py +11 -5
  28. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/__init__.py +0 -0
  29. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/cloud.py +0 -0
  30. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/crypto.py +0 -0
  31. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/data/README.md +0 -0
  32. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/data/pg_anonymizer_identifier.csv +0 -0
  33. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/data/words.txt.gz +0 -0
  34. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/decode.py +0 -0
  35. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/display.py +0 -0
  36. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/hookclient.py +0 -0
  37. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/hooks.py +0 -0
  38. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/keys.py +0 -0
  39. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/ner.py +0 -0
  40. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/openai.py +0 -0
  41. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/rotate.py +0 -0
  42. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/sources/elastic.py +0 -0
  43. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/sources/files.py +0 -0
  44. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/sources/kv.py +0 -0
  45. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/sources/mssql.py +0 -0
  46. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/sources/schema.py +0 -0
  47. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/stream.py +0 -0
  48. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/team.py +0 -0
  49. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/tokens.py +0 -0
  50. {veil_proxy-0.2.0 → veil_proxy-0.3.0}/veil/vault.py +0 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -1,10 +1,11 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: veil-proxy
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Privacy middleware for AI coding agents: the model sees consistent pseudonyms, your machine keeps the real values
5
5
  Keywords: privacy,pii,llm,proxy,pseudonymization,claude-code,coding-agent
6
6
  Requires-Python: >=3.11
7
7
  Description-Content-Type: text/markdown
8
+ License-Expression: Apache-2.0
8
9
  Classifier: Development Status :: 3 - Alpha
9
10
  Classifier: Environment :: Console
10
11
  Classifier: Intended Audience :: Developers
@@ -12,6 +13,7 @@ Classifier: Operating System :: MacOS
12
13
  Classifier: Operating System :: POSIX :: Linux
13
14
  Classifier: Programming Language :: Python :: 3
14
15
  Classifier: Topic :: Security
16
+ License-File: LICENSE
15
17
  Requires-Dist: cryptography>=50.0.2
16
18
  Requires-Dist: httpx>=0.27
17
19
  Requires-Dist: pyahocorasick>=2.3.1
@@ -24,6 +26,7 @@ Requires-Dist: gliner>=0.2.29 ; extra == "ner"
24
26
  Requires-Dist: onnxruntime>=1.31.0 ; extra == "ner"
25
27
  Requires-Dist: psycopg[binary]>=3.3.6 ; extra == "postgres"
26
28
  Requires-Dist: redis>=8.1.0 ; extra == "redis"
29
+ Requires-Dist: snowflake-connector-python>=3.12 ; extra == "snowflake"
27
30
  Project-URL: Homepage, https://github.com/lemonadesaltbagel/veil
28
31
  Project-URL: Issues, https://github.com/lemonadesaltbagel/veil/issues
29
32
  Project-URL: Repository, https://github.com/lemonadesaltbagel/veil
@@ -35,6 +38,7 @@ Provides-Extra: mysql
35
38
  Provides-Extra: ner
36
39
  Provides-Extra: postgres
37
40
  Provides-Extra: redis
41
+ Provides-Extra: snowflake
38
42
 
39
43
  # veil
40
44
 
@@ -72,7 +76,12 @@ Seeds from Postgres, MySQL/MariaDB, SQLite, SQL Server (native sensitivity label
72
76
  Elasticsearch/OpenSearch and fixture files, plus personal fields declared in code (Prisma, Django,
73
77
  Rails, SQLAlchemy, OpenAPI, protobuf), and re-seeds automatically when the data changes.
74
78
 
79
+ Also seeds git history, DynamoDB (personal data inside keys), Snowflake and BigQuery (their privacy
80
+ tags). `veil mcp-db` gives the agent a read-only database tool in which pseudonyms become **bound
81
+ parameters**, so real values are never SQL text.
82
+
75
83
  ```sh
84
+ veil init ~/code/myapp --mcp # also register the database tool with Claude Code
76
85
  veil display tokens # screen sharing: answers keep pseudonyms (veil display real to undo)
77
86
  veil quasi redact # also pseudonymise rare cities, postal codes, birth dates, employers
78
87
  veil keys rotate # re-encrypt the vault; --token-secret for new pseudonyms
@@ -84,6 +93,6 @@ proxy with `allowedProviders: ["customEndpoint"]`.
84
93
 
85
94
  Optional NER for free text: `pip install "veil-proxy[ner]"` then `veil ner-model fetch`.
86
95
 
87
- Status: alpha. Keys: macOS Keychain / Linux Secret Service (`secret-tool`) / Windows Credential
96
+ License: Apache-2.0. Status: alpha. Keys: macOS Keychain / Linux Secret Service (`secret-tool`) / Windows Credential
88
97
  Manager, or `VEIL_VAULT_KEY` / `VEIL_TOKEN_SECRET` (base64). State: `~/.veil` (encrypted vault).
89
98
 
@@ -34,7 +34,12 @@ Seeds from Postgres, MySQL/MariaDB, SQLite, SQL Server (native sensitivity label
34
34
  Elasticsearch/OpenSearch and fixture files, plus personal fields declared in code (Prisma, Django,
35
35
  Rails, SQLAlchemy, OpenAPI, protobuf), and re-seeds automatically when the data changes.
36
36
 
37
+ Also seeds git history, DynamoDB (personal data inside keys), Snowflake and BigQuery (their privacy
38
+ tags). `veil mcp-db` gives the agent a read-only database tool in which pseudonyms become **bound
39
+ parameters**, so real values are never SQL text.
40
+
37
41
  ```sh
42
+ veil init ~/code/myapp --mcp # also register the database tool with Claude Code
38
43
  veil display tokens # screen sharing: answers keep pseudonyms (veil display real to undo)
39
44
  veil quasi redact # also pseudonymise rare cities, postal codes, birth dates, employers
40
45
  veil keys rotate # re-encrypt the vault; --token-secret for new pseudonyms
@@ -46,5 +51,5 @@ proxy with `allowedProviders: ["customEndpoint"]`.
46
51
 
47
52
  Optional NER for free text: `pip install "veil-proxy[ner]"` then `veil ner-model fetch`.
48
53
 
49
- Status: alpha. Keys: macOS Keychain / Linux Secret Service (`secret-tool`) / Windows Credential
54
+ License: Apache-2.0. Status: alpha. Keys: macOS Keychain / Linux Secret Service (`secret-tool`) / Windows Credential
50
55
  Manager, or `VEIL_VAULT_KEY` / `VEIL_TOKEN_SECRET` (base64). State: `~/.veil` (encrypted vault).
@@ -1,8 +1,10 @@
1
1
  [project]
2
2
  name = "veil-proxy"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Privacy middleware for AI coding agents: the model sees consistent pseudonyms, your machine keeps the real values"
5
5
  readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
6
8
  requires-python = ">=3.11"
7
9
  keywords = ["privacy", "pii", "llm", "proxy", "pseudonymization", "claude-code", "coding-agent"]
8
10
  classifiers = [
@@ -33,6 +35,7 @@ redis = ["redis>=8.1.0"]
33
35
  bedrock = ["botocore>=1.43.115"]
34
36
  ner = ["gliner>=0.2.29", "onnxruntime>=1.31.0"]
35
37
  mssql = ["pymssql>=2.3"] # not in `all`: building it from source needs FreeTDS
38
+ snowflake = ["snowflake-connector-python>=3.12"] # not in `all`: large
36
39
  all = ["veil-proxy[postgres,mysql,mongo,redis,bedrock]"]
37
40
 
38
41
  [project.scripts]
@@ -46,6 +49,7 @@ dev = [
46
49
  "mongomock>=4.3.0",
47
50
  "openai>=3.35.1",
48
51
  "pytest>=8",
52
+ "pyyaml>=6.0.3",
49
53
  "veil-proxy[all]",
50
54
  ]
51
55
 
@@ -58,7 +62,8 @@ veil-proxy = { workspace = true }
58
62
  name = "veil"
59
63
 
60
64
  [tool.pytest.ini_options]
61
- pythonpath = ["."] # makes veil_dev importable for the test suite
65
+ pythonpath = ["."]
66
+ faulthandler_timeout = 120 # a hung test dumps every thread's stack (CI diagnosis) # makes veil_dev importable for the test suite
62
67
 
63
68
  [build-system]
64
69
  # Pure-Python backend: building the sdist needs no compiler (Homebrew builds from source).
@@ -11,7 +11,6 @@ import json
11
11
  import os
12
12
  import plistlib
13
13
  import re
14
- import shutil
15
14
  import subprocess
16
15
  import sys
17
16
  import time
@@ -29,6 +28,8 @@ LABEL = os.environ.get("VEIL_SERVICE_LABEL", "dev.veil.proxy")
29
28
  def detect_sources(project: str) -> list[tuple[str, str]]:
30
29
  """[(source, where it was found)] -- credentials stay in the source string, never printed."""
31
30
  found: dict[str, str] = {}
31
+ if os.path.isdir(os.path.join(project, ".git")):
32
+ found["git:" + os.path.abspath(project)] = ".git (commit authors)"
32
33
  for root, dirs, files in os.walk(project):
33
34
  dirs[:] = [d for d in dirs if d not in SKIP]
34
35
  depth = root[len(project):].count(os.sep)
@@ -136,14 +136,37 @@ def rehydrate_tool_input(veil: Veil, policy: Policy, tool: str, tool_input: dict
136
136
  existing = f.read()
137
137
  except OSError:
138
138
  existing = ""
139
+ # ... and each restored value is spelled for where it lands in the file's language
140
+ # (string literal, comment, code, YAML/CSV quoting): veil/filesafe.py
141
+ from . import filesafe
142
+ lang = "python" if tool == "NotebookEdit" else filesafe.language(path)
139
143
  allowed = {t for t in veil.tokens_in(_texts(tool_input))
140
- if (veil.vault.value_for(t) or "\0") in existing}
144
+ if filesafe.present(veil.vault.value_for(t) or "\0", existing, lang)}
145
+
146
+ def edit(current: str, old_real: str, new_tok: str) -> tuple[str, str]:
147
+ """(new_string with values restored, the file after this edit)"""
148
+ i = current.find(old_real) if old_real else -1
149
+ if i < 0:
150
+ return filesafe.restore_into(veil, new_tok, allowed, lang), current
151
+ full = current[:i] + new_tok + current[i + len(old_real):]
152
+ new_real = filesafe.restore_into(veil, new_tok, allowed, lang, full, i)
153
+ return new_real, current[:i] + new_real + current[i + len(old_real):]
154
+
141
155
  for k in CONTENT_FIELDS & out.keys():
142
- out[k] = veil.rehydrate_json(out[k], only=allowed)
143
- if isinstance(out.get("edits"), list): # MultiEdit
144
- out["edits"] = [{**e, "old_string": veil.rehydrate(e.get("old_string", "")),
145
- "new_string": veil.rehydrate(e.get("new_string", ""), only=allowed)}
146
- for e in tool_input["edits"]]
156
+ v = out[k]
157
+ if not isinstance(v, str):
158
+ out[k] = veil.rehydrate_json(v, only=allowed)
159
+ elif k == "new_string":
160
+ out[k] = edit(existing, out.get("old_string") or "", v)[0]
161
+ else: # Write content (the whole file), NotebookEdit new_source (the whole cell)
162
+ out[k] = filesafe.restore_into(veil, v, allowed, lang)
163
+ if isinstance(out.get("edits"), list): # MultiEdit: applied in order
164
+ current, edits = existing, []
165
+ for e in tool_input["edits"]:
166
+ old_real = veil.rehydrate(e.get("old_string", ""))
167
+ new_real, current = edit(current, old_real, e.get("new_string", ""))
168
+ edits.append({**e, "old_string": old_real, "new_string": new_real})
169
+ out["edits"] = edits
147
170
  return out
148
171
  return tool_input
149
172
 
@@ -25,7 +25,7 @@ import json
25
25
  import sys
26
26
 
27
27
  from . import state
28
- from .anthropic import Policy, rehydrate_tool_input
28
+ from .anthropic import Policy
29
29
  from .sources import seed, seed_environment
30
30
 
31
31
 
@@ -57,6 +57,30 @@ def _learn_schema(project: str, save: bool = True) -> dict:
57
57
  return hints
58
58
 
59
59
 
60
+ DB_SCHEMES = ("postgres", "postgresql", "mysql", "mariadb", "mssql", "sqlserver", "mongodb", "mongodb+srv")
61
+
62
+
63
+ def _register_mcp(project: str, remembered: list[str], new: list[str]) -> None:
64
+ import os
65
+ import shutil
66
+ import subprocess
67
+ from urllib.parse import urlparse
68
+ from .adopt import redact_uri, veil_command
69
+ dbs = [src for src in new if urlparse(src).scheme in DB_SCHEMES or src.endswith((".db", ".sqlite", ".sqlite3"))]
70
+ for n, src in enumerate(dbs):
71
+ name = "veil-db" if n == 0 else f"veil-db-{n + 1}"
72
+ index = remembered.index(src if "://" in src else os.path.abspath(src))
73
+ cmd = ["claude", "mcp", "add", name, "--scope", "local", "-e", f"VEIL_HOME={state.home()}", "--",
74
+ *veil_command(), "mcp-db", "--source", str(index)]
75
+ where = redact_uri(src) if "://" in src else os.path.relpath(src, project)
76
+ if shutil.which("claude"):
77
+ r = subprocess.run(cmd, cwd=project, capture_output=True, text=True)
78
+ ok = r.returncode == 0 or "already exists" in (r.stdout + r.stderr)
79
+ print(f" mcp {name} -> {where}" + ("" if ok else f" (failed: {r.stderr.strip()[:120]})"), file=sys.stderr)
80
+ else:
81
+ print(f" mcp run in {project}: {' '.join(cmd)}", file=sys.stderr)
82
+
83
+
60
84
  def _init(veil, args) -> int:
61
85
  import os
62
86
  from . import adopt
@@ -82,7 +106,9 @@ def _init(veil, args) -> int:
82
106
  seed_environment(veil.known)
83
107
  state.save_known(veil.known, veil.vault.cipher)
84
108
  if sources:
85
- state.remember_sources([src for src, _ in sources], veil.vault.cipher)
109
+ remembered = state.remember_sources([src for src, _ in sources], veil.vault.cipher)
110
+ if getattr(args, "mcp", False):
111
+ _register_mcp(project, remembered, [src for src, _ in sources])
86
112
  path = adopt.write_claude_settings(project, args.port, hooks=not args.no_hooks, deny_env=args.deny_env)
87
113
  print(f" wrote {os.path.relpath(path, project)} (ANTHROPIC_BASE_URL=http://127.0.0.1:{args.port})",
88
114
  file=sys.stderr)
@@ -141,29 +167,46 @@ def _team(args) -> int:
141
167
  from .keys import get_key, set_key
142
168
  pw = os.environ.get(args.passphrase_env) if args.passphrase_env else None
143
169
  cfg = state.config()
170
+ from . import secretref
144
171
  if args.action == "export":
145
- print(team.export_bundle(get_key("token-secret", state.home()), cfg.get("allow", []), pw))
146
- print("share via a password manager; it lets teammates derive the same pseudonyms "
147
- "(not decrypt anyone's vault)", file=sys.stderr)
148
- elif args.action == "join":
149
- if not args.value:
150
- raise SystemExit("usage: veil team join <bundle>")
151
- secret, allow = team.import_bundle(args.value[0], pw)
152
- vault_path = os.path.join(state.home(), "vault.db")
172
+ bundle = team.export_bundle(get_key("token-secret", state.home()), cfg.get("allow", []), pw)
173
+ if args.to:
174
+ try:
175
+ secretref.write(args.to, bundle)
176
+ except secretref.RefError as e:
177
+ raise SystemExit(f"veil: {e}")
178
+ print(f"team bundle written to {args.to}; teammates run: veil team join --from {args.to}", file=sys.stderr)
179
+ else:
180
+ print(bundle)
181
+ print("share via a password manager; it lets teammates derive the same pseudonyms "
182
+ "(not decrypt anyone's vault)", file=sys.stderr)
183
+ elif args.action in ("join", "sync"):
184
+ ref = args.source or (cfg.get("team_source") if args.action == "sync" else None)
185
+ if args.action == "sync" and not ref:
186
+ raise SystemExit("no team source remembered: veil team join --from REF")
187
+ if not ref and not args.value:
188
+ raise SystemExit("usage: veil team join <bundle> | veil team join --from REF")
189
+ try:
190
+ secret, allow = team.import_bundle(secretref.read(ref) if ref else args.value[0], pw)
191
+ except secretref.RefError as e:
192
+ raise SystemExit(f"veil: {e}")
193
+ current = get_key("token-secret", state.home())
153
194
  veil = state.load()
154
- if veil.vault.tokens() and not args.reset_vault:
195
+ changed = secret != current
196
+ if changed and veil.vault.tokens() and not (args.reset_vault or args.action == "sync"):
155
197
  raise SystemExit(f"vault already holds {len(veil.vault.tokens())} tokens derived from another secret; "
156
- "re-run with --reset-vault to re-derive them with the team secret")
157
- where = set_key("token-secret", state.home(), secret)
158
- if where == "env":
159
- raise SystemExit("VEIL_TOKEN_SECRET is set in the environment; update it there instead")
160
- if args.reset_vault:
161
- veil.vault._db.execute("DELETE FROM entities_v2")
162
- veil.vault._db.commit()
198
+ "re-run with --reset-vault (old pseudonyms are retired: they still restore)")
199
+ if changed:
200
+ where = set_key("token-secret", state.home(), secret)
201
+ if where == "env":
202
+ raise SystemExit("VEIL_TOKEN_SECRET is set in the environment; update it there instead")
203
+ retired = veil.vault.retire_all() # issued under the old secret: still restored, never issued again
163
204
  cfg["allow"] = sorted(set(cfg.get("allow", [])) | set(allow))
205
+ if ref:
206
+ cfg["team_source"] = ref
164
207
  state.save_config(cfg)
165
- print(f"joined: token secret stored in {where}; allowlist {len(cfg['allow'])} entries"
166
- + ("; vault reset" if args.reset_vault else ""), file=sys.stderr)
208
+ print(("team secret updated" + (f"; {retired} old pseudonyms retired" if retired else "") if changed
209
+ else "team secret unchanged") + f"; allowlist {len(cfg['allow'])} entries", file=sys.stderr)
167
210
  elif args.action == "allow":
168
211
  cfg["allow"] = sorted(set(cfg.get("allow", [])) | set(args.value))
169
212
  state.save_config(cfg)
@@ -239,6 +282,10 @@ def main(argv: list[str] | None = None) -> int:
239
282
  sub.add_parser("seed-env")
240
283
  sub.add_parser("redact"); sub.add_parser("rehydrate")
241
284
  s = sub.add_parser("display"); s.add_argument("mode", nargs="?", choices=["real", "tokens"])
285
+ s = sub.add_parser("mcp-db", help="read-only database tool for the agent (MCP stdio server)")
286
+ s.add_argument("uri", nargs="?", help="database URL or SQLite path")
287
+ s.add_argument("--source", type=int, metavar="N", help="a remembered source (veil sources), so no credentials "
288
+ "appear in the MCP config")
242
289
  s = sub.add_parser("keys", help="rotate the vault key (re-encrypt) or the token secret (new pseudonyms)")
243
290
  s.add_argument("action", choices=["rotate"])
244
291
  s.add_argument("--token-secret", action="store_true", help="new pseudonyms instead of a new vault key")
@@ -270,8 +317,12 @@ def main(argv: list[str] | None = None) -> int:
270
317
  s.add_argument("--no-detect", action="store_true"); s.add_argument("--no-hooks", action="store_true")
271
318
  s.add_argument("--deny-env", action="store_true", help="also deny Claude Code reading .env files")
272
319
  s.add_argument("--dry-run", action="store_true")
320
+ s.add_argument("--mcp", action="store_true", help="register `veil mcp-db` with Claude Code for each database "
321
+ "(local scope: never committed; sources by number: no credentials in the config)")
273
322
  s = sub.add_parser("status"); s.add_argument("project", nargs="?", default="."); s.add_argument("--port", type=int, default=8787)
274
- s = sub.add_parser("team"); s.add_argument("action", choices=["export", "join", "allow", "managed-settings"])
323
+ s = sub.add_parser("team"); s.add_argument("action", choices=["export", "join", "sync", "allow", "managed-settings"])
324
+ s.add_argument("--to", metavar="REF", help="export into a secrets manager: op://, aws-sm://, gcp-sm://, vault://, file:")
325
+ s.add_argument("--from", dest="source", metavar="REF", help="join from a secrets manager (remembered for `team sync`)")
275
326
  s.add_argument("value", nargs="*"); s.add_argument("--passphrase-env", metavar="VAR")
276
327
  s.add_argument("--reset-vault", action="store_true"); s.add_argument("--port", type=int, default=8787)
277
328
  s.add_argument("--no-hooks", action="store_true"); s.add_argument("--lock-hooks", action="store_true")
@@ -294,6 +345,20 @@ def main(argv: list[str] | None = None) -> int:
294
345
  return 0
295
346
  if args.cmd == "keys":
296
347
  return _keys(args)
348
+ if args.cmd == "mcp-db":
349
+ from . import mcpdb
350
+ veil = state.load()
351
+ if args.source is not None: # same numbering as `veil sources`
352
+ sources = state.load_sources(veil.vault.cipher)
353
+ if not 0 <= args.source < len(sources):
354
+ raise SystemExit(f"no remembered source {args.source} (see `veil sources`)")
355
+ uri = sources[args.source]
356
+ elif args.uri:
357
+ uri = args.uri
358
+ else:
359
+ raise SystemExit("usage: veil mcp-db URI | veil mcp-db --source N")
360
+ mcpdb.Server(veil, mcpdb.open_source(uri)).serve()
361
+ return 0
297
362
  if args.cmd == "quasi":
298
363
  from . import quasi
299
364
  if args.mode: