@kosha-ai/server 0.0.6 → 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/dist/config/kosha-config.d.ts +21 -0
- package/dist/config/kosha-config.d.ts.map +1 -1
- package/dist/config/kosha-config.js +31 -2
- package/dist/credentials/credentials.module.d.ts +3 -0
- package/dist/credentials/credentials.module.d.ts.map +1 -0
- package/dist/credentials/credentials.module.js +15 -0
- package/dist/credentials/credentials.service.d.ts +55 -0
- package/dist/credentials/credentials.service.d.ts.map +1 -0
- package/dist/credentials/credentials.service.js +108 -0
- package/dist/egress/ca.service.d.ts +36 -0
- package/dist/egress/ca.service.d.ts.map +1 -0
- package/dist/egress/ca.service.js +117 -0
- package/dist/egress/egress.controller.d.ts +24 -0
- package/dist/egress/egress.controller.d.ts.map +1 -0
- package/dist/egress/egress.controller.js +59 -0
- package/dist/egress/egress.listener.d.ts +37 -0
- package/dist/egress/egress.listener.d.ts.map +1 -0
- package/dist/egress/egress.listener.js +324 -0
- package/dist/egress/egress.module.d.ts +7 -0
- package/dist/egress/egress.module.d.ts.map +1 -0
- package/dist/egress/egress.module.js +23 -0
- package/dist/egress/grants.service.d.ts +132 -0
- package/dist/egress/grants.service.d.ts.map +1 -0
- package/dist/egress/grants.service.js +219 -0
- package/dist/egress/host-rules.service.d.ts +35 -0
- package/dist/egress/host-rules.service.d.ts.map +1 -0
- package/dist/egress/host-rules.service.js +48 -0
- package/dist/generated/prisma/browser.d.ts +5 -0
- package/dist/generated/prisma/browser.d.ts.map +1 -1
- package/dist/generated/prisma/client.d.ts +5 -0
- package/dist/generated/prisma/client.d.ts.map +1 -1
- package/dist/generated/prisma/internal/class.d.ts +11 -0
- package/dist/generated/prisma/internal/class.d.ts.map +1 -1
- package/dist/generated/prisma/internal/class.js +4 -4
- package/dist/generated/prisma/internal/prismaNamespace.d.ts +91 -1
- package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
- package/dist/generated/prisma/internal/prismaNamespace.js +15 -1
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +15 -0
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +15 -1
- package/dist/generated/prisma/models/EgressGrant.d.ts +1538 -0
- package/dist/generated/prisma/models/EgressGrant.d.ts.map +1 -0
- package/dist/generated/prisma/models/EgressGrant.js +1 -0
- package/dist/generated/prisma/models/EndUser.d.ts +127 -0
- package/dist/generated/prisma/models/EndUser.d.ts.map +1 -1
- package/dist/generated/prisma/models/Organization.d.ts +147 -0
- package/dist/generated/prisma/models/Organization.d.ts.map +1 -1
- package/dist/generated/prisma/models.d.ts +1 -0
- package/dist/generated/prisma/models.d.ts.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/kosha.module.d.ts.map +1 -1
- package/dist/kosha.module.js +4 -0
- package/dist/proxy/proxy.module.d.ts.map +1 -1
- package/dist/proxy/proxy.module.js +2 -3
- package/dist/proxy/proxy.service.d.ts +3 -19
- package/dist/proxy/proxy.service.d.ts.map +1 -1
- package/dist/proxy/proxy.service.js +9 -89
- package/package.json +6 -4
- package/prisma/migrations/20260921000000_add_egress_grant/migration.sql +31 -0
- package/prisma/schema.prisma +30 -0
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
var EgressListener_1;
|
|
2
|
+
import { __decorate, __metadata, __param } from "tslib";
|
|
3
|
+
import { Inject, Injectable, Logger, } from '@nestjs/common';
|
|
4
|
+
import { Buffer } from 'node:buffer';
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import https from 'node:https';
|
|
7
|
+
import net from 'node:net';
|
|
8
|
+
import tls from 'node:tls';
|
|
9
|
+
import { CaService } from './ca.service.js';
|
|
10
|
+
import { CredentialsService } from '../credentials/credentials.service.js';
|
|
11
|
+
import { GrantsService } from './grants.service.js';
|
|
12
|
+
import { HostRulesService, } from './host-rules.service.js';
|
|
13
|
+
import { KOSHA_CONFIG } from '../config/tokens.js';
|
|
14
|
+
/**
|
|
15
|
+
* The forward proxy a sandbox points `HTTPS_PROXY` at. Per CONNECT:
|
|
16
|
+
*
|
|
17
|
+
* 1. Authenticate the grant from `Proxy-Authorization`. Network position
|
|
18
|
+
* proves nothing, so 407 is the default answer.
|
|
19
|
+
* 2. No rule for the hostname means tunnel: a byte copy, TLS untouched.
|
|
20
|
+
* 3. A rule means terminate with a leaf from the grant's CA, set the
|
|
21
|
+
* credential header, and re-originate TLS to the real host.
|
|
22
|
+
*
|
|
23
|
+
* It is not an exfiltration control. Anything the workload could already reach
|
|
24
|
+
* it can still reach; this only adds authentication to declared hosts.
|
|
25
|
+
*
|
|
26
|
+
* Its own listener because CONNECT never reaches the Express chain, and its own
|
|
27
|
+
* port because whatever can reach it can ask for a credential.
|
|
28
|
+
*
|
|
29
|
+
* Two safeguards that look optional:
|
|
30
|
+
*
|
|
31
|
+
* - `Host` is pinned to the CONNECT hostname. Otherwise a client negotiates
|
|
32
|
+
* `github.com`, sends a different `Host` inside the encrypted connection,
|
|
33
|
+
* and the credential follows it -- domain fronting.
|
|
34
|
+
* - ALPN offers `http/1.1` only. h2 would hand this server frames it does not
|
|
35
|
+
* parse, silently.
|
|
36
|
+
*/
|
|
37
|
+
/**
|
|
38
|
+
* RFC 9110's hop-by-hop set, plus the proxy's own credentials -- forwarding
|
|
39
|
+
* `proxy-authorization` would hand a sandbox's grant to GitHub.
|
|
40
|
+
*/
|
|
41
|
+
const HOP_BY_HOP = new Set([
|
|
42
|
+
'connection',
|
|
43
|
+
'keep-alive',
|
|
44
|
+
'proxy-authenticate',
|
|
45
|
+
'proxy-authorization',
|
|
46
|
+
'proxy-connection',
|
|
47
|
+
'te',
|
|
48
|
+
'trailer',
|
|
49
|
+
'transfer-encoding',
|
|
50
|
+
'upgrade',
|
|
51
|
+
]);
|
|
52
|
+
const PRUNE_INTERVAL_MS = 24 * 60 * 60_000;
|
|
53
|
+
const CONTEXT = Symbol('kosha.egress.context');
|
|
54
|
+
/**
|
|
55
|
+
* The grant token out of a `Proxy-Authorization: Basic` header. The username is
|
|
56
|
+
* ignored: clients take it from the proxy URL's userinfo and spell it however
|
|
57
|
+
* they like, and the password is the credential.
|
|
58
|
+
*/
|
|
59
|
+
function tokenFromProxyAuth(headers) {
|
|
60
|
+
const header = headers['proxy-authorization'];
|
|
61
|
+
if (typeof header !== 'string')
|
|
62
|
+
return null;
|
|
63
|
+
const [scheme, value] = header.split(' ');
|
|
64
|
+
if (scheme?.toLowerCase() !== 'basic' || value === undefined)
|
|
65
|
+
return null;
|
|
66
|
+
const decoded = Buffer.from(value, 'base64').toString('utf8');
|
|
67
|
+
const separator = decoded.indexOf(':');
|
|
68
|
+
return separator === -1 ? null : decoded.slice(separator + 1);
|
|
69
|
+
}
|
|
70
|
+
function denyTunnel(socket, status, reason) {
|
|
71
|
+
const body = `${reason}\n`;
|
|
72
|
+
socket.end(`HTTP/1.1 ${status} ${status === 407 ? 'Proxy Authentication Required' : 'Bad Gateway'}\r\n` +
|
|
73
|
+
(status === 407
|
|
74
|
+
? 'Proxy-Authenticate: Basic realm="kosha-egress"\r\n'
|
|
75
|
+
: '') +
|
|
76
|
+
'Content-Type: text/plain\r\n' +
|
|
77
|
+
`Content-Length: ${Buffer.byteLength(body)}\r\n` +
|
|
78
|
+
'Connection: close\r\n\r\n' +
|
|
79
|
+
body);
|
|
80
|
+
}
|
|
81
|
+
function parseAuthority(authority) {
|
|
82
|
+
const separator = authority.lastIndexOf(':');
|
|
83
|
+
if (separator === -1)
|
|
84
|
+
return null;
|
|
85
|
+
const host = authority.slice(0, separator);
|
|
86
|
+
const port = Number(authority.slice(separator + 1));
|
|
87
|
+
if (host.length === 0 || !Number.isInteger(port))
|
|
88
|
+
return null;
|
|
89
|
+
return { host, port };
|
|
90
|
+
}
|
|
91
|
+
let EgressListener = EgressListener_1 = class EgressListener {
|
|
92
|
+
config;
|
|
93
|
+
grants;
|
|
94
|
+
hostRules;
|
|
95
|
+
ca;
|
|
96
|
+
credentials;
|
|
97
|
+
logger = new Logger(EgressListener_1.name);
|
|
98
|
+
/** Reused so a clone's many requests do not each pay for a TLS handshake. */
|
|
99
|
+
upstreamAgent = new https.Agent({
|
|
100
|
+
keepAlive: true,
|
|
101
|
+
maxSockets: 64,
|
|
102
|
+
});
|
|
103
|
+
server;
|
|
104
|
+
mitmServer;
|
|
105
|
+
pruneTimer;
|
|
106
|
+
constructor(config, grants, hostRules, ca, credentials) {
|
|
107
|
+
this.config = config;
|
|
108
|
+
this.grants = grants;
|
|
109
|
+
this.hostRules = hostRules;
|
|
110
|
+
this.ca = ca;
|
|
111
|
+
this.credentials = credentials;
|
|
112
|
+
}
|
|
113
|
+
async onApplicationBootstrap() {
|
|
114
|
+
if (!this.config.egress.enabled)
|
|
115
|
+
return;
|
|
116
|
+
const { port } = this.config.egress;
|
|
117
|
+
this.mitmServer = this.createMitmServer();
|
|
118
|
+
this.server = this.createProxyServer();
|
|
119
|
+
await new Promise((resolve, reject) => {
|
|
120
|
+
this.server?.once('error', reject);
|
|
121
|
+
this.server?.listen(port, '0.0.0.0', () => resolve());
|
|
122
|
+
});
|
|
123
|
+
this.pruneTimer = setInterval(() => {
|
|
124
|
+
void this.grants
|
|
125
|
+
.pruneExpired()
|
|
126
|
+
.catch((error) => this.logger.warn(`Prune failed: ${error}`));
|
|
127
|
+
}, PRUNE_INTERVAL_MS);
|
|
128
|
+
this.pruneTimer.unref();
|
|
129
|
+
this.logger.log(`🔐 Egress broker listening on :${port}, brokering ${this.hostRules.brokeredProviderKeys().join(', ') || 'nothing'}`);
|
|
130
|
+
}
|
|
131
|
+
onApplicationShutdown() {
|
|
132
|
+
if (this.pruneTimer)
|
|
133
|
+
clearInterval(this.pruneTimer);
|
|
134
|
+
this.server?.close();
|
|
135
|
+
this.mitmServer?.close();
|
|
136
|
+
}
|
|
137
|
+
createProxyServer() {
|
|
138
|
+
const server = http.createServer((_req, res) => {
|
|
139
|
+
// Plain-HTTP proxying. Nothing brokered here -- every brokered host is
|
|
140
|
+
// HTTPS in practice -- but refusing outright would break an apt or pip
|
|
141
|
+
// source that still uses http.
|
|
142
|
+
res.writeHead(400, { 'content-type': 'text/plain' });
|
|
143
|
+
res.end('The Kosha egress broker proxies CONNECT only. Point HTTPS_PROXY at it and use https urls.\n');
|
|
144
|
+
});
|
|
145
|
+
server.on('connect', (req, clientSocket, head) => {
|
|
146
|
+
clientSocket.on('error', () => undefined);
|
|
147
|
+
void this.handleConnect(req, clientSocket, head).catch((error) => {
|
|
148
|
+
this.logger.error(`CONNECT failed: ${error instanceof Error ? error.message : error}`);
|
|
149
|
+
if (!clientSocket.destroyed) {
|
|
150
|
+
denyTunnel(clientSocket, 502, 'Internal error.');
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
return server;
|
|
155
|
+
}
|
|
156
|
+
async handleConnect(req, clientSocket, head) {
|
|
157
|
+
const token = tokenFromProxyAuth(req.headers);
|
|
158
|
+
if (token === null) {
|
|
159
|
+
denyTunnel(clientSocket, 407, 'A grant is required.');
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const grant = await this.grants.resolve(token);
|
|
163
|
+
if (grant === null) {
|
|
164
|
+
this.logger.warn(`Rejected a CONNECT to ${req.url}: unusable grant`);
|
|
165
|
+
denyTunnel(clientSocket, 407, 'That grant is unknown, expired or revoked. If a task is still running, it needs restarting.');
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const authority = parseAuthority(req.url ?? '');
|
|
169
|
+
if (authority === null) {
|
|
170
|
+
denyTunnel(clientSocket, 502, `Malformed CONNECT target ${req.url}.`);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const rule = this.hostRules.ruleFor(authority.host);
|
|
174
|
+
// A rule this grant cannot use counts as no rule: the request still gets
|
|
175
|
+
// there, unauthenticated. Failing instead would turn "you have not
|
|
176
|
+
// connected Slack" into "the network is broken".
|
|
177
|
+
const connection = rule === undefined
|
|
178
|
+
? null
|
|
179
|
+
: await this.grants.connectionFor(grant, rule.providerKey);
|
|
180
|
+
if (rule === undefined || connection === null || !connection.credential) {
|
|
181
|
+
this.logger.debug(`Tunnelling ${authority.host}:${authority.port} for grant ${grant.id}`);
|
|
182
|
+
this.tunnel(clientSocket, head, authority, grant.id);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
this.logger.debug(`Intercepting ${authority.host} for grant ${grant.id} as ${rule.providerKey}`);
|
|
186
|
+
this.intercept(clientSocket, head, {
|
|
187
|
+
grant,
|
|
188
|
+
host: authority.host,
|
|
189
|
+
port: authority.port,
|
|
190
|
+
rule,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
/** Copies bytes both ways and gets out of the way. TLS is never inspected. */
|
|
194
|
+
tunnel(clientSocket, head, authority, grantId) {
|
|
195
|
+
const upstream = net.connect(authority.port, authority.host, () => {
|
|
196
|
+
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
197
|
+
if (head.length > 0)
|
|
198
|
+
upstream.write(head);
|
|
199
|
+
upstream.pipe(clientSocket);
|
|
200
|
+
clientSocket.pipe(upstream);
|
|
201
|
+
});
|
|
202
|
+
upstream.setNoDelay(true);
|
|
203
|
+
upstream.on('error', (error) => {
|
|
204
|
+
this.logger.warn(`Tunnel to ${authority.host} failed for grant ${grantId}: ${error.message}`);
|
|
205
|
+
if (!clientSocket.destroyed)
|
|
206
|
+
denyTunnel(clientSocket, 502, error.message);
|
|
207
|
+
});
|
|
208
|
+
clientSocket.on('error', () => upstream.destroy());
|
|
209
|
+
}
|
|
210
|
+
/** Terminates TLS with a leaf from the grant's CA and feeds it to the parser. */
|
|
211
|
+
intercept(clientSocket, head, context) {
|
|
212
|
+
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
213
|
+
if (head.length > 0)
|
|
214
|
+
clientSocket.unshift(head);
|
|
215
|
+
const leaf = this.ca.leafFor(context.grant, context.host);
|
|
216
|
+
const secured = new tls.TLSSocket(clientSocket, {
|
|
217
|
+
ALPNProtocols: ['http/1.1'],
|
|
218
|
+
cert: leaf.cert,
|
|
219
|
+
isServer: true,
|
|
220
|
+
key: leaf.key,
|
|
221
|
+
});
|
|
222
|
+
secured[CONTEXT] = context;
|
|
223
|
+
secured.on('error', (error) =>
|
|
224
|
+
// Almost always the client refusing the CA -- which means the PEM never
|
|
225
|
+
// made it into the sandbox, or the tool ignores the env var naming it.
|
|
226
|
+
this.logger.warn(`TLS interception of ${context.host} failed: ${error.message}`));
|
|
227
|
+
this.mitmServer?.emit('connection', secured);
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* The HTTP server that sees decrypted requests. `emit('connection', socket)`
|
|
231
|
+
* hands Node's own parser a socket it did not accept, which buys keep-alive,
|
|
232
|
+
* chunked bodies and pipelining for free; the per-connection facts ride on
|
|
233
|
+
* the socket under `CONTEXT`.
|
|
234
|
+
*/
|
|
235
|
+
createMitmServer() {
|
|
236
|
+
return http.createServer((req, res) => {
|
|
237
|
+
const context = req.socket[CONTEXT];
|
|
238
|
+
if (context === undefined) {
|
|
239
|
+
res.writeHead(500, { 'content-type': 'text/plain' });
|
|
240
|
+
res.end('The egress broker lost track of this connection.\n');
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
void this.forward(req, res, context);
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
async forward(req, res, context) {
|
|
247
|
+
const started = Date.now();
|
|
248
|
+
const { grant, host, port, rule } = context;
|
|
249
|
+
let injected;
|
|
250
|
+
try {
|
|
251
|
+
const connection = await this.grants.connectionFor(grant, rule.providerKey);
|
|
252
|
+
if (connection === null) {
|
|
253
|
+
throw new Error(`This grant can no longer use ${rule.providerKey}. The connection may have been revoked.`);
|
|
254
|
+
}
|
|
255
|
+
const credential = await this.credentials.resolveCredential(connection);
|
|
256
|
+
injected = rule.headers({
|
|
257
|
+
accessToken: credential.accessToken,
|
|
258
|
+
tokenType: credential.tokenType,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
const status = typeof error.getStatus === 'function'
|
|
263
|
+
? error.getStatus()
|
|
264
|
+
: 502;
|
|
265
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
266
|
+
this.logger.warn(`Could not authenticate ${host} for grant ${grant.id}: ${message}`);
|
|
267
|
+
res.writeHead(status, { 'content-type': 'text/plain' });
|
|
268
|
+
res.end(`${message}\n`);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
const headers = {};
|
|
272
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
273
|
+
if (value === undefined || HOP_BY_HOP.has(name))
|
|
274
|
+
continue;
|
|
275
|
+
headers[name] = value;
|
|
276
|
+
}
|
|
277
|
+
// The Host pin, and the credential last so a client cannot pre-set a header
|
|
278
|
+
// the rule is about to write and have the two merge.
|
|
279
|
+
headers.host = host;
|
|
280
|
+
for (const [name, value] of Object.entries(injected)) {
|
|
281
|
+
headers[name.toLowerCase()] = value;
|
|
282
|
+
}
|
|
283
|
+
const upstream = https.request({
|
|
284
|
+
agent: this.upstreamAgent,
|
|
285
|
+
headers,
|
|
286
|
+
host,
|
|
287
|
+
method: req.method,
|
|
288
|
+
path: req.url,
|
|
289
|
+
port,
|
|
290
|
+
// A real TLS connection to the real host, verified against the system
|
|
291
|
+
// trust store. The per-grant CA has nothing to do with this leg.
|
|
292
|
+
servername: host,
|
|
293
|
+
}, (upstreamRes) => {
|
|
294
|
+
const outbound = {};
|
|
295
|
+
for (const [name, value] of Object.entries(upstreamRes.headers)) {
|
|
296
|
+
if (value === undefined || HOP_BY_HOP.has(name))
|
|
297
|
+
continue;
|
|
298
|
+
outbound[name] = value;
|
|
299
|
+
}
|
|
300
|
+
res.writeHead(upstreamRes.statusCode ?? 502, outbound);
|
|
301
|
+
upstreamRes.pipe(res);
|
|
302
|
+
this.logger.log(
|
|
303
|
+
// Query strings are dropped: a provider may put a token in one.
|
|
304
|
+
`${req.method ?? 'GET'} ${host}${(req.url ?? '/').split('?')[0]} -> ${upstreamRes.statusCode ?? 0} as ${rule.providerKey} (grant ${grant.id}, ${Date.now() - started}ms)`);
|
|
305
|
+
});
|
|
306
|
+
upstream.on('error', (error) => {
|
|
307
|
+
this.logger.warn(`Upstream ${host} failed: ${error.message}`);
|
|
308
|
+
if (!res.headersSent) {
|
|
309
|
+
res.writeHead(502, { 'content-type': 'text/plain' });
|
|
310
|
+
}
|
|
311
|
+
res.end(`The egress broker could not reach ${host}: ${error.message}\n`);
|
|
312
|
+
});
|
|
313
|
+
req.pipe(upstream);
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
EgressListener = EgressListener_1 = __decorate([
|
|
317
|
+
Injectable(),
|
|
318
|
+
__param(0, Inject(KOSHA_CONFIG)),
|
|
319
|
+
__metadata("design:paramtypes", [Object, GrantsService,
|
|
320
|
+
HostRulesService,
|
|
321
|
+
CaService,
|
|
322
|
+
CredentialsService])
|
|
323
|
+
], EgressListener);
|
|
324
|
+
export { EgressListener };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"egress.module.d.ts","sourceRoot":"","sources":["../../src/egress/egress.module.ts"],"names":[],"mappings":"AAQA;;;GAGG;AACH,qBAMa,YAAY;CAAG"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { __decorate } from "tslib";
|
|
2
|
+
import { Module } from '@nestjs/common';
|
|
3
|
+
import { CaService } from './ca.service.js';
|
|
4
|
+
import { CredentialsModule } from '../credentials/credentials.module.js';
|
|
5
|
+
import { EgressController } from './egress.controller.js';
|
|
6
|
+
import { EgressListener } from './egress.listener.js';
|
|
7
|
+
import { GrantsService } from './grants.service.js';
|
|
8
|
+
import { HostRulesService } from './host-rules.service.js';
|
|
9
|
+
/**
|
|
10
|
+
* Imported by KoshaModule only when `egress.enabled`, so an app that has not
|
|
11
|
+
* asked for a forward proxy never registers the listener's lifecycle hook.
|
|
12
|
+
*/
|
|
13
|
+
let EgressModule = class EgressModule {
|
|
14
|
+
};
|
|
15
|
+
EgressModule = __decorate([
|
|
16
|
+
Module({
|
|
17
|
+
imports: [CredentialsModule],
|
|
18
|
+
controllers: [EgressController],
|
|
19
|
+
providers: [CaService, EgressListener, GrantsService, HostRulesService],
|
|
20
|
+
exports: [GrantsService],
|
|
21
|
+
})
|
|
22
|
+
], EgressModule);
|
|
23
|
+
export { EgressModule };
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { CaService } from './ca.service.js';
|
|
2
|
+
import { CryptoService } from '../crypto/crypto.service.js';
|
|
3
|
+
import { HostRulesService } from './host-rules.service.js';
|
|
4
|
+
import { PrismaService } from '../prisma/prisma.service.js';
|
|
5
|
+
/**
|
|
6
|
+
* Grants: what a sandbox may authenticate as, and for how long.
|
|
7
|
+
*
|
|
8
|
+
* A grant names an end user. It is not a provider credential and cannot be
|
|
9
|
+
* turned into one outside this process, so a leaked one buys only the calls
|
|
10
|
+
* that sandbox could already make, until it expires or is revoked.
|
|
11
|
+
*/
|
|
12
|
+
export interface Grant {
|
|
13
|
+
readonly id: string;
|
|
14
|
+
readonly organizationId: string;
|
|
15
|
+
readonly endUserId: string;
|
|
16
|
+
/** Empty means every provider this end user has connected. */
|
|
17
|
+
readonly providerKeys: readonly string[];
|
|
18
|
+
readonly caPem: string;
|
|
19
|
+
readonly caKeyPem: string;
|
|
20
|
+
readonly expiresAt: Date;
|
|
21
|
+
}
|
|
22
|
+
export interface MintGrantInput {
|
|
23
|
+
readonly endUserExternalId: string;
|
|
24
|
+
readonly providerKeys?: readonly string[];
|
|
25
|
+
readonly expiresAt: Date;
|
|
26
|
+
readonly label?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface MintedGrant {
|
|
29
|
+
readonly grantId: string;
|
|
30
|
+
/** Returned exactly once. Nothing can read it back afterwards. */
|
|
31
|
+
readonly token: string;
|
|
32
|
+
readonly caPem: string;
|
|
33
|
+
readonly expiresAt: Date;
|
|
34
|
+
/** The providers this grant actually resolved to, for the caller to report. */
|
|
35
|
+
readonly providers: string[];
|
|
36
|
+
}
|
|
37
|
+
export declare class GrantsService {
|
|
38
|
+
private readonly prisma;
|
|
39
|
+
private readonly crypto;
|
|
40
|
+
private readonly ca;
|
|
41
|
+
private readonly hostRules;
|
|
42
|
+
private readonly logger;
|
|
43
|
+
private readonly cache;
|
|
44
|
+
constructor(prisma: PrismaService, crypto: CryptoService, ca: CaService, hostRules: HostRulesService);
|
|
45
|
+
/**
|
|
46
|
+
* Unsalted on purpose: the token is 32 random bytes, so there is nothing to
|
|
47
|
+
* brute-force and a per-row salt would only stop the lookup being an index
|
|
48
|
+
* scan.
|
|
49
|
+
*/
|
|
50
|
+
private hashToken;
|
|
51
|
+
mint(organizationId: string, input: MintGrantInput): Promise<MintedGrant>;
|
|
52
|
+
revoke(organizationId: string, grantId: string): Promise<boolean>;
|
|
53
|
+
/**
|
|
54
|
+
* The grant a token names, or null for unknown, expired and revoked alike --
|
|
55
|
+
* telling those apart would tell an attacker which guess was once real.
|
|
56
|
+
*/
|
|
57
|
+
resolve(token: string): Promise<Grant | null>;
|
|
58
|
+
/**
|
|
59
|
+
* The active connection this grant may use for a provider, or null. Scoped by
|
|
60
|
+
* organization and end user, never by an id in a request -- that is what
|
|
61
|
+
* stops one grant reaching another tenant's credential.
|
|
62
|
+
*/
|
|
63
|
+
connectionFor(grant: Grant, providerKey: string): Promise<({
|
|
64
|
+
configuration: {
|
|
65
|
+
provider: {
|
|
66
|
+
name: string;
|
|
67
|
+
key: string;
|
|
68
|
+
id: string;
|
|
69
|
+
createdAt: Date;
|
|
70
|
+
updatedAt: Date;
|
|
71
|
+
authType: import("../generated/prisma/enums.js").AuthType;
|
|
72
|
+
authorizationUrl: string | null;
|
|
73
|
+
tokenUrl: string | null;
|
|
74
|
+
revokeUrl: string | null;
|
|
75
|
+
apiBaseUrl: string | null;
|
|
76
|
+
scopesAvailable: string[];
|
|
77
|
+
docsUrl: string | null;
|
|
78
|
+
logoUrl: string | null;
|
|
79
|
+
isActive: boolean;
|
|
80
|
+
};
|
|
81
|
+
} & {
|
|
82
|
+
name: string;
|
|
83
|
+
id: string;
|
|
84
|
+
createdAt: Date;
|
|
85
|
+
updatedAt: Date;
|
|
86
|
+
metadata: import("@prisma/client/runtime/client").JsonValue | null;
|
|
87
|
+
scopes: string[];
|
|
88
|
+
slug: string;
|
|
89
|
+
organizationId: string;
|
|
90
|
+
providerId: string;
|
|
91
|
+
environment: import("../generated/prisma/enums.js").ConnectionEnvironment;
|
|
92
|
+
authType: import("../generated/prisma/enums.js").AuthType;
|
|
93
|
+
clientId: string | null;
|
|
94
|
+
encryptedClientSecret: string | null;
|
|
95
|
+
redirectUri: string | null;
|
|
96
|
+
isEnabled: boolean;
|
|
97
|
+
};
|
|
98
|
+
credential: {
|
|
99
|
+
id: string;
|
|
100
|
+
createdAt: Date;
|
|
101
|
+
updatedAt: Date;
|
|
102
|
+
refreshToken: string | null;
|
|
103
|
+
expiresAt: Date | null;
|
|
104
|
+
idToken: string | null;
|
|
105
|
+
accessToken: string;
|
|
106
|
+
connectionId: string;
|
|
107
|
+
tokenType: string | null;
|
|
108
|
+
refreshTokenExpiresAt: Date | null;
|
|
109
|
+
} | null;
|
|
110
|
+
} & {
|
|
111
|
+
id: string;
|
|
112
|
+
createdAt: Date;
|
|
113
|
+
updatedAt: Date;
|
|
114
|
+
status: import("../generated/prisma/enums.js").ConnectionStatus;
|
|
115
|
+
metadata: import("@prisma/client/runtime/client").JsonValue | null;
|
|
116
|
+
scopes: string[];
|
|
117
|
+
organizationId: string;
|
|
118
|
+
endUserId: string;
|
|
119
|
+
configurationId: string;
|
|
120
|
+
label: string | null;
|
|
121
|
+
externalAccountId: string | null;
|
|
122
|
+
lastSyncedAt: Date | null;
|
|
123
|
+
lastUsedAt: Date | null;
|
|
124
|
+
errorMessage: string | null;
|
|
125
|
+
}) | null>;
|
|
126
|
+
/** Deletes grants that expired a while ago. Housekeeping, nothing depends on it. */
|
|
127
|
+
pruneExpired(): Promise<number>;
|
|
128
|
+
private forget;
|
|
129
|
+
/** Which brokered providers this end user has actually connected. */
|
|
130
|
+
private providersFor;
|
|
131
|
+
}
|
|
132
|
+
//# sourceMappingURL=grants.service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"grants.service.d.ts","sourceRoot":"","sources":["../../src/egress/grants.service.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D;;;;;;GAMG;AAEH,MAAM,WAAW,KAAK;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,8DAA8D;IAC9D,QAAQ,CAAC,YAAY,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,kEAAkE;IAClE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;IACzB,+EAA+E;IAC/E,QAAQ,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC;CAC9B;AAkBD,qBACa,aAAa;IAKtB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,EAAE;IACnB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAP5B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkC;IACzD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAiC;gBAGpC,MAAM,EAAE,aAAa,EACrB,MAAM,EAAE,aAAa,EACrB,EAAE,EAAE,SAAS,EACb,SAAS,EAAE,gBAAgB;IAG9C;;;;OAIG;IACH,OAAO,CAAC,SAAS;IAIX,IAAI,CACR,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,cAAc,GACpB,OAAO,CAAC,WAAW,CAAC;IAkFjB,MAAM,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAavE;;;OAGG;IACG,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC;IAqCnD;;;;OAIG;IACG,aAAa,CAAC,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAsBrD,oFAAoF;IAC9E,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC;IAOrC,OAAO,CAAC,MAAM;IAMd,qEAAqE;YACvD,YAAY;CA6B3B"}
|