@kosha-ai/server 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) 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/configurations/configurations.controller.d.ts +11 -136
  10. package/dist/configurations/configurations.controller.d.ts.map +1 -1
  11. package/dist/configurations/configurations.controller.js +58 -25
  12. package/dist/configurations/configurations.module.d.ts.map +1 -1
  13. package/dist/configurations/configurations.module.js +4 -1
  14. package/dist/configurations/configurations.repository.d.ts +43 -0
  15. package/dist/configurations/configurations.repository.d.ts.map +1 -0
  16. package/dist/configurations/configurations.repository.js +76 -0
  17. package/dist/configurations/configurations.service.d.ts +38 -194
  18. package/dist/configurations/configurations.service.d.ts.map +1 -1
  19. package/dist/configurations/configurations.service.js +118 -110
  20. package/dist/configurations/dto/create-configuration.dto.d.ts +8 -0
  21. package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -0
  22. package/dist/configurations/dto/create-configuration.dto.js +54 -0
  23. package/dist/configurations/dto/update-configuration.dto.d.ts +7 -0
  24. package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -0
  25. package/dist/configurations/dto/update-configuration.dto.js +39 -0
  26. package/dist/connect/connect.controller.d.ts +6 -8
  27. package/dist/connect/connect.controller.d.ts.map +1 -1
  28. package/dist/connect/connect.controller.js +45 -15
  29. package/dist/connect/connect.module.d.ts.map +1 -1
  30. package/dist/connect/connect.module.js +4 -2
  31. package/dist/connect/connect.repository.d.ts +78 -0
  32. package/dist/connect/connect.repository.d.ts.map +1 -0
  33. package/dist/connect/connect.repository.js +146 -0
  34. package/dist/connect/connect.service.d.ts +28 -19
  35. package/dist/connect/connect.service.d.ts.map +1 -1
  36. package/dist/connect/connect.service.js +149 -163
  37. package/dist/connect/dto/create-connect-session.dto.d.ts +8 -0
  38. package/dist/connect/dto/create-connect-session.dto.d.ts.map +1 -0
  39. package/dist/connect/dto/create-connect-session.dto.js +55 -0
  40. package/dist/connect/dto/create-test-session.dto.d.ts +10 -0
  41. package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -0
  42. package/dist/connect/dto/create-test-session.dto.js +34 -0
  43. package/dist/connections/connections.controller.d.ts +8 -61
  44. package/dist/connections/connections.controller.d.ts.map +1 -1
  45. package/dist/connections/connections.controller.js +31 -9
  46. package/dist/connections/connections.module.d.ts.map +1 -1
  47. package/dist/connections/connections.module.js +4 -1
  48. package/dist/connections/connections.repository.d.ts +24 -0
  49. package/dist/connections/connections.repository.d.ts.map +1 -0
  50. package/dist/connections/connections.repository.js +66 -0
  51. package/dist/connections/connections.service.d.ts +24 -69
  52. package/dist/connections/connections.service.d.ts.map +1 -1
  53. package/dist/connections/connections.service.js +59 -56
  54. package/dist/connections/dto/list-connections.dto.d.ts +5 -0
  55. package/dist/connections/dto/list-connections.dto.d.ts.map +1 -0
  56. package/dist/connections/dto/list-connections.dto.js +25 -0
  57. package/dist/connections/environment-connections.controller.d.ts +26 -0
  58. package/dist/connections/environment-connections.controller.d.ts.map +1 -0
  59. package/dist/connections/environment-connections.controller.js +81 -0
  60. package/dist/connections/environment-connections.module.d.ts +11 -0
  61. package/dist/connections/environment-connections.module.d.ts.map +1 -0
  62. package/dist/connections/environment-connections.module.js +21 -0
  63. package/dist/credentials/credentials.module.js +3 -3
  64. package/dist/credentials/credentials.repository.d.ts +8 -0
  65. package/dist/credentials/credentials.repository.d.ts.map +1 -0
  66. package/dist/credentials/credentials.repository.js +21 -0
  67. package/dist/credentials/credentials.service.d.ts +19 -29
  68. package/dist/credentials/credentials.service.d.ts.map +1 -1
  69. package/dist/credentials/credentials.service.js +84 -57
  70. package/dist/crypto/credential-envelope.d.ts +56 -0
  71. package/dist/crypto/credential-envelope.d.ts.map +1 -0
  72. package/dist/crypto/credential-envelope.js +70 -0
  73. package/dist/crypto/crypto.service.d.ts +8 -0
  74. package/dist/crypto/crypto.service.d.ts.map +1 -1
  75. package/dist/crypto/crypto.service.js +12 -0
  76. package/dist/egress/dto/mint-grant.dto.d.ts +7 -0
  77. package/dist/egress/dto/mint-grant.dto.d.ts.map +1 -0
  78. package/dist/egress/dto/mint-grant.dto.js +44 -0
  79. package/dist/egress/egress.controller.d.ts +2 -8
  80. package/dist/egress/egress.controller.d.ts.map +1 -1
  81. package/dist/egress/egress.controller.js +27 -6
  82. package/dist/egress/egress.listener.d.ts +3 -1
  83. package/dist/egress/egress.listener.d.ts.map +1 -1
  84. package/dist/egress/egress.listener.js +12 -8
  85. package/dist/egress/egress.module.d.ts.map +1 -1
  86. package/dist/egress/egress.module.js +10 -2
  87. package/dist/egress/egress.repository.d.ts +58 -0
  88. package/dist/egress/egress.repository.d.ts.map +1 -0
  89. package/dist/egress/egress.repository.js +116 -0
  90. package/dist/egress/grants.service.d.ts +23 -78
  91. package/dist/egress/grants.service.d.ts.map +1 -1
  92. package/dist/egress/grants.service.js +44 -104
  93. package/dist/environments/dto/create-environment.dto.d.ts +6 -0
  94. package/dist/environments/dto/create-environment.dto.d.ts.map +1 -0
  95. package/dist/environments/dto/create-environment.dto.js +34 -0
  96. package/dist/environments/dto/update-environment.dto.d.ts +5 -0
  97. package/dist/environments/dto/update-environment.dto.d.ts.map +1 -0
  98. package/dist/environments/dto/update-environment.dto.js +24 -0
  99. package/dist/environments/environments.controller.d.ts +53 -0
  100. package/dist/environments/environments.controller.d.ts.map +1 -0
  101. package/dist/environments/environments.controller.js +101 -0
  102. package/dist/environments/environments.module.d.ts +3 -0
  103. package/dist/environments/environments.module.d.ts.map +1 -0
  104. package/dist/environments/environments.module.js +15 -0
  105. package/dist/environments/environments.repository.d.ts +37 -0
  106. package/dist/environments/environments.repository.d.ts.map +1 -0
  107. package/dist/environments/environments.repository.js +82 -0
  108. package/dist/environments/environments.service.d.ts +43 -0
  109. package/dist/environments/environments.service.d.ts.map +1 -0
  110. package/dist/environments/environments.service.js +124 -0
  111. package/dist/generated/prisma/browser.d.ts +14 -37
  112. package/dist/generated/prisma/browser.d.ts.map +1 -1
  113. package/dist/generated/prisma/client.d.ts +14 -37
  114. package/dist/generated/prisma/client.d.ts.map +1 -1
  115. package/dist/generated/prisma/commonInputTypes.d.ts +104 -145
  116. package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -1
  117. package/dist/generated/prisma/enums.d.ts +1 -21
  118. package/dist/generated/prisma/enums.d.ts.map +1 -1
  119. package/dist/generated/prisma/enums.js +1 -18
  120. package/dist/generated/prisma/internal/class.d.ts +20 -53
  121. package/dist/generated/prisma/internal/class.d.ts.map +1 -1
  122. package/dist/generated/prisma/internal/class.js +4 -4
  123. package/dist/generated/prisma/internal/prismaNamespace.d.ts +215 -519
  124. package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
  125. package/dist/generated/prisma/internal/prismaNamespace.js +38 -90
  126. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +37 -92
  127. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
  128. package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +38 -90
  129. package/dist/generated/prisma/models/Account.d.ts +344 -26
  130. package/dist/generated/prisma/models/Account.d.ts.map +1 -1
  131. package/dist/generated/prisma/models/Configuration.d.ts +218 -851
  132. package/dist/generated/prisma/models/Configuration.d.ts.map +1 -1
  133. package/dist/generated/prisma/models/EgressGrant.d.ts +131 -134
  134. package/dist/generated/prisma/models/EgressGrant.d.ts.map +1 -1
  135. package/dist/generated/prisma/models/Environment.d.ts +1644 -0
  136. package/dist/generated/prisma/models/Environment.d.ts.map +1 -0
  137. package/dist/generated/prisma/models/Invitation.d.ts +42 -1
  138. package/dist/generated/prisma/models/Invitation.d.ts.map +1 -1
  139. package/dist/generated/prisma/models/Organization.d.ts +122 -408
  140. package/dist/generated/prisma/models/Organization.d.ts.map +1 -1
  141. package/dist/generated/prisma/models/Session.d.ts +36 -1
  142. package/dist/generated/prisma/models/Session.d.ts.map +1 -1
  143. package/dist/generated/prisma/models/Team.d.ts +1498 -0
  144. package/dist/generated/prisma/models/Team.d.ts.map +1 -0
  145. package/dist/generated/prisma/models/TeamMember.d.ts +1281 -0
  146. package/dist/generated/prisma/models/TeamMember.d.ts.map +1 -0
  147. package/dist/generated/prisma/models/User.d.ts +338 -2
  148. package/dist/generated/prisma/models/User.d.ts.map +1 -1
  149. package/dist/generated/prisma/models.d.ts +3 -6
  150. package/dist/generated/prisma/models.d.ts.map +1 -1
  151. package/dist/index.d.ts +15 -5
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +11 -2
  154. package/dist/integrations/integrations.controller.d.ts +2 -1
  155. package/dist/integrations/integrations.controller.d.ts.map +1 -1
  156. package/dist/integrations/integrations.module.d.ts.map +1 -1
  157. package/dist/integrations/integrations.module.js +0 -2
  158. package/dist/kosha.module.d.ts.map +1 -1
  159. package/dist/kosha.module.js +9 -3
  160. package/dist/proxy/proxy.controller.d.ts +8 -3
  161. package/dist/proxy/proxy.controller.d.ts.map +1 -1
  162. package/dist/proxy/proxy.controller.js +26 -10
  163. package/dist/proxy/proxy.module.d.ts.map +1 -1
  164. package/dist/proxy/proxy.module.js +5 -2
  165. package/dist/proxy/proxy.repository.d.ts +24 -0
  166. package/dist/proxy/proxy.repository.d.ts.map +1 -0
  167. package/dist/proxy/proxy.repository.js +47 -0
  168. package/dist/proxy/proxy.service.d.ts +17 -5
  169. package/dist/proxy/proxy.service.d.ts.map +1 -1
  170. package/dist/proxy/proxy.service.js +58 -27
  171. package/package.json +7 -4
  172. package/prisma/migrations/20260929101936_init/migration.sql +345 -0
  173. package/prisma/migrations/20260930102529_connection_config/migration.sql +2 -0
  174. package/prisma/schema.prisma +93 -198
  175. package/dist/generated/prisma/models/ConnectSession.d.ts +0 -1606
  176. package/dist/generated/prisma/models/ConnectSession.d.ts.map +0 -1
  177. package/dist/generated/prisma/models/Connection.d.ts +0 -1949
  178. package/dist/generated/prisma/models/Connection.d.ts.map +0 -1
  179. package/dist/generated/prisma/models/ConnectionCredential.d.ts +0 -1293
  180. package/dist/generated/prisma/models/ConnectionCredential.d.ts.map +0 -1
  181. package/dist/generated/prisma/models/EndUser.d.ts +0 -1666
  182. package/dist/generated/prisma/models/EndUser.d.ts.map +0 -1
  183. package/dist/generated/prisma/models/EndUser.js +0 -1
  184. package/dist/generated/prisma/models/OAuthState.d.ts +0 -1404
  185. package/dist/generated/prisma/models/OAuthState.d.ts.map +0 -1
  186. package/dist/generated/prisma/models/OAuthState.js +0 -1
  187. package/dist/generated/prisma/models/Provider.d.ts +0 -1462
  188. package/dist/generated/prisma/models/Provider.d.ts.map +0 -1
  189. package/dist/generated/prisma/models/Provider.js +0 -1
  190. package/dist/integrations/provider-sync.service.d.ts +0 -24
  191. package/dist/integrations/provider-sync.service.d.ts.map +0 -1
  192. package/dist/integrations/provider-sync.service.js +0 -74
  193. package/prisma/migrations/20260908000000_init/migration.sql +0 -209
  194. package/prisma/migrations/20260908161813_add_connect_domain/migration.sql +0 -173
  195. package/prisma/migrations/20260916000000_add_configuration_slug/migration.sql +0 -15
  196. package/prisma/migrations/20260921000000_add_egress_grant/migration.sql +0 -31
  197. /package/dist/generated/prisma/models/{ConnectSession.js → Environment.js} +0 -0
  198. /package/dist/generated/prisma/models/{Connection.js → Team.js} +0 -0
  199. /package/dist/generated/prisma/models/{ConnectionCredential.js → TeamMember.js} +0 -0
@@ -1,18 +1,19 @@
1
1
  import { __decorate, __metadata, __param } from "tslib";
2
- import { BadRequestException, Inject, Injectable, NotFoundException, } from '@nestjs/common';
2
+ import { BadRequestException, ConflictException, Inject, Injectable, NotFoundException, } from '@nestjs/common';
3
3
  import { KOSHA_CONFIG } from '../config/tokens.js';
4
4
  import { CryptoService } from '../crypto/crypto.service.js';
5
+ import { EnvironmentsService } from '../environments/environments.service.js';
5
6
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
6
- import { PrismaService } from '../prisma/prisma.service.js';
7
- /** Never selected over the REST API. */
8
- const PUBLIC_OMIT = { encryptedClientSecret: true };
7
+ import { ConfigurationsRepository } from './configurations.repository.js';
9
8
  let ConfigurationsService = class ConfigurationsService {
10
- prisma;
9
+ configurations;
10
+ environments;
11
11
  crypto;
12
12
  registry;
13
13
  config;
14
- constructor(prisma, crypto, registry, config) {
15
- this.prisma = prisma;
14
+ constructor(configurations, environments, crypto, registry, config) {
15
+ this.configurations = configurations;
16
+ this.environments = environments;
16
17
  this.crypto = crypto;
17
18
  this.registry = registry;
18
19
  this.config = config;
@@ -22,138 +23,133 @@ let ConfigurationsService = class ConfigurationsService {
22
23
  * `server.publicUrl` so it is stable and inspectable in the admin, rather
23
24
  * than being reconstructed per request.
24
25
  */
25
- callbackUrlFor(providerKey) {
26
+ callbackUrlFor(integrationKey) {
26
27
  const { publicUrl, globalPrefix } = this.config.server;
27
- return `${publicUrl}/${globalPrefix}/connect/callback/${providerKey}`;
28
+ return `${publicUrl}/${globalPrefix}/connect/callback/${integrationKey}`;
28
29
  }
29
- list(organizationId) {
30
- return this.prisma.configuration.findMany({
31
- where: { organizationId },
32
- include: { provider: true },
33
- omit: PUBLIC_OMIT,
34
- orderBy: { createdAt: 'desc' },
35
- });
30
+ async list(organizationId, userId, environmentId) {
31
+ await this.environments.getForMember(organizationId, userId, environmentId);
32
+ return this.configurations.findManyByEnvironment(environmentId);
36
33
  }
37
- async get(organizationId, id) {
38
- const configuration = await this.prisma.configuration.findFirst({
39
- where: { id, organizationId },
40
- include: { provider: true },
41
- omit: PUBLIC_OMIT,
42
- });
43
- if (!configuration) {
34
+ async get(organizationId, userId, environmentId, id) {
35
+ await this.environments.getForMember(organizationId, userId, environmentId);
36
+ const configuration = await this.configurations.findById(environmentId, id);
37
+ if (!configuration)
44
38
  throw new NotFoundException('Configuration not found');
45
- }
46
39
  return configuration;
47
40
  }
48
- async create(organizationId, input) {
49
- if (!input?.name?.trim()) {
50
- throw new BadRequestException('name is required');
51
- }
52
- if (!input.clientId?.trim() || !input.clientSecret?.trim()) {
53
- throw new BadRequestException('clientId and clientSecret are required');
54
- }
55
- // The registry is the authority on what Kosha can talk to; a provider row
56
- // may linger after its package was uninstalled.
57
- const integration = this.registry.get(input.provider);
58
- const provider = await this.prisma.provider.findUnique({
59
- where: { key: integration.key },
60
- });
61
- if (!provider) {
62
- throw new BadRequestException(`Provider "${input.provider}" has not been synced yet. Restart the server.`);
63
- }
64
- const scopes = this.validateScopes(input.provider, input.scopes ?? []);
65
- const settings = this.validateSettings(input.provider, input.settings);
66
- const slug = slugify(input.slug ?? input.name);
41
+ /** How a caller's slug resolves, once a key has named the environment. */
42
+ async getBySlug(environmentId, slug) {
43
+ const configuration = await this.configurations.findBySlug(environmentId, slug);
44
+ if (!configuration)
45
+ throw new NotFoundException('Configuration not found');
46
+ return configuration;
47
+ }
48
+ async create(organizationId, userId, environmentId, input) {
49
+ await this.environments.getForMember(organizationId, userId, environmentId);
50
+ // The registry is the authority on what Kosha can talk to, and on which
51
+ // auth type this integration uses. There is no provider table to consult.
52
+ const integration = this.registry.get(input.integrationKey);
53
+ const name = input.name.trim();
54
+ const slug = slugify(input.slug ?? name);
67
55
  if (!slug) {
68
56
  throw new BadRequestException('slug must contain at least one letter or digit');
69
57
  }
70
- return this.prisma.configuration.create({
71
- data: {
72
- organizationId,
73
- providerId: provider.id,
74
- name: input.name.trim(),
75
- slug,
76
- authType: provider.authType,
77
- environment: input.environment ?? 'LIVE',
78
- clientId: input.clientId,
79
- encryptedClientSecret: this.crypto.encrypt(input.clientSecret),
80
- redirectUri: this.callbackUrlFor(provider.key),
81
- scopes,
82
- metadata: toJsonInput(settings),
83
- },
84
- include: { provider: true },
85
- omit: PUBLIC_OMIT,
58
+ if (await this.configurations.findBySlug(environmentId, slug)) {
59
+ throw new ConflictException(`A configuration with slug "${slug}" already exists in this environment`);
60
+ }
61
+ const settings = this.validateSettings(input.integrationKey, input.settings);
62
+ return this.configurations.create({
63
+ environmentId,
64
+ integrationKey: integration.key,
65
+ authType: integration.auth.type,
66
+ name,
67
+ slug,
68
+ credentials: this.sealCredentials(input.integrationKey, input.credentials),
69
+ settings: toJsonInput(settings),
86
70
  });
87
71
  }
88
- async update(organizationId, id, input) {
89
- const existing = await this.get(organizationId, id);
90
- return this.prisma.configuration.update({
91
- where: { id },
92
- data: {
93
- name: input.name?.trim(),
94
- scopes: input.scopes
95
- ? this.validateScopes(existing.provider.key, input.scopes)
96
- : undefined,
97
- clientId: input.clientId,
98
- encryptedClientSecret: input.clientSecret
99
- ? this.crypto.encrypt(input.clientSecret)
100
- : undefined,
101
- isEnabled: input.isEnabled,
102
- metadata: input.settings
103
- ? toJsonInput(this.validateSettings(existing.provider.key, input.settings))
104
- : undefined,
105
- },
106
- include: { provider: true },
107
- omit: PUBLIC_OMIT,
72
+ async update(organizationId, userId, environmentId, id, input) {
73
+ const existing = await this.get(organizationId, userId, environmentId, id);
74
+ return this.configurations.update(id, {
75
+ name: input.name?.trim(),
76
+ credentials: input.credentials
77
+ ? this.sealCredentials(existing.integrationKey, input.credentials)
78
+ : undefined,
79
+ settings: input.settings
80
+ ? toJsonInput(this.validateSettings(existing.integrationKey, input.settings))
81
+ : undefined,
82
+ isEnabled: input.isEnabled,
108
83
  });
109
84
  }
110
- async remove(organizationId, id) {
111
- await this.get(organizationId, id);
112
- await this.prisma.configuration.delete({ where: { id } });
85
+ /**
86
+ * Refused while credentials still point at this row. `account.providerId` is
87
+ * a plain string, so nothing in the database would stop the delete from
88
+ * orphaning them.
89
+ */
90
+ async remove(organizationId, userId, environmentId, id) {
91
+ await this.get(organizationId, userId, environmentId, id);
92
+ const credentials = await this.configurations.countCredentials(id);
93
+ if (credentials > 0) {
94
+ throw new ConflictException(`${credentials} connection(s) still use this configuration. Disconnect them first.`);
95
+ }
96
+ await this.configurations.delete(id);
113
97
  }
114
98
  /**
115
- * Includes the decrypted client secret, for the connect flow only. Never
99
+ * Opens the secret half, for the connect and proxy paths only. Never
116
100
  * reachable from a controller.
117
101
  */
118
- async getWithDecryptedSecret(configurationId) {
119
- const configuration = await this.prisma.configuration.findUnique({
120
- where: { id: configurationId },
121
- include: { provider: true },
122
- });
123
- if (!configuration) {
102
+ async getWithCredentials(configurationId) {
103
+ const configuration = await this.configurations.findAnyById(configurationId);
104
+ if (!configuration)
124
105
  throw new NotFoundException('Configuration not found');
125
- }
126
- if (!configuration.encryptedClientSecret) {
127
- throw new BadRequestException(`Configuration "${configuration.name}" has no client secret stored`);
128
- }
129
106
  return {
130
- ...configuration,
131
- clientSecret: this.crypto.decrypt(configuration.encryptedClientSecret),
107
+ configuration,
108
+ credentials: configuration.credentials
109
+ ? JSON.parse(this.crypto.decrypt(configuration.credentials))
110
+ : {},
132
111
  };
133
112
  }
134
- validateScopes(providerKey, scopes) {
135
- const available = new Set(this.registry.get(providerKey).auth.scopesAvailable);
136
- const unknown = scopes.filter((scope) => !available.has(scope));
137
- if (unknown.length > 0) {
138
- throw new BadRequestException(`Unknown scope(s) for ${providerKey}: ${unknown.join(', ')}. Available: ${[...available].join(', ')}`);
113
+ /**
114
+ * What the auth type needs, encrypted as one blob rather than a column per
115
+ * field — a GitHub App configuration holds an appId and a private key where
116
+ * an OAuth2 one holds a client id and secret, and neither should force a
117
+ * migration on the other.
118
+ */
119
+ sealCredentials(integrationKey, credentials) {
120
+ const integration = this.registry.get(integrationKey);
121
+ const provided = credentials ?? {};
122
+ if (integration.auth.type === 'OAUTH2') {
123
+ const missing = ['clientId', 'clientSecret'].filter((field) => typeof provided[field] !== 'string' || !provided[field]);
124
+ if (missing.length > 0) {
125
+ throw new BadRequestException(`${integrationKey} is an OAuth2 integration and needs ${missing.join(' and ')}`);
126
+ }
139
127
  }
140
- return [...new Set(scopes)];
128
+ if (Object.keys(provided).length === 0)
129
+ return null;
130
+ return this.crypto.encrypt(JSON.stringify(provided));
141
131
  }
142
132
  /**
143
133
  * Checks per-organization settings against the integration's declared
144
- * `configFields`. Integrations describe their settings as data so the admin
145
- * can render a form; the same description is what validates here.
134
+ * `configFields`, and any scopes against what the provider actually offers.
135
+ * Integrations describe their settings as data so the admin can render a
136
+ * form; the same description is what validates here.
146
137
  */
147
- validateSettings(providerKey, settings) {
148
- const fields = this.registry.get(providerKey).configFields ?? [];
138
+ validateSettings(integrationKey, settings) {
139
+ const integration = this.registry.get(integrationKey);
140
+ const fields = integration.configFields ?? [];
149
141
  if (!settings && fields.length === 0)
150
142
  return undefined;
151
- const provided = settings ?? {};
143
+ const provided = { ...(settings ?? {}) };
152
144
  const problems = [];
145
+ if ('scopes' in provided) {
146
+ provided['scopes'] = this.validateScopes(integrationKey, provided['scopes']);
147
+ }
153
148
  const known = new Map(fields.map((field) => [field.key, field]));
154
149
  for (const key of Object.keys(provided)) {
155
- if (!known.has(key))
150
+ if (key !== 'scopes' && !known.has(key)) {
156
151
  problems.push(`unknown setting "${key}"`);
152
+ }
157
153
  }
158
154
  for (const field of fields) {
159
155
  const value = provided[field.key];
@@ -165,15 +161,27 @@ let ConfigurationsService = class ConfigurationsService {
165
161
  problems.push(...describeTypeMismatch(field, value));
166
162
  }
167
163
  if (problems.length > 0) {
168
- throw new BadRequestException(`Invalid settings for ${providerKey}: ${problems.join('; ')}`);
164
+ throw new BadRequestException(`Invalid settings for ${integrationKey}: ${problems.join('; ')}`);
169
165
  }
170
166
  return provided;
171
167
  }
168
+ validateScopes(integrationKey, scopes) {
169
+ if (!Array.isArray(scopes) || scopes.some((s) => typeof s !== 'string')) {
170
+ throw new BadRequestException('scopes must be an array of strings');
171
+ }
172
+ const available = new Set(this.registry.get(integrationKey).auth.scopesAvailable);
173
+ const unknown = scopes.filter((scope) => !available.has(scope));
174
+ if (unknown.length > 0) {
175
+ throw new BadRequestException(`Unknown scope(s) for ${integrationKey}: ${unknown.join(', ')}. Available: ${[...available].join(', ')}`);
176
+ }
177
+ return [...new Set(scopes)];
178
+ }
172
179
  };
173
180
  ConfigurationsService = __decorate([
174
181
  Injectable(),
175
- __param(3, Inject(KOSHA_CONFIG)),
176
- __metadata("design:paramtypes", [PrismaService,
182
+ __param(4, Inject(KOSHA_CONFIG)),
183
+ __metadata("design:paramtypes", [ConfigurationsRepository,
184
+ EnvironmentsService,
177
185
  CryptoService,
178
186
  IntegrationRegistry, Object])
179
187
  ], ConfigurationsService);
@@ -0,0 +1,8 @@
1
+ export declare class CreateConfigurationDto {
2
+ integrationKey: string;
3
+ name: string;
4
+ slug?: string;
5
+ credentials?: Record<string, unknown>;
6
+ settings?: Record<string, unknown>;
7
+ }
8
+ //# sourceMappingURL=create-configuration.dto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-configuration.dto.d.ts","sourceRoot":"","sources":["../../../src/configurations/dto/create-configuration.dto.ts"],"names":[],"mappings":"AASA,qBAAa,sBAAsB;IAQjC,cAAc,EAAG,MAAM,CAAC;IAMxB,IAAI,EAAG,MAAM,CAAC;IAUd,IAAI,CAAC,EAAE,MAAM,CAAC;IASd,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAStC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC"}
@@ -0,0 +1,54 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
3
+ import { IsObject, IsOptional, IsString, MaxLength, MinLength, } from 'class-validator';
4
+ export class CreateConfigurationDto {
5
+ integrationKey;
6
+ name;
7
+ slug;
8
+ credentials;
9
+ settings;
10
+ }
11
+ __decorate([
12
+ ApiProperty({
13
+ example: 'github',
14
+ description: 'Key of an installed integration package. Validated against the registry.',
15
+ }),
16
+ IsString(),
17
+ MinLength(1),
18
+ __metadata("design:type", String)
19
+ ], CreateConfigurationDto.prototype, "integrationKey", void 0);
20
+ __decorate([
21
+ ApiProperty({ example: 'GitHub' }),
22
+ IsString(),
23
+ MinLength(1),
24
+ MaxLength(64),
25
+ __metadata("design:type", String)
26
+ ], CreateConfigurationDto.prototype, "name", void 0);
27
+ __decorate([
28
+ ApiPropertyOptional({
29
+ example: 'github',
30
+ description: 'Caller-facing handle, quoted on proxy calls. Derived from the name when omitted.',
31
+ }),
32
+ IsOptional(),
33
+ IsString(),
34
+ MaxLength(64),
35
+ __metadata("design:type", String)
36
+ ], CreateConfigurationDto.prototype, "slug", void 0);
37
+ __decorate([
38
+ ApiPropertyOptional({
39
+ description: 'Secret half, encrypted at rest. Shape is the auth type’s: an OAuth2 integration needs clientId and clientSecret.',
40
+ example: { clientId: 'Iv1.abc', clientSecret: '…' },
41
+ }),
42
+ IsOptional(),
43
+ IsObject(),
44
+ __metadata("design:type", Object)
45
+ ], CreateConfigurationDto.prototype, "credentials", void 0);
46
+ __decorate([
47
+ ApiPropertyOptional({
48
+ description: 'Non-secret half: scopes, and whatever the integration declares as configFields.',
49
+ example: { scopes: ['repo', 'read:user'] },
50
+ }),
51
+ IsOptional(),
52
+ IsObject(),
53
+ __metadata("design:type", Object)
54
+ ], CreateConfigurationDto.prototype, "settings", void 0);
@@ -0,0 +1,7 @@
1
+ export declare class UpdateConfigurationDto {
2
+ name?: string;
3
+ credentials?: Record<string, unknown>;
4
+ settings?: Record<string, unknown>;
5
+ isEnabled?: boolean;
6
+ }
7
+ //# sourceMappingURL=update-configuration.dto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-configuration.dto.d.ts","sourceRoot":"","sources":["../../../src/configurations/dto/update-configuration.dto.ts"],"names":[],"mappings":"AAUA,qBAAa,sBAAsB;IAMjC,IAAI,CAAC,EAAE,MAAM,CAAC;IAOd,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAKtC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAOnC,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB"}
@@ -0,0 +1,39 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { ApiPropertyOptional } from '@nestjs/swagger';
3
+ import { IsBoolean, IsObject, IsOptional, IsString, MaxLength, MinLength, } from 'class-validator';
4
+ export class UpdateConfigurationDto {
5
+ name;
6
+ credentials;
7
+ settings;
8
+ isEnabled;
9
+ }
10
+ __decorate([
11
+ ApiPropertyOptional({ example: 'GitHub' }),
12
+ IsOptional(),
13
+ IsString(),
14
+ MinLength(1),
15
+ MaxLength(64),
16
+ __metadata("design:type", String)
17
+ ], UpdateConfigurationDto.prototype, "name", void 0);
18
+ __decorate([
19
+ ApiPropertyOptional({
20
+ description: 'Replaces the stored secrets. Omit to leave them alone.',
21
+ }),
22
+ IsOptional(),
23
+ IsObject(),
24
+ __metadata("design:type", Object)
25
+ ], UpdateConfigurationDto.prototype, "credentials", void 0);
26
+ __decorate([
27
+ ApiPropertyOptional({ example: { scopes: ['repo'] } }),
28
+ IsOptional(),
29
+ IsObject(),
30
+ __metadata("design:type", Object)
31
+ ], UpdateConfigurationDto.prototype, "settings", void 0);
32
+ __decorate([
33
+ ApiPropertyOptional({
34
+ description: 'Disable without deleting; stored credentials stay put.',
35
+ }),
36
+ IsOptional(),
37
+ IsBoolean(),
38
+ __metadata("design:type", Boolean)
39
+ ], UpdateConfigurationDto.prototype, "isEnabled", void 0);
@@ -1,7 +1,9 @@
1
1
  import { type UserSession } from '@thallesp/nestjs-better-auth';
2
2
  import type { Response } from 'express';
3
3
  import { type ApiKeyRequest } from '../auth/api-key.guard.js';
4
- import { ConnectService, type CreateConnectSessionInput } from './connect.service.js';
4
+ import { ConnectService } from './connect.service.js';
5
+ import { CreateConnectSessionDto } from './dto/create-connect-session.dto.js';
6
+ import { CreateTestSessionDto } from './dto/create-test-session.dto.js';
5
7
  export declare class ConnectController {
6
8
  private readonly connect;
7
9
  private readonly logger;
@@ -12,20 +14,16 @@ export declare class ConnectController {
12
14
  * session. `AllowAnonymous` disables the session guard so `OrgAuthGuard`
13
15
  * can authenticate either way.
14
16
  */
15
- createSession(request: ApiKeyRequest, body: CreateConnectSessionInput): Promise<import("./connect.service.js").ConnectSessionResult>;
17
+ createSession(request: ApiKeyRequest, body: CreateConnectSessionDto): Promise<import("./connect.service.js").ConnectSessionResult>;
16
18
  /**
17
19
  * Admin-only: runs the same flow with the signed-in admin standing in for an
18
20
  * end user, so an operator can verify a configuration without wiring up
19
21
  * their backend first.
20
22
  */
21
- createTestSession(session: UserSession, body: {
22
- configurationId?: string;
23
- slug?: string;
24
- redirectUrl?: string;
25
- }): Promise<import("./connect.service.js").ConnectSessionResult>;
23
+ createTestSession(session: UserSession, environmentId: string, body: CreateTestSessionDto): Promise<import("./connect.service.js").ConnectSessionResult>;
26
24
  /** The URL the end user's browser opens. Redirects to the provider. */
27
25
  start(token: string, res: Response): Promise<void>;
28
26
  /** Where the provider sends the end user back. */
29
- callback(providerKey: string, code: string | undefined, state: string | undefined, providerError: string | undefined, providerErrorDescription: string | undefined, res: Response): Promise<void>;
27
+ callback(integrationKey: string, code: string | undefined, state: string | undefined, providerError: string | undefined, providerErrorDescription: string | undefined, res: Response): Promise<void>;
30
28
  }
31
29
  //# sourceMappingURL=connect.controller.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"connect.controller.d.ts","sourceRoot":"","sources":["../../src/connect/connect.controller.ts"],"names":[],"mappings":"AAaA,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,KAAK,aAAa,EAAgB,MAAM,0BAA0B,CAAC;AAE5E,OAAO,EACL,cAAc,EACd,KAAK,yBAAyB,EAC/B,MAAM,sBAAsB,CAAC;AAE9B,qBACa,iBAAiB;IAGhB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAFpC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsC;gBAEhC,OAAO,EAAE,cAAc;IAEpD;;;;;OAKG;IAIH,aAAa,CACJ,OAAO,EAAE,aAAa,EACrB,IAAI,EAAE,yBAAyB;IAKzC;;;;OAIG;IAEH,iBAAiB,CACJ,OAAO,EAAE,WAAW,EAE/B,IAAI,EAAE;QAAE,eAAe,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE;IAUzE,uEAAuE;IAGjE,KAAK,CAAiB,KAAK,EAAE,MAAM,EAAS,GAAG,EAAE,QAAQ;IAY/D,kDAAkD;IAG5C,QAAQ,CACU,WAAW,EAAE,MAAM,EAC1B,IAAI,EAAE,MAAM,GAAG,SAAS,EACvB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,aAAa,EAAE,MAAM,GAAG,SAAS,EACrB,wBAAwB,EAAE,MAAM,GAAG,SAAS,EACjE,GAAG,EAAE,QAAQ;CA+CvB"}
1
+ {"version":3,"file":"connect.controller.d.ts","sourceRoot":"","sources":["../../src/connect/connect.controller.ts"],"names":[],"mappings":"AAsBA,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,KAAK,aAAa,EAAgB,MAAM,0BAA0B,CAAC;AAE5E,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AAExE,qBAEa,iBAAiB;IAGhB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAFpC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsC;gBAEhC,OAAO,EAAE,cAAc;IAEpD;;;;;OAKG;IAcH,aAAa,CACJ,OAAO,EAAE,aAAa,EACrB,IAAI,EAAE,uBAAuB;IAevC;;;;OAIG;IAOH,iBAAiB,CACJ,OAAO,EAAE,WAAW,EACP,aAAa,EAAE,MAAM,EACrC,IAAI,EAAE,oBAAoB;IAcpC,uEAAuE;IAIjE,KAAK,CAAiB,KAAK,EAAE,MAAM,EAAS,GAAG,EAAE,QAAQ;IAY/D,kDAAkD;IAI5C,QAAQ,CACa,cAAc,EAAE,MAAM,EAChC,IAAI,EAAE,MAAM,GAAG,SAAS,EACvB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,aAAa,EAAE,MAAM,GAAG,SAAS,EACrB,wBAAwB,EAAE,MAAM,GAAG,SAAS,EACjE,GAAG,EAAE,QAAQ;CAuDvB"}
@@ -1,10 +1,13 @@
1
1
  var ConnectController_1;
2
2
  import { __decorate, __metadata, __param } from "tslib";
3
- import { BadRequestException, Body, Controller, Get, Logger, Param, Post, Query, Req, Res, UseGuards, } from '@nestjs/common';
3
+ import { BadRequestException, ConflictException, Body, Controller, Get, Logger, Param, Post, Query, Req, Res, UseGuards, } from '@nestjs/common';
4
+ import { ApiBadRequestResponse, ApiCreatedResponse, ApiExcludeEndpoint, ApiOperation, ApiSecurity, ApiTags, } from '@nestjs/swagger';
4
5
  import { AllowAnonymous, Session, } from '@thallesp/nestjs-better-auth';
5
6
  import { OrgAuthGuard } from '../auth/api-key.guard.js';
6
7
  import { getActiveOrganizationId } from '../common/active-organization.js';
7
- import { ConnectService, } from './connect.service.js';
8
+ import { ConnectService } from './connect.service.js';
9
+ import { CreateConnectSessionDto } from './dto/create-connect-session.dto.js';
10
+ import { CreateTestSessionDto } from './dto/create-test-session.dto.js';
8
11
  let ConnectController = ConnectController_1 = class ConnectController {
9
12
  connect;
10
13
  logger = new Logger(ConnectController_1.name);
@@ -18,16 +21,19 @@ let ConnectController = ConnectController_1 = class ConnectController {
18
21
  * can authenticate either way.
19
22
  */
20
23
  createSession(request, body) {
21
- return this.connect.createSession(request.organizationId, body);
24
+ if (!request.environmentId) {
25
+ throw new BadRequestException('This route needs an API key, which is what names the environment');
26
+ }
27
+ return this.connect.createSession(request.organizationId, request.environmentId, body);
22
28
  }
23
29
  /**
24
30
  * Admin-only: runs the same flow with the signed-in admin standing in for an
25
31
  * end user, so an operator can verify a configuration without wiring up
26
32
  * their backend first.
27
33
  */
28
- createTestSession(session, body) {
29
- return this.connect.createSession(getActiveOrganizationId(session), {
30
- endUserExternalId: `kosha-admin:${session.user.id}`,
34
+ createTestSession(session, environmentId, body) {
35
+ return this.connect.createSession(getActiveOrganizationId(session), environmentId, {
36
+ externalUserId: `kosha-admin:${session.user.id}`,
31
37
  configurationId: body?.configurationId,
32
38
  configurationSlug: body?.slug,
33
39
  redirectUrl: body?.redirectUrl,
@@ -45,7 +51,7 @@ let ConnectController = ConnectController_1 = class ConnectController {
45
51
  }
46
52
  }
47
53
  /** Where the provider sends the end user back. */
48
- async callback(providerKey, code, state, providerError, providerErrorDescription, res) {
54
+ async callback(integrationKey, code, state, providerError, providerErrorDescription, res) {
49
55
  if (providerError || providerErrorDescription) {
50
56
  res
51
57
  .status(400)
@@ -59,7 +65,7 @@ let ConnectController = ConnectController_1 = class ConnectController {
59
65
  return;
60
66
  }
61
67
  try {
62
- const { redirectUrl } = await this.connect.handleCallback(providerKey, code, state);
68
+ const { redirectUrl } = await this.connect.handleCallback(integrationKey, code, state);
63
69
  if (redirectUrl) {
64
70
  const url = new URL(redirectUrl);
65
71
  url.searchParams.set('kosha_status', 'success');
@@ -69,7 +75,14 @@ let ConnectController = ConnectController_1 = class ConnectController {
69
75
  res.send('Connected. You can close this window.');
70
76
  }
71
77
  catch (error) {
72
- this.logger.warn(`Connect callback failed for "${providerKey}": ${error instanceof Error ? error.message : error}`);
78
+ this.logger.warn(`Connect callback failed for "${integrationKey}": ${error instanceof Error ? error.message : error}`);
79
+ // A conflict is worth saying out loud: somebody is already connected,
80
+ // and the end user can do something about it. Everything else stays
81
+ // vague, since this URL is reached by a browser we do not trust.
82
+ if (error instanceof ConflictException) {
83
+ res.status(409).send(error.message);
84
+ return;
85
+ }
73
86
  res
74
87
  .status(400)
75
88
  .send(error instanceof BadRequestException
@@ -82,23 +95,38 @@ __decorate([
82
95
  Post('sessions'),
83
96
  AllowAnonymous(),
84
97
  UseGuards(OrgAuthGuard),
98
+ ApiSecurity('x-api-key'),
99
+ ApiOperation({
100
+ summary: 'Start a connect flow for one of the app’s users',
101
+ description: 'The environment comes from the API key. Set organizationExternalId when the credential belongs to a tenant rather than to the person.',
102
+ }),
103
+ ApiCreatedResponse({ description: 'A connect URL and when it expires.' }),
104
+ ApiBadRequestResponse({
105
+ description: 'Unknown configuration, or no environment on the key.',
106
+ }),
85
107
  __param(0, Req()),
86
108
  __param(1, Body()),
87
109
  __metadata("design:type", Function),
88
- __metadata("design:paramtypes", [Object, Object]),
110
+ __metadata("design:paramtypes", [Object, CreateConnectSessionDto]),
89
111
  __metadata("design:returntype", void 0)
90
112
  ], ConnectController.prototype, "createSession", null);
91
113
  __decorate([
92
- Post('sessions/test'),
114
+ Post('sessions/test/:environmentId'),
115
+ ApiOperation({
116
+ summary: 'Run the same flow as the signed-in admin',
117
+ description: 'For verifying a configuration before the consuming app is wired up.',
118
+ }),
93
119
  __param(0, Session()),
94
- __param(1, Body()),
120
+ __param(1, Param('environmentId')),
121
+ __param(2, Body()),
95
122
  __metadata("design:type", Function),
96
- __metadata("design:paramtypes", [Object, Object]),
123
+ __metadata("design:paramtypes", [Object, String, CreateTestSessionDto]),
97
124
  __metadata("design:returntype", void 0)
98
125
  ], ConnectController.prototype, "createTestSession", null);
99
126
  __decorate([
100
127
  Get(':token/start'),
101
128
  AllowAnonymous(),
129
+ ApiExcludeEndpoint(),
102
130
  __param(0, Param('token')),
103
131
  __param(1, Res()),
104
132
  __metadata("design:type", Function),
@@ -106,9 +134,10 @@ __decorate([
106
134
  __metadata("design:returntype", Promise)
107
135
  ], ConnectController.prototype, "start", null);
108
136
  __decorate([
109
- Get('callback/:providerKey'),
137
+ Get('callback/:integrationKey'),
110
138
  AllowAnonymous(),
111
- __param(0, Param('providerKey')),
139
+ ApiExcludeEndpoint(),
140
+ __param(0, Param('integrationKey')),
112
141
  __param(1, Query('code')),
113
142
  __param(2, Query('state')),
114
143
  __param(3, Query('error')),
@@ -119,6 +148,7 @@ __decorate([
119
148
  __metadata("design:returntype", Promise)
120
149
  ], ConnectController.prototype, "callback", null);
121
150
  ConnectController = ConnectController_1 = __decorate([
151
+ ApiTags('connect'),
122
152
  Controller('connect'),
123
153
  __metadata("design:paramtypes", [ConnectService])
124
154
  ], ConnectController);
@@ -1 +1 @@
1
- {"version":3,"file":"connect.module.d.ts","sourceRoot":"","sources":["../../src/connect/connect.module.ts"],"names":[],"mappings":"AAKA,qBAMa,aAAa;CAAG"}
1
+ {"version":3,"file":"connect.module.d.ts","sourceRoot":"","sources":["../../src/connect/connect.module.ts"],"names":[],"mappings":"AAOA,qBAMa,aAAa;CAAG"}
@@ -1,15 +1,17 @@
1
1
  import { __decorate } from "tslib";
2
2
  import { Module } from '@nestjs/common';
3
3
  import { ConfigurationsModule } from '../configurations/configurations.module.js';
4
+ import { EnvironmentsModule } from '../environments/environments.module.js';
4
5
  import { ConnectController } from './connect.controller.js';
6
+ import { ConnectRepository } from './connect.repository.js';
5
7
  import { ConnectService } from './connect.service.js';
6
8
  let ConnectModule = class ConnectModule {
7
9
  };
8
10
  ConnectModule = __decorate([
9
11
  Module({
10
- imports: [ConfigurationsModule],
12
+ imports: [ConfigurationsModule, EnvironmentsModule],
11
13
  controllers: [ConnectController],
12
- providers: [ConnectService],
14
+ providers: [ConnectService, ConnectRepository],
13
15
  exports: [ConnectService],
14
16
  })
15
17
  ], ConnectModule);