@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.
- package/dist/auth/auth.factory.d.ts.map +1 -1
- package/dist/auth/auth.factory.js +0 -5
- package/dist/configurations/configurations.controller.d.ts +6 -5
- package/dist/configurations/configurations.controller.d.ts.map +1 -1
- package/dist/configurations/configurations.controller.js +22 -18
- package/dist/configurations/configurations.module.d.ts.map +1 -1
- package/dist/configurations/configurations.module.js +1 -2
- package/dist/configurations/configurations.service.d.ts +29 -35
- package/dist/configurations/configurations.service.d.ts.map +1 -1
- package/dist/configurations/configurations.service.js +126 -149
- package/dist/configurations/dto/create-configuration.dto.d.ts +2 -2
- package/dist/configurations/dto/create-configuration.dto.d.ts.map +1 -1
- package/dist/configurations/dto/create-configuration.dto.js +6 -6
- package/dist/configurations/dto/update-configuration.dto.d.ts +1 -2
- package/dist/configurations/dto/update-configuration.dto.d.ts.map +1 -1
- package/dist/configurations/dto/update-configuration.dto.js +7 -13
- package/dist/connect/connect.controller.d.ts +12 -2
- package/dist/connect/connect.controller.d.ts.map +1 -1
- package/dist/connect/connect.controller.js +108 -18
- package/dist/connect/connect.module.d.ts.map +1 -1
- package/dist/connect/connect.module.js +1 -2
- package/dist/connect/connect.repository.d.ts +34 -25
- package/dist/connect/connect.repository.d.ts.map +1 -1
- package/dist/connect/connect.repository.js +45 -52
- package/dist/connect/connect.service.d.ts +54 -8
- package/dist/connect/connect.service.d.ts.map +1 -1
- package/dist/connect/connect.service.js +312 -68
- package/dist/connect/dto/connect-credential.dto.d.ts +8 -0
- package/dist/connect/dto/connect-credential.dto.d.ts.map +1 -0
- package/dist/connect/dto/connect-credential.dto.js +54 -0
- package/dist/connect/dto/create-connect-session.dto.d.ts +1 -1
- package/dist/connect/dto/create-connect-session.dto.d.ts.map +1 -1
- package/dist/connect/dto/create-connect-session.dto.js +7 -8
- package/dist/connect/dto/create-test-session.dto.d.ts +8 -0
- package/dist/connect/dto/create-test-session.dto.d.ts.map +1 -1
- package/dist/connect/dto/create-test-session.dto.js +45 -3
- package/dist/connections/connections.controller.d.ts +4 -3
- package/dist/connections/connections.controller.d.ts.map +1 -1
- package/dist/connections/connections.controller.js +13 -11
- package/dist/connections/connections.repository.d.ts +24 -17
- package/dist/connections/connections.repository.d.ts.map +1 -1
- package/dist/connections/connections.repository.js +21 -43
- package/dist/connections/connections.service.d.ts +48 -13
- package/dist/connections/connections.service.d.ts.map +1 -1
- package/dist/connections/connections.service.js +111 -32
- package/dist/connections/dto/list-connections.dto.d.ts +3 -1
- package/dist/connections/dto/list-connections.dto.d.ts.map +1 -1
- package/dist/connections/dto/list-connections.dto.js +26 -4
- package/dist/connections/environment-connections.controller.d.ts +4 -3
- package/dist/connections/environment-connections.controller.d.ts.map +1 -1
- package/dist/connections/environment-connections.controller.js +14 -12
- package/dist/credentials/credentials.module.d.ts.map +1 -1
- package/dist/credentials/credentials.module.js +0 -2
- package/dist/credentials/credentials.repository.d.ts +5 -2
- package/dist/credentials/credentials.repository.d.ts.map +1 -1
- package/dist/credentials/credentials.repository.js +10 -3
- package/dist/credentials/credentials.service.d.ts +14 -4
- package/dist/credentials/credentials.service.d.ts.map +1 -1
- package/dist/credentials/credentials.service.js +106 -30
- package/dist/crypto/credential-envelope.d.ts +27 -1
- package/dist/crypto/credential-envelope.d.ts.map +1 -1
- package/dist/crypto/credential-envelope.js +43 -0
- package/dist/egress/egress.listener.d.ts +1 -3
- package/dist/egress/egress.listener.d.ts.map +1 -1
- package/dist/egress/egress.listener.js +3 -7
- package/dist/egress/egress.repository.d.ts +13 -6
- package/dist/egress/egress.repository.d.ts.map +1 -1
- package/dist/egress/egress.repository.js +31 -44
- package/dist/generated/prisma/browser.d.ts +0 -5
- package/dist/generated/prisma/browser.d.ts.map +1 -1
- package/dist/generated/prisma/client.d.ts +0 -5
- package/dist/generated/prisma/client.d.ts.map +1 -1
- package/dist/generated/prisma/commonInputTypes.d.ts +0 -55
- package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -1
- package/dist/generated/prisma/internal/class.d.ts +0 -11
- package/dist/generated/prisma/internal/class.d.ts.map +1 -1
- package/dist/generated/prisma/internal/class.js +4 -4
- package/dist/generated/prisma/internal/prismaNamespace.d.ts +1 -114
- package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -1
- package/dist/generated/prisma/internal/prismaNamespace.js +2 -29
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +0 -30
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -1
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +2 -29
- package/dist/generated/prisma/models/Account.d.ts +26 -344
- package/dist/generated/prisma/models/Account.d.ts.map +1 -1
- package/dist/generated/prisma/models/Environment.d.ts +0 -258
- package/dist/generated/prisma/models/Environment.d.ts.map +1 -1
- package/dist/generated/prisma/models/User.d.ts +2 -60
- package/dist/generated/prisma/models/User.d.ts.map +1 -1
- package/dist/generated/prisma/models.d.ts +0 -1
- package/dist/generated/prisma/models.d.ts.map +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/integrations/client-context.d.ts +20 -0
- package/dist/integrations/client-context.d.ts.map +1 -0
- package/dist/integrations/client-context.js +23 -0
- package/dist/integrations/integrations.controller.d.ts +6 -0
- package/dist/integrations/integrations.controller.d.ts.map +1 -1
- package/dist/integrations/integrations.controller.js +3 -0
- package/dist/integrations/integrations.module.d.ts.map +1 -1
- package/dist/integrations/integrations.module.js +3 -1
- package/dist/integrations/provider-store.d.ts +110 -0
- package/dist/integrations/provider-store.d.ts.map +1 -0
- package/dist/integrations/provider-store.js +302 -0
- package/dist/proxy/proxy.controller.d.ts +17 -5
- package/dist/proxy/proxy.controller.d.ts.map +1 -1
- package/dist/proxy/proxy.controller.js +46 -17
- package/dist/proxy/proxy.module.d.ts.map +1 -1
- package/dist/proxy/proxy.module.js +1 -2
- package/dist/proxy/proxy.repository.d.ts +11 -14
- package/dist/proxy/proxy.repository.d.ts.map +1 -1
- package/dist/proxy/proxy.repository.js +17 -27
- package/dist/proxy/proxy.service.d.ts +6 -8
- package/dist/proxy/proxy.service.d.ts.map +1 -1
- package/dist/proxy/proxy.service.js +72 -31
- package/package.json +4 -4
- package/prisma/migrations/{20260929101936_init → 20261008090000_init}/migration.sql +5 -58
- package/prisma/schema.prisma +2 -43
- package/dist/configurations/configurations.repository.d.ts +0 -43
- package/dist/configurations/configurations.repository.d.ts.map +0 -1
- package/dist/configurations/configurations.repository.js +0 -76
- package/dist/generated/prisma/models/Configuration.d.ts +0 -1385
- package/dist/generated/prisma/models/Configuration.d.ts.map +0 -1
- package/dist/generated/prisma/models/Configuration.js +0 -1
- package/prisma/migrations/20260930102529_connection_config/migration.sql +0 -2
|
@@ -1,20 +1,44 @@
|
|
|
1
1
|
var ConnectService_1;
|
|
2
2
|
import { __decorate, __metadata, __param } from "tslib";
|
|
3
|
-
import { BadRequestException, ConflictException, Inject, Injectable, Logger, NotFoundException, } from '@nestjs/common';
|
|
3
|
+
import { BadGatewayException, BadRequestException, ConflictException, Inject, Injectable, Logger, NotFoundException, } from '@nestjs/common';
|
|
4
4
|
import { randomBytes } from 'node:crypto';
|
|
5
|
-
import { generateCodeVerifier, httpFor } from '@kosha-ai/integration-sdk';
|
|
5
|
+
import { generateCodeVerifier, httpFor, isRedirectStrategy, } from '@kosha-ai/integration-sdk';
|
|
6
6
|
import { KOSHA_CONFIG } from '../config/tokens.js';
|
|
7
|
-
import {
|
|
8
|
-
import { ENVELOPE_VERSION, expiryOf, } from '../crypto/credential-envelope.js';
|
|
7
|
+
import { ENVELOPE_VERSION, expiryOf, storedSecondaryToken, } from '../crypto/credential-envelope.js';
|
|
9
8
|
import { CryptoService } from '../crypto/crypto.service.js';
|
|
10
9
|
import { EnvironmentsService } from '../environments/environments.service.js';
|
|
10
|
+
import { clientContextFor } from '../integrations/client-context.js';
|
|
11
11
|
import { IntegrationRegistry } from '../integrations/integration.registry.js';
|
|
12
|
+
import { ProviderStore, } from '../integrations/provider-store.js';
|
|
12
13
|
import { ConnectRepository } from './connect.repository.js';
|
|
13
14
|
const SESSION_TTL_MS = 10 * 60 * 1000;
|
|
14
15
|
const STATE_TTL_MS = 10 * 60 * 1000;
|
|
16
|
+
export const MAX_LOGGED = 500;
|
|
17
|
+
/**
|
|
18
|
+
* A connect flow that ended without a credential, carrying where the person
|
|
19
|
+
* should be sent back to and why.
|
|
20
|
+
*/
|
|
21
|
+
export class ConnectFlowEnded extends Error {
|
|
22
|
+
status;
|
|
23
|
+
redirectUrl;
|
|
24
|
+
constructor(status, redirectUrl) {
|
|
25
|
+
super(status === 'denied'
|
|
26
|
+
? 'The end user declined at the provider'
|
|
27
|
+
: 'Connect flow expired');
|
|
28
|
+
this.status = status;
|
|
29
|
+
this.redirectUrl = redirectUrl;
|
|
30
|
+
this.name = 'ConnectFlowEnded';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
15
33
|
function randomToken() {
|
|
16
34
|
return randomBytes(32).toString('hex');
|
|
17
35
|
}
|
|
36
|
+
/** The exchange's secondary tokens, as the envelope stores them. */
|
|
37
|
+
function storedSecondary(tokens) {
|
|
38
|
+
if (!tokens.secondary?.length)
|
|
39
|
+
return undefined;
|
|
40
|
+
return Object.fromEntries(tokens.secondary.map((token) => [token.kind, storedSecondaryToken(token)]));
|
|
41
|
+
}
|
|
18
42
|
/**
|
|
19
43
|
* Drives the OAuth handshake that turns an end user's consent into a stored,
|
|
20
44
|
* encrypted credential.
|
|
@@ -25,15 +49,15 @@ function randomToken() {
|
|
|
25
49
|
let ConnectService = ConnectService_1 = class ConnectService {
|
|
26
50
|
connect;
|
|
27
51
|
crypto;
|
|
28
|
-
|
|
52
|
+
store;
|
|
29
53
|
environments;
|
|
30
54
|
registry;
|
|
31
55
|
config;
|
|
32
56
|
logger = new Logger(ConnectService_1.name);
|
|
33
|
-
constructor(connect, crypto,
|
|
57
|
+
constructor(connect, crypto, store, environments, registry, config) {
|
|
34
58
|
this.connect = connect;
|
|
35
59
|
this.crypto = crypto;
|
|
36
|
-
this.
|
|
60
|
+
this.store = store;
|
|
37
61
|
this.environments = environments;
|
|
38
62
|
this.registry = registry;
|
|
39
63
|
this.config = config;
|
|
@@ -48,10 +72,11 @@ let ConnectService = ConnectService_1 = class ConnectService {
|
|
|
48
72
|
throw new BadRequestException('externalUserId is required');
|
|
49
73
|
}
|
|
50
74
|
const environment = await this.environments.get(organizationId, environmentId);
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
75
|
+
const integration = this.registry.get(input.provider);
|
|
76
|
+
// Refused here rather than when the end user opens the link, so the
|
|
77
|
+
// backend that asked for it is the one that hears about it.
|
|
78
|
+
redirectStrategyOf(integration);
|
|
79
|
+
const configuration = await this.resolveConfiguration(integration, environmentId, input);
|
|
55
80
|
// Nothing else sweeps these: `verification` is shared with email
|
|
56
81
|
// verification and password reset, so only this flow knows which rows are
|
|
57
82
|
// its own. Swept here rather than on a schedule, so no timer has to exist.
|
|
@@ -64,9 +89,9 @@ let ConnectService = ConnectService_1 = class ConnectService {
|
|
|
64
89
|
organizationId,
|
|
65
90
|
environmentId: environment.id,
|
|
66
91
|
environmentSlug: environment.slug,
|
|
92
|
+
provider: integration.key,
|
|
67
93
|
configurationId: configuration.id,
|
|
68
94
|
externalUserId,
|
|
69
|
-
organizationExternalId: input.organizationExternalId?.trim() || null,
|
|
70
95
|
redirectUrl: input.redirectUrl ?? null,
|
|
71
96
|
}, expiresAt);
|
|
72
97
|
const { publicUrl, globalPrefix } = this.config.server;
|
|
@@ -82,56 +107,127 @@ let ConnectService = ConnectService_1 = class ConnectService {
|
|
|
82
107
|
* across the redirect.
|
|
83
108
|
*/
|
|
84
109
|
async buildAuthorizationRedirect(token) {
|
|
85
|
-
const
|
|
86
|
-
if (!
|
|
110
|
+
const taken = await this.connect.takeSession(token);
|
|
111
|
+
if (!taken) {
|
|
87
112
|
throw new NotFoundException('Connect session not found or expired');
|
|
88
113
|
}
|
|
89
|
-
|
|
90
|
-
|
|
114
|
+
if (taken.expired) {
|
|
115
|
+
throw new ConnectFlowEnded('expired', taken.flow.redirectUrl ?? null);
|
|
116
|
+
}
|
|
117
|
+
const session = taken.flow;
|
|
118
|
+
const integration = this.registry.get(session.provider);
|
|
119
|
+
const configuration = await this.store.findConfigurationWithCredentials(integration, session.configurationId);
|
|
120
|
+
if (!configuration) {
|
|
91
121
|
throw new BadRequestException('Configuration is no longer available');
|
|
92
122
|
}
|
|
93
|
-
const integration = this.registry.get(configuration.integrationKey);
|
|
94
123
|
const codeVerifier = integration.auth.pkce
|
|
95
124
|
? generateCodeVerifier()
|
|
96
125
|
: undefined;
|
|
97
126
|
const state = randomToken();
|
|
98
127
|
await this.connect.putState(state, { ...session, codeVerifier }, new Date(Date.now() + STATE_TTL_MS));
|
|
99
|
-
|
|
100
|
-
|
|
128
|
+
const prepared = await this.prepareClient(integration, configuration);
|
|
129
|
+
return redirectStrategyOf(integration).buildAuthorizationUrl({
|
|
130
|
+
client: this.clientContextFor(integration, prepared),
|
|
101
131
|
state,
|
|
102
132
|
codeVerifier,
|
|
103
133
|
});
|
|
104
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* Gives a provider whose endpoints and client are not known until an
|
|
137
|
+
* operator supplies a URL a chance to discover and register them, once per
|
|
138
|
+
* configuration. Persisted onto the configuration so refresh — which has no
|
|
139
|
+
* redirect to carry fresh discovery across — reads the same thing back.
|
|
140
|
+
*/
|
|
141
|
+
async prepareClient(integration, configuration) {
|
|
142
|
+
if (!integration.auth.prepareClient)
|
|
143
|
+
return configuration;
|
|
144
|
+
const { publicUrl, globalPrefix } = this.config.server;
|
|
145
|
+
const result = await integration.auth.prepareClient({
|
|
146
|
+
fields: configuration.fields,
|
|
147
|
+
redirectUri: `${publicUrl}/${globalPrefix}/connect/callback/${integration.key}`,
|
|
148
|
+
});
|
|
149
|
+
if (!result)
|
|
150
|
+
return configuration;
|
|
151
|
+
const existingCredentials = configuration.credentials
|
|
152
|
+
? JSON.parse(this.crypto.decrypt(configuration.credentials))
|
|
153
|
+
: {};
|
|
154
|
+
const mergedCredentials = result.credentials
|
|
155
|
+
? { ...existingCredentials, ...result.credentials }
|
|
156
|
+
: undefined;
|
|
157
|
+
const mergedFields = result.fields
|
|
158
|
+
? { ...configuration.fields, ...result.fields }
|
|
159
|
+
: configuration.fields;
|
|
160
|
+
const sealedCredentials = mergedCredentials
|
|
161
|
+
? this.crypto.encrypt(JSON.stringify(mergedCredentials))
|
|
162
|
+
: configuration.credentials;
|
|
163
|
+
await this.store.updateConfiguration(integration, configuration.id, {
|
|
164
|
+
fields: result.fields,
|
|
165
|
+
credentials: mergedCredentials ? sealedCredentials : undefined,
|
|
166
|
+
});
|
|
167
|
+
return {
|
|
168
|
+
...configuration,
|
|
169
|
+
fields: mergedFields,
|
|
170
|
+
credentials: sealedCredentials,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The person declined at the provider. Burns the state, so the flow cannot
|
|
175
|
+
* be completed afterwards, and says where to send them. A state from another
|
|
176
|
+
* provider's flow has nowhere to send them; one past its window is expired.
|
|
177
|
+
*
|
|
178
|
+
* The provider's reason is logged, never sent back: it is the only trace of
|
|
179
|
+
* a misconfigured provider, and the flow names where it happened. Both it
|
|
180
|
+
* and the provider come from the request, so they are logged quoted.
|
|
181
|
+
*/
|
|
182
|
+
async deny(provider, state, reason) {
|
|
183
|
+
const taken = state ? await this.connect.takeState(state) : null;
|
|
184
|
+
const flow = taken?.flow.provider === provider ? taken.flow : null;
|
|
185
|
+
this.logger.warn(`${JSON.stringify(provider.slice(0, MAX_LOGGED))} returned an error for ${flow
|
|
186
|
+
? `configuration ${flow.configurationId} in environment ${flow.environmentId}`
|
|
187
|
+
: 'an unknown connect flow'}: ${JSON.stringify(reason.slice(0, MAX_LOGGED))}`);
|
|
188
|
+
if (!taken || !flow)
|
|
189
|
+
return new ConnectFlowEnded('denied', null);
|
|
190
|
+
return new ConnectFlowEnded(taken.expired ? 'expired' : 'denied', flow.redirectUrl ?? null);
|
|
191
|
+
}
|
|
105
192
|
/** Handles the provider's redirect back to Kosha. */
|
|
106
|
-
async handleCallback(
|
|
107
|
-
const
|
|
108
|
-
if (!
|
|
193
|
+
async handleCallback(provider, code, state) {
|
|
194
|
+
const taken = await this.connect.takeState(state);
|
|
195
|
+
if (!taken) {
|
|
109
196
|
throw new NotFoundException('OAuth state not found or expired');
|
|
110
197
|
}
|
|
111
|
-
const
|
|
112
|
-
if (
|
|
198
|
+
const flow = taken.flow;
|
|
199
|
+
if (flow.provider !== provider) {
|
|
113
200
|
throw new BadRequestException('Provider mismatch');
|
|
114
201
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
202
|
+
if (taken.expired) {
|
|
203
|
+
throw new ConnectFlowEnded('expired', flow.redirectUrl ?? null);
|
|
204
|
+
}
|
|
205
|
+
const integration = this.registry.get(provider);
|
|
206
|
+
const configuration = await this.store.findConfigurationWithCredentials(integration, flow.configurationId);
|
|
207
|
+
if (!configuration) {
|
|
208
|
+
throw new BadRequestException('Configuration is no longer available');
|
|
209
|
+
}
|
|
210
|
+
const tokens = await redirectStrategyOf(integration).exchangeCode({
|
|
211
|
+
client: this.clientContextFor(integration, configuration),
|
|
118
212
|
code,
|
|
119
213
|
codeVerifier: flow.codeVerifier,
|
|
120
214
|
});
|
|
121
215
|
const identity = await integration.identity.fetchAccount({
|
|
122
216
|
accessToken: tokens.accessToken,
|
|
123
217
|
http: httpFor(integration),
|
|
218
|
+
fields: configuration.fields,
|
|
219
|
+
tokens,
|
|
124
220
|
});
|
|
125
221
|
const user = await this.connect.upsertEndUser(flow.environmentSlug, flow.externalUserId);
|
|
126
|
-
const account = await this.writeCredential(flow, {
|
|
222
|
+
const account = await this.writeCredential(flow, integration, {
|
|
127
223
|
userId: user.id,
|
|
128
|
-
providerId: configuration.id,
|
|
129
224
|
accountId: identity.externalAccountId,
|
|
130
|
-
tokens,
|
|
225
|
+
envelope: this.envelopeFor(tokens),
|
|
226
|
+
scope: tokens.scope,
|
|
131
227
|
// What the provider told us about this account that a later proxied
|
|
132
228
|
// call needs — the Jira site, for one. Without storing it here, a
|
|
133
229
|
// provider with no fixed host has no resolvable base URL at all.
|
|
134
|
-
|
|
230
|
+
metadata: identity.metadata,
|
|
135
231
|
});
|
|
136
232
|
await this.runHook(integration, () => integration.hooks?.onConnectionCreated?.({
|
|
137
233
|
connectionId: account.id,
|
|
@@ -140,36 +236,104 @@ let ConnectService = ConnectService_1 = class ConnectService {
|
|
|
140
236
|
return { connectionId: account.id, redirectUrl: flow.redirectUrl ?? null };
|
|
141
237
|
}
|
|
142
238
|
/**
|
|
143
|
-
*
|
|
239
|
+
* Creates a connection from a credential the end user already holds.
|
|
240
|
+
*
|
|
241
|
+
* The counterpart to the redirect flow: no connect session, no state to
|
|
242
|
+
* burn, no callback. The consuming app collects the key from its own user
|
|
243
|
+
* and posts it here, so that person needs no Kosha login and Kosha still
|
|
244
|
+
* owns the secret.
|
|
144
245
|
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
147
|
-
* revoking first, which is a deliberate act by someone who can see what they
|
|
148
|
-
* are replacing.
|
|
246
|
+
* The key is proved before anything is written, because a key that cannot
|
|
247
|
+
* name its own account is not one this connection can use.
|
|
149
248
|
*/
|
|
150
|
-
async
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
249
|
+
async connectWithCredential(organizationId, environmentId, input) {
|
|
250
|
+
const externalUserId = input.externalUserId?.trim();
|
|
251
|
+
if (!externalUserId) {
|
|
252
|
+
throw new BadRequestException('externalUserId is required');
|
|
253
|
+
}
|
|
254
|
+
const environment = await this.environments.get(organizationId, environmentId);
|
|
255
|
+
const integration = this.registry.get(input.provider);
|
|
256
|
+
if (isRedirectStrategy(integration.auth)) {
|
|
257
|
+
throw new BadRequestException(`${integration.key} sends the end user to the provider. Use /connect/sessions instead.`);
|
|
258
|
+
}
|
|
259
|
+
const configuration = await this.resolveConfiguration(integration, environmentId, input);
|
|
260
|
+
const supplied = suppliedCredential(integration, input.credential);
|
|
261
|
+
const envelope = envelopeForCredential(integration, supplied);
|
|
262
|
+
const identity = await this.proveCredential(integration, usableSecret(envelope), configuration.fields);
|
|
263
|
+
const user = await this.connect.upsertEndUser(environment.slug, externalUserId);
|
|
264
|
+
const account = await this.writeCredential({ environmentId, configurationId: configuration.id }, integration, {
|
|
265
|
+
userId: user.id,
|
|
266
|
+
accountId: identity.externalAccountId,
|
|
267
|
+
envelope,
|
|
268
|
+
metadata: identity.metadata,
|
|
157
269
|
});
|
|
270
|
+
await this.runHook(integration, () => integration.hooks?.onConnectionCreated?.({
|
|
271
|
+
connectionId: account.id,
|
|
272
|
+
organizationId,
|
|
273
|
+
}));
|
|
274
|
+
return { connectionId: account.id, redirectUrl: null };
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Asks the provider who the key belongs to, which is the only check
|
|
278
|
+
* available and the right one.
|
|
279
|
+
*
|
|
280
|
+
* The provider's own message is withheld, because it can echo the key back.
|
|
281
|
+
*/
|
|
282
|
+
async proveCredential(integration, key, fields) {
|
|
283
|
+
// A provider with no fixed host is reached at whatever the configuration
|
|
284
|
+
// named, which is also what it will be proxied to later.
|
|
285
|
+
const baseUrl = integration.api.resolveBaseUrl?.({
|
|
286
|
+
credential: { accessToken: key },
|
|
287
|
+
fields,
|
|
288
|
+
});
|
|
289
|
+
try {
|
|
290
|
+
return await integration.identity.fetchAccount({
|
|
291
|
+
accessToken: key,
|
|
292
|
+
http: httpFor(integration, baseUrl),
|
|
293
|
+
fields,
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
catch (error) {
|
|
297
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
298
|
+
this.logger.warn(`Credential rejected by ${integration.key}: ${redact(message, key)}`);
|
|
299
|
+
// A transport failure is not the provider saying no, and telling the
|
|
300
|
+
// caller to check their key would be wrong.
|
|
301
|
+
if (looksLikeTransportFailure(error)) {
|
|
302
|
+
throw new BadGatewayException(`Could not reach ${integration.key} to check the credential.`);
|
|
303
|
+
}
|
|
304
|
+
throw new BadRequestException(`${integration.key} rejected that credential.`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Writes the credential, refusing when one is already there.
|
|
309
|
+
*
|
|
310
|
+
* Replacing silently would let somebody take over a credential a colleague
|
|
311
|
+
* connected, with no trace. Reconnecting means revoking first, which is a
|
|
312
|
+
* deliberate act by someone who can see what they are replacing.
|
|
313
|
+
*/
|
|
314
|
+
async writeCredential(target, integration, input) {
|
|
315
|
+
const accessToken = this.crypto.sealEnvelope(input.envelope);
|
|
316
|
+
const accessTokenExpiresAt = expiryOf(input.envelope);
|
|
317
|
+
// Read before writing, so a second connect is a clear refusal rather than
|
|
318
|
+
// the unique index surfacing as a 500. The index is still the backstop.
|
|
319
|
+
const existing = await this.store.findConnection(integration, target.environmentId, target.configurationId, input.userId);
|
|
158
320
|
if (existing) {
|
|
159
|
-
throw new ConflictException(
|
|
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.');
|
|
321
|
+
throw new ConflictException('This person is already connected to this configuration. Revoke that connection first.');
|
|
162
322
|
}
|
|
163
323
|
return this.connect.storeCredential({
|
|
164
324
|
userId: input.userId,
|
|
165
|
-
|
|
166
|
-
organizationExternalId: flow.organizationExternalId ?? null,
|
|
167
|
-
providerId: input.providerId,
|
|
325
|
+
provider: integration.key,
|
|
168
326
|
accountId: input.accountId,
|
|
169
327
|
accessToken,
|
|
170
328
|
accessTokenExpiresAt,
|
|
171
|
-
|
|
172
|
-
})
|
|
329
|
+
scope: input.scope ?? null,
|
|
330
|
+
}, (tx, accountId) => this.store.storeConnection(tx, integration, {
|
|
331
|
+
accountId,
|
|
332
|
+
userId: input.userId,
|
|
333
|
+
environmentId: target.environmentId,
|
|
334
|
+
configurationId: target.configurationId,
|
|
335
|
+
metadata: input.metadata,
|
|
336
|
+
}));
|
|
173
337
|
}
|
|
174
338
|
/** Persists a refreshed token set. Shared with the refresh path. */
|
|
175
339
|
async replaceCredential(accountId, tokens) {
|
|
@@ -180,6 +344,7 @@ let ConnectService = ConnectService_1 = class ConnectService {
|
|
|
180
344
|
});
|
|
181
345
|
}
|
|
182
346
|
envelopeFor(tokens) {
|
|
347
|
+
const secondary = storedSecondary(tokens);
|
|
183
348
|
return {
|
|
184
349
|
v: ENVELOPE_VERSION,
|
|
185
350
|
type: 'oauth2',
|
|
@@ -191,30 +356,33 @@ let ConnectService = ConnectService_1 = class ConnectService {
|
|
|
191
356
|
expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000).toISOString(),
|
|
192
357
|
}
|
|
193
358
|
: {}),
|
|
359
|
+
...(secondary ? { secondary } : {}),
|
|
194
360
|
};
|
|
195
361
|
}
|
|
196
|
-
clientContextFor(
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
362
|
+
clientContextFor(integration, configuration) {
|
|
363
|
+
return clientContextFor({
|
|
364
|
+
integration,
|
|
365
|
+
configuration,
|
|
366
|
+
credentials: configuration.credentials
|
|
367
|
+
? JSON.parse(this.crypto.decrypt(configuration.credentials))
|
|
368
|
+
: {},
|
|
369
|
+
server: this.config.server,
|
|
370
|
+
// Declared by the package. An operator does not pick these, so there is
|
|
371
|
+
// nothing stored to drift from what the provider's console allows.
|
|
372
|
+
scopes: integration.auth.scopesRequested,
|
|
373
|
+
});
|
|
205
374
|
}
|
|
206
|
-
async resolveConfiguration(environmentId, input) {
|
|
375
|
+
async resolveConfiguration(integration, environmentId, input) {
|
|
207
376
|
const slug = input.configurationSlug?.trim();
|
|
208
377
|
const id = input.configurationId?.trim();
|
|
209
378
|
if (!slug && !id) {
|
|
210
379
|
throw new BadRequestException('configurationId or configurationSlug is required');
|
|
211
380
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
if (configuration
|
|
216
|
-
throw new
|
|
217
|
-
}
|
|
381
|
+
const configuration = slug
|
|
382
|
+
? await this.store.findConfigurationBySlug(integration, environmentId, slug)
|
|
383
|
+
: await this.store.findConfigurationById(integration, environmentId, id);
|
|
384
|
+
if (!configuration)
|
|
385
|
+
throw new NotFoundException('Configuration not found');
|
|
218
386
|
return configuration;
|
|
219
387
|
}
|
|
220
388
|
/** An integration's hook must never take the request down with it. */
|
|
@@ -232,8 +400,84 @@ ConnectService = ConnectService_1 = __decorate([
|
|
|
232
400
|
__param(5, Inject(KOSHA_CONFIG)),
|
|
233
401
|
__metadata("design:paramtypes", [ConnectRepository,
|
|
234
402
|
CryptoService,
|
|
235
|
-
|
|
403
|
+
ProviderStore,
|
|
236
404
|
EnvironmentsService,
|
|
237
405
|
IntegrationRegistry, Object])
|
|
238
406
|
], ConnectService);
|
|
239
407
|
export { ConnectService };
|
|
408
|
+
/** An auth type with no redirect has no connect flow of this shape to run. */
|
|
409
|
+
function redirectStrategyOf(integration) {
|
|
410
|
+
if (!isRedirectStrategy(integration.auth)) {
|
|
411
|
+
throw new BadRequestException(`${integration.key} does not send the end user to the provider, so it has no connect link.`);
|
|
412
|
+
}
|
|
413
|
+
return integration.auth;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* The one secret to store. The SDK hands a provider a single `accessToken`,
|
|
417
|
+
* so a provider asking for more than one value has nowhere to put the rest.
|
|
418
|
+
*/
|
|
419
|
+
/**
|
|
420
|
+
* What the end user supplied, checked against what the package declared.
|
|
421
|
+
*
|
|
422
|
+
* A key nothing declared is refused rather than ignored: silently dropping
|
|
423
|
+
* half of what somebody typed is how a connection is stored that cannot work.
|
|
424
|
+
*/
|
|
425
|
+
function suppliedCredential(integration, credential) {
|
|
426
|
+
const fields = integration.auth.credentialFields ?? [];
|
|
427
|
+
if (fields.length === 0) {
|
|
428
|
+
throw new BadRequestException(`${integration.key} declares no credential for an end user to supply.`);
|
|
429
|
+
}
|
|
430
|
+
const declared = new Set(fields.map((field) => field.key));
|
|
431
|
+
const unknown = Object.keys(credential ?? {}).filter((key) => !declared.has(key));
|
|
432
|
+
if (unknown.length > 0) {
|
|
433
|
+
throw new BadRequestException(`${integration.key} declares no credential field named ${unknown.join(' or ')}`);
|
|
434
|
+
}
|
|
435
|
+
const supplied = {};
|
|
436
|
+
for (const field of fields) {
|
|
437
|
+
const value = credential?.[field.key];
|
|
438
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
439
|
+
if (field.required !== false) {
|
|
440
|
+
throw new BadRequestException(`credential.${field.key} is required`);
|
|
441
|
+
}
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
supplied[field.key] = value.trim();
|
|
445
|
+
}
|
|
446
|
+
return supplied;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* What `fetchAccount` is given to prove the credential, which is the same
|
|
450
|
+
* string the proxy will later sign requests with.
|
|
451
|
+
*/
|
|
452
|
+
function usableSecret(envelope) {
|
|
453
|
+
return envelope.type === 'basic'
|
|
454
|
+
? Buffer.from(`${envelope.username}:${envelope.password}`).toString('base64')
|
|
455
|
+
: envelope.type === 'api_key'
|
|
456
|
+
? envelope.key
|
|
457
|
+
: '';
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* The envelope a supplied credential becomes, which is the auth type's answer
|
|
461
|
+
* rather than the schema's.
|
|
462
|
+
*/
|
|
463
|
+
function envelopeForCredential(integration, supplied) {
|
|
464
|
+
if (integration.auth.type === 'BASIC') {
|
|
465
|
+
return {
|
|
466
|
+
v: ENVELOPE_VERSION,
|
|
467
|
+
type: 'basic',
|
|
468
|
+
username: supplied['username'] ?? '',
|
|
469
|
+
password: supplied['password'] ?? '',
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
// Everything else hands over one secret, whatever the package calls it.
|
|
473
|
+
const [only] = Object.values(supplied);
|
|
474
|
+
return { v: ENVELOPE_VERSION, type: 'api_key', key: only ?? '' };
|
|
475
|
+
}
|
|
476
|
+
/** `fetch` reports a host it never reached as a TypeError with a cause. */
|
|
477
|
+
function looksLikeTransportFailure(error) {
|
|
478
|
+
return error instanceof TypeError;
|
|
479
|
+
}
|
|
480
|
+
/** Keeps the key out of the log, by value rather than by trusting call sites. */
|
|
481
|
+
function redact(message, key) {
|
|
482
|
+
return key ? message.split(key).join('[redacted]') : message;
|
|
483
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-credential.dto.d.ts","sourceRoot":"","sources":["../../../src/connect/dto/connect-credential.dto.ts"],"names":[],"mappings":"AASA,qBAAa,wBAAwB;IAQnC,cAAc,EAAG,MAAM,CAAC;IAQxB,QAAQ,EAAG,MAAM,CAAC;IAQlB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAO3B,eAAe,CAAC,EAAE,MAAM,CAAC;IAQzB,UAAU,EAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACtC"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { __decorate, __metadata } from "tslib";
|
|
2
|
+
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
|
3
|
+
import { IsObject, IsOptional, IsString, MaxLength, MinLength, } from 'class-validator';
|
|
4
|
+
export class ConnectWithCredentialDto {
|
|
5
|
+
externalUserId;
|
|
6
|
+
provider;
|
|
7
|
+
configurationSlug;
|
|
8
|
+
configurationId;
|
|
9
|
+
credential;
|
|
10
|
+
}
|
|
11
|
+
__decorate([
|
|
12
|
+
ApiProperty({
|
|
13
|
+
example: 'user_9',
|
|
14
|
+
description: 'The consuming app’s own id for the person connecting.',
|
|
15
|
+
}),
|
|
16
|
+
IsString(),
|
|
17
|
+
MinLength(1),
|
|
18
|
+
MaxLength(255),
|
|
19
|
+
__metadata("design:type", String)
|
|
20
|
+
], ConnectWithCredentialDto.prototype, "externalUserId", void 0);
|
|
21
|
+
__decorate([
|
|
22
|
+
ApiProperty({
|
|
23
|
+
example: 'apollo',
|
|
24
|
+
description: 'Which provider. Must be one whose end user holds the key.',
|
|
25
|
+
}),
|
|
26
|
+
IsString(),
|
|
27
|
+
MinLength(1),
|
|
28
|
+
__metadata("design:type", String)
|
|
29
|
+
], ConnectWithCredentialDto.prototype, "provider", void 0);
|
|
30
|
+
__decorate([
|
|
31
|
+
ApiPropertyOptional({
|
|
32
|
+
example: 'apollo-main',
|
|
33
|
+
description: 'Configuration slug, as named in this environment.',
|
|
34
|
+
}),
|
|
35
|
+
IsOptional(),
|
|
36
|
+
IsString(),
|
|
37
|
+
__metadata("design:type", String)
|
|
38
|
+
], ConnectWithCredentialDto.prototype, "configurationSlug", void 0);
|
|
39
|
+
__decorate([
|
|
40
|
+
ApiPropertyOptional({
|
|
41
|
+
description: 'Configuration id, instead of the slug.',
|
|
42
|
+
}),
|
|
43
|
+
IsOptional(),
|
|
44
|
+
IsString(),
|
|
45
|
+
__metadata("design:type", String)
|
|
46
|
+
], ConnectWithCredentialDto.prototype, "configurationId", void 0);
|
|
47
|
+
__decorate([
|
|
48
|
+
ApiProperty({
|
|
49
|
+
description: 'What the end user supplied, keyed by the provider’s credentialFields.',
|
|
50
|
+
example: { credential: 'ap_live_…' },
|
|
51
|
+
}),
|
|
52
|
+
IsObject(),
|
|
53
|
+
__metadata("design:type", Object)
|
|
54
|
+
], ConnectWithCredentialDto.prototype, "credential", void 0);
|
|
@@ -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;
|
|
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"}
|
|
@@ -3,7 +3,7 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
|
|
3
3
|
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
|
4
4
|
export class CreateConnectSessionDto {
|
|
5
5
|
externalUserId;
|
|
6
|
-
|
|
6
|
+
provider;
|
|
7
7
|
configurationSlug;
|
|
8
8
|
configurationId;
|
|
9
9
|
redirectUrl;
|
|
@@ -19,18 +19,17 @@ __decorate([
|
|
|
19
19
|
__metadata("design:type", String)
|
|
20
20
|
], CreateConnectSessionDto.prototype, "externalUserId", void 0);
|
|
21
21
|
__decorate([
|
|
22
|
-
|
|
23
|
-
example: '
|
|
24
|
-
description: '
|
|
22
|
+
ApiProperty({
|
|
23
|
+
example: 'github',
|
|
24
|
+
description: 'Which provider. Configurations live in per-provider tables, so a slug is only unique within one.',
|
|
25
25
|
}),
|
|
26
|
-
IsOptional(),
|
|
27
26
|
IsString(),
|
|
28
|
-
|
|
27
|
+
MinLength(1),
|
|
29
28
|
__metadata("design:type", String)
|
|
30
|
-
], CreateConnectSessionDto.prototype, "
|
|
29
|
+
], CreateConnectSessionDto.prototype, "provider", void 0);
|
|
31
30
|
__decorate([
|
|
32
31
|
ApiPropertyOptional({
|
|
33
|
-
example: 'github',
|
|
32
|
+
example: 'my-github',
|
|
34
33
|
description: 'Configuration slug, as named in this environment.',
|
|
35
34
|
}),
|
|
36
35
|
IsOptional(),
|
|
@@ -3,8 +3,16 @@
|
|
|
3
3
|
* configuration without wiring up their backend first.
|
|
4
4
|
*/
|
|
5
5
|
export declare class CreateTestSessionDto {
|
|
6
|
+
provider: string;
|
|
6
7
|
slug?: string;
|
|
7
8
|
configurationId?: string;
|
|
8
9
|
redirectUrl?: string;
|
|
9
10
|
}
|
|
11
|
+
/** The same, for a provider whose credential the operator pastes in. */
|
|
12
|
+
export declare class TestCredentialDto {
|
|
13
|
+
provider: string;
|
|
14
|
+
slug?: string;
|
|
15
|
+
configurationId?: string;
|
|
16
|
+
credential: Record<string, unknown>;
|
|
17
|
+
}
|
|
10
18
|
//# sourceMappingURL=create-test-session.dto.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-test-session.dto.d.ts","sourceRoot":"","sources":["../../../src/connect/dto/create-test-session.dto.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,qBAAa,oBAAoB;IAI/B,IAAI,CAAC,EAAE,MAAM,CAAC;IAOd,eAAe,CAAC,EAAE,MAAM,CAAC;IAOzB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
|
|
1
|
+
{"version":3,"file":"create-test-session.dto.d.ts","sourceRoot":"","sources":["../../../src/connect/dto/create-test-session.dto.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,qBAAa,oBAAoB;IAI/B,QAAQ,EAAG,MAAM,CAAC;IAKlB,IAAI,CAAC,EAAE,MAAM,CAAC;IAOd,eAAe,CAAC,EAAE,MAAM,CAAC;IAOzB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,wEAAwE;AACxE,qBAAa,iBAAiB;IAI5B,QAAQ,EAAG,MAAM,CAAC;IAKlB,IAAI,CAAC,EAAE,MAAM,CAAC;IAOd,eAAe,CAAC,EAAE,MAAM,CAAC;IAOzB,UAAU,EAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACtC"}
|