@itphx/synth-storage-postgres 0.0.0-stage → 0.11.3

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.
Files changed (72) hide show
  1. package/LICENSE +18 -0
  2. package/LICENSE.ru.md +31 -0
  3. package/dist/errors.d.ts +71 -0
  4. package/dist/errors.js +126 -0
  5. package/dist/index.d.ts +37 -0
  6. package/dist/index.js +34 -0
  7. package/dist/json-param.d.ts +14 -0
  8. package/dist/json-param.js +22 -0
  9. package/dist/locks.d.ts +104 -0
  10. package/dist/locks.js +201 -0
  11. package/dist/migrate.d.ts +58 -0
  12. package/dist/migrate.js +125 -0
  13. package/dist/migrations/001-init.d.ts +15 -0
  14. package/dist/migrations/001-init.js +457 -0
  15. package/dist/migrations/002-egress-audit.d.ts +12 -0
  16. package/dist/migrations/002-egress-audit.js +52 -0
  17. package/dist/migrations/003-analytics-rollups.d.ts +12 -0
  18. package/dist/migrations/003-analytics-rollups.js +21 -0
  19. package/dist/migrations/index.d.ts +23 -0
  20. package/dist/migrations/index.js +23 -0
  21. package/dist/pool.d.ts +178 -0
  22. package/dist/pool.js +382 -0
  23. package/dist/ports/analytics.d.ts +26 -0
  24. package/dist/ports/analytics.js +243 -0
  25. package/dist/ports/audit.d.ts +15 -0
  26. package/dist/ports/audit.js +189 -0
  27. package/dist/ports/content.d.ts +41 -0
  28. package/dist/ports/content.js +1539 -0
  29. package/dist/ports/core-sync.d.ts +31 -0
  30. package/dist/ports/core-sync.js +34 -0
  31. package/dist/ports/deps.d.ts +63 -0
  32. package/dist/ports/deps.js +19 -0
  33. package/dist/ports/events-bindings.d.ts +77 -0
  34. package/dist/ports/events-bindings.js +356 -0
  35. package/dist/ports/events-core.d.ts +35 -0
  36. package/dist/ports/events-core.js +71 -0
  37. package/dist/ports/events-journal.d.ts +68 -0
  38. package/dist/ports/events-journal.js +211 -0
  39. package/dist/ports/events-scheduler.d.ts +49 -0
  40. package/dist/ports/events-scheduler.js +231 -0
  41. package/dist/ports/events-webhooks.d.ts +64 -0
  42. package/dist/ports/events-webhooks.js +268 -0
  43. package/dist/ports/events.d.ts +20 -0
  44. package/dist/ports/events.js +27 -0
  45. package/dist/ports/principals-defaults.d.ts +21 -0
  46. package/dist/ports/principals-defaults.js +68 -0
  47. package/dist/ports/principals-documents.d.ts +23 -0
  48. package/dist/ports/principals-documents.js +38 -0
  49. package/dist/ports/principals-profiles.d.ts +21 -0
  50. package/dist/ports/principals-profiles.js +263 -0
  51. package/dist/ports/principals-projects.d.ts +19 -0
  52. package/dist/ports/principals-projects.js +158 -0
  53. package/dist/ports/principals-settings.d.ts +25 -0
  54. package/dist/ports/principals-settings.js +275 -0
  55. package/dist/ports/principals-shared.d.ts +33 -0
  56. package/dist/ports/principals-shared.js +44 -0
  57. package/dist/ports/principals.d.ts +27 -0
  58. package/dist/ports/principals.js +39 -0
  59. package/dist/ports/sessions-mapping.d.ts +237 -0
  60. package/dist/ports/sessions-mapping.js +405 -0
  61. package/dist/ports/sessions.d.ts +133 -0
  62. package/dist/ports/sessions.js +502 -0
  63. package/dist/ports/stub.d.ts +14 -0
  64. package/dist/ports/stub.js +32 -0
  65. package/dist/postgres-storage.d.ts +59 -0
  66. package/dist/postgres-storage.js +111 -0
  67. package/dist/schema.d.ts +13 -0
  68. package/dist/schema.js +22 -0
  69. package/dist/storage-context.d.ts +51 -0
  70. package/dist/storage-context.js +130 -0
  71. package/package.json +40 -3
  72. package/README.md +0 -3
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Резолвинг синхронных данных/хелперов core для sync-геттеров портов
3
+ * (PROP-032, волна 3b).
4
+ *
5
+ * `@itphx/synth-core` — `peerDependencies` драйвера и подключается только ленивым
6
+ * `import()` (цикл core ↔ драйвер: core динамически грузит драйвер по
7
+ * `storage.backend === 'postgres'`), поэтому статический рантайм-импорт core здесь
8
+ * недопустим. При штатной сборке через core значения инъектируются в конфиг
9
+ * драйвера (`packages/core/src/storage/storage-context.ts`); при прямом вызове
10
+ * `createPostgresStorage` (контрактный suite, внешний потребитель) тот же набор
11
+ * собирается здесь — sync-геттеры иначе не получили бы доступ к данным core.
12
+ */
13
+ import type { CoreSyncDeps } from './deps.js';
14
+ /**
15
+ * Каталог-заглушка пользовательских словарей: реальный override живёт в БД
16
+ * (`settings`), файловый каталог пользователя намеренно пуст.
17
+ */
18
+ export declare const POSTGRES_EMPTY_USER_DICTIONARIES_SUBDIR = "storage-postgres/no-user-dictionaries";
19
+ /** Параметры сборки sync-данных core. */
20
+ export interface CoreSyncResolveOptions {
21
+ dataDir: string;
22
+ /** Каталог системных словарей (по умолчанию — `dictionaries/` пакета core). */
23
+ systemDictionariesDir?: string;
24
+ }
25
+ /**
26
+ * Собрать `CoreSyncDeps` ленивым `import('@itphx/synth-core')`.
27
+ *
28
+ * Используется только когда core не передал значения явно (прямой вызов фабрики);
29
+ * ошибки загрузки core не глушатся — без них sync-геттеры вернули бы неполные данные.
30
+ */
31
+ export declare function resolveCoreSyncDeps(opts: CoreSyncResolveOptions): Promise<CoreSyncDeps>;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Резолвинг синхронных данных/хелперов core для sync-геттеров портов
3
+ * (PROP-032, волна 3b).
4
+ *
5
+ * `@itphx/synth-core` — `peerDependencies` драйвера и подключается только ленивым
6
+ * `import()` (цикл core ↔ драйвер: core динамически грузит драйвер по
7
+ * `storage.backend === 'postgres'`), поэтому статический рантайм-импорт core здесь
8
+ * недопустим. При штатной сборке через core значения инъектируются в конфиг
9
+ * драйвера (`packages/core/src/storage/storage-context.ts`); при прямом вызове
10
+ * `createPostgresStorage` (контрактный suite, внешний потребитель) тот же набор
11
+ * собирается здесь — sync-геттеры иначе не получили бы доступ к данным core.
12
+ */
13
+ import { join } from 'node:path';
14
+ /**
15
+ * Каталог-заглушка пользовательских словарей: реальный override живёт в БД
16
+ * (`settings`), файловый каталог пользователя намеренно пуст.
17
+ */
18
+ export const POSTGRES_EMPTY_USER_DICTIONARIES_SUBDIR = 'storage-postgres/no-user-dictionaries';
19
+ /**
20
+ * Собрать `CoreSyncDeps` ленивым `import('@itphx/synth-core')`.
21
+ *
22
+ * Используется только когда core не передал значения явно (прямой вызов фабрики);
23
+ * ошибки загрузки core не глушатся — без них sync-геттеры вернули бы неполные данные.
24
+ */
25
+ export async function resolveCoreSyncDeps(opts) {
26
+ const core = await import('@itphx/synth-core');
27
+ const secretPatterns = core.DEFAULT_PATTERNS.map((pattern) => ({
28
+ type: pattern.type,
29
+ regex: typeof pattern.regex === 'string' ? pattern.regex : pattern.regex.source,
30
+ }));
31
+ const protectedPathsBase = core.loadProtectedPaths({ overridePath: '' });
32
+ const systemDictionaries = new core.DictionaryStore(join(opts.dataDir, POSTGRES_EMPTY_USER_DICTIONARIES_SUBDIR), opts.systemDictionariesDir);
33
+ return { secretPatterns, protectedPathsBase, systemDictionaries };
34
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Общие зависимости сборки доменных портов PostgreSQL-драйвера
3
+ * (PROP-032, волна 3b).
4
+ *
5
+ * Один объект `PortDeps` передаётся во все четыре файла-группы
6
+ * (`sessions`/`principals`/`events`/`content`), чтобы каждая группа брала только
7
+ * нужное ей и не зависела от остальных. Поля описывают ровно то, что реально
8
+ * требуется портам при реализации поверх SQL:
9
+ * - `connection` — живой пул/примитивы запросов (`query`/`withTransaction`/
10
+ * `withAdvisoryLock`) из `pool.ts`, удерживается в `StorageContext`;
11
+ * - `dataDir` — базовый каталог инстанса (файловые нужды, пути по умолчанию);
12
+ * - `secretKey`/`env` — шифрование секретов at-rest (`sshKeys`/`webhooks`);
13
+ * - `systemDictionariesDir`/`contextUserDataDir` — файловые пути словарей и
14
+ * контента (для групп, которые совмещают SQL-хранение с файловым контентом).
15
+ *
16
+ * Никаких модульных синглтонов: `deps` собирается на каждый
17
+ * `buildPostgresStorageContext` (герметичность тестов и переключаемых схем).
18
+ */
19
+ import type { DictionaryRepository, ProtectedPathsPolicy, SecretPattern } from '@itphx/synth-core';
20
+ import type { PostgresConnection } from '../pool.js';
21
+ /**
22
+ * Синхронные данные/хелперы `@itphx/synth-core`, нужные sync-геттерам портов
23
+ * (`secretPatterns`/`protectedPaths`/`dictionaries`).
24
+ *
25
+ * Sync-геттеры вызываются на горячем пути (сборка промпта, детекция секретов,
26
+ * маршрутизация) и не могут ждать I/O или ленивый `import()`. Core **инъектирует**
27
+ * их в конфиг драйвера (`packages/core/src/storage/storage-context.ts`) —
28
+ * это заменяет прежний обход `exports`-карты core; при прямом вызове
29
+ * `createPostgresStorage` (контрактный suite, внешний потребитель) драйвер
30
+ * собирает тот же набор ленивым `import('@itphx/synth-core')` (`core-sync.ts`).
31
+ */
32
+ export interface CoreSyncDeps {
33
+ /** Дефолтные паттерны детекции секретов в сериализуемой форме (core `DEFAULT_PATTERNS`). */
34
+ secretPatterns: SecretPattern[];
35
+ /** Системный base политики защищённых путей (core `loadProtectedPaths`, без override). */
36
+ protectedPathsBase: ProtectedPathsPolicy;
37
+ /** Системный источник словарей (core `DictionaryStore`, реализация `DictionaryRepository`). */
38
+ systemDictionaries: DictionaryRepository;
39
+ }
40
+ /** Общие зависимости портов: соединение + пути/ключи, не привязанные к порту. */
41
+ export interface PortDeps {
42
+ /** Живое соединение драйвера (пул + примитивы запросов/транзакций/локов). */
43
+ connection: PostgresConnection;
44
+ /** Базовый каталог данных инстанса. */
45
+ dataDir: string;
46
+ /** ADR-076: мастер-ключ секретов at-rest (env > config > файл в dataDir). */
47
+ secretKey?: string;
48
+ /** Окружение процесса (резолвинг секретов/путей). */
49
+ env?: NodeJS.ProcessEnv;
50
+ /** Каталог системных словарей (по умолчанию — `dictionaries/` пакета core). */
51
+ systemDictionariesDir?: string;
52
+ /** Корень пользовательских промптов/ролей (по умолчанию `{dataDir}/context`). */
53
+ contextUserDataDir?: string;
54
+ /** ADR-097/PROP-032: инъекция sync-данных core (см. `CoreSyncDeps`). */
55
+ coreSync: CoreSyncDeps;
56
+ /**
57
+ * Регистрация фоновой задачи сборки, которую владелец контекста обязан
58
+ * дождаться в `close()` **до** закрытия пула. Нужна для fire-and-forget
59
+ * прогрева синхронных кэшей `content`: без учёта warm-запросы попадают в уже
60
+ * закрытый пул и дают ложные предупреждения «пул недоступен».
61
+ */
62
+ trackBackground?: (task: Promise<unknown>) => void;
63
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Общие зависимости сборки доменных портов PostgreSQL-драйвера
3
+ * (PROP-032, волна 3b).
4
+ *
5
+ * Один объект `PortDeps` передаётся во все четыре файла-группы
6
+ * (`sessions`/`principals`/`events`/`content`), чтобы каждая группа брала только
7
+ * нужное ей и не зависела от остальных. Поля описывают ровно то, что реально
8
+ * требуется портам при реализации поверх SQL:
9
+ * - `connection` — живой пул/примитивы запросов (`query`/`withTransaction`/
10
+ * `withAdvisoryLock`) из `pool.ts`, удерживается в `StorageContext`;
11
+ * - `dataDir` — базовый каталог инстанса (файловые нужды, пути по умолчанию);
12
+ * - `secretKey`/`env` — шифрование секретов at-rest (`sshKeys`/`webhooks`);
13
+ * - `systemDictionariesDir`/`contextUserDataDir` — файловые пути словарей и
14
+ * контента (для групп, которые совмещают SQL-хранение с файловым контентом).
15
+ *
16
+ * Никаких модульных синглтонов: `deps` собирается на каждый
17
+ * `buildPostgresStorageContext` (герметичность тестов и переключаемых схем).
18
+ */
19
+ export {};
@@ -0,0 +1,77 @@
1
+ /**
2
+ * PG-реализация портов привязок, правил маршрутизации и API-ключей привязок
3
+ * (PROP-032, волна 3b): `eventBindings`/`eventRoutes`/`eventApiKeys`.
4
+ *
5
+ * Семантика повторяет файловые реализации core (`EventBindingStore`,
6
+ * `RouteRuleStore`, `EventApiKeyStore`): upsert по `id`, приоритет `threadKey`
7
+ * над `chatKey`, глобальная регистронезависимая уникальность `label`, резолв
8
+ * секрета по sha256-хешу при отсутствии plaintext at-rest.
9
+ */
10
+ import { type EventBinding, type EventBindingApiKey, type EventBindingApiKeyCreated, type EventRouteRule } from '@itphx/synth-shared';
11
+ import type { StorageContext, CreateEventApiKeyInput, UpdateEventApiKeyPatch, UpsertEventBindingInput, UpsertRouteRuleInput, EventApiKeyResolution, EventApiKeyRecord } from '@itphx/synth-core';
12
+ import type { PortDeps } from './deps.js';
13
+ /** Часть `StorageContext`, которой владеет под-группа привязок/ключей. */
14
+ export type EventBindingPorts = Pick<StorageContext, 'eventBindings' | 'eventRoutes' | 'eventApiKeys'>;
15
+ /** ADR-089: реестр устойчивых привязок поверх `event_bindings`. */
16
+ export declare class PgEventBindingRepository {
17
+ private readonly _deps;
18
+ constructor(_deps: PortDeps);
19
+ list(): Promise<EventBinding[]>;
20
+ get(id: string): Promise<EventBinding | null>;
21
+ /** `threadKey` приоритетнее `chatKey`; матч по `source` + ключу. */
22
+ findByKey(input: {
23
+ source: string;
24
+ chatKey?: string;
25
+ threadKey?: string;
26
+ }): Promise<EventBinding | null>;
27
+ /** Создаёт или заменяет биндинг по `id` (id отсутствует → `bnd_<uuid>`). */
28
+ upsert(input: UpsertEventBindingInput): Promise<EventBinding>;
29
+ remove(id: string): Promise<boolean>;
30
+ }
31
+ /** ADR-089: реестр правил маршрутизации поверх `event_routes`. */
32
+ export declare class PgEventRouteRepository {
33
+ private readonly _deps;
34
+ constructor(_deps: PortDeps);
35
+ list(): Promise<EventRouteRule[]>;
36
+ listEnabled(): Promise<EventRouteRule[]>;
37
+ get(id: string): Promise<EventRouteRule | null>;
38
+ /** Создаёт или заменяет правило по `id` (id отсутствует → `rule_<uuid>`). */
39
+ upsert(input: UpsertRouteRuleInput): Promise<EventRouteRule>;
40
+ remove(id: string): Promise<boolean>;
41
+ }
42
+ /**
43
+ * ADR-089/ADR-052: реестр API-ключей привязок поверх `event_api_keys`.
44
+ *
45
+ * Plaintext-секрет не сохраняется — только `secret_hash` (sha256 hex); секрет
46
+ * отдаётся единственный раз в `create`. Метка уникальна глобально
47
+ * (регистронезависимо, индекс `lower(label)`) — конфликт превращается в
48
+ * доменную `EventApiKeyConflictError` (роуты маппят в 409).
49
+ */
50
+ export declare class PgEventApiKeyRepository {
51
+ private readonly _deps;
52
+ constructor(_deps: PortDeps);
53
+ listByBinding(bindingId: string): Promise<EventBindingApiKey[]>;
54
+ get(bindingId: string, keyId: string): Promise<EventBindingApiKey | null>;
55
+ /** Полные записи (включая `secret_hash`) — только для переноса между backend'ами. */
56
+ exportAll(): Promise<EventApiKeyRecord[]>;
57
+ /**
58
+ * Импорт готовой записи как есть (PROP-032): `id`/`bindingId`/`prefix`/
59
+ * `secret_hash` сохраняются. `ON CONFLICT DO NOTHING` — идемпотентно; при
60
+ * конфликте возвращается существующая строка (по `id`, метке или хешу).
61
+ */
62
+ importExisting(record: EventApiKeyRecord): Promise<EventBindingApiKey>;
63
+ create(input: CreateEventApiKeyInput): Promise<EventBindingApiKeyCreated>;
64
+ /** Патч: `undefined` — не трогать, `null` — сбросить поле. */
65
+ update(bindingId: string, keyId: string, patch: UpdateEventApiKeyPatch): Promise<EventBindingApiKey | null>;
66
+ remove(bindingId: string, keyId: string): Promise<boolean>;
67
+ /** Каскадное удаление ключей привязки; возвращает число удалённых. */
68
+ removeByBinding(bindingId: string): Promise<number>;
69
+ /** Мягкий отзыв: `revokedAt = now()` (идемпотентно); `false`, если ключа нет. */
70
+ revoke(bindingId: string, keyId: string): Promise<boolean>;
71
+ /** Резолв секрета по sha256-хешу; revoked/expired/unknown → `null`. */
72
+ resolveBySecret(rawSecret: string): Promise<EventApiKeyResolution | null>;
73
+ /** Best-effort отметка использования (`lastUsedAt`). */
74
+ touch(id: string): Promise<void>;
75
+ }
76
+ /** Собрать под-группу портов привязок/правил/ключей. */
77
+ export declare function buildEventBindingPorts(deps: PortDeps): EventBindingPorts;
@@ -0,0 +1,356 @@
1
+ /**
2
+ * PG-реализация портов привязок, правил маршрутизации и API-ключей привязок
3
+ * (PROP-032, волна 3b): `eventBindings`/`eventRoutes`/`eventApiKeys`.
4
+ *
5
+ * Семантика повторяет файловые реализации core (`EventBindingStore`,
6
+ * `RouteRuleStore`, `EventApiKeyStore`): upsert по `id`, приоритет `threadKey`
7
+ * над `chatKey`, глобальная регистронезависимая уникальность `label`, резолв
8
+ * секрета по sha256-хешу при отсутствии plaintext at-rest.
9
+ */
10
+ import { createHash, randomBytes } from 'node:crypto';
11
+ import { generateId, } from '@itphx/synth-shared';
12
+ import { jsonbParam } from '../json-param.js';
13
+ import { compact, isUniqueViolation, loadCore, SECRET_PREFIX_VISIBLE, toIso, toIsoRequired, } from './events-core.js';
14
+ function toBinding(row) {
15
+ return compact({
16
+ id: row.id,
17
+ source: row.source,
18
+ chatKey: row.chat_key ?? undefined,
19
+ threadKey: row.thread_key ?? undefined,
20
+ sessionId: row.session_id ?? undefined,
21
+ mode: row.mode,
22
+ agentTemplate: row.agent_template ?? undefined,
23
+ project: row.project ?? undefined,
24
+ });
25
+ }
26
+ /** ADR-089: реестр устойчивых привязок поверх `event_bindings`. */
27
+ export class PgEventBindingRepository {
28
+ _deps;
29
+ constructor(_deps) {
30
+ this._deps = _deps;
31
+ }
32
+ async list() {
33
+ const rows = await this._deps.connection.query('SELECT * FROM event_bindings ORDER BY id');
34
+ return rows.map(toBinding);
35
+ }
36
+ async get(id) {
37
+ const rows = await this._deps.connection.query('SELECT * FROM event_bindings WHERE id = $1 LIMIT 1', [id]);
38
+ return rows[0] ? toBinding(rows[0]) : null;
39
+ }
40
+ /** `threadKey` приоритетнее `chatKey`; матч по `source` + ключу. */
41
+ async findByKey(input) {
42
+ if (input.threadKey) {
43
+ const rows = await this._deps.connection.query('SELECT * FROM event_bindings WHERE source = $1 AND thread_key = $2 LIMIT 1', [input.source, input.threadKey]);
44
+ if (rows[0])
45
+ return toBinding(rows[0]);
46
+ }
47
+ if (input.chatKey) {
48
+ const rows = await this._deps.connection.query('SELECT * FROM event_bindings WHERE source = $1 AND chat_key = $2 LIMIT 1', [input.source, input.chatKey]);
49
+ if (rows[0])
50
+ return toBinding(rows[0]);
51
+ }
52
+ return null;
53
+ }
54
+ /** Создаёт или заменяет биндинг по `id` (id отсутствует → `bnd_<uuid>`). */
55
+ async upsert(input) {
56
+ const id = input.id ?? `bnd_${generateId()}`;
57
+ const rows = await this._deps.connection.query(`INSERT INTO event_bindings
58
+ (id, source, chat_key, thread_key, session_id, mode, agent_template, project)
59
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
60
+ ON CONFLICT (id) DO UPDATE SET
61
+ source = EXCLUDED.source,
62
+ chat_key = EXCLUDED.chat_key,
63
+ thread_key = EXCLUDED.thread_key,
64
+ session_id = EXCLUDED.session_id,
65
+ mode = EXCLUDED.mode,
66
+ agent_template = EXCLUDED.agent_template,
67
+ project = EXCLUDED.project
68
+ RETURNING *`, [
69
+ id,
70
+ input.source,
71
+ input.chatKey ?? null,
72
+ input.threadKey ?? null,
73
+ input.sessionId ?? null,
74
+ input.mode,
75
+ input.agentTemplate ?? null,
76
+ input.project ?? null,
77
+ ]);
78
+ return toBinding(rows[0]);
79
+ }
80
+ async remove(id) {
81
+ const rows = await this._deps.connection.query('DELETE FROM event_bindings WHERE id = $1 RETURNING id', [id]);
82
+ return rows.length > 0;
83
+ }
84
+ }
85
+ function toRoute(row) {
86
+ return compact({
87
+ id: row.id,
88
+ name: row.name ?? undefined,
89
+ priority: row.priority,
90
+ enabled: row.enabled,
91
+ match: (row.match ?? {}),
92
+ target: (row.target ?? { mode: 'ephemeral' }),
93
+ });
94
+ }
95
+ /** ADR-089: реестр правил маршрутизации поверх `event_routes`. */
96
+ export class PgEventRouteRepository {
97
+ _deps;
98
+ constructor(_deps) {
99
+ this._deps = _deps;
100
+ }
101
+ async list() {
102
+ const rows = await this._deps.connection.query('SELECT * FROM event_routes ORDER BY priority DESC, id');
103
+ return rows.map(toRoute);
104
+ }
105
+ async listEnabled() {
106
+ const rows = await this._deps.connection.query('SELECT * FROM event_routes WHERE enabled = true ORDER BY priority DESC, id');
107
+ return rows.map(toRoute);
108
+ }
109
+ async get(id) {
110
+ const rows = await this._deps.connection.query('SELECT * FROM event_routes WHERE id = $1 LIMIT 1', [id]);
111
+ return rows[0] ? toRoute(rows[0]) : null;
112
+ }
113
+ /** Создаёт или заменяет правило по `id` (id отсутствует → `rule_<uuid>`). */
114
+ async upsert(input) {
115
+ const id = input.id ?? `rule_${generateId()}`;
116
+ const rows = await this._deps.connection.query(`INSERT INTO event_routes (id, name, priority, enabled, match, target)
117
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6::jsonb)
118
+ ON CONFLICT (id) DO UPDATE SET
119
+ name = EXCLUDED.name,
120
+ priority = EXCLUDED.priority,
121
+ enabled = EXCLUDED.enabled,
122
+ match = EXCLUDED.match,
123
+ target = EXCLUDED.target
124
+ RETURNING *`, [
125
+ id,
126
+ input.name ?? null,
127
+ input.priority,
128
+ input.enabled,
129
+ jsonbParam(input.match ?? {}),
130
+ jsonbParam(input.target ?? {}),
131
+ ]);
132
+ return toRoute(rows[0]);
133
+ }
134
+ async remove(id) {
135
+ const rows = await this._deps.connection.query('DELETE FROM event_routes WHERE id = $1 RETURNING id', [id]);
136
+ return rows.length > 0;
137
+ }
138
+ }
139
+ function hashSecret(secret) {
140
+ return createHash('sha256').update(secret).digest('hex');
141
+ }
142
+ function toPublicKey(row) {
143
+ return compact({
144
+ id: row.id,
145
+ bindingId: row.binding_id,
146
+ label: row.label,
147
+ description: row.description ?? undefined,
148
+ rateLimitPerMinute: row.rate_limit_per_minute ?? undefined,
149
+ createdBy: row.created_by,
150
+ createdAt: toIsoRequired(row.created_at),
151
+ lastUsedAt: toIso(row.last_used_at),
152
+ prefix: row.prefix,
153
+ expiresAt: toIso(row.expires_at),
154
+ revokedAt: toIso(row.revoked_at),
155
+ });
156
+ }
157
+ /** Внутренняя запись для переноса между backend'ами: публичные поля + sha256-хеш. */
158
+ function toRecord(row) {
159
+ return { ...toPublicKey(row), hash: row.secret_hash };
160
+ }
161
+ /**
162
+ * ADR-089/ADR-052: реестр API-ключей привязок поверх `event_api_keys`.
163
+ *
164
+ * Plaintext-секрет не сохраняется — только `secret_hash` (sha256 hex); секрет
165
+ * отдаётся единственный раз в `create`. Метка уникальна глобально
166
+ * (регистронезависимо, индекс `lower(label)`) — конфликт превращается в
167
+ * доменную `EventApiKeyConflictError` (роуты маппят в 409).
168
+ */
169
+ export class PgEventApiKeyRepository {
170
+ _deps;
171
+ constructor(_deps) {
172
+ this._deps = _deps;
173
+ }
174
+ async listByBinding(bindingId) {
175
+ const rows = await this._deps.connection.query('SELECT * FROM event_api_keys WHERE binding_id = $1 ORDER BY created_at, id', [bindingId]);
176
+ return rows.map(toPublicKey);
177
+ }
178
+ async get(bindingId, keyId) {
179
+ const rows = await this._deps.connection.query('SELECT * FROM event_api_keys WHERE id = $1 AND binding_id = $2 LIMIT 1', [keyId, bindingId]);
180
+ return rows[0] ? toPublicKey(rows[0]) : null;
181
+ }
182
+ /** Полные записи (включая `secret_hash`) — только для переноса между backend'ами. */
183
+ async exportAll() {
184
+ const rows = await this._deps.connection.query('SELECT * FROM event_api_keys ORDER BY created_at, id');
185
+ return rows.map(toRecord);
186
+ }
187
+ /**
188
+ * Импорт готовой записи как есть (PROP-032): `id`/`bindingId`/`prefix`/
189
+ * `secret_hash` сохраняются. `ON CONFLICT DO NOTHING` — идемпотентно; при
190
+ * конфликте возвращается существующая строка (по `id`, метке или хешу).
191
+ */
192
+ async importExisting(record) {
193
+ const label = record.label?.trim() ?? '';
194
+ if (!record.id)
195
+ throw new Error('id обязателен');
196
+ if (!record.bindingId)
197
+ throw new Error('bindingId обязателен');
198
+ if (!label)
199
+ throw new Error('label обязателен');
200
+ if (!record.hash)
201
+ throw new Error('hash обязателен');
202
+ const inserted = await this._deps.connection.query(`INSERT INTO event_api_keys
203
+ (id, binding_id, label, description, secret_hash, prefix, rate_limit_per_minute,
204
+ created_by, created_at, last_used_at, expires_at, revoked_at)
205
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
206
+ ON CONFLICT DO NOTHING
207
+ RETURNING *`, [
208
+ record.id,
209
+ record.bindingId,
210
+ label,
211
+ record.description ?? null,
212
+ record.hash,
213
+ record.prefix,
214
+ record.rateLimitPerMinute ?? null,
215
+ record.createdBy,
216
+ record.createdAt,
217
+ record.lastUsedAt ?? null,
218
+ record.expiresAt ?? null,
219
+ record.revokedAt ?? null,
220
+ ]);
221
+ if (inserted[0])
222
+ return toPublicKey(inserted[0]);
223
+ const existing = await this._deps.connection.query(`SELECT * FROM event_api_keys
224
+ WHERE id = $1 OR lower(label) = lower($2) OR secret_hash = $3
225
+ ORDER BY CASE WHEN id = $1 THEN 0 WHEN lower(label) = lower($2) THEN 1 ELSE 2 END
226
+ LIMIT 1`, [record.id, label, record.hash]);
227
+ if (!existing[0])
228
+ throw new Error(`API-ключ ${record.id} не импортирован (конфликт без записи)`);
229
+ return toPublicKey(existing[0]);
230
+ }
231
+ async create(input) {
232
+ const { EVENT_API_KEY_SECRET_PREFIX } = await loadCore();
233
+ const label = input.label?.trim() ?? '';
234
+ if (!label)
235
+ throw new Error('label обязателен');
236
+ const secret = `${EVENT_API_KEY_SECRET_PREFIX}${randomBytes(24).toString('base64url')}`;
237
+ let rows;
238
+ try {
239
+ rows = await this._deps.connection.query(`INSERT INTO event_api_keys
240
+ (id, binding_id, label, description, secret_hash, prefix, rate_limit_per_minute,
241
+ created_by, created_at, last_used_at, expires_at, revoked_at)
242
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, NULL)
243
+ RETURNING *`, [
244
+ `eak_${generateId()}`,
245
+ input.bindingId,
246
+ label,
247
+ input.description ?? null,
248
+ hashSecret(secret),
249
+ `${secret.slice(0, SECRET_PREFIX_VISIBLE)}…`,
250
+ input.rateLimitPerMinute ?? null,
251
+ input.createdBy,
252
+ new Date().toISOString(),
253
+ input.expiresAt ?? null,
254
+ ]);
255
+ }
256
+ catch (err) {
257
+ if (isUniqueViolation(err)) {
258
+ const { EventApiKeyConflictError } = await loadCore();
259
+ throw new EventApiKeyConflictError(label);
260
+ }
261
+ throw err;
262
+ }
263
+ return { ...toPublicKey(rows[0]), key: secret };
264
+ }
265
+ /** Патч: `undefined` — не трогать, `null` — сбросить поле. */
266
+ async update(bindingId, keyId, patch) {
267
+ const sets = [];
268
+ const params = [];
269
+ if (patch.label !== undefined) {
270
+ const label = patch.label.trim();
271
+ if (!label)
272
+ throw new Error('label обязателен');
273
+ params.push(label);
274
+ sets.push(`label = $${params.length}`);
275
+ }
276
+ if (patch.description !== undefined) {
277
+ params.push(patch.description);
278
+ sets.push(`description = $${params.length}`);
279
+ }
280
+ if (patch.expiresAt !== undefined) {
281
+ params.push(patch.expiresAt);
282
+ sets.push(`expires_at = $${params.length}`);
283
+ }
284
+ if (patch.rateLimitPerMinute !== undefined) {
285
+ params.push(patch.rateLimitPerMinute);
286
+ sets.push(`rate_limit_per_minute = $${params.length}`);
287
+ }
288
+ if (sets.length === 0) {
289
+ return this.get(bindingId, keyId);
290
+ }
291
+ params.push(keyId, bindingId);
292
+ const where = `id = $${params.length - 1} AND binding_id = $${params.length}`;
293
+ try {
294
+ const rows = await this._deps.connection.query(`UPDATE event_api_keys SET ${sets.join(', ')} WHERE ${where} RETURNING *`, params);
295
+ return rows[0] ? toPublicKey(rows[0]) : null;
296
+ }
297
+ catch (err) {
298
+ if (isUniqueViolation(err)) {
299
+ const { EventApiKeyConflictError } = await loadCore();
300
+ throw new EventApiKeyConflictError(patch.label ?? keyId);
301
+ }
302
+ throw err;
303
+ }
304
+ }
305
+ async remove(bindingId, keyId) {
306
+ const rows = await this._deps.connection.query('DELETE FROM event_api_keys WHERE id = $1 AND binding_id = $2 RETURNING id', [keyId, bindingId]);
307
+ return rows.length > 0;
308
+ }
309
+ /** Каскадное удаление ключей привязки; возвращает число удалённых. */
310
+ async removeByBinding(bindingId) {
311
+ const rows = await this._deps.connection.query('DELETE FROM event_api_keys WHERE binding_id = $1 RETURNING id', [bindingId]);
312
+ return rows.length;
313
+ }
314
+ /** Мягкий отзыв: `revokedAt = now()` (идемпотентно); `false`, если ключа нет. */
315
+ async revoke(bindingId, keyId) {
316
+ const rows = await this._deps.connection.query(`UPDATE event_api_keys
317
+ SET revoked_at = COALESCE(revoked_at, now())
318
+ WHERE id = $1 AND binding_id = $2
319
+ RETURNING id`, [keyId, bindingId]);
320
+ return rows.length > 0;
321
+ }
322
+ /** Резолв секрета по sha256-хешу; revoked/expired/unknown → `null`. */
323
+ async resolveBySecret(rawSecret) {
324
+ if (!rawSecret)
325
+ return null;
326
+ const rows = await this._deps.connection.query('SELECT * FROM event_api_keys WHERE secret_hash = $1 LIMIT 1', [hashSecret(rawSecret)]);
327
+ const record = rows[0];
328
+ if (!record)
329
+ return null;
330
+ if (record.revoked_at)
331
+ return null;
332
+ const expiresAt = toIso(record.expires_at);
333
+ if (expiresAt && Date.parse(expiresAt) <= Date.now())
334
+ return null;
335
+ const key = toPublicKey(record);
336
+ const credential = compact({
337
+ keyId: key.id,
338
+ bindingId: key.bindingId,
339
+ ownerId: key.createdBy || undefined,
340
+ rateLimitPerMinute: key.rateLimitPerMinute,
341
+ });
342
+ return { key, credential };
343
+ }
344
+ /** Best-effort отметка использования (`lastUsedAt`). */
345
+ async touch(id) {
346
+ await this._deps.connection.query('UPDATE event_api_keys SET last_used_at = now() WHERE id = $1', [id]);
347
+ }
348
+ }
349
+ /** Собрать под-группу портов привязок/правил/ключей. */
350
+ export function buildEventBindingPorts(deps) {
351
+ return {
352
+ eventBindings: new PgEventBindingRepository(deps),
353
+ eventRoutes: new PgEventRouteRepository(deps),
354
+ eventApiKeys: new PgEventApiKeyRepository(deps),
355
+ };
356
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Общие примитивы PostgreSQL-реализации портов группы `events` (PROP-032, волна 3b).
3
+ *
4
+ * Здесь только то, что переиспользуют файлы `events-*.ts`: ленивая загрузка core
5
+ * (доменные ошибки, крипто-хелперы), хелперы дат/чисел и деталь отображения
6
+ * секрета. Доменные типы берутся напрямую из `@itphx/synth-shared` (обычная
7
+ * зависимость драйвера, ADR-097), типы портов core — `import type` в файлах-группах.
8
+ */
9
+ /** Длина видимой части секрета в `prefix` (`synth_evt_abcd…`/`whsec_abcd…`) — деталь отображения. */
10
+ export declare const SECRET_PREFIX_VISIBLE = 12;
11
+ type CoreModule = typeof import('@itphx/synth-core');
12
+ /**
13
+ * Ленивая загрузка `@itphx/synth-core`.
14
+ *
15
+ * Верхнеуровневый runtime-импорт core драйверу запрещён (ADR-097): core —
16
+ * `peerDependency`, а статический импорт не должен тянуть ядро при загрузке
17
+ * модуля драйвера (цикл core ↔ драйвер). Используется только внутри
18
+ * async-методов — для доменных классов ошибок (`EventApiKeyConflictError`,
19
+ * `WebhookConflictError`) и крипто-хелперов webhooks. Промис кэшируется; при
20
+ * ошибке кэш сбрасывается, чтобы следующий вызов повторил попытку.
21
+ */
22
+ export declare function loadCore(): Promise<CoreModule>;
23
+ /** `timestamptz`/ISO → ISO-8601; `null`/`undefined` → `undefined`. */
24
+ export declare function toIso(value: unknown): string | undefined;
25
+ /** Обязательная дата: `null` недопустим (для `NOT NULL timestamptz`). */
26
+ export declare function toIsoRequired(value: unknown): string;
27
+ /** `int8`/`int4`/numeric → число; `null` → `undefined`. */
28
+ export declare function toInt(value: unknown): number | undefined;
29
+ /** Убирает ключи со значением `undefined` — чистое доменное представление. */
30
+ export declare function compact<T extends Record<string, unknown>>(value: T): T;
31
+ /** Нарушение уникальности PG (в т.ч. `lower(label)`-индекс) → доменный конфликт. */
32
+ export declare function isUniqueViolation(err: unknown): boolean;
33
+ /** Дни retention → SQL-выражение `now() - interval` (общий для журналов). */
34
+ export declare function retentionCutoffExpr(param?: string): string;
35
+ export {};