@kosha-ai/server 0.1.0 → 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 (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
@@ -2,10 +2,11 @@ var GrantsService_1;
2
2
  import { __decorate, __metadata } from "tslib";
3
3
  import { BadRequestException, Injectable, Logger, NotFoundException, } from '@nestjs/common';
4
4
  import { createHash, randomBytes } from 'node:crypto';
5
- import { CaService } from './ca.service.js';
6
5
  import { CryptoService } from '../crypto/crypto.service.js';
6
+ import { EnvironmentsService } from '../environments/environments.service.js';
7
+ import { CaService } from './ca.service.js';
8
+ import { EgressRepository, } from './egress.repository.js';
7
9
  import { HostRulesService } from './host-rules.service.js';
8
- import { PrismaService } from '../prisma/prisma.service.js';
9
10
  /** A ceiling, not a policy: callers pick their own expiry from a task budget. */
10
11
  const MAX_LIFETIME_MS = 25 * 60 * 60_000;
11
12
  const MAX_LABEL_LENGTH = 200;
@@ -14,18 +15,21 @@ const MAX_LABEL_LENGTH = 200;
14
15
  * every CONNECT, and a git clone makes a great many of those.
15
16
  */
16
17
  const CACHE_MS = 30_000;
18
+ const PRUNE_AFTER_MS = 7 * 24 * 60 * 60_000;
17
19
  let GrantsService = GrantsService_1 = class GrantsService {
18
- prisma;
20
+ grants;
19
21
  crypto;
20
22
  ca;
21
23
  hostRules;
24
+ environments;
22
25
  logger = new Logger(GrantsService_1.name);
23
26
  cache = new Map();
24
- constructor(prisma, crypto, ca, hostRules) {
25
- this.prisma = prisma;
27
+ constructor(grants, crypto, ca, hostRules, environments) {
28
+ this.grants = grants;
26
29
  this.crypto = crypto;
27
30
  this.ca = ca;
28
31
  this.hostRules = hostRules;
32
+ this.environments = environments;
29
33
  }
30
34
  /**
31
35
  * Unsalted on purpose: the token is 32 random bytes, so there is nothing to
@@ -35,10 +39,10 @@ let GrantsService = GrantsService_1 = class GrantsService {
35
39
  hashToken(token) {
36
40
  return createHash('sha256').update(token).digest('hex');
37
41
  }
38
- async mint(organizationId, input) {
39
- const externalId = input.endUserExternalId?.trim();
40
- if (!externalId) {
41
- throw new BadRequestException('endUserExternalId is required');
42
+ async mint(organizationId, environmentId, input) {
43
+ const externalUserId = input.externalUserId?.trim();
44
+ if (!externalUserId) {
45
+ throw new BadRequestException('externalUserId is required');
42
46
  }
43
47
  const lifetime = input.expiresAt.getTime() - Date.now();
44
48
  if (Number.isNaN(lifetime)) {
@@ -50,50 +54,28 @@ let GrantsService = GrantsService_1 = class GrantsService {
50
54
  if (lifetime > MAX_LIFETIME_MS) {
51
55
  throw new BadRequestException('expiresAt is more than 25h away');
52
56
  }
53
- const endUser = await this.prisma.endUser.findFirst({
54
- where: { organizationId, externalId },
55
- select: { id: true },
56
- });
57
- if (!endUser) {
58
- throw new NotFoundException(`No end user "${externalId}" in this organization. They have to connect a provider before a sandbox can borrow one.`);
57
+ const environment = await this.environments.get(organizationId, environmentId);
58
+ const user = await this.grants.findEndUser(environment.slug, externalUserId);
59
+ if (!user) {
60
+ throw new NotFoundException(`No end user "${externalUserId}" in this environment. They have to connect a provider before a sandbox can borrow one.`);
59
61
  }
60
62
  // Narrowing only. An unknown key resolves to nothing, same as the person
61
63
  // not having connected it.
62
64
  const providerKeys = (input.providerKeys ?? []).map((key) => key.trim());
63
65
  const authority = this.ca.createCertificateAuthority();
64
66
  const token = randomBytes(32).toString('base64url');
65
- const grant = await this.prisma.egressGrant.create({
66
- data: {
67
- organizationId,
68
- endUserId: endUser.id,
69
- tokenHash: this.hashToken(token),
70
- providerKeys,
71
- caPem: authority.certPem,
72
- caKey: this.crypto.encrypt(authority.keyPem),
73
- label: input.label?.slice(0, MAX_LABEL_LENGTH),
74
- expiresAt: input.expiresAt,
75
- },
76
- select: { id: true, expiresAt: true },
77
- });
78
- const providers = await this.providersFor({
79
- endUserId: endUser.id,
67
+ const grant = await this.grants.createGrant({
80
68
  organizationId,
69
+ userId: user.id,
70
+ tokenHash: this.hashToken(token),
81
71
  providerKeys,
72
+ caPem: authority.certPem,
73
+ caKey: this.crypto.encrypt(authority.keyPem),
74
+ label: input.label?.slice(0, MAX_LABEL_LENGTH),
75
+ expiresAt: input.expiresAt,
82
76
  });
83
- // Once here rather than per brokered request: a clone makes dozens, and
84
- // "last used" does not need that resolution.
85
- if (providers.length > 0) {
86
- await this.prisma.connection.updateMany({
87
- where: {
88
- organizationId,
89
- endUserId: endUser.id,
90
- status: 'ACTIVE',
91
- configuration: { provider: { key: { in: providers } } },
92
- },
93
- data: { lastUsedAt: new Date() },
94
- });
95
- }
96
- this.logger.log(`Minted egress grant ${grant.id} for end user ${externalId}` +
77
+ const providers = await this.providersFor(user.id, providerKeys);
78
+ this.logger.log(`Minted egress grant ${grant.id} for ${externalUserId} in ${environment.slug}` +
97
79
  ` (${providers.join(', ') || 'no connected provider'}), expires ${grant.expiresAt.toISOString()}`);
98
80
  return {
99
81
  caPem: authority.certPem,
@@ -104,10 +86,7 @@ let GrantsService = GrantsService_1 = class GrantsService {
104
86
  };
105
87
  }
106
88
  async revoke(organizationId, grantId) {
107
- const { count } = await this.prisma.egressGrant.updateMany({
108
- where: { id: grantId, organizationId, revokedAt: null },
109
- data: { revokedAt: new Date() },
110
- });
89
+ const count = await this.grants.revokeGrant(organizationId, grantId);
111
90
  this.forget(grantId);
112
91
  this.ca.forgetLeaves(grantId);
113
92
  this.logger.log(`Revoked egress grant ${grantId} (found: ${count > 0})`);
@@ -124,61 +103,36 @@ let GrantsService = GrantsService_1 = class GrantsService {
124
103
  const hit = this.cache.get(key);
125
104
  if (hit !== undefined && Date.now() - hit.at < CACHE_MS)
126
105
  return hit.grant;
127
- const row = await this.prisma.egressGrant.findFirst({
128
- where: { tokenHash: key, revokedAt: null, expiresAt: { gt: new Date() } },
129
- select: {
130
- id: true,
131
- organizationId: true,
132
- endUserId: true,
133
- providerKeys: true,
134
- caPem: true,
135
- caKey: true,
136
- expiresAt: true,
137
- },
138
- });
106
+ const row = await this.grants.findLiveGrant(key);
139
107
  const grant = row === null
140
108
  ? null
141
109
  : {
142
110
  caKeyPem: this.crypto.decrypt(row.caKey),
143
111
  caPem: row.caPem,
144
- endUserId: row.endUserId,
145
112
  expiresAt: row.expiresAt,
146
113
  id: row.id,
147
114
  organizationId: row.organizationId,
148
115
  providerKeys: row.providerKeys,
116
+ userId: row.userId,
149
117
  };
150
118
  this.cache.set(key, { at: Date.now(), grant });
151
119
  return grant;
152
120
  }
153
121
  /**
154
- * The active connection this grant may use for a provider, or null. Scoped by
155
- * organization and end user, never by an id in a request -- that is what
156
- * stops one grant reaching another tenant's credential.
122
+ * The credential this grant may borrow for one integration, or null. Scoped
123
+ * by the grant's own user, never by an id in a request -- that is what stops
124
+ * one grant reaching another tenant's credential.
157
125
  */
158
- async connectionFor(grant, providerKey) {
126
+ async credentialFor(grant, integrationKey) {
159
127
  if (grant.providerKeys.length > 0 &&
160
- !grant.providerKeys.includes(providerKey)) {
128
+ !grant.providerKeys.includes(integrationKey)) {
161
129
  return null;
162
130
  }
163
- return this.prisma.connection.findFirst({
164
- where: {
165
- organizationId: grant.organizationId,
166
- endUserId: grant.endUserId,
167
- status: 'ACTIVE',
168
- configuration: { provider: { key: providerKey } },
169
- },
170
- include: {
171
- configuration: { include: { provider: true } },
172
- credential: true,
173
- },
174
- });
131
+ return this.grants.findCredentialFor(grant.userId, integrationKey);
175
132
  }
176
133
  /** Deletes grants that expired a while ago. Housekeeping, nothing depends on it. */
177
- async pruneExpired() {
178
- const { count } = await this.prisma.egressGrant.deleteMany({
179
- where: { expiresAt: { lt: new Date(Date.now() - 7 * 24 * 60 * 60_000) } },
180
- });
181
- return count;
134
+ pruneExpired() {
135
+ return this.grants.deleteExpiredBefore(new Date(Date.now() - PRUNE_AFTER_MS));
182
136
  }
183
137
  forget(grantId) {
184
138
  for (const [key, entry] of this.cache) {
@@ -186,34 +140,20 @@ let GrantsService = GrantsService_1 = class GrantsService {
186
140
  this.cache.delete(key);
187
141
  }
188
142
  }
189
- /** Which brokered providers this end user has actually connected. */
190
- async providersFor(scope) {
143
+ /** Which brokered providers this person has actually connected. */
144
+ async providersFor(userId, providerKeys) {
191
145
  const candidates = this.hostRules
192
146
  .brokeredProviderKeys()
193
- .filter((key) => scope.providerKeys.length === 0 || scope.providerKeys.includes(key));
194
- if (candidates.length === 0)
195
- return [];
196
- const connections = await this.prisma.connection.findMany({
197
- where: {
198
- organizationId: scope.organizationId,
199
- endUserId: scope.endUserId,
200
- status: 'ACTIVE',
201
- configuration: { provider: { key: { in: candidates } } },
202
- },
203
- select: {
204
- configuration: { select: { provider: { select: { key: true } } } },
205
- },
206
- });
207
- return [
208
- ...new Set(connections.map((row) => row.configuration.provider.key)),
209
- ];
147
+ .filter((key) => providerKeys.length === 0 || providerKeys.includes(key));
148
+ return this.grants.connectedIntegrationKeys(userId, candidates);
210
149
  }
211
150
  };
212
151
  GrantsService = GrantsService_1 = __decorate([
213
152
  Injectable(),
214
- __metadata("design:paramtypes", [PrismaService,
153
+ __metadata("design:paramtypes", [EgressRepository,
215
154
  CryptoService,
216
155
  CaService,
217
- HostRulesService])
156
+ HostRulesService,
157
+ EnvironmentsService])
218
158
  ], GrantsService);
219
159
  export { GrantsService };
@@ -0,0 +1,6 @@
1
+ export declare class CreateEnvironmentDto {
2
+ name: string;
3
+ slug?: string;
4
+ teamId?: string | null;
5
+ }
6
+ //# sourceMappingURL=create-environment.dto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-environment.dto.d.ts","sourceRoot":"","sources":["../../../src/environments/dto/create-environment.dto.ts"],"names":[],"mappings":"AAGA,qBAAa,oBAAoB;IAK/B,IAAI,EAAG,MAAM,CAAC;IASd,IAAI,CAAC,EAAE,MAAM,CAAC;IASd,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB"}
@@ -0,0 +1,34 @@
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 CreateEnvironmentDto {
5
+ name;
6
+ slug;
7
+ teamId;
8
+ }
9
+ __decorate([
10
+ ApiProperty({ example: 'Production' }),
11
+ IsString(),
12
+ MinLength(1),
13
+ MaxLength(64),
14
+ __metadata("design:type", String)
15
+ ], CreateEnvironmentDto.prototype, "name", void 0);
16
+ __decorate([
17
+ ApiPropertyOptional({
18
+ example: 'production',
19
+ description: 'Caller-facing handle. Derived from the name when omitted.',
20
+ }),
21
+ IsOptional(),
22
+ IsString(),
23
+ MaxLength(64),
24
+ __metadata("design:type", String)
25
+ ], CreateEnvironmentDto.prototype, "slug", void 0);
26
+ __decorate([
27
+ ApiPropertyOptional({
28
+ description: 'Restricts access to members of this team. Omit to leave the environment open to every member of the organization.',
29
+ nullable: true,
30
+ }),
31
+ IsOptional(),
32
+ IsString(),
33
+ __metadata("design:type", Object)
34
+ ], CreateEnvironmentDto.prototype, "teamId", void 0);
@@ -0,0 +1,5 @@
1
+ export declare class UpdateEnvironmentDto {
2
+ name?: string;
3
+ teamId?: string | null;
4
+ }
5
+ //# sourceMappingURL=update-environment.dto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-environment.dto.d.ts","sourceRoot":"","sources":["../../../src/environments/dto/update-environment.dto.ts"],"names":[],"mappings":"AAGA,qBAAa,oBAAoB;IAM/B,IAAI,CAAC,EAAE,MAAM,CAAC;IASd,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB"}
@@ -0,0 +1,24 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { ApiPropertyOptional } from '@nestjs/swagger';
3
+ import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
4
+ export class UpdateEnvironmentDto {
5
+ name;
6
+ teamId;
7
+ }
8
+ __decorate([
9
+ ApiPropertyOptional({ example: 'Production' }),
10
+ IsOptional(),
11
+ IsString(),
12
+ MinLength(1),
13
+ MaxLength(64),
14
+ __metadata("design:type", String)
15
+ ], UpdateEnvironmentDto.prototype, "name", void 0);
16
+ __decorate([
17
+ ApiPropertyOptional({
18
+ description: 'Restricts access to members of this team. Null opens the environment to every member of the organization.',
19
+ nullable: true,
20
+ }),
21
+ IsOptional(),
22
+ IsString(),
23
+ __metadata("design:type", Object)
24
+ ], UpdateEnvironmentDto.prototype, "teamId", void 0);
@@ -0,0 +1,53 @@
1
+ import { type UserSession } from '@thallesp/nestjs-better-auth';
2
+ import { CreateEnvironmentDto } from './dto/create-environment.dto.js';
3
+ import { UpdateEnvironmentDto } from './dto/update-environment.dto.js';
4
+ import { EnvironmentsService } from './environments.service.js';
5
+ /**
6
+ * Admin-facing. Session authenticated and scoped to the caller's active
7
+ * organization — never accepts an organizationId from the request.
8
+ */
9
+ export declare class EnvironmentsController {
10
+ private readonly environments;
11
+ constructor(environments: EnvironmentsService);
12
+ list(session: UserSession): Promise<{
13
+ name: string;
14
+ id: string;
15
+ createdAt: Date;
16
+ updatedAt: Date;
17
+ slug: string;
18
+ teamId: string | null;
19
+ organizationId: string;
20
+ }[]>;
21
+ get(session: UserSession, id: string): Promise<{
22
+ name: string;
23
+ id: string;
24
+ createdAt: Date;
25
+ updatedAt: Date;
26
+ slug: string;
27
+ teamId: string | null;
28
+ organizationId: string;
29
+ }>;
30
+ create(session: UserSession, body: CreateEnvironmentDto): Promise<{
31
+ name: string;
32
+ id: string;
33
+ createdAt: Date;
34
+ updatedAt: Date;
35
+ slug: string;
36
+ teamId: string | null;
37
+ organizationId: string;
38
+ }>;
39
+ update(session: UserSession, id: string, body: UpdateEnvironmentDto): Promise<{
40
+ name: string;
41
+ id: string;
42
+ createdAt: Date;
43
+ updatedAt: Date;
44
+ slug: string;
45
+ teamId: string | null;
46
+ organizationId: string;
47
+ }>;
48
+ remove(session: UserSession, id: string): Promise<{
49
+ id: string;
50
+ deleted: boolean;
51
+ }>;
52
+ }
53
+ //# sourceMappingURL=environments.controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environments.controller.d.ts","sourceRoot":"","sources":["../../src/environments/environments.controller.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAW,KAAK,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAEzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE;;;GAGG;AACH,qBAEa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,YAAY;gBAAZ,YAAY,EAAE,mBAAmB;IAS9D,IAAI,CAAY,OAAO,EAAE,WAAW;;;;;;;;;IAYpC,GAAG,CAAY,OAAO,EAAE,WAAW,EAAe,EAAE,EAAE,MAAM;;;;;;;;;IAY5D,MAAM,CAAY,OAAO,EAAE,WAAW,EAAU,IAAI,EAAE,oBAAoB;;;;;;;;;IAS1E,MAAM,CACO,OAAO,EAAE,WAAW,EAClB,EAAE,EAAE,MAAM,EACf,IAAI,EAAE,oBAAoB;;;;;;;;;IAiB9B,MAAM,CAAY,OAAO,EAAE,WAAW,EAAe,EAAE,EAAE,MAAM;;;;CAQtE"}
@@ -0,0 +1,101 @@
1
+ import { __decorate, __metadata, __param } from "tslib";
2
+ import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Patch, Post, } from '@nestjs/common';
3
+ import { ApiCreatedResponse, ApiNotFoundResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger';
4
+ import { Session } from '@thallesp/nestjs-better-auth';
5
+ import { getActiveOrganizationId } from '../common/active-organization.js';
6
+ import { CreateEnvironmentDto } from './dto/create-environment.dto.js';
7
+ import { UpdateEnvironmentDto } from './dto/update-environment.dto.js';
8
+ import { EnvironmentsService } from './environments.service.js';
9
+ /**
10
+ * Admin-facing. Session authenticated and scoped to the caller's active
11
+ * organization — never accepts an organizationId from the request.
12
+ */
13
+ let EnvironmentsController = class EnvironmentsController {
14
+ environments;
15
+ constructor(environments) {
16
+ this.environments = environments;
17
+ }
18
+ list(session) {
19
+ return this.environments.listFor(getActiveOrganizationId(session), session.user.id);
20
+ }
21
+ get(session, id) {
22
+ return this.environments.getForMember(getActiveOrganizationId(session), session.user.id, id);
23
+ }
24
+ create(session, body) {
25
+ return this.environments.create(getActiveOrganizationId(session), body);
26
+ }
27
+ update(session, id, body) {
28
+ return this.environments.update(getActiveOrganizationId(session), session.user.id, id, body);
29
+ }
30
+ async remove(session, id) {
31
+ await this.environments.remove(getActiveOrganizationId(session), session.user.id, id);
32
+ return { id, deleted: true };
33
+ }
34
+ };
35
+ __decorate([
36
+ Get(),
37
+ ApiOperation({
38
+ summary: 'List the environments this member can reach',
39
+ description: 'An environment with no team is open to every member of the organization; one with a team is visible only to that team.',
40
+ }),
41
+ ApiOkResponse({ description: 'Environments, oldest first.' }),
42
+ __param(0, Session()),
43
+ __metadata("design:type", Function),
44
+ __metadata("design:paramtypes", [Object]),
45
+ __metadata("design:returntype", void 0)
46
+ ], EnvironmentsController.prototype, "list", null);
47
+ __decorate([
48
+ Get(':id'),
49
+ ApiOperation({ summary: 'Get one environment' }),
50
+ ApiNotFoundResponse({
51
+ description: 'No such environment in this organization.',
52
+ }),
53
+ __param(0, Session()),
54
+ __param(1, Param('id')),
55
+ __metadata("design:type", Function),
56
+ __metadata("design:paramtypes", [Object, String]),
57
+ __metadata("design:returntype", void 0)
58
+ ], EnvironmentsController.prototype, "get", null);
59
+ __decorate([
60
+ Post(),
61
+ HttpCode(HttpStatus.CREATED),
62
+ ApiOperation({ summary: 'Create an environment' }),
63
+ ApiCreatedResponse({ description: 'The created environment.' }),
64
+ __param(0, Session()),
65
+ __param(1, Body()),
66
+ __metadata("design:type", Function),
67
+ __metadata("design:paramtypes", [Object, CreateEnvironmentDto]),
68
+ __metadata("design:returntype", void 0)
69
+ ], EnvironmentsController.prototype, "create", null);
70
+ __decorate([
71
+ Patch(':id'),
72
+ ApiOperation({
73
+ summary: 'Rename an environment, or change which team gates it',
74
+ }),
75
+ ApiOkResponse({ description: 'The updated environment.' }),
76
+ __param(0, Session()),
77
+ __param(1, Param('id')),
78
+ __param(2, Body()),
79
+ __metadata("design:type", Function),
80
+ __metadata("design:paramtypes", [Object, String, UpdateEnvironmentDto]),
81
+ __metadata("design:returntype", void 0)
82
+ ], EnvironmentsController.prototype, "update", null);
83
+ __decorate([
84
+ Delete(':id'),
85
+ ApiOperation({
86
+ summary: 'Delete an environment',
87
+ description: 'Its configurations and stored credentials go with it. Kosha logins carry no environment and are untouched.',
88
+ }),
89
+ ApiOkResponse({ description: 'The deleted environment id.' }),
90
+ __param(0, Session()),
91
+ __param(1, Param('id')),
92
+ __metadata("design:type", Function),
93
+ __metadata("design:paramtypes", [Object, String]),
94
+ __metadata("design:returntype", Promise)
95
+ ], EnvironmentsController.prototype, "remove", null);
96
+ EnvironmentsController = __decorate([
97
+ ApiTags('environments'),
98
+ Controller('environments'),
99
+ __metadata("design:paramtypes", [EnvironmentsService])
100
+ ], EnvironmentsController);
101
+ export { EnvironmentsController };
@@ -0,0 +1,3 @@
1
+ export declare class EnvironmentsModule {
2
+ }
3
+ //# sourceMappingURL=environments.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environments.module.d.ts","sourceRoot":"","sources":["../../src/environments/environments.module.ts"],"names":[],"mappings":"AAKA,qBAKa,kBAAkB;CAAG"}
@@ -0,0 +1,15 @@
1
+ import { __decorate } from "tslib";
2
+ import { Module } from '@nestjs/common';
3
+ import { EnvironmentsController } from './environments.controller.js';
4
+ import { EnvironmentsRepository } from './environments.repository.js';
5
+ import { EnvironmentsService } from './environments.service.js';
6
+ let EnvironmentsModule = class EnvironmentsModule {
7
+ };
8
+ EnvironmentsModule = __decorate([
9
+ Module({
10
+ controllers: [EnvironmentsController],
11
+ providers: [EnvironmentsService, EnvironmentsRepository],
12
+ exports: [EnvironmentsService],
13
+ })
14
+ ], EnvironmentsModule);
15
+ export { EnvironmentsModule };
@@ -0,0 +1,37 @@
1
+ import type { Environment } from '../generated/prisma/client.js';
2
+ import { PrismaService } from '../prisma/prisma.service.js';
3
+ export interface EnvironmentRow {
4
+ organizationId: string;
5
+ name: string;
6
+ slug: string;
7
+ teamId?: string | null;
8
+ }
9
+ /**
10
+ * Every database statement about environments. The service above holds the
11
+ * rules and never touches Prisma, so it can be tested without one.
12
+ */
13
+ export declare class EnvironmentsRepository {
14
+ private readonly prisma;
15
+ constructor(prisma: PrismaService);
16
+ /** Teams within one organization that this user belongs to. */
17
+ teamIdsFor(organizationId: string, userId: string): Promise<string[]>;
18
+ /** Open environments, plus those gated by a team the caller is on. */
19
+ findVisible(organizationId: string, teamIds: string[]): Promise<Environment[]>;
20
+ findById(organizationId: string, id: string): Promise<Environment | null>;
21
+ /** The same row, but only when this member's teams reach it. */
22
+ findVisibleById(organizationId: string, id: string, teamIds: string[]): Promise<Environment | null>;
23
+ findBySlug(organizationId: string, slug: string): Promise<Environment | null>;
24
+ create(row: EnvironmentRow): Promise<Environment>;
25
+ update(id: string, changes: {
26
+ name?: string;
27
+ teamId?: string | null;
28
+ }): Promise<Environment>;
29
+ /**
30
+ * Configurations and credentials go with it, through the foreign keys. Kosha
31
+ * logins carry no environment and are untouched.
32
+ */
33
+ delete(id: string): Promise<void>;
34
+ createMany(rows: EnvironmentRow[]): Promise<void>;
35
+ teamExists(organizationId: string, teamId: string): Promise<boolean>;
36
+ }
37
+ //# sourceMappingURL=environments.repository.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environments.repository.d.ts","sourceRoot":"","sources":["../../src/environments/environments.repository.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,MAAM,WAAW,cAAc;IAC7B,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED;;;GAGG;AACH,qBACa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAElD,+DAA+D;IACzD,UAAU,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAQ3E,sEAAsE;IACtE,WAAW,CACT,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,EAAE,GAChB,OAAO,CAAC,WAAW,EAAE,CAAC;IAUzB,QAAQ,CAAC,cAAc,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;IAIzE,gEAAgE;IAChE,eAAe,CACb,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,MAAM,EAAE,GAChB,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;IAU9B,UAAU,CACR,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;IAM9B,MAAM,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,WAAW,CAAC;IAMjD,MAAM,CACJ,EAAE,EAAE,MAAM,EACV,OAAO,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,GACjD,OAAO,CAAC,WAAW,CAAC;IAIvB;;;OAGG;IACG,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIjC,UAAU,CAAC,IAAI,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAOjD,UAAU,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;CAO3E"}
@@ -0,0 +1,82 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { Injectable } from '@nestjs/common';
3
+ import { PrismaService } from '../prisma/prisma.service.js';
4
+ /**
5
+ * Every database statement about environments. The service above holds the
6
+ * rules and never touches Prisma, so it can be tested without one.
7
+ */
8
+ let EnvironmentsRepository = class EnvironmentsRepository {
9
+ prisma;
10
+ constructor(prisma) {
11
+ this.prisma = prisma;
12
+ }
13
+ /** Teams within one organization that this user belongs to. */
14
+ async teamIdsFor(organizationId, userId) {
15
+ const rows = await this.prisma.teamMember.findMany({
16
+ where: { userId, team: { organizationId } },
17
+ select: { teamId: true },
18
+ });
19
+ return rows.map((row) => row.teamId);
20
+ }
21
+ /** Open environments, plus those gated by a team the caller is on. */
22
+ findVisible(organizationId, teamIds) {
23
+ return this.prisma.environment.findMany({
24
+ where: {
25
+ organizationId,
26
+ OR: [{ teamId: null }, { teamId: { in: teamIds } }],
27
+ },
28
+ orderBy: { createdAt: 'asc' },
29
+ });
30
+ }
31
+ findById(organizationId, id) {
32
+ return this.prisma.environment.findFirst({ where: { id, organizationId } });
33
+ }
34
+ /** The same row, but only when this member's teams reach it. */
35
+ findVisibleById(organizationId, id, teamIds) {
36
+ return this.prisma.environment.findFirst({
37
+ where: {
38
+ id,
39
+ organizationId,
40
+ OR: [{ teamId: null }, { teamId: { in: teamIds } }],
41
+ },
42
+ });
43
+ }
44
+ findBySlug(organizationId, slug) {
45
+ return this.prisma.environment.findFirst({
46
+ where: { organizationId, slug },
47
+ });
48
+ }
49
+ create(row) {
50
+ return this.prisma.environment.create({
51
+ data: { ...row, teamId: row.teamId ?? null },
52
+ });
53
+ }
54
+ update(id, changes) {
55
+ return this.prisma.environment.update({ where: { id }, data: changes });
56
+ }
57
+ /**
58
+ * Configurations and credentials go with it, through the foreign keys. Kosha
59
+ * logins carry no environment and are untouched.
60
+ */
61
+ async delete(id) {
62
+ await this.prisma.environment.delete({ where: { id } });
63
+ }
64
+ async createMany(rows) {
65
+ await this.prisma.environment.createMany({
66
+ data: rows,
67
+ skipDuplicates: true,
68
+ });
69
+ }
70
+ async teamExists(organizationId, teamId) {
71
+ const team = await this.prisma.team.findFirst({
72
+ where: { id: teamId, organizationId },
73
+ select: { id: true },
74
+ });
75
+ return team !== null;
76
+ }
77
+ };
78
+ EnvironmentsRepository = __decorate([
79
+ Injectable(),
80
+ __metadata("design:paramtypes", [PrismaService])
81
+ ], EnvironmentsRepository);
82
+ export { EnvironmentsRepository };