@kosha-ai/server 0.0.6 → 0.2.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.
Files changed (210) hide show
  1. package/dist/auth/api-key.guard.d.ts +7 -2
  2. package/dist/auth/api-key.guard.d.ts.map +1 -1
  3. package/dist/auth/api-key.guard.js +28 -8
  4. package/dist/auth/auth.factory.d.ts +15 -1
  5. package/dist/auth/auth.factory.d.ts.map +1 -1
  6. package/dist/auth/auth.factory.js +48 -2
  7. package/dist/bootstrap.d.ts.map +1 -1
  8. package/dist/bootstrap.js +24 -6
  9. package/dist/config/kosha-config.d.ts +21 -0
  10. package/dist/config/kosha-config.d.ts.map +1 -1
  11. package/dist/config/kosha-config.js +31 -2
  12. package/dist/configurations/configurations.controller.d.ts +11 -136
  13. package/dist/configurations/configurations.controller.d.ts.map +1 -1
  14. package/dist/configurations/configurations.controller.js +58 -25
  15. package/dist/configurations/configurations.module.d.ts.map +1 -1
  16. package/dist/configurations/configurations.module.js +4 -1
  17. package/dist/configurations/configurations.repository.d.ts +43 -0
  18. package/dist/configurations/configurations.repository.d.ts.map +1 -0
  19. package/dist/configurations/configurations.repository.js +76 -0
  20. package/dist/configurations/configurations.service.d.ts +38 -194
  21. package/dist/configurations/configurations.service.d.ts.map +1 -1
  22. package/dist/configurations/configurations.service.js +118 -110
  23. package/dist/configurations/dto/create-configuration.dto.d.ts +8 -0
  24. package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -0
  25. package/dist/configurations/dto/create-configuration.dto.js +54 -0
  26. package/dist/configurations/dto/update-configuration.dto.d.ts +7 -0
  27. package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -0
  28. package/dist/configurations/dto/update-configuration.dto.js +39 -0
  29. package/dist/connect/connect.controller.d.ts +6 -8
  30. package/dist/connect/connect.controller.d.ts.map +1 -1
  31. package/dist/connect/connect.controller.js +45 -15
  32. package/dist/connect/connect.module.d.ts.map +1 -1
  33. package/dist/connect/connect.module.js +4 -2
  34. package/dist/connect/connect.repository.d.ts +78 -0
  35. package/dist/connect/connect.repository.d.ts.map +1 -0
  36. package/dist/connect/connect.repository.js +146 -0
  37. package/dist/connect/connect.service.d.ts +28 -19
  38. package/dist/connect/connect.service.d.ts.map +1 -1
  39. package/dist/connect/connect.service.js +149 -163
  40. package/dist/connect/dto/create-connect-session.dto.d.ts +8 -0
  41. package/dist/connect/dto/create-connect-session.dto.d.ts.map +1 -0
  42. package/dist/connect/dto/create-connect-session.dto.js +55 -0
  43. package/dist/connect/dto/create-test-session.dto.d.ts +10 -0
  44. package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -0
  45. package/dist/connect/dto/create-test-session.dto.js +34 -0
  46. package/dist/connections/connections.controller.d.ts +8 -61
  47. package/dist/connections/connections.controller.d.ts.map +1 -1
  48. package/dist/connections/connections.controller.js +31 -9
  49. package/dist/connections/connections.module.d.ts.map +1 -1
  50. package/dist/connections/connections.module.js +4 -1
  51. package/dist/connections/connections.repository.d.ts +24 -0
  52. package/dist/connections/connections.repository.d.ts.map +1 -0
  53. package/dist/connections/connections.repository.js +66 -0
  54. package/dist/connections/connections.service.d.ts +24 -69
  55. package/dist/connections/connections.service.d.ts.map +1 -1
  56. package/dist/connections/connections.service.js +59 -56
  57. package/dist/connections/dto/list-connections.dto.d.ts +5 -0
  58. package/dist/connections/dto/list-connections.dto.d.ts.map +1 -0
  59. package/dist/connections/dto/list-connections.dto.js +25 -0
  60. package/dist/connections/environment-connections.controller.d.ts +26 -0
  61. package/dist/connections/environment-connections.controller.d.ts.map +1 -0
  62. package/dist/connections/environment-connections.controller.js +81 -0
  63. package/dist/connections/environment-connections.module.d.ts +11 -0
  64. package/dist/connections/environment-connections.module.d.ts.map +1 -0
  65. package/dist/connections/environment-connections.module.js +21 -0
  66. package/dist/credentials/credentials.module.d.ts +3 -0
  67. package/dist/credentials/credentials.module.d.ts.map +1 -0
  68. package/dist/credentials/credentials.module.js +15 -0
  69. package/dist/credentials/credentials.repository.d.ts +8 -0
  70. package/dist/credentials/credentials.repository.d.ts.map +1 -0
  71. package/dist/credentials/credentials.repository.js +21 -0
  72. package/dist/credentials/credentials.service.d.ts +45 -0
  73. package/dist/credentials/credentials.service.d.ts.map +1 -0
  74. package/dist/credentials/credentials.service.js +135 -0
  75. package/dist/crypto/credential-envelope.d.ts +56 -0
  76. package/dist/crypto/credential-envelope.d.ts.map +1 -0
  77. package/dist/crypto/credential-envelope.js +70 -0
  78. package/dist/crypto/crypto.service.d.ts +8 -0
  79. package/dist/crypto/crypto.service.d.ts.map +1 -1
  80. package/dist/crypto/crypto.service.js +12 -0
  81. package/dist/egress/ca.service.d.ts +36 -0
  82. package/dist/egress/ca.service.d.ts.map +1 -0
  83. package/dist/egress/ca.service.js +117 -0
  84. package/dist/egress/dto/mint-grant.dto.d.ts +7 -0
  85. package/dist/egress/dto/mint-grant.dto.d.ts.map +1 -0
  86. package/dist/egress/dto/mint-grant.dto.js +44 -0
  87. package/dist/egress/egress.controller.d.ts +18 -0
  88. package/dist/egress/egress.controller.d.ts.map +1 -0
  89. package/dist/egress/egress.controller.js +80 -0
  90. package/dist/egress/egress.listener.d.ts +39 -0
  91. package/dist/egress/egress.listener.d.ts.map +1 -0
  92. package/dist/egress/egress.listener.js +328 -0
  93. package/dist/egress/egress.module.d.ts +7 -0
  94. package/dist/egress/egress.module.d.ts.map +1 -0
  95. package/dist/egress/egress.module.js +31 -0
  96. package/dist/egress/egress.repository.d.ts +58 -0
  97. package/dist/egress/egress.repository.d.ts.map +1 -0
  98. package/dist/egress/egress.repository.js +116 -0
  99. package/dist/egress/grants.service.d.ts +77 -0
  100. package/dist/egress/grants.service.d.ts.map +1 -0
  101. package/dist/egress/grants.service.js +159 -0
  102. package/dist/egress/host-rules.service.d.ts +35 -0
  103. package/dist/egress/host-rules.service.d.ts.map +1 -0
  104. package/dist/egress/host-rules.service.js +48 -0
  105. package/dist/environments/dto/create-environment.dto.d.ts +6 -0
  106. package/dist/environments/dto/create-environment.dto.d.ts.map +1 -0
  107. package/dist/environments/dto/create-environment.dto.js +34 -0
  108. package/dist/environments/dto/update-environment.dto.d.ts +5 -0
  109. package/dist/environments/dto/update-environment.dto.d.ts.map +1 -0
  110. package/dist/environments/dto/update-environment.dto.js +24 -0
  111. package/dist/environments/environments.controller.d.ts +53 -0
  112. package/dist/environments/environments.controller.d.ts.map +1 -0
  113. package/dist/environments/environments.controller.js +101 -0
  114. package/dist/environments/environments.module.d.ts +3 -0
  115. package/dist/environments/environments.module.d.ts.map +1 -0
  116. package/dist/environments/environments.module.js +15 -0
  117. package/dist/environments/environments.repository.d.ts +37 -0
  118. package/dist/environments/environments.repository.d.ts.map +1 -0
  119. package/dist/environments/environments.repository.js +82 -0
  120. package/dist/environments/environments.service.d.ts +43 -0
  121. package/dist/environments/environments.service.d.ts.map +1 -0
  122. package/dist/environments/environments.service.js +124 -0
  123. package/dist/generated/prisma/browser.d.ts +17 -35
  124. package/dist/generated/prisma/browser.d.ts.map +1 -1
  125. package/dist/generated/prisma/client.d.ts +17 -35
  126. package/dist/generated/prisma/client.d.ts.map +1 -1
  127. package/dist/generated/prisma/commonInputTypes.d.ts +104 -145
  128. package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -1
  129. package/dist/generated/prisma/enums.d.ts +1 -21
  130. package/dist/generated/prisma/enums.d.ts.map +1 -1
  131. package/dist/generated/prisma/enums.js +1 -18
  132. package/dist/generated/prisma/internal/class.d.ts +24 -46
  133. package/dist/generated/prisma/internal/class.d.ts.map +1 -1
  134. package/dist/generated/prisma/internal/class.js +4 -4
  135. package/dist/generated/prisma/internal/prismaNamespace.d.ts +258 -472
  136. package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
  137. package/dist/generated/prisma/internal/prismaNamespace.js +45 -83
  138. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +45 -85
  139. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
  140. package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +45 -83
  141. package/dist/generated/prisma/models/Account.d.ts +344 -26
  142. package/dist/generated/prisma/models/Account.d.ts.map +1 -1
  143. package/dist/generated/prisma/models/Configuration.d.ts +218 -851
  144. package/dist/generated/prisma/models/Configuration.d.ts.map +1 -1
  145. package/dist/generated/prisma/models/EgressGrant.d.ts +1535 -0
  146. package/dist/generated/prisma/models/EgressGrant.d.ts.map +1 -0
  147. package/dist/generated/prisma/models/Environment.d.ts +1644 -0
  148. package/dist/generated/prisma/models/Environment.d.ts.map +1 -0
  149. package/dist/generated/prisma/models/Invitation.d.ts +42 -1
  150. package/dist/generated/prisma/models/Invitation.d.ts.map +1 -1
  151. package/dist/generated/prisma/models/Organization.d.ts +183 -322
  152. package/dist/generated/prisma/models/Organization.d.ts.map +1 -1
  153. package/dist/generated/prisma/models/Session.d.ts +36 -1
  154. package/dist/generated/prisma/models/Session.d.ts.map +1 -1
  155. package/dist/generated/prisma/models/Team.d.ts +1498 -0
  156. package/dist/generated/prisma/models/Team.d.ts.map +1 -0
  157. package/dist/generated/prisma/models/TeamMember.d.ts +1281 -0
  158. package/dist/generated/prisma/models/TeamMember.d.ts.map +1 -0
  159. package/dist/generated/prisma/models/User.d.ts +338 -2
  160. package/dist/generated/prisma/models/User.d.ts.map +1 -1
  161. package/dist/generated/prisma/models.d.ts +4 -6
  162. package/dist/generated/prisma/models.d.ts.map +1 -1
  163. package/dist/index.d.ts +20 -5
  164. package/dist/index.d.ts.map +1 -1
  165. package/dist/index.js +17 -3
  166. package/dist/integrations/integrations.controller.d.ts +2 -1
  167. package/dist/integrations/integrations.controller.d.ts.map +1 -1
  168. package/dist/integrations/integrations.module.d.ts.map +1 -1
  169. package/dist/integrations/integrations.module.js +0 -2
  170. package/dist/kosha.module.d.ts.map +1 -1
  171. package/dist/kosha.module.js +13 -3
  172. package/dist/proxy/proxy.controller.d.ts +8 -3
  173. package/dist/proxy/proxy.controller.d.ts.map +1 -1
  174. package/dist/proxy/proxy.controller.js +26 -10
  175. package/dist/proxy/proxy.module.d.ts.map +1 -1
  176. package/dist/proxy/proxy.module.js +5 -3
  177. package/dist/proxy/proxy.repository.d.ts +24 -0
  178. package/dist/proxy/proxy.repository.d.ts.map +1 -0
  179. package/dist/proxy/proxy.repository.js +47 -0
  180. package/dist/proxy/proxy.service.d.ts +17 -21
  181. package/dist/proxy/proxy.service.d.ts.map +1 -1
  182. package/dist/proxy/proxy.service.js +61 -110
  183. package/package.json +9 -4
  184. package/prisma/migrations/20260929101936_init/migration.sql +345 -0
  185. package/prisma/migrations/20260930102529_connection_config/migration.sql +2 -0
  186. package/prisma/schema.prisma +103 -178
  187. package/dist/generated/prisma/models/ConnectSession.d.ts +0 -1606
  188. package/dist/generated/prisma/models/ConnectSession.d.ts.map +0 -1
  189. package/dist/generated/prisma/models/Connection.d.ts +0 -1949
  190. package/dist/generated/prisma/models/Connection.d.ts.map +0 -1
  191. package/dist/generated/prisma/models/ConnectionCredential.d.ts +0 -1293
  192. package/dist/generated/prisma/models/ConnectionCredential.d.ts.map +0 -1
  193. package/dist/generated/prisma/models/EndUser.d.ts +0 -1539
  194. package/dist/generated/prisma/models/EndUser.d.ts.map +0 -1
  195. package/dist/generated/prisma/models/OAuthState.d.ts +0 -1404
  196. package/dist/generated/prisma/models/OAuthState.d.ts.map +0 -1
  197. package/dist/generated/prisma/models/OAuthState.js +0 -1
  198. package/dist/generated/prisma/models/Provider.d.ts +0 -1462
  199. package/dist/generated/prisma/models/Provider.d.ts.map +0 -1
  200. package/dist/generated/prisma/models/Provider.js +0 -1
  201. package/dist/integrations/provider-sync.service.d.ts +0 -24
  202. package/dist/integrations/provider-sync.service.d.ts.map +0 -1
  203. package/dist/integrations/provider-sync.service.js +0 -74
  204. package/prisma/migrations/20260908000000_init/migration.sql +0 -209
  205. package/prisma/migrations/20260908161813_add_connect_domain/migration.sql +0 -173
  206. package/prisma/migrations/20260916000000_add_configuration_slug/migration.sql +0 -15
  207. /package/dist/generated/prisma/models/{ConnectSession.js → EgressGrant.js} +0 -0
  208. /package/dist/generated/prisma/models/{Connection.js → Environment.js} +0 -0
  209. /package/dist/generated/prisma/models/{ConnectionCredential.js → Team.js} +0 -0
  210. /package/dist/generated/prisma/models/{EndUser.js → TeamMember.js} +0 -0
@@ -1,14 +1,15 @@
1
1
  var ConnectService_1;
2
2
  import { __decorate, __metadata, __param } from "tslib";
3
- import { BadRequestException, Inject, Injectable, Logger, NotFoundException, } from '@nestjs/common';
3
+ import { BadRequestException, ConflictException, Inject, Injectable, Logger, NotFoundException, } from '@nestjs/common';
4
4
  import { randomBytes } from 'node:crypto';
5
- import { generateCodeVerifier } from '@kosha-ai/integration-sdk';
6
- import { httpFor } from '@kosha-ai/integration-sdk';
5
+ import { generateCodeVerifier, httpFor } from '@kosha-ai/integration-sdk';
7
6
  import { KOSHA_CONFIG } from '../config/tokens.js';
8
7
  import { ConfigurationsService } from '../configurations/configurations.service.js';
8
+ import { ENVELOPE_VERSION, expiryOf, } from '../crypto/credential-envelope.js';
9
9
  import { CryptoService } from '../crypto/crypto.service.js';
10
+ import { EnvironmentsService } from '../environments/environments.service.js';
10
11
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
11
- import { PrismaService } from '../prisma/prisma.service.js';
12
+ import { ConnectRepository } from './connect.repository.js';
12
13
  const SESSION_TTL_MS = 10 * 60 * 1000;
13
14
  const STATE_TTL_MS = 10 * 60 * 1000;
14
15
  function randomToken() {
@@ -16,221 +17,205 @@ function randomToken() {
16
17
  }
17
18
  /**
18
19
  * Drives the OAuth handshake that turns an end user's consent into a stored,
19
- * encrypted connection.
20
+ * encrypted credential.
20
21
  *
21
22
  * Providers are resolved through {@link IntegrationRegistry}, so nothing here
22
23
  * knows what GitHub or Slack are.
23
24
  */
24
25
  let ConnectService = ConnectService_1 = class ConnectService {
25
- prisma;
26
+ connect;
26
27
  crypto;
27
28
  configurations;
29
+ environments;
28
30
  registry;
29
31
  config;
30
32
  logger = new Logger(ConnectService_1.name);
31
- constructor(prisma, crypto, configurations, registry, config) {
32
- this.prisma = prisma;
33
+ constructor(connect, crypto, configurations, environments, registry, config) {
34
+ this.connect = connect;
33
35
  this.crypto = crypto;
34
36
  this.configurations = configurations;
37
+ this.environments = environments;
35
38
  this.registry = registry;
36
39
  this.config = config;
37
40
  }
38
41
  /**
39
- * Called by the organization's own backend (API-key authenticated) to start
40
- * a connect flow for one of its users.
42
+ * Called by the consuming app's backend to start a connect flow for one of
43
+ * its users. The environment comes from the API key, never from the body.
41
44
  */
42
- async createSession(organizationId, input) {
43
- if (!input?.endUserExternalId?.trim()) {
44
- throw new BadRequestException('endUserExternalId is required');
45
+ async createSession(organizationId, environmentId, input) {
46
+ const externalUserId = input.externalUserId?.trim();
47
+ if (!externalUserId) {
48
+ throw new BadRequestException('externalUserId is required');
45
49
  }
46
- const configurationId = input.configurationId?.trim();
47
- const configurationSlug = input.configurationSlug?.trim();
48
- if (!configurationId && !configurationSlug) {
49
- throw new BadRequestException('configurationId or configurationSlug is required');
50
- }
51
- const configuration = await this.prisma.configuration.findFirst({
52
- where: {
53
- ...(configurationId
54
- ? { id: configurationId }
55
- : { slug: configurationSlug }),
56
- organizationId,
57
- isEnabled: true,
58
- },
59
- });
60
- if (!configuration) {
61
- throw new BadRequestException('Unknown or disabled configuration');
50
+ const environment = await this.environments.get(organizationId, environmentId);
51
+ const configuration = await this.resolveConfiguration(environmentId, input);
52
+ if (!configuration.isEnabled) {
53
+ throw new BadRequestException('Configuration is disabled');
62
54
  }
63
- const endUser = await this.prisma.endUser.upsert({
64
- where: {
65
- organizationId_externalId: {
66
- organizationId,
67
- externalId: input.endUserExternalId,
68
- },
69
- },
70
- create: { organizationId, externalId: input.endUserExternalId },
71
- update: {},
72
- });
55
+ // Nothing else sweeps these: `verification` is shared with email
56
+ // verification and password reset, so only this flow knows which rows are
57
+ // its own. Swept here rather than on a schedule, so no timer has to exist.
58
+ void this.connect
59
+ .deleteExpired()
60
+ .catch((error) => this.logger.warn(`Sweeping expired connect state failed: ${String(error)}`));
61
+ const token = randomToken();
73
62
  const expiresAt = new Date(Date.now() + SESSION_TTL_MS);
74
- const session = await this.prisma.connectSession.create({
75
- data: {
76
- organizationId,
77
- endUserId: endUser.id,
78
- token: randomToken(),
79
- allowedConfigurationIds: [configuration.id],
80
- redirectUrl: input.redirectUrl,
81
- expiresAt,
82
- },
83
- });
63
+ await this.connect.putSession(token, {
64
+ organizationId,
65
+ environmentId: environment.id,
66
+ environmentSlug: environment.slug,
67
+ configurationId: configuration.id,
68
+ externalUserId,
69
+ organizationExternalId: input.organizationExternalId?.trim() || null,
70
+ redirectUrl: input.redirectUrl ?? null,
71
+ }, expiresAt);
84
72
  const { publicUrl, globalPrefix } = this.config.server;
85
73
  return {
86
- token: session.token,
87
- connectUrl: `${publicUrl}/${globalPrefix}/connect/${session.token}/start`,
74
+ token,
75
+ connectUrl: `${publicUrl}/${globalPrefix}/connect/${token}/start`,
88
76
  expiresAt,
89
77
  };
90
78
  }
91
79
  /**
92
- * Exchanges a connect-session token for the provider's authorize URL,
93
- * recording CSRF state and — where the provider supports it — a PKCE
94
- * verifier.
80
+ * Exchanges a connect token for the provider's authorize URL, carrying the
81
+ * flow's state — and, where the provider supports it, a PKCE verifier —
82
+ * across the redirect.
95
83
  */
96
84
  async buildAuthorizationRedirect(token) {
97
- const session = await this.prisma.connectSession.findUnique({
98
- where: { token },
99
- });
100
- if (!session ||
101
- session.status !== 'pending' ||
102
- session.expiresAt < new Date()) {
85
+ const session = await this.connect.takeSession(token);
86
+ if (!session) {
103
87
  throw new NotFoundException('Connect session not found or expired');
104
88
  }
105
- const configurationId = session.allowedConfigurationIds[0];
106
- const configuration = await this.configurations.getWithDecryptedSecret(configurationId);
107
- if (configuration.organizationId !== session.organizationId ||
108
- !configuration.isEnabled) {
89
+ const { configuration, credentials } = await this.configurations.getWithCredentials(session.configurationId);
90
+ if (!configuration.isEnabled) {
109
91
  throw new BadRequestException('Configuration is no longer available');
110
92
  }
111
- const integration = this.registry.get(configuration.provider.key);
93
+ const integration = this.registry.get(configuration.integrationKey);
112
94
  const codeVerifier = integration.auth.pkce
113
95
  ? generateCodeVerifier()
114
96
  : undefined;
115
- const state = await this.prisma.oAuthState.create({
116
- data: {
117
- state: randomToken(),
118
- connectSessionId: session.id,
119
- configurationId: configuration.id,
120
- codeVerifier,
121
- expiresAt: new Date(Date.now() + STATE_TTL_MS),
122
- },
123
- });
97
+ const state = randomToken();
98
+ await this.connect.putState(state, { ...session, codeVerifier }, new Date(Date.now() + STATE_TTL_MS));
124
99
  return integration.auth.buildAuthorizationUrl({
125
- client: {
126
- clientId: configuration.clientId ?? '',
127
- clientSecret: configuration.clientSecret,
128
- redirectUri: configuration.redirectUri ??
129
- this.configurations.callbackUrlFor(configuration.provider.key),
130
- scopes: configuration.scopes,
131
- },
132
- state: state.state,
100
+ client: this.clientContextFor(configuration, credentials),
101
+ state,
133
102
  codeVerifier,
134
103
  });
135
104
  }
136
105
  /** Handles the provider's redirect back to Kosha. */
137
- async handleCallback(providerKey, code, state) {
138
- const oauthState = await this.prisma.oAuthState.findUnique({
139
- where: { state },
140
- include: { connectSession: true },
141
- });
142
- if (!oauthState ||
143
- oauthState.status !== 'pending' ||
144
- oauthState.expiresAt < new Date()) {
106
+ async handleCallback(integrationKey, code, state) {
107
+ const flow = await this.connect.takeState(state);
108
+ if (!flow) {
145
109
  throw new NotFoundException('OAuth state not found or expired');
146
110
  }
147
- // Burn the state before doing any network work: a replayed callback must
148
- // not be able to mint a second connection.
149
- await this.prisma.oAuthState.update({
150
- where: { id: oauthState.id },
151
- data: { status: 'completed' },
152
- });
153
- const configuration = await this.configurations.getWithDecryptedSecret(oauthState.configurationId);
154
- if (configuration.provider.key !== providerKey) {
111
+ const { configuration, credentials } = await this.configurations.getWithCredentials(flow.configurationId);
112
+ if (configuration.integrationKey !== integrationKey) {
155
113
  throw new BadRequestException('Provider mismatch');
156
114
  }
157
- const integration = this.registry.get(providerKey);
115
+ const integration = this.registry.get(integrationKey);
158
116
  const tokens = await integration.auth.exchangeCode({
159
- client: {
160
- clientId: configuration.clientId ?? '',
161
- clientSecret: configuration.clientSecret,
162
- redirectUri: configuration.redirectUri ??
163
- this.configurations.callbackUrlFor(providerKey),
164
- scopes: configuration.scopes,
165
- },
117
+ client: this.clientContextFor(configuration, credentials),
166
118
  code,
167
- codeVerifier: oauthState.codeVerifier ?? undefined,
119
+ codeVerifier: flow.codeVerifier,
168
120
  });
169
121
  const identity = await integration.identity.fetchAccount({
170
122
  accessToken: tokens.accessToken,
171
123
  http: httpFor(integration),
172
124
  });
173
- const endUserId = oauthState.connectSession.endUserId;
174
- if (!endUserId) {
175
- throw new BadRequestException('Connect session has no end user');
176
- }
177
- const connection = await this.prisma.connection.upsert({
178
- where: {
179
- configurationId_externalAccountId: {
180
- configurationId: configuration.id,
181
- externalAccountId: identity.externalAccountId,
182
- },
183
- },
184
- create: {
185
- organizationId: configuration.organizationId,
186
- endUserId,
187
- configurationId: configuration.id,
188
- externalAccountId: identity.externalAccountId,
189
- label: identity.label,
190
- status: 'ACTIVE',
191
- scopes: configuration.scopes,
192
- lastUsedAt: new Date(),
193
- },
194
- update: {
195
- endUserId,
196
- status: 'ACTIVE',
197
- label: identity.label,
198
- errorMessage: null,
199
- lastUsedAt: new Date(),
200
- },
201
- });
202
- await this.storeCredential(connection.id, tokens);
203
- await this.prisma.connectSession.update({
204
- where: { id: oauthState.connectSessionId },
205
- data: { status: 'consumed' },
125
+ const user = await this.connect.upsertEndUser(flow.environmentSlug, flow.externalUserId);
126
+ const account = await this.writeCredential(flow, {
127
+ userId: user.id,
128
+ providerId: configuration.id,
129
+ accountId: identity.externalAccountId,
130
+ tokens,
131
+ // What the provider told us about this account that a later proxied
132
+ // call needs — the Jira site, for one. Without storing it here, a
133
+ // provider with no fixed host has no resolvable base URL at all.
134
+ connectionConfig: identity.metadata,
206
135
  });
207
136
  await this.runHook(integration, () => integration.hooks?.onConnectionCreated?.({
208
- connectionId: connection.id,
209
- organizationId: configuration.organizationId,
137
+ connectionId: account.id,
138
+ organizationId: flow.organizationId,
210
139
  }));
140
+ return { connectionId: account.id, redirectUrl: flow.redirectUrl ?? null };
141
+ }
142
+ /**
143
+ * Writes the credential, refusing when one is already there.
144
+ *
145
+ * Replacing silently would let anyone at a tenant overwrite the workspace
146
+ * credential their colleague connected, with no trace. Reconnecting means
147
+ * revoking first, which is a deliberate act by someone who can see what they
148
+ * are replacing.
149
+ */
150
+ async writeCredential(flow, input) {
151
+ const envelope = this.envelopeFor(input.tokens);
152
+ const accessToken = this.crypto.sealEnvelope(envelope);
153
+ const accessTokenExpiresAt = expiryOf(envelope);
154
+ const existing = await this.connect.findCredential(flow.environmentId, input.providerId, {
155
+ userId: input.userId,
156
+ organizationExternalId: flow.organizationExternalId ?? null,
157
+ });
158
+ if (existing) {
159
+ throw new ConflictException(flow.organizationExternalId
160
+ ? `${flow.organizationExternalId} is already connected to this configuration. Revoke that connection first.`
161
+ : 'This person is already connected to this configuration. Revoke that connection first.');
162
+ }
163
+ return this.connect.storeCredential({
164
+ userId: input.userId,
165
+ environmentId: flow.environmentId,
166
+ organizationExternalId: flow.organizationExternalId ?? null,
167
+ providerId: input.providerId,
168
+ accountId: input.accountId,
169
+ accessToken,
170
+ accessTokenExpiresAt,
171
+ connectionConfig: input.connectionConfig,
172
+ });
173
+ }
174
+ /** Persists a refreshed token set. Shared with the refresh path. */
175
+ async replaceCredential(accountId, tokens) {
176
+ const envelope = this.envelopeFor(tokens);
177
+ await this.connect.updateCredential(accountId, {
178
+ accessToken: this.crypto.sealEnvelope(envelope),
179
+ accessTokenExpiresAt: expiryOf(envelope),
180
+ });
181
+ }
182
+ envelopeFor(tokens) {
211
183
  return {
212
- connectionId: connection.id,
213
- redirectUrl: oauthState.connectSession.redirectUrl,
184
+ v: ENVELOPE_VERSION,
185
+ type: 'oauth2',
186
+ accessToken: tokens.accessToken,
187
+ ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),
188
+ ...(tokens.tokenType ? { tokenType: tokens.tokenType } : {}),
189
+ ...(tokens.expiresInSeconds
190
+ ? {
191
+ expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000).toISOString(),
192
+ }
193
+ : {}),
214
194
  };
215
195
  }
216
- /** Persists a token set, encrypted. Shared by the callback and by refresh. */
217
- async storeCredential(connectionId, tokens) {
218
- const expiresAt = tokens.expiresInSeconds
219
- ? new Date(Date.now() + tokens.expiresInSeconds * 1000)
220
- : null;
221
- const refreshToken = tokens.refreshToken
222
- ? this.crypto.encrypt(tokens.refreshToken)
223
- : null;
224
- const data = {
225
- accessToken: this.crypto.encrypt(tokens.accessToken),
226
- tokenType: tokens.tokenType,
227
- expiresAt,
196
+ clientContextFor(configuration, credentials) {
197
+ const settings = (configuration.settings ?? {});
198
+ return {
199
+ clientId: String(credentials['clientId'] ?? ''),
200
+ clientSecret: String(credentials['clientSecret'] ?? ''),
201
+ redirectUri: settings.redirectUri ??
202
+ this.configurations.callbackUrlFor(configuration.integrationKey),
203
+ scopes: settings.scopes ?? [],
228
204
  };
229
- await this.prisma.connectionCredential.upsert({
230
- where: { connectionId },
231
- create: { connectionId, ...data, refreshToken },
232
- update: refreshToken ? { ...data, refreshToken } : data,
233
- });
205
+ }
206
+ async resolveConfiguration(environmentId, input) {
207
+ const slug = input.configurationSlug?.trim();
208
+ const id = input.configurationId?.trim();
209
+ if (!slug && !id) {
210
+ throw new BadRequestException('configurationId or configurationSlug is required');
211
+ }
212
+ if (slug)
213
+ return this.configurations.getBySlug(environmentId, slug);
214
+ const { configuration } = await this.configurations.getWithCredentials(id);
215
+ if (configuration.environmentId !== environmentId) {
216
+ throw new BadRequestException('Unknown configuration');
217
+ }
218
+ return configuration;
234
219
  }
235
220
  /** An integration's hook must never take the request down with it. */
236
221
  async runHook(integration, hook) {
@@ -244,10 +229,11 @@ let ConnectService = ConnectService_1 = class ConnectService {
244
229
  };
245
230
  ConnectService = ConnectService_1 = __decorate([
246
231
  Injectable(),
247
- __param(4, Inject(KOSHA_CONFIG)),
248
- __metadata("design:paramtypes", [PrismaService,
232
+ __param(5, Inject(KOSHA_CONFIG)),
233
+ __metadata("design:paramtypes", [ConnectRepository,
249
234
  CryptoService,
250
235
  ConfigurationsService,
236
+ EnvironmentsService,
251
237
  IntegrationRegistry, Object])
252
238
  ], ConnectService);
253
239
  export { ConnectService };
@@ -0,0 +1,8 @@
1
+ export declare class CreateConnectSessionDto {
2
+ externalUserId: string;
3
+ organizationExternalId?: string;
4
+ configurationSlug?: string;
5
+ configurationId?: string;
6
+ redirectUrl?: string;
7
+ }
8
+ //# sourceMappingURL=create-connect-session.dto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-connect-session.dto.d.ts","sourceRoot":"","sources":["../../../src/connect/dto/create-connect-session.dto.ts"],"names":[],"mappings":"AAGA,qBAAa,uBAAuB;IAQlC,cAAc,EAAG,MAAM,CAAC;IAUxB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAQhC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAO3B,eAAe,CAAC,EAAE,MAAM,CAAC;IAOzB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
@@ -0,0 +1,55 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
3
+ import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
4
+ export class CreateConnectSessionDto {
5
+ externalUserId;
6
+ organizationExternalId;
7
+ configurationSlug;
8
+ configurationId;
9
+ redirectUrl;
10
+ }
11
+ __decorate([
12
+ ApiProperty({
13
+ example: 'user_9',
14
+ description: 'The consuming app’s own id for the person connecting.',
15
+ }),
16
+ IsString(),
17
+ MinLength(1),
18
+ MaxLength(255),
19
+ __metadata("design:type", String)
20
+ ], CreateConnectSessionDto.prototype, "externalUserId", void 0);
21
+ __decorate([
22
+ ApiPropertyOptional({
23
+ example: 'org_codemancers',
24
+ description: 'The app’s tenant this connection belongs to. Set it when the credential is the tenant’s — an API key for a whole workspace — and leave it out for a personal connection.',
25
+ }),
26
+ IsOptional(),
27
+ IsString(),
28
+ MaxLength(255),
29
+ __metadata("design:type", String)
30
+ ], CreateConnectSessionDto.prototype, "organizationExternalId", void 0);
31
+ __decorate([
32
+ ApiPropertyOptional({
33
+ example: 'github',
34
+ description: 'Configuration slug, as named in this environment.',
35
+ }),
36
+ IsOptional(),
37
+ IsString(),
38
+ __metadata("design:type", String)
39
+ ], CreateConnectSessionDto.prototype, "configurationSlug", void 0);
40
+ __decorate([
41
+ ApiPropertyOptional({
42
+ description: 'Configuration id, instead of the slug.',
43
+ }),
44
+ IsOptional(),
45
+ IsString(),
46
+ __metadata("design:type", String)
47
+ ], CreateConnectSessionDto.prototype, "configurationId", void 0);
48
+ __decorate([
49
+ ApiPropertyOptional({
50
+ description: 'Where to send the end user once they are back.',
51
+ }),
52
+ IsOptional(),
53
+ IsString(),
54
+ __metadata("design:type", String)
55
+ ], CreateConnectSessionDto.prototype, "redirectUrl", void 0);
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The admin standing in for an end user, so an operator can verify a
3
+ * configuration without wiring up their backend first.
4
+ */
5
+ export declare class CreateTestSessionDto {
6
+ slug?: string;
7
+ configurationId?: string;
8
+ redirectUrl?: string;
9
+ }
10
+ //# sourceMappingURL=create-test-session.dto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-test-session.dto.d.ts","sourceRoot":"","sources":["../../../src/connect/dto/create-test-session.dto.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,qBAAa,oBAAoB;IAI/B,IAAI,CAAC,EAAE,MAAM,CAAC;IAOd,eAAe,CAAC,EAAE,MAAM,CAAC;IAOzB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
@@ -0,0 +1,34 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { ApiPropertyOptional } from '@nestjs/swagger';
3
+ import { IsOptional, IsString } from 'class-validator';
4
+ /**
5
+ * The admin standing in for an end user, so an operator can verify a
6
+ * configuration without wiring up their backend first.
7
+ */
8
+ export class CreateTestSessionDto {
9
+ slug;
10
+ configurationId;
11
+ redirectUrl;
12
+ }
13
+ __decorate([
14
+ ApiPropertyOptional({ example: 'github' }),
15
+ IsOptional(),
16
+ IsString(),
17
+ __metadata("design:type", String)
18
+ ], CreateTestSessionDto.prototype, "slug", void 0);
19
+ __decorate([
20
+ ApiPropertyOptional({
21
+ description: 'Configuration id, instead of the slug.',
22
+ }),
23
+ IsOptional(),
24
+ IsString(),
25
+ __metadata("design:type", String)
26
+ ], CreateTestSessionDto.prototype, "configurationId", void 0);
27
+ __decorate([
28
+ ApiPropertyOptional({
29
+ description: 'Where to send the browser once the flow is done.',
30
+ }),
31
+ IsOptional(),
32
+ IsString(),
33
+ __metadata("design:type", String)
34
+ ], CreateTestSessionDto.prototype, "redirectUrl", void 0);
@@ -1,71 +1,18 @@
1
1
  import { type ApiKeyRequest } from '../auth/api-key.guard.js';
2
2
  import { ConnectionsService } from './connections.service.js';
3
+ import { ListConnectionsDto } from './dto/list-connections.dto.js';
4
+ /**
5
+ * The environment comes from the API key, so a caller only ever sees the
6
+ * connections of the environment its key reaches.
7
+ */
3
8
  export declare class ConnectionsController {
4
9
  private readonly connections;
5
10
  constructor(connections: ConnectionsService);
6
- list(request: ApiKeyRequest, endUserExternalId?: string): import("../generated/prisma/internal/prismaNamespace.js").PrismaPromise<({
7
- configuration: {
8
- name: string;
9
- id: string;
10
- provider: {
11
- name: string;
12
- key: string;
13
- };
14
- };
15
- endUser: {
16
- name: string | null;
17
- email: string | null;
18
- externalId: string;
19
- };
20
- } & {
21
- id: string;
22
- createdAt: Date;
23
- updatedAt: Date;
24
- status: import("../generated/prisma/enums.js").ConnectionStatus;
25
- metadata: import("@prisma/client/runtime/client").JsonValue | null;
26
- scopes: string[];
27
- organizationId: string;
28
- endUserId: string;
29
- configurationId: string;
30
- label: string | null;
31
- externalAccountId: string | null;
32
- lastSyncedAt: Date | null;
33
- lastUsedAt: Date | null;
34
- errorMessage: string | null;
35
- })[]>;
36
- get(request: ApiKeyRequest, id: string): Promise<{
37
- configuration: {
38
- name: string;
39
- id: string;
40
- provider: {
41
- name: string;
42
- key: string;
43
- };
44
- };
45
- endUser: {
46
- name: string | null;
47
- email: string | null;
48
- externalId: string;
49
- };
50
- } & {
51
- id: string;
52
- createdAt: Date;
53
- updatedAt: Date;
54
- status: import("../generated/prisma/enums.js").ConnectionStatus;
55
- metadata: import("@prisma/client/runtime/client").JsonValue | null;
56
- scopes: string[];
57
- organizationId: string;
58
- endUserId: string;
59
- configurationId: string;
60
- label: string | null;
61
- externalAccountId: string | null;
62
- lastSyncedAt: Date | null;
63
- lastUsedAt: Date | null;
64
- errorMessage: string | null;
65
- }>;
11
+ list(request: ApiKeyRequest, filters: ListConnectionsDto): Promise<import("./connections.repository.js").ListedConnection[]>;
12
+ get(request: ApiKeyRequest, id: string): Promise<import("./connections.repository.js").ListedConnection>;
66
13
  revoke(request: ApiKeyRequest, id: string): Promise<{
67
14
  id: string;
68
- status: "REVOKED";
15
+ revoked: true;
69
16
  }>;
70
17
  }
71
18
  //# sourceMappingURL=connections.controller.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"connections.controller.d.ts","sourceRoot":"","sources":["../../src/connections/connections.controller.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,KAAK,aAAa,EAAgB,MAAM,0BAA0B,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAE9D,qBAGa,qBAAqB;IACpB,OAAO,CAAC,QAAQ,CAAC,WAAW;gBAAX,WAAW,EAAE,kBAAkB;IAG5D,IAAI,CACK,OAAO,EAAE,aAAa,EACD,iBAAiB,CAAC,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAQxD,GAAG,CAAQ,OAAO,EAAE,aAAa,EAAe,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAK1D,MAAM,CAAQ,OAAO,EAAE,aAAa,EAAe,EAAE,EAAE,MAAM;;;;CAG9D"}
1
+ {"version":3,"file":"connections.controller.d.ts","sourceRoot":"","sources":["../../src/connections/connections.controller.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,KAAK,aAAa,EAAgB,MAAM,0BAA0B,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE;;;GAGG;AACH,qBAKa,qBAAqB;IACpB,OAAO,CAAC,QAAQ,CAAC,WAAW;gBAAX,WAAW,EAAE,kBAAkB;IAS5D,IAAI,CAAQ,OAAO,EAAE,aAAa,EAAW,OAAO,EAAE,kBAAkB;IAUxE,GAAG,CAAQ,OAAO,EAAE,aAAa,EAAe,EAAE,EAAE,MAAM;IAc1D,MAAM,CAAQ,OAAO,EAAE,aAAa,EAAe,EAAE,EAAE,MAAM;;;;CAO9D"}