@kosha-ai/server 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/dist/auth/auth.factory.d.ts.map +1 -1
  2. package/dist/auth/auth.factory.js +0 -5
  3. package/dist/configurations/configurations.controller.d.ts +6 -5
  4. package/dist/configurations/configurations.controller.d.ts.map +1 -1
  5. package/dist/configurations/configurations.controller.js +22 -18
  6. package/dist/configurations/configurations.module.d.ts.map +1 -1
  7. package/dist/configurations/configurations.module.js +1 -2
  8. package/dist/configurations/configurations.service.d.ts +29 -35
  9. package/dist/configurations/configurations.service.d.ts.map +1 -1
  10. package/dist/configurations/configurations.service.js +126 -149
  11. package/dist/configurations/dto/create-configuration.dto.d.ts +2 -2
  12. package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -1
  13. package/dist/configurations/dto/create-configuration.dto.js +6 -6
  14. package/dist/configurations/dto/update-configuration.dto.d.ts +1 -2
  15. package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -1
  16. package/dist/configurations/dto/update-configuration.dto.js +7 -13
  17. package/dist/connect/connect.controller.d.ts +12 -2
  18. package/dist/connect/connect.controller.d.ts.map +1 -1
  19. package/dist/connect/connect.controller.js +108 -18
  20. package/dist/connect/connect.module.d.ts.map +1 -1
  21. package/dist/connect/connect.module.js +1 -2
  22. package/dist/connect/connect.repository.d.ts +34 -25
  23. package/dist/connect/connect.repository.d.ts.map +1 -1
  24. package/dist/connect/connect.repository.js +45 -52
  25. package/dist/connect/connect.service.d.ts +54 -8
  26. package/dist/connect/connect.service.d.ts.map +1 -1
  27. package/dist/connect/connect.service.js +312 -68
  28. package/dist/connect/dto/connect-credential.dto.d.ts +8 -0
  29. package/dist/connect/dto/connect-credential.dto.d.ts.map +1 -0
  30. package/dist/connect/dto/connect-credential.dto.js +54 -0
  31. package/dist/connect/dto/create-connect-session.dto.d.ts +1 -1
  32. package/dist/connect/dto/create-connect-session.dto.d.ts.map +1 -1
  33. package/dist/connect/dto/create-connect-session.dto.js +7 -8
  34. package/dist/connect/dto/create-test-session.dto.d.ts +8 -0
  35. package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -1
  36. package/dist/connect/dto/create-test-session.dto.js +45 -3
  37. package/dist/connections/connections.controller.d.ts +4 -3
  38. package/dist/connections/connections.controller.d.ts.map +1 -1
  39. package/dist/connections/connections.controller.js +13 -11
  40. package/dist/connections/connections.repository.d.ts +24 -17
  41. package/dist/connections/connections.repository.d.ts.map +1 -1
  42. package/dist/connections/connections.repository.js +21 -43
  43. package/dist/connections/connections.service.d.ts +48 -13
  44. package/dist/connections/connections.service.d.ts.map +1 -1
  45. package/dist/connections/connections.service.js +111 -32
  46. package/dist/connections/dto/list-connections.dto.d.ts +3 -1
  47. package/dist/connections/dto/list-connections.dto.d.ts.map +1 -1
  48. package/dist/connections/dto/list-connections.dto.js +26 -4
  49. package/dist/connections/environment-connections.controller.d.ts +4 -3
  50. package/dist/connections/environment-connections.controller.d.ts.map +1 -1
  51. package/dist/connections/environment-connections.controller.js +14 -12
  52. package/dist/credentials/credentials.module.d.ts.map +1 -1
  53. package/dist/credentials/credentials.module.js +0 -2
  54. package/dist/credentials/credentials.repository.d.ts +5 -2
  55. package/dist/credentials/credentials.repository.d.ts.map +1 -1
  56. package/dist/credentials/credentials.repository.js +10 -3
  57. package/dist/credentials/credentials.service.d.ts +14 -4
  58. package/dist/credentials/credentials.service.d.ts.map +1 -1
  59. package/dist/credentials/credentials.service.js +106 -30
  60. package/dist/crypto/credential-envelope.d.ts +27 -1
  61. package/dist/crypto/credential-envelope.d.ts.map +1 -1
  62. package/dist/crypto/credential-envelope.js +43 -0
  63. package/dist/egress/egress.listener.d.ts +1 -3
  64. package/dist/egress/egress.listener.d.ts.map +1 -1
  65. package/dist/egress/egress.listener.js +3 -7
  66. package/dist/egress/egress.repository.d.ts +13 -6
  67. package/dist/egress/egress.repository.d.ts.map +1 -1
  68. package/dist/egress/egress.repository.js +31 -44
  69. package/dist/generated/prisma/browser.d.ts +0 -5
  70. package/dist/generated/prisma/browser.d.ts.map +1 -1
  71. package/dist/generated/prisma/client.d.ts +0 -5
  72. package/dist/generated/prisma/client.d.ts.map +1 -1
  73. package/dist/generated/prisma/commonInputTypes.d.ts +0 -55
  74. package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -1
  75. package/dist/generated/prisma/internal/class.d.ts +0 -11
  76. package/dist/generated/prisma/internal/class.d.ts.map +1 -1
  77. package/dist/generated/prisma/internal/class.js +4 -4
  78. package/dist/generated/prisma/internal/prismaNamespace.d.ts +1 -114
  79. package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
  80. package/dist/generated/prisma/internal/prismaNamespace.js +2 -29
  81. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +0 -30
  82. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
  83. package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +2 -29
  84. package/dist/generated/prisma/models/Account.d.ts +26 -344
  85. package/dist/generated/prisma/models/Account.d.ts.map +1 -1
  86. package/dist/generated/prisma/models/Environment.d.ts +0 -258
  87. package/dist/generated/prisma/models/Environment.d.ts.map +1 -1
  88. package/dist/generated/prisma/models/User.d.ts +2 -60
  89. package/dist/generated/prisma/models/User.d.ts.map +1 -1
  90. package/dist/generated/prisma/models.d.ts +0 -1
  91. package/dist/generated/prisma/models.d.ts.map +1 -1
  92. package/dist/index.d.ts +1 -2
  93. package/dist/index.d.ts.map +1 -1
  94. package/dist/integrations/client-context.d.ts +20 -0
  95. package/dist/integrations/client-context.d.ts.map +1 -0
  96. package/dist/integrations/client-context.js +23 -0
  97. package/dist/integrations/integrations.controller.d.ts +6 -0
  98. package/dist/integrations/integrations.controller.d.ts.map +1 -1
  99. package/dist/integrations/integrations.controller.js +3 -0
  100. package/dist/integrations/integrations.module.d.ts.map +1 -1
  101. package/dist/integrations/integrations.module.js +3 -1
  102. package/dist/integrations/provider-store.d.ts +110 -0
  103. package/dist/integrations/provider-store.d.ts.map +1 -0
  104. package/dist/integrations/provider-store.js +302 -0
  105. package/dist/proxy/proxy.controller.d.ts +17 -5
  106. package/dist/proxy/proxy.controller.d.ts.map +1 -1
  107. package/dist/proxy/proxy.controller.js +46 -17
  108. package/dist/proxy/proxy.module.d.ts.map +1 -1
  109. package/dist/proxy/proxy.module.js +1 -2
  110. package/dist/proxy/proxy.repository.d.ts +11 -14
  111. package/dist/proxy/proxy.repository.d.ts.map +1 -1
  112. package/dist/proxy/proxy.repository.js +17 -27
  113. package/dist/proxy/proxy.service.d.ts +6 -8
  114. package/dist/proxy/proxy.service.d.ts.map +1 -1
  115. package/dist/proxy/proxy.service.js +72 -31
  116. package/package.json +4 -4
  117. package/prisma/migrations/{20260929101936_init → 20261008090000_init}/migration.sql +5 -58
  118. package/prisma/schema.prisma +2 -43
  119. package/dist/configurations/configurations.repository.d.ts +0 -43
  120. package/dist/configurations/configurations.repository.d.ts.map +0 -1
  121. package/dist/configurations/configurations.repository.js +0 -76
  122. package/dist/generated/prisma/models/Configuration.d.ts +0 -1385
  123. package/dist/generated/prisma/models/Configuration.d.ts.map +0 -1
  124. package/dist/generated/prisma/models/Configuration.js +0 -1
  125. package/prisma/migrations/20260930102529_connection_config/migration.sql +0 -2
@@ -25,18 +25,18 @@ let EnvironmentConnectionsController = class EnvironmentConnectionsController {
25
25
  list(session, environmentId, filters) {
26
26
  return this.connections.listForMember(getActiveOrganizationId(session), session.user.id, environmentId, filters);
27
27
  }
28
- get(session, environmentId, id) {
29
- return this.connections.getForMember(getActiveOrganizationId(session), session.user.id, environmentId, id);
28
+ get(session, environmentId, provider, id) {
29
+ return this.connections.getForMember(getActiveOrganizationId(session), session.user.id, environmentId, provider, id);
30
30
  }
31
- revoke(session, environmentId, id) {
32
- return this.connections.revokeForMember(getActiveOrganizationId(session), session.user.id, environmentId, id);
31
+ revoke(session, environmentId, provider, id) {
32
+ return this.connections.revokeForMember(getActiveOrganizationId(session), session.user.id, environmentId, provider, id);
33
33
  }
34
34
  };
35
35
  __decorate([
36
36
  Get(),
37
37
  ApiOperation({
38
38
  summary: 'List the connections in one environment',
39
- description: 'Grouped by the tenant that owns them. Never carries a credential.',
39
+ description: 'Returns connections from every installed provider, newest first. Tokens and secrets are never included.',
40
40
  }),
41
41
  ApiOkResponse({ description: 'Connections in this environment.' }),
42
42
  __param(0, Session()),
@@ -47,30 +47,32 @@ __decorate([
47
47
  __metadata("design:returntype", void 0)
48
48
  ], EnvironmentConnectionsController.prototype, "list", null);
49
49
  __decorate([
50
- Get(':id'),
50
+ Get(':provider/:id'),
51
51
  ApiOperation({ summary: 'Get one connection' }),
52
52
  ApiNotFoundResponse({
53
53
  description: 'No such connection in an environment you can reach.',
54
54
  }),
55
55
  __param(0, Session()),
56
56
  __param(1, Param('environmentId')),
57
- __param(2, Param('id')),
57
+ __param(2, Param('provider')),
58
+ __param(3, Param('id')),
58
59
  __metadata("design:type", Function),
59
- __metadata("design:paramtypes", [Object, String, String]),
60
+ __metadata("design:paramtypes", [Object, String, String, String]),
60
61
  __metadata("design:returntype", void 0)
61
62
  ], EnvironmentConnectionsController.prototype, "get", null);
62
63
  __decorate([
63
- Delete(':id'),
64
+ Delete(':provider/:id'),
64
65
  ApiOperation({
65
66
  summary: 'Revoke a connection',
66
- description: 'Deletes the credential. Kosha logins carry no environment and are untouched.',
67
+ description: 'Deletes the credential and the provider’s connection row. Kosha logins are never affected.',
67
68
  }),
68
69
  ApiOkResponse({ description: 'The revoked connection id.' }),
69
70
  __param(0, Session()),
70
71
  __param(1, Param('environmentId')),
71
- __param(2, Param('id')),
72
+ __param(2, Param('provider')),
73
+ __param(3, Param('id')),
72
74
  __metadata("design:type", Function),
73
- __metadata("design:paramtypes", [Object, String, String]),
75
+ __metadata("design:paramtypes", [Object, String, String, String]),
74
76
  __metadata("design:returntype", void 0)
75
77
  ], EnvironmentConnectionsController.prototype, "revoke", null);
76
78
  EnvironmentConnectionsController = __decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"credentials.module.d.ts","sourceRoot":"","sources":["../../src/credentials/credentials.module.ts"],"names":[],"mappings":"AAKA,qBAKa,iBAAiB;CAAG"}
1
+ {"version":3,"file":"credentials.module.d.ts","sourceRoot":"","sources":["../../src/credentials/credentials.module.ts"],"names":[],"mappings":"AAIA,qBAIa,iBAAiB;CAAG"}
@@ -1,13 +1,11 @@
1
1
  import { __decorate } from "tslib";
2
2
  import { Module } from '@nestjs/common';
3
- import { ConfigurationsModule } from '../configurations/configurations.module.js';
4
3
  import { CredentialsRepository } from './credentials.repository.js';
5
4
  import { CredentialsService } from './credentials.service.js';
6
5
  let CredentialsModule = class CredentialsModule {
7
6
  };
8
7
  CredentialsModule = __decorate([
9
8
  Module({
10
- imports: [ConfigurationsModule],
11
9
  providers: [CredentialsService, CredentialsRepository],
12
10
  exports: [CredentialsService],
13
11
  })
@@ -2,7 +2,10 @@ import { PrismaService } from '../prisma/prisma.service.js';
2
2
  export declare class CredentialsRepository {
3
3
  private readonly prisma;
4
4
  constructor(prisma: PrismaService);
5
- /** Replaces the envelope in place, after a refresh minted a new token. */
6
- replaceEnvelope(id: string, accessToken: string, accessTokenExpiresAt: Date | null): Promise<void>;
5
+ /**
6
+ * Replaces the envelope in place, after a refresh minted a new token. The
7
+ * grant is rewritten too: a provider may report a different one.
8
+ */
9
+ replaceEnvelope(id: string, accessToken: string, accessTokenExpiresAt: Date | null, scope?: string | null): Promise<void>;
7
10
  }
8
11
  //# sourceMappingURL=credentials.repository.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"credentials.repository.d.ts","sourceRoot":"","sources":["../../src/credentials/credentials.repository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,qBACa,qBAAqB;IACpB,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAElD,0EAA0E;IACpE,eAAe,CACnB,EAAE,EAAE,MAAM,EACV,WAAW,EAAE,MAAM,EACnB,oBAAoB,EAAE,IAAI,GAAG,IAAI,GAChC,OAAO,CAAC,IAAI,CAAC;CAMjB"}
1
+ {"version":3,"file":"credentials.repository.d.ts","sourceRoot":"","sources":["../../src/credentials/credentials.repository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,qBACa,qBAAqB;IACpB,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAElD;;;OAGG;IACG,eAAe,CACnB,EAAE,EAAE,MAAM,EACV,WAAW,EAAE,MAAM,EACnB,oBAAoB,EAAE,IAAI,GAAG,IAAI,EACjC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,GACpB,OAAO,CAAC,IAAI,CAAC;CAUjB"}
@@ -6,11 +6,18 @@ let CredentialsRepository = class CredentialsRepository {
6
6
  constructor(prisma) {
7
7
  this.prisma = prisma;
8
8
  }
9
- /** Replaces the envelope in place, after a refresh minted a new token. */
10
- async replaceEnvelope(id, accessToken, accessTokenExpiresAt) {
9
+ /**
10
+ * Replaces the envelope in place, after a refresh minted a new token. The
11
+ * grant is rewritten too: a provider may report a different one.
12
+ */
13
+ async replaceEnvelope(id, accessToken, accessTokenExpiresAt, scope) {
11
14
  await this.prisma.account.update({
12
15
  where: { id },
13
- data: { accessToken, accessTokenExpiresAt },
16
+ data: {
17
+ accessToken,
18
+ accessTokenExpiresAt,
19
+ ...(scope === undefined ? {} : { scope }),
20
+ },
14
21
  });
15
22
  }
16
23
  };
@@ -1,5 +1,6 @@
1
1
  import type { KoshaIntegration } from '@kosha-ai/integration-sdk';
2
- import { ConfigurationsService } from '../configurations/configurations.service.js';
2
+ import type { ResolvedKoshaConfig } from '../config/kosha-config.js';
3
+ import type { ProviderConfiguration } from '../integrations/provider-store.js';
3
4
  import { CryptoService } from '../crypto/crypto.service.js';
4
5
  import type { Account } from '../generated/prisma/client.js';
5
6
  import { CredentialsRepository } from './credentials.repository.js';
@@ -21,9 +22,9 @@ export interface ResolvedCredential {
21
22
  export declare class CredentialsService {
22
23
  private readonly crypto;
23
24
  private readonly credentials;
24
- private readonly configurations;
25
+ private readonly config;
25
26
  private readonly logger;
26
- constructor(crypto: CryptoService, credentials: CredentialsRepository, configurations: ConfigurationsService);
27
+ constructor(crypto: CryptoService, credentials: CredentialsRepository, config: ResolvedKoshaConfig);
27
28
  /**
28
29
  * Returns a usable access token, refreshing first when the stored one has
29
30
  * expired and the provider supports it.
@@ -32,8 +33,17 @@ export declare class CredentialsService {
32
33
  * the whole consent flow again for a token the provider was willing to
33
34
  * renew.
34
35
  */
35
- resolve(account: Account, integration: KoshaIntegration): Promise<ResolvedCredential>;
36
+ resolve(account: Account, integration: KoshaIntegration, configuration: ProviderConfiguration, tokenKind?: string): Promise<ResolvedCredential>;
36
37
  private refresh;
38
+ /**
39
+ * A secondary token expires and refreshes on its own, with its own refresh
40
+ * token. Renewing it leaves the primary, and its expiry, as they were.
41
+ */
42
+ private resolveSecondary;
43
+ /** The refresh_token grant, for whichever stored token is being renewed. */
44
+ private requestRefresh;
45
+ private refreshFailed;
46
+ private openCredentials;
37
47
  /**
38
48
  * What an outbound request needs, whatever the credential's shape. A
39
49
  * client-credentials provider carries no token of its own: the integration
@@ -1 +1 @@
1
- {"version":3,"file":"credentials.service.d.ts","sourceRoot":"","sources":["../../src/credentials/credentials.service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,MAAM,6CAA6C,CAAC;AAMpF,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAEpE;;;;;;;GAOG;AACH,MAAM,WAAW,kBAAkB;IACjC,WAAW,EAAE,MAA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AED,qBACa,kBAAkB;IAI3B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,WAAW;IACN,OAAO,CAAC,QAAQ,CAAC,MAAM;IAL/C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuC;gBAG3C,MAAM,EAAE,aAAa,EACrB,WAAW,EAAE,qBAAqB,EACZ,MAAM,EAAE,mBAAmB;IAGpE;;;;;;;OAOG;IACG,OAAO,CACX,OAAO,EAAE,OAAO,EAChB,WAAW,EAAE,gBAAgB,EAC7B,aAAa,EAAE,qBAAqB,EACpC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,kBAAkB,CAAC;YA2ChB,OAAO;IA6CrB;;;OAGG;YACW,gBAAgB;IA6D9B,4EAA4E;YAC9D,cAAc;IAsB5B,OAAO,CAAC,aAAa;IAcrB,OAAO,CAAC,eAAe;IAUvB;;;;OAIG;IACH,OAAO,CAAC,MAAM;YAgDA,qBAAqB;CAoBpC"}
@@ -1,19 +1,21 @@
1
1
  var CredentialsService_1;
2
- import { __decorate, __metadata } from "tslib";
3
- import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
4
- import { ConfigurationsService } from '../configurations/configurations.service.js';
5
- import { ENVELOPE_VERSION, expiryOf, } from '../crypto/credential-envelope.js';
2
+ import { __decorate, __metadata, __param } from "tslib";
3
+ import { ForbiddenException, Injectable, Logger, UnauthorizedException, } from '@nestjs/common';
4
+ import { Inject } from '@nestjs/common';
5
+ import { KOSHA_CONFIG } from '../config/tokens.js';
6
+ import { clientContextFor } from '../integrations/client-context.js';
7
+ import { ENVELOPE_VERSION, expiryOf, storedSecondaryToken, } from '../crypto/credential-envelope.js';
6
8
  import { CryptoService } from '../crypto/crypto.service.js';
7
9
  import { CredentialsRepository } from './credentials.repository.js';
8
10
  let CredentialsService = CredentialsService_1 = class CredentialsService {
9
11
  crypto;
10
12
  credentials;
11
- configurations;
13
+ config;
12
14
  logger = new Logger(CredentialsService_1.name);
13
- constructor(crypto, credentials, configurations) {
15
+ constructor(crypto, credentials, config) {
14
16
  this.crypto = crypto;
15
17
  this.credentials = credentials;
16
- this.configurations = configurations;
18
+ this.config = config;
17
19
  }
18
20
  /**
19
21
  * Returns a usable access token, refreshing first when the stored one has
@@ -23,11 +25,16 @@ let CredentialsService = CredentialsService_1 = class CredentialsService {
23
25
  * the whole consent flow again for a token the provider was willing to
24
26
  * renew.
25
27
  */
26
- async resolve(account, integration) {
28
+ async resolve(account, integration, configuration, tokenKind) {
27
29
  if (!account.accessToken) {
28
30
  throw new UnauthorizedException('Connection has no stored credential');
29
31
  }
30
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
+ }
31
38
  const expiresAt = expiryOf(envelope);
32
39
  const expired = expiresAt !== null && expiresAt <= new Date();
33
40
  if (!expired)
@@ -37,46 +44,102 @@ let CredentialsService = CredentialsService_1 = class CredentialsService {
37
44
  if (!canRefresh) {
38
45
  throw new UnauthorizedException('Connection token expired; the end user must reconnect');
39
46
  }
40
- return this.refresh(account, integration, refreshToken);
47
+ return this.refresh(account, integration, configuration, refreshToken, envelope.type === 'oauth2' ? envelope : undefined);
41
48
  }
42
- async refresh(account, integration, refreshToken) {
43
- const { configuration, credentials } = await this.configurations.getWithCredentials(account.providerId);
44
- const settings = (configuration.settings ?? {});
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: settings.redirectUri ??
51
- this.configurations.callbackUrlFor(configuration.integrationKey),
52
- scopes: settings.scopes ?? [],
53
- },
54
- refreshToken,
55
- });
56
- if (!tokens)
57
- throw new Error('Refresh returned no tokens');
51
+ const tokens = await this.requestRefresh(integration, configuration, refreshToken);
58
52
  const envelope = {
59
53
  v: ENVELOPE_VERSION,
60
54
  type: 'oauth2',
61
55
  accessToken: tokens.accessToken,
62
- ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),
56
+ refreshToken: tokens.refreshToken ?? refreshToken,
63
57
  ...(tokens.tokenType ? { tokenType: tokens.tokenType } : {}),
64
58
  ...(tokens.expiresInSeconds
65
59
  ? {
66
60
  expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000).toISOString(),
67
61
  }
68
62
  : {}),
63
+ ...carriedSecondary(previous),
69
64
  };
70
65
  const expiresAt = expiryOf(envelope);
71
- await this.credentials.replaceEnvelope(account.id, this.crypto.sealEnvelope(envelope), expiresAt);
66
+ await this.credentials.replaceEnvelope(account.id, this.crypto.sealEnvelope(envelope), expiresAt, tokens.scope ?? undefined);
72
67
  await this.runTokenRefreshedHook(account.id, integration, tokens);
73
68
  return this.usable(envelope, expiresAt, true);
74
69
  }
75
70
  catch (error) {
76
- this.logger.warn(`Refresh failed for ${integration.key}: ${error instanceof Error ? error.message : error}`);
77
- 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);
78
114
  }
79
115
  }
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');
137
+ }
138
+ openCredentials(configuration) {
139
+ if (!configuration.credentials)
140
+ return {};
141
+ return JSON.parse(this.crypto.decrypt(configuration.credentials));
142
+ }
80
143
  /**
81
144
  * What an outbound request needs, whatever the credential's shape. A
82
145
  * client-credentials provider carries no token of its own: the integration
@@ -98,6 +161,15 @@ let CredentialsService = CredentialsService_1 = class CredentialsService {
98
161
  expiresAt: null,
99
162
  refreshed,
100
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
+ };
101
173
  case 'app':
102
174
  return {
103
175
  accessToken: envelope.installationId,
@@ -128,8 +200,12 @@ let CredentialsService = CredentialsService_1 = class CredentialsService {
128
200
  };
129
201
  CredentialsService = CredentialsService_1 = __decorate([
130
202
  Injectable(),
203
+ __param(2, Inject(KOSHA_CONFIG)),
131
204
  __metadata("design:paramtypes", [CryptoService,
132
- CredentialsRepository,
133
- ConfigurationsService])
205
+ CredentialsRepository, Object])
134
206
  ], CredentialsService);
135
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,uE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Q,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
+ }
@@ -3,7 +3,6 @@ import { CaService } from './ca.service.js';
3
3
  import type { ResolvedKoshaConfig } from '../config/kosha-config.js';
4
4
  import { CredentialsService } from '../credentials/credentials.service.js';
5
5
  import { GrantsService } from './grants.service.js';
6
- import { IntegrationRegistry } from '../integrations/integration.registry.js';
7
6
  import { HostRulesService } from './host-rules.service.js';
8
7
  export declare class EgressListener implements OnApplicationBootstrap, OnApplicationShutdown {
9
8
  private readonly config;
@@ -11,14 +10,13 @@ export declare class EgressListener implements OnApplicationBootstrap, OnApplica
11
10
  private readonly hostRules;
12
11
  private readonly ca;
13
12
  private readonly credentials;
14
- private readonly registry;
15
13
  private readonly logger;
16
14
  /** Reused so a clone's many requests do not each pay for a TLS handshake. */
17
15
  private readonly upstreamAgent;
18
16
  private server?;
19
17
  private mitmServer?;
20
18
  private pruneTimer?;
21
- constructor(config: ResolvedKoshaConfig, grants: GrantsService, hostRules: HostRulesService, ca: CaService, credentials: CredentialsService, registry: IntegrationRegistry);
19
+ constructor(config: ResolvedKoshaConfig, grants: GrantsService, hostRules: HostRulesService, ca: CaService, credentials: CredentialsService);
22
20
  onApplicationBootstrap(): Promise<void>;
23
21
  onApplicationShutdown(): void;
24
22
  private createProxyServer;
@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I,CAAC;IA0B7C,qBAAqB,IAAI,IAAI;IAM7B,OAAO,CAAC,iBAAiB;YA6BX,aAAa;IAwD3B,8EAA8E;IAC9E,OAAO,CAAC,MAAM;IAuBd,iFAAiF;IACjF,OAAO,CAAC,SAAS;IA4BjB;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;YAYV,OAAO;CA8FtB"}
@@ -9,7 +9,6 @@ import tls from 'node:tls';
9
9
  import { CaService } from './ca.service.js';
10
10
  import { CredentialsService } from '../credentials/credentials.service.js';
11
11
  import { GrantsService } from './grants.service.js';
12
- import { IntegrationRegistry } from '../integrations/integration.registry.js';
13
12
  import { HostRulesService, } from './host-rules.service.js';
14
13
  import { KOSHA_CONFIG } from '../config/tokens.js';
15
14
  /**
@@ -95,7 +94,6 @@ let EgressListener = EgressListener_1 = class EgressListener {
95
94
  hostRules;
96
95
  ca;
97
96
  credentials;
98
- registry;
99
97
  logger = new Logger(EgressListener_1.name);
100
98
  /** Reused so a clone's many requests do not each pay for a TLS handshake. */
101
99
  upstreamAgent = new https.Agent({
@@ -105,13 +103,12 @@ let EgressListener = EgressListener_1 = class EgressListener {
105
103
  server;
106
104
  mitmServer;
107
105
  pruneTimer;
108
- constructor(config, grants, hostRules, ca, credentials, registry) {
106
+ constructor(config, grants, hostRules, ca, credentials) {
109
107
  this.config = config;
110
108
  this.grants = grants;
111
109
  this.hostRules = hostRules;
112
110
  this.ca = ca;
113
111
  this.credentials = credentials;
114
- this.registry = registry;
115
112
  }
116
113
  async onApplicationBootstrap() {
117
114
  if (!this.config.egress.enabled)
@@ -255,7 +252,7 @@ let EgressListener = EgressListener_1 = class EgressListener {
255
252
  if (borrowable === null) {
256
253
  throw new Error(`This grant can no longer use ${rule.providerKey}. The connection may have been revoked.`);
257
254
  }
258
- const credential = await this.credentials.resolve(borrowable.account, this.registry.get(borrowable.configuration.integrationKey));
255
+ const credential = await this.credentials.resolve(borrowable.account, borrowable.integration, borrowable.configuration);
259
256
  injected = rule.headers({
260
257
  accessToken: credential.accessToken,
261
258
  tokenType: credential.tokenType,
@@ -322,7 +319,6 @@ EgressListener = EgressListener_1 = __decorate([
322
319
  __metadata("design:paramtypes", [Object, GrantsService,
323
320
  HostRulesService,
324
321
  CaService,
325
- CredentialsService,
326
- IntegrationRegistry])
322
+ CredentialsService])
327
323
  ], EgressListener);
328
324
  export { EgressListener };
@@ -1,4 +1,7 @@
1
- import type { Account, Configuration } from '../generated/prisma/client.js';
1
+ import type { KoshaIntegration } from '@kosha-ai/integration-sdk';
2
+ import type { Account } from '../generated/prisma/client.js';
3
+ import { IntegrationRegistry } from '../integrations/integration.registry.js';
4
+ import { ProviderStore, type ProviderConfiguration } from '../integrations/provider-store.js';
2
5
  import { PrismaService } from '../prisma/prisma.service.js';
3
6
  export interface GrantRow {
4
7
  organizationId: string;
@@ -10,14 +13,17 @@ export interface GrantRow {
10
13
  label?: string;
11
14
  expiresAt: Date;
12
15
  }
13
- /** A credential the broker may borrow, with the configuration it came from. */
16
+ /** A credential the broker may borrow, with what it takes to refresh it. */
14
17
  export interface BorrowableCredential {
15
18
  account: Account;
16
- configuration: Configuration;
19
+ configuration: ProviderConfiguration;
20
+ integration: KoshaIntegration;
17
21
  }
18
22
  export declare class EgressRepository {
19
23
  private readonly prisma;
20
- constructor(prisma: PrismaService);
24
+ private readonly store;
25
+ private readonly registry;
26
+ constructor(prisma: PrismaService, store: ProviderStore, registry: IntegrationRegistry);
21
27
  /**
22
28
  * The person a grant is minted for. A `user` row exists per environment, so
23
29
  * finding one by its derived address settles the environment too — which is
@@ -48,8 +54,9 @@ export declare class EgressRepository {
48
54
  * own user, never by anything in a request — that is what stops a grant
49
55
  * reaching another tenant's credential.
50
56
  *
51
- * There is no provider relation any more, so the integration is matched
52
- * through the configuration the credential came from.
57
+ * Starts from the provider's connection row, which an operator's password
58
+ * never has, so a login can never be lent. A person connected through two
59
+ * configurations lends the newest.
53
60
  */
54
61
  findCredentialFor(userId: string, integrationKey: string): Promise<BorrowableCredential | null>;
55
62
  /** Which of these integrations this person has actually connected. */
@@ -1 +1 @@
1
- {"version":3,"file":"egress.repository.d.ts","sourceRoot":"","sources":["../../src/egress/egress.repository.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,MAAM,WAAW,QAAQ;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,+EAA+E;AAC/E,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,aAAa,EAAE,aAAa,CAAC;CAC9B;AAED,qBACa,gBAAgB;IACf,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAElD;;;;OAIG;IACG,WAAW,CACf,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAOjC,WAAW,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,IAAI,CAAA;KAAE,CAAC;IAO9D,WAAW,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAQ3E,aAAa,CAAC,SAAS,EAAE,MAAM;;;;;;;;;;;IAezB,mBAAmB,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAOxD;;;;;;;OAOG;IACG,iBAAiB,CAC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