@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
@@ -0,0 +1,234 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { ConflictException, Injectable, InternalServerErrorException, NotFoundException, } from '@nestjs/common';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { Prisma } from '../generated/prisma/client.js';
5
+ import { PrismaService } from '../prisma/prisma.service.js';
6
+ import { IntegrationRegistry } from './integration.registry.js';
7
+ /** Same rule the packages' SQL follows, so both sides derive the same names. */
8
+ const PREFIX_PATTERN = /^[a-z][a-z0-9_]*$/;
9
+ /**
10
+ * Identifiers cannot be parameterised, so this is the one place a table name is
11
+ * built — from a registry key, never from request input.
12
+ */
13
+ export function tablePrefix(integration) {
14
+ const prefix = integration.key.replace(/-/g, '_');
15
+ if (!PREFIX_PATTERN.test(prefix)) {
16
+ throw new InternalServerErrorException(`Provider key "${integration.key}" cannot name a table`);
17
+ }
18
+ return prefix;
19
+ }
20
+ const configurationTable = (integration) => Prisma.raw(`"${tablePrefix(integration)}_configuration"`);
21
+ const connectionTable = (integration) => Prisma.raw(`"${tablePrefix(integration)}_connection"`);
22
+ const PUBLIC_COLUMNS = Prisma.raw('id, "environmentId", name, slug, "createdAt", "updatedAt"');
23
+ /**
24
+ * `now()` means whatever the database session's timezone says, while Prisma
25
+ * writes UTC. These are the only writes that bypass Prisma, so they are the
26
+ * ones that have to say which clock they mean.
27
+ */
28
+ const NOW = Prisma.raw("(now() at time zone 'utc')");
29
+ /**
30
+ * Every read and write against a provider's own two tables.
31
+ *
32
+ * Kosha's schema names no provider, so these tables arrive from the provider's
33
+ * package and Prisma knows nothing about them. They are addressed by
34
+ * convention instead: `<key>_configuration` and `<key>_connection`.
35
+ */
36
+ let ProviderStore = class ProviderStore {
37
+ prisma;
38
+ registry;
39
+ constructor(prisma, registry) {
40
+ this.prisma = prisma;
41
+ this.registry = registry;
42
+ }
43
+ /** A provider installed but never migrated fails the boot, not a request. */
44
+ async onApplicationBootstrap() {
45
+ const missing = await this.providersMissingTables(this.registry.list());
46
+ if (missing.length > 0) {
47
+ throw new Error(`No tables for ${missing.join(', ')}. Run \`kosha migrate deploy\`.`);
48
+ }
49
+ }
50
+ async listConfigurations(integration, environmentId) {
51
+ return this.query(Prisma.sql `
52
+ SELECT ${PUBLIC_COLUMNS} FROM ${configurationTable(integration)}
53
+ WHERE "environmentId" = ${environmentId}
54
+ ORDER BY "createdAt" DESC
55
+ `);
56
+ }
57
+ async findConfigurationById(integration, environmentId, id) {
58
+ const [row] = await this.query(Prisma.sql `
59
+ SELECT ${PUBLIC_COLUMNS} FROM ${configurationTable(integration)}
60
+ WHERE id = ${id} AND "environmentId" = ${environmentId}
61
+ `);
62
+ return row ?? null;
63
+ }
64
+ /** How a caller's slug becomes the row the proxy and connect flows use. */
65
+ async findConfigurationBySlug(integration, environmentId, slug) {
66
+ const [row] = await this.query(Prisma.sql `
67
+ SELECT ${PUBLIC_COLUMNS} FROM ${configurationTable(integration)}
68
+ WHERE "environmentId" = ${environmentId} AND slug = ${slug}
69
+ `);
70
+ return row ?? null;
71
+ }
72
+ /** Keeps the secrets, for the connect flow, which resolves by id. */
73
+ async findConfigurationWithCredentials(integration, id) {
74
+ const [row] = await this.query(Prisma.sql `
75
+ SELECT * FROM ${configurationTable(integration)} WHERE id = ${id}
76
+ `);
77
+ return row ?? null;
78
+ }
79
+ /** The same, by slug, so a proxied call resolves in one read. */
80
+ async findConfigurationBySlugWithCredentials(integration, environmentId, slug) {
81
+ const [row] = await this.query(Prisma.sql `
82
+ SELECT * FROM ${configurationTable(integration)}
83
+ WHERE "environmentId" = ${environmentId} AND slug = ${slug}
84
+ `);
85
+ return row ?? null;
86
+ }
87
+ async createConfiguration(integration, input) {
88
+ const [row] = await this.query(Prisma.sql `
89
+ INSERT INTO ${configurationTable(integration)}
90
+ (id, "environmentId", name, slug, credentials, "createdAt", "updatedAt")
91
+ VALUES (
92
+ ${randomUUID()}, ${input.environmentId}, ${input.name}, ${input.slug},
93
+ ${input.credentials ?? null}, ${NOW}, ${NOW}
94
+ )
95
+ RETURNING ${PUBLIC_COLUMNS}
96
+ `);
97
+ return required(row, integration, 'insert returned no row');
98
+ }
99
+ async updateConfiguration(integration, id, input) {
100
+ const [row] = await this.query(Prisma.sql `
101
+ UPDATE ${configurationTable(integration)} SET
102
+ name = COALESCE(${input.name ?? null}, name),
103
+ credentials = CASE WHEN ${input.credentials !== undefined}
104
+ THEN ${input.credentials ?? null} ELSE credentials END,
105
+ "updatedAt" = ${NOW}
106
+ WHERE id = ${id}
107
+ RETURNING ${PUBLIC_COLUMNS}
108
+ `);
109
+ if (!row)
110
+ throw new NotFoundException('Configuration not found');
111
+ return row;
112
+ }
113
+ /**
114
+ * Refused while connections still point at it. Counted rather than left to
115
+ * the foreign key, so the caller gets a 409 instead of a driver error.
116
+ */
117
+ async deleteConfiguration(integration, id) {
118
+ const [{ count }] = await this.query(Prisma.sql `
119
+ SELECT count(*) FROM ${connectionTable(integration)}
120
+ WHERE "configurationId" = ${id}
121
+ `);
122
+ if (count > 0n) {
123
+ throw new ConflictException('Configuration still has connections. Revoke them first.');
124
+ }
125
+ await this.exec(Prisma.sql `
126
+ DELETE FROM ${configurationTable(integration)} WHERE id = ${id}
127
+ `);
128
+ }
129
+ /** The one connection (environment, configuration, person) identifies. */
130
+ async findConnection(integration, environmentId, configurationId, userId) {
131
+ const [row] = await this.query(Prisma.sql `
132
+ SELECT * FROM ${connectionTable(integration)}
133
+ WHERE "environmentId" = ${environmentId}
134
+ AND "configurationId" = ${configurationId}
135
+ AND "userId" = ${userId}
136
+ `);
137
+ return row ?? null;
138
+ }
139
+ async findConnectionByAccount(integration, environmentId, accountId) {
140
+ const [row] = await this.query(Prisma.sql `
141
+ SELECT * FROM ${connectionTable(integration)}
142
+ WHERE "environmentId" = ${environmentId} AND "accountId" = ${accountId}
143
+ `);
144
+ return row ?? null;
145
+ }
146
+ async listConnections(integration, environmentId, filter = {}) {
147
+ return this.query(Prisma.sql `
148
+ SELECT * FROM ${connectionTable(integration)}
149
+ WHERE "environmentId" = ${environmentId}
150
+ AND (${filter.configurationId ?? null}::text IS NULL
151
+ OR "configurationId" = ${filter.configurationId ?? null})
152
+ AND (${filter.userId ?? null}::text IS NULL
153
+ OR "userId" = ${filter.userId ?? null})
154
+ ORDER BY "createdAt" DESC
155
+ `);
156
+ }
157
+ /**
158
+ * A person's connections to one provider, newest first. A `user` row exists
159
+ * per environment, so the person already settles which environment.
160
+ */
161
+ async listConnectionsForUser(integration, userId) {
162
+ return this.query(Prisma.sql `
163
+ SELECT * FROM ${connectionTable(integration)}
164
+ WHERE "userId" = ${userId}
165
+ ORDER BY "createdAt" DESC
166
+ `);
167
+ }
168
+ /**
169
+ * Written inside the transaction that writes the `account` row, so a
170
+ * credential without its connection cannot exist.
171
+ */
172
+ async storeConnection(tx, integration, input) {
173
+ const [row] = await this.query(Prisma.sql `
174
+ INSERT INTO ${connectionTable(integration)}
175
+ ("accountId", "userId", "environmentId", "configurationId", metadata,
176
+ "createdAt", "updatedAt")
177
+ VALUES (
178
+ ${input.accountId}, ${input.userId}, ${input.environmentId},
179
+ ${input.configurationId}, ${asJson(input.metadata)}, ${NOW}, ${NOW}
180
+ )
181
+ RETURNING *
182
+ `, tx);
183
+ return required(row, integration, 'insert returned no row');
184
+ }
185
+ /**
186
+ * Installed providers whose tables are missing, so a provider that was never
187
+ * migrated is caught at boot rather than on someone's first proxied call.
188
+ */
189
+ async providersMissingTables(integrations) {
190
+ const expected = integrations.flatMap((integration) => {
191
+ const prefix = tablePrefix(integration);
192
+ return [
193
+ { key: integration.key, table: `${prefix}_configuration` },
194
+ { key: integration.key, table: `${prefix}_connection` },
195
+ ];
196
+ });
197
+ if (expected.length === 0)
198
+ return [];
199
+ const present = await this.query(Prisma.sql `
200
+ SELECT table_name FROM information_schema.tables
201
+ WHERE table_schema = current_schema()
202
+ AND table_name IN (${Prisma.join(expected.map((it) => it.table))})
203
+ `);
204
+ const found = new Set(present.map((row) => row.table_name));
205
+ return [
206
+ ...new Set(expected.filter((it) => !found.has(it.table)).map((it) => it.key)),
207
+ ];
208
+ }
209
+ query(sql, client = this.prisma) {
210
+ return client.$queryRaw(sql);
211
+ }
212
+ exec(sql, client = this.prisma) {
213
+ return client.$executeRaw(sql);
214
+ }
215
+ };
216
+ ProviderStore = __decorate([
217
+ Injectable(),
218
+ __metadata("design:paramtypes", [PrismaService,
219
+ IntegrationRegistry])
220
+ ], ProviderStore);
221
+ export { ProviderStore };
222
+ /** An insert that returns nothing means the table is not what we think it is. */
223
+ function required(row, integration, why) {
224
+ if (!row) {
225
+ throw new InternalServerErrorException(`Provider "${integration.key}": ${why}`);
226
+ }
227
+ return row;
228
+ }
229
+ /** Postgres needs the cast; undefined means "leave it alone", null means SQL null. */
230
+ function asJson(value) {
231
+ return value === undefined
232
+ ? Prisma.sql `NULL::jsonb`
233
+ : Prisma.sql `${JSON.stringify(value)}::jsonb`;
234
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"kosha.module.d.ts","sourceRoot":"","sources":["../src/kosha.module.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAU,MAAM,gBAAgB,CAAC;AAGvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAa5D;;;;GAIG;AACH,qBACa,WAAW;IACtB,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,WAAW,GAAG,aAAa;CA0BnD"}
1
+ {"version":3,"file":"kosha.module.d.ts","sourceRoot":"","sources":["../src/kosha.module.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAU,MAAM,gBAAgB,CAAC;AAGvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAgB5D;;;;GAIG;AACH,qBACa,WAAW;IACtB,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,WAAW,GAAG,aAAa;CAgCnD"}
@@ -5,8 +5,11 @@ import { AuthModule } from '@thallesp/nestjs-better-auth';
5
5
  import { createAuth } from './auth/auth.factory.js';
6
6
  import { resolveConfig } from './config/kosha-config.js';
7
7
  import { ConfigurationsModule } from './configurations/configurations.module.js';
8
+ import { EnvironmentsModule } from './environments/environments.module.js';
9
+ import { EnvironmentsService } from './environments/environments.service.js';
8
10
  import { ConnectModule } from './connect/connect.module.js';
9
11
  import { ConnectionsModule } from './connections/connections.module.js';
12
+ import { EnvironmentConnectionsModule } from './connections/environment-connections.module.js';
10
13
  import { CryptoModule } from './crypto/crypto.module.js';
11
14
  import { EgressModule } from './egress/egress.module.js';
12
15
  import { HealthController } from './health/health.controller.js';
@@ -28,15 +31,18 @@ let KoshaModule = KoshaModule_1 = class KoshaModule {
28
31
  PrismaModule.forRoot(resolved),
29
32
  CryptoModule,
30
33
  AuthModule.forRootAsync({
31
- inject: [PrismaService],
32
- useFactory: (prisma) => ({
33
- auth: createAuth(resolved, prisma),
34
+ imports: [EnvironmentsModule],
35
+ inject: [PrismaService, EnvironmentsService],
36
+ useFactory: (prisma, environments) => ({
37
+ auth: createAuth(resolved, prisma, environments),
34
38
  }),
35
39
  }),
36
40
  IntegrationsModule.forRoot(resolved.integrations),
37
41
  ConfigurationsModule,
42
+ EnvironmentsModule,
38
43
  ConnectModule,
39
44
  ConnectionsModule,
45
+ EnvironmentConnectionsModule,
40
46
  ProxyModule,
41
47
  // Only when asked for: the broker opens a second listener, and an app
42
48
  // that has not enabled it should not have one at all.
@@ -4,13 +4,22 @@ import { ProxyService } from './proxy.service.js';
4
4
  export declare class ProxyController {
5
5
  private readonly proxy;
6
6
  constructor(proxy: ProxyService);
7
- forward(request: ApiKeyRequest, response: Response, connectionId: string): Promise<void>;
7
+ /**
8
+ * Addressed by strings the caller already has: the provider, the
9
+ * configuration slug it chose, and its own id for the person. Nothing Kosha
10
+ * generated has to be stored anywhere.
11
+ *
12
+ * The provider segment is also what makes the slug unambiguous: each
13
+ * provider's table has its own unique index, so a slug is only unique
14
+ * within one provider.
15
+ */
16
+ forward(request: ApiKeyRequest, response: Response, provider: string, configurationSlug: string, owner: string): Promise<void>;
8
17
  }
9
18
  /**
10
19
  * Recovers the upstream path from the raw URL rather than the parsed route
11
- * param, so the provider receives the caller's encoding untouched.
20
+ * params, so the provider receives the caller's encoding untouched.
12
21
  */
13
- export declare function splitUpstreamTarget(originalUrl: string, connectionId: string): {
22
+ export declare function splitUpstreamTarget(originalUrl: string, provider: string, configurationSlug: string, owner: string): {
14
23
  path: string;
15
24
  query: string;
16
25
  };
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.controller.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAYlD,qBACa,eAAe;IACd,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,YAAY;IAK1C,OAAO,CACJ,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,QAAQ,EACF,YAAY,EAAE,MAAM;CA0B9C;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,GACnB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAQjC"}
1
+ {"version":3,"file":"proxy.controller.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.controller.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAYlD,qBAEa,eAAe;IACd,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,YAAY;IAEhD;;;;;;;;OAQG;IAUG,OAAO,CACJ,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,QAAQ,EACN,QAAQ,EAAE,MAAM,EACP,iBAAiB,EAAE,MAAM,EACrC,KAAK,EAAE,MAAM;CAmChC;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,KAAK,EAAE,MAAM,GACZ;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAQjC"}
@@ -1,5 +1,6 @@
1
1
  import { __decorate, __metadata, __param } from "tslib";
2
- import { All, Controller, Param, Req, Res, UseGuards } from '@nestjs/common';
2
+ import { All, BadRequestException, Controller, Param, Req, Res, UseGuards, } from '@nestjs/common';
3
+ import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
3
4
  import { AllowAnonymous } from '@thallesp/nestjs-better-auth';
4
5
  import { ApiKeyGuard } from '../auth/api-key.guard.js';
5
6
  import { ProxyService } from './proxy.service.js';
@@ -17,9 +18,21 @@ let ProxyController = class ProxyController {
17
18
  constructor(proxy) {
18
19
  this.proxy = proxy;
19
20
  }
20
- async forward(request, response, connectionId) {
21
- const { path, query } = splitUpstreamTarget(request.originalUrl, connectionId);
22
- const result = await this.proxy.forward(request.organizationId, connectionId, {
21
+ /**
22
+ * Addressed by strings the caller already has: the provider, the
23
+ * configuration slug it chose, and its own id for the person. Nothing Kosha
24
+ * generated has to be stored anywhere.
25
+ *
26
+ * The provider segment is also what makes the slug unambiguous: each
27
+ * provider's table has its own unique index, so a slug is only unique
28
+ * within one provider.
29
+ */
30
+ async forward(request, response, provider, configurationSlug, owner) {
31
+ if (!request.environmentId) {
32
+ throw new BadRequestException('This route needs an API key, which is what names the environment');
33
+ }
34
+ const { path, query } = splitUpstreamTarget(request.originalUrl, provider, configurationSlug, owner);
35
+ const result = await this.proxy.forward(request.organizationId, request.environmentId, { provider, configurationSlug, owner }, {
23
36
  method: request.method,
24
37
  path,
25
38
  query,
@@ -36,27 +49,35 @@ let ProxyController = class ProxyController {
36
49
  }
37
50
  };
38
51
  __decorate([
39
- All(':connectionId/*path'),
52
+ All(':provider/:configurationSlug/:owner/*path'),
40
53
  AllowAnonymous(),
41
54
  UseGuards(ApiKeyGuard),
55
+ ApiSecurity('x-api-key'),
56
+ ApiOperation({
57
+ summary: 'Forward a request to a connected provider',
58
+ description: 'The environment comes from the API key. `owner` is the app’s own id for the person who connected.',
59
+ }),
42
60
  __param(0, Req()),
43
61
  __param(1, Res()),
44
- __param(2, Param('connectionId')),
62
+ __param(2, Param('provider')),
63
+ __param(3, Param('configurationSlug')),
64
+ __param(4, Param('owner')),
45
65
  __metadata("design:type", Function),
46
- __metadata("design:paramtypes", [Object, Object, String]),
66
+ __metadata("design:paramtypes", [Object, Object, String, String, String]),
47
67
  __metadata("design:returntype", Promise)
48
68
  ], ProxyController.prototype, "forward", null);
49
69
  ProxyController = __decorate([
70
+ ApiTags('proxy'),
50
71
  Controller('proxy'),
51
72
  __metadata("design:paramtypes", [ProxyService])
52
73
  ], ProxyController);
53
74
  export { ProxyController };
54
75
  /**
55
76
  * Recovers the upstream path from the raw URL rather than the parsed route
56
- * param, so the provider receives the caller's encoding untouched.
77
+ * params, so the provider receives the caller's encoding untouched.
57
78
  */
58
- export function splitUpstreamTarget(originalUrl, connectionId) {
59
- const marker = `/${connectionId}/`;
79
+ export function splitUpstreamTarget(originalUrl, provider, configurationSlug, owner) {
80
+ const marker = `/${provider}/${configurationSlug}/${owner}/`;
60
81
  const markerIndex = originalUrl.indexOf(marker);
61
82
  const rest = markerIndex >= 0 ? originalUrl.slice(markerIndex + marker.length) : '';
62
83
  const [path, query = ''] = rest.split('?');
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.module.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.module.ts"],"names":[],"mappings":"AAKA,qBAKa,WAAW;CAAG"}
1
+ {"version":3,"file":"proxy.module.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.module.ts"],"names":[],"mappings":"AAOA,qBAKa,WAAW;CAAG"}
@@ -1,15 +1,17 @@
1
1
  import { __decorate } from "tslib";
2
2
  import { Module } from '@nestjs/common';
3
3
  import { CredentialsModule } from '../credentials/credentials.module.js';
4
+ import { EnvironmentsModule } from '../environments/environments.module.js';
4
5
  import { ProxyController } from './proxy.controller.js';
6
+ import { ProxyRepository } from './proxy.repository.js';
5
7
  import { ProxyService } from './proxy.service.js';
6
8
  let ProxyModule = class ProxyModule {
7
9
  };
8
10
  ProxyModule = __decorate([
9
11
  Module({
10
- imports: [CredentialsModule],
12
+ imports: [CredentialsModule, EnvironmentsModule],
11
13
  controllers: [ProxyController],
12
- providers: [ProxyService],
14
+ providers: [ProxyService, ProxyRepository],
13
15
  })
14
16
  ], ProxyModule);
15
17
  export { ProxyModule };
@@ -0,0 +1,21 @@
1
+ import type { Account } from '../generated/prisma/client.js';
2
+ import { PrismaService } from '../prisma/prisma.service.js';
3
+ /**
4
+ * The two reads against Kosha's own tables that a proxied call needs. The
5
+ * connection itself belongs to the provider, so it comes from `ProviderStore`.
6
+ */
7
+ export declare class ProxyRepository {
8
+ private readonly prisma;
9
+ constructor(prisma: PrismaService);
10
+ /**
11
+ * The person a caller named, by the id their app uses.
12
+ *
13
+ * Nothing stores that id any more, so it is matched through the derived
14
+ * email it was encoded into — unique, and carrying the environment, so this
15
+ * is an index lookup rather than a scan.
16
+ */
17
+ findUserId(environmentSlug: string, externalUserId: string): Promise<string | null>;
18
+ /** The `account` row holding the encrypted envelope. */
19
+ findAccount(accountId: string): Promise<Account | null>;
20
+ }
21
+ //# sourceMappingURL=proxy.repository.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy.repository.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D;;;GAGG;AACH,qBACa,eAAe;IACd,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAElD;;;;;;OAMG;IACG,UAAU,CACd,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAQzB,wDAAwD;IACxD,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;CAGxD"}
@@ -0,0 +1,37 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { Injectable } from '@nestjs/common';
3
+ import { derivedEmail } from '../connect/connect.repository.js';
4
+ import { PrismaService } from '../prisma/prisma.service.js';
5
+ /**
6
+ * The two reads against Kosha's own tables that a proxied call needs. The
7
+ * connection itself belongs to the provider, so it comes from `ProviderStore`.
8
+ */
9
+ let ProxyRepository = class ProxyRepository {
10
+ prisma;
11
+ constructor(prisma) {
12
+ this.prisma = prisma;
13
+ }
14
+ /**
15
+ * The person a caller named, by the id their app uses.
16
+ *
17
+ * Nothing stores that id any more, so it is matched through the derived
18
+ * email it was encoded into — unique, and carrying the environment, so this
19
+ * is an index lookup rather than a scan.
20
+ */
21
+ async findUserId(environmentSlug, externalUserId) {
22
+ const user = await this.prisma.user.findUnique({
23
+ where: { email: derivedEmail(environmentSlug, externalUserId) },
24
+ select: { id: true },
25
+ });
26
+ return user?.id ?? null;
27
+ }
28
+ /** The `account` row holding the encrypted envelope. */
29
+ findAccount(accountId) {
30
+ return this.prisma.account.findUnique({ where: { id: accountId } });
31
+ }
32
+ };
33
+ ProxyRepository = __decorate([
34
+ Injectable(),
35
+ __metadata("design:paramtypes", [PrismaService])
36
+ ], ProxyRepository);
37
+ export { ProxyRepository };
@@ -1,6 +1,8 @@
1
1
  import { CredentialsService } from '../credentials/credentials.service.js';
2
+ import { EnvironmentsService } from '../environments/environments.service.js';
2
3
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
3
- import { PrismaService } from '../prisma/prisma.service.js';
4
+ import { ProviderStore } from '../integrations/provider-store.js';
5
+ import { ProxyRepository } from './proxy.repository.js';
4
6
  export interface ProxyRequest {
5
7
  method: string;
6
8
  path: string;
@@ -13,12 +15,20 @@ export interface ProxyResult {
13
15
  headers: Headers;
14
16
  body: string;
15
17
  }
18
+ /** What the URL names: which provider, which of its configurations, whose credential. */
19
+ export interface ProxyTarget {
20
+ provider: string;
21
+ configurationSlug: string;
22
+ owner: string;
23
+ }
16
24
  export declare class ProxyService {
17
- private readonly prisma;
25
+ private readonly proxy;
26
+ private readonly environments;
27
+ private readonly store;
18
28
  private readonly registry;
19
- private readonly credentials;
20
- constructor(prisma: PrismaService, registry: IntegrationRegistry, credentials: CredentialsService);
21
- forward(organizationId: string, connectionId: string, request: ProxyRequest): Promise<ProxyResult>;
29
+ private readonly resolver;
30
+ constructor(proxy: ProxyRepository, environments: EnvironmentsService, store: ProviderStore, registry: IntegrationRegistry, resolver: CredentialsService);
31
+ forward(organizationId: string, environmentId: string, target: ProxyTarget, request: ProxyRequest): Promise<ProxyResult>;
22
32
  private buildTargetUrl;
23
33
  }
24
34
  //# sourceMappingURL=proxy.service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.service.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.service.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAkB5D,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IACvD,IAAI,EAAE,OAAO,CAAC;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,qBACa,YAAY;IAErB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,WAAW;gBAFX,MAAM,EAAE,aAAa,EACrB,QAAQ,EAAE,mBAAmB,EAC7B,WAAW,EAAE,kBAAkB;IAG5C,OAAO,CACX,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,YAAY,GACpB,OAAO,CAAC,WAAW,CAAC;IAwEvB,OAAO,CAAC,cAAc;CAevB"}
1
+ {"version":3,"file":"proxy.service.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.service.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAkBxD,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IACvD,IAAI,EAAE,OAAO,CAAC;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,yFAAyF;AACzF,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC;CACf;AAED,qBACa,YAAY;IAErB,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAJR,KAAK,EAAE,eAAe,EACtB,YAAY,EAAE,mBAAmB,EACjC,KAAK,EAAE,aAAa,EACpB,QAAQ,EAAE,mBAAmB,EAC7B,QAAQ,EAAE,kBAAkB;IAGzC,OAAO,CACX,cAAc,EAAE,MAAM,EACtB,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,GACpB,OAAO,CAAC,WAAW,CAAC;IAyGvB,OAAO,CAAC,cAAc;CAevB"}
@@ -1,8 +1,10 @@
1
1
  import { __decorate, __metadata } from "tslib";
2
- import { BadGatewayException, ForbiddenException, Injectable, NotFoundException, } from '@nestjs/common';
2
+ import { BadGatewayException, Injectable, NotFoundException, } from '@nestjs/common';
3
3
  import { CredentialsService } from '../credentials/credentials.service.js';
4
+ import { EnvironmentsService } from '../environments/environments.service.js';
4
5
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
5
- import { PrismaService } from '../prisma/prisma.service.js';
6
+ import { ProviderStore } from '../integrations/provider-store.js';
7
+ import { ProxyRepository } from './proxy.repository.js';
6
8
  /**
7
9
  * Never forwarded upstream: hop-by-hop framing headers, and anything carrying
8
10
  * Kosha's own credentials. `cookie` matters most — forwarding it would leak
@@ -19,31 +21,56 @@ const STRIPPED_REQUEST_HEADERS = new Set([
19
21
  'x-api-key',
20
22
  ]);
21
23
  let ProxyService = class ProxyService {
22
- prisma;
24
+ proxy;
25
+ environments;
26
+ store;
23
27
  registry;
24
- credentials;
25
- constructor(prisma, registry, credentials) {
26
- this.prisma = prisma;
28
+ resolver;
29
+ constructor(proxy, environments, store, registry, resolver) {
30
+ this.proxy = proxy;
31
+ this.environments = environments;
32
+ this.store = store;
27
33
  this.registry = registry;
28
- this.credentials = credentials;
34
+ this.resolver = resolver;
29
35
  }
30
- async forward(organizationId, connectionId, request) {
31
- const connection = await this.prisma.connection.findFirst({
32
- where: { id: connectionId, organizationId },
33
- include: {
34
- configuration: { include: { provider: true } },
35
- credential: true,
36
- },
37
- });
38
- if (!connection) {
36
+ async forward(organizationId, environmentId, target, request) {
37
+ const environment = await this.environments.get(organizationId, environmentId);
38
+ // Every miss below answers the same 404: a caller learns nothing about
39
+ // what exists in another environment, or under another owner.
40
+ const integration = this.registry.find(target.provider);
41
+ if (!integration)
42
+ throw new NotFoundException('Connection not found');
43
+ // Independent reads, so they go together: the configuration this slug
44
+ // names, and the person this owner names.
45
+ const [configuration, userId] = await Promise.all([
46
+ this.store.findConfigurationBySlugWithCredentials(integration, environment.id, target.configurationSlug),
47
+ this.proxy.findUserId(environment.slug, target.owner),
48
+ ]);
49
+ if (!configuration || !userId) {
39
50
  throw new NotFoundException('Connection not found');
40
51
  }
41
- if (connection.status !== 'ACTIVE' || !connection.credential) {
42
- throw new ForbiddenException(`Connection is ${connection.status.toLowerCase()}`);
52
+ const connection = await this.store.findConnection(integration, environment.id, configuration.id, userId);
53
+ if (!connection)
54
+ throw new NotFoundException('Connection not found');
55
+ const account = await this.proxy.findAccount(connection.accountId);
56
+ if (!account)
57
+ throw new NotFoundException('Connection not found');
58
+ const credential = await this.resolver.resolve(account, integration, configuration);
59
+ const baseUrl = integration.api.resolveBaseUrl?.({
60
+ credential: {
61
+ accessToken: credential.accessToken,
62
+ tokenType: credential.tokenType,
63
+ },
64
+ // What the provider said about this account when it was connected.
65
+ // A provider with no fixed host builds its base URL from this — every
66
+ // Jira path carries a cloudId — so passing nothing made those
67
+ // providers unreachable by construction.
68
+ metadata: asMetadata(connection.metadata),
69
+ }) ?? integration.api.baseUrl;
70
+ if (!baseUrl) {
71
+ throw new BadGatewayException('Provider has no resolvable base URL for this connection');
43
72
  }
44
- const integration = this.registry.get(connection.configuration.provider.key);
45
- const credential = await this.credentials.resolveCredential(connection);
46
- const targetUrl = this.buildTargetUrl(integration.api.baseUrl, request);
73
+ const targetUrl = this.buildTargetUrl(baseUrl, request);
47
74
  /*
48
75
  * Header names are compared lowercased, and the integration's headers are
49
76
  * applied last so they win. Without the normalisation a caller's `accept`
@@ -74,10 +101,6 @@ let ProxyService = class ProxyService {
74
101
  ? JSON.stringify(request.body)
75
102
  : undefined,
76
103
  });
77
- await this.prisma.connection.update({
78
- where: { id: connection.id },
79
- data: { lastUsedAt: new Date() },
80
- });
81
104
  return {
82
105
  status: response.status,
83
106
  headers: response.headers,
@@ -99,8 +122,22 @@ let ProxyService = class ProxyService {
99
122
  };
100
123
  ProxyService = __decorate([
101
124
  Injectable(),
102
- __metadata("design:paramtypes", [PrismaService,
125
+ __metadata("design:paramtypes", [ProxyRepository,
126
+ EnvironmentsService,
127
+ ProviderStore,
103
128
  IntegrationRegistry,
104
129
  CredentialsService])
105
130
  ], ProxyService);
106
131
  export { ProxyService };
132
+ /**
133
+ * Stored metadata is free-form JSON, so it may be an array, a number or null.
134
+ * Only an object is a metadata bag; anything else is treated as absent rather
135
+ * than handed to an integration that expects to index it.
136
+ */
137
+ function asMetadata(metadata) {
138
+ return metadata !== null &&
139
+ typeof metadata === 'object' &&
140
+ !Array.isArray(metadata)
141
+ ? metadata
142
+ : undefined;
143
+ }