@jini-ai/db 0.6.12 → 0.6.15-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +76 -0
  3. package/dist/kernel/kernel-core.js +22 -4
  4. package/dist/kernel/owned-transaction.d.ts +15 -0
  5. package/dist/kernel/owned-transaction.js +9 -0
  6. package/dist/kernel/port.d.ts +1 -0
  7. package/dist/kernel/schema-scope.js +6 -1
  8. package/dist/kernel/sqlite/driver.js +20 -3
  9. package/dist/migrate/ddl.d.ts +11 -0
  10. package/dist/migrate/ddl.js +13 -0
  11. package/dist/migrate/index.d.ts +3 -1
  12. package/dist/migrate/index.js +2 -1
  13. package/dist/migrate/legacy-ledger.d.ts +39 -0
  14. package/dist/migrate/legacy-ledger.js +67 -0
  15. package/dist/migrate/runner.d.ts +58 -0
  16. package/dist/migrate/runner.js +85 -12
  17. package/dist/migrate/step.d.ts +1 -1
  18. package/dist/migrate/step.js +1 -1
  19. package/dist/owner-store/index.d.ts +3 -4
  20. package/dist/owner-store/index.js +3 -4
  21. package/dist/owner-store/migrations/0000_owner_store.js +2 -5
  22. package/dist/owner-store/migrations/index.d.ts +3 -1
  23. package/dist/owner-store/migrations/index.js +3 -1
  24. package/dist/secrets-vault/repo.sql.d.ts +3 -4
  25. package/dist/secrets-vault/repo.sql.js +12 -2
  26. package/dist/sqlite/checked-client.d.ts +19 -0
  27. package/dist/sqlite/checked-client.js +117 -0
  28. package/dist/sqlite/checked-state.d.ts +32 -0
  29. package/dist/sqlite/checked-state.js +26 -0
  30. package/dist/sqlite/index.d.ts +3 -0
  31. package/dist/sqlite/index.js +3 -0
  32. package/dist/sqlite/transaction.d.ts +29 -0
  33. package/dist/sqlite/transaction.js +80 -0
  34. package/package.json +8 -6
  35. package/dist/owner-store/backup.d.ts +0 -32
  36. package/dist/owner-store/backup.js +0 -102
  37. package/dist/owner-store/open.d.ts +0 -25
  38. package/dist/owner-store/open.js +0 -73
  39. package/dist/owner-store/service.d.ts +0 -69
  40. package/dist/owner-store/service.js +0 -122
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/db",
3
- "version": "0.6.12",
3
+ "version": "0.6.15-rc.2",
4
4
  "description": "Database ports, connection helpers, ownership, isolated Kysely kernels and migrations. All peers are optional; drivers are injected.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -24,13 +24,15 @@
24
24
  "src/kernel/index.ts",
25
25
  "src/kernel/kernel-core.ts",
26
26
  "src/kernel/ops.ts",
27
+ "src/kernel/owned-transaction.ts",
27
28
  "src/kernel/port.ts",
28
29
  "src/kernel/postgres-lock.ts",
29
30
  "src/kernel/schema-scope.ts",
30
31
  "src/kernel/schema-shape.ts",
31
32
  "src/kernel/store-copy.ts",
32
33
  "src/kernel/turn-lock.ts",
33
- "src/kernel/typegen.ts"
34
+ "src/kernel/typegen.ts",
35
+ "src/sqlite/checked-state.ts"
34
36
  ]
35
37
  }
36
38
  },
@@ -200,14 +202,14 @@
200
202
  "registry": "https://registry.npmjs.org"
201
203
  },
202
204
  "dependencies": {
203
- "@jini-ai/core": "^0.6.12"
205
+ "@jini-ai/core": "^0.6.15-rc.2"
204
206
  },
205
207
  "peerDependencies": {
206
208
  "kysely": "^0.29.6",
207
209
  "better-sqlite3": "^13.0.0",
208
210
  "@electric-sql/pglite": "0.5.8",
209
211
  "pg": "^8.23.0",
210
- "@jini-ai/platform": "^0.6.10"
212
+ "@jini-ai/platform": "^0.6.15-rc.2"
211
213
  },
212
214
  "peerDependenciesMeta": {
213
215
  "better-sqlite3": {
@@ -234,8 +236,8 @@
234
236
  "better-sqlite3": "13.0.3",
235
237
  "kysely": "0.29.6",
236
238
  "pg": "8.23.0",
237
- "@jini-ai/core": "0.6.12",
238
- "@jini-ai/platform": "0.6.12"
239
+ "@jini-ai/platform": "0.6.15-rc.2",
240
+ "@jini-ai/core": "0.6.15-rc.2"
239
241
  },
240
242
  "scripts": {
241
243
  "build": "tsc -p tsconfig.build.json",
@@ -1,32 +0,0 @@
1
- import { type VaultOptions } from "@jini-ai/platform/secrets/credential-sets/contracts";
2
- import { type OwnerStoreService } from "./service.js";
3
- /** Fixed errors keep recovery diagnostics free of parsed secret values. */
4
- export declare class OwnerStoreBackupError extends Error {
5
- readonly code: "invalid-backup" | "not-empty";
6
- constructor({ code }: {
7
- code: OwnerStoreBackupError["code"];
8
- }, _options?: VaultOptions);
9
- }
10
- /** Take one consistent logical snapshot and encrypt it with the platform passphrase envelope.
11
- * No owner key, sealed source envelope, or consumer grants enter the portable document.
12
- * @complexity O(n + payload bytes) reads and bounded platform KDF work; snapshot lives in memory.
13
- * @example const envelope = await exportOwnerStore({ store, passphrase });
14
- */
15
- export declare function exportOwnerStore({ store, passphrase }: {
16
- store: OwnerStoreService;
17
- passphrase: string;
18
- }, _options?: VaultOptions): Promise<string>;
19
- /** Authenticate and structurally validate before writing, then reuse vault parsing/sealing in
20
- * one transaction. Any row failure rolls back all rows. Grants remain inactive after restore.
21
- * @throws OwnerStoreBackupError for malformed snapshots or a nonempty destination; crypto/vault errors propagate.
22
- * @complexity O(n + payload bytes) with bounded platform KDF work.
23
- * @example await restoreOwnerStore({ store, envelope, passphrase });
24
- */
25
- export declare function restoreOwnerStore({ store, envelope, passphrase }: {
26
- store: OwnerStoreService;
27
- envelope: string;
28
- passphrase: string;
29
- }, _options?: VaultOptions): Promise<{
30
- restored: number;
31
- }>;
32
- //# sourceMappingURL=backup.d.ts.map
@@ -1,102 +0,0 @@
1
- import { openWithPassphrase, sealWithPassphrase } from "@jini-ai/platform/secrets";
2
- import { isCopyableKind } from "@jini-ai/platform/secrets/credential-sets";
3
- import { VAULT_KINDS } from "@jini-ai/platform/secrets/credential-sets/contracts";
4
- import { ownerContext } from "./service.js";
5
- const INVALID_BACKUP = "invalid-backup";
6
- const ENTRY_FIELDS = ["id", "kind", "ownerKey", "binding", "provider", "label", "isDefault", "meta", "payload"];
7
- /** Fixed errors keep recovery diagnostics free of parsed secret values. */
8
- export class OwnerStoreBackupError extends Error {
9
- code;
10
- constructor({ code }, _options = {}) {
11
- super(`Owner store backup: ${code}`);
12
- this.name = "OwnerStoreBackupError";
13
- this.code = code;
14
- }
15
- }
16
- /** Take one consistent logical snapshot and encrypt it with the platform passphrase envelope.
17
- * No owner key, sealed source envelope, or consumer grants enter the portable document.
18
- * @complexity O(n + payload bytes) reads and bounded platform KDF work; snapshot lives in memory.
19
- * @example const envelope = await exportOwnerStore({ store, passphrase });
20
- */
21
- export async function exportOwnerStore({ store, passphrase }, _options = {}) {
22
- const entries = await store.kernel.transaction(async () => {
23
- const snapshot = [];
24
- for (const summary of await store.list({})) {
25
- const entry = await store.vault.get(summary);
26
- if (!entry)
27
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
28
- snapshot.push({ id: summary.id, kind: summary.kind, ownerKey: summary.ownerKey, binding: summary.binding,
29
- provider: summary.provider, label: summary.label, isDefault: summary.isDefault, meta: summary.meta, payload: entry.payload });
30
- }
31
- return snapshot;
32
- });
33
- return sealWithPassphrase({ payload: JSON.stringify({ format: "jini-owner-store", version: 1, entries }), passphrase });
34
- }
35
- /** Authenticate and structurally validate before writing, then reuse vault parsing/sealing in
36
- * one transaction. Any row failure rolls back all rows. Grants remain inactive after restore.
37
- * @throws OwnerStoreBackupError for malformed snapshots or a nonempty destination; crypto/vault errors propagate.
38
- * @complexity O(n + payload bytes) with bounded platform KDF work.
39
- * @example await restoreOwnerStore({ store, envelope, passphrase });
40
- */
41
- export async function restoreOwnerStore({ store, envelope, passphrase }, _options = {}) {
42
- const entries = parseSnapshot({ payload: await openWithPassphrase({ envelope, passphrase }) });
43
- return store.kernel.transaction(async () => {
44
- const row = await store.kernel.run(db => db.selectFrom("secrets_vault").select("id").executeTakeFirst());
45
- const grant = await store.kernel.run(db => db.selectFrom("owner_grants").select("entry_id").executeTakeFirst());
46
- if (row || grant)
47
- throw new OwnerStoreBackupError({ code: "not-empty" });
48
- // Nondefaults first: the vault auto-selects the first row, then explicit defaults win.
49
- for (const entry of [...entries].sort((a, b) => Number(a.isDefault) - Number(b.isDefault))) {
50
- await store.vault.put({ ...entry, ...ownerContext(entry), expectedRevision: null });
51
- }
52
- return { restored: entries.length };
53
- });
54
- }
55
- /** Reject unknown versions/duplicate IDs before any destination transaction is entered. */
56
- function parseSnapshot({ payload }) {
57
- let document;
58
- try {
59
- document = JSON.parse(payload);
60
- }
61
- catch {
62
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
63
- }
64
- if (!isObject(document))
65
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
66
- if (document.format !== "jini-owner-store" || document.version !== 1 || !Array.isArray(document.entries)) {
67
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
68
- }
69
- const entries = document.entries.map(parseEntry);
70
- if (new Set(entries.map(entry => entry.id)).size !== entries.length)
71
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
72
- return entries;
73
- }
74
- /** Validate portable field types; the existing vault owns metadata and payload semantics. */
75
- function parseEntry(value) {
76
- if (!isObject(value))
77
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
78
- const keys = Object.keys(value);
79
- if (keys.length !== ENTRY_FIELDS.length || keys.some(key => !ENTRY_FIELDS.includes(key)))
80
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
81
- assertEntryIdentity(value);
82
- if (!isObject(value.meta) || !(value.payload === null || isObject(value.payload)) || typeof value.isDefault !== "boolean") {
83
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
84
- }
85
- return value;
86
- }
87
- /** Ownership is constrained to the kinds supported by cross-site copying. */
88
- function assertEntryIdentity(value) {
89
- if (![value.id, value.ownerKey, value.label].every(item => typeof item === "string" && item.length > 0)) {
90
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
91
- }
92
- if (![value.binding, value.provider].every(item => item === null || typeof item === "string"))
93
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
94
- if (!VAULT_KINDS.includes(value.kind) || !isCopyableKind[value.kind]) {
95
- throw new OwnerStoreBackupError({ code: INVALID_BACKUP });
96
- }
97
- }
98
- /** JSON objects only; arrays cannot masquerade as metadata or portable rows. */
99
- function isObject(value) {
100
- return value !== null && typeof value === "object" && !Array.isArray(value);
101
- }
102
- //# sourceMappingURL=backup.js.map
@@ -1,25 +0,0 @@
1
- import { type VaultServiceDeps } from "@jini-ai/platform/secrets/credential-sets";
2
- import type { SqliteOpener } from "../sqlite/types.js";
3
- import { OwnerStoreService } from "./service.js";
4
- export interface OpenOwnerStoreInput {
5
- filePath: string;
6
- keyFilePath: string;
7
- open: SqliteOpener;
8
- }
9
- export type OpenOwnerStoreOptions = Partial<Pick<VaultServiceDeps, "metaParsers" | "now" | "newId">>;
10
- export interface OpenedOwnerStore {
11
- service: OwnerStoreService;
12
- close(): Promise<void>;
13
- }
14
- /** Safe recovery guidance never includes underlying key material or vault payloads. */
15
- export declare class OwnerStoreRecoveryError extends Error {
16
- constructor();
17
- }
18
- /** Open an independently migrated owner database using the host's native SQLite dependency.
19
- * Key creation reuses exclusive file generation; an existing credential forbids replacement.
20
- * @throws Migration history errors unchanged, or OwnerStoreRecoveryError for unusable keys.
21
- * @complexity O(m) migration steps; initial key verification opens at most one credential.
22
- * @example const store = await openOwnerStore({ filePath, keyFilePath, open });
23
- */
24
- export declare function openOwnerStore(required: OpenOwnerStoreInput, options?: OpenOwnerStoreOptions): Promise<OpenedOwnerStore>;
25
- //# sourceMappingURL=open.d.ts.map
@@ -1,73 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { existsSync } from "node:fs";
3
- import { resolve } from "node:path";
4
- import { AesGcmSecretSealer, EnvOrFileKeyring, generateFileSiteKey, SiteKeyFileAlreadyExistsError } from "@jini-ai/platform/secrets";
5
- import { createVaultMetaParsers } from "@jini-ai/platform/secrets/credential-sets";
6
- import { closeSqliteConnection, sqliteKernel } from "../kernel/sqlite/index.js";
7
- import { runMigrations } from "../migrate/runner.js";
8
- import { openSqliteConnection } from "../sqlite/open.js";
9
- import { OWNER_STORE_LEDGER, ownerStoreMigrations } from "./migrations/index.js";
10
- import { OwnerStoreService, ownerContext } from "./service.js";
11
- /** Safe recovery guidance never includes underlying key material or vault payloads. */
12
- export class OwnerStoreRecoveryError extends Error {
13
- constructor() {
14
- super("Owner store key is missing, invalid, or cannot open existing data. Restore the original owner key or restore an encrypted backup into an empty store.");
15
- this.name = "OwnerStoreRecoveryError";
16
- }
17
- }
18
- /** Open an independently migrated owner database using the host's native SQLite dependency.
19
- * Key creation reuses exclusive file generation; an existing credential forbids replacement.
20
- * @throws Migration history errors unchanged, or OwnerStoreRecoveryError for unusable keys.
21
- * @complexity O(m) migration steps; initial key verification opens at most one credential.
22
- * @example const store = await openOwnerStore({ filePath, keyFilePath, open });
23
- */
24
- export async function openOwnerStore(required, options = {}) {
25
- if (resolve(required.filePath) === resolve(required.keyFilePath))
26
- throw new TypeError("Owner database and key paths must differ");
27
- const client = openSqliteConnection({ filePath: required.filePath, open: ({ filePath }) => required.open(filePath, {}) });
28
- try {
29
- const kernel = sqliteKernel(client);
30
- await runMigrations(sqliteKernel(client), ownerStoreMigrations, { ledgerTable: OWNER_STORE_LEDGER, appName: "owner store" });
31
- const service = await kernel.transaction(async () => {
32
- const anyEntry = await kernel.run(db => db.selectFrom("secrets_vault").select("id").executeTakeFirst());
33
- const existing = await kernel.run(db => db.selectFrom("secrets_vault").selectAll()
34
- .where("sealed_ciphertext", "is not", null).executeTakeFirst());
35
- prepareKey({ keyFilePath: required.keyFilePath, hasCredentials: anyEntry !== undefined });
36
- const keyring = new EnvOrFileKeyring({ env: { read: () => undefined }, envVarName: "OWNER_STORE_KEY",
37
- keyFilePath: required.keyFilePath, hkdfSalt: "jini-owner-store-v1", allowFileFallback: true, allowFileAutoGenerate: false });
38
- const store = new OwnerStoreService({ kernel, keyring, sealer: new AesGcmSecretSealer({ keyring }),
39
- metaParsers: options.metaParsers ?? createVaultMetaParsers({}),
40
- now: options.now ?? (() => new Date().toISOString()), newId: options.newId ?? (() => randomUUID()) });
41
- try {
42
- // activeKey is only a handle; derive actually validates the file before accepting writes.
43
- await keyring.derive({ workspaceId: "owner", purpose: "owner-store-key-check", info: "v1" });
44
- if (existing)
45
- await store.vault.get({ ...ownerContext({ kind: existing.kind, ownerKey: existing.owner_key, binding: existing.binding }), id: existing.id });
46
- }
47
- catch {
48
- throw new OwnerStoreRecoveryError();
49
- }
50
- return store;
51
- });
52
- return { service, close: async () => closeSqliteConnection(client) };
53
- }
54
- catch (error) {
55
- closeSqliteConnection(client);
56
- throw error;
57
- }
58
- }
59
- /** Never auto-generate over missing recovery material; wx settles competing initializers. */
60
- function prepareKey({ keyFilePath, hasCredentials }) {
61
- if (existsSync(keyFilePath))
62
- return;
63
- if (hasCredentials)
64
- throw new OwnerStoreRecoveryError();
65
- try {
66
- generateFileSiteKey({ keyFilePath });
67
- }
68
- catch (error) {
69
- if (!(error instanceof SiteKeyFileAlreadyExistsError))
70
- throw error;
71
- }
72
- }
73
- //# sourceMappingURL=open.js.map
@@ -1,69 +0,0 @@
1
- import { SecretsVaultService, type VaultPutInput, type VaultServiceDeps } from "@jini-ai/platform/secrets/credential-sets";
2
- import { type VaultContext, type VaultCopyResult, type VaultOptions, type VaultSummary } from "@jini-ai/platform/secrets/credential-sets/contracts";
3
- import type { StorageKernel } from "../kernel/port.js";
4
- import { SqlSecretsVaultRepo, type SecretsVaultDatabase } from "../secrets-vault/repo.sql.js";
5
- export declare const OWNER_WORKSPACE_ID = "owner";
6
- export interface OwnerGrant {
7
- entry_id: string;
8
- consumer_id: string;
9
- created_at: string;
10
- }
11
- export interface OwnerStoreDatabase extends SecretsVaultDatabase {
12
- owner_grants: OwnerGrant;
13
- }
14
- export interface OwnerSyncTarget {
15
- consumerId: string;
16
- workspaceId: string;
17
- vault: SecretsVaultService;
18
- }
19
- export type OwnerPutInput = Omit<VaultPutInput, "workspaceId" | "principalId">;
20
- /** Fixed owner scope still preserves feature ownership, which the copy contract authenticates. */
21
- export declare function ownerContext(input: Pick<VaultContext, "kind" | "ownerKey" | "binding">, _options?: VaultOptions): VaultContext;
22
- /** Composes the existing vault lifecycle and a consumer grant ledger, never another sealer.
23
- * Cross-database copies are individually reported by the vault; callers retry failed rows.
24
- * @example await store.grant({ entryId, consumerId }); await store.syncTo({ target });
25
- */
26
- export declare class OwnerStoreService {
27
- readonly vault: SecretsVaultService;
28
- readonly repo: SqlSecretsVaultRepo;
29
- readonly kernel: StorageKernel<OwnerStoreDatabase>;
30
- private readonly now;
31
- constructor(required: {
32
- kernel: StorageKernel<OwnerStoreDatabase>;
33
- } & Omit<VaultServiceDeps, "repo" | "authorize">, _options?: VaultOptions);
34
- /** Create/replace through vault validation, CAS and encryption; never returns submitted payloads. */
35
- put(input: OwnerPutInput, _options?: VaultOptions): Promise<VaultSummary>;
36
- /** Metadata-only inventory; distinct scopes reuse the vault's authorization and parsing owner.
37
- * @complexity O(n + g) rows and g indexed scope queries, for n entries in g scopes.
38
- */
39
- list(_input: VaultOptions, _options?: VaultOptions): Promise<VaultSummary[]>;
40
- /** Validate existence before granting. Idempotent under the same database writer lock. */
41
- grant(input: {
42
- entryId: string;
43
- consumerId: string;
44
- }, _options?: VaultOptions): Promise<void>;
45
- /** Return only grant metadata, ordered for stable command output. */
46
- grants(_input: VaultOptions, _options?: VaultOptions): Promise<OwnerGrant[]>;
47
- /** Source lock orders sync against replacement/revoke; copies keep their immutable entry IDs.
48
- * @complexity O(n + payload bytes) for this consumer's n granted entries.
49
- */
50
- syncTo({ target }: {
51
- target: OwnerSyncTarget;
52
- }, _options?: VaultOptions): Promise<VaultCopyResult[]>;
53
- /** Revoke centrally even if target cleanup fails. Retrying removes the same copied ID.
54
- * The source lock prevents an in-flight sync from republishing after cleanup.
55
- * @throws Target vault failures after the central revocation has committed.
56
- */
57
- revoke({ entryId, target }: {
58
- entryId: string;
59
- target: OwnerSyncTarget;
60
- }, _options?: VaultOptions): Promise<void>;
61
- /** Require explicit revocation before deletion so copied values cannot become untracked. */
62
- delete(input: {
63
- entryId: string;
64
- expectedRevision: number;
65
- }, _options?: VaultOptions): Promise<boolean>;
66
- /** Resolve the fixed owner row; grants never infer ownership from caller-supplied context. */
67
- private requireEntry;
68
- }
69
- //# sourceMappingURL=service.d.ts.map
@@ -1,122 +0,0 @@
1
- import { SecretsVaultService, isCopyableKind } from "@jini-ai/platform/secrets/credential-sets";
2
- import { VaultError } from "@jini-ai/platform/secrets/credential-sets/contracts";
3
- import { SqlSecretsVaultRepo } from "../secrets-vault/repo.sql.js";
4
- export const OWNER_WORKSPACE_ID = "owner";
5
- /** Fixed owner scope still preserves feature ownership, which the copy contract authenticates. */
6
- export function ownerContext(input, _options = {}) {
7
- return { kind: input.kind, ownerKey: input.ownerKey, binding: input.binding,
8
- workspaceId: OWNER_WORKSPACE_ID, principalId: null };
9
- }
10
- /** Composes the existing vault lifecycle and a consumer grant ledger, never another sealer.
11
- * Cross-database copies are individually reported by the vault; callers retry failed rows.
12
- * @example await store.grant({ entryId, consumerId }); await store.syncTo({ target });
13
- */
14
- export class OwnerStoreService {
15
- vault;
16
- repo;
17
- kernel;
18
- now;
19
- constructor(required, _options = {}) {
20
- this.kernel = required.kernel;
21
- this.now = required.now;
22
- // Kysely's DB generic is invariant. The vault sees only its table on this same transaction owner.
23
- this.repo = new SqlSecretsVaultRepo({ kernel: required.kernel });
24
- this.vault = new SecretsVaultService({ ...required, repo: this.repo, authorize: async ({ context }) => {
25
- if (context.workspaceId !== OWNER_WORKSPACE_ID || context.principalId !== null || !isCopyableKind[context.kind]) {
26
- throw new VaultError({ code: "context" });
27
- }
28
- } });
29
- }
30
- /** Create/replace through vault validation, CAS and encryption; never returns submitted payloads. */
31
- put(input, _options = {}) {
32
- return this.vault.put({ ...input, ...ownerContext(input) });
33
- }
34
- /** Metadata-only inventory; distinct scopes reuse the vault's authorization and parsing owner.
35
- * @complexity O(n + g) rows and g indexed scope queries, for n entries in g scopes.
36
- */
37
- async list(_input, _options = {}) {
38
- const groups = await this.kernel.run(db => db.selectFrom("secrets_vault").select(["kind", "owner_key"])
39
- .where("workspace_id", "=", OWNER_WORKSPACE_ID).distinct().execute());
40
- const entries = [];
41
- for (const group of groups)
42
- entries.push(...await this.vault.list({ ...ownerContext({ kind: group.kind, ownerKey: group.owner_key, binding: null }) }));
43
- return entries;
44
- }
45
- /** Validate existence before granting. Idempotent under the same database writer lock. */
46
- async grant(input, _options = {}) {
47
- if (!input.consumerId)
48
- throw new VaultError({ code: "context" });
49
- await this.kernel.transaction(async () => {
50
- await this.requireEntry(input);
51
- await this.kernel.run(db => db.insertInto("owner_grants").values({ entry_id: input.entryId,
52
- consumer_id: input.consumerId, created_at: this.now({}) })
53
- .onConflict(conflict => conflict.columns(["entry_id", "consumer_id"]).doNothing()).execute());
54
- });
55
- }
56
- /** Return only grant metadata, ordered for stable command output. */
57
- grants(_input, _options = {}) {
58
- return this.kernel.run(db => db.selectFrom("owner_grants").selectAll().orderBy("consumer_id").orderBy("entry_id").execute());
59
- }
60
- /** Source lock orders sync against replacement/revoke; copies keep their immutable entry IDs.
61
- * @complexity O(n + payload bytes) for this consumer's n granted entries.
62
- */
63
- async syncTo({ target }, _options = {}) {
64
- return this.kernel.transaction(async () => {
65
- const grants = await this.kernel.run(db => db.selectFrom("owner_grants").select("entry_id")
66
- .where("consumer_id", "=", target.consumerId).orderBy("entry_id").execute());
67
- const results = [];
68
- for (const grant of grants) {
69
- const entry = await this.requireEntry({ entryId: grant.entry_id });
70
- results.push(...await target.vault.copyToSite({ source: this.vault, sourceContext: ownerContext(entry),
71
- targetContext: { ...ownerContext(entry), workspaceId: target.workspaceId }, ids: [entry.id], overwrite: true }));
72
- }
73
- return results;
74
- });
75
- }
76
- /** Revoke centrally even if target cleanup fails. Retrying removes the same copied ID.
77
- * The source lock prevents an in-flight sync from republishing after cleanup.
78
- * @throws Target vault failures after the central revocation has committed.
79
- */
80
- async revoke({ entryId, target }, _options = {}) {
81
- const outcome = await this.kernel.transaction(async () => {
82
- const entry = await this.requireEntry({ entryId });
83
- await this.kernel.run(db => db.deleteFrom("owner_grants").where("entry_id", "=", entryId)
84
- .where("consumer_id", "=", target.consumerId).execute());
85
- try {
86
- const scope = { ...ownerContext(entry), workspaceId: target.workspaceId };
87
- // Metadata-only lookup: a copy the target can no longer decrypt must still be deleted.
88
- const copied = (await target.vault.list(scope)).find(summary => summary.id === entryId);
89
- if (copied)
90
- await target.vault.delete({ ...scope, id: entryId, expectedRevision: copied.revision });
91
- return { ok: true };
92
- }
93
- catch (error) {
94
- // Committing revocation must not depend on another database's availability.
95
- return { ok: false, error };
96
- }
97
- });
98
- if (!outcome.ok)
99
- throw outcome.error;
100
- }
101
- /** Require explicit revocation before deletion so copied values cannot become untracked. */
102
- async delete(input, _options = {}) {
103
- return this.kernel.transaction(async () => {
104
- const grant = await this.kernel.run(db => db.selectFrom("owner_grants").select("entry_id")
105
- .where("entry_id", "=", input.entryId).executeTakeFirst());
106
- if (grant)
107
- throw new VaultError({ code: "conflict" });
108
- const entry = await this.repo.find({ workspaceId: OWNER_WORKSPACE_ID, id: input.entryId });
109
- if (!entry)
110
- return false;
111
- return this.vault.delete({ ...ownerContext(entry), id: entry.id, expectedRevision: input.expectedRevision });
112
- });
113
- }
114
- /** Resolve the fixed owner row; grants never infer ownership from caller-supplied context. */
115
- async requireEntry({ entryId }) {
116
- const entry = await this.repo.find({ workspaceId: OWNER_WORKSPACE_ID, id: entryId });
117
- if (!entry || entry.principalId !== null || !isCopyableKind[entry.kind])
118
- throw new VaultError({ code: "context" });
119
- return entry;
120
- }
121
- }
122
- //# sourceMappingURL=service.js.map