@kosha-ai/server 0.0.6 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/api-key.guard.d.ts +7 -2
- package/dist/auth/api-key.guard.d.ts.map +1 -1
- package/dist/auth/api-key.guard.js +28 -8
- package/dist/auth/auth.factory.d.ts +15 -1
- package/dist/auth/auth.factory.d.ts.map +1 -1
- package/dist/auth/auth.factory.js +48 -2
- package/dist/bootstrap.d.ts.map +1 -1
- package/dist/bootstrap.js +24 -6
- 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/configurations/configurations.controller.d.ts +11 -136
- package/dist/configurations/configurations.controller.d.ts.map +1 -1
- package/dist/configurations/configurations.controller.js +58 -25
- package/dist/configurations/configurations.module.d.ts.map +1 -1
- package/dist/configurations/configurations.module.js +4 -1
- package/dist/configurations/configurations.repository.d.ts +43 -0
- package/dist/configurations/configurations.repository.d.ts.map +1 -0
- package/dist/configurations/configurations.repository.js +76 -0
- package/dist/configurations/configurations.service.d.ts +38 -194
- package/dist/configurations/configurations.service.d.ts.map +1 -1
- package/dist/configurations/configurations.service.js +118 -110
- package/dist/configurations/dto/create-configuration.dto.d.ts +8 -0
- package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -0
- package/dist/configurations/dto/create-configuration.dto.js +54 -0
- package/dist/configurations/dto/update-configuration.dto.d.ts +7 -0
- package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -0
- package/dist/configurations/dto/update-configuration.dto.js +39 -0
- package/dist/connect/connect.controller.d.ts +6 -8
- package/dist/connect/connect.controller.d.ts.map +1 -1
- package/dist/connect/connect.controller.js +45 -15
- package/dist/connect/connect.module.d.ts.map +1 -1
- package/dist/connect/connect.module.js +4 -2
- package/dist/connect/connect.repository.d.ts +78 -0
- package/dist/connect/connect.repository.d.ts.map +1 -0
- package/dist/connect/connect.repository.js +146 -0
- package/dist/connect/connect.service.d.ts +28 -19
- package/dist/connect/connect.service.d.ts.map +1 -1
- package/dist/connect/connect.service.js +149 -163
- package/dist/connect/dto/create-connect-session.dto.d.ts +8 -0
- package/dist/connect/dto/create-connect-session.dto.d.ts.map +1 -0
- package/dist/connect/dto/create-connect-session.dto.js +55 -0
- package/dist/connect/dto/create-test-session.dto.d.ts +10 -0
- package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -0
- package/dist/connect/dto/create-test-session.dto.js +34 -0
- package/dist/connections/connections.controller.d.ts +8 -61
- package/dist/connections/connections.controller.d.ts.map +1 -1
- package/dist/connections/connections.controller.js +31 -9
- package/dist/connections/connections.module.d.ts.map +1 -1
- package/dist/connections/connections.module.js +4 -1
- package/dist/connections/connections.repository.d.ts +24 -0
- package/dist/connections/connections.repository.d.ts.map +1 -0
- package/dist/connections/connections.repository.js +66 -0
- package/dist/connections/connections.service.d.ts +24 -69
- package/dist/connections/connections.service.d.ts.map +1 -1
- package/dist/connections/connections.service.js +59 -56
- package/dist/connections/dto/list-connections.dto.d.ts +5 -0
- package/dist/connections/dto/list-connections.dto.d.ts.map +1 -0
- package/dist/connections/dto/list-connections.dto.js +25 -0
- package/dist/connections/environment-connections.controller.d.ts +26 -0
- package/dist/connections/environment-connections.controller.d.ts.map +1 -0
- package/dist/connections/environment-connections.controller.js +81 -0
- package/dist/connections/environment-connections.module.d.ts +11 -0
- package/dist/connections/environment-connections.module.d.ts.map +1 -0
- package/dist/connections/environment-connections.module.js +21 -0
- 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.repository.d.ts +8 -0
- package/dist/credentials/credentials.repository.d.ts.map +1 -0
- package/dist/credentials/credentials.repository.js +21 -0
- package/dist/credentials/credentials.service.d.ts +45 -0
- package/dist/credentials/credentials.service.d.ts.map +1 -0
- package/dist/credentials/credentials.service.js +135 -0
- package/dist/crypto/credential-envelope.d.ts +56 -0
- package/dist/crypto/credential-envelope.d.ts.map +1 -0
- package/dist/crypto/credential-envelope.js +70 -0
- package/dist/crypto/crypto.service.d.ts +8 -0
- package/dist/crypto/crypto.service.d.ts.map +1 -1
- package/dist/crypto/crypto.service.js +12 -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/dto/mint-grant.dto.d.ts +7 -0
- package/dist/egress/dto/mint-grant.dto.d.ts.map +1 -0
- package/dist/egress/dto/mint-grant.dto.js +44 -0
- package/dist/egress/egress.controller.d.ts +18 -0
- package/dist/egress/egress.controller.d.ts.map +1 -0
- package/dist/egress/egress.controller.js +80 -0
- package/dist/egress/egress.listener.d.ts +39 -0
- package/dist/egress/egress.listener.d.ts.map +1 -0
- package/dist/egress/egress.listener.js +328 -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 +31 -0
- package/dist/egress/egress.repository.d.ts +58 -0
- package/dist/egress/egress.repository.d.ts.map +1 -0
- package/dist/egress/egress.repository.js +116 -0
- package/dist/egress/grants.service.d.ts +77 -0
- package/dist/egress/grants.service.d.ts.map +1 -0
- package/dist/egress/grants.service.js +159 -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/environments/dto/create-environment.dto.d.ts +6 -0
- package/dist/environments/dto/create-environment.dto.d.ts.map +1 -0
- package/dist/environments/dto/create-environment.dto.js +34 -0
- package/dist/environments/dto/update-environment.dto.d.ts +5 -0
- package/dist/environments/dto/update-environment.dto.d.ts.map +1 -0
- package/dist/environments/dto/update-environment.dto.js +24 -0
- package/dist/environments/environments.controller.d.ts +53 -0
- package/dist/environments/environments.controller.d.ts.map +1 -0
- package/dist/environments/environments.controller.js +101 -0
- package/dist/environments/environments.module.d.ts +3 -0
- package/dist/environments/environments.module.d.ts.map +1 -0
- package/dist/environments/environments.module.js +15 -0
- package/dist/environments/environments.repository.d.ts +37 -0
- package/dist/environments/environments.repository.d.ts.map +1 -0
- package/dist/environments/environments.repository.js +82 -0
- package/dist/environments/environments.service.d.ts +43 -0
- package/dist/environments/environments.service.d.ts.map +1 -0
- package/dist/environments/environments.service.js +124 -0
- package/dist/generated/prisma/browser.d.ts +17 -35
- package/dist/generated/prisma/browser.d.ts.map +1 -1
- package/dist/generated/prisma/client.d.ts +17 -35
- package/dist/generated/prisma/client.d.ts.map +1 -1
- package/dist/generated/prisma/commonInputTypes.d.ts +104 -145
- package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -1
- package/dist/generated/prisma/enums.d.ts +1 -21
- package/dist/generated/prisma/enums.d.ts.map +1 -1
- package/dist/generated/prisma/enums.js +1 -18
- package/dist/generated/prisma/internal/class.d.ts +24 -46
- 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 +258 -472
- package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
- package/dist/generated/prisma/internal/prismaNamespace.js +45 -83
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +45 -85
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +45 -83
- package/dist/generated/prisma/models/Account.d.ts +344 -26
- package/dist/generated/prisma/models/Account.d.ts.map +1 -1
- package/dist/generated/prisma/models/Configuration.d.ts +218 -851
- package/dist/generated/prisma/models/Configuration.d.ts.map +1 -1
- package/dist/generated/prisma/models/EgressGrant.d.ts +1535 -0
- package/dist/generated/prisma/models/EgressGrant.d.ts.map +1 -0
- package/dist/generated/prisma/models/Environment.d.ts +1644 -0
- package/dist/generated/prisma/models/Environment.d.ts.map +1 -0
- package/dist/generated/prisma/models/Invitation.d.ts +42 -1
- package/dist/generated/prisma/models/Invitation.d.ts.map +1 -1
- package/dist/generated/prisma/models/Organization.d.ts +183 -322
- package/dist/generated/prisma/models/Organization.d.ts.map +1 -1
- package/dist/generated/prisma/models/Session.d.ts +36 -1
- package/dist/generated/prisma/models/Session.d.ts.map +1 -1
- package/dist/generated/prisma/models/Team.d.ts +1498 -0
- package/dist/generated/prisma/models/Team.d.ts.map +1 -0
- package/dist/generated/prisma/models/TeamMember.d.ts +1281 -0
- package/dist/generated/prisma/models/TeamMember.d.ts.map +1 -0
- package/dist/generated/prisma/models/User.d.ts +338 -2
- package/dist/generated/prisma/models/User.d.ts.map +1 -1
- package/dist/generated/prisma/models.d.ts +4 -6
- package/dist/generated/prisma/models.d.ts.map +1 -1
- package/dist/index.d.ts +20 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +17 -3
- package/dist/integrations/integrations.controller.d.ts +2 -1
- package/dist/integrations/integrations.controller.d.ts.map +1 -1
- package/dist/integrations/integrations.module.d.ts.map +1 -1
- package/dist/integrations/integrations.module.js +0 -2
- package/dist/kosha.module.d.ts.map +1 -1
- package/dist/kosha.module.js +13 -3
- package/dist/proxy/proxy.controller.d.ts +8 -3
- package/dist/proxy/proxy.controller.d.ts.map +1 -1
- package/dist/proxy/proxy.controller.js +26 -10
- package/dist/proxy/proxy.module.d.ts.map +1 -1
- package/dist/proxy/proxy.module.js +5 -3
- package/dist/proxy/proxy.repository.d.ts +24 -0
- package/dist/proxy/proxy.repository.d.ts.map +1 -0
- package/dist/proxy/proxy.repository.js +47 -0
- package/dist/proxy/proxy.service.d.ts +17 -21
- package/dist/proxy/proxy.service.d.ts.map +1 -1
- package/dist/proxy/proxy.service.js +61 -110
- package/package.json +9 -4
- package/prisma/migrations/20260929101936_init/migration.sql +345 -0
- package/prisma/migrations/20260930102529_connection_config/migration.sql +2 -0
- package/prisma/schema.prisma +103 -178
- package/dist/generated/prisma/models/ConnectSession.d.ts +0 -1606
- package/dist/generated/prisma/models/ConnectSession.d.ts.map +0 -1
- package/dist/generated/prisma/models/Connection.d.ts +0 -1949
- package/dist/generated/prisma/models/Connection.d.ts.map +0 -1
- package/dist/generated/prisma/models/ConnectionCredential.d.ts +0 -1293
- package/dist/generated/prisma/models/ConnectionCredential.d.ts.map +0 -1
- package/dist/generated/prisma/models/EndUser.d.ts +0 -1539
- package/dist/generated/prisma/models/EndUser.d.ts.map +0 -1
- package/dist/generated/prisma/models/OAuthState.d.ts +0 -1404
- package/dist/generated/prisma/models/OAuthState.d.ts.map +0 -1
- package/dist/generated/prisma/models/OAuthState.js +0 -1
- package/dist/generated/prisma/models/Provider.d.ts +0 -1462
- package/dist/generated/prisma/models/Provider.d.ts.map +0 -1
- package/dist/generated/prisma/models/Provider.js +0 -1
- package/dist/integrations/provider-sync.service.d.ts +0 -24
- package/dist/integrations/provider-sync.service.d.ts.map +0 -1
- package/dist/integrations/provider-sync.service.js +0 -74
- package/prisma/migrations/20260908000000_init/migration.sql +0 -209
- package/prisma/migrations/20260908161813_add_connect_domain/migration.sql +0 -173
- package/prisma/migrations/20260916000000_add_configuration_slug/migration.sql +0 -15
- /package/dist/generated/prisma/models/{ConnectSession.js → EgressGrant.js} +0 -0
- /package/dist/generated/prisma/models/{Connection.js → Environment.js} +0 -0
- /package/dist/generated/prisma/models/{ConnectionCredential.js → Team.js} +0 -0
- /package/dist/generated/prisma/models/{EndUser.js → TeamMember.js} +0 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { __decorate, __metadata, __param } from "tslib";
|
|
2
|
+
import { BadRequestException, Body, Controller, Delete, HttpCode, Param, Post, Req, UseGuards, } from '@nestjs/common';
|
|
3
|
+
import { ApiCreatedResponse, ApiNotFoundResponse, ApiOperation, ApiSecurity, ApiTags, } from '@nestjs/swagger';
|
|
4
|
+
import { AllowAnonymous } from '@thallesp/nestjs-better-auth';
|
|
5
|
+
import { ApiKeyGuard } from '../auth/api-key.guard.js';
|
|
6
|
+
import { MintGrantDto } from './dto/mint-grant.dto.js';
|
|
7
|
+
import { GrantsService } from './grants.service.js';
|
|
8
|
+
/**
|
|
9
|
+
* Minting and revoking egress grants. `ApiKeyGuard` rather than `OrgAuthGuard`
|
|
10
|
+
* because handing a sandbox an identity is an errand for an app's backend, not
|
|
11
|
+
* for a browser session.
|
|
12
|
+
*/
|
|
13
|
+
let EgressController = class EgressController {
|
|
14
|
+
grants;
|
|
15
|
+
constructor(grants) {
|
|
16
|
+
this.grants = grants;
|
|
17
|
+
}
|
|
18
|
+
async mint(request, body) {
|
|
19
|
+
const expiresAt = new Date(body.expiresAt);
|
|
20
|
+
if (Number.isNaN(expiresAt.getTime())) {
|
|
21
|
+
throw new BadRequestException('expiresAt must be an ISO date');
|
|
22
|
+
}
|
|
23
|
+
return this.grants.mint(request.organizationId, environmentOf(request), {
|
|
24
|
+
externalUserId: body.externalUserId,
|
|
25
|
+
expiresAt,
|
|
26
|
+
label: body.label,
|
|
27
|
+
providerKeys: body.providerKeys,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
async revoke(request, id) {
|
|
31
|
+
const revoked = await this.grants.revoke(request.organizationId, id);
|
|
32
|
+
return { grantId: id, revoked };
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
__decorate([
|
|
36
|
+
Post('grants'),
|
|
37
|
+
HttpCode(201),
|
|
38
|
+
ApiOperation({
|
|
39
|
+
summary: 'Mint a grant a sandbox can authenticate with',
|
|
40
|
+
description: 'Returns a token and a CA certificate, once. The sandbox trusts that CA and proxies through Kosha; the credentials themselves never leave the server.',
|
|
41
|
+
}),
|
|
42
|
+
ApiCreatedResponse({
|
|
43
|
+
description: 'The grant, its token, and the providers it resolved to.',
|
|
44
|
+
}),
|
|
45
|
+
ApiNotFoundResponse({
|
|
46
|
+
description: 'That person has connected nothing in this environment.',
|
|
47
|
+
}),
|
|
48
|
+
__param(0, Req()),
|
|
49
|
+
__param(1, Body()),
|
|
50
|
+
__metadata("design:type", Function),
|
|
51
|
+
__metadata("design:paramtypes", [Object, MintGrantDto]),
|
|
52
|
+
__metadata("design:returntype", Promise)
|
|
53
|
+
], EgressController.prototype, "mint", null);
|
|
54
|
+
__decorate([
|
|
55
|
+
Delete('grants/:id'),
|
|
56
|
+
ApiOperation({
|
|
57
|
+
summary: 'Revoke a grant',
|
|
58
|
+
description: 'Takes up to 30 seconds to bite: the broker caches token lookups, since a single git clone makes dozens of them.',
|
|
59
|
+
}),
|
|
60
|
+
__param(0, Req()),
|
|
61
|
+
__param(1, Param('id')),
|
|
62
|
+
__metadata("design:type", Function),
|
|
63
|
+
__metadata("design:paramtypes", [Object, String]),
|
|
64
|
+
__metadata("design:returntype", Promise)
|
|
65
|
+
], EgressController.prototype, "revoke", null);
|
|
66
|
+
EgressController = __decorate([
|
|
67
|
+
ApiTags('egress'),
|
|
68
|
+
ApiSecurity('x-api-key'),
|
|
69
|
+
Controller('egress'),
|
|
70
|
+
AllowAnonymous(),
|
|
71
|
+
UseGuards(ApiKeyGuard),
|
|
72
|
+
__metadata("design:paramtypes", [GrantsService])
|
|
73
|
+
], EgressController);
|
|
74
|
+
export { EgressController };
|
|
75
|
+
function environmentOf(request) {
|
|
76
|
+
if (!request.environmentId) {
|
|
77
|
+
throw new BadRequestException('This route needs an API key, which is what names the environment');
|
|
78
|
+
}
|
|
79
|
+
return request.environmentId;
|
|
80
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type OnApplicationBootstrap, type OnApplicationShutdown } from '@nestjs/common';
|
|
2
|
+
import { CaService } from './ca.service.js';
|
|
3
|
+
import type { ResolvedKoshaConfig } from '../config/kosha-config.js';
|
|
4
|
+
import { CredentialsService } from '../credentials/credentials.service.js';
|
|
5
|
+
import { GrantsService } from './grants.service.js';
|
|
6
|
+
import { IntegrationRegistry } from '../integrations/integration.registry.js';
|
|
7
|
+
import { HostRulesService } from './host-rules.service.js';
|
|
8
|
+
export declare class EgressListener implements OnApplicationBootstrap, OnApplicationShutdown {
|
|
9
|
+
private readonly config;
|
|
10
|
+
private readonly grants;
|
|
11
|
+
private readonly hostRules;
|
|
12
|
+
private readonly ca;
|
|
13
|
+
private readonly credentials;
|
|
14
|
+
private readonly registry;
|
|
15
|
+
private readonly logger;
|
|
16
|
+
/** Reused so a clone's many requests do not each pay for a TLS handshake. */
|
|
17
|
+
private readonly upstreamAgent;
|
|
18
|
+
private server?;
|
|
19
|
+
private mitmServer?;
|
|
20
|
+
private pruneTimer?;
|
|
21
|
+
constructor(config: ResolvedKoshaConfig, grants: GrantsService, hostRules: HostRulesService, ca: CaService, credentials: CredentialsService, registry: IntegrationRegistry);
|
|
22
|
+
onApplicationBootstrap(): Promise<void>;
|
|
23
|
+
onApplicationShutdown(): void;
|
|
24
|
+
private createProxyServer;
|
|
25
|
+
private handleConnect;
|
|
26
|
+
/** Copies bytes both ways and gets out of the way. TLS is never inspected. */
|
|
27
|
+
private tunnel;
|
|
28
|
+
/** Terminates TLS with a leaf from the grant's CA and feeds it to the parser. */
|
|
29
|
+
private intercept;
|
|
30
|
+
/**
|
|
31
|
+
* The HTTP server that sees decrypted requests. `emit('connection', socket)`
|
|
32
|
+
* hands Node's own parser a socket it did not accept, which buys keep-alive,
|
|
33
|
+
* chunked bodies and pipelining for free; the per-connection facts ride on
|
|
34
|
+
* the socket under `CONTEXT`.
|
|
35
|
+
*/
|
|
36
|
+
private createMitmServer;
|
|
37
|
+
private forward;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=egress.listener.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"egress.listener.d.ts","sourceRoot":"","sources":["../../src/egress/egress.listener.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC3B,MAAM,gBAAgB,CAAC;AAWxB,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAc,MAAM,qBAAqB,CAAC;AAChE,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EACL,gBAAgB,EAEjB,MAAM,yBAAyB,CAAC;AAgGjC,qBACa,cACX,YAAW,sBAAsB,EAAE,qBAAqB;IAahC,OAAO,CAAC,QAAQ,CAAC,MAAM;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,EAAE;IACnB,OAAO,CAAC,QAAQ,CAAC,WAAW;IAC5B,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAhB3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmC;IAC1D,6EAA6E;IAC7E,OAAO,CAAC,QAAQ,CAAC,aAAa,CAG3B;IACH,OAAO,CAAC,MAAM,CAAC,CAAc;IAC7B,OAAO,CAAC,UAAU,CAAC,CAAc;IACjC,OAAO,CAAC,UAAU,CAAC,CAAiB;gBAGK,MAAM,EAAE,mBAAmB,EACjD,MAAM,EAAE,aAAa,EACrB,SAAS,EAAE,gBAAgB,EAC3B,EAAE,EAAE,SAAS,EACb,WAAW,EAAE,kBAAkB,EAC/B,QAAQ,EAAE,mBAAmB;IAG1C,sBAAsB,IAAI,OAAO,CAAC,IAAI,CAAC;IA0B7C,qBAAqB,IAAI,IAAI;IAM7B,OAAO,CAAC,iBAAiB;YA6BX,aAAa;IAwD3B,8EAA8E;IAC9E,OAAO,CAAC,MAAM;IAuBd,iFAAiF;IACjF,OAAO,CAAC,SAAS;IA4BjB;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;YAYV,OAAO;CA6FtB"}
|
|
@@ -0,0 +1,328 @@
|
|
|
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 { IntegrationRegistry } from '../integrations/integration.registry.js';
|
|
13
|
+
import { HostRulesService, } from './host-rules.service.js';
|
|
14
|
+
import { KOSHA_CONFIG } from '../config/tokens.js';
|
|
15
|
+
/**
|
|
16
|
+
* The forward proxy a sandbox points `HTTPS_PROXY` at. Per CONNECT:
|
|
17
|
+
*
|
|
18
|
+
* 1. Authenticate the grant from `Proxy-Authorization`. Network position
|
|
19
|
+
* proves nothing, so 407 is the default answer.
|
|
20
|
+
* 2. No rule for the hostname means tunnel: a byte copy, TLS untouched.
|
|
21
|
+
* 3. A rule means terminate with a leaf from the grant's CA, set the
|
|
22
|
+
* credential header, and re-originate TLS to the real host.
|
|
23
|
+
*
|
|
24
|
+
* It is not an exfiltration control. Anything the workload could already reach
|
|
25
|
+
* it can still reach; this only adds authentication to declared hosts.
|
|
26
|
+
*
|
|
27
|
+
* Its own listener because CONNECT never reaches the Express chain, and its own
|
|
28
|
+
* port because whatever can reach it can ask for a credential.
|
|
29
|
+
*
|
|
30
|
+
* Two safeguards that look optional:
|
|
31
|
+
*
|
|
32
|
+
* - `Host` is pinned to the CONNECT hostname. Otherwise a client negotiates
|
|
33
|
+
* `github.com`, sends a different `Host` inside the encrypted connection,
|
|
34
|
+
* and the credential follows it -- domain fronting.
|
|
35
|
+
* - ALPN offers `http/1.1` only. h2 would hand this server frames it does not
|
|
36
|
+
* parse, silently.
|
|
37
|
+
*/
|
|
38
|
+
/**
|
|
39
|
+
* RFC 9110's hop-by-hop set, plus the proxy's own credentials -- forwarding
|
|
40
|
+
* `proxy-authorization` would hand a sandbox's grant to GitHub.
|
|
41
|
+
*/
|
|
42
|
+
const HOP_BY_HOP = new Set([
|
|
43
|
+
'connection',
|
|
44
|
+
'keep-alive',
|
|
45
|
+
'proxy-authenticate',
|
|
46
|
+
'proxy-authorization',
|
|
47
|
+
'proxy-connection',
|
|
48
|
+
'te',
|
|
49
|
+
'trailer',
|
|
50
|
+
'transfer-encoding',
|
|
51
|
+
'upgrade',
|
|
52
|
+
]);
|
|
53
|
+
const PRUNE_INTERVAL_MS = 24 * 60 * 60_000;
|
|
54
|
+
const CONTEXT = Symbol('kosha.egress.context');
|
|
55
|
+
/**
|
|
56
|
+
* The grant token out of a `Proxy-Authorization: Basic` header. The username is
|
|
57
|
+
* ignored: clients take it from the proxy URL's userinfo and spell it however
|
|
58
|
+
* they like, and the password is the credential.
|
|
59
|
+
*/
|
|
60
|
+
function tokenFromProxyAuth(headers) {
|
|
61
|
+
const header = headers['proxy-authorization'];
|
|
62
|
+
if (typeof header !== 'string')
|
|
63
|
+
return null;
|
|
64
|
+
const [scheme, value] = header.split(' ');
|
|
65
|
+
if (scheme?.toLowerCase() !== 'basic' || value === undefined)
|
|
66
|
+
return null;
|
|
67
|
+
const decoded = Buffer.from(value, 'base64').toString('utf8');
|
|
68
|
+
const separator = decoded.indexOf(':');
|
|
69
|
+
return separator === -1 ? null : decoded.slice(separator + 1);
|
|
70
|
+
}
|
|
71
|
+
function denyTunnel(socket, status, reason) {
|
|
72
|
+
const body = `${reason}\n`;
|
|
73
|
+
socket.end(`HTTP/1.1 ${status} ${status === 407 ? 'Proxy Authentication Required' : 'Bad Gateway'}\r\n` +
|
|
74
|
+
(status === 407
|
|
75
|
+
? 'Proxy-Authenticate: Basic realm="kosha-egress"\r\n'
|
|
76
|
+
: '') +
|
|
77
|
+
'Content-Type: text/plain\r\n' +
|
|
78
|
+
`Content-Length: ${Buffer.byteLength(body)}\r\n` +
|
|
79
|
+
'Connection: close\r\n\r\n' +
|
|
80
|
+
body);
|
|
81
|
+
}
|
|
82
|
+
function parseAuthority(authority) {
|
|
83
|
+
const separator = authority.lastIndexOf(':');
|
|
84
|
+
if (separator === -1)
|
|
85
|
+
return null;
|
|
86
|
+
const host = authority.slice(0, separator);
|
|
87
|
+
const port = Number(authority.slice(separator + 1));
|
|
88
|
+
if (host.length === 0 || !Number.isInteger(port))
|
|
89
|
+
return null;
|
|
90
|
+
return { host, port };
|
|
91
|
+
}
|
|
92
|
+
let EgressListener = EgressListener_1 = class EgressListener {
|
|
93
|
+
config;
|
|
94
|
+
grants;
|
|
95
|
+
hostRules;
|
|
96
|
+
ca;
|
|
97
|
+
credentials;
|
|
98
|
+
registry;
|
|
99
|
+
logger = new Logger(EgressListener_1.name);
|
|
100
|
+
/** Reused so a clone's many requests do not each pay for a TLS handshake. */
|
|
101
|
+
upstreamAgent = new https.Agent({
|
|
102
|
+
keepAlive: true,
|
|
103
|
+
maxSockets: 64,
|
|
104
|
+
});
|
|
105
|
+
server;
|
|
106
|
+
mitmServer;
|
|
107
|
+
pruneTimer;
|
|
108
|
+
constructor(config, grants, hostRules, ca, credentials, registry) {
|
|
109
|
+
this.config = config;
|
|
110
|
+
this.grants = grants;
|
|
111
|
+
this.hostRules = hostRules;
|
|
112
|
+
this.ca = ca;
|
|
113
|
+
this.credentials = credentials;
|
|
114
|
+
this.registry = registry;
|
|
115
|
+
}
|
|
116
|
+
async onApplicationBootstrap() {
|
|
117
|
+
if (!this.config.egress.enabled)
|
|
118
|
+
return;
|
|
119
|
+
const { port } = this.config.egress;
|
|
120
|
+
this.mitmServer = this.createMitmServer();
|
|
121
|
+
this.server = this.createProxyServer();
|
|
122
|
+
await new Promise((resolve, reject) => {
|
|
123
|
+
this.server?.once('error', reject);
|
|
124
|
+
this.server?.listen(port, '0.0.0.0', () => resolve());
|
|
125
|
+
});
|
|
126
|
+
this.pruneTimer = setInterval(() => {
|
|
127
|
+
void this.grants
|
|
128
|
+
.pruneExpired()
|
|
129
|
+
.catch((error) => this.logger.warn(`Prune failed: ${error}`));
|
|
130
|
+
}, PRUNE_INTERVAL_MS);
|
|
131
|
+
this.pruneTimer.unref();
|
|
132
|
+
this.logger.log(`🔐 Egress broker listening on :${port}, brokering ${this.hostRules.brokeredProviderKeys().join(', ') || 'nothing'}`);
|
|
133
|
+
}
|
|
134
|
+
onApplicationShutdown() {
|
|
135
|
+
if (this.pruneTimer)
|
|
136
|
+
clearInterval(this.pruneTimer);
|
|
137
|
+
this.server?.close();
|
|
138
|
+
this.mitmServer?.close();
|
|
139
|
+
}
|
|
140
|
+
createProxyServer() {
|
|
141
|
+
const server = http.createServer((_req, res) => {
|
|
142
|
+
// Plain-HTTP proxying. Nothing brokered here -- every brokered host is
|
|
143
|
+
// HTTPS in practice -- but refusing outright would break an apt or pip
|
|
144
|
+
// source that still uses http.
|
|
145
|
+
res.writeHead(400, { 'content-type': 'text/plain' });
|
|
146
|
+
res.end('The Kosha egress broker proxies CONNECT only. Point HTTPS_PROXY at it and use https urls.\n');
|
|
147
|
+
});
|
|
148
|
+
server.on('connect', (req, clientSocket, head) => {
|
|
149
|
+
clientSocket.on('error', () => undefined);
|
|
150
|
+
void this.handleConnect(req, clientSocket, head).catch((error) => {
|
|
151
|
+
this.logger.error(`CONNECT failed: ${error instanceof Error ? error.message : error}`);
|
|
152
|
+
if (!clientSocket.destroyed) {
|
|
153
|
+
denyTunnel(clientSocket, 502, 'Internal error.');
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
return server;
|
|
158
|
+
}
|
|
159
|
+
async handleConnect(req, clientSocket, head) {
|
|
160
|
+
const token = tokenFromProxyAuth(req.headers);
|
|
161
|
+
if (token === null) {
|
|
162
|
+
denyTunnel(clientSocket, 407, 'A grant is required.');
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
const grant = await this.grants.resolve(token);
|
|
166
|
+
if (grant === null) {
|
|
167
|
+
this.logger.warn(`Rejected a CONNECT to ${req.url}: unusable grant`);
|
|
168
|
+
denyTunnel(clientSocket, 407, 'That grant is unknown, expired or revoked. If a task is still running, it needs restarting.');
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const authority = parseAuthority(req.url ?? '');
|
|
172
|
+
if (authority === null) {
|
|
173
|
+
denyTunnel(clientSocket, 502, `Malformed CONNECT target ${req.url}.`);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const rule = this.hostRules.ruleFor(authority.host);
|
|
177
|
+
// A rule this grant cannot use counts as no rule: the request still gets
|
|
178
|
+
// there, unauthenticated. Failing instead would turn "you have not
|
|
179
|
+
// connected Slack" into "the network is broken".
|
|
180
|
+
const borrowable = rule === undefined
|
|
181
|
+
? null
|
|
182
|
+
: await this.grants.credentialFor(grant, rule.providerKey);
|
|
183
|
+
if (rule === undefined || borrowable === null) {
|
|
184
|
+
this.logger.debug(`Tunnelling ${authority.host}:${authority.port} for grant ${grant.id}`);
|
|
185
|
+
this.tunnel(clientSocket, head, authority, grant.id);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
this.logger.debug(`Intercepting ${authority.host} for grant ${grant.id} as ${rule.providerKey}`);
|
|
189
|
+
this.intercept(clientSocket, head, {
|
|
190
|
+
grant,
|
|
191
|
+
host: authority.host,
|
|
192
|
+
port: authority.port,
|
|
193
|
+
rule,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/** Copies bytes both ways and gets out of the way. TLS is never inspected. */
|
|
197
|
+
tunnel(clientSocket, head, authority, grantId) {
|
|
198
|
+
const upstream = net.connect(authority.port, authority.host, () => {
|
|
199
|
+
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
200
|
+
if (head.length > 0)
|
|
201
|
+
upstream.write(head);
|
|
202
|
+
upstream.pipe(clientSocket);
|
|
203
|
+
clientSocket.pipe(upstream);
|
|
204
|
+
});
|
|
205
|
+
upstream.setNoDelay(true);
|
|
206
|
+
upstream.on('error', (error) => {
|
|
207
|
+
this.logger.warn(`Tunnel to ${authority.host} failed for grant ${grantId}: ${error.message}`);
|
|
208
|
+
if (!clientSocket.destroyed)
|
|
209
|
+
denyTunnel(clientSocket, 502, error.message);
|
|
210
|
+
});
|
|
211
|
+
clientSocket.on('error', () => upstream.destroy());
|
|
212
|
+
}
|
|
213
|
+
/** Terminates TLS with a leaf from the grant's CA and feeds it to the parser. */
|
|
214
|
+
intercept(clientSocket, head, context) {
|
|
215
|
+
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
216
|
+
if (head.length > 0)
|
|
217
|
+
clientSocket.unshift(head);
|
|
218
|
+
const leaf = this.ca.leafFor(context.grant, context.host);
|
|
219
|
+
const secured = new tls.TLSSocket(clientSocket, {
|
|
220
|
+
ALPNProtocols: ['http/1.1'],
|
|
221
|
+
cert: leaf.cert,
|
|
222
|
+
isServer: true,
|
|
223
|
+
key: leaf.key,
|
|
224
|
+
});
|
|
225
|
+
secured[CONTEXT] = context;
|
|
226
|
+
secured.on('error', (error) =>
|
|
227
|
+
// Almost always the client refusing the CA -- which means the PEM never
|
|
228
|
+
// made it into the sandbox, or the tool ignores the env var naming it.
|
|
229
|
+
this.logger.warn(`TLS interception of ${context.host} failed: ${error.message}`));
|
|
230
|
+
this.mitmServer?.emit('connection', secured);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* The HTTP server that sees decrypted requests. `emit('connection', socket)`
|
|
234
|
+
* hands Node's own parser a socket it did not accept, which buys keep-alive,
|
|
235
|
+
* chunked bodies and pipelining for free; the per-connection facts ride on
|
|
236
|
+
* the socket under `CONTEXT`.
|
|
237
|
+
*/
|
|
238
|
+
createMitmServer() {
|
|
239
|
+
return http.createServer((req, res) => {
|
|
240
|
+
const context = req.socket[CONTEXT];
|
|
241
|
+
if (context === undefined) {
|
|
242
|
+
res.writeHead(500, { 'content-type': 'text/plain' });
|
|
243
|
+
res.end('The egress broker lost track of this connection.\n');
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
void this.forward(req, res, context);
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
async forward(req, res, context) {
|
|
250
|
+
const started = Date.now();
|
|
251
|
+
const { grant, host, port, rule } = context;
|
|
252
|
+
let injected;
|
|
253
|
+
try {
|
|
254
|
+
const borrowable = await this.grants.credentialFor(grant, rule.providerKey);
|
|
255
|
+
if (borrowable === null) {
|
|
256
|
+
throw new Error(`This grant can no longer use ${rule.providerKey}. The connection may have been revoked.`);
|
|
257
|
+
}
|
|
258
|
+
const credential = await this.credentials.resolve(borrowable.account, this.registry.get(borrowable.configuration.integrationKey));
|
|
259
|
+
injected = rule.headers({
|
|
260
|
+
accessToken: credential.accessToken,
|
|
261
|
+
tokenType: credential.tokenType,
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
const status = typeof error.getStatus === 'function'
|
|
266
|
+
? error.getStatus()
|
|
267
|
+
: 502;
|
|
268
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
269
|
+
this.logger.warn(`Could not authenticate ${host} for grant ${grant.id}: ${message}`);
|
|
270
|
+
res.writeHead(status, { 'content-type': 'text/plain' });
|
|
271
|
+
res.end(`${message}\n`);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const headers = {};
|
|
275
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
276
|
+
if (value === undefined || HOP_BY_HOP.has(name))
|
|
277
|
+
continue;
|
|
278
|
+
headers[name] = value;
|
|
279
|
+
}
|
|
280
|
+
// The Host pin, and the credential last so a client cannot pre-set a header
|
|
281
|
+
// the rule is about to write and have the two merge.
|
|
282
|
+
headers.host = host;
|
|
283
|
+
for (const [name, value] of Object.entries(injected)) {
|
|
284
|
+
headers[name.toLowerCase()] = value;
|
|
285
|
+
}
|
|
286
|
+
const upstream = https.request({
|
|
287
|
+
agent: this.upstreamAgent,
|
|
288
|
+
headers,
|
|
289
|
+
host,
|
|
290
|
+
method: req.method,
|
|
291
|
+
path: req.url,
|
|
292
|
+
port,
|
|
293
|
+
// A real TLS connection to the real host, verified against the system
|
|
294
|
+
// trust store. The per-grant CA has nothing to do with this leg.
|
|
295
|
+
servername: host,
|
|
296
|
+
}, (upstreamRes) => {
|
|
297
|
+
const outbound = {};
|
|
298
|
+
for (const [name, value] of Object.entries(upstreamRes.headers)) {
|
|
299
|
+
if (value === undefined || HOP_BY_HOP.has(name))
|
|
300
|
+
continue;
|
|
301
|
+
outbound[name] = value;
|
|
302
|
+
}
|
|
303
|
+
res.writeHead(upstreamRes.statusCode ?? 502, outbound);
|
|
304
|
+
upstreamRes.pipe(res);
|
|
305
|
+
this.logger.log(
|
|
306
|
+
// Query strings are dropped: a provider may put a token in one.
|
|
307
|
+
`${req.method ?? 'GET'} ${host}${(req.url ?? '/').split('?')[0]} -> ${upstreamRes.statusCode ?? 0} as ${rule.providerKey} (grant ${grant.id}, ${Date.now() - started}ms)`);
|
|
308
|
+
});
|
|
309
|
+
upstream.on('error', (error) => {
|
|
310
|
+
this.logger.warn(`Upstream ${host} failed: ${error.message}`);
|
|
311
|
+
if (!res.headersSent) {
|
|
312
|
+
res.writeHead(502, { 'content-type': 'text/plain' });
|
|
313
|
+
}
|
|
314
|
+
res.end(`The egress broker could not reach ${host}: ${error.message}\n`);
|
|
315
|
+
});
|
|
316
|
+
req.pipe(upstream);
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
EgressListener = EgressListener_1 = __decorate([
|
|
320
|
+
Injectable(),
|
|
321
|
+
__param(0, Inject(KOSHA_CONFIG)),
|
|
322
|
+
__metadata("design:paramtypes", [Object, GrantsService,
|
|
323
|
+
HostRulesService,
|
|
324
|
+
CaService,
|
|
325
|
+
CredentialsService,
|
|
326
|
+
IntegrationRegistry])
|
|
327
|
+
], EgressListener);
|
|
328
|
+
export { EgressListener };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"egress.module.d.ts","sourceRoot":"","sources":["../../src/egress/egress.module.ts"],"names":[],"mappings":"AAUA;;;GAGG;AACH,qBAYa,YAAY;CAAG"}
|
|
@@ -0,0 +1,31 @@
|
|
|
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 { EgressRepository } from './egress.repository.js';
|
|
6
|
+
import { EnvironmentsModule } from '../environments/environments.module.js';
|
|
7
|
+
import { EgressController } from './egress.controller.js';
|
|
8
|
+
import { EgressListener } from './egress.listener.js';
|
|
9
|
+
import { GrantsService } from './grants.service.js';
|
|
10
|
+
import { HostRulesService } from './host-rules.service.js';
|
|
11
|
+
/**
|
|
12
|
+
* Imported by KoshaModule only when `egress.enabled`, so an app that has not
|
|
13
|
+
* asked for a forward proxy never registers the listener's lifecycle hook.
|
|
14
|
+
*/
|
|
15
|
+
let EgressModule = class EgressModule {
|
|
16
|
+
};
|
|
17
|
+
EgressModule = __decorate([
|
|
18
|
+
Module({
|
|
19
|
+
imports: [CredentialsModule, EnvironmentsModule],
|
|
20
|
+
controllers: [EgressController],
|
|
21
|
+
providers: [
|
|
22
|
+
CaService,
|
|
23
|
+
EgressListener,
|
|
24
|
+
EgressRepository,
|
|
25
|
+
GrantsService,
|
|
26
|
+
HostRulesService,
|
|
27
|
+
],
|
|
28
|
+
exports: [GrantsService],
|
|
29
|
+
})
|
|
30
|
+
], EgressModule);
|
|
31
|
+
export { EgressModule };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Account, Configuration } from '../generated/prisma/client.js';
|
|
2
|
+
import { PrismaService } from '../prisma/prisma.service.js';
|
|
3
|
+
export interface GrantRow {
|
|
4
|
+
organizationId: string;
|
|
5
|
+
userId: string;
|
|
6
|
+
tokenHash: string;
|
|
7
|
+
providerKeys: string[];
|
|
8
|
+
caPem: string;
|
|
9
|
+
caKey: string;
|
|
10
|
+
label?: string;
|
|
11
|
+
expiresAt: Date;
|
|
12
|
+
}
|
|
13
|
+
/** A credential the broker may borrow, with the configuration it came from. */
|
|
14
|
+
export interface BorrowableCredential {
|
|
15
|
+
account: Account;
|
|
16
|
+
configuration: Configuration;
|
|
17
|
+
}
|
|
18
|
+
export declare class EgressRepository {
|
|
19
|
+
private readonly prisma;
|
|
20
|
+
constructor(prisma: PrismaService);
|
|
21
|
+
/**
|
|
22
|
+
* The person a grant is minted for. A `user` row exists per environment, so
|
|
23
|
+
* finding one by its derived address settles the environment too — which is
|
|
24
|
+
* why a grant needs no environment column of its own.
|
|
25
|
+
*/
|
|
26
|
+
findEndUser(environmentSlug: string, externalUserId: string): Promise<{
|
|
27
|
+
id: string;
|
|
28
|
+
} | null>;
|
|
29
|
+
createGrant(row: GrantRow): Promise<{
|
|
30
|
+
id: string;
|
|
31
|
+
expiresAt: Date;
|
|
32
|
+
}>;
|
|
33
|
+
revokeGrant(organizationId: string, grantId: string): Promise<number>;
|
|
34
|
+
findLiveGrant(tokenHash: string): import("../generated/prisma/models.js").Prisma__EgressGrantClient<{
|
|
35
|
+
id: string;
|
|
36
|
+
userId: string;
|
|
37
|
+
organizationId: string;
|
|
38
|
+
expiresAt: Date;
|
|
39
|
+
providerKeys: string[];
|
|
40
|
+
caPem: string;
|
|
41
|
+
caKey: string;
|
|
42
|
+
} | null, null, import("@prisma/client/runtime/client").DefaultArgs, {
|
|
43
|
+
omit: import("../generated/prisma/internal/prismaNamespace.js").GlobalOmitConfig | undefined;
|
|
44
|
+
}>;
|
|
45
|
+
deleteExpiredBefore(cutoff: Date): Promise<number>;
|
|
46
|
+
/**
|
|
47
|
+
* A credential this person holds for one integration. Scoped by the grant's
|
|
48
|
+
* own user, never by anything in a request — that is what stops a grant
|
|
49
|
+
* reaching another tenant's credential.
|
|
50
|
+
*
|
|
51
|
+
* There is no provider relation any more, so the integration is matched
|
|
52
|
+
* through the configuration the credential came from.
|
|
53
|
+
*/
|
|
54
|
+
findCredentialFor(userId: string, integrationKey: string): Promise<BorrowableCredential | null>;
|
|
55
|
+
/** Which of these integrations this person has actually connected. */
|
|
56
|
+
connectedIntegrationKeys(userId: string, integrationKeys: string[]): Promise<string[]>;
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=egress.repository.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"egress.repository.d.ts","sourceRoot":"","sources":["../../src/egress/egress.repository.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,MAAM,WAAW,QAAQ;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,+EAA+E;AAC/E,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,aAAa,EAAE,aAAa,CAAC;CAC9B;AAED,qBACa,gBAAgB;IACf,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAElD;;;;OAIG;IACG,WAAW,CACf,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAOjC,WAAW,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,IAAI,CAAA;KAAE,CAAC;IAO9D,WAAW,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAQ3E,aAAa,CAAC,SAAS,EAAE,MAAM;;;;;;;;;;;IAezB,mBAAmB,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAOxD;;;;;;;OAOG;IACG,iBAAiB,CACrB,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAwBvC,sEAAsE;IAChE,wBAAwB,CAC5B,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,MAAM,EAAE,GACxB,OAAO,CAAC,MAAM,EAAE,CAAC;CA8BrB"}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { __decorate, __metadata } from "tslib";
|
|
2
|
+
import { Injectable } from '@nestjs/common';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { derivedEmail } from '../connect/connect.repository.js';
|
|
5
|
+
import { PrismaService } from '../prisma/prisma.service.js';
|
|
6
|
+
let EgressRepository = class EgressRepository {
|
|
7
|
+
prisma;
|
|
8
|
+
constructor(prisma) {
|
|
9
|
+
this.prisma = prisma;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The person a grant is minted for. A `user` row exists per environment, so
|
|
13
|
+
* finding one by its derived address settles the environment too — which is
|
|
14
|
+
* why a grant needs no environment column of its own.
|
|
15
|
+
*/
|
|
16
|
+
async findEndUser(environmentSlug, externalUserId) {
|
|
17
|
+
return this.prisma.user.findUnique({
|
|
18
|
+
where: { email: derivedEmail(environmentSlug, externalUserId) },
|
|
19
|
+
select: { id: true },
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
createGrant(row) {
|
|
23
|
+
return this.prisma.egressGrant.create({
|
|
24
|
+
data: { id: randomUUID(), ...row },
|
|
25
|
+
select: { id: true, expiresAt: true },
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
async revokeGrant(organizationId, grantId) {
|
|
29
|
+
const { count } = await this.prisma.egressGrant.updateMany({
|
|
30
|
+
where: { id: grantId, organizationId, revokedAt: null },
|
|
31
|
+
data: { revokedAt: new Date() },
|
|
32
|
+
});
|
|
33
|
+
return count;
|
|
34
|
+
}
|
|
35
|
+
findLiveGrant(tokenHash) {
|
|
36
|
+
return this.prisma.egressGrant.findFirst({
|
|
37
|
+
where: { tokenHash, revokedAt: null, expiresAt: { gt: new Date() } },
|
|
38
|
+
select: {
|
|
39
|
+
id: true,
|
|
40
|
+
organizationId: true,
|
|
41
|
+
userId: true,
|
|
42
|
+
providerKeys: true,
|
|
43
|
+
caPem: true,
|
|
44
|
+
caKey: true,
|
|
45
|
+
expiresAt: true,
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async deleteExpiredBefore(cutoff) {
|
|
50
|
+
const { count } = await this.prisma.egressGrant.deleteMany({
|
|
51
|
+
where: { expiresAt: { lt: cutoff } },
|
|
52
|
+
});
|
|
53
|
+
return count;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A credential this person holds for one integration. Scoped by the grant's
|
|
57
|
+
* own user, never by anything in a request — that is what stops a grant
|
|
58
|
+
* reaching another tenant's credential.
|
|
59
|
+
*
|
|
60
|
+
* There is no provider relation any more, so the integration is matched
|
|
61
|
+
* through the configuration the credential came from.
|
|
62
|
+
*/
|
|
63
|
+
async findCredentialFor(userId, integrationKey) {
|
|
64
|
+
const configurations = await this.prisma.configuration.findMany({
|
|
65
|
+
where: { integrationKey, isEnabled: true },
|
|
66
|
+
select: { id: true },
|
|
67
|
+
});
|
|
68
|
+
if (configurations.length === 0)
|
|
69
|
+
return null;
|
|
70
|
+
const account = await this.prisma.account.findFirst({
|
|
71
|
+
where: {
|
|
72
|
+
userId,
|
|
73
|
+
providerId: { in: configurations.map((row) => row.id) },
|
|
74
|
+
NOT: { environmentId: null },
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
if (!account)
|
|
78
|
+
return null;
|
|
79
|
+
const configuration = await this.prisma.configuration.findUnique({
|
|
80
|
+
where: { id: account.providerId },
|
|
81
|
+
});
|
|
82
|
+
if (!configuration)
|
|
83
|
+
return null;
|
|
84
|
+
return { account, configuration };
|
|
85
|
+
}
|
|
86
|
+
/** Which of these integrations this person has actually connected. */
|
|
87
|
+
async connectedIntegrationKeys(userId, integrationKeys) {
|
|
88
|
+
if (integrationKeys.length === 0)
|
|
89
|
+
return [];
|
|
90
|
+
const configurations = await this.prisma.configuration.findMany({
|
|
91
|
+
where: { integrationKey: { in: integrationKeys }, isEnabled: true },
|
|
92
|
+
select: { id: true, integrationKey: true },
|
|
93
|
+
});
|
|
94
|
+
if (configurations.length === 0)
|
|
95
|
+
return [];
|
|
96
|
+
const byId = new Map(configurations.map((row) => [row.id, row.integrationKey]));
|
|
97
|
+
const accounts = await this.prisma.account.findMany({
|
|
98
|
+
where: {
|
|
99
|
+
userId,
|
|
100
|
+
providerId: { in: [...byId.keys()] },
|
|
101
|
+
NOT: { environmentId: null },
|
|
102
|
+
},
|
|
103
|
+
select: { providerId: true },
|
|
104
|
+
});
|
|
105
|
+
return [
|
|
106
|
+
...new Set(accounts
|
|
107
|
+
.map((row) => byId.get(row.providerId))
|
|
108
|
+
.filter((key) => key !== undefined)),
|
|
109
|
+
];
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
EgressRepository = __decorate([
|
|
113
|
+
Injectable(),
|
|
114
|
+
__metadata("design:paramtypes", [PrismaService])
|
|
115
|
+
], EgressRepository);
|
|
116
|
+
export { EgressRepository };
|