@kosha-ai/server 0.2.0 → 0.4.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 (125) hide show
  1. package/dist/auth/auth.factory.d.ts.map +1 -1
  2. package/dist/auth/auth.factory.js +0 -5
  3. package/dist/configurations/configurations.controller.d.ts +6 -5
  4. package/dist/configurations/configurations.controller.d.ts.map +1 -1
  5. package/dist/configurations/configurations.controller.js +22 -18
  6. package/dist/configurations/configurations.module.d.ts.map +1 -1
  7. package/dist/configurations/configurations.module.js +1 -2
  8. package/dist/configurations/configurations.service.d.ts +29 -35
  9. package/dist/configurations/configurations.service.d.ts.map +1 -1
  10. package/dist/configurations/configurations.service.js +126 -149
  11. package/dist/configurations/dto/create-configuration.dto.d.ts +2 -2
  12. package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -1
  13. package/dist/configurations/dto/create-configuration.dto.js +6 -6
  14. package/dist/configurations/dto/update-configuration.dto.d.ts +1 -2
  15. package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -1
  16. package/dist/configurations/dto/update-configuration.dto.js +7 -13
  17. package/dist/connect/connect.controller.d.ts +12 -2
  18. package/dist/connect/connect.controller.d.ts.map +1 -1
  19. package/dist/connect/connect.controller.js +108 -18
  20. package/dist/connect/connect.module.d.ts.map +1 -1
  21. package/dist/connect/connect.module.js +1 -2
  22. package/dist/connect/connect.repository.d.ts +34 -25
  23. package/dist/connect/connect.repository.d.ts.map +1 -1
  24. package/dist/connect/connect.repository.js +45 -52
  25. package/dist/connect/connect.service.d.ts +54 -8
  26. package/dist/connect/connect.service.d.ts.map +1 -1
  27. package/dist/connect/connect.service.js +312 -68
  28. package/dist/connect/dto/connect-credential.dto.d.ts +8 -0
  29. package/dist/connect/dto/connect-credential.dto.d.ts.map +1 -0
  30. package/dist/connect/dto/connect-credential.dto.js +54 -0
  31. package/dist/connect/dto/create-connect-session.dto.d.ts +1 -1
  32. package/dist/connect/dto/create-connect-session.dto.d.ts.map +1 -1
  33. package/dist/connect/dto/create-connect-session.dto.js +7 -8
  34. package/dist/connect/dto/create-test-session.dto.d.ts +8 -0
  35. package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -1
  36. package/dist/connect/dto/create-test-session.dto.js +45 -3
  37. package/dist/connections/connections.controller.d.ts +4 -3
  38. package/dist/connections/connections.controller.d.ts.map +1 -1
  39. package/dist/connections/connections.controller.js +13 -11
  40. package/dist/connections/connections.repository.d.ts +24 -17
  41. package/dist/connections/connections.repository.d.ts.map +1 -1
  42. package/dist/connections/connections.repository.js +21 -43
  43. package/dist/connections/connections.service.d.ts +48 -13
  44. package/dist/connections/connections.service.d.ts.map +1 -1
  45. package/dist/connections/connections.service.js +111 -32
  46. package/dist/connections/dto/list-connections.dto.d.ts +3 -1
  47. package/dist/connections/dto/list-connections.dto.d.ts.map +1 -1
  48. package/dist/connections/dto/list-connections.dto.js +26 -4
  49. package/dist/connections/environment-connections.controller.d.ts +4 -3
  50. package/dist/connections/environment-connections.controller.d.ts.map +1 -1
  51. package/dist/connections/environment-connections.controller.js +14 -12
  52. package/dist/credentials/credentials.module.d.ts.map +1 -1
  53. package/dist/credentials/credentials.module.js +0 -2
  54. package/dist/credentials/credentials.repository.d.ts +5 -2
  55. package/dist/credentials/credentials.repository.d.ts.map +1 -1
  56. package/dist/credentials/credentials.repository.js +10 -3
  57. package/dist/credentials/credentials.service.d.ts +14 -4
  58. package/dist/credentials/credentials.service.d.ts.map +1 -1
  59. package/dist/credentials/credentials.service.js +106 -30
  60. package/dist/crypto/credential-envelope.d.ts +27 -1
  61. package/dist/crypto/credential-envelope.d.ts.map +1 -1
  62. package/dist/crypto/credential-envelope.js +43 -0
  63. package/dist/egress/egress.listener.d.ts +1 -3
  64. package/dist/egress/egress.listener.d.ts.map +1 -1
  65. package/dist/egress/egress.listener.js +3 -7
  66. package/dist/egress/egress.repository.d.ts +13 -6
  67. package/dist/egress/egress.repository.d.ts.map +1 -1
  68. package/dist/egress/egress.repository.js +31 -44
  69. package/dist/generated/prisma/browser.d.ts +0 -5
  70. package/dist/generated/prisma/browser.d.ts.map +1 -1
  71. package/dist/generated/prisma/client.d.ts +0 -5
  72. package/dist/generated/prisma/client.d.ts.map +1 -1
  73. package/dist/generated/prisma/commonInputTypes.d.ts +0 -55
  74. package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -1
  75. package/dist/generated/prisma/internal/class.d.ts +0 -11
  76. package/dist/generated/prisma/internal/class.d.ts.map +1 -1
  77. package/dist/generated/prisma/internal/class.js +4 -4
  78. package/dist/generated/prisma/internal/prismaNamespace.d.ts +1 -114
  79. package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
  80. package/dist/generated/prisma/internal/prismaNamespace.js +2 -29
  81. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +0 -30
  82. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
  83. package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +2 -29
  84. package/dist/generated/prisma/models/Account.d.ts +26 -344
  85. package/dist/generated/prisma/models/Account.d.ts.map +1 -1
  86. package/dist/generated/prisma/models/Environment.d.ts +0 -258
  87. package/dist/generated/prisma/models/Environment.d.ts.map +1 -1
  88. package/dist/generated/prisma/models/User.d.ts +2 -60
  89. package/dist/generated/prisma/models/User.d.ts.map +1 -1
  90. package/dist/generated/prisma/models.d.ts +0 -1
  91. package/dist/generated/prisma/models.d.ts.map +1 -1
  92. package/dist/index.d.ts +1 -2
  93. package/dist/index.d.ts.map +1 -1
  94. package/dist/integrations/client-context.d.ts +20 -0
  95. package/dist/integrations/client-context.d.ts.map +1 -0
  96. package/dist/integrations/client-context.js +23 -0
  97. package/dist/integrations/integrations.controller.d.ts +6 -0
  98. package/dist/integrations/integrations.controller.d.ts.map +1 -1
  99. package/dist/integrations/integrations.controller.js +3 -0
  100. package/dist/integrations/integrations.module.d.ts.map +1 -1
  101. package/dist/integrations/integrations.module.js +3 -1
  102. package/dist/integrations/provider-store.d.ts +110 -0
  103. package/dist/integrations/provider-store.d.ts.map +1 -0
  104. package/dist/integrations/provider-store.js +302 -0
  105. package/dist/proxy/proxy.controller.d.ts +17 -5
  106. package/dist/proxy/proxy.controller.d.ts.map +1 -1
  107. package/dist/proxy/proxy.controller.js +46 -17
  108. package/dist/proxy/proxy.module.d.ts.map +1 -1
  109. package/dist/proxy/proxy.module.js +1 -2
  110. package/dist/proxy/proxy.repository.d.ts +11 -14
  111. package/dist/proxy/proxy.repository.d.ts.map +1 -1
  112. package/dist/proxy/proxy.repository.js +17 -27
  113. package/dist/proxy/proxy.service.d.ts +6 -8
  114. package/dist/proxy/proxy.service.d.ts.map +1 -1
  115. package/dist/proxy/proxy.service.js +72 -31
  116. package/package.json +4 -4
  117. package/prisma/migrations/{20260929101936_init → 20261008090000_init}/migration.sql +5 -58
  118. package/prisma/schema.prisma +2 -43
  119. package/dist/configurations/configurations.repository.d.ts +0 -43
  120. package/dist/configurations/configurations.repository.d.ts.map +0 -1
  121. package/dist/configurations/configurations.repository.js +0 -76
  122. package/dist/generated/prisma/models/Configuration.d.ts +0 -1385
  123. package/dist/generated/prisma/models/Configuration.d.ts.map +0 -1
  124. package/dist/generated/prisma/models/Configuration.js +0 -1
  125. package/prisma/migrations/20260930102529_connection_config/migration.sql +0 -2
@@ -0,0 +1,302 @@
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
+ const COLUMN_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;
8
+ /**
9
+ * A provider's own column, quoted for a statement.
10
+ *
11
+ * The name comes from the package's own `configFields`, never from a request,
12
+ * and is checked anyway: this is the second place an identifier is built.
13
+ */
14
+ function column(name) {
15
+ if (!COLUMN_PATTERN.test(name) || BASE_COLUMNS.has(name)) {
16
+ throw new InternalServerErrorException(`"${name}" cannot name a configuration column`);
17
+ }
18
+ return Prisma.raw(`"${name}"`);
19
+ }
20
+ /** The names every provider's table has, so the rest are the provider's own. */
21
+ const BASE_COLUMNS = new Set([
22
+ 'id',
23
+ 'environmentId',
24
+ 'name',
25
+ 'slug',
26
+ 'credentials',
27
+ 'createdAt',
28
+ 'updatedAt',
29
+ ]);
30
+ /**
31
+ * Splits a row into the shape core knows and the columns the package added.
32
+ *
33
+ * Without this a package can store a value it then cannot read: the subdomain
34
+ * Zendesk authorizes at is a column on its own table, and the authorize URL is
35
+ * built by the package.
36
+ */
37
+ function describeRow(row) {
38
+ const base = {};
39
+ const fields = {};
40
+ for (const [column, value] of Object.entries(row)) {
41
+ (BASE_COLUMNS.has(column) ? base : fields)[column] = value;
42
+ }
43
+ return { ...base, fields };
44
+ }
45
+ /** Same rule the packages' SQL follows, so both sides derive the same names. */
46
+ const PREFIX_PATTERN = /^[a-z][a-z0-9_]*$/;
47
+ /**
48
+ * Identifiers cannot be parameterised, so this is the one place a table name is
49
+ * built — from a registry key, never from request input.
50
+ */
51
+ export function tablePrefix(integration) {
52
+ const prefix = integration.key.replace(/-/g, '_');
53
+ if (!PREFIX_PATTERN.test(prefix)) {
54
+ throw new InternalServerErrorException(`Provider key "${integration.key}" cannot name a table`);
55
+ }
56
+ return prefix;
57
+ }
58
+ const configurationTable = (integration) => Prisma.raw(`"${tablePrefix(integration)}_configuration"`);
59
+ const connectionTable = (integration) => Prisma.raw(`"${tablePrefix(integration)}_connection"`);
60
+ /** Everything the row has: a fixed list cannot name a provider's own columns. */
61
+ const ALL_COLUMNS = Prisma.raw('*');
62
+ /** The secret never leaves this module except on the explicit read. */
63
+ function withoutCredentials(row) {
64
+ const { credentials: _secret, ...rest } = row;
65
+ return rest;
66
+ }
67
+ /**
68
+ * `now()` means whatever the database session's timezone says, while Prisma
69
+ * writes UTC. These are the only writes that bypass Prisma, so they are the
70
+ * ones that have to say which clock they mean.
71
+ */
72
+ const NOW = Prisma.raw("(now() at time zone 'utc')");
73
+ /**
74
+ * Every read and write against a provider's own two tables.
75
+ *
76
+ * Kosha's schema names no provider, so these tables arrive from the provider's
77
+ * package and Prisma knows nothing about them. They are addressed by
78
+ * convention instead: `<key>_configuration` and `<key>_connection`.
79
+ */
80
+ let ProviderStore = class ProviderStore {
81
+ prisma;
82
+ registry;
83
+ constructor(prisma, registry) {
84
+ this.prisma = prisma;
85
+ this.registry = registry;
86
+ }
87
+ /** A provider installed but never migrated fails the boot, not a request. */
88
+ async onApplicationBootstrap() {
89
+ const missing = await this.providersMissingTables(this.registry.list());
90
+ if (missing.length > 0) {
91
+ throw new Error(`No tables for ${missing.join(', ')}. Run \`kosha migrate deploy\`.`);
92
+ }
93
+ }
94
+ async listConfigurations(integration, environmentId) {
95
+ const rows = await this.query(Prisma.sql `
96
+ SELECT ${ALL_COLUMNS} FROM ${configurationTable(integration)}
97
+ WHERE "environmentId" = ${environmentId}
98
+ ORDER BY "createdAt" DESC
99
+ `);
100
+ return rows.map((row) => withoutCredentials(describeRow(row)));
101
+ }
102
+ async findConfigurationById(integration, environmentId, id) {
103
+ const [row] = await this.query(Prisma.sql `
104
+ SELECT ${ALL_COLUMNS} FROM ${configurationTable(integration)}
105
+ WHERE id = ${id} AND "environmentId" = ${environmentId}
106
+ `);
107
+ return row ? withoutCredentials(describeRow(row)) : null;
108
+ }
109
+ /** How a caller's slug becomes the row the proxy and connect flows use. */
110
+ async findConfigurationBySlug(integration, environmentId, slug) {
111
+ const [row] = await this.query(Prisma.sql `
112
+ SELECT ${ALL_COLUMNS} FROM ${configurationTable(integration)}
113
+ WHERE "environmentId" = ${environmentId} AND slug = ${slug}
114
+ `);
115
+ return row ? withoutCredentials(describeRow(row)) : null;
116
+ }
117
+ /** Keeps the secrets, for the connect flow, which resolves by id. */
118
+ async findConfigurationWithCredentials(integration, id) {
119
+ const [row] = await this.query(Prisma.sql `
120
+ SELECT * FROM ${configurationTable(integration)} WHERE id = ${id}
121
+ `);
122
+ return row ? describeRow(row) : null;
123
+ }
124
+ /** The same, by slug, so a proxied call resolves in one read. */
125
+ async findConfigurationBySlugWithCredentials(integration, environmentId, slug) {
126
+ const [row] = await this.query(Prisma.sql `
127
+ SELECT * FROM ${configurationTable(integration)}
128
+ WHERE "environmentId" = ${environmentId} AND slug = ${slug}
129
+ `);
130
+ return row ? describeRow(row) : null;
131
+ }
132
+ async createConfiguration(integration, input) {
133
+ const extra = Object.entries(input.fields ?? {});
134
+ const [row] = await this.query(Prisma.sql `
135
+ INSERT INTO ${configurationTable(integration)}
136
+ (id, "environmentId", name, slug, credentials, "createdAt", "updatedAt"
137
+ ${joinColumns(extra.map(([name]) => name))})
138
+ VALUES (
139
+ ${randomUUID()}, ${input.environmentId}, ${input.name}, ${input.slug},
140
+ ${input.credentials ?? null}, ${NOW}, ${NOW}
141
+ ${joinValues(extra.map(([, value]) => value))}
142
+ )
143
+ RETURNING ${ALL_COLUMNS}
144
+ `);
145
+ return withoutCredentials(describeRow(required(row, integration, 'insert returned no row')));
146
+ }
147
+ async updateConfiguration(integration, id, input) {
148
+ const [row] = await this.query(Prisma.sql `
149
+ UPDATE ${configurationTable(integration)} SET
150
+ name = COALESCE(${input.name ?? null}, name),
151
+ credentials = CASE WHEN ${input.credentials !== undefined}
152
+ THEN ${input.credentials ?? null} ELSE credentials END,
153
+ "updatedAt" = ${NOW}
154
+ ${assignments(input.fields ?? {})}
155
+ WHERE id = ${id}
156
+ RETURNING ${ALL_COLUMNS}
157
+ `);
158
+ if (!row)
159
+ throw new NotFoundException('Configuration not found');
160
+ return withoutCredentials(describeRow(row));
161
+ }
162
+ /**
163
+ * Refused while connections still point at it. Counted rather than left to
164
+ * the foreign key, so the caller gets a 409 instead of a driver error.
165
+ */
166
+ async deleteConfiguration(integration, id) {
167
+ const [{ count }] = await this.query(Prisma.sql `
168
+ SELECT count(*) FROM ${connectionTable(integration)}
169
+ WHERE "configurationId" = ${id}
170
+ `);
171
+ if (count > 0n) {
172
+ throw new ConflictException('Configuration still has connections. Revoke them first.');
173
+ }
174
+ await this.exec(Prisma.sql `
175
+ DELETE FROM ${configurationTable(integration)} WHERE id = ${id}
176
+ `);
177
+ }
178
+ /** The one connection (environment, configuration, person) identifies. */
179
+ async findConnection(integration, environmentId, configurationId, userId) {
180
+ const [row] = await this.query(Prisma.sql `
181
+ SELECT * FROM ${connectionTable(integration)}
182
+ WHERE "environmentId" = ${environmentId}
183
+ AND "configurationId" = ${configurationId}
184
+ AND "userId" = ${userId}
185
+ `);
186
+ return row ?? null;
187
+ }
188
+ async findConnectionByAccount(integration, environmentId, accountId) {
189
+ const [row] = await this.query(Prisma.sql `
190
+ SELECT * FROM ${connectionTable(integration)}
191
+ WHERE "environmentId" = ${environmentId} AND "accountId" = ${accountId}
192
+ `);
193
+ return row ?? null;
194
+ }
195
+ async listConnections(integration, environmentId, filter = {}) {
196
+ return this.query(Prisma.sql `
197
+ SELECT * FROM ${connectionTable(integration)}
198
+ WHERE "environmentId" = ${environmentId}
199
+ AND (${filter.configurationId ?? null}::text IS NULL
200
+ OR "configurationId" = ${filter.configurationId ?? null})
201
+ AND (${filter.userId ?? null}::text IS NULL
202
+ OR "userId" = ${filter.userId ?? null})
203
+ ORDER BY "createdAt" DESC
204
+ `);
205
+ }
206
+ /**
207
+ * A person's connections to one provider, newest first. A `user` row exists
208
+ * per environment, so the person already settles which environment.
209
+ */
210
+ async listConnectionsForUser(integration, userId) {
211
+ return this.query(Prisma.sql `
212
+ SELECT * FROM ${connectionTable(integration)}
213
+ WHERE "userId" = ${userId}
214
+ ORDER BY "createdAt" DESC
215
+ `);
216
+ }
217
+ /**
218
+ * Written inside the transaction that writes the `account` row, so a
219
+ * credential without its connection cannot exist.
220
+ */
221
+ async storeConnection(tx, integration, input) {
222
+ const [row] = await this.query(Prisma.sql `
223
+ INSERT INTO ${connectionTable(integration)}
224
+ ("accountId", "userId", "environmentId", "configurationId", metadata,
225
+ "createdAt", "updatedAt")
226
+ VALUES (
227
+ ${input.accountId}, ${input.userId}, ${input.environmentId},
228
+ ${input.configurationId}, ${asJson(input.metadata)}, ${NOW}, ${NOW}
229
+ )
230
+ RETURNING *
231
+ `, tx);
232
+ return required(row, integration, 'insert returned no row');
233
+ }
234
+ /**
235
+ * Installed providers whose tables are missing, so a provider that was never
236
+ * migrated is caught at boot rather than on someone's first proxied call.
237
+ */
238
+ async providersMissingTables(integrations) {
239
+ const expected = integrations.flatMap((integration) => {
240
+ const prefix = tablePrefix(integration);
241
+ return [
242
+ { key: integration.key, table: `${prefix}_configuration` },
243
+ { key: integration.key, table: `${prefix}_connection` },
244
+ ];
245
+ });
246
+ if (expected.length === 0)
247
+ return [];
248
+ const present = await this.query(Prisma.sql `
249
+ SELECT table_name FROM information_schema.tables
250
+ WHERE table_schema = current_schema()
251
+ AND table_name IN (${Prisma.join(expected.map((it) => it.table))})
252
+ `);
253
+ const found = new Set(present.map((row) => row.table_name));
254
+ return [
255
+ ...new Set(expected.filter((it) => !found.has(it.table)).map((it) => it.key)),
256
+ ];
257
+ }
258
+ query(sql, client = this.prisma) {
259
+ return client.$queryRaw(sql);
260
+ }
261
+ exec(sql, client = this.prisma) {
262
+ return client.$executeRaw(sql);
263
+ }
264
+ };
265
+ ProviderStore = __decorate([
266
+ Injectable(),
267
+ __metadata("design:paramtypes", [PrismaService,
268
+ IntegrationRegistry])
269
+ ], ProviderStore);
270
+ export { ProviderStore };
271
+ /** An insert that returns nothing means the table is not what we think it is. */
272
+ function required(row, integration, why) {
273
+ if (!row) {
274
+ throw new InternalServerErrorException(`Provider "${integration.key}": ${why}`);
275
+ }
276
+ return row;
277
+ }
278
+ /** `, "a" = $1, "b" = $2` or nothing, for the columns an update was given. */
279
+ function assignments(fields) {
280
+ const entries = Object.entries(fields);
281
+ return entries.length === 0
282
+ ? Prisma.empty
283
+ : Prisma.sql `, ${Prisma.join(entries.map(([name, value]) => Prisma.sql `${column(name)} = ${value}`))}`;
284
+ }
285
+ /** `, "a", "b"` or nothing, so the base column list stays readable above. */
286
+ function joinColumns(names) {
287
+ return names.length === 0
288
+ ? Prisma.empty
289
+ : Prisma.sql `, ${Prisma.join(names.map(column))}`;
290
+ }
291
+ /** The matching values, parameterised: only the names are interpolated. */
292
+ function joinValues(values) {
293
+ return values.length === 0
294
+ ? Prisma.empty
295
+ : Prisma.sql `, ${Prisma.join(values.map((value) => Prisma.sql `${value}`))}`;
296
+ }
297
+ /** Postgres needs the cast; undefined means "leave it alone", null means SQL null. */
298
+ function asJson(value) {
299
+ return value === undefined
300
+ ? Prisma.sql `NULL::jsonb`
301
+ : Prisma.sql `${JSON.stringify(value)}::jsonb`;
302
+ }
@@ -5,17 +5,29 @@ export declare class ProxyController {
5
5
  private readonly proxy;
6
6
  constructor(proxy: ProxyService);
7
7
  /**
8
- * Addressed by strings the caller already has: the configuration slug it
9
- * chose, and its own id for the tenant or person the credential belongs to.
10
- * Nothing Kosha generated has to be stored anywhere.
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.
11
15
  */
12
- forward(request: ApiKeyRequest, response: Response, configurationSlug: string, owner: string): Promise<void>;
16
+ forward(request: ApiKeyRequest, response: Response, provider: string, configurationSlug: string, pathOwner: string, headerOwner: string | undefined): Promise<void>;
13
17
  }
18
+ /**
19
+ * The header, when a caller sent one, else the URL's `:owner` segment.
20
+ *
21
+ * For a caller whose URL can't vary per request (an MCP connection has one
22
+ * fixed `url`, unlike an OpenAPI connection's per-call operation paths).
23
+ * Additive: every existing caller sends no header and is unaffected.
24
+ */
25
+ export declare function resolveOwner(headerOwner: string | undefined, pathOwner: string): string;
14
26
  /**
15
27
  * Recovers the upstream path from the raw URL rather than the parsed route
16
28
  * params, so the provider receives the caller's encoding untouched.
17
29
  */
18
- export declare function splitUpstreamTarget(originalUrl: string, configurationSlug: string, owner: string): {
30
+ export declare function splitUpstreamTarget(originalUrl: string, provider: string, configurationSlug: string, owner: string): {
19
31
  path: string;
20
32
  query: string;
21
33
  };
@@ -1 +1 @@
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;;;;OAIG;IAUG,OAAO,CACJ,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,QAAQ,EACG,iBAAiB,EAAE,MAAM,EACrC,KAAK,EAAE,MAAM;CAkChC;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,EACnB,iBAAiB,EAAE,MAAM,EACzB,KAAK,EAAE,MAAM,GACZ;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":"AAYA,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;IAiBG,OAAO,CACJ,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,QAAQ,EACN,QAAQ,EAAE,MAAM,EACP,iBAAiB,EAAE,MAAM,EACrC,SAAS,EAAE,MAAM,EACP,WAAW,EAAE,MAAM,GAAG,SAAS;CAuC5D;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC1B,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,SAAS,EAAE,MAAM,GAChB,MAAM,CAER;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,CAYjC"}
@@ -1,5 +1,5 @@
1
1
  import { __decorate, __metadata, __param } from "tslib";
2
- import { All, BadRequestException, Controller, Param, Req, Res, UseGuards, } from '@nestjs/common';
2
+ import { All, BadRequestException, Controller, Headers, Param, Req, Res, UseGuards, } from '@nestjs/common';
3
3
  import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
4
4
  import { AllowAnonymous } from '@thallesp/nestjs-better-auth';
5
5
  import { ApiKeyGuard } from '../auth/api-key.guard.js';
@@ -19,16 +19,25 @@ let ProxyController = class ProxyController {
19
19
  this.proxy = proxy;
20
20
  }
21
21
  /**
22
- * Addressed by strings the caller already has: the configuration slug it
23
- * chose, and its own id for the tenant or person the credential belongs to.
24
- * Nothing Kosha generated has to be stored anywhere.
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.
25
29
  */
26
- async forward(request, response, configurationSlug, owner) {
30
+ // `{/*path}` wraps the slash too, so MCP's `.../owner` with nothing after
31
+ // it also matches — `/{*path}` alone would still require that slash.
32
+ async forward(request, response, provider, configurationSlug, pathOwner, headerOwner) {
27
33
  if (!request.environmentId) {
28
34
  throw new BadRequestException('This route needs an API key, which is what names the environment');
29
35
  }
30
- const { path, query } = splitUpstreamTarget(request.originalUrl, configurationSlug, owner);
31
- const result = await this.proxy.forward(request.organizationId, request.environmentId, { configurationSlug, owner }, {
36
+ const owner = resolveOwner(headerOwner, pathOwner);
37
+ // Always the path segment here, not the resolved owner -- the marker has
38
+ // to match what is literally in the URL.
39
+ const { path, query } = splitUpstreamTarget(request.originalUrl, provider, configurationSlug, pathOwner);
40
+ const result = await this.proxy.forward(request.organizationId, request.environmentId, { provider, configurationSlug, owner }, {
32
41
  method: request.method,
33
42
  path,
34
43
  query,
@@ -45,20 +54,27 @@ let ProxyController = class ProxyController {
45
54
  }
46
55
  };
47
56
  __decorate([
48
- All(':configurationSlug/:owner/*path'),
57
+ All(':provider/:configurationSlug/:owner{/*path}'),
49
58
  AllowAnonymous(),
50
59
  UseGuards(ApiKeyGuard),
51
60
  ApiSecurity('x-api-key'),
52
61
  ApiOperation({
53
62
  summary: 'Forward a request to a connected provider',
54
- description: 'The environment comes from the API key. `owner` is the app’s own id for the tenant or the person; a tenant-owned credential is preferred when both would match.',
63
+ description: 'The environment comes from the API key. `owner` is the app’s own id ' +
64
+ 'for the person who connected. A caller whose URL has to stay fixed ' +
65
+ 'across calls — an MCP client connection, which has no per-call path ' +
66
+ 'the way an OpenAPI connection does — may send `x-kosha-owner` instead ' +
67
+ 'and put any placeholder in the `owner` segment; the header wins when ' +
68
+ 'both are present.',
55
69
  }),
56
70
  __param(0, Req()),
57
71
  __param(1, Res()),
58
- __param(2, Param('configurationSlug')),
59
- __param(3, Param('owner')),
72
+ __param(2, Param('provider')),
73
+ __param(3, Param('configurationSlug')),
74
+ __param(4, Param('owner')),
75
+ __param(5, Headers('x-kosha-owner')),
60
76
  __metadata("design:type", Function),
61
- __metadata("design:paramtypes", [Object, Object, String, String]),
77
+ __metadata("design:paramtypes", [Object, Object, String, String, String, Object]),
62
78
  __metadata("design:returntype", Promise)
63
79
  ], ProxyController.prototype, "forward", null);
64
80
  ProxyController = __decorate([
@@ -67,14 +83,27 @@ ProxyController = __decorate([
67
83
  __metadata("design:paramtypes", [ProxyService])
68
84
  ], ProxyController);
69
85
  export { ProxyController };
86
+ /**
87
+ * The header, when a caller sent one, else the URL's `:owner` segment.
88
+ *
89
+ * For a caller whose URL can't vary per request (an MCP connection has one
90
+ * fixed `url`, unlike an OpenAPI connection's per-call operation paths).
91
+ * Additive: every existing caller sends no header and is unaffected.
92
+ */
93
+ export function resolveOwner(headerOwner, pathOwner) {
94
+ return headerOwner?.trim() ? headerOwner.trim() : pathOwner;
95
+ }
70
96
  /**
71
97
  * Recovers the upstream path from the raw URL rather than the parsed route
72
98
  * params, so the provider receives the caller's encoding untouched.
73
99
  */
74
- export function splitUpstreamTarget(originalUrl, configurationSlug, owner) {
75
- const marker = `/${configurationSlug}/${owner}/`;
76
- const markerIndex = originalUrl.indexOf(marker);
77
- const rest = markerIndex >= 0 ? originalUrl.slice(markerIndex + marker.length) : '';
78
- const [path, query = ''] = rest.split('?');
100
+ export function splitUpstreamTarget(originalUrl, provider, configurationSlug, owner) {
101
+ const [beforeQuery, query = ''] = originalUrl.split('?');
102
+ // No trailing slash in the marker, so an owner with nothing after it also matches.
103
+ const marker = `/${provider}/${configurationSlug}/${owner}`;
104
+ const markerIndex = beforeQuery.indexOf(marker);
105
+ const path = markerIndex >= 0
106
+ ? beforeQuery.slice(markerIndex + marker.length).replace(/^\/+/, '')
107
+ : '';
79
108
  return { path, query };
80
109
  }
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.module.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.module.ts"],"names":[],"mappings":"AAQA,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,6 +1,5 @@
1
1
  import { __decorate } from "tslib";
2
2
  import { Module } from '@nestjs/common';
3
- import { ConfigurationsModule } from '../configurations/configurations.module.js';
4
3
  import { CredentialsModule } from '../credentials/credentials.module.js';
5
4
  import { EnvironmentsModule } from '../environments/environments.module.js';
6
5
  import { ProxyController } from './proxy.controller.js';
@@ -10,7 +9,7 @@ let ProxyModule = class ProxyModule {
10
9
  };
11
10
  ProxyModule = __decorate([
12
11
  Module({
13
- imports: [CredentialsModule, EnvironmentsModule, ConfigurationsModule],
12
+ imports: [CredentialsModule, EnvironmentsModule],
14
13
  controllers: [ProxyController],
15
14
  providers: [ProxyService, ProxyRepository],
16
15
  })
@@ -1,24 +1,21 @@
1
1
  import type { Account } from '../generated/prisma/client.js';
2
2
  import { PrismaService } from '../prisma/prisma.service.js';
3
- /** Whose credential a caller is asking for. */
4
- export interface CredentialOwner {
5
- /** The app's tenant, when the credential belongs to one. */
6
- organizationExternalId?: string | null;
7
- /** The app's id for the person, when it belongs to them. */
8
- externalUserId?: string | null;
9
- }
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
+ */
10
7
  export declare class ProxyRepository {
11
8
  private readonly prisma;
12
9
  constructor(prisma: PrismaService);
13
10
  /**
14
- * A tenant-owned credential is one read against the unique index on
15
- * (environmentId, organizationExternalId, providerId) — no join, since both
16
- * columns are on the row.
11
+ * The person a caller named, by the id their app uses.
17
12
  *
18
- * A personal one joins `user`, because the app's id for a person lives
19
- * there. That join is on `user.email`, which is unique, and the derived form
20
- * carries the environment — so it is an index lookup rather than a scan.
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.
21
16
  */
22
- findCredential(environmentId: string, environmentSlug: string, providerId: string, owner: CredentialOwner): Promise<Account | null>;
17
+ findUserId(environmentSlug: string, externalUserId: string): Promise<string | null>;
18
+ /** The `account` row holding the encrypted envelope. */
19
+ findAccount(accountId: string): Promise<Account | null>;
23
20
  }
24
21
  //# sourceMappingURL=proxy.repository.d.ts.map
@@ -1 +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,+CAA+C;AAC/C,MAAM,WAAW,eAAe;IAC9B,4DAA4D;IAC5D,sBAAsB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvC,4DAA4D;IAC5D,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,qBACa,eAAe;IACd,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAElD;;;;;;;;OAQG;IACG,cAAc,CAClB,aAAa,EAAE,MAAM,EACrB,eAAe,EAAE,MAAM,EACvB,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,eAAe,GACrB,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;CAwB3B"}
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"}
@@ -2,42 +2,32 @@ import { __decorate, __metadata } from "tslib";
2
2
  import { Injectable } from '@nestjs/common';
3
3
  import { derivedEmail } from '../connect/connect.repository.js';
4
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
+ */
5
9
  let ProxyRepository = class ProxyRepository {
6
10
  prisma;
7
11
  constructor(prisma) {
8
12
  this.prisma = prisma;
9
13
  }
10
14
  /**
11
- * A tenant-owned credential is one read against the unique index on
12
- * (environmentId, organizationExternalId, providerId) — no join, since both
13
- * columns are on the row.
15
+ * The person a caller named, by the id their app uses.
14
16
  *
15
- * A personal one joins `user`, because the app's id for a person lives
16
- * there. That join is on `user.email`, which is unique, and the derived form
17
- * carries the environment — so it is an index lookup rather than a scan.
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.
18
20
  */
19
- async findCredential(environmentId, environmentSlug, providerId, owner) {
20
- if (owner.organizationExternalId) {
21
- return this.prisma.account.findFirst({
22
- where: {
23
- environmentId,
24
- providerId,
25
- organizationExternalId: owner.organizationExternalId,
26
- },
27
- });
28
- }
29
- if (!owner.externalUserId)
30
- return null;
31
- return this.prisma.account.findFirst({
32
- where: {
33
- environmentId,
34
- providerId,
35
- organizationExternalId: null,
36
- user: {
37
- email: derivedEmail(environmentSlug, owner.externalUserId),
38
- },
39
- },
21
+ async findUserId(environmentSlug, externalUserId) {
22
+ const user = await this.prisma.user.findUnique({
23
+ where: { email: derivedEmail(environmentSlug, externalUserId) },
24
+ select: { id: true },
40
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 } });
41
31
  }
42
32
  };
43
33
  ProxyRepository = __decorate([
@@ -1,7 +1,7 @@
1
- import { ConfigurationsService } from '../configurations/configurations.service.js';
2
1
  import { CredentialsService } from '../credentials/credentials.service.js';
3
2
  import { EnvironmentsService } from '../environments/environments.service.js';
4
3
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
4
+ import { ProviderStore } from '../integrations/provider-store.js';
5
5
  import { ProxyRepository } from './proxy.repository.js';
6
6
  export interface ProxyRequest {
7
7
  method: string;
@@ -15,21 +15,19 @@ export interface ProxyResult {
15
15
  headers: Headers;
16
16
  body: string;
17
17
  }
18
- /**
19
- * Who the caller says the credential belongs to. One of these, taken from the
20
- * URL: a tenant of the consuming app, or one of its users.
21
- */
18
+ /** What the URL names: which provider, which of its configurations, whose credential. */
22
19
  export interface ProxyTarget {
20
+ provider: string;
23
21
  configurationSlug: string;
24
22
  owner: string;
25
23
  }
26
24
  export declare class ProxyService {
27
- private readonly credentials;
25
+ private readonly proxy;
28
26
  private readonly environments;
29
- private readonly configurations;
27
+ private readonly store;
30
28
  private readonly registry;
31
29
  private readonly resolver;
32
- constructor(credentials: ProxyRepository, environments: EnvironmentsService, configurations: ConfigurationsService, registry: IntegrationRegistry, resolver: CredentialsService);
30
+ constructor(proxy: ProxyRepository, environments: EnvironmentsService, store: ProviderStore, registry: IntegrationRegistry, resolver: CredentialsService);
33
31
  forward(organizationId: string, environmentId: string, target: ProxyTarget, request: ProxyRequest): Promise<ProxyResult>;
34
32
  private buildTargetUrl;
35
33
  }
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.service.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.service.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,qBAAqB,EAAE,MAAM,6CAA6C,CAAC;AACpF,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,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;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC;CACf;AAED,qBACa,YAAY;IAErB,OAAO,CAAC,QAAQ,CAAC,WAAW;IAC5B,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,cAAc;IAC/B,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAJR,WAAW,EAAE,eAAe,EAC5B,YAAY,EAAE,mBAAmB,EACjC,cAAc,EAAE,qBAAqB,EACrC,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;IAqGvB,OAAO,CAAC,cAAc;CAevB"}
1
+ {"version":3,"file":"proxy.service.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.service.ts"],"names":[],"mappings":"AAQA,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;AAoBxD,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;IAsHvB,OAAO,CAAC,cAAc;CAevB"}