@kosha-ai/integration-s3 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Codemancers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,20 @@
1
- # Temporary Holding Version
1
+ # @kosha-ai/integration-s3
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Amazon S3 integration for Kosha. Stores an IAM access key pair encrypted, verifies
4
+ access to a configured bucket, and signs HTTP proxy requests with AWS Signature V4.
5
+
6
+ ```ts
7
+ import s3 from '@kosha-ai/integration-s3';
8
+
9
+ export default {
10
+ integrations: [s3()],
11
+ };
12
+ ```
13
+
14
+ For an existing Kosha app, run `npx kosha integration add s3`, then apply migrations
15
+ with `npx kosha migrate deploy`. See [setup](docs/setup.md).
16
+
17
+ This version supports IAM access keys and general purpose AWS S3 buckets. Temporary
18
+ session credentials, AssumeRole, custom S3-compatible endpoints, presigned URLs and
19
+ egress brokering are not supported. Binary and document uploads up to 50 MB are
20
+ forwarded for non-JSON content types.
@@ -0,0 +1,2 @@
1
+ export { s3, s3 as default } from './lib/integration-s3.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,EAAE,IAAI,OAAO,EAAE,MAAM,yBAAyB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { s3, s3 as default } from './lib/integration-s3.js';
@@ -0,0 +1,5 @@
1
+ import type { KoshaIntegration } from '@kosha-ai/integration-sdk';
2
+ /** A single AWS S3 bucket, authenticated with an IAM access key pair. */
3
+ export declare function s3(): KoshaIntegration;
4
+ export default s3;
5
+ //# sourceMappingURL=integration-s3.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integration-s3.d.ts","sourceRoot":"","sources":["../../src/lib/integration-s3.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAGV,gBAAgB,EACjB,MAAM,2BAA2B,CAAC;AAqHnC,yEAAyE;AACzE,wBAAgB,EAAE,IAAI,gBAAgB,CAyErC;AAED,eAAe,EAAE,CAAC"}
@@ -0,0 +1,164 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AwsV4Signer } from 'aws4fetch';
3
+ import { basic, defineIntegration, packageDirs, } from '@kosha-ai/integration-sdk';
4
+ const { docsPath, migrationsPath } = packageDirs(import.meta.url);
5
+ const REGION = /^[a-z]{2}(?:-[a-z]+)+-\d+$/;
6
+ const BUCKET = /^(?!\d+\.\d+\.\d+\.\d+$)(?!.*\.\.)[a-z0-9](?:[a-z0-9.]|-){1,61}[a-z0-9]$/;
7
+ function settings(fields) {
8
+ const region = fields?.['region'];
9
+ const bucket = fields?.['bucket'];
10
+ if (typeof region !== 'string' || !REGION.test(region)) {
11
+ throw new Error('A valid AWS region is required.');
12
+ }
13
+ if (typeof bucket !== 'string' || !BUCKET.test(bucket)) {
14
+ throw new Error('A valid S3 bucket name is required.');
15
+ }
16
+ const domain = region.startsWith('cn-')
17
+ ? 'amazonaws.com.cn'
18
+ : 'amazonaws.com';
19
+ return {
20
+ region,
21
+ bucket,
22
+ baseUrl: `https://s3.${region}.${domain}/${bucket}`,
23
+ };
24
+ }
25
+ const signRequest = async ({ credential, fields, url, method, headers, body, }) => {
26
+ const { region } = settings(fields);
27
+ // Kosha's BASIC envelope keeps both keys encrypted and resolves them as
28
+ // base64(accessKeyId:secretAccessKey). No Basic header is sent to AWS.
29
+ const decoded = Buffer.from(credential.accessToken, 'base64').toString('utf8');
30
+ const colon = decoded.indexOf(':');
31
+ const accessKeyId = decoded.slice(0, colon);
32
+ const secretAccessKey = decoded.slice(colon + 1);
33
+ if (colon < 1 || !secretAccessKey) {
34
+ throw new Error('An AWS access key ID and secret access key are required.');
35
+ }
36
+ if ([...url.searchParams.keys()].some((key) => /^x-amz-/i.test(key))) {
37
+ throw new Error('Presigned authentication parameters are not supported.');
38
+ }
39
+ const clean = new Headers(headers);
40
+ for (const name of [
41
+ 'authorization',
42
+ 'x-amz-date',
43
+ 'x-amz-security-token',
44
+ 'x-amz-content-sha256',
45
+ ]) {
46
+ clean.delete(name);
47
+ }
48
+ clean.set('x-amz-content-sha256', createHash('sha256')
49
+ .update(body ?? '')
50
+ .digest('hex'));
51
+ const signed = await new AwsV4Signer({
52
+ accessKeyId,
53
+ secretAccessKey,
54
+ service: 's3',
55
+ region,
56
+ url: url.toString(),
57
+ method,
58
+ headers: clean,
59
+ body,
60
+ }).sign();
61
+ return Object.fromEntries(signed.headers.entries());
62
+ };
63
+ const presignUrl = async ({ credential, fields, url, method = 'GET', expiresInSeconds, }) => {
64
+ const { region } = settings(fields);
65
+ if (!Number.isInteger(expiresInSeconds) ||
66
+ expiresInSeconds < 1 ||
67
+ expiresInSeconds > 604800) {
68
+ throw new Error('S3 presigned URL expiry must be between 1 and 604800 seconds.');
69
+ }
70
+ const decoded = Buffer.from(credential.accessToken, 'base64').toString('utf8');
71
+ const colon = decoded.indexOf(':');
72
+ const accessKeyId = decoded.slice(0, colon);
73
+ const secretAccessKey = decoded.slice(colon + 1);
74
+ if (colon < 1 || !secretAccessKey) {
75
+ throw new Error('An AWS access key ID and secret access key are required.');
76
+ }
77
+ url.searchParams.set('X-Amz-Expires', String(expiresInSeconds));
78
+ const signed = await new AwsV4Signer({
79
+ accessKeyId,
80
+ secretAccessKey,
81
+ service: 's3',
82
+ region,
83
+ url: url.toString(),
84
+ method,
85
+ signQuery: true,
86
+ appendSessionToken: true,
87
+ }).sign();
88
+ return signed.url.toString();
89
+ };
90
+ /** A single AWS S3 bucket, authenticated with an IAM access key pair. */
91
+ export function s3() {
92
+ return defineIntegration({
93
+ key: 's3',
94
+ name: 'Amazon S3',
95
+ docsUrl: 'https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html',
96
+ docsPath,
97
+ migrationsPath,
98
+ auth: basic({
99
+ credentialFields: [
100
+ {
101
+ key: 'username',
102
+ label: 'AWS access key ID',
103
+ type: 'string',
104
+ required: true,
105
+ },
106
+ {
107
+ key: 'password',
108
+ label: 'AWS secret access key',
109
+ type: 'string',
110
+ required: true,
111
+ secret: true,
112
+ },
113
+ ],
114
+ }),
115
+ configFields: [
116
+ {
117
+ key: 'region',
118
+ label: 'AWS region',
119
+ type: 'string',
120
+ required: true,
121
+ pattern: REGION.source.slice(1, -1),
122
+ help: 'The bucket region, e.g. us-east-1.',
123
+ },
124
+ {
125
+ key: 'bucket',
126
+ label: 'Bucket name',
127
+ type: 'string',
128
+ required: true,
129
+ pattern: BUCKET.source.slice(1, -1),
130
+ help: 'An existing general purpose S3 bucket.',
131
+ },
132
+ ],
133
+ api: {
134
+ resolveBaseUrl: ({ fields }) => settings(fields).baseUrl,
135
+ authHeaders: () => ({}),
136
+ signRequest,
137
+ presignUrl,
138
+ },
139
+ identity: {
140
+ async fetchAccount({ accessToken, fields, http }) {
141
+ const { bucket, baseUrl } = settings(fields);
142
+ const url = new URL(`${baseUrl}/`);
143
+ const headers = await signRequest({
144
+ credential: { accessToken },
145
+ fields,
146
+ url,
147
+ method: 'HEAD',
148
+ headers: {},
149
+ });
150
+ // HeadBucket validates the pair and bucket access without listing objects.
151
+ await http.request(url.toString(), {
152
+ method: 'HEAD',
153
+ headers,
154
+ redirect: 'manual',
155
+ });
156
+ const accessKeyId = Buffer.from(accessToken, 'base64')
157
+ .toString('utf8')
158
+ .split(':')[0];
159
+ return { externalAccountId: `${accessKeyId}@${bucket}`, label: bucket };
160
+ },
161
+ },
162
+ });
163
+ }
164
+ export default s3;
package/docs/setup.md ADDED
@@ -0,0 +1,48 @@
1
+ # Connect Amazon S3
2
+
3
+ 1. Create an IAM access key for a principal with access to the bucket. Use a policy
4
+ scoped to that bucket and its objects. Connecting requires `s3:ListBucket`
5
+ because Kosha verifies access with `HeadBucket`. Add `s3:GetObject`,
6
+ `s3:PutObject` or `s3:DeleteObject` only for operations your application needs.
7
+ 2. Create an Amazon S3 configuration in Kosha. Enter the bucket's AWS region
8
+ (for example `us-east-1`) and bucket name. Use the actual bucket region;
9
+ signed requests do not follow region redirects.
10
+ 3. Connect using the AWS access key ID and secret access key. Kosha verifies
11
+ bucket access before creating the connection. No OAuth app is needed.
12
+
13
+ Requests use path-style regional endpoints, including China regions. The configured
14
+ bucket is the root of the proxy, so omit the bucket name from request paths.
15
+
16
+ ```sh
17
+ curl "$KOSHA_URL/api/proxy/s3/<configurationSlug>/<owner>/?list-type=2" \
18
+ -H "x-api-key: $KOSHA_API_KEY"
19
+ ```
20
+
21
+ Upload an image, PDF, CSV, Word document, Excel workbook, or other file with its bytes unchanged:
22
+
23
+ ```sh
24
+ curl -X PUT "$KOSHA_URL/api/proxy/s3/<configurationSlug>/<owner>/images/photo.png" \
25
+ -H "x-api-key: $KOSHA_API_KEY" \
26
+ -H "content-type: image/png" \
27
+ --data-binary @photo.png
28
+ ```
29
+
30
+ Create a browser-download URL valid for 15 minutes:
31
+
32
+ ```sh
33
+ curl "$KOSHA_URL/api/proxy/presign/s3/<configurationSlug>/<owner>/images/photo.png?expires=900" \
34
+ -H "x-api-key: $KOSHA_API_KEY"
35
+ ```
36
+
37
+ The response contains a JSON `url` field. Share that URL directly; it already
38
+ contains the temporary AWS signature and does not require a Kosha header.
39
+
40
+ See the [AWS HeadBucket API](https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadBucket.html)
41
+ and [S3 policy examples](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-policies-s3.html).
42
+
43
+ The BASIC credential type shown by Kosha describes how the two keys are stored.
44
+ Requests to AWS use Signature V4; the secret key is never sent as an HTTP Basic header.
45
+ This version does not support STS session tokens or role assumption. The proxy's
46
+ Binary and document request bodies are accepted up to 50 MB for non-JSON content
47
+ types. JSON requests continue to use normal JSON proxy body handling. Multipart
48
+ form uploads are not interpreted; send the file itself with `--data-binary`.
@@ -0,0 +1,50 @@
1
+ CREATE TABLE "s3_configuration" (
2
+ "id" TEXT NOT NULL,
3
+ "environmentId" TEXT NOT NULL,
4
+ "name" TEXT NOT NULL,
5
+ "slug" TEXT NOT NULL,
6
+ -- Encrypted, so TEXT rather than JSONB.
7
+ "credentials" TEXT,
8
+ "region" TEXT NOT NULL,
9
+ "bucket" TEXT NOT NULL,
10
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
11
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
12
+
13
+ CONSTRAINT "s3_configuration_pkey" PRIMARY KEY ("id")
14
+ );
15
+
16
+ CREATE TABLE "s3_connection" (
17
+ "accountId" TEXT NOT NULL,
18
+ -- Copied from `account` so the unique index below can use it.
19
+ "userId" TEXT NOT NULL,
20
+ "environmentId" TEXT NOT NULL,
21
+ "configurationId" TEXT NOT NULL,
22
+ "metadata" JSONB,
23
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
24
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
25
+
26
+ CONSTRAINT "s3_connection_pkey" PRIMARY KEY ("accountId")
27
+ );
28
+
29
+ CREATE UNIQUE INDEX "s3_configuration_environmentId_slug_key" ON "s3_configuration"("environmentId", "slug");
30
+
31
+ CREATE INDEX "s3_configuration_environmentId_idx" ON "s3_configuration"("environmentId");
32
+
33
+ CREATE UNIQUE INDEX "s3_connection_environmentId_configurationId_userId_key" ON "s3_connection"("environmentId", "configurationId", "userId");
34
+
35
+ CREATE INDEX "s3_connection_environmentId_idx" ON "s3_connection"("environmentId");
36
+
37
+ CREATE INDEX "s3_connection_configurationId_idx" ON "s3_connection"("configurationId");
38
+
39
+ CREATE INDEX "s3_connection_userId_idx" ON "s3_connection"("userId");
40
+
41
+ ALTER TABLE "s3_configuration" ADD CONSTRAINT "s3_configuration_environmentId_fkey" FOREIGN KEY ("environmentId") REFERENCES "environment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
42
+
43
+ ALTER TABLE "s3_connection" ADD CONSTRAINT "s3_connection_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
44
+
45
+ ALTER TABLE "s3_connection" ADD CONSTRAINT "s3_connection_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
46
+
47
+ ALTER TABLE "s3_connection" ADD CONSTRAINT "s3_connection_environmentId_fkey" FOREIGN KEY ("environmentId") REFERENCES "environment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
48
+
49
+ -- RESTRICT: a configuration that still has connections cannot be deleted.
50
+ ALTER TABLE "s3_connection" ADD CONSTRAINT "s3_connection_configurationId_fkey" FOREIGN KEY ("configurationId") REFERENCES "s3_configuration"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@kosha-ai/integration-s3",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.5.2",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ "./package.json": "./package.json",
10
+ ".": {
11
+ "@org/source": "./src/index.ts",
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "default": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "docs",
20
+ "migrations",
21
+ "!**/*.tsbuildinfo"
22
+ ],
23
+ "dependencies": {
24
+ "aws4fetch": "^1.0.20",
25
+ "tslib": "^2.3.0"
26
+ },
27
+ "devDependencies": {
28
+ "@kosha-ai/integration-sdk": "0.5.2"
29
+ },
30
+ "peerDependencies": {
31
+ "@kosha-ai/integration-sdk": "0.5.2"
32
+ },
33
+ "license": "MIT",
34
+ "homepage": "https://github.com/codemancers/kosha#readme",
35
+ "bugs": {
36
+ "url": "https://github.com/codemancers/kosha/issues"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/codemancers/kosha.git",
41
+ "directory": "packages/integrations/s3"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "description": "Amazon S3 integration for Kosha with AWS Signature V4 authentication",
47
+ "keywords": [
48
+ "kosha",
49
+ "s3",
50
+ "aws",
51
+ "integrations"
52
+ ],
53
+ "kosha": {
54
+ "kind": "integration",
55
+ "key": "s3"
56
+ }
6
57
  }