@jini-ai/db 0.3.0 → 0.3.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 (63) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/core/artifact-naming.d.ts +4 -1
  3. package/dist/core/artifact-naming.js +3 -4
  4. package/dist/core/index.d.ts +1 -0
  5. package/dist/core/messages.d.ts +1 -1
  6. package/dist/core/pg-types.d.ts +52 -0
  7. package/dist/core/pg-types.js +8 -0
  8. package/dist/core/transfer-naming.d.ts +10 -0
  9. package/dist/core/transfer-naming.js +2 -0
  10. package/dist/kernel/postgres/driver.d.ts +1 -1
  11. package/dist/kernel/postgres/driver.js +1 -1
  12. package/dist/kernel/postgres/pglite-socket.d.ts +1 -1
  13. package/dist/kernel/postgres/pglite-socket.js +1 -1
  14. package/dist/pg-fixture.d.ts +50 -0
  15. package/dist/pg-fixture.js +84 -0
  16. package/dist/pglite/owner.js +7 -0
  17. package/dist/postgres/index.d.ts +1 -1
  18. package/dist/postgres/index.js +1 -1
  19. package/dist/postgres/types.d.ts +1 -52
  20. package/dist/postgres/types.js +2 -13
  21. package/dist/recovery/deep-link.d.ts +60 -0
  22. package/dist/recovery/deep-link.js +16 -0
  23. package/dist/recovery/degraded-banners.d.ts +40 -0
  24. package/dist/recovery/degraded-banners.js +69 -0
  25. package/dist/recovery/disclosure.d.ts +58 -0
  26. package/dist/recovery/disclosure.js +55 -0
  27. package/dist/recovery/evaluate-boot-migration-policy.d.ts +41 -0
  28. package/dist/recovery/evaluate-boot-migration-policy.js +50 -0
  29. package/dist/recovery/hook-policy.d.ts +9 -0
  30. package/dist/recovery/hook-policy.js +2 -0
  31. package/dist/recovery/index.d.ts +15 -0
  32. package/dist/recovery/index.js +13 -0
  33. package/dist/recovery/lookup-adapters.d.ts +40 -0
  34. package/dist/recovery/lookup-adapters.js +44 -0
  35. package/dist/recovery/migrate-forward-execute.d.ts +65 -0
  36. package/dist/recovery/migrate-forward-execute.js +68 -0
  37. package/dist/recovery/migrate-forward-hooks.d.ts +118 -0
  38. package/dist/recovery/migrate-forward-hooks.js +85 -0
  39. package/dist/recovery/operation-lock.d.ts +78 -0
  40. package/dist/recovery/operation-lock.js +58 -0
  41. package/dist/recovery/reconcile-interrupted-migration.d.ts +73 -0
  42. package/dist/recovery/reconcile-interrupted-migration.js +47 -0
  43. package/dist/recovery/recovery-orchestrator.d.ts +204 -0
  44. package/dist/recovery/recovery-orchestrator.js +96 -0
  45. package/dist/recovery/restore-hooks.d.ts +105 -0
  46. package/dist/recovery/restore-hooks.js +154 -0
  47. package/dist/recovery/restore-point-create.d.ts +80 -0
  48. package/dist/recovery/restore-point-create.js +37 -0
  49. package/dist/secrets-vault/index.d.ts +2 -0
  50. package/dist/secrets-vault/index.js +2 -0
  51. package/dist/secrets-vault/repo.sql.d.ts +82 -0
  52. package/dist/secrets-vault/repo.sql.js +176 -0
  53. package/dist/sqlite/inspect.d.ts +5 -1
  54. package/dist/sqlite/inspect.js +47 -18
  55. package/dist/sqlite/open.d.ts +1 -1
  56. package/dist/sqlite/open.js +3 -3
  57. package/dist/sqlite/restore-types.d.ts +7 -3
  58. package/dist/tools/surface-port.d.ts +11 -35
  59. package/dist/tools/transfer-tools.js +36 -37
  60. package/dist/transfer/internal-ddl.d.ts +3 -0
  61. package/dist/transfer/internal-ddl.js +6 -2
  62. package/dist/transfer/types.d.ts +6 -9
  63. package/package.json +57 -6
@@ -0,0 +1,105 @@
1
+ import type { Clock as ClockPort, IdGenerator as IdGeneratorPort } from "@jini-ai/core/primitives";
2
+ import { type GatedMutationHooks } from "@jini-ai/core/gated-mutations";
3
+ import type { RecoveryHookPolicy } from "./hook-policy.js";
4
+ import type { MigrationRunsRepoPort, SiteStatusPort } from "./reconcile-interrupted-migration.js";
5
+ import type { LedgerAppendPort } from "./migrate-forward-hooks.js";
6
+ /**
7
+ * @file Recovery's `GatedMutationHooks` factory for the `restore` ceremony (SPEC-019 C-301/C-303),
8
+ * plus `toRecoveryResult` (the throwing-gateway-to-`Result` adapter `recovery-orchestrator.ts`'s
9
+ * ports declare) — the domain-specific quarter of what used to be
10
+ * `server/gated-mutations-composition.ts`, split out so Recovery no longer needs a back-edge into
11
+ * `server/` for its own hook builder. The generic pieces every ceremony shares (`buildGatewayDeps`,
12
+ * `planHashOf`, `resolveActorClassIdentity`, `buildConfirmOnlyHooks`) stayed in
13
+ * `core/gated-mutations/composition.ts`, which this file imports from — the correct direction (a
14
+ * domain depending on `core`), unlike the old direction (a domain depending on `server`).
15
+ *
16
+ * `LedgerAppendPort` is imported from `features/database/gated-hooks.ts` rather than duplicated —
17
+ * Recovery already imports several other Database-owned ports (`restore-points.ts`,
18
+ * `boot/reconcile-interrupted-migration.ts`), so this is the established "Recovery depends on
19
+ * Database, never the reverse" direction, not a new one.
20
+ */
21
+ export interface BuildRestoreHooksInput extends RecoveryHookPolicy {
22
+ workspaceId: string;
23
+ actorId: string;
24
+ restorePointId: string;
25
+ clock: ClockPort;
26
+ idGen: IdGeneratorPort;
27
+ restorePointsRepo: {
28
+ list(): Promise<Array<{
29
+ id: string;
30
+ createdAt: string;
31
+ artifactRef: string;
32
+ }>>;
33
+ };
34
+ databaseLedgerRepo: LedgerAppendPort;
35
+ /** SPEC-016 `DbOpsPort` — real (SQLite) composition performs the physical file swap;
36
+ * hermetic-test composition's in-memory double is a no-op (`restartRequired: false`). */
37
+ dbOps: {
38
+ restoreFromArtifact(required: {
39
+ artifactRef: string;
40
+ }): Promise<{
41
+ restartRequired: boolean;
42
+ }>;
43
+ };
44
+ /** Round-5 re-audit (2026-07-16, TM-adr041-043-044-045-audit-001, R5-F2 / Fable
45
+ * `R5-F2-BLOCK-HAS-NO-EXIT` fix): a successful restore must actually exit
46
+ * `BLOCKED_PENDING_RECOVERY` — before this fix, nothing did. */
47
+ migrationRunsRepo: Pick<MigrationRunsRepoPort, "findNonTerminalForSite" | "markResolved">;
48
+ siteStatus: SiteStatusPort;
49
+ }
50
+ export declare class RestorePointNotFoundError extends Error {
51
+ constructor(message: string);
52
+ }
53
+ /**
54
+ * SPEC-019 C-301/C-303 — the Recovery `restore` ceremony's `GatedMutationHooks`.
55
+ *
56
+ * `executeMutation()` is a deliberately, disclosedly SCOPED implementation: it validates the
57
+ * target restore point still exists and records a real `restore.executed` `database_ledger` row —
58
+ * the honest, auditable half of a restore. It does NOT physically overwrite the live `content.db`
59
+ * file. This codebase has no mechanism to hot-swap the shared, already-open `content.db`
60
+ * connection every other repo across `server/deps.ts` holds a reference to (doing so would either
61
+ * crash every other in-flight request against a closed handle, or silently leave every existing
62
+ * repo instance reading the stale pre-restore file) — inventing an unreviewed live-swap or
63
+ * process-restart mechanism here is exactly the kind of unrequested architecture this dispatch's
64
+ * own guardrails warn against, and ADR-041/ADR-045 do not pin a specific mechanism for it either.
65
+ * `[CIC_REQUESTED]` Unit=gated-mutations-composition Trigger=recovery restore execute
66
+ * Property=REQ-06/AC-XX "a confirmed restore actually replaces content.db's data"
67
+ * PlausibleWrong=silently faking a full hot restore, or crashing the process mid-request
68
+ * MissingConstraint=a defined live-swap-or-restart mechanism for the shared `content.db`
69
+ * connection Evidence=ADR-041 §2 (`content.db` restore = whole-file copy), ADR-045 §3, this file.
70
+ * The plan -> confirm -> execute ceremony itself (token flow, authorize, operation-lock,
71
+ * disclosure-acknowledgment gate) is fully real and this file's own test coverage exercises it
72
+ * end-to-end; only the final byte-for-byte file replacement is the disclosed gap.
73
+ *
74
+ * `scopeKind: "instance"` (internal audit, 2026-08-12): `dbOps.restoreFromArtifact` (`db/sqlite/
75
+ * db-ops.ts`) physically swaps the entire `content.db` file, and a `content.db` can hold more
76
+ * than one workspace row (`site-dir/resolve-workspace.ts`, ADR-007, SPEC-044's admin CRUD). A
77
+ * principal authorized only within one workspace has no standing to replace data belonging to
78
+ * every OTHER workspace that file also holds — the ordinary workspace-scoped `authorize()` this
79
+ * hook used before would either deny every principal (no real workspace ever matches a
80
+ * whole-instance operation) or let one workspace's admin approve a cross-tenant file swap. See
81
+ * `core/gated-mutations/gateway.ts`'s `GatedMutationHooks.scopeKind` and `core/gated-mutations/
82
+ * composition.ts`'s `buildOwnerOnlyInstanceAuthorize` for the evaluator this now routes through.
83
+ *
84
+ * @complexity O(n) in the number of restore points (one `list()` scan per `computePlan` and per
85
+ * `executeMutation` — low-volume, ADR-041 §2).
86
+ */
87
+ export declare function buildRestoreHooks(input: BuildRestoreHooksInput, _optional?: Record<string, never>): GatedMutationHooks<{
88
+ restorePointId: string;
89
+ }, {
90
+ restoreRunId: string;
91
+ state: string;
92
+ restartRequired: boolean;
93
+ }>;
94
+ export type { RecoveryErrorPayload } from "./recovery-orchestrator.js";
95
+ import type { RecoveryErrorPayload } from "./recovery-orchestrator.js";
96
+ export declare function toRecoveryResult<T>({ run }: {
97
+ run: () => Promise<T>;
98
+ }, _optional?: Record<string, never>): Promise<{
99
+ ok: true;
100
+ value: T;
101
+ } | {
102
+ ok: false;
103
+ error: RecoveryErrorPayload;
104
+ }>;
105
+ //# sourceMappingURL=restore-hooks.d.ts.map
@@ -0,0 +1,154 @@
1
+ import { nowIso as clockNowIso } from "@jini-ai/core/primitives";
2
+ import { ForbiddenError, PlanStaleError, } from "@jini-ai/core/gated-mutations";
3
+ import { TokenAlreadyRedeemedError, TokenExpiredError } from "@jini-ai/core/gated-mutations";
4
+ export class RestorePointNotFoundError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "RestorePointNotFoundError";
8
+ }
9
+ }
10
+ /**
11
+ * SPEC-019 C-301/C-303 — the Recovery `restore` ceremony's `GatedMutationHooks`.
12
+ *
13
+ * `executeMutation()` is a deliberately, disclosedly SCOPED implementation: it validates the
14
+ * target restore point still exists and records a real `restore.executed` `database_ledger` row —
15
+ * the honest, auditable half of a restore. It does NOT physically overwrite the live `content.db`
16
+ * file. This codebase has no mechanism to hot-swap the shared, already-open `content.db`
17
+ * connection every other repo across `server/deps.ts` holds a reference to (doing so would either
18
+ * crash every other in-flight request against a closed handle, or silently leave every existing
19
+ * repo instance reading the stale pre-restore file) — inventing an unreviewed live-swap or
20
+ * process-restart mechanism here is exactly the kind of unrequested architecture this dispatch's
21
+ * own guardrails warn against, and ADR-041/ADR-045 do not pin a specific mechanism for it either.
22
+ * `[CIC_REQUESTED]` Unit=gated-mutations-composition Trigger=recovery restore execute
23
+ * Property=REQ-06/AC-XX "a confirmed restore actually replaces content.db's data"
24
+ * PlausibleWrong=silently faking a full hot restore, or crashing the process mid-request
25
+ * MissingConstraint=a defined live-swap-or-restart mechanism for the shared `content.db`
26
+ * connection Evidence=ADR-041 §2 (`content.db` restore = whole-file copy), ADR-045 §3, this file.
27
+ * The plan -> confirm -> execute ceremony itself (token flow, authorize, operation-lock,
28
+ * disclosure-acknowledgment gate) is fully real and this file's own test coverage exercises it
29
+ * end-to-end; only the final byte-for-byte file replacement is the disclosed gap.
30
+ *
31
+ * `scopeKind: "instance"` (internal audit, 2026-08-12): `dbOps.restoreFromArtifact` (`db/sqlite/
32
+ * db-ops.ts`) physically swaps the entire `content.db` file, and a `content.db` can hold more
33
+ * than one workspace row (`site-dir/resolve-workspace.ts`, ADR-007, SPEC-044's admin CRUD). A
34
+ * principal authorized only within one workspace has no standing to replace data belonging to
35
+ * every OTHER workspace that file also holds — the ordinary workspace-scoped `authorize()` this
36
+ * hook used before would either deny every principal (no real workspace ever matches a
37
+ * whole-instance operation) or let one workspace's admin approve a cross-tenant file swap. See
38
+ * `core/gated-mutations/gateway.ts`'s `GatedMutationHooks.scopeKind` and `core/gated-mutations/
39
+ * composition.ts`'s `buildOwnerOnlyInstanceAuthorize` for the evaluator this now routes through.
40
+ *
41
+ * @complexity O(n) in the number of restore points (one `list()` scan per `computePlan` and per
42
+ * `executeMutation` — low-volume, ADR-041 §2).
43
+ */
44
+ export function buildRestoreHooks(input, _optional = {}) {
45
+ return {
46
+ domain: "backup.restore",
47
+ readPermission: "backup.read",
48
+ mutatePermission: "backup.restore",
49
+ scopeId: input.workspaceId,
50
+ scopeKind: "instance",
51
+ // The plan refuses an unknown restore point itself: without this, a wrong id passed plan AND
52
+ // confirm (minting a real token) and only failed at execute. The gateway re-runs this at
53
+ // execute's plan re-derivation too, so a point deleted after confirm is caught there.
54
+ computePlan: async () => {
55
+ await findRestorePoint(input);
56
+ const details = { restorePointId: input.restorePointId };
57
+ return { planHash: input.planHashOf({ details }, {}), details };
58
+ },
59
+ executeMutation: async () => {
60
+ // Re-checked here, not trusted from the plan: the point can be deleted between execute's
61
+ // plan re-derivation and this mutation (token redemption runs in between).
62
+ const target = await findRestorePoint(input);
63
+ // 2026-07-16: closes the "ledger-only" gap this file previously disclosed — swap the file
64
+ // FIRST, ledger-record second. If the process dies between the two, the file already
65
+ // reflects reality (a missing ledger entry is reconcilable later; a ledger entry claiming a
66
+ // restore that never physically happened would not be).
67
+ const { restartRequired } = await input.dbOps.restoreFromArtifact({ artifactRef: target.artifactRef });
68
+ const restoreRunId = input.idGen.newId();
69
+ const now = clockNowIso({ clock: input.clock });
70
+ await input.databaseLedgerRepo.append({
71
+ id: input.idGen.newId(),
72
+ kind: "restore.executed",
73
+ restorePointId: input.restorePointId,
74
+ outcome: "success",
75
+ detailJson: JSON.stringify({ restoreRunId, restartRequired }),
76
+ actorWorkspaceId: input.workspaceId,
77
+ actorId: input.actorId,
78
+ createdAt: now,
79
+ });
80
+ // Round-5 re-audit (TM-adr041-043-044-045-audit-001, R5-F2 fix): a successful restore is the
81
+ // ceremony ADR-041 §3's own text names as how an operator "resolves" a crash-interrupted
82
+ // migration -- so it must actually exit BLOCKED_PENDING_RECOVERY, not just record a ledger
83
+ // row. Terminalize whatever non-terminal migration_runs row exists for this site (if any --
84
+ // a restore can also be run for reasons unrelated to a crash-interrupted migration, in which
85
+ // case there is nothing to resolve) so the next boot's findNonTerminalForSite no longer
86
+ // re-detects it.
87
+ //
88
+ // Round-6 re-audit (TM-adr041-043-044-045-audit-001, codex `R6-F1-RESTART-REQUIRED-RESTORE-
89
+ // UNBLOCKS-STALE-DB`, verified directly against `db-ops.ts`'s own doc comment): the DURABLE
90
+ // resolution (markResolved) and the IN-PROCESS unblock (siteStatus.set) are NOT the same
91
+ // thing and must not be conflated. `SqliteDbOpsAdapter.restoreFromArtifact` always returns
92
+ // `restartRequired: true` for a real file-backed db -- the running process keeps its open
93
+ // file descriptor pointed at the now-unlinked OLD inode until it restarts, so clearing the
94
+ // gate in-process here would let normal traffic resume against stale pre-restore data, with
95
+ // writes accepted in that window silently lost on the eventual restart. Only clear the
96
+ // in-process block when the restore genuinely didn't require one (memory-mode dev, or a
97
+ // future adapter that can restore live) -- when a restart IS required, the durable
98
+ // terminalization above is what makes the NEXT boot resolve to SERVING; the running process
99
+ // stays blocked (correctly) until then.
100
+ const nonTerminal = await input.migrationRunsRepo.findNonTerminalForSite(input.workspaceId);
101
+ if (nonTerminal) {
102
+ await input.migrationRunsRepo.markResolved({ id: nonTerminal.id });
103
+ if (!restartRequired) {
104
+ await input.siteStatus.set(input.workspaceId, "SERVING");
105
+ }
106
+ }
107
+ return { restoreRunId, state: "RESTORED", restartRequired };
108
+ },
109
+ resolveActorClassIdentity: input.resolveActorClassIdentity,
110
+ };
111
+ }
112
+ /** Looks up the restore point `input.restorePointId` names, throwing `RestorePointNotFoundError`
113
+ * when it does not exist. @complexity O(n) in restore points (one `list()` scan). */
114
+ async function findRestorePoint(input) {
115
+ const points = await input.restorePointsRepo.list();
116
+ const target = points.find((p) => p.id === input.restorePointId);
117
+ if (!target) {
118
+ throw new RestorePointNotFoundError(`restore point '${input.restorePointId}' was not found`);
119
+ }
120
+ return target;
121
+ }
122
+ /**
123
+ * Adapts a throwing call against the real (throwing) `core/gated-mutations` gateway into the
124
+ * `Result<T, RecoveryErrorPayload>` shape `features/recovery/recovery-orchestrator.ts`'s
125
+ * `PlanRestoreGatewayPort`/`ConfirmRestoreGatewayPort`/`ExecuteRestoreGatewayPort` all declare —
126
+ * exactly the "Result-wrapped composition-root binding over the real throwing gateway" Session 4's
127
+ * progress-ledger entry named as still-owed future work. Maps each of `gateway.ts`'s typed thrown
128
+ * errors to a stable `code` string; every other error collapses to `INTERNAL_ERROR`.
129
+ */
130
+ /** Maps one caught error to its stable `code` string — split out of {@link toRecoveryResult}'s
131
+ * `catch` block as a whole unit, not just its branchiest arm, since every arm here pays the same
132
+ * nesting cost inside a `catch`. */
133
+ function classifyRecoveryError(err) {
134
+ if (err instanceof ForbiddenError)
135
+ return { code: err.reasonCode, message: err.message };
136
+ if (err instanceof PlanStaleError)
137
+ return { code: "PLAN_STALE", message: err.message };
138
+ if (err instanceof TokenExpiredError)
139
+ return { code: "TOKEN_EXPIRED", message: err.message };
140
+ if (err instanceof TokenAlreadyRedeemedError)
141
+ return { code: "TOKEN_ALREADY_REDEEMED", message: err.message };
142
+ if (err instanceof RestorePointNotFoundError)
143
+ return { code: "RESTORE_POINT_NOT_FOUND", message: err.message };
144
+ return { code: "INTERNAL_ERROR", message: err instanceof Error ? err.message : "internal error" };
145
+ }
146
+ export async function toRecoveryResult({ run }, _optional = {}) {
147
+ try {
148
+ return { ok: true, value: await run() };
149
+ }
150
+ catch (err) {
151
+ return { ok: false, error: classifyRecoveryError(err) };
152
+ }
153
+ }
154
+ //# sourceMappingURL=restore-hooks.js.map
@@ -0,0 +1,80 @@
1
+ import type { PrincipalKind, Result } from "./recovery-orchestrator.js";
2
+ /**
3
+ * @file SPEC-019 C-304 / REQ-05 — `createRestorePoint`, an ordinary `authorize()`-gated mutation
4
+ * (ADR-045 §3, "backup.create" independent of any migration).
5
+ *
6
+ * Purpose:
7
+ * Structurally distinct from the gated restore ceremony (`recovery-orchestrator.ts`): this never
8
+ * calls the gateway's `plan()`/`confirm()`/`execute()` at all (AC-10) — it mints a restore point
9
+ * directly once `authorize()` and the shared-lock "no operation in flight" check both pass.
10
+ * `authorize()` runs on EVERY call, before the idempotency short-circuit (AC-11, SPEC-016 REQ-14)
11
+ * — a repeated idempotency key never skips re-authorization, only re-creation.
12
+ *
13
+ * How it relates to the project:
14
+ * `operationInFlight` is supplied by the caller (typically derived from the same shared
15
+ * `core/operation-lock` state `recovery-orchestrator.ts`'s `executeRestore` consults) rather than
16
+ * this module acquiring the lock itself — REQ-13's "extends here too, via `onBeforeCreateOrExecute`"
17
+ * is a pre-check on an already-resolved flag, not this module owning lock lifecycle.
18
+ */
19
+ export interface CreateRestorePointRepoPort {
20
+ save(row: {
21
+ restorePointId: string;
22
+ idempotencyKey: string;
23
+ trigger: string;
24
+ createdAt: string;
25
+ createdBy: string;
26
+ }): Promise<void>;
27
+ findByIdempotencyKey(key: string): Promise<{
28
+ restorePointId: string;
29
+ idempotencyKey: string;
30
+ } | null>;
31
+ }
32
+ export interface CreateRestorePointClockPort {
33
+ nowIso(): string;
34
+ }
35
+ export interface CreateRestorePointIdPort {
36
+ newId(): string;
37
+ }
38
+ export type CreateRestorePointAuthorizeFn = (params: {
39
+ principalId: string;
40
+ permission: string;
41
+ }) => Promise<{
42
+ allowed: boolean;
43
+ reason: string;
44
+ }>;
45
+ export interface CreateRestorePointRequired {
46
+ deps: {
47
+ repo: CreateRestorePointRepoPort;
48
+ clock: CreateRestorePointClockPort;
49
+ ids: CreateRestorePointIdPort;
50
+ authorize: CreateRestorePointAuthorizeFn;
51
+ /** Present in the seam for shape-parity with the gated ceremony's deps; deliberately never
52
+ * called here (AC-10) — kept so a caller wiring a shared deps object cannot be tempted to
53
+ * route restore-point creation through it. */
54
+ gateway: {
55
+ plan: (...args: unknown[]) => Promise<unknown>;
56
+ };
57
+ };
58
+ input: {
59
+ principalId: string;
60
+ principalKind: PrincipalKind;
61
+ idempotencyKey: string;
62
+ trigger: "manual" | "pre-migration-auto" | "template-upgrade";
63
+ operationInFlight: boolean;
64
+ };
65
+ }
66
+ export interface CreateRestorePointValue {
67
+ restorePointId: string;
68
+ }
69
+ /**
70
+ * AC-10/AC-11/REQ-05/REQ-13 — authorize (always) -> in-flight refusal -> idempotency lookup ->
71
+ * write. Never invokes `deps.gateway` at all.
72
+ *
73
+ * @complexity O(1) plus one `authorize()` call, one idempotency lookup, and (on the first call for
74
+ * a given key) one `repo.save()` call.
75
+ */
76
+ export declare function createRestorePoint(required: CreateRestorePointRequired, _optional?: Record<string, never>): Promise<Result<CreateRestorePointValue, {
77
+ code: string;
78
+ message?: string;
79
+ }>>;
80
+ //# sourceMappingURL=restore-point-create.d.ts.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * AC-10/AC-11/REQ-05/REQ-13 — authorize (always) -> in-flight refusal -> idempotency lookup ->
3
+ * write. Never invokes `deps.gateway` at all.
4
+ *
5
+ * @complexity O(1) plus one `authorize()` call, one idempotency lookup, and (on the first call for
6
+ * a given key) one `repo.save()` call.
7
+ */
8
+ export async function createRestorePoint(required, _optional = {}) {
9
+ const { deps, input } = required;
10
+ const authResult = await deps.authorize({ principalId: input.principalId, permission: "backup.create" });
11
+ if (!authResult.allowed) {
12
+ return { ok: false, error: { code: "FORBIDDEN", message: authResult.reason } };
13
+ }
14
+ if (input.operationInFlight) {
15
+ return {
16
+ ok: false,
17
+ error: {
18
+ code: "RESTORE_OPERATION_IN_FLIGHT",
19
+ message: "a migration or restore is already in flight for this site",
20
+ },
21
+ };
22
+ }
23
+ const existing = await deps.repo.findByIdempotencyKey(input.idempotencyKey);
24
+ if (existing) {
25
+ return { ok: true, value: { restorePointId: existing.restorePointId } };
26
+ }
27
+ const restorePointId = deps.ids.newId();
28
+ await deps.repo.save({
29
+ restorePointId,
30
+ idempotencyKey: input.idempotencyKey,
31
+ trigger: input.trigger,
32
+ createdAt: deps.clock.nowIso(),
33
+ createdBy: input.principalId,
34
+ });
35
+ return { ok: true, value: { restorePointId } };
36
+ }
37
+ //# sourceMappingURL=restore-point-create.js.map
@@ -0,0 +1,2 @@
1
+ export { SqlSecretsVaultRepo, type SecretsVaultTable, type SecretsVaultDatabase } from "./repo.sql.js";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,2 @@
1
+ export { SqlSecretsVaultRepo } from "./repo.sql.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,82 @@
1
+ import { type VaultBatchOp, type VaultBatchResult, type VaultDefaultQuery, type VaultSingletonQuery, type VaultMeta, type VaultOptions, type VaultQuery, type VaultRecord, type VaultRepoPort } from "@jini-ai/platform/secrets/credential-sets";
2
+ import type { StorageKernel } from "../kernel/port.js";
3
+ /** Fixed columns consumed by the adapter; hosts own DDL, foreign keys and migration provenance.
4
+ * A partial unique default index and label index use the same scope as VaultRepoPort.
5
+ * Nullable principal/provider scope columns must be normalized in those index expressions.
6
+ * Read indexes: (workspace_id,kind,owner_key,principal_id,provider,is_default), and the same
7
+ * group prefix plus (updated_at DESC,id DESC) with binary/C ID collation for promotion.
8
+ * Singleton reads use the lookup index's (workspace_id,kind) prefix, optionally owner/principal.
9
+ */
10
+ export interface SecretsVaultTable {
11
+ workspace_id: string;
12
+ id: string;
13
+ kind: VaultRecord["kind"];
14
+ owner_key: string;
15
+ principal_id: string | null;
16
+ binding: string | null;
17
+ provider: string | null;
18
+ label: string;
19
+ is_default: boolean | number;
20
+ revision: number;
21
+ sealed_key_id: string | null;
22
+ sealed_ciphertext: string | null;
23
+ sealed_nonce: string | null;
24
+ sealed_alg: string | null;
25
+ last4: string | null;
26
+ token_length: number | null;
27
+ meta: string | VaultMeta;
28
+ created_at: string;
29
+ updated_at: string;
30
+ }
31
+ export interface SecretsVaultDatabase {
32
+ secrets_vault: SecretsVaultTable;
33
+ }
34
+ /** One Kysely adapter for SQLite and Postgres/PGlite. Workspace lock `secrets_vault:<workspaceId>`
35
+ * serializes every writer, including targeted patches and boot rotation. Nested transactions join
36
+ * the host's transaction, allowing MCP payload/pointer/status writes to commit together.
37
+ */
38
+ export declare class SqlSecretsVaultRepo implements VaultRepoPort {
39
+ private readonly kernel;
40
+ constructor({ kernel }: {
41
+ kernel: StorageKernel<SecretsVaultDatabase>;
42
+ }, _options?: VaultOptions);
43
+ private write;
44
+ private group;
45
+ private scoped;
46
+ find(input: {
47
+ workspaceId: string;
48
+ id: string;
49
+ }, _options?: VaultOptions): Promise<VaultRecord | null>;
50
+ /** One indexed singleton SELECT; provider/default never participate in this lookup. */
51
+ findOne(input: VaultSingletonQuery, _options?: VaultOptions): Promise<VaultRecord | null>;
52
+ /** One kernel transaction; nested mutations join it and retain their CAS/default owner.
53
+ * Lock every workspace in sorted order before writes to avoid opposite-order batch deadlocks.
54
+ * Failures must escape a surrounding host transaction (the kernel does not use savepoints).
55
+ */
56
+ applyBatch({ ops }: {
57
+ ops: readonly VaultBatchOp[];
58
+ }, _options?: VaultOptions): Promise<VaultBatchResult[]>;
59
+ /** One indexed exact-group lookup; ciphertext is loaded only for the chosen default. */
60
+ findDefault(input: VaultDefaultQuery, _options?: VaultOptions): Promise<VaultRecord | null>;
61
+ list(input: VaultQuery, _options?: VaultOptions): Promise<VaultRecord[]>;
62
+ put(input: {
63
+ record: VaultRecord;
64
+ expectedRevision: number | null;
65
+ }, _options?: VaultOptions): Promise<VaultRecord>;
66
+ /** Top-level targeted JSON writes preserve ciphertext/default fields; caller validates merged meta. */
67
+ patchMeta(input: {
68
+ workspaceId: string;
69
+ id: string;
70
+ expectedRevision: number;
71
+ patch: VaultMeta;
72
+ updatedAt: string;
73
+ }, _options?: VaultOptions): Promise<VaultRecord>;
74
+ delete(input: {
75
+ workspaceId: string;
76
+ id: string;
77
+ expectedRevision: number;
78
+ }, _options?: VaultOptions): Promise<boolean>;
79
+ /** Pick only one identity using the same binary ordering for deletion and provider moves. */
80
+ private promote;
81
+ }
82
+ //# sourceMappingURL=repo.sql.d.ts.map
@@ -0,0 +1,176 @@
1
+ import { sql } from "kysely";
2
+ import { assertVaultReplacement, VaultError } from "@jini-ai/platform/secrets/credential-sets";
3
+ import { jsonSet, toBool } from "../kernel/dialect.js";
4
+ function fromRow(row) {
5
+ const parts = [row.sealed_key_id, row.sealed_ciphertext, row.sealed_nonce, row.sealed_alg];
6
+ if (parts.some(v => v === null) && !parts.every(v => v === null))
7
+ throw new VaultError({ code: "invalid-record" });
8
+ let meta;
9
+ try {
10
+ meta = typeof row.meta === "string" ? JSON.parse(row.meta) : row.meta;
11
+ }
12
+ catch {
13
+ throw new VaultError({ code: "invalid-meta" });
14
+ }
15
+ return { workspaceId: row.workspace_id, id: row.id, kind: row.kind, ownerKey: row.owner_key,
16
+ principalId: row.principal_id, binding: row.binding, provider: row.provider, label: row.label,
17
+ isDefault: toBool(row.is_default) ?? false, revision: Number(row.revision),
18
+ sealed: row.sealed_key_id === null ? null : { keyId: row.sealed_key_id, ciphertext: row.sealed_ciphertext, nonce: row.sealed_nonce, alg: row.sealed_alg },
19
+ last4: row.last4, tokenLength: row.token_length,
20
+ meta,
21
+ createdAt: row.created_at, updatedAt: row.updated_at };
22
+ }
23
+ function toRow(record) {
24
+ return { workspace_id: record.workspaceId, id: record.id, kind: record.kind, owner_key: record.ownerKey,
25
+ principal_id: record.principalId, binding: record.binding, provider: record.provider, label: record.label,
26
+ is_default: record.isDefault, revision: record.revision, sealed_key_id: record.sealed?.keyId ?? null,
27
+ sealed_ciphertext: record.sealed?.ciphertext ?? null, sealed_nonce: record.sealed?.nonce ?? null, sealed_alg: record.sealed?.alg ?? null,
28
+ last4: record.last4, token_length: record.tokenLength, meta: JSON.stringify(record.meta),
29
+ created_at: record.createdAt, updated_at: record.updatedAt };
30
+ }
31
+ /** One Kysely adapter for SQLite and Postgres/PGlite. Workspace lock `secrets_vault:<workspaceId>`
32
+ * serializes every writer, including targeted patches and boot rotation. Nested transactions join
33
+ * the host's transaction, allowing MCP payload/pointer/status writes to commit together.
34
+ */
35
+ export class SqlSecretsVaultRepo {
36
+ kernel;
37
+ constructor({ kernel }, _options = {}) { this.kernel = kernel; }
38
+ write(workspaceId, body) {
39
+ return this.kernel.transaction(async () => {
40
+ await this.kernel.lockKey(`secrets_vault:${workspaceId}`);
41
+ return body();
42
+ });
43
+ }
44
+ group(record) {
45
+ return { workspaceId: record.workspaceId, kind: record.kind, ownerKey: record.ownerKey,
46
+ principalId: record.principalId, provider: record.provider };
47
+ }
48
+ scoped({ db, input }, _options = {}) {
49
+ let query = db.selectFrom("secrets_vault").where("workspace_id", "=", input.workspaceId)
50
+ .where("kind", "=", input.kind).where("owner_key", "=", input.ownerKey)
51
+ .where("principal_id", input.principalId === null ? "is" : "=", input.principalId);
52
+ if (input.provider !== undefined)
53
+ query = query.where("provider", input.provider === null ? "is" : "=", input.provider);
54
+ return query;
55
+ }
56
+ async find(input, _options = {}) {
57
+ const row = await this.kernel.run(db => db.selectFrom("secrets_vault").selectAll()
58
+ .where("workspace_id", "=", input.workspaceId).where("id", "=", input.id).executeTakeFirst());
59
+ return row ? fromRow(row) : null;
60
+ }
61
+ /** One indexed singleton SELECT; provider/default never participate in this lookup. */
62
+ async findOne(input, _options = {}) {
63
+ const row = await this.kernel.run(db => {
64
+ let query = db.selectFrom("secrets_vault").selectAll().where("workspace_id", "=", input.workspaceId).where("kind", "=", input.kind);
65
+ if (input.ownerKey !== undefined)
66
+ query = query.where("owner_key", "=", input.ownerKey);
67
+ if (input.principalId !== undefined)
68
+ query = query.where("principal_id", input.principalId === null ? "is" : "=", input.principalId);
69
+ return query.limit(1).executeTakeFirst();
70
+ });
71
+ return row ? fromRow(row) : null;
72
+ }
73
+ /** One kernel transaction; nested mutations join it and retain their CAS/default owner.
74
+ * Lock every workspace in sorted order before writes to avoid opposite-order batch deadlocks.
75
+ * Failures must escape a surrounding host transaction (the kernel does not use savepoints).
76
+ */
77
+ async applyBatch({ ops }, _options = {}) {
78
+ return this.kernel.transaction(async () => {
79
+ const workspaces = ops.map(op => "put" in op ? op.put.record.workspaceId : "delete" in op ? op.delete.workspaceId : op.patchMeta.workspaceId);
80
+ for (const workspaceId of [...new Set(workspaces)].sort())
81
+ await this.kernel.lockKey(`secrets_vault:${workspaceId}`);
82
+ const results = [];
83
+ for (const op of ops) {
84
+ results.push("put" in op ? await this.put(op.put) : "delete" in op ? await this.delete(op.delete) : await this.patchMeta(op.patchMeta));
85
+ }
86
+ return results;
87
+ });
88
+ }
89
+ /** One indexed exact-group lookup; ciphertext is loaded only for the chosen default. */
90
+ async findDefault(input, _options = {}) {
91
+ const row = await this.kernel.run(db => this.scoped({ db, input }).selectAll()
92
+ .where("is_default", "=", true).limit(1).executeTakeFirst());
93
+ return row ? fromRow(row) : null;
94
+ }
95
+ async list(input, _options = {}) {
96
+ const rows = await this.kernel.run(db => this.scoped({ db, input }).selectAll().execute());
97
+ // Sort identifiers in JS to avoid host database collation changing the memory contract.
98
+ return rows.map(fromRow).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
99
+ }
100
+ async put(input, _options = {}) {
101
+ return this.write(input.record.workspaceId, async () => {
102
+ const existing = await this.find(input.record);
103
+ assertVaultReplacement({ ...input, existing });
104
+ const scope = this.group(input.record);
105
+ // Unchanged-label rotations need no uniqueness read; DB constraints still guard writes.
106
+ const moved = existing !== null && existing.provider !== input.record.provider;
107
+ if (moved || existing?.label !== input.record.label) {
108
+ const duplicate = await this.kernel.run(db => this.scoped({ db, input: scope }).select("id")
109
+ .where("id", "!=", input.record.id).where("label", "=", input.record.label).limit(1).executeTakeFirst());
110
+ if (duplicate)
111
+ throw new VaultError({ code: "conflict" });
112
+ }
113
+ const hasGroup = (existing !== null && !moved) || input.record.isDefault || Boolean(await this.kernel.run(db => this.scoped({ db, input: scope }).select("id").limit(1).executeTakeFirst()));
114
+ const saved = { ...input.record, isDefault: input.record.isDefault || !hasGroup };
115
+ // Clear before insert/update so a partial UNIQUE default index never sees two defaults.
116
+ if (saved.isDefault)
117
+ await this.kernel.run(db => db.updateTable("secrets_vault")
118
+ .set(eb => ({ is_default: false, revision: eb("revision", "+", 1) }))
119
+ .where("workspace_id", "=", saved.workspaceId).where("kind", "=", saved.kind).where("owner_key", "=", saved.ownerKey)
120
+ .where("principal_id", saved.principalId === null ? "is" : "=", saved.principalId)
121
+ .where("provider", saved.provider === null ? "is" : "=", saved.provider)
122
+ .where("id", "!=", saved.id).where("is_default", "=", true).execute());
123
+ const row = await this.kernel.run(db => input.expectedRevision === null
124
+ ? db.insertInto("secrets_vault").values(toRow(saved)).returningAll().executeTakeFirstOrThrow()
125
+ : db.updateTable("secrets_vault").set(toRow(saved)).where("workspace_id", "=", saved.workspaceId)
126
+ .where("id", "=", saved.id).where("revision", "=", input.expectedRevision).returningAll().executeTakeFirst());
127
+ if (!row)
128
+ throw new VaultError({ code: "conflict" });
129
+ if (moved && existing.isDefault)
130
+ await this.promote({ record: existing });
131
+ return fromRow(row);
132
+ });
133
+ }
134
+ /** Top-level targeted JSON writes preserve ciphertext/default fields; caller validates merged meta. */
135
+ async patchMeta(input, _options = {}) {
136
+ return this.write(input.workspaceId, async () => {
137
+ const row = await this.kernel.run(db => db.updateTable("secrets_vault").set(eb => {
138
+ let meta = eb.ref("meta");
139
+ for (const [key, value] of Object.entries(input.patch))
140
+ meta = jsonSet(this.kernel.dialect, meta, [key], value);
141
+ return { meta: meta, revision: eb("revision", "+", 1), updated_at: input.updatedAt };
142
+ }).where("workspace_id", "=", input.workspaceId).where("id", "=", input.id)
143
+ .where("revision", "=", input.expectedRevision).returningAll().executeTakeFirst());
144
+ if (!row)
145
+ throw new VaultError({ code: "conflict" });
146
+ return fromRow(row);
147
+ });
148
+ }
149
+ async delete(input, _options = {}) {
150
+ return this.write(input.workspaceId, async () => {
151
+ const existing = await this.find(input);
152
+ if (!existing)
153
+ return false;
154
+ if (existing.revision !== input.expectedRevision)
155
+ throw new VaultError({ code: "conflict" });
156
+ await this.kernel.run(db => db.deleteFrom("secrets_vault").where("workspace_id", "=", input.workspaceId)
157
+ .where("id", "=", input.id).where("revision", "=", input.expectedRevision).execute());
158
+ if (existing.isDefault)
159
+ await this.promote({ record: existing });
160
+ return true;
161
+ });
162
+ }
163
+ /** Pick only one identity using the same binary ordering for deletion and provider moves. */
164
+ async promote({ record }, _options = {}) {
165
+ // Let the database pick one identity; binary collation avoids locale-dependent winners.
166
+ const promoted = await this.kernel.run(db => this.scoped({ db, input: this.group(record) })
167
+ .select(["id", "updated_at"]).orderBy("updated_at", "desc")
168
+ .orderBy(this.kernel.dialect === "sqlite" ? sql `id COLLATE BINARY` : sql `id COLLATE "C"`, "desc")
169
+ .limit(1).executeTakeFirst());
170
+ if (promoted)
171
+ await this.kernel.run(db => db.updateTable("secrets_vault")
172
+ .set(eb => ({ is_default: true, revision: eb("revision", "+", 1) }))
173
+ .where("workspace_id", "=", record.workspaceId).where("id", "=", promoted.id).execute());
174
+ }
175
+ }
176
+ //# sourceMappingURL=repo.sql.js.map