@aictrl/hush 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
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 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 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 those 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
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,112 @@
1
+ <p align="center">
2
+ <img src="logo.svg" width="400" alt="hush Logo" />
3
+ </p>
4
+
5
+ **hush** is a Semantic Security Gateway for AI agents.
6
+ It acts as a local proxy between your AI tools (like Claude Code, Cursor, or custom CLI agents) and LLM providers (Anthropic, OpenAI).
7
+
8
+ Hush ensures that sensitive data—like emails, IP addresses, and secrets—never leaves your machine by redacting it from prompts and tool outputs before they hit the cloud.
9
+
10
+ ## Why Hush?
11
+
12
+ When an AI agent runs a local tool (like `snow` or `ls`), it often returns PII (Personally Identifiable Information) to the terminal. Without Hush, this sensitive data is sent directly to the LLM provider for processing.
13
+
14
+ Hush intercepts this traffic, replaces PII with persistent tokens, and stores the original values in a local `TokenVault`.
15
+
16
+ ## Features
17
+
18
+ - **Semantic Redaction:** Automatically identifies and masks PII (emails, IPs, secrets, credit cards) using high-entropy random tokens (e.g., `[HUSH_EML_8a2b3c]`).
19
+ - **Local Rehydration:** Automatically restores original values in the LLM's response locally. You see the real data; the cloud provider only sees tokens.
20
+ - **Live Protection Dashboard:** Run with `--dashboard` to see a real-time TUI showing PII being blocked and intercepted.
21
+ - **Zero-Trust Architecture:** Local-only processing. PII never leaves your machine. Bindings default to `127.0.0.1`.
22
+ - **Streaming Support:** Robust rehydration for SSE (Server-Sent Events) even when tokens are split across network chunks.
23
+
24
+ ## Getting Started
25
+
26
+ ### Installation
27
+
28
+ ```bash
29
+ npm install -g @aictrl/hush
30
+ ```
31
+
32
+ ### Usage
33
+
34
+ 1. **Start the hush Gateway:**
35
+ ```bash
36
+ hush --dashboard
37
+ ```
38
+ hush will start listening on `http://127.0.0.1:4000`.
39
+
40
+ 2. **Point your AI tool to the Gateway:**
41
+
42
+ For **Claude Code**:
43
+ ```bash
44
+ export ANTHROPIC_BASE_URL=http://127.0.0.1:4000
45
+ claude
46
+ ```
47
+
48
+ For **OpenAI-based tools**:
49
+ ```bash
50
+ export OPENAI_BASE_URL=http://127.0.0.1:4000/v1
51
+ ```
52
+
53
+ For **Google Gemini**:
54
+ ```bash
55
+ # For the Google Generative AI SDK
56
+ export GOOGLE_GENERATIVE_AI_BASE_URL=http://127.0.0.1:4000
57
+
58
+ # For the Gemini CLI
59
+ export CODE_ASSIST_ENDPOINT=http://127.0.0.1:4000
60
+ ```
61
+
62
+ ## Configuration
63
+
64
+ | Variable | Description | Default |
65
+ |----------|-------------|---------|
66
+ | `PORT` | The port the gateway listens on. | `4000` |
67
+ | `HUSH_HOST` | The host interface to bind to. | `127.0.0.1` |
68
+ | `HUSH_AUTH_TOKEN` | If set, the proxy requires `Authorization: Bearer <token>` | `undefined` |
69
+ | `HUSH_DASHBOARD` | Set to `true` to enable the TUI dashboard. | `false` |
70
+
71
+ ## How it Works
72
+
73
+ 1. **Intercept:** Hush sits locally on your machine as an HTTP proxy.
74
+ 2. **Redact:** Before a request is forwarded to Anthropic/OpenAI, Hush scans the message content for sensitive data and swaps it for tokens (e.g., `[USER_EMAIL_1]`).
75
+ 3. **Vault:** The original data is saved in a local, in-memory `TokenVault`.
76
+ 4. **Forward:** The redacted request is sent to the LLM provider.
77
+ 5. **Rehydrate:** When the LLM responds, Hush re-inserts the original values from the vault before showing the response to you.
78
+
79
+ ## Development
80
+
81
+ ### Prerequisites
82
+
83
+ - Node.js 18+
84
+ - npm
85
+
86
+ ### Setup
87
+
88
+ ```bash
89
+ git clone https://github.com/aictrl-dev/hush.git
90
+ cd hush
91
+ npm install
92
+ ```
93
+
94
+ ### Testing
95
+
96
+ ```bash
97
+ npm test
98
+ ```
99
+
100
+ ### Building
101
+
102
+ ```bash
103
+ npm run build
104
+ ```
105
+
106
+ ## Contributing
107
+
108
+ We welcome contributions! Please see our [CONTRIBUTING.md](CONTRIBUTING.md) for details.
109
+
110
+ ## License
111
+
112
+ This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { app } from './index.js';
3
+ import { createLogger } from './lib/logger.js';
4
+ const log = createLogger('hush-cli');
5
+ const PORT = process.env.PORT || 4000;
6
+ app.listen(PORT, () => {
7
+ log.info(`Hush Semantic Gateway is listening on http://localhost:${PORT}`);
8
+ log.info(`To use with Claude Code: export ANTHROPIC_BASE_URL=http://localhost:${PORT}`);
9
+ });
10
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,GAAG,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;AACrC,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC;AAEtC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE;IACpB,GAAG,CAAC,IAAI,CAAC,0DAA0D,IAAI,EAAE,CAAC,CAAC;IAC3E,GAAG,CAAC,IAAI,CAAC,uEAAuE,IAAI,EAAE,CAAC,CAAC;AAC1F,CAAC,CAAC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare const app: import("express-serve-static-core").Express;
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAwBA,eAAO,MAAM,GAAG,6CAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,210 @@
1
+ import express from 'express';
2
+ import cors from 'cors';
3
+ import { createLogger } from './lib/logger.js';
4
+ import { Redactor } from './middleware/redactor.js';
5
+ import { TokenVault } from './vault/token-vault.js';
6
+ import { Dashboard } from './lib/dashboard.js';
7
+ const log = createLogger('hush-proxy');
8
+ const redactor = new Redactor();
9
+ const vault = new TokenVault();
10
+ // Lazy-initialize dashboard to ensure it captures flags set by CLI or ENV
11
+ let _dashboard = null;
12
+ function getDashboard() {
13
+ if (_dashboard)
14
+ return _dashboard;
15
+ if (process.env.HUSH_DASHBOARD === 'true' || process.argv.includes('--dashboard')) {
16
+ _dashboard = new Dashboard();
17
+ }
18
+ return _dashboard;
19
+ }
20
+ // Force immediate initialization if dashboard flag is present
21
+ getDashboard();
22
+ export const app = express();
23
+ // Security: Bind only to localhost by default to prevent network exposure
24
+ const BIND_ADDRESS = process.env.HUSH_HOST || '127.0.0.1';
25
+ // Security: Optional Bearer Token for the proxy itself
26
+ const HUSH_TOKEN = process.env.HUSH_AUTH_TOKEN;
27
+ app.use(cors({ origin: 'http://localhost' })); // Restrict CORS
28
+ app.use(express.json({ limit: '50mb' }));
29
+ /**
30
+ * Security Middleware: Local Proxy Authentication
31
+ */
32
+ app.use((req, res, next) => {
33
+ if (req.path === '/health')
34
+ return next();
35
+ if (HUSH_TOKEN) {
36
+ const authHeader = req.headers['x-hush-token'] || req.headers['authorization'];
37
+ const providedToken = Array.isArray(authHeader) ? authHeader[0] : authHeader;
38
+ if (!providedToken || (providedToken !== HUSH_TOKEN && providedToken !== `Bearer ${HUSH_TOKEN}`)) {
39
+ log.warn({ ip: req.ip }, 'Unauthorized access attempt');
40
+ return res.status(401).json({ error: 'Unauthorized: Invalid HUSH_AUTH_TOKEN' });
41
+ }
42
+ }
43
+ next();
44
+ });
45
+ /**
46
+ * Helper to handle proxying with optional streaming
47
+ */
48
+ async function proxyRequest(req, res, targetUrl, headers) {
49
+ const startTime = performance.now();
50
+ const dashboard = getDashboard();
51
+ // 1. Redact Request Body (Prompts, Tool Results)
52
+ const { content: redactedBody, tokens, hasRedacted } = redactor.redact(req.body);
53
+ const redactionDuration = Math.round(performance.now() - startTime);
54
+ // Log all requests to dashboard
55
+ if (dashboard) {
56
+ dashboard.logRequest(req.path, redactionDuration);
57
+ }
58
+ if (hasRedacted) {
59
+ log.info({ path: req.path, tokenCount: tokens.size, duration: redactionDuration }, 'Redacted sensitive data from request');
60
+ vault.saveTokens(tokens);
61
+ // Log redaction events
62
+ if (dashboard) {
63
+ tokens.forEach((value, token) => {
64
+ const type = token.split('_')[1] ?? 'UNK'; // Extract type from [HUSH_TYPE_ID]
65
+ dashboard.logRedaction(type, token);
66
+ });
67
+ }
68
+ }
69
+ try {
70
+ const response = await fetch(targetUrl, {
71
+ method: 'POST',
72
+ headers: {
73
+ 'Content-Type': 'application/json',
74
+ ...headers,
75
+ },
76
+ body: JSON.stringify(redactedBody),
77
+ signal: AbortSignal.timeout(30000), // 30s timeout
78
+ });
79
+ // Handle Upstream Errors (4xx, 5xx)
80
+ if (!response.ok) {
81
+ log.error({ status: response.status, path: req.path }, 'Upstream provider returned an error');
82
+ const errorData = await response.text();
83
+ return res.status(response.status).send(errorData);
84
+ }
85
+ // Case A: Streaming
86
+ if (req.body.stream && response.body) {
87
+ log.info({ path: req.path }, 'Starting stream proxy');
88
+ res.setHeader('Content-Type', 'text/event-stream');
89
+ res.setHeader('Cache-Control', 'no-cache');
90
+ res.setHeader('Connection', 'keep-alive');
91
+ const reader = response.body.getReader();
92
+ const decoder = new TextDecoder();
93
+ // Security: Use stateful rehydrator to handle tokens split across chunks
94
+ const rehydrateChunk = vault.createStreamingRehydrator();
95
+ try {
96
+ while (true) {
97
+ const { done, value } = await reader.read();
98
+ if (done)
99
+ break;
100
+ const chunk = decoder.decode(value, { stream: true });
101
+ const rehydratedChunk = rehydrateChunk(chunk);
102
+ if (rehydratedChunk) {
103
+ const canWrite = res.write(rehydratedChunk);
104
+ // Handle backpressure
105
+ if (!canWrite) {
106
+ await new Promise((resolve) => res.once('drain', resolve));
107
+ }
108
+ }
109
+ }
110
+ }
111
+ finally {
112
+ reader.releaseLock();
113
+ }
114
+ res.end();
115
+ return;
116
+ }
117
+ // Case B: Regular JSON
118
+ const data = await response.json();
119
+ const rehydratedData = vault.rehydrate(data);
120
+ res.status(response.status).json(rehydratedData);
121
+ }
122
+ catch (error) {
123
+ log.error({ err: error, path: req.path }, 'Failed to forward request');
124
+ res.status(500).json({ error: 'Gateway forwarding failed' });
125
+ }
126
+ }
127
+ /**
128
+ * Handle Anthropic /messages proxy
129
+ */
130
+ app.post('/v1/messages', async (req, res) => {
131
+ const apiKey = req.headers['x-api-key'];
132
+ if (!apiKey)
133
+ return res.status(401).json({ error: 'Missing Anthropic API Key' });
134
+ await proxyRequest(req, res, 'https://api.anthropic.com/v1/messages', {
135
+ 'x-api-key': apiKey,
136
+ 'anthropic-version': req.headers['anthropic-version'] || '2023-06-01',
137
+ });
138
+ });
139
+ /**
140
+ * Handle OpenAI /chat/completions proxy
141
+ */
142
+ app.post('/v1/chat/completions', async (req, res) => {
143
+ const auth = req.headers['authorization'];
144
+ if (!auth)
145
+ return res.status(401).json({ error: 'Missing OpenAI Authorization' });
146
+ await proxyRequest(req, res, 'https://api.openai.com/v1/chat/completions', {
147
+ 'Authorization': auth,
148
+ });
149
+ });
150
+ /**
151
+ * Handle ZhipuAI GLM API proxy (OpenCode + GLM-5)
152
+ * Supports: /api/paas/v4/chat/completions
153
+ * Used by OpenCode when configured with baseURL: http://127.0.0.1:4000/api/paas/v4
154
+ */
155
+ app.post('/api/paas/v4/chat/completions', async (req, res) => {
156
+ const auth = req.headers['authorization'];
157
+ if (!auth)
158
+ return res.status(401).json({ error: 'Missing ZhipuAI Authorization' });
159
+ await proxyRequest(req, res, 'https://api.z.ai/api/paas/v4/chat/completions', {
160
+ 'Authorization': auth,
161
+ });
162
+ });
163
+ /**
164
+ * Handle Google Gemini API proxy
165
+ * Supports: /v1beta/models/{model}:generateContent
166
+ */
167
+ app.post('/v1beta/models/:modelAndAction', async (req, res) => {
168
+ const apiKey = req.headers['x-goog-api-key'] || req.query.key;
169
+ if (!apiKey)
170
+ return res.status(401).json({ error: 'Missing Google API Key' });
171
+ const targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${req.params.modelAndAction}${req.url.includes('?') ? '?' + req.url.split('?')[1] : ''}`;
172
+ await proxyRequest(req, res, targetUrl, {
173
+ 'x-goog-api-key': apiKey,
174
+ });
175
+ });
176
+ // Health check (must be before catch-all)
177
+ app.get('/health', (req, res) => {
178
+ const response = { status: 'running' };
179
+ if (process.env.DEBUG === 'true') {
180
+ response.vaultSize = vault.size;
181
+ }
182
+ res.json(response);
183
+ });
184
+ /**
185
+ * Catch-all Handler: Forward any other requests to Google
186
+ * This ensures login and metadata calls work correctly.
187
+ */
188
+ app.all('/*path', async (req, res) => {
189
+ const targetBase = 'https://generativelanguage.googleapis.com';
190
+ const targetUrl = `${targetBase}${req.url}`;
191
+ log.info({ path: req.path, method: req.method }, 'Forwarding unknown endpoint to Google');
192
+ try {
193
+ const headers = { ...req.headers };
194
+ delete headers.host;
195
+ delete headers.connection;
196
+ const response = await fetch(targetUrl, {
197
+ method: req.method,
198
+ headers,
199
+ body: ['POST', 'PUT', 'PATCH'].includes(req.method) ? JSON.stringify(req.body) : undefined,
200
+ signal: AbortSignal.timeout(30000),
201
+ });
202
+ const data = await response.text();
203
+ res.status(response.status).send(data);
204
+ }
205
+ catch (error) {
206
+ log.error({ err: error, path: req.path }, 'Catch-all forwarding failed');
207
+ res.status(500).json({ error: 'Gateway forwarding failed' });
208
+ }
209
+ });
210
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,OAA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OAAO,OAAO,CAAC,UAAU,CAAC;QAE1B,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,SAAS,EAAE;YACtC,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,OAAO;YACP,IAAI,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;YAC1F,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,KAAK,CAAC;SACnC,CAAC,CAAC;QAEH,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,EAAE,6BAA6B,CAAC,CAAC;QACzE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,2BAA2B,EAAE,CAAC,CAAC;IAC/D,CAAC;AACH,CAAC,CAAC,CAAC"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * hush 🛡️ Dashboard v2 - Terminal Edition
3
+ * Aligned with the official brand book and dashboard mockup.
4
+ */
5
+ export declare class Dashboard {
6
+ private screen;
7
+ private grid;
8
+ private log;
9
+ private piiBreakdown;
10
+ private vaultGauge;
11
+ private latencySpark;
12
+ private statBoxes;
13
+ private stats;
14
+ constructor();
15
+ logRedaction(type: string, token: string): void;
16
+ logRequest(path: string, durationMs?: number): void;
17
+ private getTypeColor;
18
+ private updateUI;
19
+ private render;
20
+ /**
21
+ * Get current dashboard statistics (for testing and programmatic access).
22
+ */
23
+ getStats(): {
24
+ redactedCount: number;
25
+ requestCount: number;
26
+ leaks: number;
27
+ types: Map<string, number>;
28
+ latency: number[];
29
+ };
30
+ }
31
+ //# sourceMappingURL=dashboard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dashboard.d.ts","sourceRoot":"","sources":["../../src/lib/dashboard.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAyB;IACvC,OAAO,CAAC,IAAI,CAAe;IAG3B,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,YAAY,CAAM;IAC1B,OAAO,CAAC,UAAU,CAAM;IACxB,OAAO,CAAC,YAAY,CAAM;IAG1B,OAAO,CAAC,SAAS,CAKf;IAGF,OAAO,CAAC,KAAK,CAMX;;IA0EK,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;IAWxC,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,GAAE,MAAU;IAStD,OAAO,CAAC,YAAY;IAWpB,OAAO,CAAC,QAAQ;IA0BhB,OAAO,CAAC,MAAM;IAId;;OAEG;IACI,QAAQ;;;;;;;CAShB"}