pgleash 0.0.0-stage → 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.
@@ -0,0 +1,286 @@
1
+ // Opens the real database connection with credentials only pgleash holds.
2
+ import { readFileSync } from 'node:fs';
3
+ import net from 'node:net';
4
+ import tls from 'node:tls';
5
+ import * as P from './protocol.js';
6
+ import { md5Password, ScramClient } from './scram.js';
7
+ export class UpstreamError extends Error {
8
+ code;
9
+ constructor(message, code = '08006') {
10
+ super(message);
11
+ this.code = code;
12
+ }
13
+ }
14
+ const SSL_MODES = ['disable', 'prefer', 'require', 'verify-ca', 'verify-full'];
15
+ /** Parses postgres://user:password@host:port/database?sslmode=require&sslrootcert=/path/ca.pem */
16
+ export function parseUpstreamUrl(url) {
17
+ let u;
18
+ try {
19
+ u = new URL(url);
20
+ }
21
+ catch {
22
+ throw new Error('the upstream must be a postgres:// URL');
23
+ }
24
+ if (u.protocol !== 'postgres:' && u.protocol !== 'postgresql:') {
25
+ throw new Error('the upstream must be a postgres:// URL');
26
+ }
27
+ const user = decodeURIComponent(u.username);
28
+ if (!user)
29
+ throw new Error('the upstream URL needs a user name');
30
+ const sslmode = (u.searchParams.get('sslmode') ?? 'prefer');
31
+ if (!SSL_MODES.includes(sslmode))
32
+ throw new Error(`unsupported sslmode "${sslmode}"`);
33
+ const rootCert = u.searchParams.get('sslrootcert');
34
+ return {
35
+ host: u.hostname.replace(/^\[(.*)\]$/, '$1') || 'localhost',
36
+ port: u.port ? Number(u.port) : 5432,
37
+ user,
38
+ password: u.password ? decodeURIComponent(u.password) : undefined,
39
+ database: decodeURIComponent(u.pathname.slice(1)) || user,
40
+ sslmode,
41
+ ca: rootCert ? readFileSync(rootCert) : undefined,
42
+ };
43
+ }
44
+ /** Reads whole messages from a socket during the handshake. */
45
+ class HandshakeReader {
46
+ reader = new P.MessageReader(false);
47
+ wake;
48
+ failure;
49
+ socket;
50
+ onData = (chunk) => {
51
+ this.reader.push(chunk);
52
+ this.wake?.();
53
+ };
54
+ onError = (err) => {
55
+ this.failure = err;
56
+ this.wake?.();
57
+ };
58
+ onClose = () => {
59
+ this.failure ??= new UpstreamError('the upstream server closed the connection');
60
+ this.wake?.();
61
+ };
62
+ constructor(socket, pending) {
63
+ this.socket = socket;
64
+ if (pending?.length)
65
+ this.reader.push(pending);
66
+ socket.on('data', this.onData);
67
+ socket.on('error', this.onError);
68
+ socket.on('close', this.onClose);
69
+ }
70
+ async next() {
71
+ for (;;) {
72
+ const m = this.reader.next();
73
+ if (m)
74
+ return m;
75
+ if (this.failure)
76
+ throw this.failure;
77
+ await new Promise((resolve) => (this.wake = resolve));
78
+ this.wake = undefined;
79
+ }
80
+ }
81
+ /** Stops reading and returns any bytes that arrived after the last message. */
82
+ detach() {
83
+ this.socket.off('data', this.onData);
84
+ this.socket.off('error', this.onError);
85
+ this.socket.off('close', this.onClose);
86
+ this.socket.pause();
87
+ return this.reader.take();
88
+ }
89
+ }
90
+ function connectTcp(cfg, timeoutMs) {
91
+ return new Promise((resolve, reject) => {
92
+ const socket = net.connect({ host: cfg.host, port: cfg.port });
93
+ const timer = setTimeout(() => {
94
+ socket.destroy();
95
+ reject(new UpstreamError(`timed out connecting to ${cfg.host}:${cfg.port}`));
96
+ }, timeoutMs);
97
+ socket.once('connect', () => {
98
+ clearTimeout(timer);
99
+ socket.setNoDelay(true);
100
+ socket.setKeepAlive(true, 30_000);
101
+ resolve(socket);
102
+ });
103
+ socket.once('error', (err) => {
104
+ clearTimeout(timer);
105
+ reject(new UpstreamError(`could not reach ${cfg.host}:${cfg.port} (${err.message})`));
106
+ });
107
+ });
108
+ }
109
+ function readOneByte(socket) {
110
+ return new Promise((resolve, reject) => {
111
+ const onData = (chunk) => {
112
+ cleanup();
113
+ if (chunk.length !== 1)
114
+ reject(new UpstreamError('unexpected reply to the SSL request'));
115
+ else
116
+ resolve(chunk[0]);
117
+ };
118
+ const onError = (err) => {
119
+ cleanup();
120
+ reject(err);
121
+ };
122
+ const cleanup = () => {
123
+ socket.off('data', onData);
124
+ socket.off('error', onError);
125
+ socket.pause();
126
+ };
127
+ socket.on('data', onData);
128
+ socket.on('error', onError);
129
+ });
130
+ }
131
+ async function negotiateSsl(socket, cfg) {
132
+ if (cfg.sslmode === 'disable')
133
+ return socket;
134
+ socket.write(P.sslRequest());
135
+ const answer = await readOneByte(socket);
136
+ if (answer === 0x4e /* N */) {
137
+ if (cfg.sslmode === 'prefer')
138
+ return socket;
139
+ throw new UpstreamError(`the upstream server does not accept SSL, but sslmode is ${cfg.sslmode}`);
140
+ }
141
+ if (answer !== 0x53 /* S */)
142
+ throw new UpstreamError('unexpected reply to the SSL request');
143
+ const verify = cfg.sslmode === 'verify-ca' || cfg.sslmode === 'verify-full';
144
+ const secure = tls.connect({
145
+ socket,
146
+ servername: net.isIP(cfg.host) ? undefined : cfg.host,
147
+ rejectUnauthorized: verify,
148
+ ca: cfg.ca,
149
+ checkServerIdentity: cfg.sslmode === 'verify-full' ? tls.checkServerIdentity : () => undefined,
150
+ });
151
+ await new Promise((resolve, reject) => {
152
+ secure.once('secureConnect', resolve);
153
+ secure.once('error', (err) => reject(new UpstreamError(`SSL handshake with the upstream failed (${err.message})`)));
154
+ });
155
+ return secure;
156
+ }
157
+ export async function connectUpstream(cfg, opts = {}) {
158
+ let socket = await connectTcp(cfg, opts.timeoutMs ?? 10_000);
159
+ try {
160
+ socket = await negotiateSsl(socket, cfg);
161
+ const reader = new HandshakeReader(socket);
162
+ socket.resume();
163
+ socket.write(P.startupMessage({ ...opts.startupParams, user: cfg.user, database: cfg.database, client_encoding: 'UTF8' }));
164
+ const params = new Map();
165
+ let pid = 0;
166
+ let key = 0;
167
+ let scram;
168
+ const password = () => {
169
+ if (cfg.password === undefined)
170
+ throw new UpstreamError('the upstream server asked for a password, but the URL has none', '28P01');
171
+ return cfg.password;
172
+ };
173
+ const readUntilReady = async () => {
174
+ for (;;) {
175
+ const m = await reader.next();
176
+ switch (m.type) {
177
+ case 'R': {
178
+ const code = m.payload.readInt32BE(0);
179
+ if (code === 0)
180
+ break;
181
+ if (code === 3)
182
+ socket.write(P.passwordMessage(password()));
183
+ else if (code === 5)
184
+ socket.write(P.passwordMessage(md5Password(cfg.user, password(), m.payload.subarray(4, 8))));
185
+ else if (code === 10) {
186
+ const mechanisms = m.payload.subarray(4).toString('utf8').split('\0');
187
+ if (!mechanisms.includes('SCRAM-SHA-256')) {
188
+ throw new UpstreamError(`unsupported SASL mechanisms: ${mechanisms.filter(Boolean).join(', ')}`);
189
+ }
190
+ scram = new ScramClient(password());
191
+ socket.write(P.saslInitialResponse('SCRAM-SHA-256', scram.clientFirst()));
192
+ }
193
+ else if (code === 11) {
194
+ if (!scram)
195
+ throw new UpstreamError('unexpected SASL message');
196
+ socket.write(P.saslResponse(scram.clientFinal(m.payload.subarray(4).toString('utf8'))));
197
+ }
198
+ else if (code === 12) {
199
+ scram?.verifyServerFinal(m.payload.subarray(4).toString('utf8'));
200
+ }
201
+ else {
202
+ throw new UpstreamError(`unsupported authentication method (code ${code})`);
203
+ }
204
+ break;
205
+ }
206
+ case 'S': {
207
+ const [k, next] = P.readCString(m.payload, 0);
208
+ params.set(k, P.readCString(m.payload, next)[0]);
209
+ break;
210
+ }
211
+ case 'K':
212
+ pid = m.payload.readInt32BE(0);
213
+ key = m.payload.readInt32BE(4);
214
+ break;
215
+ case 'E': {
216
+ const f = P.parseFields(m.payload);
217
+ throw new UpstreamError(f.M ?? 'the upstream server returned an error', f.C);
218
+ }
219
+ case 'Z':
220
+ return;
221
+ default:
222
+ break; // NoticeResponse, NegotiateProtocolVersion
223
+ }
224
+ }
225
+ };
226
+ await readUntilReady();
227
+ if (opts.setupSql) {
228
+ socket.write(P.query(opts.setupSql));
229
+ await readUntilReady();
230
+ }
231
+ return { socket, params, pid, key, pending: reader.detach() };
232
+ }
233
+ catch (err) {
234
+ socket.destroy();
235
+ throw err;
236
+ }
237
+ }
238
+ /** Sends a CancelRequest for an upstream backend, over a fresh connection. */
239
+ export async function sendCancel(cfg, pid, key) {
240
+ let socket = await connectTcp(cfg, 5_000);
241
+ try {
242
+ socket = await negotiateSsl(socket, cfg);
243
+ await new Promise((resolve) => socket.end(P.cancelRequest(pid, key), resolve));
244
+ }
245
+ finally {
246
+ socket.destroy();
247
+ }
248
+ }
249
+ /** Runs one query on a fresh connection and returns its rows as text. Used for schema lookups. */
250
+ export async function fetchRows(cfg, sql) {
251
+ const up = await connectUpstream(cfg, { startupParams: { application_name: 'pgleash' } });
252
+ const reader = new HandshakeReader(up.socket, up.pending);
253
+ up.socket.resume();
254
+ try {
255
+ up.socket.write(P.query(sql));
256
+ const rows = [];
257
+ let failure;
258
+ for (;;) {
259
+ const m = await reader.next();
260
+ if (m.type === 'D') {
261
+ const count = m.payload.readInt16BE(0);
262
+ const row = [];
263
+ let i = 2;
264
+ for (let c = 0; c < count; c++) {
265
+ const len = m.payload.readInt32BE(i);
266
+ row.push(len < 0 ? null : m.payload.toString('utf8', i + 4, i + 4 + len));
267
+ i += 4 + Math.max(len, 0);
268
+ }
269
+ rows.push(row);
270
+ }
271
+ else if (m.type === 'E') {
272
+ const f = P.parseFields(m.payload);
273
+ failure = new UpstreamError(f.M ?? 'query failed', f.C);
274
+ }
275
+ else if (m.type === 'Z') {
276
+ if (failure)
277
+ throw failure;
278
+ return rows;
279
+ }
280
+ }
281
+ }
282
+ finally {
283
+ reader.detach();
284
+ up.socket.end(P.terminate());
285
+ }
286
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "pgleash",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A Postgres proxy that keeps AI agents on a leash: read-only by default, no DROP or unbounded DELETE, row caps, off-limits tables and columns, and an audit log.",
5
+ "type": "module",
6
+ "bin": {
7
+ "pgleash": "dist/cli.js"
8
+ },
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "!dist/**/*.test.*",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "node --test --test-concurrency=1 test/*.test.ts",
30
+ "prepublishOnly": "npm run build && npm test"
31
+ },
32
+ "keywords": [
33
+ "postgres",
34
+ "postgresql",
35
+ "ai-agents",
36
+ "mcp",
37
+ "guardrails",
38
+ "proxy",
39
+ "claude-code",
40
+ "cursor",
41
+ "llm",
42
+ "database-security"
43
+ ],
44
+ "author": "Mufasil Iqbal",
45
+ "license": "MIT",
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/mufasil/pgleash.git"
49
+ },
50
+ "homepage": "https://github.com/mufasil/pgleash#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/mufasil/pgleash/issues"
53
+ },
54
+ "dependencies": {
55
+ "@modelcontextprotocol/sdk": "^1.32.2",
56
+ "libpg-query": "^18.3.0",
57
+ "pg": "^8.23.1",
58
+ "zod": "^4.6.7"
59
+ },
60
+ "devDependencies": {
61
+ "@types/node": "^26.6.11",
62
+ "@types/pg": "^8.23.1",
63
+ "embedded-postgres": "^18.7.0-beta.19",
64
+ "typescript": "^7.0.2"
65
+ }
66
+ }