@kosha-ai/server 0.3.0 → 0.4.1

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 (65) hide show
  1. package/dist/configurations/configurations.service.d.ts +6 -0
  2. package/dist/configurations/configurations.service.d.ts.map +1 -1
  3. package/dist/configurations/configurations.service.js +63 -1
  4. package/dist/configurations/dto/create-configuration.dto.d.ts +1 -0
  5. package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -1
  6. package/dist/configurations/dto/create-configuration.dto.js +10 -0
  7. package/dist/configurations/dto/update-configuration.dto.d.ts +1 -0
  8. package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -1
  9. package/dist/configurations/dto/update-configuration.dto.js +10 -0
  10. package/dist/connect/connect.controller.d.ts +11 -1
  11. package/dist/connect/connect.controller.d.ts.map +1 -1
  12. package/dist/connect/connect.controller.js +102 -13
  13. package/dist/connect/connect.repository.d.ts +11 -2
  14. package/dist/connect/connect.repository.d.ts.map +1 -1
  15. package/dist/connect/connect.repository.js +8 -3
  16. package/dist/connect/connect.service.d.ts +47 -0
  17. package/dist/connect/connect.service.d.ts.map +1 -1
  18. package/dist/connect/connect.service.js +269 -28
  19. package/dist/connect/dto/connect-credential.dto.d.ts +8 -0
  20. package/dist/connect/dto/connect-credential.dto.d.ts.map +1 -0
  21. package/dist/connect/dto/connect-credential.dto.js +54 -0
  22. package/dist/connect/dto/create-test-session.dto.d.ts +7 -0
  23. package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -1
  24. package/dist/connect/dto/create-test-session.dto.js +36 -1
  25. package/dist/credentials/credentials.service.d.ts +9 -3
  26. package/dist/credentials/credentials.service.d.ts.map +1 -1
  27. package/dist/credentials/credentials.service.js +91 -26
  28. package/dist/crypto/credential-envelope.d.ts +27 -1
  29. package/dist/crypto/credential-envelope.d.ts.map +1 -1
  30. package/dist/crypto/credential-envelope.js +43 -0
  31. package/dist/egress/host-rules.service.js +2 -2
  32. package/dist/index.d.ts +2 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +2 -0
  35. package/dist/integrations/client-context.d.ts +20 -0
  36. package/dist/integrations/client-context.d.ts.map +1 -0
  37. package/dist/integrations/client-context.js +23 -0
  38. package/dist/integrations/integrations.controller.d.ts +4 -0
  39. package/dist/integrations/integrations.controller.d.ts.map +1 -1
  40. package/dist/integrations/integrations.controller.js +3 -1
  41. package/dist/integrations/provider-store.d.ts +8 -2
  42. package/dist/integrations/provider-store.d.ts.map +1 -1
  43. package/dist/integrations/provider-store.js +82 -14
  44. package/dist/kosha.module.d.ts.map +1 -1
  45. package/dist/kosha.module.js +2 -0
  46. package/dist/proxy/proxy.controller.d.ts +9 -1
  47. package/dist/proxy/proxy.controller.d.ts.map +1 -1
  48. package/dist/proxy/proxy.controller.js +34 -10
  49. package/dist/proxy/proxy.module.d.ts.map +1 -1
  50. package/dist/proxy/proxy.module.js +4 -0
  51. package/dist/proxy/proxy.service.d.ts.map +1 -1
  52. package/dist/proxy/proxy.service.js +44 -4
  53. package/dist/query/dto/run-query.dto.d.ts +5 -0
  54. package/dist/query/dto/run-query.dto.d.ts.map +1 -0
  55. package/dist/query/dto/run-query.dto.js +26 -0
  56. package/dist/query/query.controller.d.ts +15 -0
  57. package/dist/query/query.controller.d.ts.map +1 -0
  58. package/dist/query/query.controller.js +52 -0
  59. package/dist/query/query.module.d.ts +3 -0
  60. package/dist/query/query.module.d.ts.map +1 -0
  61. package/dist/query/query.module.js +19 -0
  62. package/dist/query/query.service.d.ts +32 -0
  63. package/dist/query/query.service.d.ts.map +1 -0
  64. package/dist/query/query.service.js +83 -0
  65. package/package.json +4 -4
@@ -4,6 +4,44 @@ import { randomUUID } from 'node:crypto';
4
4
  import { Prisma } from '../generated/prisma/client.js';
5
5
  import { PrismaService } from '../prisma/prisma.service.js';
6
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
+ }
7
45
  /** Same rule the packages' SQL follows, so both sides derive the same names. */
8
46
  const PREFIX_PATTERN = /^[a-z][a-z0-9_]*$/;
9
47
  /**
@@ -19,7 +57,13 @@ export function tablePrefix(integration) {
19
57
  }
20
58
  const configurationTable = (integration) => Prisma.raw(`"${tablePrefix(integration)}_configuration"`);
21
59
  const connectionTable = (integration) => Prisma.raw(`"${tablePrefix(integration)}_connection"`);
22
- const PUBLIC_COLUMNS = Prisma.raw('id, "environmentId", name, slug, "createdAt", "updatedAt"');
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
+ }
23
67
  /**
24
68
  * `now()` means whatever the database session's timezone says, while Prisma
25
69
  * writes UTC. These are the only writes that bypass Prisma, so they are the
@@ -48,33 +92,34 @@ let ProviderStore = class ProviderStore {
48
92
  }
49
93
  }
50
94
  async listConfigurations(integration, environmentId) {
51
- return this.query(Prisma.sql `
52
- SELECT ${PUBLIC_COLUMNS} FROM ${configurationTable(integration)}
95
+ const rows = await this.query(Prisma.sql `
96
+ SELECT ${ALL_COLUMNS} FROM ${configurationTable(integration)}
53
97
  WHERE "environmentId" = ${environmentId}
54
98
  ORDER BY "createdAt" DESC
55
99
  `);
100
+ return rows.map((row) => withoutCredentials(describeRow(row)));
56
101
  }
57
102
  async findConfigurationById(integration, environmentId, id) {
58
103
  const [row] = await this.query(Prisma.sql `
59
- SELECT ${PUBLIC_COLUMNS} FROM ${configurationTable(integration)}
104
+ SELECT ${ALL_COLUMNS} FROM ${configurationTable(integration)}
60
105
  WHERE id = ${id} AND "environmentId" = ${environmentId}
61
106
  `);
62
- return row ?? null;
107
+ return row ? withoutCredentials(describeRow(row)) : null;
63
108
  }
64
109
  /** How a caller's slug becomes the row the proxy and connect flows use. */
65
110
  async findConfigurationBySlug(integration, environmentId, slug) {
66
111
  const [row] = await this.query(Prisma.sql `
67
- SELECT ${PUBLIC_COLUMNS} FROM ${configurationTable(integration)}
112
+ SELECT ${ALL_COLUMNS} FROM ${configurationTable(integration)}
68
113
  WHERE "environmentId" = ${environmentId} AND slug = ${slug}
69
114
  `);
70
- return row ?? null;
115
+ return row ? withoutCredentials(describeRow(row)) : null;
71
116
  }
72
117
  /** Keeps the secrets, for the connect flow, which resolves by id. */
73
118
  async findConfigurationWithCredentials(integration, id) {
74
119
  const [row] = await this.query(Prisma.sql `
75
120
  SELECT * FROM ${configurationTable(integration)} WHERE id = ${id}
76
121
  `);
77
- return row ?? null;
122
+ return row ? describeRow(row) : null;
78
123
  }
79
124
  /** The same, by slug, so a proxied call resolves in one read. */
80
125
  async findConfigurationBySlugWithCredentials(integration, environmentId, slug) {
@@ -82,19 +127,22 @@ let ProviderStore = class ProviderStore {
82
127
  SELECT * FROM ${configurationTable(integration)}
83
128
  WHERE "environmentId" = ${environmentId} AND slug = ${slug}
84
129
  `);
85
- return row ?? null;
130
+ return row ? describeRow(row) : null;
86
131
  }
87
132
  async createConfiguration(integration, input) {
133
+ const extra = Object.entries(input.fields ?? {});
88
134
  const [row] = await this.query(Prisma.sql `
89
135
  INSERT INTO ${configurationTable(integration)}
90
- (id, "environmentId", name, slug, credentials, "createdAt", "updatedAt")
136
+ (id, "environmentId", name, slug, credentials, "createdAt", "updatedAt"
137
+ ${joinColumns(extra.map(([name]) => name))})
91
138
  VALUES (
92
139
  ${randomUUID()}, ${input.environmentId}, ${input.name}, ${input.slug},
93
140
  ${input.credentials ?? null}, ${NOW}, ${NOW}
141
+ ${joinValues(extra.map(([, value]) => value))}
94
142
  )
95
- RETURNING ${PUBLIC_COLUMNS}
143
+ RETURNING ${ALL_COLUMNS}
96
144
  `);
97
- return required(row, integration, 'insert returned no row');
145
+ return withoutCredentials(describeRow(required(row, integration, 'insert returned no row')));
98
146
  }
99
147
  async updateConfiguration(integration, id, input) {
100
148
  const [row] = await this.query(Prisma.sql `
@@ -103,12 +151,13 @@ let ProviderStore = class ProviderStore {
103
151
  credentials = CASE WHEN ${input.credentials !== undefined}
104
152
  THEN ${input.credentials ?? null} ELSE credentials END,
105
153
  "updatedAt" = ${NOW}
154
+ ${assignments(input.fields ?? {})}
106
155
  WHERE id = ${id}
107
- RETURNING ${PUBLIC_COLUMNS}
156
+ RETURNING ${ALL_COLUMNS}
108
157
  `);
109
158
  if (!row)
110
159
  throw new NotFoundException('Configuration not found');
111
- return row;
160
+ return withoutCredentials(describeRow(row));
112
161
  }
113
162
  /**
114
163
  * Refused while connections still point at it. Counted rather than left to
@@ -226,6 +275,25 @@ function required(row, integration, why) {
226
275
  }
227
276
  return row;
228
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
+ }
229
297
  /** Postgres needs the cast; undefined means "leave it alone", null means SQL null. */
230
298
  function asJson(value) {
231
299
  return value === undefined
@@ -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;AAgB5D;;;;GAIG;AACH,qBACa,WAAW;IACtB,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,WAAW,GAAG,aAAa;CAgCnD"}
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;AAiB5D;;;;GAIG;AACH,qBACa,WAAW;IACtB,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,WAAW,GAAG,aAAa;CAiCnD"}
@@ -17,6 +17,7 @@ import { IntegrationsModule } from './integrations/integrations.module.js';
17
17
  import { PrismaModule } from './prisma/prisma.module.js';
18
18
  import { PrismaService } from './prisma/prisma.service.js';
19
19
  import { ProxyModule } from './proxy/proxy.module.js';
20
+ import { QueryModule } from './query/query.module.js';
20
21
  /**
21
22
  * An app that needs nothing custom never imports this directly — `kosha start`
22
23
  * builds it from `kosha.config.ts`. Apps that add their own controllers import
@@ -44,6 +45,7 @@ let KoshaModule = KoshaModule_1 = class KoshaModule {
44
45
  ConnectionsModule,
45
46
  EnvironmentConnectionsModule,
46
47
  ProxyModule,
48
+ QueryModule,
47
49
  // Only when asked for: the broker opens a second listener, and an app
48
50
  // that has not enabled it should not have one at all.
49
51
  ...(resolved.egress.enabled ? [EgressModule] : []),
@@ -13,8 +13,16 @@ export declare class ProxyController {
13
13
  * provider's table has its own unique index, so a slug is only unique
14
14
  * within one provider.
15
15
  */
16
- forward(request: ApiKeyRequest, response: Response, provider: string, configurationSlug: string, owner: string): Promise<void>;
16
+ forward(request: ApiKeyRequest, response: Response, provider: string, configurationSlug: string, pathOwner: string, headerOwner: string | undefined): Promise<void>;
17
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;
18
26
  /**
19
27
  * Recovers the upstream path from the raw URL rather than the parsed route
20
28
  * params, so the provider receives the caller's encoding untouched.
@@ -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;;;;;;;;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
+ {"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';
@@ -27,11 +27,16 @@ let ProxyController = class ProxyController {
27
27
  * provider's table has its own unique index, so a slug is only unique
28
28
  * within one provider.
29
29
  */
30
- async forward(request, response, provider, 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) {
31
33
  if (!request.environmentId) {
32
34
  throw new BadRequestException('This route needs an API key, which is what names the environment');
33
35
  }
34
- const { path, query } = splitUpstreamTarget(request.originalUrl, provider, 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);
35
40
  const result = await this.proxy.forward(request.organizationId, request.environmentId, { provider, configurationSlug, owner }, {
36
41
  method: request.method,
37
42
  path,
@@ -49,21 +54,27 @@ let ProxyController = class ProxyController {
49
54
  }
50
55
  };
51
56
  __decorate([
52
- All(':provider/:configurationSlug/:owner/*path'),
57
+ All(':provider/:configurationSlug/:owner{/*path}'),
53
58
  AllowAnonymous(),
54
59
  UseGuards(ApiKeyGuard),
55
60
  ApiSecurity('x-api-key'),
56
61
  ApiOperation({
57
62
  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.',
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.',
59
69
  }),
60
70
  __param(0, Req()),
61
71
  __param(1, Res()),
62
72
  __param(2, Param('provider')),
63
73
  __param(3, Param('configurationSlug')),
64
74
  __param(4, Param('owner')),
75
+ __param(5, Headers('x-kosha-owner')),
65
76
  __metadata("design:type", Function),
66
- __metadata("design:paramtypes", [Object, Object, String, String, String]),
77
+ __metadata("design:paramtypes", [Object, Object, String, String, String, Object]),
67
78
  __metadata("design:returntype", Promise)
68
79
  ], ProxyController.prototype, "forward", null);
69
80
  ProxyController = __decorate([
@@ -72,14 +83,27 @@ ProxyController = __decorate([
72
83
  __metadata("design:paramtypes", [ProxyService])
73
84
  ], ProxyController);
74
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
+ }
75
96
  /**
76
97
  * Recovers the upstream path from the raw URL rather than the parsed route
77
98
  * params, so the provider receives the caller's encoding untouched.
78
99
  */
79
100
  export function splitUpstreamTarget(originalUrl, provider, configurationSlug, owner) {
80
- const marker = `/${provider}/${configurationSlug}/${owner}/`;
81
- const markerIndex = originalUrl.indexOf(marker);
82
- const rest = markerIndex >= 0 ? originalUrl.slice(markerIndex + marker.length) : '';
83
- const [path, query = ''] = rest.split('?');
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
+ : '';
84
108
  return { path, query };
85
109
  }
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.module.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.module.ts"],"names":[],"mappings":"AAOA,qBAKa,WAAW;CAAG"}
1
+ {"version":3,"file":"proxy.module.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.module.ts"],"names":[],"mappings":"AAOA,qBASa,WAAW;CAAG"}
@@ -12,6 +12,10 @@ ProxyModule = __decorate([
12
12
  imports: [CredentialsModule, EnvironmentsModule],
13
13
  controllers: [ProxyController],
14
14
  providers: [ProxyService, ProxyRepository],
15
+ // QueryModule reuses this: the two Prisma reads it does (who `owner`
16
+ // names, which account holds the envelope) have nothing proxy-specific
17
+ // about them.
18
+ exports: [ProxyRepository],
15
19
  })
16
20
  ], ProxyModule);
17
21
  export { ProxyModule };
@@ -1 +1 @@
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
+ {"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;IA2HvB,OAAO,CAAC,cAAc;CAevB"}
@@ -1,5 +1,6 @@
1
1
  import { __decorate, __metadata } from "tslib";
2
- import { BadGatewayException, Injectable, NotFoundException, } from '@nestjs/common';
2
+ import { assertPublicUrl } from '@kosha-ai/integration-sdk';
3
+ import { BadGatewayException, BadRequestException, Injectable, NotFoundException, } from '@nestjs/common';
3
4
  import { CredentialsService } from '../credentials/credentials.service.js';
4
5
  import { EnvironmentsService } from '../environments/environments.service.js';
5
6
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
@@ -19,6 +20,8 @@ const STRIPPED_REQUEST_HEADERS = new Set([
19
20
  'authorization',
20
21
  'cookie',
21
22
  'x-api-key',
23
+ 'x-kosha-token-kind',
24
+ 'x-kosha-owner',
22
25
  ]);
23
26
  let ProxyService = class ProxyService {
24
27
  proxy;
@@ -40,6 +43,13 @@ let ProxyService = class ProxyService {
40
43
  const integration = this.registry.find(target.provider);
41
44
  if (!integration)
42
45
  throw new NotFoundException('Connection not found');
46
+ // A query-shaped integration (e.g. a direct database connection) has no
47
+ // REST API to forward to at all; see QueryService for its counterpart.
48
+ if (!integration.api) {
49
+ throw new NotFoundException(`${target.provider} has no HTTP proxy.`);
50
+ }
51
+ // Depends only on the provider, so a bad header is refused before any read.
52
+ const tokenKind = requestedTokenKind(integration, request.headers);
43
53
  // Independent reads, so they go together: the configuration this slug
44
54
  // names, and the person this owner names.
45
55
  const [configuration, userId] = await Promise.all([
@@ -55,8 +65,8 @@ let ProxyService = class ProxyService {
55
65
  const account = await this.proxy.findAccount(connection.accountId);
56
66
  if (!account)
57
67
  throw new NotFoundException('Connection not found');
58
- const credential = await this.resolver.resolve(account, integration, configuration);
59
- const baseUrl = integration.api.resolveBaseUrl?.({
68
+ const credential = await this.resolver.resolve(account, integration, configuration, tokenKind);
69
+ const resolved = integration.api.resolveBaseUrl?.({
60
70
  credential: {
61
71
  accessToken: credential.accessToken,
62
72
  tokenType: credential.tokenType,
@@ -66,10 +76,20 @@ let ProxyService = class ProxyService {
66
76
  // Jira path carries a cloudId — so passing nothing made those
67
77
  // providers unreachable by construction.
68
78
  metadata: asMetadata(connection.metadata),
69
- }) ?? integration.api.baseUrl;
79
+ // And what the operator set up: a self-hosted provider's host is a
80
+ // column on its own configuration, not a fact the package knows.
81
+ fields: configuration.fields,
82
+ });
83
+ // A host the package hardcoded is ours; one resolved from a configuration
84
+ // or a connection was chosen by an operator, so it is checked.
85
+ const baseUrl = resolved ?? integration.api.baseUrl;
70
86
  if (!baseUrl) {
71
87
  throw new BadGatewayException('Provider has no resolvable base URL for this connection');
72
88
  }
89
+ // Re-resolved per call, not only when saved: a host that answered
90
+ // publicly yesterday can point inside the network today.
91
+ if (resolved)
92
+ await assertPublicUrl(baseUrl);
73
93
  const targetUrl = this.buildTargetUrl(baseUrl, request);
74
94
  /*
75
95
  * Header names are compared lowercased, and the integration's headers are
@@ -141,3 +161,23 @@ function asMetadata(metadata) {
141
161
  ? metadata
142
162
  : undefined;
143
163
  }
164
+ /**
165
+ * Which stored token to send. The primary unless `x-kosha-token-kind` names
166
+ * another, and a kind the provider does not issue is refused rather than
167
+ * quietly answered with the primary. The header is stripped before the
168
+ * request leaves Kosha.
169
+ */
170
+ function requestedTokenKind(integration, headers) {
171
+ const raw = headers['x-kosha-token-kind'];
172
+ const kind = (Array.isArray(raw) ? raw[0] : raw)?.trim();
173
+ if (!kind)
174
+ return undefined;
175
+ const kinds = integration.auth?.tokenKinds ?? [];
176
+ if (!kinds.includes(kind)) {
177
+ // Says what would have worked, since the caller has no other way to ask.
178
+ throw new BadRequestException(kinds.length > 0
179
+ ? `${integration.key} issues no "${kind}" token; use one of: ${kinds.join(', ')}`
180
+ : `${integration.key} issues a single token, so x-kosha-token-kind does not apply`);
181
+ }
182
+ return kind;
183
+ }
@@ -0,0 +1,5 @@
1
+ export declare class RunQueryDto {
2
+ sql: string;
3
+ params?: unknown[];
4
+ }
5
+ //# sourceMappingURL=run-query.dto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-query.dto.d.ts","sourceRoot":"","sources":["../../../src/query/dto/run-query.dto.ts"],"names":[],"mappings":"AAGA,qBAAa,WAAW;IAStB,GAAG,EAAG,MAAM,CAAC;IAQb,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;CACpB"}
@@ -0,0 +1,26 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
3
+ import { IsArray, IsOptional, IsString, MinLength } from 'class-validator';
4
+ export class RunQueryDto {
5
+ sql;
6
+ params;
7
+ }
8
+ __decorate([
9
+ ApiProperty({
10
+ example: 'SELECT id, name FROM users WHERE id = $1',
11
+ description: 'Run inside a read-only transaction that is always rolled back — a ' +
12
+ 'write statement is rejected by the database itself.',
13
+ }),
14
+ IsString(),
15
+ MinLength(1),
16
+ __metadata("design:type", String)
17
+ ], RunQueryDto.prototype, "sql", void 0);
18
+ __decorate([
19
+ ApiPropertyOptional({
20
+ example: [42],
21
+ description: 'Positional parameters for the SQL above, e.g. $1, $2.',
22
+ }),
23
+ IsOptional(),
24
+ IsArray(),
25
+ __metadata("design:type", Array)
26
+ ], RunQueryDto.prototype, "params", void 0);
@@ -0,0 +1,15 @@
1
+ import { type ApiKeyRequest } from '../auth/api-key.guard.js';
2
+ import { RunQueryDto } from './dto/run-query.dto.js';
3
+ import { QueryService } from './query.service.js';
4
+ export declare class QueryController {
5
+ private readonly query;
6
+ constructor(query: QueryService);
7
+ /**
8
+ * Addressed the same way `/api/proxy/...` is: the provider, the
9
+ * configuration slug it chose, and its own id for the person. There is no
10
+ * upstream path to reconstruct here — the SQL is the body — so this is
11
+ * simpler than `ProxyController`.
12
+ */
13
+ run(request: ApiKeyRequest, provider: string, configurationSlug: string, owner: string, body: RunQueryDto): Promise<import("@kosha-ai/integration-sdk").QueryResult>;
14
+ }
15
+ //# sourceMappingURL=query.controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.controller.d.ts","sourceRoot":"","sources":["../../src/query/query.controller.ts"],"names":[],"mappings":"AAWA,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,qBAEa,eAAe;IACd,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,YAAY;IAEhD;;;;;OAKG;IAaG,GAAG,CACA,OAAO,EAAE,aAAa,EACV,QAAQ,EAAE,MAAM,EACP,iBAAiB,EAAE,MAAM,EACrC,KAAK,EAAE,MAAM,EACrB,IAAI,EAAE,WAAW;CAe5B"}
@@ -0,0 +1,52 @@
1
+ import { __decorate, __metadata, __param } from "tslib";
2
+ import { BadRequestException, Body, Controller, Param, Post, Req, UseGuards, } from '@nestjs/common';
3
+ import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
4
+ import { AllowAnonymous } from '@thallesp/nestjs-better-auth';
5
+ import { ApiKeyGuard } from '../auth/api-key.guard.js';
6
+ import { RunQueryDto } from './dto/run-query.dto.js';
7
+ import { QueryService } from './query.service.js';
8
+ let QueryController = class QueryController {
9
+ query;
10
+ constructor(query) {
11
+ this.query = query;
12
+ }
13
+ /**
14
+ * Addressed the same way `/api/proxy/...` is: the provider, the
15
+ * configuration slug it chose, and its own id for the person. There is no
16
+ * upstream path to reconstruct here — the SQL is the body — so this is
17
+ * simpler than `ProxyController`.
18
+ */
19
+ async run(request, provider, configurationSlug, owner, body) {
20
+ if (!request.environmentId) {
21
+ throw new BadRequestException('This route needs an API key, which is what names the environment');
22
+ }
23
+ return this.query.run(request.organizationId, request.environmentId, { provider, configurationSlug, owner }, { sql: body.sql, params: body.params });
24
+ }
25
+ };
26
+ __decorate([
27
+ Post(':provider/:configurationSlug/:owner'),
28
+ AllowAnonymous(),
29
+ UseGuards(ApiKeyGuard),
30
+ ApiSecurity('x-api-key'),
31
+ ApiOperation({
32
+ summary: 'Run a read-only query against a connected provider',
33
+ description: 'The environment comes from the API key. `owner` is the app’s own id ' +
34
+ 'for the person who connected. Every call runs inside a read-only ' +
35
+ 'transaction that is always rolled back — a write statement is ' +
36
+ 'rejected by the database itself, not by Kosha parsing the SQL.',
37
+ }),
38
+ __param(0, Req()),
39
+ __param(1, Param('provider')),
40
+ __param(2, Param('configurationSlug')),
41
+ __param(3, Param('owner')),
42
+ __param(4, Body()),
43
+ __metadata("design:type", Function),
44
+ __metadata("design:paramtypes", [Object, String, String, String, RunQueryDto]),
45
+ __metadata("design:returntype", Promise)
46
+ ], QueryController.prototype, "run", null);
47
+ QueryController = __decorate([
48
+ ApiTags('query'),
49
+ Controller('query'),
50
+ __metadata("design:paramtypes", [QueryService])
51
+ ], QueryController);
52
+ export { QueryController };
@@ -0,0 +1,3 @@
1
+ export declare class QueryModule {
2
+ }
3
+ //# sourceMappingURL=query.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.module.d.ts","sourceRoot":"","sources":["../../src/query/query.module.ts"],"names":[],"mappings":"AAOA,qBAOa,WAAW;CAAG"}
@@ -0,0 +1,19 @@
1
+ import { __decorate } from "tslib";
2
+ import { Module } from '@nestjs/common';
3
+ import { CredentialsModule } from '../credentials/credentials.module.js';
4
+ import { EnvironmentsModule } from '../environments/environments.module.js';
5
+ import { ProxyModule } from '../proxy/proxy.module.js';
6
+ import { QueryController } from './query.controller.js';
7
+ import { QueryService } from './query.service.js';
8
+ let QueryModule = class QueryModule {
9
+ };
10
+ QueryModule = __decorate([
11
+ Module({
12
+ // ProxyModule only for its exported ProxyRepository — the two Prisma reads
13
+ // it does are provider-agnostic.
14
+ imports: [CredentialsModule, EnvironmentsModule, ProxyModule],
15
+ controllers: [QueryController],
16
+ providers: [QueryService],
17
+ })
18
+ ], QueryModule);
19
+ export { QueryModule };
@@ -0,0 +1,32 @@
1
+ import type { QueryResult } from '@kosha-ai/integration-sdk';
2
+ import { CredentialsService } from '../credentials/credentials.service.js';
3
+ import { EnvironmentsService } from '../environments/environments.service.js';
4
+ import { IntegrationRegistry } from '../integrations/integration.registry.js';
5
+ import { ProviderStore } from '../integrations/provider-store.js';
6
+ import { ProxyRepository } from '../proxy/proxy.repository.js';
7
+ /** What the URL names: which provider, which of its configurations, whose credential. */
8
+ export interface QueryTarget {
9
+ provider: string;
10
+ configurationSlug: string;
11
+ owner: string;
12
+ }
13
+ export interface QueryRequest {
14
+ sql: string;
15
+ params?: unknown[];
16
+ }
17
+ /**
18
+ * The direct-connection counterpart to `ProxyService`: a query-shaped
19
+ * integration (declares `query`, not `api`) has no REST API to forward an
20
+ * HTTP request to, so the credential is handed to the integration's own
21
+ * `query.run` instead of signing a `fetch`.
22
+ */
23
+ export declare class QueryService {
24
+ private readonly proxy;
25
+ private readonly environments;
26
+ private readonly store;
27
+ private readonly registry;
28
+ private readonly resolver;
29
+ constructor(proxy: ProxyRepository, environments: EnvironmentsService, store: ProviderStore, registry: IntegrationRegistry, resolver: CredentialsService);
30
+ run(organizationId: string, environmentId: string, target: QueryTarget, request: QueryRequest): Promise<QueryResult>;
31
+ }
32
+ //# sourceMappingURL=query.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.service.d.ts","sourceRoot":"","sources":["../../src/query/query.service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAC7D,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,8BAA8B,CAAC;AAE/D,yFAAyF;AACzF,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;CACpB;AAED;;;;;GAKG;AACH,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,GAAG,CACP,cAAc,EAAE,MAAM,EACtB,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,GACpB,OAAO,CAAC,WAAW,CAAC;CAwDxB"}