@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
@@ -37,6 +37,12 @@ export declare class ConfigurationsService {
37
37
  * reachable from a controller.
38
38
  */
39
39
  getWithCredentials(provider: string, configurationId: string): Promise<ConfigurationWithCredentials>;
40
+ /**
41
+ * Refuses a URL the server would later be made to fetch from inside its own
42
+ * network. Checked when saved so an operator sees why, and again on every
43
+ * proxied call, since what a hostname resolves to can change.
44
+ */
45
+ private checkedFields;
40
46
  /**
41
47
  * Seals the whole credential set as one blob, so the shape is the auth
42
48
  * type's business rather than the schema's: an OAuth2 provider stores a
@@ -1 +1 @@
1
- {"version":3,"file":"configurations.service.d.ts","sourceRoot":"","sources":["../../src/configurations/configurations.service.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EACL,aAAa,EACb,KAAK,qBAAqB,EAC1B,KAAK,2BAA2B,EACjC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AAChF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AAEhF,kFAAkF;AAClF,MAAM,MAAM,sBAAsB,GAAG,2BAA2B,GAAG;IACjE,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,wEAAwE;AACxE,MAAM,WAAW,4BAA4B;IAC3C,aAAa,EAAE,qBAAqB,CAAC;IACrC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACtC;AAED,qBACa,qBAAqB;IAE9B,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAHR,KAAK,EAAE,aAAa,EACpB,YAAY,EAAE,mBAAmB,EACjC,MAAM,EAAE,aAAa,EACrB,QAAQ,EAAE,mBAAmB;IAGhD;;;;;OAKG;IACG,IAAI,CACR,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,GACpB,OAAO,CAAC,sBAAsB,EAAE,CAAC;IAkB9B,GAAG,CACP,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,EACrB,QAAQ,EAAE,MAAM,EAChB,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,sBAAsB,CAAC;IAc5B,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,EACrB,KAAK,EAAE,sBAAsB,GAC5B,OAAO,CAAC,sBAAsB,CAAC;IAsC5B,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,EACrB,QAAQ,EAAE,MAAM,EAChB,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,sBAAsB,GAC5B,OAAO,CAAC,sBAAsB,CAAC;IAclC,yDAAyD;IACnD,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,EACrB,QAAQ,EAAE,MAAM,EAChB,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,IAAI,CAAC;IAMhB;;;OAGG;IACG,kBAAkB,CACtB,QAAQ,EAAE,MAAM,EAChB,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,4BAA4B,CAAC;IAmBxC;;;;;OAKG;IACH,OAAO,CAAC,eAAe;CAqBxB"}
1
+ {"version":3,"file":"configurations.service.d.ts","sourceRoot":"","sources":["../../src/configurations/configurations.service.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EACL,aAAa,EACb,KAAK,qBAAqB,EAC1B,KAAK,2BAA2B,EACjC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAA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,KAAK,EAAE,sBAAsB,GAC5B,OAAO,CAAC,sBAAsB,CAAC;IAkBlC,yDAAyD;IACnD,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,EACrB,QAAQ,EAAE,MAAM,EAChB,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,IAAI,CAAC;IAMhB;;;OAGG;IACG,kBAAkB,CACtB,QAAQ,EAAE,MAAM,EAChB,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,4BAA4B,CAAC;IAmBxC;;;;OAIG;YACW,aAAa;IAqB3B;;;;;OAKG;IACH,OAAO,CAAC,eAAe;CA2BxB"}
@@ -1,5 +1,6 @@
1
1
  import { __decorate, __metadata } from "tslib";
2
2
  import { BadRequestException, ConflictException, Injectable, NotFoundException, } from '@nestjs/common';
3
+ import { assertPublicHost, assertPublicUrl } from '@kosha-ai/integration-sdk';
3
4
  import { CryptoService } from '../crypto/crypto.service.js';
4
5
  import { EnvironmentsService } from '../environments/environments.service.js';
5
6
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
@@ -59,6 +60,7 @@ let ConfigurationsService = class ConfigurationsService {
59
60
  environmentId,
60
61
  name,
61
62
  slug,
63
+ fields: await this.checkedFields(integration, declaredFields(integration, input.fields, { required: true })),
62
64
  credentials: this.sealCredentials(integration, input.credentials),
63
65
  });
64
66
  return describe(created, integration);
@@ -68,6 +70,7 @@ let ConfigurationsService = class ConfigurationsService {
68
70
  const integration = this.registry.get(provider);
69
71
  const updated = await this.store.updateConfiguration(integration, id, {
70
72
  name: input.name?.trim(),
73
+ fields: await this.checkedFields(integration, declaredFields(integration, input.fields)),
71
74
  credentials: input.credentials
72
75
  ? this.sealCredentials(integration, input.credentials)
73
76
  : undefined,
@@ -95,6 +98,30 @@ let ConfigurationsService = class ConfigurationsService {
95
98
  : {},
96
99
  };
97
100
  }
101
+ /**
102
+ * Refuses a URL the server would later be made to fetch from inside its own
103
+ * network. Checked when saved so an operator sees why, and again on every
104
+ * proxied call, since what a hostname resolves to can change.
105
+ */
106
+ async checkedFields(integration, fields) {
107
+ for (const field of integration.configFields ?? []) {
108
+ const value = fields?.[field.key];
109
+ if (typeof value !== 'string')
110
+ continue;
111
+ if (field.type !== 'url' && field.type !== 'host')
112
+ continue;
113
+ try {
114
+ if (field.type === 'url')
115
+ await assertPublicUrl(value);
116
+ else
117
+ await assertPublicHost(value);
118
+ }
119
+ catch (error) {
120
+ throw new BadRequestException(error instanceof Error ? error.message : `${field.label} is invalid`);
121
+ }
122
+ }
123
+ return fields;
124
+ }
98
125
  /**
99
126
  * Seals the whole credential set as one blob, so the shape is the auth
100
127
  * type's business rather than the schema's: an OAuth2 provider stores a
@@ -103,7 +130,11 @@ let ConfigurationsService = class ConfigurationsService {
103
130
  */
104
131
  sealCredentials(integration, credentials) {
105
132
  const provided = credentials ?? {};
106
- if (integration.auth.type === 'OAUTH2') {
133
+ // False for a provider with no fixed OAuth app to register — e.g. one
134
+ // that discovers its client dynamically per configuration — so there is
135
+ // nothing here for an operator to supply.
136
+ if (integration.auth.type === 'OAUTH2' &&
137
+ integration.auth.requiresClientCredentials !== false) {
107
138
  const missing = ['clientId', 'clientSecret'].filter((key) => !provided[key]);
108
139
  if (missing.length > 0) {
109
140
  throw new BadRequestException(`${integration.key} is an OAuth2 integration and needs ${missing.join(' and ')}`);
@@ -122,6 +153,37 @@ ConfigurationsService = __decorate([
122
153
  IntegrationRegistry])
123
154
  ], ConfigurationsService);
124
155
  export { ConfigurationsService };
156
+ /**
157
+ * The values an operator supplied, checked against what the package declared.
158
+ *
159
+ * A key the package never declared is refused rather than ignored: it would
160
+ * otherwise name a column that does not exist, and the failure would surface
161
+ * as a driver error on insert.
162
+ */
163
+ function declaredFields(integration, supplied, options = {}) {
164
+ const declared = integration.configFields ?? [];
165
+ if (declared.length === 0 && !supplied)
166
+ return undefined;
167
+ const known = new Set(declared.map((field) => field.key));
168
+ const unknown = Object.keys(supplied ?? {}).filter((key) => !known.has(key));
169
+ if (unknown.length > 0) {
170
+ throw new BadRequestException(`${integration.key} declares no field named ${unknown.join(' or ')}`);
171
+ }
172
+ const fields = {};
173
+ for (const field of declared) {
174
+ const value = supplied?.[field.key];
175
+ if (value === undefined || value === '') {
176
+ // On create a required field must be there; on update, absent means
177
+ // "leave what is stored".
178
+ if (options.required && field.required) {
179
+ throw new BadRequestException(`${field.label} is required`);
180
+ }
181
+ continue;
182
+ }
183
+ fields[field.key] = value;
184
+ }
185
+ return Object.keys(fields).length > 0 ? fields : undefined;
186
+ }
125
187
  /**
126
188
  * The provider and its auth type come from the registry rather than from the
127
189
  * row: both are facts about the installed package, and a copy in the database
@@ -3,5 +3,6 @@ export declare class CreateConfigurationDto {
3
3
  name: string;
4
4
  slug?: string;
5
5
  credentials?: Record<string, unknown>;
6
+ fields?: Record<string, unknown>;
6
7
  }
7
8
  //# sourceMappingURL=create-configuration.dto.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-configuration.dto.d.ts","sourceRoot":"","sources":["../../../src/configurations/dto/create-configuration.dto.ts"],"names":[],"mappings":"AASA,qBAAa,sBAAsB;IAQjC,QAAQ,EAAG,MAAM,CAAC;IAMlB,IAAI,EAAG,MAAM,CAAC;IAUd,IAAI,CAAC,EAAE,MAAM,CAAC;IASd,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC"}
1
+ {"version":3,"file":"create-configuration.dto.d.ts","sourceRoot":"","sources":["../../../src/configurations/dto/create-configuration.dto.ts"],"names":[],"mappings":"AASA,qBAAa,sBAAsB;IAQjC,QAAQ,EAAG,MAAM,CAAC;IAMlB,IAAI,EAAG,MAAM,CAAC;IAUd,IAAI,CAAC,EAAE,MAAM,CAAC;IASd,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAStC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC"}
@@ -6,6 +6,7 @@ export class CreateConfigurationDto {
6
6
  name;
7
7
  slug;
8
8
  credentials;
9
+ fields;
9
10
  }
10
11
  __decorate([
11
12
  ApiProperty({
@@ -42,3 +43,12 @@ __decorate([
42
43
  IsObject(),
43
44
  __metadata("design:type", Object)
44
45
  ], CreateConfigurationDto.prototype, "credentials", void 0);
46
+ __decorate([
47
+ ApiPropertyOptional({
48
+ description: 'What this provider declares in configFields, by key. Not secret: these become columns on its own table.',
49
+ example: { subdomain: 'acme' },
50
+ }),
51
+ IsOptional(),
52
+ IsObject(),
53
+ __metadata("design:type", Object)
54
+ ], CreateConfigurationDto.prototype, "fields", void 0);
@@ -1,5 +1,6 @@
1
1
  export declare class UpdateConfigurationDto {
2
2
  name?: string;
3
3
  credentials?: Record<string, unknown>;
4
+ fields?: Record<string, unknown>;
4
5
  }
5
6
  //# sourceMappingURL=update-configuration.dto.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"update-configuration.dto.d.ts","sourceRoot":"","sources":["../../../src/configurations/dto/update-configuration.dto.ts"],"names":[],"mappings":"AASA,qBAAa,sBAAsB;IAMjC,IAAI,CAAC,EAAE,MAAM,CAAC;IAOd,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC"}
1
+ {"version":3,"file":"update-configuration.dto.d.ts","sourceRoot":"","sources":["../../../src/configurations/dto/update-configuration.dto.ts"],"names":[],"mappings":"AASA,qBAAa,sBAAsB;IAMjC,IAAI,CAAC,EAAE,MAAM,CAAC;IAOd,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAStC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC"}
@@ -4,6 +4,7 @@ import { IsObject, IsOptional, IsString, MaxLength, MinLength, } from 'class-val
4
4
  export class UpdateConfigurationDto {
5
5
  name;
6
6
  credentials;
7
+ fields;
7
8
  }
8
9
  __decorate([
9
10
  ApiPropertyOptional({ example: 'GitHub' }),
@@ -21,3 +22,12 @@ __decorate([
21
22
  IsObject(),
22
23
  __metadata("design:type", Object)
23
24
  ], UpdateConfigurationDto.prototype, "credentials", void 0);
25
+ __decorate([
26
+ ApiPropertyOptional({
27
+ description: 'What this provider declares in configFields, by key. Not secret: these become columns on its own table.',
28
+ example: { subdomain: 'acme' },
29
+ }),
30
+ IsOptional(),
31
+ IsObject(),
32
+ __metadata("design:type", Object)
33
+ ], UpdateConfigurationDto.prototype, "fields", void 0);
@@ -2,8 +2,9 @@ import { type UserSession } from '@thallesp/nestjs-better-auth';
2
2
  import type { Response } from 'express';
3
3
  import { type ApiKeyRequest } from '../auth/api-key.guard.js';
4
4
  import { ConnectService } from './connect.service.js';
5
+ import { ConnectWithCredentialDto } from './dto/connect-credential.dto.js';
5
6
  import { CreateConnectSessionDto } from './dto/create-connect-session.dto.js';
6
- import { CreateTestSessionDto } from './dto/create-test-session.dto.js';
7
+ import { CreateTestSessionDto, TestCredentialDto } from './dto/create-test-session.dto.js';
7
8
  export declare class ConnectController {
8
9
  private readonly connect;
9
10
  private readonly logger;
@@ -15,14 +16,23 @@ export declare class ConnectController {
15
16
  * can authenticate either way.
16
17
  */
17
18
  createSession(request: ApiKeyRequest, body: CreateConnectSessionDto): Promise<import("./connect.service.js").ConnectSessionResult>;
19
+ /**
20
+ * The counterpart for a provider whose end user already holds the key:
21
+ * the app collects it and posts it here, and a connection exists at once.
22
+ */
23
+ connectWithCredential(request: ApiKeyRequest, body: ConnectWithCredentialDto): Promise<import("./connect.service.js").CallbackResult>;
18
24
  /**
19
25
  * Admin-only: runs the same flow with the signed-in admin standing in for an
20
26
  * end user, so an operator can verify a configuration without wiring up
21
27
  * their backend first.
22
28
  */
23
29
  createTestSession(session: UserSession, environmentId: string, body: CreateTestSessionDto): Promise<import("./connect.service.js").ConnectSessionResult>;
30
+ /** The same, for a provider whose credential the operator pastes in. */
31
+ testCredential(session: UserSession, environmentId: string, body: TestCredentialDto): Promise<import("./connect.service.js").CallbackResult>;
24
32
  /** The URL the end user's browser opens. Redirects to the provider. */
25
33
  start(token: string, res: Response): Promise<void>;
34
+ /** A decline at the provider; never fails the response it is answering. */
35
+ private denied;
26
36
  /** Where the provider sends the end user back. */
27
37
  callback(provider: string, code: string | undefined, state: string | undefined, providerError: string | undefined, providerErrorDescription: string | undefined, res: Response): Promise<void>;
28
38
  }
@@ -1 +1 @@
1
- {"version":3,"file":"connect.controller.d.ts","sourceRoot":"","sources":["../../src/connect/connect.controller.ts"],"names":[],"mappings":"AAsBA,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,KAAK,aAAa,EAAgB,MAAM,0BAA0B,CAAC;AAE5E,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AAExE,qBAEa,iBAAiB;IAGhB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAFpC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsC;gBAEhC,OAAO,EAAE,cAAc;IAEpD;;;;;OAKG;IAcH,aAAa,CACJ,OAAO,EAAE,aAAa,EACrB,IAAI,EAAE,uBAAuB;IAevC;;;;OAIG;IAOH,iBAAiB,CACJ,OAAO,EAAE,WAAW,EACP,aAAa,EAAE,MAAM,EACrC,IAAI,EAAE,oBAAoB;IAepC,uEAAuE;IAIjE,KAAK,CAAiB,KAAK,EAAE,MAAM,EAAS,GAAG,EAAE,QAAQ;IAY/D,kDAAkD;IAI5C,QAAQ,CACO,QAAQ,EAAE,MAAM,EACpB,IAAI,EAAE,MAAM,GAAG,SAAS,EACvB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,aAAa,EAAE,MAAM,GAAG,SAAS,E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AM,GAAG,SAAS,EACvB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,aAAa,EAAE,MAAM,GAAG,SAAS,EACrB,wBAAwB,EAAE,MAAM,GAAG,SAAS,EACjE,GAAG,EAAE,QAAQ;CAyDvB"}
@@ -5,9 +5,10 @@ import { ApiBadRequestResponse, ApiCreatedResponse, ApiExcludeEndpoint, ApiOpera
5
5
  import { AllowAnonymous, Session, } from '@thallesp/nestjs-better-auth';
6
6
  import { OrgAuthGuard } from '../auth/api-key.guard.js';
7
7
  import { getActiveOrganizationId } from '../common/active-organization.js';
8
- import { ConnectService } from './connect.service.js';
8
+ import { ConnectFlowEnded, ConnectService, MAX_LOGGED, } from './connect.service.js';
9
+ import { ConnectWithCredentialDto } from './dto/connect-credential.dto.js';
9
10
  import { CreateConnectSessionDto } from './dto/create-connect-session.dto.js';
10
- import { CreateTestSessionDto } from './dto/create-test-session.dto.js';
11
+ import { CreateTestSessionDto, TestCredentialDto, } from './dto/create-test-session.dto.js';
11
12
  let ConnectController = ConnectController_1 = class ConnectController {
12
13
  connect;
13
14
  logger = new Logger(ConnectController_1.name);
@@ -26,6 +27,16 @@ let ConnectController = ConnectController_1 = class ConnectController {
26
27
  }
27
28
  return this.connect.createSession(request.organizationId, request.environmentId, body);
28
29
  }
30
+ /**
31
+ * The counterpart for a provider whose end user already holds the key:
32
+ * the app collects it and posts it here, and a connection exists at once.
33
+ */
34
+ connectWithCredential(request, body) {
35
+ if (!request.environmentId) {
36
+ throw new BadRequestException('This route needs an API key, which is what names the environment');
37
+ }
38
+ return this.connect.connectWithCredential(request.organizationId, request.environmentId, body);
39
+ }
29
40
  /**
30
41
  * Admin-only: runs the same flow with the signed-in admin standing in for an
31
42
  * end user, so an operator can verify a configuration without wiring up
@@ -40,6 +51,16 @@ let ConnectController = ConnectController_1 = class ConnectController {
40
51
  redirectUrl: body?.redirectUrl,
41
52
  });
42
53
  }
54
+ /** The same, for a provider whose credential the operator pastes in. */
55
+ testCredential(session, environmentId, body) {
56
+ return this.connect.connectWithCredential(getActiveOrganizationId(session), environmentId, {
57
+ externalUserId: `kosha-admin:${session.user.id}`,
58
+ provider: body.provider,
59
+ configurationId: body?.configurationId,
60
+ configurationSlug: body?.slug,
61
+ credential: body.credential,
62
+ });
63
+ }
43
64
  /** The URL the end user's browser opens. Redirects to the provider. */
44
65
  async start(token, res) {
45
66
  try {
@@ -47,18 +68,36 @@ let ConnectController = ConnectController_1 = class ConnectController {
47
68
  }
48
69
  catch (error) {
49
70
  this.logger.warn(`Connect start rejected: ${error instanceof Error ? error.message : error}`);
71
+ if (error instanceof ConnectFlowEnded &&
72
+ redirectBack(res, error.redirectUrl, error.status)) {
73
+ return;
74
+ }
50
75
  // Deliberately vague to the browser: this URL is handed to end users.
51
76
  res.status(400).send('This connect link is invalid or has expired.');
52
77
  }
53
78
  }
79
+ /** A decline at the provider; never fails the response it is answering. */
80
+ async denied(provider, state, reason) {
81
+ try {
82
+ return await this.connect.deny(provider, state, reason);
83
+ }
84
+ catch (error) {
85
+ this.logger.warn(`Connect denial for ${JSON.stringify(provider.slice(0, MAX_LOGGED))} not recorded: ${error instanceof Error ? error.message : error}`);
86
+ return null;
87
+ }
88
+ }
54
89
  /** Where the provider sends the end user back. */
55
90
  async callback(provider, code, state, providerError, providerErrorDescription, res) {
56
91
  if (providerError || providerErrorDescription) {
57
- res
58
- .status(400)
59
- .send(providerErrorDescription ??
60
- providerError ??
61
- 'Provider denied access.');
92
+ const reason = [providerError, providerErrorDescription]
93
+ .filter(Boolean)
94
+ .join(': ');
95
+ const ended = await this.denied(provider, state, reason);
96
+ if (ended && redirectBack(res, ended.redirectUrl, ended.status))
97
+ return;
98
+ // A fixed message: the provider's own text arrives in the query string,
99
+ // and echoing it would let anyone put markup on Kosha's origin.
100
+ res.status(400).send('The provider did not grant access.');
62
101
  return;
63
102
  }
64
103
  if (!code || !state) {
@@ -67,16 +106,16 @@ let ConnectController = ConnectController_1 = class ConnectController {
67
106
  }
68
107
  try {
69
108
  const { redirectUrl } = await this.connect.handleCallback(provider, code, state);
70
- if (redirectUrl) {
71
- const url = new URL(redirectUrl);
72
- url.searchParams.set('kosha_status', 'success');
73
- res.redirect(url.toString());
109
+ if (redirectBack(res, redirectUrl, 'success'))
74
110
  return;
75
- }
76
111
  res.send('Connected. You can close this window.');
77
112
  }
78
113
  catch (error) {
79
- this.logger.warn(`Connect callback failed for "${provider}": ${error instanceof Error ? error.message : error}`);
114
+ this.logger.warn(`Connect callback failed for ${JSON.stringify(provider.slice(0, MAX_LOGGED))}: ${error instanceof Error ? error.message : error}`);
115
+ if (error instanceof ConnectFlowEnded &&
116
+ redirectBack(res, error.redirectUrl, error.status)) {
117
+ return;
118
+ }
80
119
  // A conflict is worth saying out loud: somebody is already connected,
81
120
  // and the end user can do something about it. Everything else stays
82
121
  // vague, since this URL is reached by a browser we do not trust.
@@ -111,6 +150,25 @@ __decorate([
111
150
  __metadata("design:paramtypes", [Object, CreateConnectSessionDto]),
112
151
  __metadata("design:returntype", void 0)
113
152
  ], ConnectController.prototype, "createSession", null);
153
+ __decorate([
154
+ Post('credential'),
155
+ AllowAnonymous(),
156
+ UseGuards(OrgAuthGuard),
157
+ ApiSecurity('x-api-key'),
158
+ ApiOperation({
159
+ summary: 'Connect one of the app’s users with a credential they hold',
160
+ description: 'For a provider with no redirect. The credential is checked against the provider before anything is stored.',
161
+ }),
162
+ ApiCreatedResponse({ description: 'The connection that was created.' }),
163
+ ApiBadRequestResponse({
164
+ description: 'The provider rejected the credential, or it was incomplete.',
165
+ }),
166
+ __param(0, Req()),
167
+ __param(1, Body()),
168
+ __metadata("design:type", Function),
169
+ __metadata("design:paramtypes", [Object, ConnectWithCredentialDto]),
170
+ __metadata("design:returntype", void 0)
171
+ ], ConnectController.prototype, "connectWithCredential", null);
114
172
  __decorate([
115
173
  Post('sessions/test/:environmentId'),
116
174
  ApiOperation({
@@ -124,6 +182,19 @@ __decorate([
124
182
  __metadata("design:paramtypes", [Object, String, CreateTestSessionDto]),
125
183
  __metadata("design:returntype", void 0)
126
184
  ], ConnectController.prototype, "createTestSession", null);
185
+ __decorate([
186
+ Post('credential/test/:environmentId'),
187
+ ApiOperation({
188
+ summary: 'Connect as the signed-in admin with a pasted credential',
189
+ description: 'For verifying a configuration before the consuming app is wired up.',
190
+ }),
191
+ __param(0, Session()),
192
+ __param(1, Param('environmentId')),
193
+ __param(2, Body()),
194
+ __metadata("design:type", Function),
195
+ __metadata("design:paramtypes", [Object, String, TestCredentialDto]),
196
+ __metadata("design:returntype", void 0)
197
+ ], ConnectController.prototype, "testCredential", null);
127
198
  __decorate([
128
199
  Get(':token/start'),
129
200
  AllowAnonymous(),
@@ -154,3 +225,21 @@ ConnectController = ConnectController_1 = __decorate([
154
225
  __metadata("design:paramtypes", [ConnectService])
155
226
  ], ConnectController);
156
227
  export { ConnectController };
228
+ /**
229
+ * Sends the person back to the app with how the connect flow ended. False when
230
+ * there is nowhere valid to send them, so the caller answers itself.
231
+ */
232
+ function redirectBack(res, redirectUrl, status) {
233
+ if (!redirectUrl)
234
+ return false;
235
+ let url;
236
+ try {
237
+ url = new URL(redirectUrl);
238
+ }
239
+ catch {
240
+ return false;
241
+ }
242
+ url.searchParams.set('kosha_status', status);
243
+ res.redirect(url.toString());
244
+ return true;
245
+ }
@@ -17,6 +17,11 @@ export interface ConnectState {
17
17
  /** PKCE, present only once the authorization URL has been built. */
18
18
  codeVerifier?: string;
19
19
  }
20
+ /** A single-use row, and whether it had outlived its window when taken. */
21
+ export interface TakenFlow {
22
+ flow: ConnectState;
23
+ expired: boolean;
24
+ }
20
25
  export interface StoreCredentialInput {
21
26
  userId: string;
22
27
  /** The provider, which is what Better Auth means by `providerId`. */
@@ -33,9 +38,9 @@ export declare class ConnectRepository {
33
38
  private readonly prisma;
34
39
  constructor(prisma: PrismaService);
35
40
  putSession(token: string, state: ConnectState, expiresAt: Date): Promise<void>;
36
- takeSession(token: string): Promise<ConnectState | null>;
41
+ takeSession(token: string): Promise<TakenFlow | null>;
37
42
  putState(state: string, payload: ConnectState, expiresAt: Date): Promise<void>;
38
- takeState(state: string): Promise<ConnectState | null>;
43
+ takeState(state: string): Promise<TakenFlow | null>;
39
44
  /** Nothing else sweeps these, so the connect flow has to. */
40
45
  deleteExpired(now?: Date): Promise<number>;
41
46
  /**
@@ -56,6 +61,10 @@ export declare class ConnectRepository {
56
61
  /** Rewritten on refresh: a provider may report a different grant. */
57
62
  scope?: string | null;
58
63
  }): Promise<Account>;
64
+ /**
65
+ * An expired row is still handed back, flagged, so the person can be sent
66
+ * back to the app rather than left on a Kosha error page.
67
+ */
59
68
  private take;
60
69
  }
61
70
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"connect.repository.d.ts","sourceRoot":"","sources":["../../src/connect/connect.repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,mDAAmD;IACnD,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,oEAAoE;IACpE,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AASD,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAC;IACjB,6CAA6C;IAC7C,SAAS,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,WAAW,EAAE,MAAM,CAAC;IACpB,oBAAoB,EAAE,IAAI,GAAG,IAAI,CAAC;IAClC,uEAAuE;IACvE,KAAK,EAAE,MAA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AM,GACrB,MAAM,CAER;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,eAAe,EAAE,MAAM,EACvB,KAAK,EAAE,MAAM,GACZ,MAAM,CAGR"}
1
+ {"version":3,"file":"connect.repository.d.ts","sourceRoot":"","sources":["../../src/connect/connect.repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,mDAAmD;IACnD,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,oEAAoE;IACpE,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,2EAA2E;AAC3E,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,YAAY,CAAC;IACnB,OAAO,EAAE,OAAO,CAAC;CAClB;AASD,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAC;IACjB,6CAA6C;IAC7C,SAAS,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,WAAW,EAAE,MAAM,CAAC;IACpB,oBAAoB,EAAE,IAAI,GAAG,IAAI,CAAC;IAClC,uEAAuE;IACvE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAED,qBACa,iBAAiB;IAChB,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAE5C,UAAU,CACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,YAAY,EACnB,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ConnectRepository {
91
91
  updateCredential(id, changes) {
92
92
  return this.prisma.account.update({ where: { id }, data: changes });
93
93
  }
94
+ /**
95
+ * An expired row is still handed back, flagged, so the person can be sent
96
+ * back to the app rather than left on a Kosha error page.
97
+ */
94
98
  async take(identifier) {
95
99
  const row = await this.prisma.verification.findFirst({
96
100
  where: { identifier },
@@ -100,9 +104,10 @@ let ConnectRepository = class ConnectRepository {
100
104
  // Burnt before any network work, so a replayed callback cannot mint a
101
105
  // second credential.
102
106
  await this.prisma.verification.delete({ where: { id: row.id } });
103
- if (row.expiresAt < new Date())
104
- return null;
105
- return JSON.parse(row.value);
107
+ return {
108
+ flow: JSON.parse(row.value),
109
+ expired: row.expiresAt < new Date(),
110
+ };
106
111
  }
107
112
  };
108
113
  ConnectRepository = __decorate([
@@ -5,7 +5,9 @@ import { EnvironmentsService } from '../environments/environments.service.js';
5
5
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
6
6
  import { ProviderStore } from '../integrations/provider-store.js';
7
7
  import { ConnectRepository } from './connect.repository.js';
8
+ import type { ConnectWithCredentialDto } from './dto/connect-credential.dto.js';
8
9
  import type { CreateConnectSessionDto } from './dto/create-connect-session.dto.js';
10
+ export declare const MAX_LOGGED = 500;
9
11
  export interface ConnectSessionResult {
10
12
  token: string;
11
13
  connectUrl: string;
@@ -15,6 +17,15 @@ export interface CallbackResult {
15
17
  connectionId: string;
16
18
  redirectUrl: string | null;
17
19
  }
20
+ /**
21
+ * A connect flow that ended without a credential, carrying where the person
22
+ * should be sent back to and why.
23
+ */
24
+ export declare class ConnectFlowEnded extends Error {
25
+ readonly status: 'denied' | 'expired';
26
+ readonly redirectUrl: string | null;
27
+ constructor(status: 'denied' | 'expired', redirectUrl: string | null);
28
+ }
18
29
  /**
19
30
  * Drives the OAuth handshake that turns an end user's consent into a stored,
20
31
  * encrypted credential.
@@ -42,8 +53,44 @@ export declare class ConnectService {
42
53
  * across the redirect.
43
54
  */
44
55
  buildAuthorizationRedirect(token: string): Promise<string>;
56
+ /**
57
+ * Gives a provider whose endpoints and client are not known until an
58
+ * operator supplies a URL a chance to discover and register them, once per
59
+ * configuration. Persisted onto the configuration so refresh — which has no
60
+ * redirect to carry fresh discovery across — reads the same thing back.
61
+ */
62
+ private prepareClient;
63
+ /**
64
+ * The person declined at the provider. Burns the state, so the flow cannot
65
+ * be completed afterwards, and says where to send them. A state from another
66
+ * provider's flow has nowhere to send them; one past its window is expired.
67
+ *
68
+ * The provider's reason is logged, never sent back: it is the only trace of
69
+ * a misconfigured provider, and the flow names where it happened. Both it
70
+ * and the provider come from the request, so they are logged quoted.
71
+ */
72
+ deny(provider: string, state: string | undefined, reason: string): Promise<ConnectFlowEnded>;
45
73
  /** Handles the provider's redirect back to Kosha. */
46
74
  handleCallback(provider: string, code: string, state: string): Promise<CallbackResult>;
75
+ /**
76
+ * Creates a connection from a credential the end user already holds.
77
+ *
78
+ * The counterpart to the redirect flow: no connect session, no state to
79
+ * burn, no callback. The consuming app collects the key from its own user
80
+ * and posts it here, so that person needs no Kosha login and Kosha still
81
+ * owns the secret.
82
+ *
83
+ * The key is proved before anything is written, because a key that cannot
84
+ * name its own account is not one this connection can use.
85
+ */
86
+ connectWithCredential(organizationId: string, environmentId: string, input: ConnectWithCredentialDto): Promise<CallbackResult>;
87
+ /**
88
+ * Asks the provider who the key belongs to, which is the only check
89
+ * available and the right one.
90
+ *
91
+ * The provider's own message is withheld, because it can echo the key back.
92
+ */
93
+ private proveCredential;
47
94
  /**
48
95
  * Writes the credential, refusing when one is already there.
49
96
  *
@@ -1 +1 @@
1
- {"version":3,"file":"connect.service.d.ts","sourceRoot":"","sources":["../../src/connect/connect.service.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAoB,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAC5E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAOrE,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAA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