@kosha-ai/server 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/auth/api-key.guard.d.ts +18 -0
- package/dist/auth/api-key.guard.d.ts.map +1 -0
- package/dist/auth/api-key.guard.js +33 -0
- package/dist/auth/auth.factory.d.ts +35 -0
- package/dist/auth/auth.factory.d.ts.map +1 -0
- package/dist/auth/auth.factory.js +29 -0
- package/dist/bootstrap.d.ts +13 -0
- package/dist/bootstrap.d.ts.map +1 -0
- package/dist/bootstrap.js +33 -0
- package/dist/common/active-organization.d.ts +3 -0
- package/dist/common/active-organization.d.ts.map +1 -0
- package/dist/common/active-organization.js +8 -0
- package/dist/config/kosha-config.d.ts +80 -0
- package/dist/config/kosha-config.d.ts.map +1 -0
- package/dist/config/kosha-config.js +69 -0
- package/dist/config/tokens.d.ts +4 -0
- package/dist/config/tokens.d.ts.map +1 -0
- package/dist/config/tokens.js +3 -0
- package/dist/configurations/configurations.controller.d.ts +143 -0
- package/dist/configurations/configurations.controller.d.ts.map +1 -0
- package/dist/configurations/configurations.controller.js +76 -0
- package/dist/configurations/configurations.module.d.ts +3 -0
- package/dist/configurations/configurations.module.d.ts.map +1 -0
- package/dist/configurations/configurations.module.js +14 -0
- package/dist/configurations/configurations.service.d.ts +210 -0
- package/dist/configurations/configurations.service.d.ts.map +1 -0
- package/dist/configurations/configurations.service.js +204 -0
- package/dist/connect/connect.controller.d.ts +33 -0
- package/dist/connect/connect.controller.d.ts.map +1 -0
- package/dist/connect/connect.controller.js +123 -0
- package/dist/connect/connect.module.d.ts +3 -0
- package/dist/connect/connect.module.d.ts.map +1 -0
- package/dist/connect/connect.module.js +16 -0
- package/dist/connect/connect.service.d.ts +54 -0
- package/dist/connect/connect.service.d.ts.map +1 -0
- package/dist/connect/connect.service.js +248 -0
- package/dist/connections/connections.controller.d.ts +71 -0
- package/dist/connections/connections.controller.d.ts.map +1 -0
- package/dist/connections/connections.controller.js +51 -0
- package/dist/connections/connections.module.d.ts +3 -0
- package/dist/connections/connections.module.d.ts.map +1 -0
- package/dist/connections/connections.module.js +14 -0
- package/dist/connections/connections.service.d.ts +76 -0
- package/dist/connections/connections.service.d.ts.map +1 -0
- package/dist/connections/connections.service.js +71 -0
- package/dist/crypto/crypto.module.d.ts +3 -0
- package/dist/crypto/crypto.module.d.ts.map +1 -0
- package/dist/crypto/crypto.module.js +13 -0
- package/dist/crypto/crypto.service.d.ts +21 -0
- package/dist/crypto/crypto.service.d.ts.map +1 -0
- package/dist/crypto/crypto.service.js +77 -0
- package/dist/generated/prisma/browser.d.ts +88 -0
- package/dist/generated/prisma/browser.d.ts.map +1 -0
- package/dist/generated/prisma/browser.js +17 -0
- package/dist/generated/prisma/client.d.ts +107 -0
- package/dist/generated/prisma/client.d.ts.map +1 -0
- package/dist/generated/prisma/client.js +34 -0
- package/dist/generated/prisma/commonInputTypes.d.ts +478 -0
- package/dist/generated/prisma/commonInputTypes.d.ts.map +1 -0
- package/dist/generated/prisma/commonInputTypes.js +10 -0
- package/dist/generated/prisma/enums.d.ts +22 -0
- package/dist/generated/prisma/enums.d.ts.map +1 -0
- package/dist/generated/prisma/enums.js +27 -0
- package/dist/generated/prisma/internal/class.d.ts +287 -0
- package/dist/generated/prisma/internal/class.d.ts.map +1 -0
- package/dist/generated/prisma/internal/class.js +49 -0
- package/dist/generated/prisma/internal/prismaNamespace.d.ts +1905 -0
- package/dist/generated/prisma/internal/prismaNamespace.d.ts.map +1 -0
- package/dist/generated/prisma/internal/prismaNamespace.js +299 -0
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts +277 -0
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.d.ts.map +1 -0
- package/dist/generated/prisma/internal/prismaNamespaceBrowser.js +270 -0
- package/dist/generated/prisma/models/Account.d.ts +1459 -0
- package/dist/generated/prisma/models/Account.d.ts.map +1 -0
- package/dist/generated/prisma/models/Account.js +1 -0
- package/dist/generated/prisma/models/Apikey.d.ts +1552 -0
- package/dist/generated/prisma/models/Apikey.d.ts.map +1 -0
- package/dist/generated/prisma/models/Apikey.js +1 -0
- package/dist/generated/prisma/models/Configuration.d.ts +1964 -0
- package/dist/generated/prisma/models/Configuration.d.ts.map +1 -0
- package/dist/generated/prisma/models/Configuration.js +1 -0
- package/dist/generated/prisma/models/ConnectSession.d.ts +1606 -0
- package/dist/generated/prisma/models/ConnectSession.d.ts.map +1 -0
- package/dist/generated/prisma/models/ConnectSession.js +1 -0
- package/dist/generated/prisma/models/Connection.d.ts +1949 -0
- package/dist/generated/prisma/models/Connection.d.ts.map +1 -0
- package/dist/generated/prisma/models/Connection.js +1 -0
- package/dist/generated/prisma/models/ConnectionCredential.d.ts +1293 -0
- package/dist/generated/prisma/models/ConnectionCredential.d.ts.map +1 -0
- package/dist/generated/prisma/models/ConnectionCredential.js +1 -0
- package/dist/generated/prisma/models/EndUser.d.ts +1539 -0
- package/dist/generated/prisma/models/EndUser.d.ts.map +1 -0
- package/dist/generated/prisma/models/EndUser.js +1 -0
- package/dist/generated/prisma/models/Invitation.d.ts +1404 -0
- package/dist/generated/prisma/models/Invitation.d.ts.map +1 -0
- package/dist/generated/prisma/models/Invitation.js +1 -0
- package/dist/generated/prisma/models/Member.d.ts +1281 -0
- package/dist/generated/prisma/models/Member.d.ts.map +1 -0
- package/dist/generated/prisma/models/Member.js +1 -0
- package/dist/generated/prisma/models/OAuthState.d.ts +1404 -0
- package/dist/generated/prisma/models/OAuthState.d.ts.map +1 -0
- package/dist/generated/prisma/models/OAuthState.js +1 -0
- package/dist/generated/prisma/models/Organization.d.ts +1807 -0
- package/dist/generated/prisma/models/Organization.d.ts.map +1 -0
- package/dist/generated/prisma/models/Organization.js +1 -0
- package/dist/generated/prisma/models/Provider.d.ts +1462 -0
- package/dist/generated/prisma/models/Provider.d.ts.map +1 -0
- package/dist/generated/prisma/models/Provider.js +1 -0
- package/dist/generated/prisma/models/Session.d.ts +1316 -0
- package/dist/generated/prisma/models/Session.d.ts.map +1 -0
- package/dist/generated/prisma/models/Session.js +1 -0
- package/dist/generated/prisma/models/User.d.ts +1593 -0
- package/dist/generated/prisma/models/User.d.ts.map +1 -0
- package/dist/generated/prisma/models/User.js +1 -0
- package/dist/generated/prisma/models/Verification.d.ts +1026 -0
- package/dist/generated/prisma/models/Verification.d.ts.map +1 -0
- package/dist/generated/prisma/models/Verification.js +1 -0
- package/dist/generated/prisma/models.d.ts +17 -0
- package/dist/generated/prisma/models.d.ts.map +1 -0
- package/dist/generated/prisma/models.js +1 -0
- package/dist/health/health.controller.d.ts +12 -0
- package/dist/health/health.controller.d.ts.map +1 -0
- package/dist/health/health.controller.js +36 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -0
- package/dist/integrations/integration.registry.d.ts +19 -0
- package/dist/integrations/integration.registry.d.ts.map +1 -0
- package/dist/integrations/integration.registry.js +45 -0
- package/dist/integrations/integrations.controller.d.ts +26 -0
- package/dist/integrations/integrations.controller.d.ts.map +1 -0
- package/dist/integrations/integrations.controller.js +47 -0
- package/dist/integrations/integrations.module.d.ts +6 -0
- package/dist/integrations/integrations.module.d.ts.map +1 -0
- package/dist/integrations/integrations.module.js +26 -0
- package/dist/integrations/provider-sync.service.d.ts +24 -0
- package/dist/integrations/provider-sync.service.d.ts.map +1 -0
- package/dist/integrations/provider-sync.service.js +74 -0
- package/dist/kosha.module.d.ts +11 -0
- package/dist/kosha.module.d.ts.map +1 -0
- package/dist/kosha.module.js +48 -0
- package/dist/prisma/prisma.module.d.ts +11 -0
- package/dist/prisma/prisma.module.d.ts.map +1 -0
- package/dist/prisma/prisma.module.js +24 -0
- package/dist/prisma/prisma.service.d.ts +10 -0
- package/dist/prisma/prisma.service.d.ts.map +1 -0
- package/dist/prisma/prisma.service.js +25 -0
- package/dist/proxy/proxy.controller.d.ts +17 -0
- package/dist/proxy/proxy.controller.d.ts.map +1 -0
- package/dist/proxy/proxy.controller.js +64 -0
- package/dist/proxy/proxy.module.d.ts +3 -0
- package/dist/proxy/proxy.module.d.ts.map +1 -0
- package/dist/proxy/proxy.module.js +16 -0
- package/dist/proxy/proxy.service.d.ts +40 -0
- package/dist/proxy/proxy.service.d.ts.map +1 -0
- package/dist/proxy/proxy.service.js +186 -0
- package/package.json +118 -0
- package/prisma/migrations/20260908000000_init/migration.sql +209 -0
- package/prisma/migrations/20260908161813_add_connect_domain/migration.sql +173 -0
- package/prisma/migrations/migration_lock.toml +3 -0
- package/prisma/schema.prisma +347 -0
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
var ConnectService_1;
|
|
2
|
+
import { __decorate, __metadata, __param } from "tslib";
|
|
3
|
+
import { BadRequestException, Inject, Injectable, Logger, NotFoundException, } from '@nestjs/common';
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { generateCodeVerifier } from '@kosha-ai/integration-sdk';
|
|
6
|
+
import { httpFor } from '@kosha-ai/integration-sdk';
|
|
7
|
+
import { KOSHA_CONFIG } from '../config/tokens.js';
|
|
8
|
+
import { ConfigurationsService } from '../configurations/configurations.service.js';
|
|
9
|
+
import { CryptoService } from '../crypto/crypto.service.js';
|
|
10
|
+
import { IntegrationRegistry } from '../integrations/integration.registry.js';
|
|
11
|
+
import { PrismaService } from '../prisma/prisma.service.js';
|
|
12
|
+
const SESSION_TTL_MS = 10 * 60 * 1000;
|
|
13
|
+
const STATE_TTL_MS = 10 * 60 * 1000;
|
|
14
|
+
function randomToken() {
|
|
15
|
+
return randomBytes(32).toString('hex');
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Drives the OAuth handshake that turns an end user's consent into a stored,
|
|
19
|
+
* encrypted connection.
|
|
20
|
+
*
|
|
21
|
+
* Providers are resolved through {@link IntegrationRegistry}, so nothing here
|
|
22
|
+
* knows what GitHub or Slack are.
|
|
23
|
+
*/
|
|
24
|
+
let ConnectService = ConnectService_1 = class ConnectService {
|
|
25
|
+
prisma;
|
|
26
|
+
crypto;
|
|
27
|
+
configurations;
|
|
28
|
+
registry;
|
|
29
|
+
config;
|
|
30
|
+
logger = new Logger(ConnectService_1.name);
|
|
31
|
+
constructor(prisma, crypto, configurations, registry, config) {
|
|
32
|
+
this.prisma = prisma;
|
|
33
|
+
this.crypto = crypto;
|
|
34
|
+
this.configurations = configurations;
|
|
35
|
+
this.registry = registry;
|
|
36
|
+
this.config = config;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Called by the organization's own backend (API-key authenticated) to start
|
|
40
|
+
* a connect flow for one of its users.
|
|
41
|
+
*/
|
|
42
|
+
async createSession(organizationId, input) {
|
|
43
|
+
if (!input?.endUserExternalId?.trim()) {
|
|
44
|
+
throw new BadRequestException('endUserExternalId is required');
|
|
45
|
+
}
|
|
46
|
+
if (!input.configurationId?.trim()) {
|
|
47
|
+
throw new BadRequestException('configurationId is required');
|
|
48
|
+
}
|
|
49
|
+
const configuration = await this.prisma.configuration.findFirst({
|
|
50
|
+
where: {
|
|
51
|
+
id: input.configurationId,
|
|
52
|
+
organizationId,
|
|
53
|
+
isEnabled: true,
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
if (!configuration) {
|
|
57
|
+
throw new BadRequestException('Unknown or disabled configuration');
|
|
58
|
+
}
|
|
59
|
+
const endUser = await this.prisma.endUser.upsert({
|
|
60
|
+
where: {
|
|
61
|
+
organizationId_externalId: {
|
|
62
|
+
organizationId,
|
|
63
|
+
externalId: input.endUserExternalId,
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
create: { organizationId, externalId: input.endUserExternalId },
|
|
67
|
+
update: {},
|
|
68
|
+
});
|
|
69
|
+
const expiresAt = new Date(Date.now() + SESSION_TTL_MS);
|
|
70
|
+
const session = await this.prisma.connectSession.create({
|
|
71
|
+
data: {
|
|
72
|
+
organizationId,
|
|
73
|
+
endUserId: endUser.id,
|
|
74
|
+
token: randomToken(),
|
|
75
|
+
allowedConfigurationIds: [configuration.id],
|
|
76
|
+
redirectUrl: input.redirectUrl,
|
|
77
|
+
expiresAt,
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
const { publicUrl, globalPrefix } = this.config.server;
|
|
81
|
+
return {
|
|
82
|
+
token: session.token,
|
|
83
|
+
connectUrl: `${publicUrl}/${globalPrefix}/connect/${session.token}/start`,
|
|
84
|
+
expiresAt,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Exchanges a connect-session token for the provider's authorize URL,
|
|
89
|
+
* recording CSRF state and — where the provider supports it — a PKCE
|
|
90
|
+
* verifier.
|
|
91
|
+
*/
|
|
92
|
+
async buildAuthorizationRedirect(token) {
|
|
93
|
+
const session = await this.prisma.connectSession.findUnique({
|
|
94
|
+
where: { token },
|
|
95
|
+
});
|
|
96
|
+
if (!session ||
|
|
97
|
+
session.status !== 'pending' ||
|
|
98
|
+
session.expiresAt < new Date()) {
|
|
99
|
+
throw new NotFoundException('Connect session not found or expired');
|
|
100
|
+
}
|
|
101
|
+
const configurationId = session.allowedConfigurationIds[0];
|
|
102
|
+
const configuration = await this.configurations.getWithDecryptedSecret(configurationId);
|
|
103
|
+
if (configuration.organizationId !== session.organizationId ||
|
|
104
|
+
!configuration.isEnabled) {
|
|
105
|
+
throw new BadRequestException('Configuration is no longer available');
|
|
106
|
+
}
|
|
107
|
+
const integration = this.registry.get(configuration.provider.key);
|
|
108
|
+
const codeVerifier = integration.auth.pkce
|
|
109
|
+
? generateCodeVerifier()
|
|
110
|
+
: undefined;
|
|
111
|
+
const state = await this.prisma.oAuthState.create({
|
|
112
|
+
data: {
|
|
113
|
+
state: randomToken(),
|
|
114
|
+
connectSessionId: session.id,
|
|
115
|
+
configurationId: configuration.id,
|
|
116
|
+
codeVerifier,
|
|
117
|
+
expiresAt: new Date(Date.now() + STATE_TTL_MS),
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
return integration.auth.buildAuthorizationUrl({
|
|
121
|
+
client: {
|
|
122
|
+
clientId: configuration.clientId ?? '',
|
|
123
|
+
clientSecret: configuration.clientSecret,
|
|
124
|
+
redirectUri: configuration.redirectUri ??
|
|
125
|
+
this.configurations.callbackUrlFor(configuration.provider.key),
|
|
126
|
+
scopes: configuration.scopes,
|
|
127
|
+
},
|
|
128
|
+
state: state.state,
|
|
129
|
+
codeVerifier,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/** Handles the provider's redirect back to Kosha. */
|
|
133
|
+
async handleCallback(providerKey, code, state) {
|
|
134
|
+
const oauthState = await this.prisma.oAuthState.findUnique({
|
|
135
|
+
where: { state },
|
|
136
|
+
include: { connectSession: true },
|
|
137
|
+
});
|
|
138
|
+
if (!oauthState ||
|
|
139
|
+
oauthState.status !== 'pending' ||
|
|
140
|
+
oauthState.expiresAt < new Date()) {
|
|
141
|
+
throw new NotFoundException('OAuth state not found or expired');
|
|
142
|
+
}
|
|
143
|
+
// Burn the state before doing any network work: a replayed callback must
|
|
144
|
+
// not be able to mint a second connection.
|
|
145
|
+
await this.prisma.oAuthState.update({
|
|
146
|
+
where: { id: oauthState.id },
|
|
147
|
+
data: { status: 'completed' },
|
|
148
|
+
});
|
|
149
|
+
const configuration = await this.configurations.getWithDecryptedSecret(oauthState.configurationId);
|
|
150
|
+
if (configuration.provider.key !== providerKey) {
|
|
151
|
+
throw new BadRequestException('Provider mismatch');
|
|
152
|
+
}
|
|
153
|
+
const integration = this.registry.get(providerKey);
|
|
154
|
+
const tokens = await integration.auth.exchangeCode({
|
|
155
|
+
client: {
|
|
156
|
+
clientId: configuration.clientId ?? '',
|
|
157
|
+
clientSecret: configuration.clientSecret,
|
|
158
|
+
redirectUri: configuration.redirectUri ??
|
|
159
|
+
this.configurations.callbackUrlFor(providerKey),
|
|
160
|
+
scopes: configuration.scopes,
|
|
161
|
+
},
|
|
162
|
+
code,
|
|
163
|
+
codeVerifier: oauthState.codeVerifier ?? undefined,
|
|
164
|
+
});
|
|
165
|
+
const identity = await integration.identity.fetchAccount({
|
|
166
|
+
accessToken: tokens.accessToken,
|
|
167
|
+
http: httpFor(integration),
|
|
168
|
+
});
|
|
169
|
+
const endUserId = oauthState.connectSession.endUserId;
|
|
170
|
+
if (!endUserId) {
|
|
171
|
+
throw new BadRequestException('Connect session has no end user');
|
|
172
|
+
}
|
|
173
|
+
const connection = await this.prisma.connection.upsert({
|
|
174
|
+
where: {
|
|
175
|
+
configurationId_externalAccountId: {
|
|
176
|
+
configurationId: configuration.id,
|
|
177
|
+
externalAccountId: identity.externalAccountId,
|
|
178
|
+
},
|
|
179
|
+
},
|
|
180
|
+
create: {
|
|
181
|
+
organizationId: configuration.organizationId,
|
|
182
|
+
endUserId,
|
|
183
|
+
configurationId: configuration.id,
|
|
184
|
+
externalAccountId: identity.externalAccountId,
|
|
185
|
+
label: identity.label,
|
|
186
|
+
status: 'ACTIVE',
|
|
187
|
+
scopes: configuration.scopes,
|
|
188
|
+
lastUsedAt: new Date(),
|
|
189
|
+
},
|
|
190
|
+
update: {
|
|
191
|
+
status: 'ACTIVE',
|
|
192
|
+
label: identity.label,
|
|
193
|
+
errorMessage: null,
|
|
194
|
+
lastUsedAt: new Date(),
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
await this.storeCredential(connection.id, tokens);
|
|
198
|
+
await this.prisma.connectSession.update({
|
|
199
|
+
where: { id: oauthState.connectSessionId },
|
|
200
|
+
data: { status: 'consumed' },
|
|
201
|
+
});
|
|
202
|
+
await this.runHook(integration, () => integration.hooks?.onConnectionCreated?.({
|
|
203
|
+
connectionId: connection.id,
|
|
204
|
+
organizationId: configuration.organizationId,
|
|
205
|
+
}));
|
|
206
|
+
return {
|
|
207
|
+
connectionId: connection.id,
|
|
208
|
+
redirectUrl: oauthState.connectSession.redirectUrl,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
/** Persists a token set, encrypted. Shared by the callback and by refresh. */
|
|
212
|
+
async storeCredential(connectionId, tokens) {
|
|
213
|
+
const expiresAt = tokens.expiresInSeconds
|
|
214
|
+
? new Date(Date.now() + tokens.expiresInSeconds * 1000)
|
|
215
|
+
: null;
|
|
216
|
+
const data = {
|
|
217
|
+
accessToken: this.crypto.encrypt(tokens.accessToken),
|
|
218
|
+
refreshToken: tokens.refreshToken
|
|
219
|
+
? this.crypto.encrypt(tokens.refreshToken)
|
|
220
|
+
: null,
|
|
221
|
+
tokenType: tokens.tokenType,
|
|
222
|
+
expiresAt,
|
|
223
|
+
};
|
|
224
|
+
await this.prisma.connectionCredential.upsert({
|
|
225
|
+
where: { connectionId },
|
|
226
|
+
create: { connectionId, ...data },
|
|
227
|
+
update: data,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** An integration's hook must never take the request down with it. */
|
|
231
|
+
async runHook(integration, hook) {
|
|
232
|
+
try {
|
|
233
|
+
await hook();
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
this.logger.error(`Hook failed for integration "${integration.key}": ${error instanceof Error ? error.message : error}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
ConnectService = ConnectService_1 = __decorate([
|
|
241
|
+
Injectable(),
|
|
242
|
+
__param(4, Inject(KOSHA_CONFIG)),
|
|
243
|
+
__metadata("design:paramtypes", [PrismaService,
|
|
244
|
+
CryptoService,
|
|
245
|
+
ConfigurationsService,
|
|
246
|
+
IntegrationRegistry, Object])
|
|
247
|
+
], ConnectService);
|
|
248
|
+
export { ConnectService };
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type UserSession } from '@thallesp/nestjs-better-auth';
|
|
2
|
+
import { ConnectionsService } from './connections.service.js';
|
|
3
|
+
export declare class ConnectionsController {
|
|
4
|
+
private readonly connections;
|
|
5
|
+
constructor(connections: ConnectionsService);
|
|
6
|
+
list(session: UserSession, endUserExternalId?: string): import("../generated/prisma/internal/prismaNamespace.js").PrismaPromise<({
|
|
7
|
+
configuration: {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
provider: {
|
|
11
|
+
key: string;
|
|
12
|
+
name: string;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
endUser: {
|
|
16
|
+
name: string | null;
|
|
17
|
+
externalId: string;
|
|
18
|
+
email: string | null;
|
|
19
|
+
};
|
|
20
|
+
} & {
|
|
21
|
+
id: string;
|
|
22
|
+
organizationId: string;
|
|
23
|
+
scopes: string[];
|
|
24
|
+
metadata: import("@prisma/client/runtime/client").JsonValue | null;
|
|
25
|
+
createdAt: Date;
|
|
26
|
+
updatedAt: Date;
|
|
27
|
+
status: import("../generated/prisma/enums.js").ConnectionStatus;
|
|
28
|
+
endUserId: string;
|
|
29
|
+
configurationId: string;
|
|
30
|
+
label: string | null;
|
|
31
|
+
externalAccountId: string | null;
|
|
32
|
+
lastSyncedAt: Date | null;
|
|
33
|
+
lastUsedAt: Date | null;
|
|
34
|
+
errorMessage: string | null;
|
|
35
|
+
})[]>;
|
|
36
|
+
get(session: UserSession, id: string): Promise<{
|
|
37
|
+
configuration: {
|
|
38
|
+
id: string;
|
|
39
|
+
name: string;
|
|
40
|
+
provider: {
|
|
41
|
+
key: string;
|
|
42
|
+
name: string;
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
endUser: {
|
|
46
|
+
name: string | null;
|
|
47
|
+
externalId: string;
|
|
48
|
+
email: string | null;
|
|
49
|
+
};
|
|
50
|
+
} & {
|
|
51
|
+
id: string;
|
|
52
|
+
organizationId: string;
|
|
53
|
+
scopes: string[];
|
|
54
|
+
metadata: import("@prisma/client/runtime/client").JsonValue | null;
|
|
55
|
+
createdAt: Date;
|
|
56
|
+
updatedAt: Date;
|
|
57
|
+
status: import("../generated/prisma/enums.js").ConnectionStatus;
|
|
58
|
+
endUserId: string;
|
|
59
|
+
configurationId: string;
|
|
60
|
+
label: string | null;
|
|
61
|
+
externalAccountId: string | null;
|
|
62
|
+
lastSyncedAt: Date | null;
|
|
63
|
+
lastUsedAt: Date | null;
|
|
64
|
+
errorMessage: string | null;
|
|
65
|
+
}>;
|
|
66
|
+
revoke(session: UserSession, id: string): Promise<{
|
|
67
|
+
id: string;
|
|
68
|
+
status: "REVOKED";
|
|
69
|
+
}>;
|
|
70
|
+
}
|
|
71
|
+
//# sourceMappingURL=connections.controller.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connections.controller.d.ts","sourceRoot":"","sources":["../../src/connections/connections.controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAW,KAAK,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAEzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAE9D,qBACa,qBAAqB;IACpB,OAAO,CAAC,QAAQ,CAAC,WAAW;gBAAX,WAAW,EAAE,kBAAkB;IAG5D,IAAI,CACS,OAAO,EAAE,WAAW,EACH,iBAAiB,CAAC,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAQxD,GAAG,CAAY,OAAO,EAAE,WAAW,EAAe,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAK5D,MAAM,CAAY,OAAO,EAAE,WAAW,EAAe,EAAE,EAAE,MAAM;;;;CAGhE"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { __decorate, __metadata, __param } from "tslib";
|
|
2
|
+
import { Controller, Delete, Get, Param, Query } from '@nestjs/common';
|
|
3
|
+
import { Session } from '@thallesp/nestjs-better-auth';
|
|
4
|
+
import { getActiveOrganizationId } from '../common/active-organization.js';
|
|
5
|
+
import { ConnectionsService } from './connections.service.js';
|
|
6
|
+
let ConnectionsController = class ConnectionsController {
|
|
7
|
+
connections;
|
|
8
|
+
constructor(connections) {
|
|
9
|
+
this.connections = connections;
|
|
10
|
+
}
|
|
11
|
+
list(session, endUserExternalId) {
|
|
12
|
+
return this.connections.list(getActiveOrganizationId(session), {
|
|
13
|
+
endUserExternalId,
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
get(session, id) {
|
|
17
|
+
return this.connections.get(getActiveOrganizationId(session), id);
|
|
18
|
+
}
|
|
19
|
+
revoke(session, id) {
|
|
20
|
+
return this.connections.revoke(getActiveOrganizationId(session), id);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
__decorate([
|
|
24
|
+
Get(),
|
|
25
|
+
__param(0, Session()),
|
|
26
|
+
__param(1, Query('endUserExternalId')),
|
|
27
|
+
__metadata("design:type", Function),
|
|
28
|
+
__metadata("design:paramtypes", [Object, String]),
|
|
29
|
+
__metadata("design:returntype", void 0)
|
|
30
|
+
], ConnectionsController.prototype, "list", null);
|
|
31
|
+
__decorate([
|
|
32
|
+
Get(':id'),
|
|
33
|
+
__param(0, Session()),
|
|
34
|
+
__param(1, Param('id')),
|
|
35
|
+
__metadata("design:type", Function),
|
|
36
|
+
__metadata("design:paramtypes", [Object, String]),
|
|
37
|
+
__metadata("design:returntype", void 0)
|
|
38
|
+
], ConnectionsController.prototype, "get", null);
|
|
39
|
+
__decorate([
|
|
40
|
+
Delete(':id'),
|
|
41
|
+
__param(0, Session()),
|
|
42
|
+
__param(1, Param('id')),
|
|
43
|
+
__metadata("design:type", Function),
|
|
44
|
+
__metadata("design:paramtypes", [Object, String]),
|
|
45
|
+
__metadata("design:returntype", void 0)
|
|
46
|
+
], ConnectionsController.prototype, "revoke", null);
|
|
47
|
+
ConnectionsController = __decorate([
|
|
48
|
+
Controller('connections'),
|
|
49
|
+
__metadata("design:paramtypes", [ConnectionsService])
|
|
50
|
+
], ConnectionsController);
|
|
51
|
+
export { ConnectionsController };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connections.module.d.ts","sourceRoot":"","sources":["../../src/connections/connections.module.ts"],"names":[],"mappings":"AAIA,qBAKa,iBAAiB;CAAG"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { __decorate } from "tslib";
|
|
2
|
+
import { Module } from '@nestjs/common';
|
|
3
|
+
import { ConnectionsController } from './connections.controller.js';
|
|
4
|
+
import { ConnectionsService } from './connections.service.js';
|
|
5
|
+
let ConnectionsModule = class ConnectionsModule {
|
|
6
|
+
};
|
|
7
|
+
ConnectionsModule = __decorate([
|
|
8
|
+
Module({
|
|
9
|
+
controllers: [ConnectionsController],
|
|
10
|
+
providers: [ConnectionsService],
|
|
11
|
+
exports: [ConnectionsService],
|
|
12
|
+
})
|
|
13
|
+
], ConnectionsModule);
|
|
14
|
+
export { ConnectionsModule };
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { PrismaService } from '../prisma/prisma.service.js';
|
|
2
|
+
export declare class ConnectionsService {
|
|
3
|
+
private readonly prisma;
|
|
4
|
+
constructor(prisma: PrismaService);
|
|
5
|
+
list(organizationId: string, filters?: {
|
|
6
|
+
endUserExternalId?: string;
|
|
7
|
+
}): import("../generated/prisma/internal/prismaNamespace.js").PrismaPromise<({
|
|
8
|
+
configuration: {
|
|
9
|
+
id: string;
|
|
10
|
+
name: string;
|
|
11
|
+
provider: {
|
|
12
|
+
key: string;
|
|
13
|
+
name: string;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
endUser: {
|
|
17
|
+
name: string | null;
|
|
18
|
+
externalId: string;
|
|
19
|
+
email: string | null;
|
|
20
|
+
};
|
|
21
|
+
} & {
|
|
22
|
+
id: string;
|
|
23
|
+
organizationId: string;
|
|
24
|
+
scopes: string[];
|
|
25
|
+
metadata: import("@prisma/client/runtime/client").JsonValue | null;
|
|
26
|
+
createdAt: Date;
|
|
27
|
+
updatedAt: Date;
|
|
28
|
+
status: import("../generated/prisma/enums.js").ConnectionStatus;
|
|
29
|
+
endUserId: string;
|
|
30
|
+
configurationId: string;
|
|
31
|
+
label: string | null;
|
|
32
|
+
externalAccountId: string | null;
|
|
33
|
+
lastSyncedAt: Date | null;
|
|
34
|
+
lastUsedAt: Date | null;
|
|
35
|
+
errorMessage: string | null;
|
|
36
|
+
})[]>;
|
|
37
|
+
get(organizationId: string, id: string): Promise<{
|
|
38
|
+
configuration: {
|
|
39
|
+
id: string;
|
|
40
|
+
name: string;
|
|
41
|
+
provider: {
|
|
42
|
+
key: string;
|
|
43
|
+
name: string;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
endUser: {
|
|
47
|
+
name: string | null;
|
|
48
|
+
externalId: string;
|
|
49
|
+
email: string | null;
|
|
50
|
+
};
|
|
51
|
+
} & {
|
|
52
|
+
id: string;
|
|
53
|
+
organizationId: string;
|
|
54
|
+
scopes: string[];
|
|
55
|
+
metadata: import("@prisma/client/runtime/client").JsonValue | null;
|
|
56
|
+
createdAt: Date;
|
|
57
|
+
updatedAt: Date;
|
|
58
|
+
status: import("../generated/prisma/enums.js").ConnectionStatus;
|
|
59
|
+
endUserId: string;
|
|
60
|
+
configurationId: string;
|
|
61
|
+
label: string | null;
|
|
62
|
+
externalAccountId: string | null;
|
|
63
|
+
lastSyncedAt: Date | null;
|
|
64
|
+
lastUsedAt: Date | null;
|
|
65
|
+
errorMessage: string | null;
|
|
66
|
+
}>;
|
|
67
|
+
/**
|
|
68
|
+
* Deletes the stored tokens and marks the connection revoked, keeping the
|
|
69
|
+
* row so history and audit trails survive.
|
|
70
|
+
*/
|
|
71
|
+
revoke(organizationId: string, id: string): Promise<{
|
|
72
|
+
id: string;
|
|
73
|
+
status: "REVOKED";
|
|
74
|
+
}>;
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=connections.service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connections.service.d.ts","sourceRoot":"","sources":["../../src/connections/connections.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,qBACa,kBAAkB;IACjB,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAElD,IAAI,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,iBAAiB,CAAC,EAAE,MAAM,CAAA;KAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAsBnE,GAAG,CAAC,cAAc,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAoB5C;;;OAGG;IACG,MAAM,CAAC,cAAc,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;;;;CAehD"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { __decorate, __metadata } from "tslib";
|
|
2
|
+
import { Injectable, NotFoundException } from '@nestjs/common';
|
|
3
|
+
import { PrismaService } from '../prisma/prisma.service.js';
|
|
4
|
+
let ConnectionsService = class ConnectionsService {
|
|
5
|
+
prisma;
|
|
6
|
+
constructor(prisma) {
|
|
7
|
+
this.prisma = prisma;
|
|
8
|
+
}
|
|
9
|
+
list(organizationId, filters = {}) {
|
|
10
|
+
return this.prisma.connection.findMany({
|
|
11
|
+
where: {
|
|
12
|
+
organizationId,
|
|
13
|
+
...(filters.endUserExternalId
|
|
14
|
+
? { endUser: { externalId: filters.endUserExternalId } }
|
|
15
|
+
: {}),
|
|
16
|
+
},
|
|
17
|
+
include: {
|
|
18
|
+
endUser: { select: { externalId: true, email: true, name: true } },
|
|
19
|
+
configuration: {
|
|
20
|
+
select: {
|
|
21
|
+
id: true,
|
|
22
|
+
name: true,
|
|
23
|
+
provider: { select: { key: true, name: true } },
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
orderBy: { createdAt: 'desc' },
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
async get(organizationId, id) {
|
|
31
|
+
const connection = await this.prisma.connection.findFirst({
|
|
32
|
+
where: { id, organizationId },
|
|
33
|
+
include: {
|
|
34
|
+
endUser: { select: { externalId: true, email: true, name: true } },
|
|
35
|
+
configuration: {
|
|
36
|
+
select: {
|
|
37
|
+
id: true,
|
|
38
|
+
name: true,
|
|
39
|
+
provider: { select: { key: true, name: true } },
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
if (!connection) {
|
|
45
|
+
throw new NotFoundException('Connection not found');
|
|
46
|
+
}
|
|
47
|
+
return connection;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Deletes the stored tokens and marks the connection revoked, keeping the
|
|
51
|
+
* row so history and audit trails survive.
|
|
52
|
+
*/
|
|
53
|
+
async revoke(organizationId, id) {
|
|
54
|
+
await this.get(organizationId, id);
|
|
55
|
+
await this.prisma.$transaction([
|
|
56
|
+
this.prisma.connectionCredential.deleteMany({
|
|
57
|
+
where: { connectionId: id },
|
|
58
|
+
}),
|
|
59
|
+
this.prisma.connection.update({
|
|
60
|
+
where: { id },
|
|
61
|
+
data: { status: 'REVOKED', errorMessage: null },
|
|
62
|
+
}),
|
|
63
|
+
]);
|
|
64
|
+
return { id, status: 'REVOKED' };
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
ConnectionsService = __decorate([
|
|
68
|
+
Injectable(),
|
|
69
|
+
__metadata("design:paramtypes", [PrismaService])
|
|
70
|
+
], ConnectionsService);
|
|
71
|
+
export { ConnectionsService };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crypto.module.d.ts","sourceRoot":"","sources":["../../src/crypto/crypto.module.ts"],"names":[],"mappings":"AAGA,qBAKa,YAAY;CAAG"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { __decorate } from "tslib";
|
|
2
|
+
import { Global, Module } from '@nestjs/common';
|
|
3
|
+
import { CryptoService } from './crypto.service.js';
|
|
4
|
+
let CryptoModule = class CryptoModule {
|
|
5
|
+
};
|
|
6
|
+
CryptoModule = __decorate([
|
|
7
|
+
Global(),
|
|
8
|
+
Module({
|
|
9
|
+
providers: [CryptoService],
|
|
10
|
+
exports: [CryptoService],
|
|
11
|
+
})
|
|
12
|
+
], CryptoModule);
|
|
13
|
+
export { CryptoModule };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ResolvedKoshaConfig } from '../config/kosha-config.js';
|
|
2
|
+
export declare class MissingEncryptionKeyError extends Error {
|
|
3
|
+
constructor();
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* AES-256-GCM for everything secret at rest: provider access and refresh
|
|
7
|
+
* tokens, and each configuration's OAuth client secret.
|
|
8
|
+
*
|
|
9
|
+
* GCM rather than CBC so ciphertext is authenticated — a tampered token fails
|
|
10
|
+
* to decrypt instead of being handed to a provider.
|
|
11
|
+
*/
|
|
12
|
+
export declare class CryptoService {
|
|
13
|
+
private readonly key?;
|
|
14
|
+
constructor(config: ResolvedKoshaConfig);
|
|
15
|
+
get isConfigured(): boolean;
|
|
16
|
+
/** `iv.authTag.ciphertext`, each part base64. */
|
|
17
|
+
encrypt(plaintext: string): string;
|
|
18
|
+
decrypt(payload: string): string;
|
|
19
|
+
private requireKey;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=crypto.service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crypto.service.d.ts","sourceRoot":"","sources":["../../src/crypto/crypto.service.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAOrE,qBAAa,yBAA0B,SAAQ,KAAK;;CAOnD;AAED;;;;;;GAMG;AACH,qBACa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAS;gBAEI,MAAM,EAAE,mBAAmB;IAgB7D,IAAI,YAAY,IAAI,OAAO,CAE1B;IAED,iDAAiD;IACjD,OAAO,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM;IAgBlC,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM;IAoBhC,OAAO,CAAC,UAAU;CAInB"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { __decorate, __metadata, __param } from "tslib";
|
|
2
|
+
import { Inject, Injectable } from '@nestjs/common';
|
|
3
|
+
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
|
4
|
+
import { KOSHA_CONFIG } from '../config/tokens.js';
|
|
5
|
+
const ALGORITHM = 'aes-256-gcm';
|
|
6
|
+
const IV_LENGTH = 12;
|
|
7
|
+
const KEY_LENGTH = 32;
|
|
8
|
+
export class MissingEncryptionKeyError extends Error {
|
|
9
|
+
constructor() {
|
|
10
|
+
super("This operation stores provider credentials, which needs encryption.key in kosha.config.ts. Generate one with: node -e \"console.log(require('node:crypto').randomBytes(32).toString('base64'))\"");
|
|
11
|
+
this.name = 'MissingEncryptionKeyError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* AES-256-GCM for everything secret at rest: provider access and refresh
|
|
16
|
+
* tokens, and each configuration's OAuth client secret.
|
|
17
|
+
*
|
|
18
|
+
* GCM rather than CBC so ciphertext is authenticated — a tampered token fails
|
|
19
|
+
* to decrypt instead of being handed to a provider.
|
|
20
|
+
*/
|
|
21
|
+
let CryptoService = class CryptoService {
|
|
22
|
+
key;
|
|
23
|
+
constructor(config) {
|
|
24
|
+
if (!config.encryption?.key) {
|
|
25
|
+
// Not fatal at boot: an app that has not configured any provider yet is
|
|
26
|
+
// perfectly usable. It becomes fatal on first use.
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const key = Buffer.from(config.encryption.key, 'base64');
|
|
30
|
+
if (key.length !== KEY_LENGTH) {
|
|
31
|
+
throw new Error(`encryption.key must decode to ${KEY_LENGTH} bytes, got ${key.length}`);
|
|
32
|
+
}
|
|
33
|
+
this.key = key;
|
|
34
|
+
}
|
|
35
|
+
get isConfigured() {
|
|
36
|
+
return this.key !== undefined;
|
|
37
|
+
}
|
|
38
|
+
/** `iv.authTag.ciphertext`, each part base64. */
|
|
39
|
+
encrypt(plaintext) {
|
|
40
|
+
const key = this.requireKey();
|
|
41
|
+
const iv = randomBytes(IV_LENGTH);
|
|
42
|
+
const cipher = createCipheriv(ALGORITHM, key, iv);
|
|
43
|
+
const ciphertext = Buffer.concat([
|
|
44
|
+
cipher.update(plaintext, 'utf8'),
|
|
45
|
+
cipher.final(),
|
|
46
|
+
]);
|
|
47
|
+
return [
|
|
48
|
+
iv.toString('base64'),
|
|
49
|
+
cipher.getAuthTag().toString('base64'),
|
|
50
|
+
ciphertext.toString('base64'),
|
|
51
|
+
].join('.');
|
|
52
|
+
}
|
|
53
|
+
decrypt(payload) {
|
|
54
|
+
const key = this.requireKey();
|
|
55
|
+
const [ivB64, authTagB64, ciphertextB64] = payload.split('.');
|
|
56
|
+
if (!ivB64 || !authTagB64 || !ciphertextB64) {
|
|
57
|
+
throw new Error('Invalid encrypted payload format');
|
|
58
|
+
}
|
|
59
|
+
const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(ivB64, 'base64'));
|
|
60
|
+
decipher.setAuthTag(Buffer.from(authTagB64, 'base64'));
|
|
61
|
+
return Buffer.concat([
|
|
62
|
+
decipher.update(Buffer.from(ciphertextB64, 'base64')),
|
|
63
|
+
decipher.final(),
|
|
64
|
+
]).toString('utf8');
|
|
65
|
+
}
|
|
66
|
+
requireKey() {
|
|
67
|
+
if (!this.key)
|
|
68
|
+
throw new MissingEncryptionKeyError();
|
|
69
|
+
return this.key;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
CryptoService = __decorate([
|
|
73
|
+
Injectable(),
|
|
74
|
+
__param(0, Inject(KOSHA_CONFIG)),
|
|
75
|
+
__metadata("design:paramtypes", [Object])
|
|
76
|
+
], CryptoService);
|
|
77
|
+
export { CryptoService };
|