@kosha-ai/server 0.5.0 → 0.5.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../src/bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,KAAK,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAK/E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAI5D;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,gBAAgB,CAAC,CA6D3B;AAED,gCAAgC;AAChC,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,gBAAgB,CAAC,CAkB3B"}
1
+ {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../src/bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,KAAK,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAK/E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAI5D;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,gBAAgB,CAAC,CAiF3B;AAED,gCAAgC;AAChC,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,gBAAgB,CAAC,CAkB3B"}
package/dist/bootstrap.js CHANGED
@@ -33,6 +33,20 @@ export async function createKoshaServer(config) {
33
33
  }
34
34
  }
35
35
  app.setGlobalPrefix(resolved.server.globalPrefix);
36
+ // Keep binary proxy uploads as bytes. JSON and form requests continue
37
+ // through the normal parsers installed by the application modules.
38
+ expressApp.use(`/${resolved.server.globalPrefix}/proxy`, express.raw({
39
+ type: (request) => {
40
+ const contentType = request.headers['content-type']?.toLowerCase() ?? '';
41
+ if (!contentType)
42
+ return false;
43
+ return (!contentType.startsWith('application/json') &&
44
+ !contentType.includes('+json') &&
45
+ !contentType.startsWith('application/x-www-form-urlencoded') &&
46
+ !contentType.startsWith('multipart/form-data'));
47
+ },
48
+ limit: '50mb',
49
+ }));
36
50
  // `whitelist` strips properties no DTO declares, so an endpoint can only
37
51
  // ever see what it asked for. Better Auth's own routes are mounted by the
38
52
  // auth module and never reach a Nest pipe.
@@ -116,7 +116,7 @@ let ConfigurationsService = class ConfigurationsService {
116
116
  // unanchored `[a-z]+` matches inside `acme/evil`, so a pattern meant to
117
117
  // constrain a value would quietly accept one that escapes it.
118
118
  if (field.pattern !== undefined &&
119
- !new RegExp(`^(?:${field.pattern})$`).test(value)) {
119
+ !new RegExp(`^(?:${field.pattern})$`, 'v').test(value)) {
120
120
  throw new BadRequestException(`${field.label} is not in the expected format`);
121
121
  }
122
122
  if (field.type !== 'url' && field.type !== 'host')
@@ -183,7 +183,9 @@ function declaredFields(integration, supplied, options = {}) {
183
183
  const fields = {};
184
184
  for (const field of declared) {
185
185
  const value = supplied?.[field.key];
186
- if (value === undefined || value === '') {
186
+ if (value === undefined ||
187
+ value === '' ||
188
+ (Array.isArray(value) && value.length === 0)) {
187
189
  // On create a required field must be there; on update, absent means
188
190
  // "leave what is stored".
189
191
  if (options.required && field.required) {
@@ -191,6 +193,13 @@ function declaredFields(integration, supplied, options = {}) {
191
193
  }
192
194
  continue;
193
195
  }
196
+ if (field.type === 'select') {
197
+ const allowed = new Set((field.options ?? []).map((option) => option.value));
198
+ const values = Array.isArray(value) ? value : [value];
199
+ if (values.some((option) => typeof option !== 'string' || !allowed.has(option))) {
200
+ throw new BadRequestException(`${field.label} contains an unsupported option`);
201
+ }
202
+ }
194
203
  fields[field.key] = value;
195
204
  }
196
205
  return Object.keys(fields).length > 0 ? fields : undefined;
@@ -4,6 +4,10 @@ import { ProxyService } from './proxy.service.js';
4
4
  export declare class ProxyController {
5
5
  private readonly proxy;
6
6
  constructor(proxy: ProxyService);
7
+ presign(request: ApiKeyRequest, provider: string, configurationSlug: string, pathOwner: string, expires: string | undefined, headerOwner: string | undefined): Promise<{
8
+ url: string;
9
+ expiresInSeconds: number;
10
+ }>;
7
11
  /**
8
12
  * Addressed by strings the caller already has: the provider, the
9
13
  * configuration slug it chose, and its own id for the person. Nothing Kosha
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.controller.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.controller.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAYlD,qBAEa,eAAe;IACd,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,YAAY;IAEhD;;;;;;;;OAQG;IAiBG,OAAO,CACJ,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,QAAQ,EACN,QAAQ,EAAE,MAAM,EACP,iBAAiB,EAAE,MAAM,EACrC,SAAS,EAAE,MAAM,EACP,WAAW,EAAE,MAAM,GAAG,SAAS;CAuC5D;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC1B,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,SAAS,EAAE,MAAM,GAChB,MAAM,CAER;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,KAAK,EAAE,MAAM,GACZ;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAYjC"}
1
+ {"version":3,"file":"proxy.controller.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.controller.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAYlD,qBAEa,eAAe;IACd,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,YAAY;IAM1C,OAAO,CACJ,OAAO,EAAE,aAAa,EACV,QAAQ,EAAE,MAAM,EACP,iBAAiB,EAAE,MAAM,EACrC,SAAS,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,GAAG,SAAS,EACnB,WAAW,EAAE,MAAM,GAAG,SAAS;;;;IAwB3D;;;;;;;;OAQG;IAiBG,OAAO,CACJ,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,QAAQ,EACN,QAAQ,EAAE,MAAM,EACP,iBAAiB,EAAE,MAAM,EACrC,SAAS,EAAE,MAAM,EACP,WAAW,EAAE,MAAM,GAAG,SAAS;CAuC5D;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC1B,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,SAAS,EAAE,MAAM,GAChB,MAAM,CAER;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,KAAK,EAAE,MAAM,GACZ;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAYjC"}
@@ -1,5 +1,5 @@
1
1
  import { __decorate, __metadata, __param } from "tslib";
2
- import { All, BadRequestException, Controller, Headers, Param, Req, Res, UseGuards, } from '@nestjs/common';
2
+ import { All, BadRequestException, Controller, Headers, Get, Param, Query, Req, Res, UseGuards, } from '@nestjs/common';
3
3
  import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
4
4
  import { AllowAnonymous } from '@thallesp/nestjs-better-auth';
5
5
  import { ApiKeyGuard } from '../auth/api-key.guard.js';
@@ -18,6 +18,15 @@ let ProxyController = class ProxyController {
18
18
  constructor(proxy) {
19
19
  this.proxy = proxy;
20
20
  }
21
+ async presign(request, provider, configurationSlug, pathOwner, expires, headerOwner) {
22
+ if (!request.environmentId) {
23
+ throw new BadRequestException('This route needs an API key, which is what names the environment');
24
+ }
25
+ const owner = resolveOwner(headerOwner, pathOwner);
26
+ const { path } = splitUpstreamTarget(request.originalUrl, provider, configurationSlug, pathOwner);
27
+ const expiresInSeconds = expires === undefined ? 900 : Number(expires);
28
+ return this.proxy.presign(request.organizationId, request.environmentId, { provider, configurationSlug, owner }, path, expiresInSeconds);
29
+ }
21
30
  /**
22
31
  * Addressed by strings the caller already has: the provider, the
23
32
  * configuration slug it chose, and its own id for the person. Nothing Kosha
@@ -53,6 +62,21 @@ let ProxyController = class ProxyController {
53
62
  response.send(result.body);
54
63
  }
55
64
  };
65
+ __decorate([
66
+ Get('presign/:provider/:configurationSlug/:owner{/*path}'),
67
+ AllowAnonymous(),
68
+ UseGuards(ApiKeyGuard),
69
+ ApiSecurity('x-api-key'),
70
+ __param(0, Req()),
71
+ __param(1, Param('provider')),
72
+ __param(2, Param('configurationSlug')),
73
+ __param(3, Param('owner')),
74
+ __param(4, Query('expires')),
75
+ __param(5, Headers('x-kosha-owner')),
76
+ __metadata("design:type", Function),
77
+ __metadata("design:paramtypes", [Object, String, String, String, Object, Object]),
78
+ __metadata("design:returntype", Promise)
79
+ ], ProxyController.prototype, "presign", null);
56
80
  __decorate([
57
81
  All(':provider/:configurationSlug/:owner{/*path}'),
58
82
  AllowAnonymous(),
@@ -29,6 +29,10 @@ export declare class ProxyService {
29
29
  private readonly resolver;
30
30
  constructor(proxy: ProxyRepository, environments: EnvironmentsService, store: ProviderStore, registry: IntegrationRegistry, resolver: CredentialsService);
31
31
  forward(organizationId: string, environmentId: string, target: ProxyTarget, request: ProxyRequest): Promise<ProxyResult>;
32
+ presign(organizationId: string, environmentId: string, target: ProxyTarget, path: string, expiresInSeconds: number): Promise<{
33
+ url: string;
34
+ expiresInSeconds: number;
35
+ }>;
32
36
  private buildTargetUrl;
33
37
  }
34
38
  //# sourceMappingURL=proxy.service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.service.d.ts","sourceRoot":"","sources":["../../src/proxy/proxy.service.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAoBxD,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IACvD,IAAI,EAAE,OAAO,CAAC;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,yFAAyF;AACzF,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC;CACf;AAED,qBACa,YAAY;IAErB,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAJR,KAAK,EAAE,eAAe,EACtB,YAAY,EAAE,mBAAmB,EACjC,KAAK,EAAE,aAAa,EACpB,QAAQ,EAAE,mBAAmB,EAC7B,Q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,QAAQ;gBAJR,KAAK,EAAE,eAAe,EACtB,YAAY,EAAE,mBAAmB,EACjC,KAAK,EAAE,aAAa,EACpB,QAAQ,EAAE,mBAAmB,EAC7B,QAAQ,EAAE,kBAAkB;IAGzC,OAAO,CACX,cAAc,EAAE,MAAM,EACtB,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,GACpB,OAAO,CAAC,WAAW,CAAC;IAyIjB,OAAO,CACX,cAAc,EAAE,MAAM,EACtB,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,WAAW,EACnB,IAAI,EAAE,MAAM,EACZ,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,gBAAgB,EAAE,MAAM,CAAA;KAAE,CAAC;IAoErD,OAAO,CAAC,cAAc;CAevB"}
@@ -114,12 +114,26 @@ let ProxyService = class ProxyService {
114
114
  }
115
115
  const method = request.method.toUpperCase();
116
116
  const sendsBody = !['GET', 'HEAD'].includes(method);
117
- const response = await fetch(targetUrl, {
117
+ const body = sendsBody && request.body !== undefined && request.body !== null
118
+ ? Buffer.isBuffer(request.body)
119
+ ? request.body
120
+ : JSON.stringify(request.body)
121
+ : undefined;
122
+ const signedHeaders = await integration.api.signRequest?.({
123
+ credential,
124
+ fields: configuration.fields,
125
+ url: targetUrl,
118
126
  method,
119
127
  headers: Object.fromEntries(headers),
120
- body: sendsBody && request.body !== undefined && request.body !== null
121
- ? JSON.stringify(request.body)
122
- : undefined,
128
+ body,
129
+ });
130
+ const fetchBody = Buffer.isBuffer(body) ? Uint8Array.from(body) : body;
131
+ const response = await fetch(targetUrl, {
132
+ method,
133
+ headers: signedHeaders ?? Object.fromEntries(headers),
134
+ body: fetchBody,
135
+ // A signed request must not forward credentials to a redirect target.
136
+ ...(signedHeaders ? { redirect: 'manual' } : {}),
123
137
  });
124
138
  return {
125
139
  status: response.status,
@@ -127,6 +141,56 @@ let ProxyService = class ProxyService {
127
141
  body: await response.text(),
128
142
  };
129
143
  }
144
+ async presign(organizationId, environmentId, target, path, expiresInSeconds) {
145
+ const environment = await this.environments.get(organizationId, environmentId);
146
+ const integration = this.registry.find(target.provider);
147
+ if (!integration?.api?.presignUrl) {
148
+ throw new NotFoundException(`${target.provider} does not support presigned URLs.`);
149
+ }
150
+ const [configuration, userId] = await Promise.all([
151
+ this.store.findConfigurationBySlugWithCredentials(integration, environment.id, target.configurationSlug),
152
+ this.proxy.findUserId(environment.slug, target.owner),
153
+ ]);
154
+ if (!configuration || !userId)
155
+ throw new NotFoundException('Connection not found');
156
+ const connection = await this.store.findConnection(integration, environment.id, configuration.id, userId);
157
+ if (!connection)
158
+ throw new NotFoundException('Connection not found');
159
+ const account = await this.proxy.findAccount(connection.accountId);
160
+ if (!account)
161
+ throw new NotFoundException('Connection not found');
162
+ const credential = await this.resolver.resolve(account, integration, configuration);
163
+ const resolved = integration.api.resolveBaseUrl?.({
164
+ credential: {
165
+ accessToken: credential.accessToken,
166
+ tokenType: credential.tokenType,
167
+ },
168
+ metadata: asMetadata(connection.metadata),
169
+ fields: configuration.fields,
170
+ });
171
+ const baseUrl = resolved ?? integration.api.baseUrl;
172
+ if (!baseUrl)
173
+ throw new BadGatewayException('Provider has no resolvable base URL for this connection');
174
+ if (resolved)
175
+ await assertAllowedUrl(baseUrl);
176
+ const url = this.buildTargetUrl(baseUrl, {
177
+ path,
178
+ query: '',
179
+ method: 'GET',
180
+ headers: {},
181
+ body: undefined,
182
+ });
183
+ const signed = await integration.api.presignUrl({
184
+ credential: {
185
+ accessToken: credential.accessToken,
186
+ tokenType: credential.tokenType,
187
+ },
188
+ fields: configuration.fields,
189
+ url,
190
+ expiresInSeconds,
191
+ });
192
+ return { url: signed, expiresInSeconds };
193
+ }
130
194
  buildTargetUrl(baseUrl, request) {
131
195
  const base = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
132
196
  const url = new URL(request.path.replace(/^\/+/, ''), base);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kosha-ai/server",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Kosha server: OAuth handshake, encrypted credential storage, token refresh, and an authenticated request proxy for third-party integrations",
5
5
  "keywords": [
6
6
  "kosha",
@@ -109,7 +109,7 @@
109
109
  "rxjs": "^7.8.0",
110
110
  "tslib": "^2.3.0",
111
111
  "zod": "4.5.4",
112
- "@kosha-ai/integration-sdk": "0.5.0"
112
+ "@kosha-ai/integration-sdk": "0.5.2"
113
113
  },
114
114
  "devDependencies": {
115
115
  "@nestjs/testing": "^11.0.0",
@@ -117,7 +117,7 @@
117
117
  "@types/node-forge": "^1.3.14",
118
118
  "@types/pg": "^8.23.1",
119
119
  "prisma": "^7.10.0",
120
- "@kosha-ai/integration-github": "0.5.0",
121
- "@kosha-ai/integration-slack": "0.5.0"
120
+ "@kosha-ai/integration-github": "0.5.2",
121
+ "@kosha-ai/integration-slack": "0.5.2"
122
122
  }
123
123
  }