@kici-dev/shared 0.1.22 → 0.1.24

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.
@@ -221,10 +221,13 @@ export interface SeedEnvironmentBindingOpts {
221
221
  orgId: string;
222
222
  envName: string;
223
223
  scopePattern: string;
224
+ /** Host selector; defaults to `'**'` (all hosts). */
225
+ hostPattern?: string;
224
226
  }
225
227
  /**
226
- * Upsert an `environment_bindings` row connecting `envName` to `scopePattern`.
227
- * Throws if the environment does not exist.
228
+ * Upsert an `environment_bindings` row connecting `envName` to `scopePattern`
229
+ * (scoped to `hostPattern`, default `'**'`). Throws if the environment does
230
+ * not exist.
228
231
  */
229
232
  export declare function seedEnvironmentBindingDirect(databaseUrl: string, opts: SeedEnvironmentBindingOpts): Promise<{
230
233
  created: boolean;
@@ -275,6 +278,7 @@ export interface EnvironmentVariableRow {
275
278
  }
276
279
  export interface EnvironmentBindingRow {
277
280
  scope_pattern: string;
281
+ host_pattern: string;
278
282
  created_at: string;
279
283
  }
280
284
  export interface ShowEnvironmentResult {
@@ -399,6 +403,8 @@ export interface ExecutionJobRow {
399
403
  duration_ms: number | null;
400
404
  created_at: string;
401
405
  error_message: string | null;
406
+ /** Ordered bound deployment-environment names (JSON-encoded `string[]`), or null. */
407
+ environments: string | null;
402
408
  }
403
409
  export interface ListExecutionRunsOpts {
404
410
  routingKey?: string;
package/dist/db-admin.js CHANGED
@@ -433,8 +433,9 @@ async function deleteEnvironmentDirect(databaseUrl, opts) {
433
433
  }
434
434
  }
435
435
  /**
436
- * Upsert an `environment_bindings` row connecting `envName` to `scopePattern`.
437
- * Throws if the environment does not exist.
436
+ * Upsert an `environment_bindings` row connecting `envName` to `scopePattern`
437
+ * (scoped to `hostPattern`, default `'**'`). Throws if the environment does
438
+ * not exist.
438
439
  */
439
440
  async function seedEnvironmentBindingDirect(databaseUrl, opts) {
440
441
  const pool = new pg.Pool({
@@ -445,13 +446,14 @@ async function seedEnvironmentBindingDirect(databaseUrl, opts) {
445
446
  const envRow = await pool.query(`SELECT id FROM environments WHERE org_id = $1 AND name = $2`, [opts.orgId, opts.envName]);
446
447
  if (envRow.rows.length === 0) throw new Error(`environment: not found (org=${opts.orgId}, name=${opts.envName})`);
447
448
  const envId = envRow.rows[0].id;
448
- return { created: (await pool.query(`INSERT INTO environment_bindings (org_id, environment_id, scope_pattern)
449
- VALUES ($1, $2, $3)
449
+ return { created: (await pool.query(`INSERT INTO environment_bindings (org_id, environment_id, scope_pattern, host_pattern)
450
+ VALUES ($1, $2, $3, $4)
450
451
  ON CONFLICT DO NOTHING
451
452
  RETURNING (xmax = 0) AS inserted`, [
452
453
  opts.orgId,
453
454
  envId,
454
- opts.scopePattern
455
+ opts.scopePattern,
456
+ opts.hostPattern ?? "**"
455
457
  ])).rows[0]?.inserted ?? false };
456
458
  } finally {
457
459
  await pool.end();
@@ -537,10 +539,10 @@ async function showEnvironmentDirect(databaseUrl, opts) {
537
539
  FROM environment_variables
538
540
  WHERE environment_id = $1
539
541
  ORDER BY key`, [env.id]);
540
- const bindings = await pool.query(`SELECT scope_pattern, created_at
542
+ const bindings = await pool.query(`SELECT scope_pattern, host_pattern, created_at
541
543
  FROM environment_bindings
542
544
  WHERE environment_id = $1
543
- ORDER BY scope_pattern`, [env.id]);
545
+ ORDER BY scope_pattern, host_pattern`, [env.id]);
544
546
  return {
545
547
  environment: env,
546
548
  variables: variables.rows,
@@ -780,7 +782,7 @@ async function showExecutionRunDirect(databaseUrl, opts) {
780
782
  return {
781
783
  run,
782
784
  jobs: (await pool.query(`SELECT id, run_id, job_id, job_name, status, agent_id,
783
- started_at, completed_at, duration_ms, created_at, error_message
785
+ started_at, completed_at, duration_ms, created_at, error_message, environments
784
786
  FROM execution_jobs
785
787
  WHERE run_id = $1
786
788
  ORDER BY created_at ASC`, [run.run_id])).rows
@@ -797,7 +799,8 @@ async function listExecutionJobsDirect(databaseUrl, opts) {
797
799
  const pool = createPool(databaseUrl);
798
800
  try {
799
801
  return { jobs: (await pool.query(`SELECT j.id, j.run_id, j.job_id, j.job_name, j.status, j.agent_id,
800
- j.started_at, j.completed_at, j.duration_ms, j.created_at, j.error_message
802
+ j.started_at, j.completed_at, j.duration_ms, j.created_at, j.error_message,
803
+ j.environments
801
804
  FROM execution_jobs j
802
805
  INNER JOIN execution_runs r ON r.run_id = j.run_id
803
806
  WHERE r.run_id::text = $1 OR r.id::text = $1
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  export * from '@kici-dev/core';
2
+ export { encrypt, decrypt, deriveKey, generateMasterKey, type EncryptedValue, } from './secret-crypto.js';
2
3
  export { RingBuffer } from './ring-buffer.js';
3
4
  export { redactConfig, addLogsToArchive, MAX_LOG_BYTES } from './diagnostics/bundle-archive.js';
4
5
  export { chunkBuffer, BundleChunkAssembler, ChunkRequestWaiter, FLEET_CHUNK_BYTES, type BundleChunkFrame, } from './diagnostics/bundle-chunks.js';
5
6
  export { createPool, createDb, type CreatePoolOptions, type PgPoolErrorSource } from './db.js';
7
+ export { isPgUniqueViolation } from './pg-errors.js';
6
8
  export { parseDatabaseUrl, maskDatabaseUrl, dropAndCreateDatabase, dropDatabaseDirect, ensureDatabase, type EnsureDatabaseOpts, createDbRole, createReadOnlyDbUser, computeMigrationsHash, storeMigrationContentHash, readStoredMigrationContentHash, isSchemaCurrent, clearDispatchQueueDirect, purgeStaleExecutionDirect, purgeStaleSourcesDirect, purgeScopedSecretsDirect, seedEnvironmentDirect, deleteEnvironmentDirect, seedEnvironmentBindingDirect, setEnvironmentPolicyDirect, listEnvironmentsDirect, showEnvironmentDirect, createEnvironmentTemplateDirect, setEnvironmentSecretDirect, listQueueDirect, showQueueEntryDirect, listExecutionRunsDirect, showExecutionRunDirect, listExecutionJobsDirect, listRegistrationsDirect, showRegistrationDirect, registerWorkflowManualDirect, resetRaftStateDirect, emitKiciEventDirect, seedGenericWebhookSourceDirect, purgeSecretBackendsDirect, apiKeyExistsDirect, seedApiKeyInlineDirect, platformConnectionExistsDirect, countWebhookSourcesByConnectionIdDirect, getWebhookSourceByRoutingKeyDirect, findAnyUserApiKeyIdDirect, seedSyntheticGithubSourceDirect, seedWebhookSecretDirect, seedSourcePrivateKeyDirect, bumpRegistryVersionDirect, pollKiciEventsDirect, waitForPostgresDirect, waitForRunCompletionDirect, cleanupExecutionRowsDirect, isSchemaCurrentFromFilesDirect, storeMigrationContentHashInTableDirect, createJoinTokenDirect, deleteJoinTokensByCreatedByDirect, updateSourceRoutingKeyDirect, prunePeerCredentialsDirect, waitForPlatformRegistrationsDirect, seedUniversalGitSourceDirect, seedCiSecurityFixturesDirect, waitForExecutionRunStatusSinceDirect, latestExecutionRunByStatusDirect, waitForLatestExecutionJobStatusDirect, describeTableColumnsDirect, tableExistsDirect, insertKiciEventRawDirect, showKiciEventDirect, listKiciEventsDirect, deleteKiciEventsDirect, verifyKiciEventNotifyDirect, seedCrossRepoTrustDirect, listCrossRepoTrustBySourceRoutingKeyDirect, deleteCrossRepoTrustDirect, insertCrossRepoTrustStrictDirect, deleteWorkflowRegistrationsDirect, getWorkflowRegistrationByIdDirect, listRegistrationsByRoutingKeyDirect, waitForRegistrationsByRoutingKeyDirect, waitForRegistrationsUpdatedAtAdvanceDirect, updateWorkflowRegistrationCommitShaDirect, insertWorkflowRegistrationRawDirect, insertWorkflowRegistrationStrictDirect, getRegistryVersionDirect, bumpRegistryVersionSimpleDirect, upsertCronLastFiredDirect, countCronLastFiredDirect, insertCronLastFiredNowDirect, deleteCronLastFiredDirect, deleteExecutionRunsByWorkflowNameDirect, getGenericWebhookSourceByRoutingKeyDirect, listActiveGenericWebhookSourcesDirect, updateGenericWebhookVerificationConfigDirect, deleteGenericWebhookSourcesByNameDirect, restoreSoftDeletedGenericWebhookSourceDirect, upsertOrgSettingsGlobalWorkflowsDirect, updateOrgSettingsDeniedReposDirect, deleteOrgSettingsByCustomerIdDirect, getExecutionRunSecurityDirect, getHeldRunByIdDirect, listHeldRunApprovalsDirect, countHeldRunsByRunIdDirect, waitForPlatformExecutionRunStatusDirect, waitForPlatformEventLogDistinctRoutedDirect, waitForEventLogRowByDeliveryIdDirect, resolvePlatformWebhookSourceRoutingKeyDirect, ensureOrgOwnerMemberDirect, deletePeerCredentialsByInstanceIdLikeDirect, insertPeerCredentialExpiredDirect, getPeerCredentialRevokedAtDirect, listActivePeerCredentialsExcludingDirect, clearPeerCredentialsRevokedAtByIdsDirect, countActivePeerCredentialsByInstanceDirect, terminateIdleDbBackendsDirect, type ColumnInfo, type KiciEventRow, type CrossRepoTrustRow, type WorkflowRegistrationFullRow, type RegistrationsScopedResult, type LatestExecutionRunResult, type WaitForLatestJobResult, type ExecutionRunSecurityRow, type HeldRunSecurityRow, type EventLogRow as PlatformEventLogRow, type UpsertOrgSettingsOpts, type OrgSettingsRepoPatternEntry, type InsertKiciEventRawOpts, type EmitKiciEventOpts, type SeedGenericWebhookSourceOpts, REGISTERABLE_TRIGGER_TYPES, MIGRATION_HASH_TABLE, type PurgeStaleExecutionResult, type PurgeStaleSourcesResult, type SeedEnvironmentOpts, type SeedEnvironmentResult, type SeedEnvironmentBindingOpts, type SetEnvironmentPolicyOpts, type EnvironmentRow, type EnvironmentVariableRow, type EnvironmentBindingRow, type ShowEnvironmentResult, type CreateEnvironmentTemplateOpts, type SetEnvironmentSecretOpts, type DispatchQueueRow, type ListQueueOpts, type ExecutionRunRow, type ExecutionJobRow, type ListExecutionRunsOpts, type WorkflowRegistrationRow, type ListRegistrationsOpts, type ListRegistrationsResult, type ShowRegistrationResult, type RegisterWorkflowManualOpts, type RegisterWorkflowManualResult, } from './db-admin.js';
7
9
  export { createMetricsRoutes, type MetricsRoutesDeps } from './routes/metrics.js';
8
10
  export { createHealthRoutes, type HealthRoutesDeps } from './routes/health.js';
package/dist/index.js CHANGED
@@ -2,9 +2,11 @@ import "./chunk-BTugEXQM.js";
2
2
  import { createDb, createPool } from "./db.js";
3
3
  import { MIGRATION_HASH_TABLE, REGISTERABLE_TRIGGER_TYPES, apiKeyExistsDirect, bumpRegistryVersionDirect, bumpRegistryVersionSimpleDirect, cleanupExecutionRowsDirect, clearDispatchQueueDirect, clearPeerCredentialsRevokedAtByIdsDirect, computeMigrationsHash, countActivePeerCredentialsByInstanceDirect, countCronLastFiredDirect, countHeldRunsByRunIdDirect, countWebhookSourcesByConnectionIdDirect, createDbRole, createEnvironmentTemplateDirect, createJoinTokenDirect, createReadOnlyDbUser, deleteCronLastFiredDirect, deleteCrossRepoTrustDirect, deleteEnvironmentDirect, deleteExecutionRunsByWorkflowNameDirect, deleteGenericWebhookSourcesByNameDirect, deleteJoinTokensByCreatedByDirect, deleteKiciEventsDirect, deleteOrgSettingsByCustomerIdDirect, deletePeerCredentialsByInstanceIdLikeDirect, deleteWorkflowRegistrationsDirect, describeTableColumnsDirect, dropAndCreateDatabase, dropDatabaseDirect, emitKiciEventDirect, ensureDatabase, ensureOrgOwnerMemberDirect, findAnyUserApiKeyIdDirect, getExecutionRunSecurityDirect, getGenericWebhookSourceByRoutingKeyDirect, getHeldRunByIdDirect, getPeerCredentialRevokedAtDirect, getRegistryVersionDirect, getWebhookSourceByRoutingKeyDirect, getWorkflowRegistrationByIdDirect, insertCronLastFiredNowDirect, insertCrossRepoTrustStrictDirect, insertKiciEventRawDirect, insertPeerCredentialExpiredDirect, insertWorkflowRegistrationRawDirect, insertWorkflowRegistrationStrictDirect, isSchemaCurrent, isSchemaCurrentFromFilesDirect, latestExecutionRunByStatusDirect, listActiveGenericWebhookSourcesDirect, listActivePeerCredentialsExcludingDirect, listCrossRepoTrustBySourceRoutingKeyDirect, listEnvironmentsDirect, listExecutionJobsDirect, listExecutionRunsDirect, listHeldRunApprovalsDirect, listKiciEventsDirect, listQueueDirect, listRegistrationsByRoutingKeyDirect, listRegistrationsDirect, maskDatabaseUrl, parseDatabaseUrl, platformConnectionExistsDirect, pollKiciEventsDirect, prunePeerCredentialsDirect, purgeScopedSecretsDirect, purgeSecretBackendsDirect, purgeStaleExecutionDirect, purgeStaleSourcesDirect, readStoredMigrationContentHash, registerWorkflowManualDirect, resetRaftStateDirect, resolvePlatformWebhookSourceRoutingKeyDirect, restoreSoftDeletedGenericWebhookSourceDirect, seedApiKeyInlineDirect, seedCiSecurityFixturesDirect, seedCrossRepoTrustDirect, seedEnvironmentBindingDirect, seedEnvironmentDirect, seedGenericWebhookSourceDirect, seedSourcePrivateKeyDirect, seedSyntheticGithubSourceDirect, seedUniversalGitSourceDirect, seedWebhookSecretDirect, setEnvironmentPolicyDirect, setEnvironmentSecretDirect, showEnvironmentDirect, showExecutionRunDirect, showKiciEventDirect, showQueueEntryDirect, showRegistrationDirect, storeMigrationContentHash, storeMigrationContentHashInTableDirect, tableExistsDirect, terminateIdleDbBackendsDirect, updateGenericWebhookVerificationConfigDirect, updateOrgSettingsDeniedReposDirect, updateSourceRoutingKeyDirect, updateWorkflowRegistrationCommitShaDirect, upsertCronLastFiredDirect, upsertOrgSettingsGlobalWorkflowsDirect, verifyKiciEventNotifyDirect, waitForEventLogRowByDeliveryIdDirect, waitForExecutionRunStatusSinceDirect, waitForLatestExecutionJobStatusDirect, waitForPlatformEventLogDistinctRoutedDirect, waitForPlatformExecutionRunStatusDirect, waitForPlatformRegistrationsDirect, waitForPostgresDirect, waitForRegistrationsByRoutingKeyDirect, waitForRegistrationsUpdatedAtAdvanceDirect, waitForRunCompletionDirect } from "./db-admin.js";
4
4
  import { setupGracefulShutdown } from "./graceful-shutdown.js";
5
+ import { decrypt, deriveKey, encrypt, generateMasterKey } from "./secret-crypto.js";
5
6
  import { RingBuffer } from "./ring-buffer.js";
6
7
  import { MAX_LOG_BYTES, addLogsToArchive, redactConfig } from "./diagnostics/bundle-archive.js";
7
8
  import { BundleChunkAssembler, ChunkRequestWaiter, FLEET_CHUNK_BYTES, chunkBuffer } from "./diagnostics/bundle-chunks.js";
9
+ import { isPgUniqueViolation } from "./pg-errors.js";
8
10
  import { createMetricsRoutes } from "./routes/metrics.js";
9
11
  import { createHealthRoutes } from "./routes/health.js";
10
12
  import { getReconnectDelay } from "./reconnect-delay.js";
@@ -24,4 +26,4 @@ import { ChunkLru } from "./cold-store/lru.js";
24
26
  import { DEFAULT_TABLE_CONFIG, resolveTableConfig } from "./cold-store/config.js";
25
27
  import "./cold-store/index.js";
26
28
  export * from "@kici-dev/core";
27
- export { BaseColdStore, BundleChunkAssembler, COLD_BUCKET_NAMES, ChunkLru, ChunkRequestWaiter, DEFAULT_TABLE_CONFIG, FLEET_CHUNK_BYTES, MAX_LOG_BYTES, MIGRATION_HASH_TABLE, REGISTERABLE_TRIGGER_TYPES, RingBuffer, addLogsToArchive, apiKeyExistsDirect, bumpRegistryVersionDirect, bumpRegistryVersionSimpleDirect, chunkBuffer, chunkObjectKey, cleanupExecutionRowsDirect, clearDispatchQueueDirect, clearPeerCredentialsRevokedAtByIdsDirect, coldDaysToBucket, coldStoreArchiveBytesTotal, coldStoreArchiveCyclesTotal, coldStoreArchiveDurationSeconds, coldStoreArchiveRowsTotal, coldStorePurgeBytesTotal, coldStorePurgeChunksTotal, coldStorePurgeDurationSeconds, coldStoreRehydrateBytesTotal, coldStoreRehydrateDurationSeconds, coldStoreRehydrateRequestsTotal, coldStoreReplayDurationSeconds, coldStoreReplayRowsTotal, coldStoreVerifyFailuresTotal, collectRuntimeMetricNames, computeChunkId, computeMigrationsHash, countActivePeerCredentialsByInstanceDirect, countCronLastFiredDirect, countHeldRunsByRunIdDirect, countWebhookSourcesByConnectionIdDirect, createDb, createDbRole, createEnvironmentTemplateDirect, createHealthRoutes, createJoinTokenDirect, createMeter, createMetricsRoutes, createPool, createReadOnlyDbUser, createS3Client, decodeChunk, deleteCronLastFiredDirect, deleteCrossRepoTrustDirect, deleteEnvironmentDirect, deleteExecutionRunsByWorkflowNameDirect, deleteGenericWebhookSourcesByNameDirect, deleteJoinTokensByCreatedByDirect, deleteKiciEventsDirect, deleteOrgSettingsByCustomerIdDirect, deletePeerCredentialsByInstanceIdLikeDirect, deleteWorkflowRegistrationsDirect, describeTableColumnsDirect, dropAndCreateDatabase, dropDatabaseDirect, emitKiciEventDirect, encodeChunk, encodeKeySegment, ensureDatabase, ensureOrgOwnerMemberDirect, findAnyUserApiKeyIdDirect, getExecutionRunSecurityDirect, getGenericWebhookSourceByRoutingKeyDirect, getHeldRunByIdDirect, getPeerCredentialRevokedAtDirect, getPrometheusExporter, getReconnectDelay, getRegistryVersionDirect, getWebhookSourceByRoutingKeyDirect, getWorkflowRegistrationByIdDirect, initTelemetry, insertCronLastFiredNowDirect, insertCrossRepoTrustStrictDirect, insertKiciEventRawDirect, insertPeerCredentialExpiredDirect, insertWorkflowRegistrationRawDirect, insertWorkflowRegistrationStrictDirect, isLongerColdRetention, isSchemaCurrent, isSchemaCurrentFromFilesDirect, latestExecutionRunByStatusDirect, listActiveGenericWebhookSourcesDirect, listActivePeerCredentialsExcludingDirect, listCrossRepoTrustBySourceRoutingKeyDirect, listEnvironmentsDirect, listExecutionJobsDirect, listExecutionRunsDirect, listHeldRunApprovalsDirect, listKiciEventsDirect, listQueueDirect, listRegistrationsByRoutingKeyDirect, listRegistrationsDirect, maskDatabaseUrl, parseDatabaseUrl, parseManifest, platformConnectionExistsDirect, pollKiciEventsDirect, prunePeerCredentialsDirect, purgeScopedSecretsDirect, purgeSecretBackendsDirect, purgeStaleExecutionDirect, purgeStaleSourcesDirect, readStoredMigrationContentHash, redactConfig, registerWorkflowManualDirect, resetRaftStateDirect, resolvePlatformWebhookSourceRoutingKeyDirect, resolveTableConfig, restoreSoftDeletedGenericWebhookSourceDirect, seedApiKeyInlineDirect, seedCiSecurityFixturesDirect, seedCrossRepoTrustDirect, seedEnvironmentBindingDirect, seedEnvironmentDirect, seedGenericWebhookSourceDirect, seedSourcePrivateKeyDirect, seedSyntheticGithubSourceDirect, seedUniversalGitSourceDirect, seedWebhookSecretDirect, serializeManifest, setEnvironmentPolicyDirect, setEnvironmentSecretDirect, setupGracefulShutdown, showEnvironmentDirect, showExecutionRunDirect, showKiciEventDirect, showQueueEntryDirect, showRegistrationDirect, storeMigrationContentHash, storeMigrationContentHashInTableDirect, tableExistsDirect, tablePrefix, tenantDayBucketPrefix, tenantDayPrefix, terminateIdleDbBackendsDirect, updateGenericWebhookVerificationConfigDirect, updateOrgSettingsDeniedReposDirect, updateSourceRoutingKeyDirect, updateWorkflowRegistrationCommitShaDirect, upsertCronLastFiredDirect, upsertOrgSettingsGlobalWorkflowsDirect, validateRequiredTools, verifyKiciEventNotifyDirect, waitForEventLogRowByDeliveryIdDirect, waitForExecutionRunStatusSinceDirect, waitForLatestExecutionJobStatusDirect, waitForPlatformEventLogDistinctRoutedDirect, waitForPlatformExecutionRunStatusDirect, waitForPlatformRegistrationsDirect, waitForPostgresDirect, waitForRegistrationsByRoutingKeyDirect, waitForRegistrationsUpdatedAtAdvanceDirect, waitForRunCompletionDirect };
29
+ export { BaseColdStore, BundleChunkAssembler, COLD_BUCKET_NAMES, ChunkLru, ChunkRequestWaiter, DEFAULT_TABLE_CONFIG, FLEET_CHUNK_BYTES, MAX_LOG_BYTES, MIGRATION_HASH_TABLE, REGISTERABLE_TRIGGER_TYPES, RingBuffer, addLogsToArchive, apiKeyExistsDirect, bumpRegistryVersionDirect, bumpRegistryVersionSimpleDirect, chunkBuffer, chunkObjectKey, cleanupExecutionRowsDirect, clearDispatchQueueDirect, clearPeerCredentialsRevokedAtByIdsDirect, coldDaysToBucket, coldStoreArchiveBytesTotal, coldStoreArchiveCyclesTotal, coldStoreArchiveDurationSeconds, coldStoreArchiveRowsTotal, coldStorePurgeBytesTotal, coldStorePurgeChunksTotal, coldStorePurgeDurationSeconds, coldStoreRehydrateBytesTotal, coldStoreRehydrateDurationSeconds, coldStoreRehydrateRequestsTotal, coldStoreReplayDurationSeconds, coldStoreReplayRowsTotal, coldStoreVerifyFailuresTotal, collectRuntimeMetricNames, computeChunkId, computeMigrationsHash, countActivePeerCredentialsByInstanceDirect, countCronLastFiredDirect, countHeldRunsByRunIdDirect, countWebhookSourcesByConnectionIdDirect, createDb, createDbRole, createEnvironmentTemplateDirect, createHealthRoutes, createJoinTokenDirect, createMeter, createMetricsRoutes, createPool, createReadOnlyDbUser, createS3Client, decodeChunk, decrypt, deleteCronLastFiredDirect, deleteCrossRepoTrustDirect, deleteEnvironmentDirect, deleteExecutionRunsByWorkflowNameDirect, deleteGenericWebhookSourcesByNameDirect, deleteJoinTokensByCreatedByDirect, deleteKiciEventsDirect, deleteOrgSettingsByCustomerIdDirect, deletePeerCredentialsByInstanceIdLikeDirect, deleteWorkflowRegistrationsDirect, deriveKey, describeTableColumnsDirect, dropAndCreateDatabase, dropDatabaseDirect, emitKiciEventDirect, encodeChunk, encodeKeySegment, encrypt, ensureDatabase, ensureOrgOwnerMemberDirect, findAnyUserApiKeyIdDirect, generateMasterKey, getExecutionRunSecurityDirect, getGenericWebhookSourceByRoutingKeyDirect, getHeldRunByIdDirect, getPeerCredentialRevokedAtDirect, getPrometheusExporter, getReconnectDelay, getRegistryVersionDirect, getWebhookSourceByRoutingKeyDirect, getWorkflowRegistrationByIdDirect, initTelemetry, insertCronLastFiredNowDirect, insertCrossRepoTrustStrictDirect, insertKiciEventRawDirect, insertPeerCredentialExpiredDirect, insertWorkflowRegistrationRawDirect, insertWorkflowRegistrationStrictDirect, isLongerColdRetention, isPgUniqueViolation, isSchemaCurrent, isSchemaCurrentFromFilesDirect, latestExecutionRunByStatusDirect, listActiveGenericWebhookSourcesDirect, listActivePeerCredentialsExcludingDirect, listCrossRepoTrustBySourceRoutingKeyDirect, listEnvironmentsDirect, listExecutionJobsDirect, listExecutionRunsDirect, listHeldRunApprovalsDirect, listKiciEventsDirect, listQueueDirect, listRegistrationsByRoutingKeyDirect, listRegistrationsDirect, maskDatabaseUrl, parseDatabaseUrl, parseManifest, platformConnectionExistsDirect, pollKiciEventsDirect, prunePeerCredentialsDirect, purgeScopedSecretsDirect, purgeSecretBackendsDirect, purgeStaleExecutionDirect, purgeStaleSourcesDirect, readStoredMigrationContentHash, redactConfig, registerWorkflowManualDirect, resetRaftStateDirect, resolvePlatformWebhookSourceRoutingKeyDirect, resolveTableConfig, restoreSoftDeletedGenericWebhookSourceDirect, seedApiKeyInlineDirect, seedCiSecurityFixturesDirect, seedCrossRepoTrustDirect, seedEnvironmentBindingDirect, seedEnvironmentDirect, seedGenericWebhookSourceDirect, seedSourcePrivateKeyDirect, seedSyntheticGithubSourceDirect, seedUniversalGitSourceDirect, seedWebhookSecretDirect, serializeManifest, setEnvironmentPolicyDirect, setEnvironmentSecretDirect, setupGracefulShutdown, showEnvironmentDirect, showExecutionRunDirect, showKiciEventDirect, showQueueEntryDirect, showRegistrationDirect, storeMigrationContentHash, storeMigrationContentHashInTableDirect, tableExistsDirect, tablePrefix, tenantDayBucketPrefix, tenantDayPrefix, terminateIdleDbBackendsDirect, updateGenericWebhookVerificationConfigDirect, updateOrgSettingsDeniedReposDirect, updateSourceRoutingKeyDirect, updateWorkflowRegistrationCommitShaDirect, upsertCronLastFiredDirect, upsertOrgSettingsGlobalWorkflowsDirect, validateRequiredTools, verifyKiciEventNotifyDirect, waitForEventLogRowByDeliveryIdDirect, waitForExecutionRunStatusSinceDirect, waitForLatestExecutionJobStatusDirect, waitForPlatformEventLogDistinctRoutedDirect, waitForPlatformExecutionRunStatusDirect, waitForPlatformRegistrationsDirect, waitForPostgresDirect, waitForRegistrationsByRoutingKeyDirect, waitForRegistrationsUpdatedAtAdvanceDirect, waitForRunCompletionDirect };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * True iff `err` is a Postgres unique-violation, optionally scoped to a named
3
+ * constraint. Pure guard over `unknown` — no `pg` import — so callers in the
4
+ * data layer can translate a raw driver error into a domain error, and it can
5
+ * be unit-tested without a live database.
6
+ */
7
+ export declare function isPgUniqueViolation(err: unknown, constraint?: string): boolean;
8
+ //# sourceMappingURL=pg-errors.d.ts.map
@@ -0,0 +1,21 @@
1
+ import "./chunk-BTugEXQM.js";
2
+ //#region src/pg-errors.ts
3
+ /** Postgres SQLSTATE for a unique-violation. */
4
+ const PG_UNIQUE_VIOLATION = "23505";
5
+ /**
6
+ * True iff `err` is a Postgres unique-violation, optionally scoped to a named
7
+ * constraint. Pure guard over `unknown` — no `pg` import — so callers in the
8
+ * data layer can translate a raw driver error into a domain error, and it can
9
+ * be unit-tested without a live database.
10
+ */
11
+ function isPgUniqueViolation(err, constraint) {
12
+ if (typeof err !== "object" || err === null) return false;
13
+ const e = err;
14
+ if (e.code !== PG_UNIQUE_VIOLATION) return false;
15
+ if (constraint !== void 0 && e.constraint !== constraint) return false;
16
+ return true;
17
+ }
18
+ //#endregion
19
+ export { isPgUniqueViolation };
20
+
21
+ //# sourceMappingURL=pg-errors.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=pg-errors.test.d.ts.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Encrypted value with key version tracking.
3
+ * The data field contains base64-encoded IV || AuthTag || Ciphertext.
4
+ */
5
+ export interface EncryptedValue {
6
+ /** Base64-encoded IV + auth tag + ciphertext. */
7
+ data: string;
8
+ /** Version of the encryption key used. */
9
+ keyVersion: number;
10
+ }
11
+ /**
12
+ * Encrypt a plaintext string using AES-256-GCM with AAD.
13
+ *
14
+ * @param plaintext - The string to encrypt
15
+ * @param key - 32-byte encryption key
16
+ * @param keyVersion - Version number for key rotation tracking
17
+ * @param aad - Additional authenticated data (e.g., "contextId:keyName")
18
+ * @returns Encrypted value with key version
19
+ */
20
+ export declare function encrypt(plaintext: string, key: Buffer, keyVersion: number, aad: string): EncryptedValue;
21
+ /**
22
+ * Decrypt an encrypted value using AES-256-GCM with AAD verification.
23
+ *
24
+ * @param encrypted - The encrypted value to decrypt
25
+ * @param key - 32-byte encryption key (must match the key used for encryption)
26
+ * @param aad - Additional authenticated data (must match the AAD used for encryption)
27
+ * @returns Decrypted plaintext string
28
+ * @throws If decryption fails (wrong key, wrong AAD, tampered data)
29
+ */
30
+ export declare function decrypt(encrypted: EncryptedValue, key: Buffer, aad: string): string;
31
+ /**
32
+ * Derive a 32-byte encryption key from a string input.
33
+ *
34
+ * Accepts two formats:
35
+ * - 64-character hex string (e.g., from generateMasterKey())
36
+ * - Base64-encoded 32-byte key
37
+ *
38
+ * @param input - Hex or base64 encoded key material
39
+ * @returns 32-byte Buffer suitable for use with encrypt/decrypt
40
+ * @throws If the derived key is not exactly 32 bytes
41
+ */
42
+ export declare function deriveKey(input: string): Buffer;
43
+ /**
44
+ * Generate a new random 32-byte master key as a hex string.
45
+ *
46
+ * @returns 64-character hex string suitable for KICI_SECRET_KEY env var
47
+ */
48
+ export declare function generateMasterKey(): string;
49
+ //# sourceMappingURL=secret-crypto.d.ts.map
@@ -0,0 +1,92 @@
1
+ import "./chunk-BTugEXQM.js";
2
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
3
+ //#region src/secret-crypto.ts
4
+ /**
5
+ * AES-256-GCM encryption layer for secrets management.
6
+ *
7
+ * Provides authenticated encryption with additional data (AAD)
8
+ * to prevent cross-context secret swaps. The AAD is typically
9
+ * "contextId:keyName" binding the ciphertext to its location.
10
+ *
11
+ * Wire format (base64 encoded): IV (12 bytes) || AuthTag (16 bytes) || Ciphertext
12
+ */
13
+ /** Length of the initialization vector in bytes. */
14
+ const IV_LENGTH = 12;
15
+ /** Length of the GCM authentication tag in bytes. */
16
+ const TAG_LENGTH = 16;
17
+ /** Algorithm identifier for Node.js crypto. */
18
+ const ALGO = "aes-256-gcm";
19
+ /**
20
+ * Encrypt a plaintext string using AES-256-GCM with AAD.
21
+ *
22
+ * @param plaintext - The string to encrypt
23
+ * @param key - 32-byte encryption key
24
+ * @param keyVersion - Version number for key rotation tracking
25
+ * @param aad - Additional authenticated data (e.g., "contextId:keyName")
26
+ * @returns Encrypted value with key version
27
+ */
28
+ function encrypt(plaintext, key, keyVersion, aad) {
29
+ const iv = randomBytes(IV_LENGTH);
30
+ const cipher = createCipheriv(ALGO, key, iv, { authTagLength: TAG_LENGTH });
31
+ cipher.setAAD(Buffer.from(aad, "utf-8"));
32
+ const encrypted = Buffer.concat([cipher.update(plaintext, "utf-8"), cipher.final()]);
33
+ const authTag = cipher.getAuthTag();
34
+ return {
35
+ data: Buffer.concat([
36
+ iv,
37
+ authTag,
38
+ encrypted
39
+ ]).toString("base64"),
40
+ keyVersion
41
+ };
42
+ }
43
+ /**
44
+ * Decrypt an encrypted value using AES-256-GCM with AAD verification.
45
+ *
46
+ * @param encrypted - The encrypted value to decrypt
47
+ * @param key - 32-byte encryption key (must match the key used for encryption)
48
+ * @param aad - Additional authenticated data (must match the AAD used for encryption)
49
+ * @returns Decrypted plaintext string
50
+ * @throws If decryption fails (wrong key, wrong AAD, tampered data)
51
+ */
52
+ function decrypt(encrypted, key, aad) {
53
+ const packed = Buffer.from(encrypted.data, "base64");
54
+ if (packed.length < 28) throw new Error("Invalid encrypted data: too short");
55
+ const iv = packed.subarray(0, IV_LENGTH);
56
+ const authTag = packed.subarray(IV_LENGTH, 28);
57
+ const ciphertext = packed.subarray(28);
58
+ const decipher = createDecipheriv(ALGO, key, iv, { authTagLength: TAG_LENGTH });
59
+ decipher.setAuthTag(authTag);
60
+ decipher.setAAD(Buffer.from(aad, "utf-8"));
61
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf-8");
62
+ }
63
+ /**
64
+ * Derive a 32-byte encryption key from a string input.
65
+ *
66
+ * Accepts two formats:
67
+ * - 64-character hex string (e.g., from generateMasterKey())
68
+ * - Base64-encoded 32-byte key
69
+ *
70
+ * @param input - Hex or base64 encoded key material
71
+ * @returns 32-byte Buffer suitable for use with encrypt/decrypt
72
+ * @throws If the derived key is not exactly 32 bytes
73
+ */
74
+ function deriveKey(input) {
75
+ let key;
76
+ if (/^[0-9a-fA-F]{64}$/.test(input)) key = Buffer.from(input, "hex");
77
+ else key = Buffer.from(input, "base64");
78
+ if (key.length !== 32) throw new Error(`Encryption key must be exactly 32 bytes, got ${key.length} bytes. Provide a 64-character hex string or a base64-encoded 32-byte value.`);
79
+ return key;
80
+ }
81
+ /**
82
+ * Generate a new random 32-byte master key as a hex string.
83
+ *
84
+ * @returns 64-character hex string suitable for KICI_SECRET_KEY env var
85
+ */
86
+ function generateMasterKey() {
87
+ return randomBytes(32).toString("hex");
88
+ }
89
+ //#endregion
90
+ export { decrypt, deriveKey, encrypt, generateMasterKey };
91
+
92
+ //# sourceMappingURL=secret-crypto.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=secret-crypto.test.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kici-dev/shared",
3
- "version": "0.1.22",
3
+ "version": "0.1.24",
4
4
  "description": "Shared utilities for the KiCI CI/CD stack — logging, zx setup, crypto, telemetry, health and metrics routes. No business logic.",
5
5
  "keywords": [
6
6
  "ci",
@@ -70,6 +70,10 @@
70
70
  "import": "./dist/db-collation.js",
71
71
  "types": "./dist/db-collation.d.ts"
72
72
  },
73
+ "./secret-crypto": {
74
+ "import": "./dist/secret-crypto.js",
75
+ "types": "./dist/secret-crypto.d.ts"
76
+ },
73
77
  "./package-manager": {
74
78
  "import": "./dist/package-manager.js",
75
79
  "types": "./dist/package-manager.d.ts"
@@ -101,7 +105,7 @@
101
105
  "yaml": "^2.9.0",
102
106
  "zod": "^4.4.3",
103
107
  "zx": "^8.8.5",
104
- "@kici-dev/core": "0.1.22"
108
+ "@kici-dev/core": "0.1.24"
105
109
  },
106
110
  "devDependencies": {
107
111
  "@opentelemetry/sdk-trace-base": "^2.7.1",
package/sbom.spdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "spdxVersion": "SPDX-2.3",
3
3
  "dataLicense": "CC0-1.0",
4
4
  "SPDXID": "SPDXRef-DOCUMENT",
5
- "name": "@kici-dev/shared@0.1.22",
6
- "documentNamespace": "https://kici.dev/sbom/%40kici-dev%2Fshared/0.1.22/4ad51631-4f2e-44f4-b188-501f882737e9",
5
+ "name": "@kici-dev/shared@0.1.24",
6
+ "documentNamespace": "https://kici.dev/sbom/%40kici-dev%2Fshared/0.1.24/6bcbb358-8666-476c-a539-39b29265ee1b",
7
7
  "creationInfo": {
8
- "created": "2026-06-24T06:02:52Z",
8
+ "created": "2026-06-28T16:24:12Z",
9
9
  "creators": [
10
10
  "Tool: kici-sbom-generator"
11
11
  ]
@@ -696,9 +696,9 @@
696
696
  "homepage": "https://js-sdsl.org"
697
697
  },
698
698
  {
699
- "SPDXID": "SPDXRef-Package--kici-dev-core-0.1.22",
699
+ "SPDXID": "SPDXRef-Package--kici-dev-core-0.1.24",
700
700
  "name": "@kici-dev/core",
701
- "versionInfo": "0.1.22",
701
+ "versionInfo": "0.1.24",
702
702
  "downloadLocation": "NOASSERTION",
703
703
  "filesAnalyzed": false,
704
704
  "licenseConcluded": "NOASSERTION",
@@ -709,7 +709,7 @@
709
709
  {
710
710
  "referenceCategory": "PACKAGE-MANAGER",
711
711
  "referenceType": "purl",
712
- "referenceLocator": "pkg:npm/%40kici-dev/core@0.1.22"
712
+ "referenceLocator": "pkg:npm/%40kici-dev/core@0.1.24"
713
713
  }
714
714
  ],
715
715
  "description": "Light shared utilities for the KiCI stack (logging, errors, formatting, crypto, zx init, the TypeScript ESM loader hook). No server-side dependencies.",
@@ -718,7 +718,7 @@
718
718
  {
719
719
  "SPDXID": "SPDXRef-RootPackage",
720
720
  "name": "@kici-dev/shared",
721
- "versionInfo": "0.1.22",
721
+ "versionInfo": "0.1.24",
722
722
  "downloadLocation": "NOASSERTION",
723
723
  "filesAnalyzed": false,
724
724
  "licenseConcluded": "NOASSERTION",
@@ -729,7 +729,7 @@
729
729
  {
730
730
  "referenceCategory": "PACKAGE-MANAGER",
731
731
  "referenceType": "purl",
732
- "referenceLocator": "pkg:npm/%40kici-dev/shared@0.1.22"
732
+ "referenceLocator": "pkg:npm/%40kici-dev/shared@0.1.24"
733
733
  }
734
734
  ],
735
735
  "description": "Shared utilities for the KiCI CI/CD stack — logging, zx setup, crypto, telemetry, health and metrics routes. No business logic.",
@@ -5202,32 +5202,32 @@
5202
5202
  "relationshipType": "DEPENDS_ON"
5203
5203
  },
5204
5204
  {
5205
- "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.22",
5205
+ "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.24",
5206
5206
  "relatedSpdxElement": "SPDXRef-Package-oxc-transform-0.135.0",
5207
5207
  "relationshipType": "DEPENDS_ON"
5208
5208
  },
5209
5209
  {
5210
- "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.22",
5210
+ "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.24",
5211
5211
  "relatedSpdxElement": "SPDXRef-Package-picocolors-1.1.1",
5212
5212
  "relationshipType": "DEPENDS_ON"
5213
5213
  },
5214
5214
  {
5215
- "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.22",
5215
+ "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.24",
5216
5216
  "relatedSpdxElement": "SPDXRef-Package-winston-daily-rotate-file-5.0.0",
5217
5217
  "relationshipType": "DEPENDS_ON"
5218
5218
  },
5219
5219
  {
5220
- "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.22",
5220
+ "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.24",
5221
5221
  "relatedSpdxElement": "SPDXRef-Package-winston-3.19.0",
5222
5222
  "relationshipType": "DEPENDS_ON"
5223
5223
  },
5224
5224
  {
5225
- "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.22",
5225
+ "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.24",
5226
5226
  "relatedSpdxElement": "SPDXRef-Package-zod-4.4.3",
5227
5227
  "relationshipType": "DEPENDS_ON"
5228
5228
  },
5229
5229
  {
5230
- "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.22",
5230
+ "spdxElementId": "SPDXRef-Package--kici-dev-core-0.1.24",
5231
5231
  "relatedSpdxElement": "SPDXRef-Package-zx-8.8.5",
5232
5232
  "relationshipType": "DEPENDS_ON"
5233
5233
  },
@@ -5238,7 +5238,7 @@
5238
5238
  },
5239
5239
  {
5240
5240
  "spdxElementId": "SPDXRef-RootPackage",
5241
- "relatedSpdxElement": "SPDXRef-Package--kici-dev-core-0.1.22",
5241
+ "relatedSpdxElement": "SPDXRef-Package--kici-dev-core-0.1.24",
5242
5242
  "relationshipType": "DEPENDS_ON"
5243
5243
  },
5244
5244
  {