@kosha-ai/server 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/LICENSE +21 -0
  2. package/dist/auth/api-key.guard.d.ts +18 -0
  3. package/dist/auth/api-key.guard.d.ts.map +1 -0
  4. package/dist/auth/api-key.guard.js +33 -0
  5. package/dist/auth/auth.factory.d.ts +35 -0
  6. package/dist/auth/auth.factory.d.ts.map +1 -0
  7. package/dist/auth/auth.factory.js +29 -0
  8. package/dist/bootstrap.d.ts +13 -0
  9. package/dist/bootstrap.d.ts.map +1 -0
  10. package/dist/bootstrap.js +33 -0
  11. package/dist/common/active-organization.d.ts +3 -0
  12. package/dist/common/active-organization.d.ts.map +1 -0
  13. package/dist/common/active-organization.js +8 -0
  14. package/dist/config/kosha-config.d.ts +80 -0
  15. package/dist/config/kosha-config.d.ts.map +1 -0
  16. package/dist/config/kosha-config.js +69 -0
  17. package/dist/config/tokens.d.ts +4 -0
  18. package/dist/config/tokens.d.ts.map +1 -0
  19. package/dist/config/tokens.js +3 -0
  20. package/dist/configurations/configurations.controller.d.ts +143 -0
  21. package/dist/configurations/configurations.controller.d.ts.map +1 -0
  22. package/dist/configurations/configurations.controller.js +76 -0
  23. package/dist/configurations/configurations.module.d.ts +3 -0
  24. package/dist/configurations/configurations.module.d.ts.map +1 -0
  25. package/dist/configurations/configurations.module.js +14 -0
  26. package/dist/configurations/configurations.service.d.ts +210 -0
  27. package/dist/configurations/configurations.service.d.ts.map +1 -0
  28. package/dist/configurations/configurations.service.js +204 -0
  29. package/dist/connect/connect.controller.d.ts +33 -0
  30. package/dist/connect/connect.controller.d.ts.map +1 -0
  31. package/dist/connect/connect.controller.js +123 -0
  32. package/dist/connect/connect.module.d.ts +3 -0
  33. package/dist/connect/connect.module.d.ts.map +1 -0
  34. package/dist/connect/connect.module.js +16 -0
  35. package/dist/connect/connect.service.d.ts +54 -0
  36. package/dist/connect/connect.service.d.ts.map +1 -0
  37. package/dist/connect/connect.service.js +248 -0
  38. package/dist/connections/connections.controller.d.ts +71 -0
  39. package/dist/connections/connections.controller.d.ts.map +1 -0
  40. package/dist/connections/connections.controller.js +51 -0
  41. package/dist/connections/connections.module.d.ts +3 -0
  42. package/dist/connections/connections.module.d.ts.map +1 -0
  43. package/dist/connections/connections.module.js +14 -0
  44. package/dist/connections/connections.service.d.ts +76 -0
  45. package/dist/connections/connections.service.d.ts.map +1 -0
  46. package/dist/connections/connections.service.js +71 -0
  47. package/dist/crypto/crypto.module.d.ts +3 -0
  48. package/dist/crypto/crypto.module.d.ts.map +1 -0
  49. package/dist/crypto/crypto.module.js +13 -0
  50. package/dist/crypto/crypto.service.d.ts +21 -0
  51. package/dist/crypto/crypto.service.d.ts.map +1 -0
  52. package/dist/crypto/crypto.service.js +77 -0
  53. package/dist/generated/prisma/browser.d.ts +88 -0
  54. package/dist/generated/prisma/browser.d.ts.map +1 -0
  55. package/dist/generated/prisma/browser.js +17 -0
  56. package/dist/generated/prisma/client.d.ts +107 -0
  57. package/dist/generated/prisma/client.d.ts.map +1 -0
  58. package/dist/generated/prisma/client.js +34 -0
  59. package/dist/generated/prisma/commonInputTypes.d.ts +478 -0
  60. package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -0
  61. package/dist/generated/prisma/commonInputTypes.js +10 -0
  62. package/dist/generated/prisma/enums.d.ts +22 -0
  63. package/dist/generated/prisma/enums.d.ts.map +1 -0
  64. package/dist/generated/prisma/enums.js +27 -0
  65. package/dist/generated/prisma/internal/class.d.ts +287 -0
  66. package/dist/generated/prisma/internal/class.d.ts.map +1 -0
  67. package/dist/generated/prisma/internal/class.js +49 -0
  68. package/dist/generated/prisma/internal/prismaNamespace.d.ts +1905 -0
  69. package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -0
  70. package/dist/generated/prisma/internal/prismaNamespace.js +299 -0
  71. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +277 -0
  72. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -0
  73. package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +270 -0
  74. package/dist/generated/prisma/models/Account.d.ts +1459 -0
  75. package/dist/generated/prisma/models/Account.d.ts.map +1 -0
  76. package/dist/generated/prisma/models/Account.js +1 -0
  77. package/dist/generated/prisma/models/Apikey.d.ts +1552 -0
  78. package/dist/generated/prisma/models/Apikey.d.ts.map +1 -0
  79. package/dist/generated/prisma/models/Apikey.js +1 -0
  80. package/dist/generated/prisma/models/Configuration.d.ts +1964 -0
  81. package/dist/generated/prisma/models/Configuration.d.ts.map +1 -0
  82. package/dist/generated/prisma/models/Configuration.js +1 -0
  83. package/dist/generated/prisma/models/ConnectSession.d.ts +1606 -0
  84. package/dist/generated/prisma/models/ConnectSession.d.ts.map +1 -0
  85. package/dist/generated/prisma/models/ConnectSession.js +1 -0
  86. package/dist/generated/prisma/models/Connection.d.ts +1949 -0
  87. package/dist/generated/prisma/models/Connection.d.ts.map +1 -0
  88. package/dist/generated/prisma/models/Connection.js +1 -0
  89. package/dist/generated/prisma/models/ConnectionCredential.d.ts +1293 -0
  90. package/dist/generated/prisma/models/ConnectionCredential.d.ts.map +1 -0
  91. package/dist/generated/prisma/models/ConnectionCredential.js +1 -0
  92. package/dist/generated/prisma/models/EndUser.d.ts +1539 -0
  93. package/dist/generated/prisma/models/EndUser.d.ts.map +1 -0
  94. package/dist/generated/prisma/models/EndUser.js +1 -0
  95. package/dist/generated/prisma/models/Invitation.d.ts +1404 -0
  96. package/dist/generated/prisma/models/Invitation.d.ts.map +1 -0
  97. package/dist/generated/prisma/models/Invitation.js +1 -0
  98. package/dist/generated/prisma/models/Member.d.ts +1281 -0
  99. package/dist/generated/prisma/models/Member.d.ts.map +1 -0
  100. package/dist/generated/prisma/models/Member.js +1 -0
  101. package/dist/generated/prisma/models/OAuthState.d.ts +1404 -0
  102. package/dist/generated/prisma/models/OAuthState.d.ts.map +1 -0
  103. package/dist/generated/prisma/models/OAuthState.js +1 -0
  104. package/dist/generated/prisma/models/Organization.d.ts +1807 -0
  105. package/dist/generated/prisma/models/Organization.d.ts.map +1 -0
  106. package/dist/generated/prisma/models/Organization.js +1 -0
  107. package/dist/generated/prisma/models/Provider.d.ts +1462 -0
  108. package/dist/generated/prisma/models/Provider.d.ts.map +1 -0
  109. package/dist/generated/prisma/models/Provider.js +1 -0
  110. package/dist/generated/prisma/models/Session.d.ts +1316 -0
  111. package/dist/generated/prisma/models/Session.d.ts.map +1 -0
  112. package/dist/generated/prisma/models/Session.js +1 -0
  113. package/dist/generated/prisma/models/User.d.ts +1593 -0
  114. package/dist/generated/prisma/models/User.d.ts.map +1 -0
  115. package/dist/generated/prisma/models/User.js +1 -0
  116. package/dist/generated/prisma/models/Verification.d.ts +1026 -0
  117. package/dist/generated/prisma/models/Verification.d.ts.map +1 -0
  118. package/dist/generated/prisma/models/Verification.js +1 -0
  119. package/dist/generated/prisma/models.d.ts +17 -0
  120. package/dist/generated/prisma/models.d.ts.map +1 -0
  121. package/dist/generated/prisma/models.js +1 -0
  122. package/dist/health/health.controller.d.ts +12 -0
  123. package/dist/health/health.controller.d.ts.map +1 -0
  124. package/dist/health/health.controller.js +36 -0
  125. package/dist/index.d.ts +26 -0
  126. package/dist/index.d.ts.map +1 -0
  127. package/dist/index.js +25 -0
  128. package/dist/integrations/integration.registry.d.ts +19 -0
  129. package/dist/integrations/integration.registry.d.ts.map +1 -0
  130. package/dist/integrations/integration.registry.js +45 -0
  131. package/dist/integrations/integrations.controller.d.ts +26 -0
  132. package/dist/integrations/integrations.controller.d.ts.map +1 -0
  133. package/dist/integrations/integrations.controller.js +47 -0
  134. package/dist/integrations/integrations.module.d.ts +6 -0
  135. package/dist/integrations/integrations.module.d.ts.map +1 -0
  136. package/dist/integrations/integrations.module.js +26 -0
  137. package/dist/integrations/provider-sync.service.d.ts +24 -0
  138. package/dist/integrations/provider-sync.service.d.ts.map +1 -0
  139. package/dist/integrations/provider-sync.service.js +74 -0
  140. package/dist/kosha.module.d.ts +11 -0
  141. package/dist/kosha.module.d.ts.map +1 -0
  142. package/dist/kosha.module.js +48 -0
  143. package/dist/prisma/prisma.module.d.ts +11 -0
  144. package/dist/prisma/prisma.module.d.ts.map +1 -0
  145. package/dist/prisma/prisma.module.js +24 -0
  146. package/dist/prisma/prisma.service.d.ts +10 -0
  147. package/dist/prisma/prisma.service.d.ts.map +1 -0
  148. package/dist/prisma/prisma.service.js +25 -0
  149. package/dist/proxy/proxy.controller.d.ts +17 -0
  150. package/dist/proxy/proxy.controller.d.ts.map +1 -0
  151. package/dist/proxy/proxy.controller.js +64 -0
  152. package/dist/proxy/proxy.module.d.ts +3 -0
  153. package/dist/proxy/proxy.module.d.ts.map +1 -0
  154. package/dist/proxy/proxy.module.js +16 -0
  155. package/dist/proxy/proxy.service.d.ts +40 -0
  156. package/dist/proxy/proxy.service.d.ts.map +1 -0
  157. package/dist/proxy/proxy.service.js +186 -0
  158. package/package.json +118 -0
  159. package/prisma/migrations/20260908000000_init/migration.sql +209 -0
  160. package/prisma/migrations/20260908161813_add_connect_domain/migration.sql +173 -0
  161. package/prisma/migrations/migration_lock.toml +3 -0
  162. package/prisma/schema.prisma +347 -0
@@ -0,0 +1,25 @@
1
+ var PrismaService_1;
2
+ import { __decorate, __metadata, __param } from "tslib";
3
+ import { Inject, Injectable, Logger, } from '@nestjs/common';
4
+ import { PrismaPg } from '@prisma/adapter-pg';
5
+ import { PrismaClient } from '../generated/prisma/client.js';
6
+ import { KOSHA_CONFIG } from '../config/tokens.js';
7
+ let PrismaService = PrismaService_1 = class PrismaService extends PrismaClient {
8
+ logger = new Logger(PrismaService_1.name);
9
+ constructor(config) {
10
+ super({ adapter: new PrismaPg({ connectionString: config.database.url }) });
11
+ }
12
+ async onModuleInit() {
13
+ await this.$connect();
14
+ this.logger.log('Connected to the database');
15
+ }
16
+ async onModuleDestroy() {
17
+ await this.$disconnect();
18
+ }
19
+ };
20
+ PrismaService = PrismaService_1 = __decorate([
21
+ Injectable(),
22
+ __param(0, Inject(KOSHA_CONFIG)),
23
+ __metadata("design:paramtypes", [Object])
24
+ ], PrismaService);
25
+ export { PrismaService };
@@ -0,0 +1,17 @@
1
+ import type { Response } from 'express';
2
+ import { type ApiKeyRequest } from '../auth/api-key.guard.js';
3
+ import { ProxyService } from './proxy.service.js';
4
+ export declare class ProxyController {
5
+ private readonly proxy;
6
+ constructor(proxy: ProxyService);
7
+ forward(request: ApiKeyRequest, response: Response, connectionId: string): Promise<void>;
8
+ }
9
+ /**
10
+ * Recovers the upstream path from the raw URL rather than the parsed route
11
+ * param, so the provider receives the caller's encoding untouched.
12
+ */
13
+ export declare function splitUpstreamTarget(originalUrl: string, connectionId: string): {
14
+ path: string;
15
+ query: string;
16
+ };
17
+ //# sourceMappingURL=proxy.controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy.controller.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAYlD,qBACa,eAAe;IACd,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,YAAY;IAK1C,OAAO,CACJ,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,QAAQ,EACF,YAAY,EAAE,MAAM;CA0B9C;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,GACnB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAQjC"}
@@ -0,0 +1,64 @@
1
+ import { __decorate, __metadata, __param } from "tslib";
2
+ import { All, Controller, Param, Req, Res, UseGuards } from '@nestjs/common';
3
+ import { AllowAnonymous } from '@thallesp/nestjs-better-auth';
4
+ import { ApiKeyGuard } from '../auth/api-key.guard.js';
5
+ import { ProxyService } from './proxy.service.js';
6
+ /**
7
+ * Framing headers we set ourselves on the way back out; the upstream's do not
8
+ * apply to our re-serialized response.
9
+ */
10
+ const SKIPPED_RESPONSE_HEADERS = new Set([
11
+ 'content-encoding',
12
+ 'transfer-encoding',
13
+ 'content-length',
14
+ ]);
15
+ let ProxyController = class ProxyController {
16
+ proxy;
17
+ constructor(proxy) {
18
+ this.proxy = proxy;
19
+ }
20
+ async forward(request, response, connectionId) {
21
+ const { path, query } = splitUpstreamTarget(request.originalUrl, connectionId);
22
+ const result = await this.proxy.forward(request.organizationId, connectionId, {
23
+ method: request.method,
24
+ path,
25
+ query,
26
+ headers: request.headers,
27
+ body: request.body,
28
+ });
29
+ response.status(result.status);
30
+ result.headers.forEach((value, key) => {
31
+ if (SKIPPED_RESPONSE_HEADERS.has(key.toLowerCase()))
32
+ return;
33
+ response.setHeader(key, value);
34
+ });
35
+ response.send(result.body);
36
+ }
37
+ };
38
+ __decorate([
39
+ All(':connectionId/*path'),
40
+ AllowAnonymous(),
41
+ UseGuards(ApiKeyGuard),
42
+ __param(0, Req()),
43
+ __param(1, Res()),
44
+ __param(2, Param('connectionId')),
45
+ __metadata("design:type", Function),
46
+ __metadata("design:paramtypes", [Object, Object, String]),
47
+ __metadata("design:returntype", Promise)
48
+ ], ProxyController.prototype, "forward", null);
49
+ ProxyController = __decorate([
50
+ Controller('proxy'),
51
+ __metadata("design:paramtypes", [ProxyService])
52
+ ], ProxyController);
53
+ export { ProxyController };
54
+ /**
55
+ * Recovers the upstream path from the raw URL rather than the parsed route
56
+ * param, so the provider receives the caller's encoding untouched.
57
+ */
58
+ export function splitUpstreamTarget(originalUrl, connectionId) {
59
+ const marker = `/${connectionId}/`;
60
+ const markerIndex = originalUrl.indexOf(marker);
61
+ const rest = markerIndex >= 0 ? originalUrl.slice(markerIndex + marker.length) : '';
62
+ const [path, query = ''] = rest.split('?');
63
+ return { path, query };
64
+ }
@@ -0,0 +1,3 @@
1
+ export declare class ProxyModule {
2
+ }
3
+ //# sourceMappingURL=proxy.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy.module.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.module.ts"],"names":[],"mappings":"AAMA,qBAKa,WAAW;CAAG"}
@@ -0,0 +1,16 @@
1
+ import { __decorate } from "tslib";
2
+ import { Module } from '@nestjs/common';
3
+ import { ConfigurationsModule } from '../configurations/configurations.module.js';
4
+ import { ConnectModule } from '../connect/connect.module.js';
5
+ import { ProxyController } from './proxy.controller.js';
6
+ import { ProxyService } from './proxy.service.js';
7
+ let ProxyModule = class ProxyModule {
8
+ };
9
+ ProxyModule = __decorate([
10
+ Module({
11
+ imports: [ConnectModule, ConfigurationsModule],
12
+ controllers: [ProxyController],
13
+ providers: [ProxyService],
14
+ })
15
+ ], ProxyModule);
16
+ export { ProxyModule };
@@ -0,0 +1,40 @@
1
+ import { ConnectService } from '../connect/connect.service.js';
2
+ import { ConfigurationsService } from '../configurations/configurations.service.js';
3
+ import { CryptoService } from '../crypto/crypto.service.js';
4
+ import { IntegrationRegistry } from '../integrations/integration.registry.js';
5
+ import { PrismaService } from '../prisma/prisma.service.js';
6
+ export interface ProxyRequest {
7
+ method: string;
8
+ path: string;
9
+ query: string;
10
+ headers: Record<string, string | string[] | undefined>;
11
+ body: unknown;
12
+ }
13
+ export interface ProxyResult {
14
+ status: number;
15
+ headers: Headers;
16
+ body: string;
17
+ }
18
+ export declare class ProxyService {
19
+ private readonly prisma;
20
+ private readonly crypto;
21
+ private readonly registry;
22
+ private readonly connect;
23
+ private readonly configurations;
24
+ private readonly logger;
25
+ constructor(prisma: PrismaService, crypto: CryptoService, registry: IntegrationRegistry, connect: ConnectService, configurations: ConfigurationsService);
26
+ forward(organizationId: string, connectionId: string, request: ProxyRequest): Promise<ProxyResult>;
27
+ /**
28
+ * Returns a usable access token, refreshing first when the stored one has
29
+ * expired and the provider supports refresh.
30
+ *
31
+ * Without this an expired token is a dead end for the end user: they have to
32
+ * walk the whole consent flow again for a token the provider was willing to
33
+ * renew.
34
+ */
35
+ private resolveCredential;
36
+ private runTokenRefreshedHook;
37
+ private markExpired;
38
+ private buildTargetUrl;
39
+ }
40
+ //# sourceMappingURL=proxy.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy.service.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.service.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,6CAA6C,CAAC;AACpF,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAkB5D,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IACvD,IAAI,EAAE,OAAO,CAAC;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,qBACa,YAAY;IAIrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,cAAc;IAPjC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiC;gBAGrC,MAAM,EAAE,aAAa,EACrB,MAAM,EAAE,aAAa,EACrB,QAAQ,EAAE,mBAAmB,EAC7B,OAAO,EAAE,cAAc,EACvB,cAAc,EAAE,qBAAqB;IAGlD,OAAO,CACX,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,YAAY,GACpB,OAAO,CAAC,WAAW,CAAC;IAwEvB;;;;;;;OAOG;YACW,iBAAiB;YA0EjB,qBAAqB;YAqBrB,WAAW;IAOzB,OAAO,CAAC,cAAc;CAevB"}
@@ -0,0 +1,186 @@
1
+ var ProxyService_1;
2
+ import { __decorate, __metadata } from "tslib";
3
+ import { BadGatewayException, ForbiddenException, Injectable, Logger, NotFoundException, UnauthorizedException, } from '@nestjs/common';
4
+ import { ConnectService } from '../connect/connect.service.js';
5
+ import { ConfigurationsService } from '../configurations/configurations.service.js';
6
+ import { CryptoService } from '../crypto/crypto.service.js';
7
+ import { IntegrationRegistry } from '../integrations/integration.registry.js';
8
+ import { PrismaService } from '../prisma/prisma.service.js';
9
+ /**
10
+ * Never forwarded upstream: hop-by-hop framing headers, and anything carrying
11
+ * Kosha's own credentials. `cookie` matters most — forwarding it would leak
12
+ * the caller's Kosha session to a third party.
13
+ */
14
+ const STRIPPED_REQUEST_HEADERS = new Set([
15
+ 'host',
16
+ 'connection',
17
+ 'content-length',
18
+ 'transfer-encoding',
19
+ 'accept-encoding',
20
+ 'authorization',
21
+ 'cookie',
22
+ 'x-api-key',
23
+ ]);
24
+ let ProxyService = ProxyService_1 = class ProxyService {
25
+ prisma;
26
+ crypto;
27
+ registry;
28
+ connect;
29
+ configurations;
30
+ logger = new Logger(ProxyService_1.name);
31
+ constructor(prisma, crypto, registry, connect, configurations) {
32
+ this.prisma = prisma;
33
+ this.crypto = crypto;
34
+ this.registry = registry;
35
+ this.connect = connect;
36
+ this.configurations = configurations;
37
+ }
38
+ async forward(organizationId, connectionId, request) {
39
+ const connection = await this.prisma.connection.findFirst({
40
+ where: { id: connectionId, organizationId },
41
+ include: {
42
+ configuration: { include: { provider: true } },
43
+ credential: true,
44
+ },
45
+ });
46
+ if (!connection) {
47
+ throw new NotFoundException('Connection not found');
48
+ }
49
+ if (connection.status !== 'ACTIVE' || !connection.credential) {
50
+ throw new ForbiddenException(`Connection is ${connection.status.toLowerCase()}`);
51
+ }
52
+ const integration = this.registry.get(connection.configuration.provider.key);
53
+ const credential = await this.resolveCredential(connection);
54
+ const targetUrl = this.buildTargetUrl(integration.api.baseUrl, request);
55
+ /*
56
+ * Header names are compared lowercased, and the integration's headers are
57
+ * applied last so they win. Without the normalisation a caller's `accept`
58
+ * and the integration's `Accept` are distinct keys, and fetch merges them
59
+ * into one comma-joined value — letting the caller append to any header
60
+ * the integration sets.
61
+ */
62
+ const headers = new Map();
63
+ for (const [key, value] of Object.entries(request.headers)) {
64
+ const name = key.toLowerCase();
65
+ if (!value || STRIPPED_REQUEST_HEADERS.has(name))
66
+ continue;
67
+ headers.set(name, Array.isArray(value) ? value.join(', ') : value);
68
+ }
69
+ const authHeaders = integration.api.authHeaders({
70
+ accessToken: credential.accessToken,
71
+ tokenType: credential.tokenType,
72
+ });
73
+ for (const [key, value] of Object.entries(authHeaders)) {
74
+ headers.set(key.toLowerCase(), value);
75
+ }
76
+ const method = request.method.toUpperCase();
77
+ const sendsBody = !['GET', 'HEAD'].includes(method);
78
+ const response = await fetch(targetUrl, {
79
+ method,
80
+ headers: Object.fromEntries(headers),
81
+ body: sendsBody && request.body !== undefined && request.body !== null
82
+ ? JSON.stringify(request.body)
83
+ : undefined,
84
+ });
85
+ await this.prisma.connection.update({
86
+ where: { id: connection.id },
87
+ data: { lastUsedAt: new Date() },
88
+ });
89
+ return {
90
+ status: response.status,
91
+ headers: response.headers,
92
+ body: await response.text(),
93
+ };
94
+ }
95
+ /**
96
+ * Returns a usable access token, refreshing first when the stored one has
97
+ * expired and the provider supports refresh.
98
+ *
99
+ * Without this an expired token is a dead end for the end user: they have to
100
+ * walk the whole consent flow again for a token the provider was willing to
101
+ * renew.
102
+ */
103
+ async resolveCredential(connection) {
104
+ const credential = connection.credential;
105
+ if (!credential) {
106
+ throw new ForbiddenException('Connection has no stored credential');
107
+ }
108
+ const expired = credential.expiresAt !== null && credential.expiresAt <= new Date();
109
+ if (!expired) {
110
+ return {
111
+ accessToken: this.crypto.decrypt(credential.accessToken),
112
+ tokenType: credential.tokenType,
113
+ };
114
+ }
115
+ const integration = this.registry.get(connection.configuration.provider.key);
116
+ const canRefresh = typeof integration.auth.refresh === 'function' && credential.refreshToken;
117
+ if (!canRefresh) {
118
+ await this.markExpired(connection.id, 'Access token expired');
119
+ throw new UnauthorizedException('Connection token expired; the end user must reconnect');
120
+ }
121
+ const configuration = await this.configurations.getWithDecryptedSecret(connection.configurationId);
122
+ try {
123
+ const tokens = await integration.auth.refresh?.({
124
+ client: {
125
+ clientId: configuration.clientId ?? '',
126
+ clientSecret: configuration.clientSecret,
127
+ redirectUri: configuration.redirectUri ??
128
+ this.configurations.callbackUrlFor(configuration.provider.key),
129
+ scopes: configuration.scopes,
130
+ },
131
+ refreshToken: this.crypto.decrypt(credential.refreshToken),
132
+ });
133
+ if (!tokens)
134
+ throw new Error('Refresh returned no tokens');
135
+ await this.connect.storeCredential(connection.id, tokens);
136
+ await this.runTokenRefreshedHook(connection.id, integration, tokens);
137
+ return {
138
+ accessToken: tokens.accessToken,
139
+ tokenType: tokens.tokenType ?? credential.tokenType,
140
+ };
141
+ }
142
+ catch (error) {
143
+ const message = error instanceof Error ? error.message : 'Refresh failed';
144
+ await this.markExpired(connection.id, `Token refresh failed: ${message}`);
145
+ throw new UnauthorizedException('Connection token expired and could not be refreshed; the end user must reconnect');
146
+ }
147
+ }
148
+ async runTokenRefreshedHook(connectionId, integration, tokens) {
149
+ const hook = integration.hooks?.onTokenRefreshed;
150
+ if (!hook)
151
+ return;
152
+ try {
153
+ await hook({ connectionId, tokens });
154
+ }
155
+ catch (error) {
156
+ this.logger.error(`onTokenRefreshed hook failed for "${integration.key}": ${error instanceof Error ? error.message : error}`);
157
+ }
158
+ }
159
+ async markExpired(connectionId, reason) {
160
+ await this.prisma.connection.update({
161
+ where: { id: connectionId },
162
+ data: { status: 'EXPIRED', errorMessage: reason },
163
+ });
164
+ }
165
+ buildTargetUrl(baseUrl, request) {
166
+ const base = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
167
+ const url = new URL(request.path.replace(/^\/+/, ''), base);
168
+ // A path that escapes the provider's base URL would turn the proxy into an
169
+ // open relay against Kosha's own network.
170
+ if (!url.href.startsWith(base)) {
171
+ throw new BadGatewayException('Resolved path escapes the provider base URL');
172
+ }
173
+ if (request.query)
174
+ url.search = request.query;
175
+ return url;
176
+ }
177
+ };
178
+ ProxyService = ProxyService_1 = __decorate([
179
+ Injectable(),
180
+ __metadata("design:paramtypes", [PrismaService,
181
+ CryptoService,
182
+ IntegrationRegistry,
183
+ ConnectService,
184
+ ConfigurationsService])
185
+ ], ProxyService);
186
+ export { ProxyService };
package/package.json ADDED
@@ -0,0 +1,118 @@
1
+ {
2
+ "name": "@kosha-ai/server",
3
+ "version": "0.0.1",
4
+ "description": "Kosha server: OAuth handshake, encrypted credential storage, token refresh, and an authenticated request proxy for third-party integrations",
5
+ "keywords": [
6
+ "kosha",
7
+ "oauth",
8
+ "integrations",
9
+ "nestjs"
10
+ ],
11
+ "license": "MIT",
12
+ "homepage": "https://github.com/codemancers/kosha#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/codemancers/kosha/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/codemancers/kosha.git",
19
+ "directory": "packages/server"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "type": "module",
25
+ "main": "./dist/index.js",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ "./package.json": "./package.json",
30
+ ".": {
31
+ "@org/source": "./src/index.ts",
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "default": "./dist/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "prisma",
40
+ "!**/*.tsbuildinfo"
41
+ ],
42
+ "kosha": {
43
+ "kind": "server"
44
+ },
45
+ "nx": {
46
+ "targets": {
47
+ "build": {
48
+ "dependsOn": [
49
+ "prisma-generate"
50
+ ]
51
+ },
52
+ "typecheck": {
53
+ "dependsOn": [
54
+ "prisma-generate"
55
+ ]
56
+ },
57
+ "prisma-deploy": {
58
+ "executor": "@nx-tools/nx-prisma:deploy"
59
+ },
60
+ "prisma-format": {
61
+ "executor": "@nx-tools/nx-prisma:format"
62
+ },
63
+ "prisma-generate": {
64
+ "executor": "@nx-tools/nx-prisma:generate"
65
+ },
66
+ "prisma-migrate": {
67
+ "executor": "@nx-tools/nx-prisma:migrate"
68
+ },
69
+ "prisma-pull": {
70
+ "executor": "@nx-tools/nx-prisma:pull"
71
+ },
72
+ "prisma-push": {
73
+ "executor": "@nx-tools/nx-prisma:push"
74
+ },
75
+ "prisma-reset": {
76
+ "executor": "@nx-tools/nx-prisma:reset"
77
+ },
78
+ "prisma-resolve": {
79
+ "executor": "@nx-tools/nx-prisma:resolve"
80
+ },
81
+ "prisma-status": {
82
+ "executor": "@nx-tools/nx-prisma:status"
83
+ },
84
+ "prisma-studio": {
85
+ "executor": "@nx-tools/nx-prisma:studio"
86
+ },
87
+ "prisma-validate": {
88
+ "executor": "@nx-tools/nx-prisma:validate"
89
+ }
90
+ }
91
+ },
92
+ "dependencies": {
93
+ "@better-auth/api-key": "^1.7.3",
94
+ "@better-auth/utils": "0.4.2",
95
+ "@nestjs/common": "^11.0.0",
96
+ "@nestjs/core": "^11.0.0",
97
+ "@nestjs/platform-express": "^11.0.0",
98
+ "@prisma/adapter-pg": "^7.10.0",
99
+ "@prisma/client": "^7.10.0",
100
+ "@thallesp/nestjs-better-auth": "^2.8.0",
101
+ "better-auth": "^1.7.3",
102
+ "express": "^5.2.1",
103
+ "pg": "^8.23.0",
104
+ "reflect-metadata": "^0.2.0",
105
+ "rxjs": "^7.8.0",
106
+ "tslib": "^2.3.0",
107
+ "zod": "4.5.4",
108
+ "@kosha-ai/integration-sdk": "0.0.1"
109
+ },
110
+ "devDependencies": {
111
+ "@nestjs/testing": "^11.0.0",
112
+ "@types/express": "^5.0.6",
113
+ "@types/pg": "^8.23.1",
114
+ "prisma": "^7.10.0",
115
+ "@kosha-ai/integration-github": "0.0.1",
116
+ "@kosha-ai/integration-slack": "0.0.1"
117
+ }
118
+ }