@kosha-ai/server 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/auth/auth.factory.d.ts.map +1 -1
  2. package/dist/auth/auth.factory.js +0 -5
  3. package/dist/configurations/configurations.controller.d.ts +6 -5
  4. package/dist/configurations/configurations.controller.d.ts.map +1 -1
  5. package/dist/configurations/configurations.controller.js +22 -18
  6. package/dist/configurations/configurations.module.d.ts.map +1 -1
  7. package/dist/configurations/configurations.module.js +1 -2
  8. package/dist/configurations/configurations.service.d.ts +24 -36
  9. package/dist/configurations/configurations.service.d.ts.map +1 -1
  10. package/dist/configurations/configurations.service.js +71 -151
  11. package/dist/configurations/dto/create-configuration.dto.d.ts +1 -2
  12. package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -1
  13. package/dist/configurations/dto/create-configuration.dto.js +2 -12
  14. package/dist/configurations/dto/update-configuration.dto.d.ts +0 -2
  15. package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -1
  16. package/dist/configurations/dto/update-configuration.dto.js +1 -17
  17. package/dist/connect/connect.controller.d.ts +1 -1
  18. package/dist/connect/connect.controller.d.ts.map +1 -1
  19. package/dist/connect/connect.controller.js +7 -6
  20. package/dist/connect/connect.module.d.ts.map +1 -1
  21. package/dist/connect/connect.module.js +1 -2
  22. package/dist/connect/connect.repository.d.ts +23 -23
  23. package/dist/connect/connect.repository.d.ts.map +1 -1
  24. package/dist/connect/connect.repository.js +37 -49
  25. package/dist/connect/connect.service.d.ts +7 -8
  26. package/dist/connect/connect.service.d.ts.map +1 -1
  27. package/dist/connect/connect.service.js +54 -51
  28. package/dist/connect/dto/create-connect-session.dto.d.ts +1 -1
  29. package/dist/connect/dto/create-connect-session.dto.d.ts.map +1 -1
  30. package/dist/connect/dto/create-connect-session.dto.js +7 -8
  31. package/dist/connect/dto/create-test-session.dto.d.ts +1 -0
  32. package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -1
  33. package/dist/connect/dto/create-test-session.dto.js +10 -3
  34. package/dist/connections/connections.controller.d.ts +4 -3
  35. package/dist/connections/connections.controller.d.ts.map +1 -1
  36. package/dist/connections/connections.controller.js +13 -11
  37. package/dist/connections/connections.repository.d.ts +24 -17
  38. package/dist/connections/connections.repository.d.ts.map +1 -1
  39. package/dist/connections/connections.repository.js +21 -43
  40. package/dist/connections/connections.service.d.ts +48 -13
  41. package/dist/connections/connections.service.d.ts.map +1 -1
  42. package/dist/connections/connections.service.js +111 -32
  43. package/dist/connections/dto/list-connections.dto.d.ts +3 -1
  44. package/dist/connections/dto/list-connections.dto.d.ts.map +1 -1
  45. package/dist/connections/dto/list-connections.dto.js +26 -4
  46. package/dist/connections/environment-connections.controller.d.ts +4 -3
  47. package/dist/connections/environment-connections.controller.d.ts.map +1 -1
  48. package/dist/connections/environment-connections.controller.js +14 -12
  49. package/dist/credentials/credentials.module.d.ts.map +1 -1
  50. package/dist/credentials/credentials.module.js +0 -2
  51. package/dist/credentials/credentials.repository.d.ts +5 -2
  52. package/dist/credentials/credentials.repository.d.ts.map +1 -1
  53. package/dist/credentials/credentials.repository.js +10 -3
  54. package/dist/credentials/credentials.service.d.ts +8 -4
  55. package/dist/credentials/credentials.service.d.ts.map +1 -1
  56. package/dist/credentials/credentials.service.js +27 -16
  57. package/dist/egress/egress.listener.d.ts +1 -3
  58. package/dist/egress/egress.listener.d.ts.map +1 -1
  59. package/dist/egress/egress.listener.js +3 -7
  60. package/dist/egress/egress.repository.d.ts +13 -6
  61. package/dist/egress/egress.repository.d.ts.map +1 -1
  62. package/dist/egress/egress.repository.js +31 -44
  63. package/dist/generated/prisma/browser.d.ts +0 -5
  64. package/dist/generated/prisma/browser.d.ts.map +1 -1
  65. package/dist/generated/prisma/client.d.ts +0 -5
  66. package/dist/generated/prisma/client.d.ts.map +1 -1
  67. package/dist/generated/prisma/commonInputTypes.d.ts +0 -55
  68. package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -1
  69. package/dist/generated/prisma/internal/class.d.ts +0 -11
  70. package/dist/generated/prisma/internal/class.d.ts.map +1 -1
  71. package/dist/generated/prisma/internal/class.js +4 -4
  72. package/dist/generated/prisma/internal/prismaNamespace.d.ts +1 -114
  73. package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
  74. package/dist/generated/prisma/internal/prismaNamespace.js +2 -29
  75. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +0 -30
  76. package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
  77. package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +2 -29
  78. package/dist/generated/prisma/models/Account.d.ts +26 -344
  79. package/dist/generated/prisma/models/Account.d.ts.map +1 -1
  80. package/dist/generated/prisma/models/Environment.d.ts +0 -258
  81. package/dist/generated/prisma/models/Environment.d.ts.map +1 -1
  82. package/dist/generated/prisma/models/User.d.ts +2 -60
  83. package/dist/generated/prisma/models/User.d.ts.map +1 -1
  84. package/dist/generated/prisma/models.d.ts +0 -1
  85. package/dist/generated/prisma/models.d.ts.map +1 -1
  86. package/dist/index.d.ts +1 -2
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/integrations/integrations.controller.d.ts +2 -0
  89. package/dist/integrations/integrations.controller.d.ts.map +1 -1
  90. package/dist/integrations/integrations.controller.js +1 -0
  91. package/dist/integrations/integrations.module.d.ts.map +1 -1
  92. package/dist/integrations/integrations.module.js +3 -1
  93. package/dist/integrations/provider-store.d.ts +104 -0
  94. package/dist/integrations/provider-store.d.ts.map +1 -0
  95. package/dist/integrations/provider-store.js +234 -0
  96. package/dist/proxy/proxy.controller.d.ts +9 -5
  97. package/dist/proxy/proxy.controller.d.ts.map +1 -1
  98. package/dist/proxy/proxy.controller.js +18 -13
  99. package/dist/proxy/proxy.module.d.ts.map +1 -1
  100. package/dist/proxy/proxy.module.js +1 -2
  101. package/dist/proxy/proxy.repository.d.ts +11 -14
  102. package/dist/proxy/proxy.repository.d.ts.map +1 -1
  103. package/dist/proxy/proxy.repository.js +17 -27
  104. package/dist/proxy/proxy.service.d.ts +6 -8
  105. package/dist/proxy/proxy.service.d.ts.map +1 -1
  106. package/dist/proxy/proxy.service.js +34 -28
  107. package/package.json +4 -4
  108. package/prisma/migrations/{20260929101936_init → 20261008090000_init}/migration.sql +5 -58
  109. package/prisma/schema.prisma +2 -43
  110. package/dist/configurations/configurations.repository.d.ts +0 -43
  111. package/dist/configurations/configurations.repository.d.ts.map +0 -1
  112. package/dist/configurations/configurations.repository.js +0 -76
  113. package/dist/generated/prisma/models/Configuration.d.ts +0 -1385
  114. package/dist/generated/prisma/models/Configuration.d.ts.map +0 -1
  115. package/dist/generated/prisma/models/Configuration.js +0 -1
  116. package/prisma/migrations/20260930102529_connection_config/migration.sql +0 -2
@@ -1,11 +1,9 @@
1
1
  import { __decorate, __metadata } from "tslib";
2
2
  import { ApiPropertyOptional } from '@nestjs/swagger';
3
- import { IsBoolean, IsObject, IsOptional, IsString, MaxLength, MinLength, } from 'class-validator';
3
+ import { IsObject, IsOptional, IsString, MaxLength, MinLength, } from 'class-validator';
4
4
  export class UpdateConfigurationDto {
5
5
  name;
6
6
  credentials;
7
- settings;
8
- isEnabled;
9
7
  }
10
8
  __decorate([
11
9
  ApiPropertyOptional({ example: 'GitHub' }),
@@ -23,17 +21,3 @@ __decorate([
23
21
  IsObject(),
24
22
  __metadata("design:type", Object)
25
23
  ], UpdateConfigurationDto.prototype, "credentials", void 0);
26
- __decorate([
27
- ApiPropertyOptional({ example: { scopes: ['repo'] } }),
28
- IsOptional(),
29
- IsObject(),
30
- __metadata("design:type", Object)
31
- ], UpdateConfigurationDto.prototype, "settings", void 0);
32
- __decorate([
33
- ApiPropertyOptional({
34
- description: 'Disable without deleting; stored credentials stay put.',
35
- }),
36
- IsOptional(),
37
- IsBoolean(),
38
- __metadata("design:type", Boolean)
39
- ], UpdateConfigurationDto.prototype, "isEnabled", void 0);
@@ -24,6 +24,6 @@ export declare class ConnectController {
24
24
  /** The URL the end user's browser opens. Redirects to the provider. */
25
25
  start(token: string, res: Response): Promise<void>;
26
26
  /** Where the provider sends the end user back. */
27
- callback(integrationKey: string, code: string | undefined, state: string | undefined, providerError: string | undefined, providerErrorDescription: string | undefined, res: Response): Promise<void>;
27
+ callback(provider: string, code: string | undefined, state: string | undefined, providerError: string | undefined, providerErrorDescription: string | undefined, res: Response): Promise<void>;
28
28
  }
29
29
  //# sourceMappingURL=connect.controller.d.ts.map
@@ -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;IAcpC,uEAAuE;IAIjE,KAAK,CAAiB,KAAK,EAAE,MAAM,EAAS,GAAG,EAAE,QAAQ;IAY/D,kDAAkD;IAI5C,QAAQ,CACa,cAAc,EAAE,MAAM,EAChC,IAAI,EAAE,MAAM,GAAG,SAAS,EACvB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,aAAa,EAAE,MAAM,GAAG,SAAS,EACrB,wBAAwB,EAAE,MAAM,GAAG,SAAS,EACjE,GAAG,EAAE,QAAQ;CAuDvB"}
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,EACrB,wBAAwB,EAAE,MAAM,GAAG,SAAS,EACjE,GAAG,EAAE,QAAQ;CAuDvB"}
@@ -34,6 +34,7 @@ let ConnectController = ConnectController_1 = class ConnectController {
34
34
  createTestSession(session, environmentId, body) {
35
35
  return this.connect.createSession(getActiveOrganizationId(session), environmentId, {
36
36
  externalUserId: `kosha-admin:${session.user.id}`,
37
+ provider: body.provider,
37
38
  configurationId: body?.configurationId,
38
39
  configurationSlug: body?.slug,
39
40
  redirectUrl: body?.redirectUrl,
@@ -51,7 +52,7 @@ let ConnectController = ConnectController_1 = class ConnectController {
51
52
  }
52
53
  }
53
54
  /** Where the provider sends the end user back. */
54
- async callback(integrationKey, code, state, providerError, providerErrorDescription, res) {
55
+ async callback(provider, code, state, providerError, providerErrorDescription, res) {
55
56
  if (providerError || providerErrorDescription) {
56
57
  res
57
58
  .status(400)
@@ -65,7 +66,7 @@ let ConnectController = ConnectController_1 = class ConnectController {
65
66
  return;
66
67
  }
67
68
  try {
68
- const { redirectUrl } = await this.connect.handleCallback(integrationKey, code, state);
69
+ const { redirectUrl } = await this.connect.handleCallback(provider, code, state);
69
70
  if (redirectUrl) {
70
71
  const url = new URL(redirectUrl);
71
72
  url.searchParams.set('kosha_status', 'success');
@@ -75,7 +76,7 @@ let ConnectController = ConnectController_1 = class ConnectController {
75
76
  res.send('Connected. You can close this window.');
76
77
  }
77
78
  catch (error) {
78
- this.logger.warn(`Connect callback failed for "${integrationKey}": ${error instanceof Error ? error.message : error}`);
79
+ this.logger.warn(`Connect callback failed for "${provider}": ${error instanceof Error ? error.message : error}`);
79
80
  // A conflict is worth saying out loud: somebody is already connected,
80
81
  // and the end user can do something about it. Everything else stays
81
82
  // vague, since this URL is reached by a browser we do not trust.
@@ -98,7 +99,7 @@ __decorate([
98
99
  ApiSecurity('x-api-key'),
99
100
  ApiOperation({
100
101
  summary: 'Start a connect flow for one of the app’s users',
101
- description: 'The environment comes from the API key. Set organizationExternalId when the credential belongs to a tenant rather than to the person.',
102
+ description: 'The environment comes from the API key. Name the provider and the configuration slug it was set up under.',
102
103
  }),
103
104
  ApiCreatedResponse({ description: 'A connect URL and when it expires.' }),
104
105
  ApiBadRequestResponse({
@@ -134,10 +135,10 @@ __decorate([
134
135
  __metadata("design:returntype", Promise)
135
136
  ], ConnectController.prototype, "start", null);
136
137
  __decorate([
137
- Get('callback/:integrationKey'),
138
+ Get('callback/:provider'),
138
139
  AllowAnonymous(),
139
140
  ApiExcludeEndpoint(),
140
- __param(0, Param('integrationKey')),
141
+ __param(0, Param('provider')),
141
142
  __param(1, Query('code')),
142
143
  __param(2, Query('state')),
143
144
  __param(3, Query('error')),
@@ -1 +1 @@
1
- {"version":3,"file":"connect.module.d.ts","sourceRoot":"","sources":["../../src/connect/connect.module.ts"],"names":[],"mappings":"AAOA,qBAMa,aAAa;CAAG"}
1
+ {"version":3,"file":"connect.module.d.ts","sourceRoot":"","sources":["../../src/connect/connect.module.ts"],"names":[],"mappings":"AAMA,qBAMa,aAAa;CAAG"}
@@ -1,6 +1,5 @@
1
1
  import { __decorate } from "tslib";
2
2
  import { Module } from '@nestjs/common';
3
- import { ConfigurationsModule } from '../configurations/configurations.module.js';
4
3
  import { EnvironmentsModule } from '../environments/environments.module.js';
5
4
  import { ConnectController } from './connect.controller.js';
6
5
  import { ConnectRepository } from './connect.repository.js';
@@ -9,7 +8,7 @@ let ConnectModule = class ConnectModule {
9
8
  };
10
9
  ConnectModule = __decorate([
11
10
  Module({
12
- imports: [ConfigurationsModule, EnvironmentsModule],
11
+ imports: [EnvironmentsModule],
13
12
  controllers: [ConnectController],
14
13
  providers: [ConnectService, ConnectRepository],
15
14
  exports: [ConnectService],
@@ -1,4 +1,4 @@
1
- import type { Account, User } from '../generated/prisma/client.js';
1
+ import type { Account, Prisma, User } from '../generated/prisma/client.js';
2
2
  import { PrismaService } from '../prisma/prisma.service.js';
3
3
  /**
4
4
  * What a connect flow remembers between the link being handed out and the
@@ -9,30 +9,25 @@ export interface ConnectState {
9
9
  organizationId: string;
10
10
  environmentId: string;
11
11
  environmentSlug: string;
12
+ /** Which provider's tables this flow writes to. */
13
+ provider: string;
12
14
  configurationId: string;
13
15
  externalUserId: string;
14
- /** Set when the connection belongs to a tenant rather than to the person. */
15
- organizationExternalId?: string | null;
16
16
  redirectUrl?: string | null;
17
17
  /** PKCE, present only once the authorization URL has been built. */
18
18
  codeVerifier?: string;
19
19
  }
20
20
  export interface StoreCredentialInput {
21
21
  userId: string;
22
- environmentId: string;
23
- organizationExternalId: string | null;
24
- /** The configuration id. `account.providerId` holds it as a plain string. */
25
- providerId: string;
22
+ /** The provider, which is what Better Auth means by `providerId`. */
23
+ provider: string;
26
24
  /** The provider's own id for the account. */
27
25
  accountId: string;
28
26
  /** Already an encrypted envelope by the time it arrives here. */
29
27
  accessToken: string;
30
28
  accessTokenExpiresAt: Date | null;
31
- /**
32
- * Provider facts a later proxied call needs beyond the credential — the Jira
33
- * site, say. Non-secret, so it is stored in the clear.
34
- */
35
- connectionConfig?: Record<string, unknown>;
29
+ /** What the provider granted, which can be less than was asked for. */
30
+ scope: string | null;
36
31
  }
37
32
  export declare class ConnectRepository {
38
33
  private readonly prisma;
@@ -50,22 +45,16 @@ export declare class ConnectRepository {
50
45
  */
51
46
  upsertEndUser(environmentSlug: string, externalUserId: string): Promise<User>;
52
47
  /**
53
- * One credential per owner per configuration, which the database enforces:
54
- * a unique index for tenant-owned rows, a partial one for personal rows.
55
- * Found first rather than upserted, because Prisma cannot upsert on an index
56
- * whose columns are nullable.
48
+ * Writes the credential and lets the provider record its own connection in
49
+ * the same transaction, so a credential nothing points at cannot exist.
57
50
  */
58
- findCredential(environmentId: string, providerId: string, owner: {
59
- userId: string;
60
- organizationExternalId: string | null;
61
- }): Promise<Account | null>;
62
- storeCredential(input: StoreCredentialInput): Promise<Account>;
51
+ storeCredential(input: StoreCredentialInput, link: (tx: Prisma.TransactionClient, accountId: string) => Promise<unknown>): Promise<Account>;
63
52
  updateCredential(id: string, changes: {
64
53
  accountId?: string;
65
54
  accessToken: string;
66
55
  accessTokenExpiresAt: Date | null;
67
- userId?: string;
68
- connectionConfig?: Record<string, unknown>;
56
+ /** Rewritten on refresh: a provider may report a different grant. */
57
+ scope?: string | null;
69
58
  }): Promise<Account>;
70
59
  private take;
71
60
  }
@@ -73,6 +62,17 @@ export declare class ConnectRepository {
73
62
  * Better Auth requires `user.email` to be present and unique, while an end
74
63
  * user exists per environment. The derived form encodes both, so the same
75
64
  * person in sandbox and production is two rows rather than a unique violation.
65
+ *
66
+ * `.internal` is reserved for private use, so the address can never resolve or
67
+ * receive mail — an end user has none to store.
76
68
  */
77
69
  export declare function derivedEmail(environmentSlug: string, externalUserId: string): string;
70
+ /**
71
+ * Gets the app's user id back out of a stored email, the reverse of
72
+ * {@link derivedEmail}: `production.user_9@kosha.internal` → `user_9`.
73
+ *
74
+ * Uses `derivedEmail` to know what comes before and after the id, so a change
75
+ * to the email format cannot break it.
76
+ */
77
+ export declare function externalUserIdOf(environmentSlug: string, email: string): string;
78
78
  //# sourceMappingURL=connect.repository.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"connect.repository.d.ts","sourceRoot":"","sources":["../../src/connect/connect.repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAU,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAc5D;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,6EAA6E;IAC7E,sBAAsB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvC,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,aAAa,EAAE,MAAM,CAAC;IACtB,sBAAsB,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC,6EAA6E;IA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AAO,EAAE;QACP,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,WAAW,EAAE,MAAM,CAAC;QACpB,oBAAoB,EAAE,IAAI,GAAG,IAAI,CAAC;QAClC,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KAC5C,GACA,OAAO,CAAC,OAAO,CAAC;YAOL,IAAI;CAanB;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAC1B,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,GACrB,MAAM,CAER"}
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,MAAM,GAAG,IAAI,CAAC;CACtB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;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,eAAe,EAAE,MAAM,EACvB,KAAK,EAAE,MAAM,GACZ,MAAM,CAGR"}
@@ -2,15 +2,6 @@ import { __decorate, __metadata } from "tslib";
2
2
  import { Injectable } from '@nestjs/common';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { PrismaService } from '../prisma/prisma.service.js';
5
- /**
6
- * Prisma distinguishes "leave this column alone" from "write JSON null", and a
7
- * plain index signature is not assignable to its Json input type. Undefined
8
- * stays undefined, so an update that says nothing about the config keeps what
9
- * is already stored.
10
- */
11
- function asJson(value) {
12
- return value;
13
- }
14
5
  /**
15
6
  * Namespaced, because `verification` is shared with email verification and
16
7
  * password reset.
@@ -70,52 +61,35 @@ let ConnectRepository = class ConnectRepository {
70
61
  const email = derivedEmail(environmentSlug, externalUserId);
71
62
  return this.prisma.user.upsert({
72
63
  where: { email },
73
- create: {
74
- email,
75
- externalId: externalUserId,
76
- name: externalUserId,
77
- emailVerified: false,
78
- },
79
- update: { externalId: externalUserId },
64
+ create: { email, name: externalUserId, emailVerified: false },
65
+ // Nothing of ours lives on this row, so a second connect by the same
66
+ // person has nothing to write.
67
+ update: {},
80
68
  });
81
69
  }
82
70
  /**
83
- * One credential per owner per configuration, which the database enforces:
84
- * a unique index for tenant-owned rows, a partial one for personal rows.
85
- * Found first rather than upserted, because Prisma cannot upsert on an index
86
- * whose columns are nullable.
71
+ * Writes the credential and lets the provider record its own connection in
72
+ * the same transaction, so a credential nothing points at cannot exist.
87
73
  */
88
- async findCredential(environmentId, providerId, owner) {
89
- return this.prisma.account.findFirst({
90
- where: {
91
- environmentId,
92
- providerId,
93
- ...(owner.organizationExternalId
94
- ? { organizationExternalId: owner.organizationExternalId }
95
- : { organizationExternalId: null, userId: owner.userId }),
96
- },
97
- });
98
- }
99
- storeCredential(input) {
100
- return this.prisma.account.create({
101
- data: {
102
- id: randomUUID(),
103
- userId: input.userId,
104
- environmentId: input.environmentId,
105
- organizationExternalId: input.organizationExternalId,
106
- providerId: input.providerId,
107
- accountId: input.accountId,
108
- accessToken: input.accessToken,
109
- accessTokenExpiresAt: input.accessTokenExpiresAt,
110
- connectionConfig: asJson(input.connectionConfig),
111
- },
74
+ storeCredential(input, link) {
75
+ return this.prisma.$transaction(async (tx) => {
76
+ const account = await tx.account.create({
77
+ data: {
78
+ id: randomUUID(),
79
+ userId: input.userId,
80
+ providerId: input.provider,
81
+ accountId: input.accountId,
82
+ accessToken: input.accessToken,
83
+ accessTokenExpiresAt: input.accessTokenExpiresAt,
84
+ scope: input.scope,
85
+ },
86
+ });
87
+ await link(tx, account.id);
88
+ return account;
112
89
  });
113
90
  }
114
91
  updateCredential(id, changes) {
115
- return this.prisma.account.update({
116
- where: { id },
117
- data: { ...changes, connectionConfig: asJson(changes.connectionConfig) },
118
- });
92
+ return this.prisma.account.update({ where: { id }, data: changes });
119
93
  }
120
94
  async take(identifier) {
121
95
  const row = await this.prisma.verification.findFirst({
@@ -140,7 +114,21 @@ export { ConnectRepository };
140
114
  * Better Auth requires `user.email` to be present and unique, while an end
141
115
  * user exists per environment. The derived form encodes both, so the same
142
116
  * person in sandbox and production is two rows rather than a unique violation.
117
+ *
118
+ * `.internal` is reserved for private use, so the address can never resolve or
119
+ * receive mail — an end user has none to store.
143
120
  */
144
121
  export function derivedEmail(environmentSlug, externalUserId) {
145
- return `${environmentSlug}.${externalUserId}@endusers.kosha.invalid`;
122
+ return `${environmentSlug}.${externalUserId}@kosha.internal`;
123
+ }
124
+ /**
125
+ * Gets the app's user id back out of a stored email, the reverse of
126
+ * {@link derivedEmail}: `production.user_9@kosha.internal` → `user_9`.
127
+ *
128
+ * Uses `derivedEmail` to know what comes before and after the id, so a change
129
+ * to the email format cannot break it.
130
+ */
131
+ export function externalUserIdOf(environmentSlug, email) {
132
+ const [prefix, suffix] = derivedEmail(environmentSlug, '\0').split('\0');
133
+ return email.slice(prefix.length, email.length - suffix.length);
146
134
  }
@@ -1,9 +1,9 @@
1
1
  import type { TokenSet } from '@kosha-ai/integration-sdk';
2
2
  import type { ResolvedKoshaConfig } from '../config/kosha-config.js';
3
- import { ConfigurationsService } from '../configurations/configurations.service.js';
4
3
  import { CryptoService } from '../crypto/crypto.service.js';
5
4
  import { EnvironmentsService } from '../environments/environments.service.js';
6
5
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
6
+ import { ProviderStore } from '../integrations/provider-store.js';
7
7
  import { ConnectRepository } from './connect.repository.js';
8
8
  import type { CreateConnectSessionDto } from './dto/create-connect-session.dto.js';
9
9
  export interface ConnectSessionResult {
@@ -25,12 +25,12 @@ export interface CallbackResult {
25
25
  export declare class ConnectService {
26
26
  private readonly connect;
27
27
  private readonly crypto;
28
- private readonly configurations;
28
+ private readonly store;
29
29
  private readonly environments;
30
30
  private readonly registry;
31
31
  private readonly config;
32
32
  private readonly logger;
33
- constructor(connect: ConnectRepository, crypto: CryptoService, configurations: ConfigurationsService, environments: EnvironmentsService, registry: IntegrationRegistry, config: ResolvedKoshaConfig);
33
+ constructor(connect: ConnectRepository, crypto: CryptoService, store: ProviderStore, environments: EnvironmentsService, registry: IntegrationRegistry, config: ResolvedKoshaConfig);
34
34
  /**
35
35
  * Called by the consuming app's backend to start a connect flow for one of
36
36
  * its users. The environment comes from the API key, never from the body.
@@ -43,14 +43,13 @@ export declare class ConnectService {
43
43
  */
44
44
  buildAuthorizationRedirect(token: string): Promise<string>;
45
45
  /** Handles the provider's redirect back to Kosha. */
46
- handleCallback(integrationKey: string, code: string, state: string): Promise<CallbackResult>;
46
+ handleCallback(provider: string, code: string, state: string): Promise<CallbackResult>;
47
47
  /**
48
48
  * Writes the credential, refusing when one is already there.
49
49
  *
50
- * Replacing silently would let anyone at a tenant overwrite the workspace
51
- * credential their colleague connected, with no trace. Reconnecting means
52
- * revoking first, which is a deliberate act by someone who can see what they
53
- * are replacing.
50
+ * Replacing silently would let somebody take over a credential a colleague
51
+ * connected, with no trace. Reconnecting means revoking first, which is a
52
+ * deliberate act by someone who can see what they are replacing.
54
53
  */
55
54
  private writeCredential;
56
55
  /** Persists a refreshed token set. Shared with the refresh path. */
@@ -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;AAErE,OAAO,EAAE,qBAAqB,EAAE,MAAM,6CAA6C,CAAC;AAMpF,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,EAAE,iBAAiB,EAAqB,MAAM,yBAAyB,CAAC;AAC/E,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAKnF,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAMD;;;;;;GAMG;AACH,qBACa,cAAc;IAIvB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,cAAc;IAC/B,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACH,OAAO,CAAC,QAAQ,CAAC,MAAM;IAR/C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmC;gBAGvC,OAAO,EAAE,iBAAiB,EAC1B,MAAM,EAAE,aAAa,EACrB,cAAc,EAAE,qBAAqB,EACrC,YAAY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E;YACxD,OAAO;CActB"}
@@ -4,11 +4,11 @@ import { BadRequestException, ConflictException, Inject, Injectable, Logger, Not
4
4
  import { randomBytes } from 'node:crypto';
5
5
  import { generateCodeVerifier, httpFor } from '@kosha-ai/integration-sdk';
6
6
  import { KOSHA_CONFIG } from '../config/tokens.js';
7
- import { ConfigurationsService } from '../configurations/configurations.service.js';
8
7
  import { ENVELOPE_VERSION, expiryOf, } from '../crypto/credential-envelope.js';
9
8
  import { CryptoService } from '../crypto/crypto.service.js';
10
9
  import { EnvironmentsService } from '../environments/environments.service.js';
11
10
  import { IntegrationRegistry } from '../integrations/integration.registry.js';
11
+ import { ProviderStore, } from '../integrations/provider-store.js';
12
12
  import { ConnectRepository } from './connect.repository.js';
13
13
  const SESSION_TTL_MS = 10 * 60 * 1000;
14
14
  const STATE_TTL_MS = 10 * 60 * 1000;
@@ -25,15 +25,15 @@ function randomToken() {
25
25
  let ConnectService = ConnectService_1 = class ConnectService {
26
26
  connect;
27
27
  crypto;
28
- configurations;
28
+ store;
29
29
  environments;
30
30
  registry;
31
31
  config;
32
32
  logger = new Logger(ConnectService_1.name);
33
- constructor(connect, crypto, configurations, environments, registry, config) {
33
+ constructor(connect, crypto, store, environments, registry, config) {
34
34
  this.connect = connect;
35
35
  this.crypto = crypto;
36
- this.configurations = configurations;
36
+ this.store = store;
37
37
  this.environments = environments;
38
38
  this.registry = registry;
39
39
  this.config = config;
@@ -48,10 +48,8 @@ let ConnectService = ConnectService_1 = class ConnectService {
48
48
  throw new BadRequestException('externalUserId is required');
49
49
  }
50
50
  const environment = await this.environments.get(organizationId, environmentId);
51
- const configuration = await this.resolveConfiguration(environmentId, input);
52
- if (!configuration.isEnabled) {
53
- throw new BadRequestException('Configuration is disabled');
54
- }
51
+ const integration = this.registry.get(input.provider);
52
+ const configuration = await this.resolveConfiguration(integration, environmentId, input);
55
53
  // Nothing else sweeps these: `verification` is shared with email
56
54
  // verification and password reset, so only this flow knows which rows are
57
55
  // its own. Swept here rather than on a schedule, so no timer has to exist.
@@ -64,9 +62,9 @@ let ConnectService = ConnectService_1 = class ConnectService {
64
62
  organizationId,
65
63
  environmentId: environment.id,
66
64
  environmentSlug: environment.slug,
65
+ provider: integration.key,
67
66
  configurationId: configuration.id,
68
67
  externalUserId,
69
- organizationExternalId: input.organizationExternalId?.trim() || null,
70
68
  redirectUrl: input.redirectUrl ?? null,
71
69
  }, expiresAt);
72
70
  const { publicUrl, globalPrefix } = this.config.server;
@@ -86,35 +84,38 @@ let ConnectService = ConnectService_1 = class ConnectService {
86
84
  if (!session) {
87
85
  throw new NotFoundException('Connect session not found or expired');
88
86
  }
89
- const { configuration, credentials } = await this.configurations.getWithCredentials(session.configurationId);
90
- if (!configuration.isEnabled) {
87
+ const integration = this.registry.get(session.provider);
88
+ const configuration = await this.store.findConfigurationWithCredentials(integration, session.configurationId);
89
+ if (!configuration) {
91
90
  throw new BadRequestException('Configuration is no longer available');
92
91
  }
93
- const integration = this.registry.get(configuration.integrationKey);
94
92
  const codeVerifier = integration.auth.pkce
95
93
  ? generateCodeVerifier()
96
94
  : undefined;
97
95
  const state = randomToken();
98
96
  await this.connect.putState(state, { ...session, codeVerifier }, new Date(Date.now() + STATE_TTL_MS));
99
97
  return integration.auth.buildAuthorizationUrl({
100
- client: this.clientContextFor(configuration, credentials),
98
+ client: this.clientContextFor(integration, configuration),
101
99
  state,
102
100
  codeVerifier,
103
101
  });
104
102
  }
105
103
  /** Handles the provider's redirect back to Kosha. */
106
- async handleCallback(integrationKey, code, state) {
104
+ async handleCallback(provider, code, state) {
107
105
  const flow = await this.connect.takeState(state);
108
106
  if (!flow) {
109
107
  throw new NotFoundException('OAuth state not found or expired');
110
108
  }
111
- const { configuration, credentials } = await this.configurations.getWithCredentials(flow.configurationId);
112
- if (configuration.integrationKey !== integrationKey) {
109
+ if (flow.provider !== provider) {
113
110
  throw new BadRequestException('Provider mismatch');
114
111
  }
115
- const integration = this.registry.get(integrationKey);
112
+ const integration = this.registry.get(provider);
113
+ const configuration = await this.store.findConfigurationWithCredentials(integration, flow.configurationId);
114
+ if (!configuration) {
115
+ throw new BadRequestException('Configuration is no longer available');
116
+ }
116
117
  const tokens = await integration.auth.exchangeCode({
117
- client: this.clientContextFor(configuration, credentials),
118
+ client: this.clientContextFor(integration, configuration),
118
119
  code,
119
120
  codeVerifier: flow.codeVerifier,
120
121
  });
@@ -123,15 +124,14 @@ let ConnectService = ConnectService_1 = class ConnectService {
123
124
  http: httpFor(integration),
124
125
  });
125
126
  const user = await this.connect.upsertEndUser(flow.environmentSlug, flow.externalUserId);
126
- const account = await this.writeCredential(flow, {
127
+ const account = await this.writeCredential(flow, integration, {
127
128
  userId: user.id,
128
- providerId: configuration.id,
129
129
  accountId: identity.externalAccountId,
130
130
  tokens,
131
131
  // What the provider told us about this account that a later proxied
132
132
  // call needs — the Jira site, for one. Without storing it here, a
133
133
  // provider with no fixed host has no resolvable base URL at all.
134
- connectionConfig: identity.metadata,
134
+ metadata: identity.metadata,
135
135
  });
136
136
  await this.runHook(integration, () => integration.hooks?.onConnectionCreated?.({
137
137
  connectionId: account.id,
@@ -142,34 +142,34 @@ let ConnectService = ConnectService_1 = class ConnectService {
142
142
  /**
143
143
  * Writes the credential, refusing when one is already there.
144
144
  *
145
- * Replacing silently would let anyone at a tenant overwrite the workspace
146
- * credential their colleague connected, with no trace. Reconnecting means
147
- * revoking first, which is a deliberate act by someone who can see what they
148
- * are replacing.
145
+ * Replacing silently would let somebody take over a credential a colleague
146
+ * connected, with no trace. Reconnecting means revoking first, which is a
147
+ * deliberate act by someone who can see what they are replacing.
149
148
  */
150
- async writeCredential(flow, input) {
149
+ async writeCredential(flow, integration, input) {
151
150
  const envelope = this.envelopeFor(input.tokens);
152
151
  const accessToken = this.crypto.sealEnvelope(envelope);
153
152
  const accessTokenExpiresAt = expiryOf(envelope);
154
- const existing = await this.connect.findCredential(flow.environmentId, input.providerId, {
155
- userId: input.userId,
156
- organizationExternalId: flow.organizationExternalId ?? null,
157
- });
153
+ // Read before writing, so a second connect is a clear refusal rather than
154
+ // the unique index surfacing as a 500. The index is still the backstop.
155
+ const existing = await this.store.findConnection(integration, flow.environmentId, flow.configurationId, input.userId);
158
156
  if (existing) {
159
- throw new ConflictException(flow.organizationExternalId
160
- ? `${flow.organizationExternalId} is already connected to this configuration. Revoke that connection first.`
161
- : 'This person is already connected to this configuration. Revoke that connection first.');
157
+ throw new ConflictException('This person is already connected to this configuration. Revoke that connection first.');
162
158
  }
163
159
  return this.connect.storeCredential({
164
160
  userId: input.userId,
165
- environmentId: flow.environmentId,
166
- organizationExternalId: flow.organizationExternalId ?? null,
167
- providerId: input.providerId,
161
+ provider: integration.key,
168
162
  accountId: input.accountId,
169
163
  accessToken,
170
164
  accessTokenExpiresAt,
171
- connectionConfig: input.connectionConfig,
172
- });
165
+ scope: input.tokens.scope ?? null,
166
+ }, (tx, accountId) => this.store.storeConnection(tx, integration, {
167
+ accountId,
168
+ userId: input.userId,
169
+ environmentId: flow.environmentId,
170
+ configurationId: flow.configurationId,
171
+ metadata: input.metadata,
172
+ }));
173
173
  }
174
174
  /** Persists a refreshed token set. Shared with the refresh path. */
175
175
  async replaceCredential(accountId, tokens) {
@@ -193,28 +193,31 @@ let ConnectService = ConnectService_1 = class ConnectService {
193
193
  : {}),
194
194
  };
195
195
  }
196
- clientContextFor(configuration, credentials) {
197
- const settings = (configuration.settings ?? {});
196
+ clientContextFor(integration, configuration) {
197
+ const credentials = configuration.credentials
198
+ ? JSON.parse(this.crypto.decrypt(configuration.credentials))
199
+ : {};
200
+ const { publicUrl, globalPrefix } = this.config.server;
198
201
  return {
199
202
  clientId: String(credentials['clientId'] ?? ''),
200
203
  clientSecret: String(credentials['clientSecret'] ?? ''),
201
- redirectUri: settings.redirectUri ??
202
- this.configurations.callbackUrlFor(configuration.integrationKey),
203
- scopes: settings.scopes ?? [],
204
+ redirectUri: `${publicUrl}/${globalPrefix}/connect/callback/${integration.key}`,
205
+ // Declared by the package. An operator does not pick these, so there is
206
+ // nothing stored to drift from what the provider's console allows.
207
+ scopes: integration.auth.scopesRequested,
204
208
  };
205
209
  }
206
- async resolveConfiguration(environmentId, input) {
210
+ async resolveConfiguration(integration, environmentId, input) {
207
211
  const slug = input.configurationSlug?.trim();
208
212
  const id = input.configurationId?.trim();
209
213
  if (!slug && !id) {
210
214
  throw new BadRequestException('configurationId or configurationSlug is required');
211
215
  }
212
- if (slug)
213
- return this.configurations.getBySlug(environmentId, slug);
214
- const { configuration } = await this.configurations.getWithCredentials(id);
215
- if (configuration.environmentId !== environmentId) {
216
- throw new BadRequestException('Unknown configuration');
217
- }
216
+ const configuration = slug
217
+ ? await this.store.findConfigurationBySlug(integration, environmentId, slug)
218
+ : await this.store.findConfigurationById(integration, environmentId, id);
219
+ if (!configuration)
220
+ throw new NotFoundException('Configuration not found');
218
221
  return configuration;
219
222
  }
220
223
  /** An integration's hook must never take the request down with it. */
@@ -232,7 +235,7 @@ ConnectService = ConnectService_1 = __decorate([
232
235
  __param(5, Inject(KOSHA_CONFIG)),
233
236
  __metadata("design:paramtypes", [ConnectRepository,
234
237
  CryptoService,
235
- ConfigurationsService,
238
+ ProviderStore,
236
239
  EnvironmentsService,
237
240
  IntegrationRegistry, Object])
238
241
  ], ConnectService);
@@ -1,6 +1,6 @@
1
1
  export declare class CreateConnectSessionDto {
2
2
  externalUserId: string;
3
- organizationExternalId?: string;
3
+ provider: string;
4
4
  configurationSlug?: string;
5
5
  configurationId?: string;
6
6
  redirectUrl?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"create-connect-session.dto.d.ts","sourceRoot":"","sources":["../../../src/connect/dto/create-connect-session.dto.ts"],"names":[],"mappings":"AAGA,qBAAa,uBAAuB;IAQlC,cAAc,EAAG,MAAM,CAAC;IAUxB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAQhC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAO3B,eAAe,CAAC,EAAE,MAAM,CAAC;IAOzB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
1
+ {"version":3,"file":"create-connect-session.dto.d.ts","sourceRoot":"","sources":["../../../src/connect/dto/create-connect-session.dto.ts"],"names":[],"mappings":"AAGA,qBAAa,uBAAuB;IAQlC,cAAc,EAAG,MAAM,CAAC;IASxB,QAAQ,EAAG,MAAM,CAAC;IAQlB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAO3B,eAAe,CAAC,EAAE,MAAM,CAAC;IAOzB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}