@kosha-ai/server 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) 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 +58 -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/integrations/client-context.d.ts +20 -0
  32. package/dist/integrations/client-context.d.ts.map +1 -0
  33. package/dist/integrations/client-context.js +23 -0
  34. package/dist/integrations/integrations.controller.d.ts +4 -0
  35. package/dist/integrations/integrations.controller.d.ts.map +1 -1
  36. package/dist/integrations/integrations.controller.js +2 -0
  37. package/dist/integrations/provider-store.d.ts +8 -2
  38. package/dist/integrations/provider-store.d.ts.map +1 -1
  39. package/dist/integrations/provider-store.js +82 -14
  40. package/dist/proxy/proxy.controller.d.ts +9 -1
  41. package/dist/proxy/proxy.controller.d.ts.map +1 -1
  42. package/dist/proxy/proxy.controller.js +34 -10
  43. package/dist/proxy/proxy.service.d.ts.map +1 -1
  44. package/dist/proxy/proxy.service.js +39 -4
  45. package/package.json +4 -4
@@ -1,9 +1,10 @@
1
1
  var CredentialsService_1;
2
2
  import { __decorate, __metadata, __param } from "tslib";
3
- import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
3
+ import { ForbiddenException, Injectable, Logger, UnauthorizedException, } from '@nestjs/common';
4
4
  import { Inject } from '@nestjs/common';
5
5
  import { KOSHA_CONFIG } from '../config/tokens.js';
6
- import { ENVELOPE_VERSION, expiryOf, } from '../crypto/credential-envelope.js';
6
+ import { clientContextFor } from '../integrations/client-context.js';
7
+ import { ENVELOPE_VERSION, expiryOf, storedSecondaryToken, } from '../crypto/credential-envelope.js';
7
8
  import { CryptoService } from '../crypto/crypto.service.js';
8
9
  import { CredentialsRepository } from './credentials.repository.js';
9
10
  let CredentialsService = CredentialsService_1 = class CredentialsService {
@@ -24,11 +25,16 @@ let CredentialsService = CredentialsService_1 = class CredentialsService {
24
25
  * the whole consent flow again for a token the provider was willing to
25
26
  * renew.
26
27
  */
27
- async resolve(account, integration, configuration) {
28
+ async resolve(account, integration, configuration, tokenKind) {
28
29
  if (!account.accessToken) {
29
30
  throw new UnauthorizedException('Connection has no stored credential');
30
31
  }
31
32
  const envelope = this.crypto.openEnvelope(account.accessToken);
33
+ // The integration lists its primary token first; any other kind is a
34
+ // secondary one stored beside it.
35
+ if (tokenKind && tokenKind !== integration.auth.tokenKinds?.[0]) {
36
+ return this.resolveSecondary(account, integration, configuration, envelope, tokenKind);
37
+ }
32
38
  const expiresAt = expiryOf(envelope);
33
39
  const expired = expiresAt !== null && expiresAt <= new Date();
34
40
  if (!expired)
@@ -38,35 +44,23 @@ let CredentialsService = CredentialsService_1 = class CredentialsService {
38
44
  if (!canRefresh) {
39
45
  throw new UnauthorizedException('Connection token expired; the end user must reconnect');
40
46
  }
41
- return this.refresh(account, integration, configuration, refreshToken);
47
+ return this.refresh(account, integration, configuration, refreshToken, envelope.type === 'oauth2' ? envelope : undefined);
42
48
  }
43
- async refresh(account, integration, configuration, refreshToken) {
44
- const credentials = this.openCredentials(configuration);
49
+ async refresh(account, integration, configuration, refreshToken, previous) {
45
50
  try {
46
- const tokens = await integration.auth.refresh?.({
47
- client: {
48
- clientId: String(credentials['clientId'] ?? ''),
49
- clientSecret: String(credentials['clientSecret'] ?? ''),
50
- redirectUri: this.callbackUrlFor(integration.key),
51
- // The refresh_token grant carries no scope; the provider returns
52
- // whatever the original consent granted.
53
- scopes: [],
54
- },
55
- refreshToken,
56
- });
57
- if (!tokens)
58
- throw new Error('Refresh returned no tokens');
51
+ const tokens = await this.requestRefresh(integration, configuration, refreshToken);
59
52
  const envelope = {
60
53
  v: ENVELOPE_VERSION,
61
54
  type: 'oauth2',
62
55
  accessToken: tokens.accessToken,
63
- ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),
56
+ refreshToken: tokens.refreshToken ?? refreshToken,
64
57
  ...(tokens.tokenType ? { tokenType: tokens.tokenType } : {}),
65
58
  ...(tokens.expiresInSeconds
66
59
  ? {
67
60
  expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000).toISOString(),
68
61
  }
69
62
  : {}),
63
+ ...carriedSecondary(previous),
70
64
  };
71
65
  const expiresAt = expiryOf(envelope);
72
66
  await this.credentials.replaceEnvelope(account.id, this.crypto.sealEnvelope(envelope), expiresAt, tokens.scope ?? undefined);
@@ -74,14 +68,72 @@ let CredentialsService = CredentialsService_1 = class CredentialsService {
74
68
  return this.usable(envelope, expiresAt, true);
75
69
  }
76
70
  catch (error) {
77
- this.logger.warn(`Refresh failed for ${integration.key}: ${error instanceof Error ? error.message : error}`);
78
- throw new UnauthorizedException('Connection token expired and could not be refreshed; the end user must reconnect');
71
+ throw this.refreshFailed(integration, error);
72
+ }
73
+ }
74
+ /**
75
+ * A secondary token expires and refreshes on its own, with its own refresh
76
+ * token. Renewing it leaves the primary, and its expiry, as they were.
77
+ */
78
+ async resolveSecondary(account, integration, configuration, envelope, tokenKind) {
79
+ const credential = envelope.type === 'oauth2' ? envelope.secondary?.[tokenKind] : undefined;
80
+ if (envelope.type !== 'oauth2' || !credential) {
81
+ throw new ForbiddenException(`Connection has no ${tokenKind} token`);
82
+ }
83
+ const parsed = credential.expiresAt ? new Date(credential.expiresAt) : null;
84
+ const expiresAt = parsed && !Number.isNaN(parsed.getTime()) ? parsed : null;
85
+ if (!expiresAt || expiresAt > new Date()) {
86
+ return {
87
+ accessToken: credential.accessToken,
88
+ tokenType: credential.tokenType ?? null,
89
+ expiresAt,
90
+ refreshed: false,
91
+ };
92
+ }
93
+ if (!credential.refreshToken || !integration.auth.refresh) {
94
+ throw new UnauthorizedException(`Connection ${tokenKind} token expired; the end user must reconnect`);
95
+ }
96
+ try {
97
+ const tokens = await this.requestRefresh(integration, configuration, credential.refreshToken);
98
+ const renewed = storedSecondaryToken(tokens);
99
+ await this.credentials.replaceEnvelope(account.id, this.crypto.sealEnvelope({
100
+ ...envelope,
101
+ secondary: { ...envelope.secondary, [tokenKind]: renewed },
102
+ }), expiryOf(envelope));
103
+ // No onTokenRefreshed here: the hook is handed tokens with nothing to
104
+ // say which kind they are, so a listener would take them for the primary.
105
+ return {
106
+ accessToken: renewed.accessToken,
107
+ tokenType: renewed.tokenType ?? null,
108
+ expiresAt: renewed.expiresAt ? new Date(renewed.expiresAt) : null,
109
+ refreshed: true,
110
+ };
111
+ }
112
+ catch (error) {
113
+ throw this.refreshFailed(integration, error);
79
114
  }
80
115
  }
81
- /** Where the provider sends the end user back. */
82
- callbackUrlFor(provider) {
83
- const { publicUrl, globalPrefix } = this.config.server;
84
- return `${publicUrl}/${globalPrefix}/connect/callback/${provider}`;
116
+ /** The refresh_token grant, for whichever stored token is being renewed. */
117
+ async requestRefresh(integration, configuration, refreshToken) {
118
+ const tokens = await integration.auth.refresh?.({
119
+ client: clientContextFor({
120
+ integration,
121
+ configuration,
122
+ credentials: this.openCredentials(configuration),
123
+ server: this.config.server,
124
+ // The refresh_token grant carries no scope; the provider returns
125
+ // whatever the original consent granted.
126
+ scopes: [],
127
+ }),
128
+ refreshToken,
129
+ });
130
+ if (!tokens)
131
+ throw new Error('Refresh returned no tokens');
132
+ return tokens;
133
+ }
134
+ refreshFailed(integration, error) {
135
+ this.logger.warn(`Refresh failed for ${integration.key}: ${error instanceof Error ? error.message : error}`);
136
+ return new UnauthorizedException('Connection token expired and could not be refreshed; the end user must reconnect');
85
137
  }
86
138
  openCredentials(configuration) {
87
139
  if (!configuration.credentials)
@@ -109,6 +161,15 @@ let CredentialsService = CredentialsService_1 = class CredentialsService {
109
161
  expiresAt: null,
110
162
  refreshed,
111
163
  };
164
+ // Encoded here rather than in the package: `authHeaders` is handed one
165
+ // string, and base64("user:pass") is what Basic auth puts on the wire.
166
+ case 'basic':
167
+ return {
168
+ accessToken: Buffer.from(`${envelope.username}:${envelope.password}`).toString('base64'),
169
+ tokenType: 'Basic',
170
+ expiresAt: null,
171
+ refreshed,
172
+ };
112
173
  case 'app':
113
174
  return {
114
175
  accessToken: envelope.installationId,
@@ -144,3 +205,7 @@ CredentialsService = CredentialsService_1 = __decorate([
144
205
  CredentialsRepository, Object])
145
206
  ], CredentialsService);
146
207
  export { CredentialsService };
208
+ /** A refresh replaces the primary token. Secondary tokens stay as they were. */
209
+ function carriedSecondary(previous) {
210
+ return previous?.secondary ? { secondary: previous.secondary } : {};
211
+ }
@@ -10,6 +10,24 @@ export declare const ENVELOPE_VERSION = 1;
10
10
  interface Versioned {
11
11
  v: typeof ENVELOPE_VERSION;
12
12
  }
13
+ /** A token beyond the primary one, from the same exchange. */
14
+ export interface OAuth2SecondaryToken {
15
+ accessToken: string;
16
+ refreshToken?: string;
17
+ tokenType?: string;
18
+ /** ISO 8601. */
19
+ expiresAt?: string;
20
+ /** What the provider granted for this token. */
21
+ scope?: string;
22
+ }
23
+ /** A secondary token as the envelope stores it, from what the provider sent. */
24
+ export declare function storedSecondaryToken(token: {
25
+ accessToken: string;
26
+ refreshToken?: string;
27
+ tokenType?: string;
28
+ expiresInSeconds?: number;
29
+ scope?: string;
30
+ }): OAuth2SecondaryToken;
13
31
  /** A token pair from an authorization-code flow. */
14
32
  export interface OAuth2Envelope extends Versioned {
15
33
  type: 'oauth2';
@@ -18,12 +36,20 @@ export interface OAuth2Envelope extends Versioned {
18
36
  tokenType?: string;
19
37
  /** ISO 8601. Mirrored into `account.accessTokenExpiresAt` on write. */
20
38
  expiresAt?: string;
39
+ /** The exchange's other tokens, by kind. The primary is not repeated here. */
40
+ secondary?: Record<string, OAuth2SecondaryToken>;
21
41
  }
22
42
  /** A key the end user pasted, such as Apollo's. */
23
43
  export interface ApiKeyEnvelope extends Versioned {
24
44
  type: 'api_key';
25
45
  key: string;
26
46
  }
47
+ /** A username and password the end user supplied, for an API behind Basic auth. */
48
+ export interface BasicEnvelope extends Versioned {
49
+ type: 'basic';
50
+ username: string;
51
+ password: string;
52
+ }
27
53
  /** A GitHub App install: tokens are minted per call from the installation. */
28
54
  export interface AppEnvelope extends Versioned {
29
55
  type: 'app';
@@ -36,7 +62,7 @@ export interface AppEnvelope extends Versioned {
36
62
  export interface ClientCredentialsEnvelope extends Versioned {
37
63
  type: 'oauth2_cc';
38
64
  }
39
- export type CredentialEnvelope = OAuth2Envelope | ApiKeyEnvelope | AppEnvelope | ClientCredentialsEnvelope;
65
+ export type CredentialEnvelope = OAuth2Envelope | ApiKeyEnvelope | BasicEnvelope | AppEnvelope | ClientCredentialsEnvelope;
40
66
  export type CredentialEnvelopeType = CredentialEnvelope['type'];
41
67
  export declare class InvalidEnvelopeError extends Error {
42
68
  constructor(reason: string);
@@ -1 +1 @@
1
- {"version":3,"file":"credential-envelope.d.ts","sourceRoot":"","sources":["../../src/crypto/credential-envelope.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAElC,UAAU,SAAS;IACjB,CAAC,EAAE,OAAO,gBAAgB,CAAC;CAC5B;AAED,oDAAoD;AACpD,MAAM,WAAW,cAAe,SAAQ,SAAS;IAC/C,IAAI,EAAE,QAAQ,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,uEAAuE;IACvE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,mDAAmD;AACnD,MAAM,WAAW,cAAe,SAAQ,SAAS;IAC/C,IAAI,EAAE,SAAS,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACb;AAED,8EAA8E;AAC9E,MAAM,WAAW,WAAY,SAAQ,SAAS;IAC5C,IAAI,EAAE,KAAK,CAAC;IACZ,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,yBAA0B,SAAQ,SAAS;IAC1D,IAAI,EAAE,WAAW,CAAC;CACnB;AAED,MAAM,MAAM,kBAAkB,GAC5B,cAAc,GAAG,cAAc,GAAG,WAAW,GAAG,yBAAyB,CAAC;AAE5E,MAAM,MAAM,sBAAsB,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;AAEhE,qBAAa,oBAAqB,SAAQ,KAAK;gBACjC,MAAM,EAAE,MAAM;CAI3B;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,CA6C9D;AAED;;;GAGG;AACH,wBAAgB,QAAQ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;AACnF,MAAM,WAAW,aAAc,SAAQ,SAAS;IAC9C,IAAI,EAAE,OAAO,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,8EAA8E;AAC9E,MAAM,WAAW,WAAY,SAAQ,SAAS;IAC5C,IAAI,EAAE,KAAK,CAAC;IACZ,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,yBAA0B,SAAQ,SAAS;IAC1D,IAAI,EAAE,WAAW,CAAC;CACnB;AAED,MAAM,MAAM,kBAAkB,GAC1B,cAAc,GACd,cAAc,GACd,aAAa,GACb,WAAW,GACX,yBAAyB,CAAC;AAE9B,MAAM,MAAM,sBAAsB,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;AAEhE,qBAAa,oBAAqB,SAAQ,KAAK;gBACjC,MAAM,EAAE,MAAM;CAI3B;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,CA2D9D;AAED;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,QAAQ,EAAE,kBAAkB,GAAG,IAAI,GAAG,IAAI,CAKlE"}
@@ -7,6 +7,20 @@
7
7
  * different fields needs no migration.
8
8
  */
9
9
  export const ENVELOPE_VERSION = 1;
10
+ /** A secondary token as the envelope stores it, from what the provider sent. */
11
+ export function storedSecondaryToken(token) {
12
+ return {
13
+ accessToken: token.accessToken,
14
+ ...(token.refreshToken ? { refreshToken: token.refreshToken } : {}),
15
+ ...(token.tokenType ? { tokenType: token.tokenType } : {}),
16
+ ...(token.scope ? { scope: token.scope } : {}),
17
+ ...(token.expiresInSeconds
18
+ ? {
19
+ expiresAt: new Date(Date.now() + token.expiresInSeconds * 1000).toISOString(),
20
+ }
21
+ : {}),
22
+ };
23
+ }
10
24
  export class InvalidEnvelopeError extends Error {
11
25
  constructor(reason) {
12
26
  super(`Stored credential is unusable: ${reason}`);
@@ -38,12 +52,25 @@ export function parseEnvelope(json) {
38
52
  if (!isNonEmptyString(envelope.accessToken)) {
39
53
  throw new InvalidEnvelopeError('oauth2 envelope has no accessToken');
40
54
  }
55
+ assertSecondary(envelope.secondary);
41
56
  return envelope;
42
57
  case 'api_key':
43
58
  if (!isNonEmptyString(envelope.key)) {
44
59
  throw new InvalidEnvelopeError('api_key envelope has no key');
45
60
  }
46
61
  return envelope;
62
+ case 'basic': {
63
+ const basic = envelope;
64
+ // A blank password is a real choice for some APIs; a blank username is
65
+ // not, since the header would then carry nothing identifying.
66
+ if (!isNonEmptyString(basic.username)) {
67
+ throw new InvalidEnvelopeError('basic envelope has no username');
68
+ }
69
+ if (typeof basic.password !== 'string') {
70
+ throw new InvalidEnvelopeError('basic envelope has no password');
71
+ }
72
+ return basic;
73
+ }
47
74
  case 'app':
48
75
  if (!isNonEmptyString(envelope.installationId)) {
49
76
  throw new InvalidEnvelopeError('app envelope has no installationId');
@@ -68,3 +95,19 @@ export function expiryOf(envelope) {
68
95
  function isNonEmptyString(value) {
69
96
  return typeof value === 'string' && value.length > 0;
70
97
  }
98
+ function assertSecondary(secondary) {
99
+ if (secondary === undefined)
100
+ return;
101
+ if (typeof secondary !== 'object' ||
102
+ secondary === null ||
103
+ Array.isArray(secondary)) {
104
+ throw new InvalidEnvelopeError('oauth2 secondary must be an object');
105
+ }
106
+ for (const [kind, credential] of Object.entries(secondary)) {
107
+ if (!credential ||
108
+ typeof credential !== 'object' ||
109
+ !isNonEmptyString(credential.accessToken)) {
110
+ throw new InvalidEnvelopeError(`oauth2 secondary.${kind} has no accessToken`);
111
+ }
112
+ }
113
+ }
@@ -0,0 +1,20 @@
1
+ import type { KoshaIntegration, OAuthClientContext } from '@kosha-ai/integration-sdk';
2
+ import type { ResolvedKoshaConfig } from '../config/kosha-config.js';
3
+ import type { ProviderConfiguration } from './provider-store.js';
4
+ /**
5
+ * What a package is given to talk to its provider, built from one
6
+ * configuration.
7
+ *
8
+ * One builder for connecting and for refreshing. They were two, and drifted:
9
+ * a refresh that omits something a connect passes fails only once the first
10
+ * token expires, which is long after anyone is watching.
11
+ */
12
+ export declare function clientContextFor(args: {
13
+ integration: KoshaIntegration;
14
+ configuration: ProviderConfiguration;
15
+ credentials: Record<string, unknown>;
16
+ server: ResolvedKoshaConfig['server'];
17
+ /** The refresh_token grant carries none; the provider returns what it granted. */
18
+ scopes: string[];
19
+ }): OAuthClientContext;
20
+ //# sourceMappingURL=client-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-context.d.ts","sourceRoot":"","sources":["../../src/integrations/client-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,kBAAkB,EACnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAEjE;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE;IACrC,WAAW,EAAE,gBAAgB,CAAC;IAC9B,aAAa,EAAE,qBAAqB,CAAC;IACrC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,MAAM,EAAE,mBAAmB,CAAC,QAAQ,CAAC,CAAC;IACtC,kFAAkF;IAClF,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB,GAAG,kBAAkB,CAerB"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * What a package is given to talk to its provider, built from one
3
+ * configuration.
4
+ *
5
+ * One builder for connecting and for refreshing. They were two, and drifted:
6
+ * a refresh that omits something a connect passes fails only once the first
7
+ * token expires, which is long after anyone is watching.
8
+ */
9
+ export function clientContextFor(args) {
10
+ const { publicUrl, globalPrefix } = args.server;
11
+ const secret = args.credentials['clientSecret'];
12
+ return {
13
+ clientId: String(args.credentials['clientId'] ?? ''),
14
+ // Absent rather than '': a provider that issued no secret can reject a
15
+ // request that carries one.
16
+ clientSecret: typeof secret === 'string' ? secret : '',
17
+ redirectUri: `${publicUrl}/${globalPrefix}/connect/callback/${args.integration.key}`,
18
+ scopes: args.scopes,
19
+ // The package's own columns, for a provider whose endpoints are not
20
+ // knowable from the package alone.
21
+ fields: args.configuration.fields,
22
+ };
23
+ }
@@ -17,6 +17,10 @@ export interface IntegrationSummary {
17
17
  /** What this integration asks for. What an operator must grant. */
18
18
  scopesRequested: string[];
19
19
  pkce: boolean;
20
+ /** False for a provider with no OAuth app, so a configuration needs no client id. */
21
+ requiresClientCredentials: boolean;
22
+ /** What the end user supplies, for a provider whose credential they already hold. */
23
+ credentialFields: NonNullable<KoshaIntegration['auth']['credentialFields']>;
20
24
  configFields: NonNullable<KoshaIntegration['configFields']>;
21
25
  supportsWebhooks: boolean;
22
26
  }
@@ -1 +1 @@
1
- {"version":3,"file":"integrations.controller.d.ts","sourceRoot":"","sources":["../../src/integrations/integrations.controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,+EAA+E;IAC/E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,mEAAmE;IACnE,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,OAAO,CAAC;IACd,YAAY,EAAE,WAAW,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAAC,CAAC;IAC5D,gBAAgB,EAAE,OAAO,CAAC;CAC3B;AAED,qBACa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAAR,QAAQ,EAAE,mBAAmB;IAG1D,IAAI,IAAI,kBAAkB,EAAE;IAK5B,GAAG,CAAe,GAAG,EAAE,MAAM,GAAG,kBAAkB;CAGnD"}
1
+ {"version":3,"file":"integrations.controller.d.ts","sourceRoot":"","sources":["../../src/integrations/integrations.controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,+EAA+E;IAC/E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,mEAAmE;IACnE,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,OAAO,CAAC;IACd,qFAAqF;IACrF,yBAAyB,EAAE,OAAO,CAAC;IACnC,qFAAqF;IACrF,gBAAgB,EAAE,WAAW,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;IAC5E,YAAY,EAAE,WAAW,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAAC,CAAC;IAC5D,gBAAgB,EAAE,OAAO,CAAC;CAC3B;AAED,qBACa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAAR,QAAQ,EAAE,mBAAmB;IAG1D,IAAI,IAAI,kBAAkB,EAAE;IAK5B,GAAG,CAAe,GAAG,EAAE,MAAM,GAAG,kBAAkB;CAGnD"}
@@ -42,6 +42,8 @@ function toSummary(integration) {
42
42
  scopesAvailable: integration.auth.scopesAvailable,
43
43
  scopesRequested: integration.auth.scopesRequested,
44
44
  pkce: integration.auth.pkce,
45
+ requiresClientCredentials: integration.auth.requiresClientCredentials ?? true,
46
+ credentialFields: integration.auth.credentialFields ?? [],
45
47
  configFields: integration.configFields ?? [],
46
48
  supportsWebhooks: Boolean(integration.webhooks),
47
49
  };
@@ -1,9 +1,9 @@
1
1
  import { type OnApplicationBootstrap } from '@nestjs/common';
2
- import type { KoshaIntegration } from '@kosha-ai/integration-sdk';
2
+ import type { ConfigurationFields, KoshaIntegration } from '@kosha-ai/integration-sdk';
3
3
  import { Prisma } from '../generated/prisma/client.js';
4
4
  import { PrismaService } from '../prisma/prisma.service.js';
5
5
  import { IntegrationRegistry } from './integration.registry.js';
6
- /** The columns every provider's configuration table has. Nothing provider-specific is ever one. */
6
+ /** The columns every provider's configuration table has. */
7
7
  export interface ProviderConfiguration {
8
8
  id: string;
9
9
  environmentId: string;
@@ -13,6 +13,8 @@ export interface ProviderConfiguration {
13
13
  credentials: string | null;
14
14
  createdAt: Date;
15
15
  updatedAt: Date;
16
+ /** Whatever else this provider's own table holds, by column name. */
17
+ fields: ConfigurationFields;
16
18
  }
17
19
  /** A configuration as a client may see it: everything but the secrets. */
18
20
  export type PublicProviderConfiguration = Omit<ProviderConfiguration, 'credentials'>;
@@ -29,12 +31,16 @@ export interface CreateConfiguration {
29
31
  environmentId: string;
30
32
  name: string;
31
33
  slug: string;
34
+ /** This provider's own columns, already checked against its configFields. */
35
+ fields?: ConfigurationFields;
32
36
  credentials?: string | null;
33
37
  }
34
38
  /** Only what is given is written; anything absent is left alone. */
35
39
  export interface UpdateConfiguration {
36
40
  name?: string;
37
41
  credentials?: string | null;
42
+ /** Only the columns given are written; the rest keep what they hold. */
43
+ fields?: ConfigurationFields;
38
44
  }
39
45
  export interface StoreConnection {
40
46
  accountId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"provider-store.d.ts","sourceRoot":"","sources":["../../src/integrations/provider-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,sBAAsB,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SAAS,gBAAgB,EAAE,GACxC,OAAO,CAAC,MAAM,EAAE,CAAC;IAwBpB,OAAO,CAAC,KAAK;IAOb,OAAO,CAAC,IAAI;CAMb"}
@@ -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
@@ -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,EAA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