@jini-ai/db 0.6.11 → 0.6.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ ## 0.6.12
2
+
3
+ ### Patch Changes
4
+
5
+ - db: new `@jini-ai/db/owner-store` entry — owner-only SQLite vault with grants, copy-to-site sync and passphrase-sealed backup (uses the optional `better-sqlite3` peer or an injected opener).
6
+ - @jini-ai/core@0.6.12
7
+
1
8
  ## 0.6.11
2
9
 
3
10
  ### Patch Changes
@@ -0,0 +1,32 @@
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
@@ -0,0 +1,102 @@
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
@@ -0,0 +1,5 @@
1
+ /** Owner-only SQLite store. Native driver dependencies are supplied by the host. */
2
+ export { openOwnerStore, OwnerStoreRecoveryError, type OpenOwnerStoreInput, type OpenOwnerStoreOptions, type OpenedOwnerStore } from "./open.js";
3
+ export { OwnerStoreService, OWNER_WORKSPACE_ID, ownerContext, type OwnerStoreDatabase, type OwnerGrant, type OwnerPutInput, type OwnerSyncTarget } from "./service.js";
4
+ export { exportOwnerStore, restoreOwnerStore, OwnerStoreBackupError } from "./backup.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** Owner-only SQLite store. Native driver dependencies are supplied by the host. */
2
+ export { openOwnerStore, OwnerStoreRecoveryError } from "./open.js";
3
+ export { OwnerStoreService, OWNER_WORKSPACE_ID, ownerContext } from "./service.js";
4
+ export { exportOwnerStore, restoreOwnerStore, OwnerStoreBackupError } from "./backup.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ import type { MigrationStep } from "../../migrate/step.js";
2
+ /** Owner-only history: no site tables or foreign workspace records are required. */
3
+ export declare const ownerStoreDdl = "\nCREATE TABLE secrets_vault (\n workspace_id TEXT NOT NULL, id TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, owner_key TEXT NOT NULL,\n principal_id TEXT, binding TEXT, provider TEXT, label TEXT NOT NULL, is_default INTEGER NOT NULL,\n revision INTEGER NOT NULL, sealed_key_id TEXT, sealed_ciphertext TEXT, sealed_nonce TEXT, sealed_alg TEXT,\n last4 TEXT, token_length INTEGER, meta TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n PRIMARY KEY (workspace_id, id)\n);\nCREATE UNIQUE INDEX owner_vault_default ON secrets_vault\n (workspace_id, kind, owner_key, (principal_id IS NULL), coalesce(principal_id, ''),\n (provider IS NULL), coalesce(provider, '')) WHERE is_default = 1;\nCREATE UNIQUE INDEX owner_vault_label ON secrets_vault\n (workspace_id, kind, owner_key, (principal_id IS NULL), coalesce(principal_id, ''),\n (provider IS NULL), coalesce(provider, ''), label);\nCREATE INDEX owner_vault_lookup ON secrets_vault\n (workspace_id, kind, owner_key, principal_id, provider, is_default);\nCREATE INDEX owner_vault_promotion ON secrets_vault\n (workspace_id, kind, owner_key, principal_id, provider, updated_at DESC, id COLLATE BINARY DESC);\nCREATE TABLE owner_grants (\n entry_id TEXT NOT NULL REFERENCES secrets_vault(id) ON DELETE CASCADE,\n consumer_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (entry_id, consumer_id)\n);\nCREATE INDEX owner_grants_consumer ON owner_grants (consumer_id, entry_id);\n";
4
+ /** Pin is checked against the DDL in tests; never edit this step after publication. */
5
+ export declare const ownerStoreMigration: MigrationStep;
6
+ //# sourceMappingURL=0000_owner_store.d.ts.map
@@ -0,0 +1,39 @@
1
+ import { sql } from "kysely";
2
+ /** Owner-only history: no site tables or foreign workspace records are required. */
3
+ export const ownerStoreDdl = `
4
+ CREATE TABLE secrets_vault (
5
+ workspace_id TEXT NOT NULL, id TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, owner_key TEXT NOT NULL,
6
+ principal_id TEXT, binding TEXT, provider TEXT, label TEXT NOT NULL, is_default INTEGER NOT NULL,
7
+ revision INTEGER NOT NULL, sealed_key_id TEXT, sealed_ciphertext TEXT, sealed_nonce TEXT, sealed_alg TEXT,
8
+ last4 TEXT, token_length INTEGER, meta TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
9
+ PRIMARY KEY (workspace_id, id)
10
+ );
11
+ CREATE UNIQUE INDEX owner_vault_default ON secrets_vault
12
+ (workspace_id, kind, owner_key, (principal_id IS NULL), coalesce(principal_id, ''),
13
+ (provider IS NULL), coalesce(provider, '')) WHERE is_default = 1;
14
+ CREATE UNIQUE INDEX owner_vault_label ON secrets_vault
15
+ (workspace_id, kind, owner_key, (principal_id IS NULL), coalesce(principal_id, ''),
16
+ (provider IS NULL), coalesce(provider, ''), label);
17
+ CREATE INDEX owner_vault_lookup ON secrets_vault
18
+ (workspace_id, kind, owner_key, principal_id, provider, is_default);
19
+ CREATE INDEX owner_vault_promotion ON secrets_vault
20
+ (workspace_id, kind, owner_key, principal_id, provider, updated_at DESC, id COLLATE BINARY DESC);
21
+ CREATE TABLE owner_grants (
22
+ entry_id TEXT NOT NULL REFERENCES secrets_vault(id) ON DELETE CASCADE,
23
+ consumer_id TEXT NOT NULL, created_at TEXT NOT NULL,
24
+ PRIMARY KEY (entry_id, consumer_id)
25
+ );
26
+ CREATE INDEX owner_grants_consumer ON owner_grants (consumer_id, entry_id);
27
+ `;
28
+ /** Pin is checked against the DDL in tests; never edit this step after publication. */
29
+ export const ownerStoreMigration = {
30
+ id: "0000_owner_store",
31
+ checksum: "ea2c33cf1835f6b1db0f52a4de3419aaf8c1a2e2edeece1e2b3240c517592446",
32
+ async up(kernel) {
33
+ // Kysely executes one SQLite statement at a time; the runner owns the encompassing transaction.
34
+ for (const statement of ownerStoreDdl.split(";").filter(part => part.trim())) {
35
+ await kernel.execute(sql.raw(statement));
36
+ }
37
+ },
38
+ };
39
+ //# sourceMappingURL=0000_owner_store.js.map
@@ -0,0 +1,4 @@
1
+ /** Independent history: a site migration ledger must never govern this database. */
2
+ export declare const OWNER_STORE_LEDGER = "owner_migrations";
3
+ export declare const ownerStoreMigrations: readonly [import("../../migrate/step.js").MigrationStep];
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ import { ownerStoreMigration } from "./0000_owner_store.js";
2
+ /** Independent history: a site migration ledger must never govern this database. */
3
+ export const OWNER_STORE_LEDGER = "owner_migrations";
4
+ export const ownerStoreMigrations = [ownerStoreMigration];
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,25 @@
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
@@ -0,0 +1,73 @@
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
@@ -0,0 +1,69 @@
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
@@ -0,0 +1,122 @@
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/db",
3
- "version": "0.6.11",
3
+ "version": "0.6.12",
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": {
@@ -113,6 +113,11 @@
113
113
  "import": "./dist/recovery/index.js",
114
114
  "default": "./dist/recovery/index.js"
115
115
  },
116
+ "./owner-store": {
117
+ "types": "./dist/owner-store/index.d.ts",
118
+ "import": "./dist/owner-store/index.js",
119
+ "default": "./dist/owner-store/index.js"
120
+ },
116
121
  "./secrets-vault": {
117
122
  "types": "./dist/secrets-vault/index.d.ts",
118
123
  "import": "./dist/secrets-vault/index.js",
@@ -169,6 +174,9 @@
169
174
  "recovery": [
170
175
  "./dist/recovery/index.d.ts"
171
176
  ],
177
+ "owner-store": [
178
+ "./dist/owner-store/index.d.ts"
179
+ ],
172
180
  "secrets-vault": [
173
181
  "./dist/secrets-vault/index.d.ts"
174
182
  ]
@@ -192,7 +200,7 @@
192
200
  "registry": "https://registry.npmjs.org"
193
201
  },
194
202
  "dependencies": {
195
- "@jini-ai/core": "^0.6.11"
203
+ "@jini-ai/core": "^0.6.12"
196
204
  },
197
205
  "peerDependencies": {
198
206
  "kysely": "^0.29.6",
@@ -226,8 +234,8 @@
226
234
  "better-sqlite3": "13.0.3",
227
235
  "kysely": "0.29.6",
228
236
  "pg": "8.23.0",
229
- "@jini-ai/platform": "0.6.11",
230
- "@jini-ai/core": "0.6.11"
237
+ "@jini-ai/core": "0.6.12",
238
+ "@jini-ai/platform": "0.6.12"
231
239
  },
232
240
  "scripts": {
233
241
  "build": "tsc -p tsconfig.build.json",