@kosha-ai/server 0.1.0 → 0.3.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 (196) 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 +43 -2
  7. package/dist/bootstrap.d.ts.map +1 -1
  8. package/dist/bootstrap.js +24 -6
  9. package/dist/configurations/configurations.controller.d.ts +12 -136
  10. package/dist/configurations/configurations.controller.d.ts.map +1 -1
  11. package/dist/configurations/configurations.controller.js +65 -28
  12. package/dist/configurations/configurations.module.d.ts.map +1 -1
  13. package/dist/configurations/configurations.module.js +2 -0
  14. package/dist/configurations/configurations.service.d.ts +32 -200
  15. package/dist/configurations/configurations.service.d.ts.map +1 -1
  16. package/dist/configurations/configurations.service.js +98 -170
  17. package/dist/configurations/dto/create-configuration.dto.d.ts +7 -0
  18. package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -0
  19. package/dist/configurations/dto/create-configuration.dto.js +44 -0
  20. package/dist/configurations/dto/update-configuration.dto.d.ts +5 -0
  21. package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -0
  22. package/dist/configurations/dto/update-configuration.dto.js +23 -0
  23. package/dist/connect/connect.controller.d.ts +6 -8
  24. package/dist/connect/connect.controller.d.ts.map +1 -1
  25. package/dist/connect/connect.controller.js +46 -15
  26. package/dist/connect/connect.module.d.ts.map +1 -1
  27. package/dist/connect/connect.module.js +4 -3
  28. package/dist/connect/connect.repository.d.ts +78 -0
  29. package/dist/connect/connect.repository.d.ts.map +1 -0
  30. package/dist/connect/connect.repository.js +134 -0
  31. package/dist/connect/connect.service.d.ts +29 -21
  32. package/dist/connect/connect.service.d.ts.map +1 -1
  33. package/dist/connect/connect.service.js +157 -168
  34. package/dist/connect/dto/create-connect-session.dto.d.ts +8 -0
  35. package/dist/connect/dto/create-connect-session.dto.d.ts.map +1 -0
  36. package/dist/connect/dto/create-connect-session.dto.js +54 -0
  37. package/dist/connect/dto/create-test-session.dto.d.ts +11 -0
  38. package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -0
  39. package/dist/connect/dto/create-test-session.dto.js +41 -0
  40. package/dist/connections/connections.controller.d.ts +10 -62
  41. package/dist/connections/connections.controller.d.ts.map +1 -1
  42. package/dist/connections/connections.controller.js +41 -17
  43. package/dist/connections/connections.module.d.ts.map +1 -1
  44. package/dist/connections/connections.module.js +4 -1
  45. package/dist/connections/connections.repository.d.ts +31 -0
  46. package/dist/connections/connections.repository.d.ts.map +1 -0
  47. package/dist/connections/connections.repository.js +44 -0
  48. package/dist/connections/connections.service.d.ts +58 -68
  49. package/dist/connections/connections.service.d.ts.map +1 -1
  50. package/dist/connections/connections.service.js +137 -55
  51. package/dist/connections/dto/list-connections.dto.d.ts +7 -0
  52. package/dist/connections/dto/list-connections.dto.d.ts.map +1 -0
  53. package/dist/connections/dto/list-connections.dto.js +47 -0
  54. package/dist/connections/environment-connections.controller.d.ts +27 -0
  55. package/dist/connections/environment-connections.controller.d.ts.map +1 -0
  56. package/dist/connections/environment-connections.controller.js +83 -0
  57. package/dist/connections/environment-connections.module.d.ts +11 -0
  58. package/dist/connections/environment-connections.module.d.ts.map +1 -0
  59. package/dist/connections/environment-connections.module.js +21 -0
  60. package/dist/credentials/credentials.module.d.ts.map +1 -1
  61. package/dist/credentials/credentials.module.js +2 -4
  62. package/dist/credentials/credentials.repository.d.ts +11 -0
  63. package/dist/credentials/credentials.repository.d.ts.map +1 -0
  64. package/dist/credentials/credentials.repository.js +28 -0
  65. package/dist/credentials/credentials.service.d.ts +25 -31
  66. package/dist/credentials/credentials.service.d.ts.map +1 -1
  67. package/dist/credentials/credentials.service.js +100 -62
  68. package/dist/crypto/credential-envelope.d.ts +56 -0
  69. package/dist/crypto/credential-envelope.d.ts.map +1 -0
  70. package/dist/crypto/credential-envelope.js +70 -0
  71. package/dist/crypto/crypto.service.d.ts +8 -0
  72. package/dist/crypto/crypto.service.d.ts.map +1 -1
  73. package/dist/crypto/crypto.service.js +12 -0
  74. package/dist/egress/dto/mint-grant.dto.d.ts +7 -0
  75. package/dist/egress/dto/mint-grant.dto.d.ts.map +1 -0
  76. package/dist/egress/dto/mint-grant.dto.js +44 -0
  77. package/dist/egress/egress.controller.d.ts +2 -8
  78. package/dist/egress/egress.controller.d.ts.map +1 -1
  79. package/dist/egress/egress.controller.js +27 -6
  80. package/dist/egress/egress.listener.d.ts.map +1 -1
  81. package/dist/egress/egress.listener.js +6 -6
  82. package/dist/egress/egress.module.d.ts.map +1 -1
  83. package/dist/egress/egress.module.js +10 -2
  84. package/dist/egress/egress.repository.d.ts +65 -0
  85. package/dist/egress/egress.repository.d.ts.map +1 -0
  86. package/dist/egress/egress.repository.js +103 -0
  87. package/dist/egress/grants.service.d.ts +23 -78
  88. package/dist/egress/grants.service.d.ts.map +1 -1
  89. package/dist/egress/grants.service.js +44 -104
  90. package/dist/environments/dto/create-environment.dto.d.ts +6 -0
  91. package/dist/environments/dto/create-environment.dto.d.ts.map +1 -0
  92. package/dist/environments/dto/create-environment.dto.js +34 -0
  93. package/dist/environments/dto/update-environment.dto.d.ts +5 -0
  94. package/dist/environments/dto/update-environment.dto.d.ts.map +1 -0
  95. package/dist/environments/dto/update-environment.dto.js +24 -0
  96. package/dist/environments/environments.controller.d.ts +53 -0
  97. package/dist/environments/environments.controller.d.ts.map +1 -0
  98. package/dist/environments/environments.controller.js +101 -0
  99. package/dist/environments/environments.module.d.ts +3 -0
  100. package/dist/environments/environments.module.d.ts.map +1 -0
  101. package/dist/environments/environments.module.js +15 -0
  102. package/dist/environments/environments.repository.d.ts +37 -0
  103. package/dist/environments/environments.repository.d.ts.map +1 -0
  104. package/dist/environments/environments.repository.js +82 -0
  105. package/dist/environments/environments.service.d.ts +43 -0
  106. package/dist/environments/environments.service.d.ts.map +1 -0
  107. package/dist/environments/environments.service.js +124 -0
  108. package/dist/generated/prisma/browser.d.ts +11 -39
  109. package/dist/generated/prisma/browser.d.ts.map +1 -1
  110. package/dist/generated/prisma/client.d.ts +11 -39
  111. package/dist/generated/prisma/client.d.ts.map +1 -1
  112. package/dist/generated/prisma/commonInputTypes.d.ts +50 -146
  113. package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -1
  114. package/dist/generated/prisma/enums.d.ts +1 -21
  115. package/dist/generated/prisma/enums.d.ts.map +1 -1
  116. package/dist/generated/prisma/enums.js +1 -18
  117. package/dist/generated/prisma/internal/class.d.ts +16 -60
  118. package/dist/generated/prisma/internal/class.d.ts.map +1 -1
  119. package/dist/generated/prisma/internal/class.js +4 -4
  120. package/dist/generated/prisma/internal/prismaNamespace.d.ts +166 -583
  121. package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
  122. package/dist/generated/prisma/internal/prismaNamespace.js +25 -104
  123. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +26 -111
  124. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
  125. package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +25 -104
  126. package/dist/generated/prisma/models/EgressGrant.d.ts +131 -134
  127. package/dist/generated/prisma/models/EgressGrant.d.ts.map +1 -1
  128. package/dist/generated/prisma/models/Environment.d.ts +1386 -0
  129. package/dist/generated/prisma/models/Environment.d.ts.map +1 -0
  130. package/dist/generated/prisma/models/Invitation.d.ts +42 -1
  131. package/dist/generated/prisma/models/Invitation.d.ts.map +1 -1
  132. package/dist/generated/prisma/models/Organization.d.ts +122 -408
  133. package/dist/generated/prisma/models/Organization.d.ts.map +1 -1
  134. package/dist/generated/prisma/models/Session.d.ts +36 -1
  135. package/dist/generated/prisma/models/Session.d.ts.map +1 -1
  136. package/dist/generated/prisma/models/Team.d.ts +1498 -0
  137. package/dist/generated/prisma/models/Team.d.ts.map +1 -0
  138. package/dist/generated/prisma/models/TeamMember.d.ts +1281 -0
  139. package/dist/generated/prisma/models/TeamMember.d.ts.map +1 -0
  140. package/dist/generated/prisma/models/User.d.ts +278 -0
  141. package/dist/generated/prisma/models/User.d.ts.map +1 -1
  142. package/dist/generated/prisma/models.d.ts +3 -7
  143. package/dist/generated/prisma/models.d.ts.map +1 -1
  144. package/dist/index.d.ts +14 -5
  145. package/dist/index.d.ts.map +1 -1
  146. package/dist/index.js +11 -2
  147. package/dist/integrations/integrations.controller.d.ts +4 -1
  148. package/dist/integrations/integrations.controller.d.ts.map +1 -1
  149. package/dist/integrations/integrations.controller.js +1 -0
  150. package/dist/integrations/integrations.module.js +3 -3
  151. package/dist/integrations/provider-store.d.ts +104 -0
  152. package/dist/integrations/provider-store.d.ts.map +1 -0
  153. package/dist/integrations/provider-store.js +234 -0
  154. package/dist/kosha.module.d.ts.map +1 -1
  155. package/dist/kosha.module.js +9 -3
  156. package/dist/proxy/proxy.controller.d.ts +12 -3
  157. package/dist/proxy/proxy.controller.d.ts.map +1 -1
  158. package/dist/proxy/proxy.controller.js +31 -10
  159. package/dist/proxy/proxy.module.d.ts.map +1 -1
  160. package/dist/proxy/proxy.module.js +4 -2
  161. package/dist/proxy/proxy.repository.d.ts +21 -0
  162. package/dist/proxy/proxy.repository.d.ts.map +1 -0
  163. package/dist/proxy/proxy.repository.js +37 -0
  164. package/dist/proxy/proxy.service.d.ts +15 -5
  165. package/dist/proxy/proxy.service.d.ts.map +1 -1
  166. package/dist/proxy/proxy.service.js +63 -26
  167. package/package.json +7 -4
  168. package/prisma/migrations/{20260908000000_init → 20261008090000_init}/migration.sql +99 -16
  169. package/prisma/schema.prisma +56 -202
  170. package/dist/generated/prisma/models/Configuration.d.ts +0 -2018
  171. package/dist/generated/prisma/models/Configuration.d.ts.map +0 -1
  172. package/dist/generated/prisma/models/ConnectSession.d.ts +0 -1606
  173. package/dist/generated/prisma/models/ConnectSession.d.ts.map +0 -1
  174. package/dist/generated/prisma/models/Connection.d.ts +0 -1949
  175. package/dist/generated/prisma/models/Connection.d.ts.map +0 -1
  176. package/dist/generated/prisma/models/ConnectionCredential.d.ts +0 -1293
  177. package/dist/generated/prisma/models/ConnectionCredential.d.ts.map +0 -1
  178. package/dist/generated/prisma/models/ConnectionCredential.js +0 -1
  179. package/dist/generated/prisma/models/EndUser.d.ts +0 -1666
  180. package/dist/generated/prisma/models/EndUser.d.ts.map +0 -1
  181. package/dist/generated/prisma/models/EndUser.js +0 -1
  182. package/dist/generated/prisma/models/OAuthState.d.ts +0 -1404
  183. package/dist/generated/prisma/models/OAuthState.d.ts.map +0 -1
  184. package/dist/generated/prisma/models/OAuthState.js +0 -1
  185. package/dist/generated/prisma/models/Provider.d.ts +0 -1462
  186. package/dist/generated/prisma/models/Provider.d.ts.map +0 -1
  187. package/dist/generated/prisma/models/Provider.js +0 -1
  188. package/dist/integrations/provider-sync.service.d.ts +0 -24
  189. package/dist/integrations/provider-sync.service.d.ts.map +0 -1
  190. package/dist/integrations/provider-sync.service.js +0 -74
  191. package/prisma/migrations/20260908161813_add_connect_domain/migration.sql +0 -173
  192. package/prisma/migrations/20260916000000_add_configuration_slug/migration.sql +0 -15
  193. package/prisma/migrations/20260921000000_add_egress_grant/migration.sql +0 -31
  194. /package/dist/generated/prisma/models/{Configuration.js → Environment.js} +0 -0
  195. /package/dist/generated/prisma/models/{ConnectSession.js → Team.js} +0 -0
  196. /package/dist/generated/prisma/models/{Connection.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
- import { ConfigurationsService } from '../configurations/configurations.service.js';
7
+ import { ENVELOPE_VERSION, expiryOf, } from '../crypto/credential-envelope.js';
9
8
  import { CryptoService } from '../crypto/crypto.service.js';
9
+ import { EnvironmentsService } from '../environments/environments.service.js';
10
10
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
11
- import { PrismaService } from '../prisma/prisma.service.js';
11
+ import { ProviderStore, } from '../integrations/provider-store.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,208 @@ 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
- configurations;
28
+ store;
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, store, environments, registry, config) {
34
+ this.connect = connect;
33
35
  this.crypto = crypto;
34
- this.configurations = configurations;
36
+ this.store = store;
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');
62
- }
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
- });
50
+ const environment = await this.environments.get(organizationId, environmentId);
51
+ const integration = this.registry.get(input.provider);
52
+ const configuration = await this.resolveConfiguration(integration, environmentId, input);
53
+ // Nothing else sweeps these: `verification` is shared with email
54
+ // verification and password reset, so only this flow knows which rows are
55
+ // its own. Swept here rather than on a schedule, so no timer has to exist.
56
+ void this.connect
57
+ .deleteExpired()
58
+ .catch((error) => this.logger.warn(`Sweeping expired connect state failed: ${String(error)}`));
59
+ const token = randomToken();
73
60
  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
- });
61
+ await this.connect.putSession(token, {
62
+ organizationId,
63
+ environmentId: environment.id,
64
+ environmentSlug: environment.slug,
65
+ provider: integration.key,
66
+ configurationId: configuration.id,
67
+ externalUserId,
68
+ redirectUrl: input.redirectUrl ?? null,
69
+ }, expiresAt);
84
70
  const { publicUrl, globalPrefix } = this.config.server;
85
71
  return {
86
- token: session.token,
87
- connectUrl: `${publicUrl}/${globalPrefix}/connect/${session.token}/start`,
72
+ token,
73
+ connectUrl: `${publicUrl}/${globalPrefix}/connect/${token}/start`,
88
74
  expiresAt,
89
75
  };
90
76
  }
91
77
  /**
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.
78
+ * Exchanges a connect token for the provider's authorize URL, carrying the
79
+ * flow's state — and, where the provider supports it, a PKCE verifier —
80
+ * across the redirect.
95
81
  */
96
82
  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()) {
83
+ const session = await this.connect.takeSession(token);
84
+ if (!session) {
103
85
  throw new NotFoundException('Connect session not found or expired');
104
86
  }
105
- const configurationId = session.allowedConfigurationIds[0];
106
- const configuration = await this.configurations.getWithDecryptedSecret(configurationId);
107
- if (configuration.organizationId !== session.organizationId ||
108
- !configuration.isEnabled) {
87
+ const integration = this.registry.get(session.provider);
88
+ const configuration = await this.store.findConfigurationWithCredentials(integration, session.configurationId);
89
+ if (!configuration) {
109
90
  throw new BadRequestException('Configuration is no longer available');
110
91
  }
111
- const integration = this.registry.get(configuration.provider.key);
112
92
  const codeVerifier = integration.auth.pkce
113
93
  ? generateCodeVerifier()
114
94
  : 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
- });
95
+ const state = randomToken();
96
+ await this.connect.putState(state, { ...session, codeVerifier }, new Date(Date.now() + STATE_TTL_MS));
124
97
  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,
98
+ client: this.clientContextFor(integration, configuration),
99
+ state,
133
100
  codeVerifier,
134
101
  });
135
102
  }
136
103
  /** 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()) {
104
+ async handleCallback(provider, code, state) {
105
+ const flow = await this.connect.takeState(state);
106
+ if (!flow) {
145
107
  throw new NotFoundException('OAuth state not found or expired');
146
108
  }
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) {
109
+ if (flow.provider !== provider) {
155
110
  throw new BadRequestException('Provider mismatch');
156
111
  }
157
- const integration = this.registry.get(providerKey);
112
+ const integration = this.registry.get(provider);
113
+ const configuration = await this.store.findConfigurationWithCredentials(integration, flow.configurationId);
114
+ if (!configuration) {
115
+ throw new BadRequestException('Configuration is no longer available');
116
+ }
158
117
  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
- },
118
+ client: this.clientContextFor(integration, configuration),
166
119
  code,
167
- codeVerifier: oauthState.codeVerifier ?? undefined,
120
+ codeVerifier: flow.codeVerifier,
168
121
  });
169
122
  const identity = await integration.identity.fetchAccount({
170
123
  accessToken: tokens.accessToken,
171
124
  http: httpFor(integration),
172
125
  });
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' },
126
+ const user = await this.connect.upsertEndUser(flow.environmentSlug, flow.externalUserId);
127
+ const account = await this.writeCredential(flow, integration, {
128
+ userId: user.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
+ metadata: 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 somebody take over a credential a colleague
146
+ * connected, with no trace. Reconnecting means revoking first, which is a
147
+ * deliberate act by someone who can see what they are replacing.
148
+ */
149
+ async writeCredential(flow, integration, input) {
150
+ const envelope = this.envelopeFor(input.tokens);
151
+ const accessToken = this.crypto.sealEnvelope(envelope);
152
+ const accessTokenExpiresAt = expiryOf(envelope);
153
+ // Read before writing, so a second connect is a clear refusal rather than
154
+ // the unique index surfacing as a 500. The index is still the backstop.
155
+ const existing = await this.store.findConnection(integration, flow.environmentId, flow.configurationId, input.userId);
156
+ if (existing) {
157
+ throw new ConflictException('This person is already connected to this configuration. Revoke that connection first.');
158
+ }
159
+ return this.connect.storeCredential({
160
+ userId: input.userId,
161
+ provider: integration.key,
162
+ accountId: input.accountId,
163
+ accessToken,
164
+ accessTokenExpiresAt,
165
+ scope: input.tokens.scope ?? null,
166
+ }, (tx, accountId) => this.store.storeConnection(tx, integration, {
167
+ accountId,
168
+ userId: input.userId,
169
+ environmentId: flow.environmentId,
170
+ configurationId: flow.configurationId,
171
+ metadata: input.metadata,
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(integration, configuration) {
197
+ const credentials = configuration.credentials
198
+ ? JSON.parse(this.crypto.decrypt(configuration.credentials))
199
+ : {};
200
+ const { publicUrl, globalPrefix } = this.config.server;
201
+ return {
202
+ clientId: String(credentials['clientId'] ?? ''),
203
+ clientSecret: String(credentials['clientSecret'] ?? ''),
204
+ redirectUri: `${publicUrl}/${globalPrefix}/connect/callback/${integration.key}`,
205
+ // Declared by the package. An operator does not pick these, so there is
206
+ // nothing stored to drift from what the provider's console allows.
207
+ scopes: integration.auth.scopesRequested,
228
208
  };
229
- await this.prisma.connectionCredential.upsert({
230
- where: { connectionId },
231
- create: { connectionId, ...data, refreshToken },
232
- update: refreshToken ? { ...data, refreshToken } : data,
233
- });
209
+ }
210
+ async resolveConfiguration(integration, environmentId, input) {
211
+ const slug = input.configurationSlug?.trim();
212
+ const id = input.configurationId?.trim();
213
+ if (!slug && !id) {
214
+ throw new BadRequestException('configurationId or configurationSlug is required');
215
+ }
216
+ const configuration = slug
217
+ ? await this.store.findConfigurationBySlug(integration, environmentId, slug)
218
+ : await this.store.findConfigurationById(integration, environmentId, id);
219
+ if (!configuration)
220
+ throw new NotFoundException('Configuration not found');
221
+ return configuration;
234
222
  }
235
223
  /** An integration's hook must never take the request down with it. */
236
224
  async runHook(integration, hook) {
@@ -244,10 +232,11 @@ let ConnectService = ConnectService_1 = class ConnectService {
244
232
  };
245
233
  ConnectService = ConnectService_1 = __decorate([
246
234
  Injectable(),
247
- __param(4, Inject(KOSHA_CONFIG)),
248
- __metadata("design:paramtypes", [PrismaService,
235
+ __param(5, Inject(KOSHA_CONFIG)),
236
+ __metadata("design:paramtypes", [ConnectRepository,
249
237
  CryptoService,
250
- ConfigurationsService,
238
+ ProviderStore,
239
+ EnvironmentsService,
251
240
  IntegrationRegistry, Object])
252
241
  ], ConnectService);
253
242
  export { ConnectService };
@@ -0,0 +1,8 @@
1
+ export declare class CreateConnectSessionDto {
2
+ externalUserId: string;
3
+ provider: 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;IASxB,QAAQ,EAAG,MAAM,CAAC;IAQlB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAO3B,eAAe,CAAC,EAAE,MAAM,CAAC;IAOzB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
@@ -0,0 +1,54 @@
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
+ provider;
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
+ ApiProperty({
23
+ example: 'github',
24
+ description: 'Which provider. Configurations live in per-provider tables, so a slug is only unique within one.',
25
+ }),
26
+ IsString(),
27
+ MinLength(1),
28
+ __metadata("design:type", String)
29
+ ], CreateConnectSessionDto.prototype, "provider", void 0);
30
+ __decorate([
31
+ ApiPropertyOptional({
32
+ example: 'my-github',
33
+ description: 'Configuration slug, as named in this environment.',
34
+ }),
35
+ IsOptional(),
36
+ IsString(),
37
+ __metadata("design:type", String)
38
+ ], CreateConnectSessionDto.prototype, "configurationSlug", void 0);
39
+ __decorate([
40
+ ApiPropertyOptional({
41
+ description: 'Configuration id, instead of the slug.',
42
+ }),
43
+ IsOptional(),
44
+ IsString(),
45
+ __metadata("design:type", String)
46
+ ], CreateConnectSessionDto.prototype, "configurationId", void 0);
47
+ __decorate([
48
+ ApiPropertyOptional({
49
+ description: 'Where to send the end user once they are back.',
50
+ }),
51
+ IsOptional(),
52
+ IsString(),
53
+ __metadata("design:type", String)
54
+ ], CreateConnectSessionDto.prototype, "redirectUrl", void 0);
@@ -0,0 +1,11 @@
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
+ provider: string;
7
+ slug?: string;
8
+ configurationId?: string;
9
+ redirectUrl?: string;
10
+ }
11
+ //# 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,QAAQ,EAAG,MAAM,CAAC;IAKlB,IAAI,CAAC,EAAE,MAAM,CAAC;IAOd,eAAe,CAAC,EAAE,MAAM,CAAC;IAOzB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
@@ -0,0 +1,41 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
3
+ import { IsOptional, IsString, MinLength } 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
+ provider;
10
+ slug;
11
+ configurationId;
12
+ redirectUrl;
13
+ }
14
+ __decorate([
15
+ ApiProperty({ example: 'github', description: 'Which provider.' }),
16
+ IsString(),
17
+ MinLength(1),
18
+ __metadata("design:type", String)
19
+ ], CreateTestSessionDto.prototype, "provider", void 0);
20
+ __decorate([
21
+ ApiPropertyOptional({ example: 'my-github' }),
22
+ IsOptional(),
23
+ IsString(),
24
+ __metadata("design:type", String)
25
+ ], CreateTestSessionDto.prototype, "slug", void 0);
26
+ __decorate([
27
+ ApiPropertyOptional({
28
+ description: 'Configuration id, instead of the slug.',
29
+ }),
30
+ IsOptional(),
31
+ IsString(),
32
+ __metadata("design:type", String)
33
+ ], CreateTestSessionDto.prototype, "configurationId", void 0);
34
+ __decorate([
35
+ ApiPropertyOptional({
36
+ description: 'Where to send the browser once the flow is done.',
37
+ }),
38
+ IsOptional(),
39
+ IsString(),
40
+ __metadata("design:type", String)
41
+ ], CreateTestSessionDto.prototype, "redirectUrl", void 0);
@@ -1,71 +1,19 @@
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
- } & {
11
+ list(request: ApiKeyRequest, filters: ListConnectionsDto): Promise<import("./connections.service.js").DescribedConnection[]>;
12
+ get(request: ApiKeyRequest, provider: string, id: string): Promise<import("./connections.service.js").DescribedConnection>;
13
+ revoke(request: ApiKeyRequest, provider: string, id: string): Promise<{
21
14
  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
- }>;
66
- revoke(request: ApiKeyRequest, id: string): Promise<{
67
- id: string;
68
- status: "REVOKED";
15
+ provider: string;
16
+ revoked: true;
69
17
  }>;
70
18
  }
71
19
  //# 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,CACM,OAAO,EAAE,aAAa,EACV,QAAQ,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM;IAgBzB,MAAM,CACG,OAAO,EAAE,aAAa,EACV,QAAQ,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM;;;;;CAS1B"}