@itphx/synth-storage-postgres 0.11.3 → 0.13.4
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/errors.d.ts +1 -1
- package/dist/errors.js +2 -2
- package/dist/index.d.ts +15 -1
- package/dist/index.js +24 -2
- package/dist/locks.d.ts +4 -4
- package/dist/locks.js +4 -4
- package/dist/migrate.d.ts +1 -1
- package/dist/migrate.js +1 -1
- package/dist/migrations/001-init.d.ts +2 -2
- package/dist/migrations/001-init.js +2 -2
- package/dist/migrations/003-analytics-rollups.d.ts +1 -1
- package/dist/migrations/003-analytics-rollups.js +1 -1
- package/dist/migrations/004-pipeline-engine.d.ts +19 -0
- package/dist/migrations/004-pipeline-engine.js +74 -0
- package/dist/migrations/005-pipeline-provenance.d.ts +12 -0
- package/dist/migrations/005-pipeline-provenance.js +15 -0
- package/dist/migrations/006-plugin-audit.d.ts +13 -0
- package/dist/migrations/006-plugin-audit.js +34 -0
- package/dist/migrations/007-plugin-lock.d.ts +10 -0
- package/dist/migrations/007-plugin-lock.js +25 -0
- package/dist/migrations/008-plugin-audit-scan.d.ts +11 -0
- package/dist/migrations/008-plugin-audit-scan.js +15 -0
- package/dist/migrations/009-plugin-lock-previous.d.ts +13 -0
- package/dist/migrations/009-plugin-lock-previous.js +16 -0
- package/dist/migrations/010-plugin-lock-mode.d.ts +16 -0
- package/dist/migrations/010-plugin-lock-mode.js +20 -0
- package/dist/migrations/011-session-steer-inbox.d.ts +11 -0
- package/dist/migrations/011-session-steer-inbox.js +14 -0
- package/dist/migrations/012-external-credentials.d.ts +15 -0
- package/dist/migrations/012-external-credentials.js +40 -0
- package/dist/migrations/013-service-key-plugin-id.d.ts +17 -0
- package/dist/migrations/013-service-key-plugin-id.js +20 -0
- package/dist/migrations/014-session-mode-by-principal.d.ts +12 -0
- package/dist/migrations/014-session-mode-by-principal.js +15 -0
- package/dist/migrations/015-authority.d.ts +17 -0
- package/dist/migrations/015-authority.js +43 -0
- package/dist/migrations/016-credential-audit.d.ts +17 -0
- package/dist/migrations/016-credential-audit.js +32 -0
- package/dist/migrations/017-memory.d.ts +29 -0
- package/dist/migrations/017-memory.js +95 -0
- package/dist/migrations/018-memory-index-scope.d.ts +14 -0
- package/dist/migrations/018-memory-index-scope.js +18 -0
- package/dist/migrations/019-memory-index-enabled.d.ts +11 -0
- package/dist/migrations/019-memory-index-enabled.js +14 -0
- package/dist/migrations/020-project-memory.d.ts +11 -0
- package/dist/migrations/020-project-memory.js +13 -0
- package/dist/migrations/021-background-runs.d.ts +17 -0
- package/dist/migrations/021-background-runs.js +67 -0
- package/dist/migrations/022-background-run-process-id.d.ts +14 -0
- package/dist/migrations/022-background-run-process-id.js +18 -0
- package/dist/migrations/023-session-worktree.d.ts +12 -0
- package/dist/migrations/023-session-worktree.js +16 -0
- package/dist/migrations/024-blob-refs.d.ts +15 -0
- package/dist/migrations/024-blob-refs.js +26 -0
- package/dist/migrations/025-packs-pipelines.d.ts +28 -0
- package/dist/migrations/025-packs-pipelines.js +82 -0
- package/dist/migrations/026-instance-skills.d.ts +17 -0
- package/dist/migrations/026-instance-skills.js +25 -0
- package/dist/migrations/027-context-files.d.ts +20 -0
- package/dist/migrations/027-context-files.js +30 -0
- package/dist/migrations/028-message-reasoning-signature.d.ts +13 -0
- package/dist/migrations/028-message-reasoning-signature.js +19 -0
- package/dist/migrations/029-message-stream-v2.d.ts +22 -0
- package/dist/migrations/029-message-stream-v2.js +33 -0
- package/dist/migrations/030-session-retry.d.ts +12 -0
- package/dist/migrations/030-session-retry.js +16 -0
- package/dist/migrations/index.d.ts +1 -1
- package/dist/migrations/index.js +55 -1
- package/dist/pool.d.ts +6 -6
- package/dist/pool.js +8 -8
- package/dist/ports/analytics.d.ts +1 -1
- package/dist/ports/analytics.js +1 -1
- package/dist/ports/audit.d.ts +1 -1
- package/dist/ports/audit.js +3 -0
- package/dist/ports/authority.d.ts +27 -0
- package/dist/ports/authority.js +148 -0
- package/dist/ports/background-runs.d.ts +41 -0
- package/dist/ports/background-runs.js +179 -0
- package/dist/ports/blob-refs.d.ts +36 -0
- package/dist/ports/blob-refs.js +55 -0
- package/dist/ports/content.d.ts +1 -1
- package/dist/ports/content.js +21 -7
- package/dist/ports/context-files.d.ts +147 -0
- package/dist/ports/context-files.js +285 -0
- package/dist/ports/core-sync.d.ts +1 -1
- package/dist/ports/core-sync.js +1 -1
- package/dist/ports/credential-audit.d.ts +19 -0
- package/dist/ports/credential-audit.js +96 -0
- package/dist/ports/deps.d.ts +2 -2
- package/dist/ports/deps.js +1 -1
- package/dist/ports/events-bindings.d.ts +2 -2
- package/dist/ports/events-bindings.js +2 -2
- package/dist/ports/events-core.d.ts +1 -1
- package/dist/ports/events-core.js +1 -1
- package/dist/ports/events-journal.d.ts +1 -1
- package/dist/ports/events-journal.js +1 -1
- package/dist/ports/events-scheduler.d.ts +1 -1
- package/dist/ports/events-scheduler.js +20 -12
- package/dist/ports/events-webhooks.d.ts +1 -1
- package/dist/ports/events-webhooks.js +1 -1
- package/dist/ports/events.d.ts +1 -1
- package/dist/ports/events.js +1 -1
- package/dist/ports/external-credentials.d.ts +6 -0
- package/dist/ports/external-credentials.js +363 -0
- package/dist/ports/legacy-pipelines.d.ts +50 -0
- package/dist/ports/legacy-pipelines.js +202 -0
- package/dist/ports/memory.d.ts +65 -0
- package/dist/ports/memory.js +471 -0
- package/dist/ports/packs.d.ts +32 -0
- package/dist/ports/packs.js +117 -0
- package/dist/ports/pipelines.d.ts +67 -0
- package/dist/ports/pipelines.js +297 -0
- package/dist/ports/plugin-audit.d.ts +14 -0
- package/dist/ports/plugin-audit.js +110 -0
- package/dist/ports/plugin-lock.d.ts +27 -0
- package/dist/ports/plugin-lock.js +145 -0
- package/dist/ports/principals-defaults.d.ts +1 -1
- package/dist/ports/principals-defaults.js +21 -1
- package/dist/ports/principals-documents.d.ts +1 -1
- package/dist/ports/principals-documents.js +1 -1
- package/dist/ports/principals-profiles.d.ts +1 -1
- package/dist/ports/principals-profiles.js +1 -1
- package/dist/ports/principals-projects.d.ts +1 -1
- package/dist/ports/principals-projects.js +82 -47
- package/dist/ports/principals-settings.d.ts +1 -1
- package/dist/ports/principals-settings.js +57 -1
- package/dist/ports/principals-shared.d.ts +1 -1
- package/dist/ports/principals-shared.js +1 -1
- package/dist/ports/principals.d.ts +1 -1
- package/dist/ports/principals.js +1 -1
- package/dist/ports/questions.d.ts +40 -0
- package/dist/ports/questions.js +135 -0
- package/dist/ports/sessions-mapping.d.ts +80 -6
- package/dist/ports/sessions-mapping.js +165 -8
- package/dist/ports/sessions.d.ts +62 -8
- package/dist/ports/sessions.js +96 -20
- package/dist/ports/skills.d.ts +59 -0
- package/dist/ports/skills.js +205 -0
- package/dist/ports/stub.d.ts +1 -1
- package/dist/ports/stub.js +2 -2
- package/dist/ports/worktrees.d.ts +41 -0
- package/dist/ports/worktrees.js +85 -0
- package/dist/postgres-storage.d.ts +4 -5
- package/dist/postgres-storage.js +5 -6
- package/dist/storage-context.d.ts +44 -15
- package/dist/storage-context.js +139 -31
- package/package.json +4 -4
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* PG-реализация append-журнала событий, одноразовых claim-кодов и дедупа
|
|
3
|
-
* (
|
|
3
|
+
* (ADR-097, волна 3b): `eventJournal`/`identityClaims`/`dedup`.
|
|
4
4
|
*
|
|
5
5
|
* Семантика повторяет файловые реализации core (`EventJournalStore`,
|
|
6
6
|
* `IdentityClaimStore`, `FileDedupStore`): журнал — append-only (`seq bigserial`),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* PG-реализация портов планировщика (
|
|
2
|
+
* PG-реализация портов планировщика (ADR-097, волна 3b): `schedules`/`jobs`.
|
|
3
3
|
*
|
|
4
4
|
* Семантика повторяет файловые реализации core (`ScheduleStore`, `JobStore`):
|
|
5
5
|
* id `sch_<uuid>`, `updatedAt` при правке; `hasEnabledTargetFor` учитывает
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* PG-реализация портов планировщика (
|
|
2
|
+
* PG-реализация портов планировщика (ADR-097, волна 3b): `schedules`/`jobs`.
|
|
3
3
|
*
|
|
4
4
|
* Семантика повторяет файловые реализации core (`ScheduleStore`, `JobStore`):
|
|
5
5
|
* id `sch_<uuid>`, `updatedAt` при правке; `hasEnabledTargetFor` учитывает
|
|
@@ -91,32 +91,40 @@ export class PgScheduleRepository {
|
|
|
91
91
|
params.push(patch.enabled);
|
|
92
92
|
sets.push(`enabled = $${params.length}`);
|
|
93
93
|
}
|
|
94
|
-
|
|
95
|
-
|
|
94
|
+
// Пара триггеров заменяется целиком (контракт порта): собственный ключ
|
|
95
|
+
// `cron`/`every` переписывает **обе** колонки, отсутствующая/`undefined`
|
|
96
|
+
// уходит в NULL. Иначе очистить прежний триггер было нельзя, а запись с
|
|
97
|
+
// обоими полями не лечилась.
|
|
98
|
+
if (Object.hasOwn(patch, 'cron') || Object.hasOwn(patch, 'every')) {
|
|
99
|
+
params.push(patch.cron ?? null);
|
|
96
100
|
sets.push(`cron = $${params.length}`);
|
|
97
|
-
|
|
98
|
-
if (patch.every !== undefined) {
|
|
99
|
-
params.push(patch.every);
|
|
101
|
+
params.push(patch.every ?? null);
|
|
100
102
|
sets.push(`every = $${params.length}`);
|
|
101
103
|
}
|
|
102
104
|
if (patch.target !== undefined) {
|
|
103
105
|
params.push(jsonbParam(patch.target));
|
|
104
106
|
sets.push(`target = $${params.length}::jsonb`);
|
|
105
107
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
+
// Nullable-поля — own-property семантика: собственный ключ со значением
|
|
109
|
+
// `undefined` очищает колонку (`NULL`), отсутствие ключа — не трогает.
|
|
110
|
+
if (Object.hasOwn(patch, 'prompt')) {
|
|
111
|
+
params.push(patch.prompt ?? null);
|
|
108
112
|
sets.push(`prompt = $${params.length}`);
|
|
109
113
|
}
|
|
110
|
-
if (patch
|
|
111
|
-
params.push(jsonbParam(patch.payload));
|
|
114
|
+
if (Object.hasOwn(patch, 'payload')) {
|
|
115
|
+
params.push(patch.payload !== undefined ? jsonbParam(patch.payload) : null);
|
|
112
116
|
sets.push(`payload = $${params.length}::jsonb`);
|
|
113
117
|
}
|
|
118
|
+
// Владелец — исключение: это атрибуция/область доступа расписания
|
|
119
|
+
// (`ownerId === userId`), а не пользовательское содержимое. Патч с
|
|
120
|
+
// `ownerId: undefined` считается «не менять», иначе владельца можно было
|
|
121
|
+
// бы случайно потерять и расписание выпало бы из области «свои + проект».
|
|
114
122
|
if (patch.ownerId !== undefined) {
|
|
115
123
|
params.push(patch.ownerId);
|
|
116
124
|
sets.push(`owner_id = $${params.length}`);
|
|
117
125
|
}
|
|
118
|
-
if (patch
|
|
119
|
-
params.push(patch.catchUp);
|
|
126
|
+
if (Object.hasOwn(patch, 'catchUp')) {
|
|
127
|
+
params.push(patch.catchUp ?? null);
|
|
120
128
|
sets.push(`catch_up = $${params.length}`);
|
|
121
129
|
}
|
|
122
130
|
params.push(id);
|
package/dist/ports/events.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Группа портов **событий, расписаний и webhooks** PostgreSQL-драйвера
|
|
3
|
-
* (
|
|
3
|
+
* (ADR-097, волна 3b).
|
|
4
4
|
*
|
|
5
5
|
* Фабрика `buildEventPorts(deps)` собирает свою часть `StorageContext` из четырёх
|
|
6
6
|
* независимых под-файлов (каждый — отдельная подсистема, удобно править/тестировать):
|
package/dist/ports/events.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Группа портов **событий, расписаний и webhooks** PostgreSQL-драйвера
|
|
3
|
-
* (
|
|
3
|
+
* (ADR-097, волна 3b).
|
|
4
4
|
*
|
|
5
5
|
* Фабрика `buildEventPorts(deps)` собирает свою часть `StorageContext` из четырёх
|
|
6
6
|
* независимых под-файлов (каждый — отдельная подсистема, удобно править/тестировать):
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { StorageContext } from '@itphx/synth-core';
|
|
2
|
+
import type { PortDeps } from './deps.js';
|
|
3
|
+
/** Часть `StorageContext`, которой владеет модуль внешних доступов. */
|
|
4
|
+
export type ExternalCredentialPorts = Pick<StorageContext, 'externalCredentials'>;
|
|
5
|
+
/** Собрать порт внешних доступов. */
|
|
6
|
+
export declare function buildExternalCredentialPorts(deps: PortDeps): ExternalCredentialPorts;
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
import { generateId, toExternalCredentialMeta } from '@itphx/synth-shared';
|
|
2
|
+
import { jsonbParam } from '../json-param.js';
|
|
3
|
+
let coreAsyncCache = null;
|
|
4
|
+
function loadCore() {
|
|
5
|
+
if (!coreAsyncCache) {
|
|
6
|
+
coreAsyncCache = import('@itphx/synth-core').catch((err) => {
|
|
7
|
+
coreAsyncCache = null;
|
|
8
|
+
throw err;
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
return coreAsyncCache;
|
|
12
|
+
}
|
|
13
|
+
/** ISO-строка из `timestamptz` (pg отдаёт `Date`) либо строки. */
|
|
14
|
+
function toISO(value) {
|
|
15
|
+
if (value instanceof Date)
|
|
16
|
+
return value.toISOString();
|
|
17
|
+
if (typeof value === 'string')
|
|
18
|
+
return value;
|
|
19
|
+
return String(value);
|
|
20
|
+
}
|
|
21
|
+
/** ISO-строка или `undefined` для nullable-поля. */
|
|
22
|
+
function toISOOrUndefined(value) {
|
|
23
|
+
if (value === null || value === undefined)
|
|
24
|
+
return undefined;
|
|
25
|
+
return toISO(value);
|
|
26
|
+
}
|
|
27
|
+
/** Массив строк из `jsonb` (невалидные элементы отбрасываются). */
|
|
28
|
+
function asStringArray(value) {
|
|
29
|
+
if (!Array.isArray(value))
|
|
30
|
+
return [];
|
|
31
|
+
return value.filter((item) => typeof item === 'string');
|
|
32
|
+
}
|
|
33
|
+
/** JSON-строка для `jsonb`-параметра (драйвер сериализует сам). */
|
|
34
|
+
function jsonParam(value) {
|
|
35
|
+
return jsonbParam(value) ?? 'null';
|
|
36
|
+
}
|
|
37
|
+
function rowToCredential(row) {
|
|
38
|
+
const credential = {
|
|
39
|
+
id: row.id,
|
|
40
|
+
provider: row.provider,
|
|
41
|
+
clientId: row.client_id,
|
|
42
|
+
scopes: asStringArray(row.scopes),
|
|
43
|
+
owner: {
|
|
44
|
+
kind: row.owner_kind,
|
|
45
|
+
id: row.owner_id,
|
|
46
|
+
},
|
|
47
|
+
secretEnc: row.secret_enc,
|
|
48
|
+
status: row.status,
|
|
49
|
+
createdBy: row.created_by,
|
|
50
|
+
createdAt: toISO(row.created_at),
|
|
51
|
+
};
|
|
52
|
+
if (row.connector_id !== null)
|
|
53
|
+
credential.connectorId = row.connector_id;
|
|
54
|
+
if (row.project_id !== null)
|
|
55
|
+
credential.projectId = row.project_id;
|
|
56
|
+
if (row.refresh_enc !== null)
|
|
57
|
+
credential.refreshEnc = row.refresh_enc;
|
|
58
|
+
const expiresAt = toISOOrUndefined(row.expires_at);
|
|
59
|
+
if (expiresAt !== undefined)
|
|
60
|
+
credential.expiresAt = expiresAt;
|
|
61
|
+
const revokedAt = toISOOrUndefined(row.revoked_at);
|
|
62
|
+
if (revokedAt !== undefined)
|
|
63
|
+
credential.revokedAt = revokedAt;
|
|
64
|
+
const lastUsedAt = toISOOrUndefined(row.last_used_at);
|
|
65
|
+
if (lastUsedAt !== undefined)
|
|
66
|
+
credential.lastUsedAt = lastUsedAt;
|
|
67
|
+
// `NULL` — поле не задано (паритет с файловой реализацией: `scopesGranted`
|
|
68
|
+
// отсутствует, пока провайдер не сообщил выданные scope'ы).
|
|
69
|
+
if (row.scopes_granted !== null && row.scopes_granted !== undefined) {
|
|
70
|
+
credential.scopesGranted = asStringArray(row.scopes_granted);
|
|
71
|
+
}
|
|
72
|
+
return credential;
|
|
73
|
+
}
|
|
74
|
+
/** Реализация порта `ExternalCredentialRepository` поверх SQL. */
|
|
75
|
+
class PostgresExternalCredentialRepository {
|
|
76
|
+
_deps;
|
|
77
|
+
_masterKeyPromise;
|
|
78
|
+
constructor(_deps) {
|
|
79
|
+
this._deps = _deps;
|
|
80
|
+
}
|
|
81
|
+
_db() {
|
|
82
|
+
return this._deps.connection;
|
|
83
|
+
}
|
|
84
|
+
/** Мастер-ключ core (ленивый импорт — криптография в драйвере не дублируется). */
|
|
85
|
+
async _masterKey() {
|
|
86
|
+
const core = await loadCore();
|
|
87
|
+
if (!this._masterKeyPromise) {
|
|
88
|
+
this._masterKeyPromise = core
|
|
89
|
+
.resolveMasterKey({
|
|
90
|
+
dataDir: this._deps.dataDir,
|
|
91
|
+
secretKey: this._deps.secretKey,
|
|
92
|
+
env: this._deps.env,
|
|
93
|
+
})
|
|
94
|
+
.then((result) => ({ core, key: result.key }))
|
|
95
|
+
.catch((err) => {
|
|
96
|
+
this._masterKeyPromise = undefined;
|
|
97
|
+
throw mapCryptoError(err, core);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
return this._masterKeyPromise;
|
|
101
|
+
}
|
|
102
|
+
async list(filter) {
|
|
103
|
+
const conditions = [];
|
|
104
|
+
const params = [];
|
|
105
|
+
if (filter?.owner) {
|
|
106
|
+
params.push(filter.owner.kind, filter.owner.id);
|
|
107
|
+
conditions.push(`owner_kind = $${params.length - 1} AND owner_id = $${params.length}`);
|
|
108
|
+
}
|
|
109
|
+
if (filter?.connectorId !== undefined) {
|
|
110
|
+
params.push(filter.connectorId);
|
|
111
|
+
conditions.push(`connector_id = $${params.length}`);
|
|
112
|
+
}
|
|
113
|
+
if (filter?.provider !== undefined) {
|
|
114
|
+
params.push(filter.provider);
|
|
115
|
+
conditions.push(`provider = $${params.length}`);
|
|
116
|
+
}
|
|
117
|
+
if (filter?.projectId !== undefined) {
|
|
118
|
+
params.push(filter.projectId);
|
|
119
|
+
conditions.push(`project_id = $${params.length}`);
|
|
120
|
+
}
|
|
121
|
+
if (filter?.status !== undefined) {
|
|
122
|
+
params.push(filter.status);
|
|
123
|
+
conditions.push(`status = $${params.length}`);
|
|
124
|
+
}
|
|
125
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
126
|
+
const rows = await this._db().query(`SELECT * FROM external_credentials ${where} ORDER BY created_at ASC, id ASC`, params);
|
|
127
|
+
return rows.map((row) => toExternalCredentialMeta(rowToCredential(row)));
|
|
128
|
+
}
|
|
129
|
+
async get(id) {
|
|
130
|
+
const rows = await this._db().query('SELECT * FROM external_credentials WHERE id = $1', [id]);
|
|
131
|
+
const row = rows[0];
|
|
132
|
+
return row ? toExternalCredentialMeta(rowToCredential(row)) : null;
|
|
133
|
+
}
|
|
134
|
+
async create(input) {
|
|
135
|
+
const core = await loadCore();
|
|
136
|
+
if (!input.accessToken || input.accessToken.trim() === '') {
|
|
137
|
+
throw new core.ExternalCredentialStoreError('invalid', 'access-токен обязателен');
|
|
138
|
+
}
|
|
139
|
+
if (!input.provider || input.provider.trim() === '') {
|
|
140
|
+
throw new core.ExternalCredentialStoreError('invalid', 'provider обязателен');
|
|
141
|
+
}
|
|
142
|
+
if (!input.clientId || input.clientId.trim() === '') {
|
|
143
|
+
throw new core.ExternalCredentialStoreError('invalid', 'clientId обязателен');
|
|
144
|
+
}
|
|
145
|
+
const { key } = await this._masterKey();
|
|
146
|
+
const id = input.id?.trim() || `${core.EXTERNAL_CREDENTIAL_ID_PREFIX}${generateId()}`;
|
|
147
|
+
const secretEnc = core.encryptSecret(input.accessToken, key);
|
|
148
|
+
const refreshEnc = input.refreshToken !== undefined && input.refreshToken !== ''
|
|
149
|
+
? core.encryptSecret(input.refreshToken, key)
|
|
150
|
+
: null;
|
|
151
|
+
const rows = await this._db().query(`INSERT INTO external_credentials
|
|
152
|
+
(id, provider, connector_id, client_id, scopes, owner_kind, owner_id, project_id,
|
|
153
|
+
secret_enc, refresh_enc, status, expires_at, revoked_at, created_by, created_at,
|
|
154
|
+
last_used_at, scopes_granted)
|
|
155
|
+
VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7,$8,$9,$10,'active',$11,NULL,$12,now(),NULL,$13::jsonb)
|
|
156
|
+
ON CONFLICT (id) DO NOTHING
|
|
157
|
+
RETURNING *`, [
|
|
158
|
+
id,
|
|
159
|
+
input.provider.trim(),
|
|
160
|
+
input.connectorId ?? null,
|
|
161
|
+
input.clientId.trim(),
|
|
162
|
+
jsonParam([...(input.scopes ?? [])]),
|
|
163
|
+
input.owner.kind,
|
|
164
|
+
input.owner.id,
|
|
165
|
+
input.projectId ?? null,
|
|
166
|
+
secretEnc,
|
|
167
|
+
refreshEnc,
|
|
168
|
+
input.expiresAt ?? null,
|
|
169
|
+
input.createdBy,
|
|
170
|
+
input.scopesGranted !== undefined ? jsonParam([...input.scopesGranted]) : null,
|
|
171
|
+
]);
|
|
172
|
+
const row = rows[0];
|
|
173
|
+
if (!row) {
|
|
174
|
+
// `ON CONFLICT DO NOTHING` — id уже занят.
|
|
175
|
+
throw new core.ExternalCredentialStoreError('duplicate_id', `Доступ с id ${id} уже существует`);
|
|
176
|
+
}
|
|
177
|
+
return toExternalCredentialMeta(rowToCredential(row));
|
|
178
|
+
}
|
|
179
|
+
async updateTokens(id, patch) {
|
|
180
|
+
const { core, key } = await this._masterKey();
|
|
181
|
+
const sets = [];
|
|
182
|
+
const params = [id];
|
|
183
|
+
if (patch.accessToken !== undefined) {
|
|
184
|
+
if (patch.accessToken.trim() === '') {
|
|
185
|
+
throw new core.ExternalCredentialStoreError('invalid', 'access-токен не может быть пустым');
|
|
186
|
+
}
|
|
187
|
+
params.push(core.encryptSecret(patch.accessToken, key));
|
|
188
|
+
sets.push(`secret_enc = $${params.length}`);
|
|
189
|
+
}
|
|
190
|
+
if (patch.refreshToken !== undefined && patch.refreshToken !== '') {
|
|
191
|
+
params.push(core.encryptSecret(patch.refreshToken, key));
|
|
192
|
+
sets.push(`refresh_enc = $${params.length}`);
|
|
193
|
+
}
|
|
194
|
+
if (patch.expiresAt !== undefined) {
|
|
195
|
+
params.push(patch.expiresAt);
|
|
196
|
+
sets.push(`expires_at = $${params.length}`);
|
|
197
|
+
}
|
|
198
|
+
if (patch.scopesGranted !== undefined) {
|
|
199
|
+
params.push(jsonParam([...patch.scopesGranted]));
|
|
200
|
+
sets.push(`scopes_granted = $${params.length}::jsonb`);
|
|
201
|
+
}
|
|
202
|
+
// Статус: отозванный доступ не «оживает»; иначе — по патчу или `active`
|
|
203
|
+
// при смене токена.
|
|
204
|
+
const status = patch.status ?? (patch.accessToken !== undefined ? 'active' : undefined);
|
|
205
|
+
if (status !== undefined) {
|
|
206
|
+
params.push(status);
|
|
207
|
+
sets.push(`status = CASE WHEN status = 'revoked' THEN status ELSE $${params.length}::text END`);
|
|
208
|
+
}
|
|
209
|
+
if (sets.length === 0)
|
|
210
|
+
return this.get(id);
|
|
211
|
+
const rows = await this._db().query(`UPDATE external_credentials SET ${sets.join(', ')} WHERE id = $1 RETURNING *`, params);
|
|
212
|
+
const row = rows[0];
|
|
213
|
+
return row ? toExternalCredentialMeta(rowToCredential(row)) : null;
|
|
214
|
+
}
|
|
215
|
+
async markError(id) {
|
|
216
|
+
const rows = await this._db().query(`UPDATE external_credentials
|
|
217
|
+
SET status = CASE WHEN status = 'revoked' THEN status ELSE 'error' END
|
|
218
|
+
WHERE id = $1
|
|
219
|
+
RETURNING *`, [id]);
|
|
220
|
+
const row = rows[0];
|
|
221
|
+
return row ? toExternalCredentialMeta(rowToCredential(row)) : null;
|
|
222
|
+
}
|
|
223
|
+
async revoke(id) {
|
|
224
|
+
// Идемпотентно: `revoked_at` фиксируется один раз (COALESCE).
|
|
225
|
+
const rows = await this._db().query(`UPDATE external_credentials
|
|
226
|
+
SET status = 'revoked', revoked_at = COALESCE(revoked_at, now())
|
|
227
|
+
WHERE id = $1
|
|
228
|
+
RETURNING *`, [id]);
|
|
229
|
+
const row = rows[0];
|
|
230
|
+
return row ? toExternalCredentialMeta(rowToCredential(row)) : null;
|
|
231
|
+
}
|
|
232
|
+
async touch(id) {
|
|
233
|
+
await this._db().query('UPDATE external_credentials SET last_used_at = now() WHERE id = $1', [id]);
|
|
234
|
+
}
|
|
235
|
+
async reveal(id) {
|
|
236
|
+
const { core, key } = await this._masterKey();
|
|
237
|
+
const rows = await this._db().query('SELECT secret_enc, refresh_enc FROM external_credentials WHERE id = $1', [id]);
|
|
238
|
+
const row = rows[0];
|
|
239
|
+
if (!row)
|
|
240
|
+
return null;
|
|
241
|
+
try {
|
|
242
|
+
const accessToken = core.isEncrypted(row.secret_enc)
|
|
243
|
+
? core.decryptSecret(row.secret_enc, key)
|
|
244
|
+
: row.secret_enc;
|
|
245
|
+
if (row.refresh_enc === null)
|
|
246
|
+
return { accessToken };
|
|
247
|
+
const refreshToken = core.isEncrypted(row.refresh_enc)
|
|
248
|
+
? core.decryptSecret(row.refresh_enc, key)
|
|
249
|
+
: row.refresh_enc;
|
|
250
|
+
return { accessToken, refreshToken };
|
|
251
|
+
}
|
|
252
|
+
catch (err) {
|
|
253
|
+
throw mapCryptoError(err, core);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
async listRaw() {
|
|
257
|
+
const rows = await this._db().query('SELECT * FROM external_credentials ORDER BY created_at ASC, id ASC');
|
|
258
|
+
return rows.map(rowToCredential);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Ротация мастер-ключа (ADR-105 Ф4, one-shot) — по образцу `sshKeys`.
|
|
262
|
+
*
|
|
263
|
+
* Порядок — как у `SSHKeyRepository.rotateMasterKey`: сначала preflight по
|
|
264
|
+
* всем записям (каждое зашифрованное поле расшифровывается новым либо
|
|
265
|
+
* старым ключом; иначе `preflight_failed` и **ничего не записывается**), затем
|
|
266
|
+
* перешифровка (идемпотентно: уже новые — `skipped`), plaintext-поля
|
|
267
|
+
* «апгрейдятся» новым ключом. `dryRun` — без записи.
|
|
268
|
+
*/
|
|
269
|
+
async rotateMasterKey(oldKey, newKey, opts = {}) {
|
|
270
|
+
const core = await loadCore();
|
|
271
|
+
if (oldKey.length !== core.crypto.MASTER_KEY_LENGTH || newKey.length !== core.crypto.MASTER_KEY_LENGTH) {
|
|
272
|
+
throw new core.ExternalCredentialStoreError('invalid', 'Мастер-ключ должен быть 32 байта');
|
|
273
|
+
}
|
|
274
|
+
const rows = await this._db().query('SELECT id, secret_enc, refresh_enc FROM external_credentials ORDER BY created_at ASC, id ASC');
|
|
275
|
+
const failures = new Set();
|
|
276
|
+
const planned = [];
|
|
277
|
+
for (const row of rows) {
|
|
278
|
+
const plan = planCredentialRotation(core, row.secret_enc, row.refresh_enc, oldKey, newKey);
|
|
279
|
+
if (!plan) {
|
|
280
|
+
failures.add(row.id);
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
planned.push({ id: row.id, ...plan });
|
|
284
|
+
}
|
|
285
|
+
if (failures.size > 0) {
|
|
286
|
+
throw new core.ExternalCredentialStoreError('preflight_failed', `Не удалось расшифровать внешние доступы (ни старым, ни новым ключом): ${[...failures].sort().join(', ')}`);
|
|
287
|
+
}
|
|
288
|
+
let rotated = 0;
|
|
289
|
+
let upgraded = 0;
|
|
290
|
+
let skipped = 0;
|
|
291
|
+
const ids = [];
|
|
292
|
+
for (const item of planned) {
|
|
293
|
+
if (item.kind === 'rotated') {
|
|
294
|
+
rotated += 1;
|
|
295
|
+
ids.push(item.id);
|
|
296
|
+
}
|
|
297
|
+
else if (item.kind === 'upgraded') {
|
|
298
|
+
upgraded += 1;
|
|
299
|
+
ids.push(item.id);
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
skipped += 1;
|
|
303
|
+
}
|
|
304
|
+
if (item.kind !== 'skipped' && !opts.dryRun) {
|
|
305
|
+
await this._db().query('UPDATE external_credentials SET secret_enc = $2, refresh_enc = $3 WHERE id = $1', [item.id, item.secretEnc, item.refreshEnc]);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return { total: rows.length, rotated, upgraded, skipped, ids };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Планирует ротацию полей записи доступа (plaintext → upgraded, старый шифр →
|
|
313
|
+
* rotated). `null` — поле не расшифровывается ни старым, ни новым ключом.
|
|
314
|
+
*/
|
|
315
|
+
function planCredentialRotation(core, secretEnc, refreshEnc, oldKey, newKey) {
|
|
316
|
+
let kind = 'skipped';
|
|
317
|
+
const rotateToken = (token) => {
|
|
318
|
+
if (!core.isEncrypted(token)) {
|
|
319
|
+
kind = 'upgraded';
|
|
320
|
+
return core.encryptSecret(token, newKey);
|
|
321
|
+
}
|
|
322
|
+
try {
|
|
323
|
+
core.decryptSecret(token, newKey);
|
|
324
|
+
return token;
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
// не расшифровывается новым — пробуем старым
|
|
328
|
+
}
|
|
329
|
+
try {
|
|
330
|
+
const plaintext = core.decryptSecret(token, oldKey);
|
|
331
|
+
kind = 'rotated';
|
|
332
|
+
return core.encryptSecret(plaintext, newKey);
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
const nextSecret = rotateToken(secretEnc);
|
|
339
|
+
if (nextSecret === null)
|
|
340
|
+
return null;
|
|
341
|
+
let nextRefresh = refreshEnc;
|
|
342
|
+
if (refreshEnc !== null) {
|
|
343
|
+
nextRefresh = rotateToken(refreshEnc);
|
|
344
|
+
if (nextRefresh === null)
|
|
345
|
+
return null;
|
|
346
|
+
}
|
|
347
|
+
return { secretEnc: nextSecret, refreshEnc: nextRefresh, kind };
|
|
348
|
+
}
|
|
349
|
+
/** Ошибка криптослоя → типизированная ошибка хранилища (без утечки секрета). */
|
|
350
|
+
function mapCryptoError(err, core) {
|
|
351
|
+
if (err instanceof core.ExternalCredentialStoreError)
|
|
352
|
+
return err;
|
|
353
|
+
if (err instanceof core.CryptoError) {
|
|
354
|
+
return new core.ExternalCredentialStoreError(err.code === 'encryption_unavailable' ? 'encryption_unavailable' : 'decrypt_failed', err.message);
|
|
355
|
+
}
|
|
356
|
+
return new core.ExternalCredentialStoreError('decrypt_failed', 'Не удалось расшифровать секрет');
|
|
357
|
+
}
|
|
358
|
+
/** Собрать порт внешних доступов. */
|
|
359
|
+
export function buildExternalCredentialPorts(deps) {
|
|
360
|
+
return {
|
|
361
|
+
externalCredentials: new PostgresExternalCredentialRepository(deps),
|
|
362
|
+
};
|
|
363
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PG-реализация порта **legacy-пайплайнов** (ADR-051/ADR-100, ADR-116, ADR-097):
|
|
3
|
+
* определения автомата и экземпляры прогонов.
|
|
4
|
+
*
|
|
5
|
+
* Не путать с `ports/pipelines.ts` (ADR-101 — движок пайплайнов проекта:
|
|
6
|
+
* `pipeline_specs`/`pipeline_versions`/`pipeline_runs`/`pipeline_run_events`).
|
|
7
|
+
* Здесь — реестр **инстанса** «декларация + учёт» (ADR-051/ADR-100), который
|
|
8
|
+
* ставится пакетами расширений.
|
|
9
|
+
*
|
|
10
|
+
* Таблицы (миграция `025_packs_pipelines`): `pipeline_definitions`,
|
|
11
|
+
* `pipeline_instances`.
|
|
12
|
+
*
|
|
13
|
+
* Семантика повторяет файловую реализацию core (`FilePipelineStore`) и
|
|
14
|
+
* in-memory (`MemoryPipelineRepository`):
|
|
15
|
+
* - upsert по `id`: `created_at` не перезаписывается, `updated_at` монотонно
|
|
16
|
+
* не убывает (в SQL — `GREATEST` + сдвиг 1 мс, паритет с
|
|
17
|
+
* `record-timestamps.ts` core);
|
|
18
|
+
* - `listDefinitions` — детерминированный порядок (`ORDER BY id ASC`);
|
|
19
|
+
* - `deleteDefinition` — `true`, если запись была удалена; экземпляры **не**
|
|
20
|
+
* трогаются (прогон самодостаточен, паритет с файловой реализацией);
|
|
21
|
+
* - `listInstances` — «свежие первыми» (`created_at` убыв., тайбрейкер `id`),
|
|
22
|
+
* фильтры `pipelineId`/`status` — по «И», `limit` — дефолт 100 / потолок 1000.
|
|
23
|
+
*
|
|
24
|
+
* Драйвер не тянет core рантаймом (только `import type`), поэтому потолок
|
|
25
|
+
* выборки повторён здесь локально — точная реплика
|
|
26
|
+
* `resolvePipelineInstanceLimit` (`storage/ports/pipeline-repository.ts` core);
|
|
27
|
+
* паритет значений зафиксирован контрактным suite (константы
|
|
28
|
+
* `PIPELINE_INSTANCE_DEFAULT_LIMIT`/`PIPELINE_INSTANCE_MAX_LIMIT` проверяются
|
|
29
|
+
* там же, а `limit`-сценарии — на этой реализации).
|
|
30
|
+
*/
|
|
31
|
+
import type { PipelineDefinitionRecord, PipelineInstanceFilter, PipelineInstanceRecord, PipelineRepository, StorageContext } from '@itphx/synth-core';
|
|
32
|
+
import type { PortDeps } from './deps.js';
|
|
33
|
+
/** Часть `StorageContext`, которой владеет группа «legacy-pipelines». */
|
|
34
|
+
export type LegacyPipelinePorts = Pick<StorageContext, 'pipelines'>;
|
|
35
|
+
/**
|
|
36
|
+
* ADR-051/ADR-100: реестр определений и экземпляров пайплайнов инстанса.
|
|
37
|
+
*/
|
|
38
|
+
export declare class PgPipelineRepository implements PipelineRepository {
|
|
39
|
+
private readonly _deps;
|
|
40
|
+
constructor(_deps: PortDeps);
|
|
41
|
+
saveDefinition(def: PipelineDefinitionRecord): Promise<void>;
|
|
42
|
+
getDefinition(id: string): Promise<PipelineDefinitionRecord | null>;
|
|
43
|
+
listDefinitions(): Promise<PipelineDefinitionRecord[]>;
|
|
44
|
+
deleteDefinition(id: string): Promise<boolean>;
|
|
45
|
+
saveInstance(instance: PipelineInstanceRecord): Promise<void>;
|
|
46
|
+
getInstance(id: string): Promise<PipelineInstanceRecord | null>;
|
|
47
|
+
listInstances(filter?: PipelineInstanceFilter): Promise<PipelineInstanceRecord[]>;
|
|
48
|
+
}
|
|
49
|
+
/** Собрать порт legacy-пайплайнов (ADR-051/ADR-100). */
|
|
50
|
+
export declare function buildLegacyPipelinePorts(deps: PortDeps): LegacyPipelinePorts;
|