@kosha-ai/server 0.2.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 (116) 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 +24 -36
  9. package/dist/configurations/configurations.service.d.ts.map +1 -1
  10. package/dist/configurations/configurations.service.js +71 -151
  11. package/dist/configurations/dto/create-configuration.dto.d.ts +1 -2
  12. package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -1
  13. package/dist/configurations/dto/create-configuration.dto.js +2 -12
  14. package/dist/configurations/dto/update-configuration.dto.d.ts +0 -2
  15. package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -1
  16. package/dist/configurations/dto/update-configuration.dto.js +1 -17
  17. package/dist/connect/connect.controller.d.ts +1 -1
  18. package/dist/connect/connect.controller.d.ts.map +1 -1
  19. package/dist/connect/connect.controller.js +7 -6
  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 +23 -23
  23. package/dist/connect/connect.repository.d.ts.map +1 -1
  24. package/dist/connect/connect.repository.js +37 -49
  25. package/dist/connect/connect.service.d.ts +7 -8
  26. package/dist/connect/connect.service.d.ts.map +1 -1
  27. package/dist/connect/connect.service.js +54 -51
  28. package/dist/connect/dto/create-connect-session.dto.d.ts +1 -1
  29. package/dist/connect/dto/create-connect-session.dto.d.ts.map +1 -1
  30. package/dist/connect/dto/create-connect-session.dto.js +7 -8
  31. package/dist/connect/dto/create-test-session.dto.d.ts +1 -0
  32. package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -1
  33. package/dist/connect/dto/create-test-session.dto.js +10 -3
  34. package/dist/connections/connections.controller.d.ts +4 -3
  35. package/dist/connections/connections.controller.d.ts.map +1 -1
  36. package/dist/connections/connections.controller.js +13 -11
  37. package/dist/connections/connections.repository.d.ts +24 -17
  38. package/dist/connections/connections.repository.d.ts.map +1 -1
  39. package/dist/connections/connections.repository.js +21 -43
  40. package/dist/connections/connections.service.d.ts +48 -13
  41. package/dist/connections/connections.service.d.ts.map +1 -1
  42. package/dist/connections/connections.service.js +111 -32
  43. package/dist/connections/dto/list-connections.dto.d.ts +3 -1
  44. package/dist/connections/dto/list-connections.dto.d.ts.map +1 -1
  45. package/dist/connections/dto/list-connections.dto.js +26 -4
  46. package/dist/connections/environment-connections.controller.d.ts +4 -3
  47. package/dist/connections/environment-connections.controller.d.ts.map +1 -1
  48. package/dist/connections/environment-connections.controller.js +14 -12
  49. package/dist/credentials/credentials.module.d.ts.map +1 -1
  50. package/dist/credentials/credentials.module.js +0 -2
  51. package/dist/credentials/credentials.repository.d.ts +5 -2
  52. package/dist/credentials/credentials.repository.d.ts.map +1 -1
  53. package/dist/credentials/credentials.repository.js +10 -3
  54. package/dist/credentials/credentials.service.d.ts +8 -4
  55. package/dist/credentials/credentials.service.d.ts.map +1 -1
  56. package/dist/credentials/credentials.service.js +27 -16
  57. package/dist/egress/egress.listener.d.ts +1 -3
  58. package/dist/egress/egress.listener.d.ts.map +1 -1
  59. package/dist/egress/egress.listener.js +3 -7
  60. package/dist/egress/egress.repository.d.ts +13 -6
  61. package/dist/egress/egress.repository.d.ts.map +1 -1
  62. package/dist/egress/egress.repository.js +31 -44
  63. package/dist/generated/prisma/browser.d.ts +0 -5
  64. package/dist/generated/prisma/browser.d.ts.map +1 -1
  65. package/dist/generated/prisma/client.d.ts +0 -5
  66. package/dist/generated/prisma/client.d.ts.map +1 -1
  67. package/dist/generated/prisma/commonInputTypes.d.ts +0 -55
  68. package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -1
  69. package/dist/generated/prisma/internal/class.d.ts +0 -11
  70. package/dist/generated/prisma/internal/class.d.ts.map +1 -1
  71. package/dist/generated/prisma/internal/class.js +4 -4
  72. package/dist/generated/prisma/internal/prismaNamespace.d.ts +1 -114
  73. package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
  74. package/dist/generated/prisma/internal/prismaNamespace.js +2 -29
  75. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +0 -30
  76. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
  77. package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +2 -29
  78. package/dist/generated/prisma/models/Account.d.ts +26 -344
  79. package/dist/generated/prisma/models/Account.d.ts.map +1 -1
  80. package/dist/generated/prisma/models/Environment.d.ts +0 -258
  81. package/dist/generated/prisma/models/Environment.d.ts.map +1 -1
  82. package/dist/generated/prisma/models/User.d.ts +2 -60
  83. package/dist/generated/prisma/models/User.d.ts.map +1 -1
  84. package/dist/generated/prisma/models.d.ts +0 -1
  85. package/dist/generated/prisma/models.d.ts.map +1 -1
  86. package/dist/index.d.ts +1 -2
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/integrations/integrations.controller.d.ts +2 -0
  89. package/dist/integrations/integrations.controller.d.ts.map +1 -1
  90. package/dist/integrations/integrations.controller.js +1 -0
  91. package/dist/integrations/integrations.module.d.ts.map +1 -1
  92. package/dist/integrations/integrations.module.js +3 -1
  93. package/dist/integrations/provider-store.d.ts +104 -0
  94. package/dist/integrations/provider-store.d.ts.map +1 -0
  95. package/dist/integrations/provider-store.js +234 -0
  96. package/dist/proxy/proxy.controller.d.ts +9 -5
  97. package/dist/proxy/proxy.controller.d.ts.map +1 -1
  98. package/dist/proxy/proxy.controller.js +18 -13
  99. package/dist/proxy/proxy.module.d.ts.map +1 -1
  100. package/dist/proxy/proxy.module.js +1 -2
  101. package/dist/proxy/proxy.repository.d.ts +11 -14
  102. package/dist/proxy/proxy.repository.d.ts.map +1 -1
  103. package/dist/proxy/proxy.repository.js +17 -27
  104. package/dist/proxy/proxy.service.d.ts +6 -8
  105. package/dist/proxy/proxy.service.d.ts.map +1 -1
  106. package/dist/proxy/proxy.service.js +34 -28
  107. package/package.json +4 -4
  108. package/prisma/migrations/{20260929101936_init → 20261008090000_init}/migration.sql +5 -58
  109. package/prisma/schema.prisma +2 -43
  110. package/dist/configurations/configurations.repository.d.ts +0 -43
  111. package/dist/configurations/configurations.repository.d.ts.map +0 -1
  112. package/dist/configurations/configurations.repository.js +0 -76
  113. package/dist/generated/prisma/models/Configuration.d.ts +0 -1385
  114. package/dist/generated/prisma/models/Configuration.d.ts.map +0 -1
  115. package/dist/generated/prisma/models/Configuration.js +0 -1
  116. package/prisma/migrations/20260930102529_connection_config/migration.sql +0 -2
@@ -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
+ }
@@ -5,17 +5,21 @@ 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, owner: string): Promise<void>;
13
17
  }
14
18
  /**
15
19
  * Recovers the upstream path from the raw URL rather than the parsed route
16
20
  * params, so the provider receives the caller's encoding untouched.
17
21
  */
18
- export declare function splitUpstreamTarget(originalUrl: string, configurationSlug: string, owner: string): {
22
+ export declare function splitUpstreamTarget(originalUrl: string, provider: string, configurationSlug: string, owner: string): {
19
23
  path: string;
20
24
  query: string;
21
25
  };
@@ -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":"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"}
@@ -19,16 +19,20 @@ 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
+ async forward(request, response, provider, configurationSlug, owner) {
27
31
  if (!request.environmentId) {
28
32
  throw new BadRequestException('This route needs an API key, which is what names the environment');
29
33
  }
30
- const { path, query } = splitUpstreamTarget(request.originalUrl, configurationSlug, owner);
31
- const result = await this.proxy.forward(request.organizationId, request.environmentId, { configurationSlug, owner }, {
34
+ const { path, query } = splitUpstreamTarget(request.originalUrl, provider, configurationSlug, owner);
35
+ const result = await this.proxy.forward(request.organizationId, request.environmentId, { provider, configurationSlug, owner }, {
32
36
  method: request.method,
33
37
  path,
34
38
  query,
@@ -45,20 +49,21 @@ let ProxyController = class ProxyController {
45
49
  }
46
50
  };
47
51
  __decorate([
48
- All(':configurationSlug/:owner/*path'),
52
+ All(':provider/:configurationSlug/:owner/*path'),
49
53
  AllowAnonymous(),
50
54
  UseGuards(ApiKeyGuard),
51
55
  ApiSecurity('x-api-key'),
52
56
  ApiOperation({
53
57
  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.',
58
+ description: 'The environment comes from the API key. `owner` is the app’s own id for the person who connected.',
55
59
  }),
56
60
  __param(0, Req()),
57
61
  __param(1, Res()),
58
- __param(2, Param('configurationSlug')),
59
- __param(3, Param('owner')),
62
+ __param(2, Param('provider')),
63
+ __param(3, Param('configurationSlug')),
64
+ __param(4, Param('owner')),
60
65
  __metadata("design:type", Function),
61
- __metadata("design:paramtypes", [Object, Object, String, String]),
66
+ __metadata("design:paramtypes", [Object, Object, String, String, String]),
62
67
  __metadata("design:returntype", Promise)
63
68
  ], ProxyController.prototype, "forward", null);
64
69
  ProxyController = __decorate([
@@ -71,8 +76,8 @@ export { ProxyController };
71
76
  * Recovers the upstream path from the raw URL rather than the parsed route
72
77
  * params, so the provider receives the caller's encoding untouched.
73
78
  */
74
- export function splitUpstreamTarget(originalUrl, configurationSlug, owner) {
75
- const marker = `/${configurationSlug}/${owner}/`;
79
+ export function splitUpstreamTarget(originalUrl, provider, configurationSlug, owner) {
80
+ const marker = `/${provider}/${configurationSlug}/${owner}/`;
76
81
  const markerIndex = originalUrl.indexOf(marker);
77
82
  const rest = markerIndex >= 0 ? originalUrl.slice(markerIndex + marker.length) : '';
78
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":"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,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AC,WAAW,CAAC;IAyGvB,OAAO,CAAC,cAAc;CAevB"}
@@ -1,9 +1,9 @@
1
1
  import { __decorate, __metadata } from "tslib";
2
2
  import { BadGatewayException, Injectable, NotFoundException, } from '@nestjs/common';
3
- import { ConfigurationsService } from '../configurations/configurations.service.js';
4
3
  import { CredentialsService } from '../credentials/credentials.service.js';
5
4
  import { EnvironmentsService } from '../environments/environments.service.js';
6
5
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
6
+ import { ProviderStore } from '../integrations/provider-store.js';
7
7
  import { ProxyRepository } from './proxy.repository.js';
8
8
  /**
9
9
  * Never forwarded upstream: hop-by-hop framing headers, and anything carrying
@@ -21,35 +21,41 @@ const STRIPPED_REQUEST_HEADERS = new Set([
21
21
  'x-api-key',
22
22
  ]);
23
23
  let ProxyService = class ProxyService {
24
- credentials;
24
+ proxy;
25
25
  environments;
26
- configurations;
26
+ store;
27
27
  registry;
28
28
  resolver;
29
- constructor(credentials, environments, configurations, registry, resolver) {
30
- this.credentials = credentials;
29
+ constructor(proxy, environments, store, registry, resolver) {
30
+ this.proxy = proxy;
31
31
  this.environments = environments;
32
- this.configurations = configurations;
32
+ this.store = store;
33
33
  this.registry = registry;
34
34
  this.resolver = resolver;
35
35
  }
36
36
  async forward(organizationId, environmentId, target, request) {
37
37
  const environment = await this.environments.get(organizationId, environmentId);
38
- const configuration = await this.configurations.getBySlug(environment.id, target.configurationSlug);
39
- if (!configuration.isEnabled) {
40
- throw new NotFoundException('Configuration is disabled');
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) {
50
+ throw new NotFoundException('Connection not found');
41
51
  }
42
- // The owner string is whatever the app calls its tenant or its user, and
43
- // Kosha cannot tell which. A tenant-owned credential wins when both match,
44
- // since that is the shared one.
45
- const account = (await this.credentials.findCredential(environment.id, environment.slug, configuration.id, { organizationExternalId: target.owner })) ??
46
- (await this.credentials.findCredential(environment.id, environment.slug, configuration.id, { externalUserId: target.owner }));
47
- // Deliberately the same answer as a wrong environment or a wrong tenant:
48
- // a caller learns nothing about what exists elsewhere.
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);
49
56
  if (!account)
50
57
  throw new NotFoundException('Connection not found');
51
- const integration = this.registry.get(configuration.integrationKey);
52
- const credential = await this.resolver.resolve(account, integration);
58
+ const credential = await this.resolver.resolve(account, integration, configuration);
53
59
  const baseUrl = integration.api.resolveBaseUrl?.({
54
60
  credential: {
55
61
  accessToken: credential.accessToken,
@@ -59,7 +65,7 @@ let ProxyService = class ProxyService {
59
65
  // A provider with no fixed host builds its base URL from this — every
60
66
  // Jira path carries a cloudId — so passing nothing made those
61
67
  // providers unreachable by construction.
62
- metadata: asMetadata(account.connectionConfig),
68
+ metadata: asMetadata(connection.metadata),
63
69
  }) ?? integration.api.baseUrl;
64
70
  if (!baseUrl) {
65
71
  throw new BadGatewayException('Provider has no resolvable base URL for this connection');
@@ -118,20 +124,20 @@ ProxyService = __decorate([
118
124
  Injectable(),
119
125
  __metadata("design:paramtypes", [ProxyRepository,
120
126
  EnvironmentsService,
121
- ConfigurationsService,
127
+ ProviderStore,
122
128
  IntegrationRegistry,
123
129
  CredentialsService])
124
130
  ], ProxyService);
125
131
  export { ProxyService };
126
132
  /**
127
- * A connection's stored config is free-form JSON, so it may be an array, a
128
- * number or null. Only an object is a config bag; anything else is treated as
129
- * absent rather than handed to an integration that expects to index it.
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.
130
136
  */
131
- function asMetadata(connectionConfig) {
132
- return connectionConfig !== null &&
133
- typeof connectionConfig === 'object' &&
134
- !Array.isArray(connectionConfig)
135
- ? connectionConfig
137
+ function asMetadata(metadata) {
138
+ return metadata !== null &&
139
+ typeof metadata === 'object' &&
140
+ !Array.isArray(metadata)
141
+ ? metadata
136
142
  : undefined;
137
143
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kosha-ai/server",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Kosha server: OAuth handshake, encrypted credential storage, token refresh, and an authenticated request proxy for third-party integrations",
5
5
  "keywords": [
6
6
  "kosha",
@@ -109,7 +109,7 @@
109
109
  "rxjs": "^7.8.0",
110
110
  "tslib": "^2.3.0",
111
111
  "zod": "4.5.4",
112
- "@kosha-ai/integration-sdk": "0.2.0"
112
+ "@kosha-ai/integration-sdk": "0.3.0"
113
113
  },
114
114
  "devDependencies": {
115
115
  "@nestjs/testing": "^11.0.0",
@@ -117,7 +117,7 @@
117
117
  "@types/node-forge": "^1.3.14",
118
118
  "@types/pg": "^8.23.1",
119
119
  "prisma": "^7.10.0",
120
- "@kosha-ai/integration-github": "0.2.0",
121
- "@kosha-ai/integration-slack": "0.2.0"
120
+ "@kosha-ai/integration-github": "0.3.0",
121
+ "@kosha-ai/integration-slack": "0.3.0"
122
122
  }
123
123
  }