@kosha-ai/integration-postgres 0.0.0-stage → 0.4.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 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.
@@ -0,0 +1,2 @@
1
+ export { postgres, postgres as default, PostgresConnectionError, } from './lib/integration-postgres.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,EACL,QAAQ,EACR,QAAQ,IAAI,OAAO,EACnB,uBAAuB,GACxB,MAAM,+BAA+B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { postgres, postgres as default, PostgresConnectionError, } from './lib/integration-postgres.js';
@@ -0,0 +1,13 @@
1
+ import type { KoshaIntegration } from '@kosha-ai/integration-sdk';
2
+ export declare class PostgresConnectionError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ /**
6
+ * A Postgres database, reached directly over its own wire protocol rather
7
+ * than proxied as HTTP — hence `query`, not `api`. Every call is read-only:
8
+ * Kosha has no write path for this integration regardless of what the
9
+ * connected database user is otherwise allowed to do.
10
+ */
11
+ export declare function postgres(): KoshaIntegration;
12
+ export default postgres;
13
+ //# sourceMappingURL=integration-postgres.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integration-postgres.d.ts","sourceRoot":"","sources":["../../src/lib/integration-postgres.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAIV,gBAAgB,EAEjB,MAAM,2BAA2B,CAAC;AAInC,qBAAa,uBAAwB,SAAQ,KAAK;gBACpC,OAAO,EAAE,MAAM;CAI5B;AAsKD;;;;;GAKG;AACH,wBAAgB,QAAQ,IAAI,gBAAgB,CAgE3C;AAED,eAAe,QAAQ,CAAC"}
@@ -0,0 +1,193 @@
1
+ import { Client } from 'pg';
2
+ import { assertPublicHost, basic as basicAuth, defineIntegration, packageDirs, } from '@kosha-ai/integration-sdk';
3
+ const { docsPath, migrationsPath } = packageDirs(import.meta.url);
4
+ export class PostgresConnectionError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = 'PostgresConnectionError';
8
+ }
9
+ }
10
+ const DEFAULT_PORT = 5432;
11
+ const STATEMENT_TIMEOUT = '30s';
12
+ function required(fields, key) {
13
+ const value = fields?.[key];
14
+ if (typeof value !== 'string' || value.trim() === '') {
15
+ throw new PostgresConnectionError(`${key} is missing from this configuration`);
16
+ }
17
+ return value;
18
+ }
19
+ /**
20
+ * `url` is `host` or `host:port` — not a scheme-carrying URL, since Postgres
21
+ * speaks its own wire protocol rather than HTTP. Defaults to 5432 when no
22
+ * port is given, and leaves an IPv6 literal (`::1`, `2001:db8::1`) untouched
23
+ * rather than mistaking part of it for a port.
24
+ */
25
+ function parseUrl(value) {
26
+ const lastColon = value.lastIndexOf(':');
27
+ if (lastColon === -1)
28
+ return { host: value, port: DEFAULT_PORT };
29
+ const host = value.slice(0, lastColon);
30
+ if (host.includes(':'))
31
+ return { host: value, port: DEFAULT_PORT };
32
+ const port = Number(value.slice(lastColon + 1));
33
+ return Number.isInteger(port) && port > 0 && port < 65536
34
+ ? { host, port }
35
+ : { host: value, port: DEFAULT_PORT };
36
+ }
37
+ /**
38
+ * `accessToken` is `base64(username:password)` — the same encoding
39
+ * `envelopeForCredential`'s `BASIC` case in the server produces for every
40
+ * Basic-auth integration, and the same one `@kosha-ai/integration-basic`
41
+ * decodes for an HTTP one.
42
+ */
43
+ function decodeCredential(credential) {
44
+ const [username, ...rest] = Buffer.from(credential.accessToken, 'base64')
45
+ .toString('utf8')
46
+ .split(':');
47
+ if (!username) {
48
+ throw new PostgresConnectionError('Credential did not decode to a username and password');
49
+ }
50
+ return { username, password: rest.join(':') };
51
+ }
52
+ function targetOf(fields, credential) {
53
+ const { username, password } = decodeCredential(credential);
54
+ const { host, port } = parseUrl(required(fields, 'url'));
55
+ return {
56
+ host,
57
+ port,
58
+ database: required(fields, 'database'),
59
+ username,
60
+ password,
61
+ };
62
+ }
63
+ /**
64
+ * Connects encrypted when the server offers it — not verified against a CA,
65
+ * since most managed Postgres providers terminate TLS with a cert this
66
+ * process has no chain for — and falls back to a plain connection only when
67
+ * the server says outright it has no SSL to offer (common for self-hosted
68
+ * and local setups). Any other failure (wrong password, unreachable host)
69
+ * surfaces as-is rather than being retried blind.
70
+ */
71
+ async function connectClient(target) {
72
+ const base = {
73
+ host: target.host,
74
+ port: target.port,
75
+ database: target.database,
76
+ user: target.username,
77
+ password: target.password,
78
+ };
79
+ const encrypted = new Client({ ...base, ssl: { rejectUnauthorized: false } });
80
+ try {
81
+ await encrypted.connect();
82
+ return encrypted;
83
+ }
84
+ catch (error) {
85
+ if (!(error instanceof Error) ||
86
+ !/does not support SSL/i.test(error.message)) {
87
+ throw error;
88
+ }
89
+ }
90
+ const plain = new Client({ ...base, ssl: false });
91
+ await plain.connect();
92
+ return plain;
93
+ }
94
+ /**
95
+ * Opens a fresh connection, runs `fn` inside a read-only transaction, and
96
+ * always rolls back — never commits — regardless of how `fn` ends.
97
+ *
98
+ * Read-only is enforced by Postgres itself (`BEGIN READ ONLY` rejects
99
+ * INSERT/UPDATE/DELETE/DDL/`SELECT ... FOR UPDATE` at the engine level), not
100
+ * by Kosha parsing the SQL text: the same trust-the-real-protocol stance
101
+ * `assertPublicUrl`/`assertPublicHost` take with DNS over regex.
102
+ *
103
+ * No connection pooling: every call opens and closes its own client, which
104
+ * is simplest and safest for a multi-tenant service where no two calls
105
+ * should ever be able to share a session — every other credential this SDK
106
+ * resolves is similarly per-call rather than cached.
107
+ */
108
+ async function withReadOnlyClient(fields, credential, fn) {
109
+ const target = targetOf(fields, credential);
110
+ // Re-checked on every call, not only when the configuration was saved: a
111
+ // hostname that answered publicly yesterday can point inside the network
112
+ // today (DNS rebinding).
113
+ await assertPublicHost(target.host);
114
+ let client;
115
+ try {
116
+ client = await connectClient(target);
117
+ }
118
+ catch (error) {
119
+ throw new PostgresConnectionError(`Could not connect to ${target.host}:${target.port}/${target.database}: ${error instanceof Error ? error.message : String(error)}`);
120
+ }
121
+ try {
122
+ await client.query('BEGIN READ ONLY');
123
+ await client.query(`SET LOCAL statement_timeout = '${STATEMENT_TIMEOUT}'`);
124
+ return await fn(client);
125
+ }
126
+ finally {
127
+ // Always rolled back, even on success: nothing this integration runs is
128
+ // ever meant to persist, and a read-only transaction has nothing to
129
+ // commit anyway.
130
+ await client.query('ROLLBACK').catch(() => undefined);
131
+ await client.end();
132
+ }
133
+ }
134
+ /**
135
+ * A Postgres database, reached directly over its own wire protocol rather
136
+ * than proxied as HTTP — hence `query`, not `api`. Every call is read-only:
137
+ * Kosha has no write path for this integration regardless of what the
138
+ * connected database user is otherwise allowed to do.
139
+ */
140
+ export function postgres() {
141
+ return defineIntegration({
142
+ key: 'postgres',
143
+ name: 'Postgres',
144
+ docsPath,
145
+ migrationsPath,
146
+ auth: basicAuth(),
147
+ configFields: [
148
+ {
149
+ key: 'url',
150
+ label: 'URL',
151
+ type: 'host',
152
+ required: true,
153
+ help: 'The database host, optionally with :port (defaults to 5432), e.g. db.acme.test:5432. Must resolve to a public address.',
154
+ },
155
+ {
156
+ key: 'database',
157
+ label: 'Database',
158
+ type: 'string',
159
+ required: true,
160
+ },
161
+ ],
162
+ query: {
163
+ readOnly: true,
164
+ async run({ credential, fields, sql, params }) {
165
+ return withReadOnlyClient(fields, credential, async (client) => {
166
+ const result = await client.query({ text: sql, values: params });
167
+ return {
168
+ rows: result.rows,
169
+ fields: result.fields.map((field) => field.name),
170
+ rowCount: result.rowCount ?? result.rows.length,
171
+ };
172
+ });
173
+ },
174
+ },
175
+ identity: {
176
+ /**
177
+ * `http` is unusable here — there is no REST endpoint to call — so it
178
+ * is ignored; the same real connection this integration will later
179
+ * query with is what proves the credential.
180
+ */
181
+ async fetchAccount({ accessToken, fields }) {
182
+ const credential = { accessToken };
183
+ const { host, database } = targetOf(fields, credential);
184
+ const row = await withReadOnlyClient(fields, credential, async (client) => {
185
+ const result = await client.query('SELECT current_user');
186
+ return result.rows[0];
187
+ });
188
+ return { externalAccountId: `${row.current_user}@${host}/${database}` };
189
+ },
190
+ },
191
+ });
192
+ }
193
+ export default postgres;
package/docs/setup.md ADDED
@@ -0,0 +1,73 @@
1
+ # Postgres setup
2
+
3
+ There is nothing to register with a provider. You need two things, and —
4
+ unlike an OAuth provider — both are usually entered by one admin, not by
5
+ each person who will end up running a query.
6
+
7
+ ### 1. The database
8
+
9
+ When you create the configuration, give Kosha:
10
+
11
+ - **URL** — the database host, optionally with `:port` (e.g. `db.acme.test`
12
+ or `db.acme.test:5432`; defaults to `5432`). It must resolve to a public
13
+ address; a host pointing at `localhost`, a private range or a link-local
14
+ address is refused, because Kosha is the one connecting and an operator
15
+ could otherwise reach inside the network Kosha runs in.
16
+ - **Database** — the database name.
17
+
18
+ Connections are always encrypted in transit (TLS), but the server's
19
+ certificate isn't verified against a CA — most managed Postgres providers
20
+ terminate TLS with a cert this process has no chain for. This isn't
21
+ configurable yet.
22
+
23
+ ### 2. The credentials
24
+
25
+ Postgres has no concept of "the workspace's key" the way Apollo's API key
26
+ does, but the usage is the same in practice: one admin connects **one**
27
+ read-only username and password, once, and every query Kosha runs
28
+ afterwards — on behalf of however many people in the org — rides on that
29
+ same connection. This is a fact about how organizations run this integration,
30
+ not a different mechanism: Kosha's connect flow is always "one secret, one
31
+ connection," it's just that here the one secret is a shared database role
32
+ rather than a personal login.
33
+
34
+ Concretely, that's `POST /api/connect/credential` called once, with a fixed
35
+ placeholder `externalUserId` the admin picks (`"org"`, the org's own id,
36
+ anything stable) rather than a real person:
37
+
38
+ ```jsonc
39
+ POST /api/connect/credential
40
+ {
41
+ "provider": "postgres",
42
+ "configurationSlug": "pg-main",
43
+ "externalUserId": "org",
44
+ "credential": { "username": "readonly_role", "password": "…" }
45
+ }
46
+ ```
47
+
48
+ Every later query reuses that same owner, regardless of which of _your_
49
+ users triggered it — Kosha never sees them individually:
50
+
51
+ ```jsonc
52
+ POST /api/query/postgres/pg-main/org
53
+ { "sql": "SELECT …" }
54
+ ```
55
+
56
+ Nothing stops you from connecting a second, different credential under a
57
+ different owner later (per team, per environment, whatever you need) — it's
58
+ just that most setups only ever need the one.
59
+
60
+ ### Read-only, enforced by Postgres itself
61
+
62
+ Every query Kosha runs through this connection happens inside a `BEGIN READ
63
+ ONLY` transaction that is always rolled back, never committed. Postgres
64
+ itself rejects `INSERT`/`UPDATE`/`DELETE`/DDL/`SELECT ... FOR UPDATE` inside
65
+ that transaction — Kosha does not parse or filter the SQL text, so there is
66
+ no way to word a write around it.
67
+
68
+ That guarantee doesn't bound _cost_: a read-only transaction can still run an
69
+ expensive or endless `SELECT`. Kosha sets a 30-second statement timeout per
70
+ call as a cheap backstop, but as defense in depth you should still grant the
71
+ database user you connect with here a dedicated **read-only role** — never
72
+ one with write access, which this integration does not need and should not
73
+ be trusted with just because Kosha's own transaction happens to block it.
@@ -0,0 +1,53 @@
1
+ CREATE TABLE "postgres_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
+ -- The database this configuration points at. Operator-supplied, so
9
+ -- checked against private ranges before Kosha ever connects to it.
10
+ -- "url" is `host` or `host:port`, not a scheme-carrying URL.
11
+ "url" TEXT NOT NULL,
12
+ "database" TEXT NOT NULL,
13
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
14
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
15
+
16
+ CONSTRAINT "postgres_configuration_pkey" PRIMARY KEY ("id")
17
+ );
18
+
19
+ CREATE TABLE "postgres_connection" (
20
+ "accountId" TEXT NOT NULL,
21
+ -- Copied from `account` so the unique index below can use it.
22
+ "userId" TEXT NOT NULL,
23
+ "environmentId" TEXT NOT NULL,
24
+ "configurationId" TEXT NOT NULL,
25
+ "metadata" JSONB,
26
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
27
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
28
+
29
+ CONSTRAINT "postgres_connection_pkey" PRIMARY KEY ("accountId")
30
+ );
31
+
32
+ CREATE UNIQUE INDEX "postgres_configuration_environmentId_slug_key" ON "postgres_configuration"("environmentId", "slug");
33
+
34
+ CREATE INDEX "postgres_configuration_environmentId_idx" ON "postgres_configuration"("environmentId");
35
+
36
+ CREATE UNIQUE INDEX "postgres_connection_environmentId_configurationId_userId_key" ON "postgres_connection"("environmentId", "configurationId", "userId");
37
+
38
+ CREATE INDEX "postgres_connection_environmentId_idx" ON "postgres_connection"("environmentId");
39
+
40
+ CREATE INDEX "postgres_connection_configurationId_idx" ON "postgres_connection"("configurationId");
41
+
42
+ CREATE INDEX "postgres_connection_userId_idx" ON "postgres_connection"("userId");
43
+
44
+ ALTER TABLE "postgres_configuration" ADD CONSTRAINT "postgres_configuration_environmentId_fkey" FOREIGN KEY ("environmentId") REFERENCES "environment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
45
+
46
+ ALTER TABLE "postgres_connection" ADD CONSTRAINT "postgres_connection_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
47
+
48
+ ALTER TABLE "postgres_connection" ADD CONSTRAINT "postgres_connection_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
49
+
50
+ ALTER TABLE "postgres_connection" ADD CONSTRAINT "postgres_connection_environmentId_fkey" FOREIGN KEY ("environmentId") REFERENCES "environment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
51
+
52
+ -- RESTRICT: a configuration that still has connections cannot be deleted.
53
+ ALTER TABLE "postgres_connection" ADD CONSTRAINT "postgres_connection_configurationId_fkey" FOREIGN KEY ("configurationId") REFERENCES "postgres_configuration"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@kosha-ai/integration-postgres",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.4.1",
4
+ "description": "Postgres integration for Kosha: read-only queries against a connected database",
5
+ "keywords": [
6
+ "kosha",
7
+ "postgres",
8
+ "integrations"
9
+ ],
10
+ "license": "MIT",
11
+ "homepage": "https://github.com/codemancers/kosha#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/codemancers/kosha/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/codemancers/kosha.git",
18
+ "directory": "packages/integrations/postgres"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "type": "module",
24
+ "main": "./dist/index.js",
25
+ "module": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ "./package.json": "./package.json",
29
+ ".": {
30
+ "@org/source": "./src/index.ts",
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "default": "./dist/index.js"
34
+ }
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "docs",
39
+ "migrations",
40
+ "!**/*.tsbuildinfo"
41
+ ],
42
+ "dependencies": {
43
+ "tslib": "^2.3.0",
44
+ "pg": "^8.13.0"
45
+ },
46
+ "kosha": {
47
+ "kind": "integration",
48
+ "key": "postgres"
49
+ },
50
+ "peerDependencies": {
51
+ "@kosha-ai/integration-sdk": "0.4.1"
52
+ },
53
+ "devDependencies": {
54
+ "@types/pg": "^8.11.0",
55
+ "@kosha-ai/integration-sdk": "0.4.1"
56
+ }
6
57
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.