@k9o/kibo 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,117 @@
1
+ /**
2
+ * TS contract for the ZK encrypt/decrypt FFI surface — mirrors the Rust
3
+ * `kibo-kms-rest-ffi::types` (the bound core, piece C) field-for-field.
4
+ *
5
+ * These types cross the wasm boundary as plain JS objects (serde-wasm-bindgen),
6
+ * so the field names + enum wire-tokens must match the Rust serde exactly:
7
+ * - `KmsProvider` kebab-case (`aws-kms`, `gcp-kms`, `azure-kv`, `hashicorp-vault`)
8
+ * - all other enums snake_case (`byok`, `local_envelope`, `hardware_backed`, …)
9
+ * - bytes (`Vec<u8>`) `Uint8Array` at the boundary
10
+ *
11
+ * Strict-ZK invariant: the `secret` in `KiboCredential` is a customer-issued
12
+ * short-lived federated token — never a platform KEK; it is zeroized in the core
13
+ * after use and never logged or returned. The platform never sees plaintext.
14
+ */
15
+
16
+ // The customer KMS provider — the same routing selector as the F.5 store
17
+ // surface. Reuse the canonical definition (no duplication).
18
+ import type { KmsProvider } from "./types.ts";
19
+ export type { KmsProvider };
20
+
21
+ /** Custody posture for an encrypt call. `platform-managed` is structurally absent
22
+ * here — `kibo-kms-rest` is the KEK-free customer-KMS layer (ZK is never PM). */
23
+ export type KiboPosture = "byok" | "hyok";
24
+
25
+ /** Explicit strategy pin. Omit → `local_envelope` (the posture default). */
26
+ export type KiboStrategy = "local_envelope" | "customer_kms_oracle";
27
+
28
+ /** Oracle routing mode. Omit → `brokered` (default). */
29
+ export type KiboOracleMode = "brokered" | "direct";
30
+
31
+ /** Device attestation tier bound into the AAD for every operation. */
32
+ export type KiboAttestationTier = "software" | "hardware_backed" | "confidential";
33
+
34
+ /** The min-custody-posture floor ladder (3-mode; `platform_managed` = no floor).
35
+ * Ordering: `PLATFORM_MANAGED < BYOK < HYOK`. */
36
+ export type KiboMinPosture = "platform_managed" | "byok" | "hyok";
37
+
38
+ /** Acceptable oracle-mode set (the `allowed_oracle_modes` policy dial). */
39
+ export interface KiboAllowedOracleModes {
40
+ brokered: boolean;
41
+ direct: boolean;
42
+ }
43
+
44
+ /** Project-declared crypto-posture floor (ch08 §11.3.3.4). Omit fields for the
45
+ * most-permissive default (`platform_managed` floor + both oracle modes). */
46
+ export interface KiboPosturePolicy {
47
+ min_custody_posture?: KiboMinPosture;
48
+ allowed_oracle_modes?: KiboAllowedOracleModes;
49
+ }
50
+
51
+ /** Short-lived customer KMS credential — the edge device's federated token.
52
+ * `secret` is treated as secret material (zeroized in-core; never returned). */
53
+ export interface KiboCredential {
54
+ secret: string;
55
+ expires_at_unix_secs: number;
56
+ }
57
+
58
+ /** Key version reference identifying the customer KMS key. `external_ref` is
59
+ * provider-specific (AWS key ARN / GCP resource name / Azure key URL / Vault
60
+ * `<mount>/<key>:<ver>`). `version` is the monotone KEK-rotation counter. */
61
+ export interface KiboKeyRef {
62
+ version: number;
63
+ external_ref: string;
64
+ }
65
+
66
+ /** Provider-specific init params. Only the compiled-in provider's field is read. */
67
+ export interface KiboProviderConfig {
68
+ aws_region?: string;
69
+ vault_address?: string;
70
+ }
71
+
72
+ /** A single encryption-context key/value pair. Bound into the AAD at encrypt and
73
+ * re-supplied byte-for-byte at decrypt. (Record shape — uniffi can't cross
74
+ * tuples; the wasm JSON is `[{"key":"…","value":"…"}]`.) `kibo:` is reserved. */
75
+ export interface KiboKvPair {
76
+ key: string;
77
+ value: string;
78
+ }
79
+
80
+ /** All inputs to `encrypt` — mirrors Rust `EncryptInput`. */
81
+ export interface KiboEncryptInput {
82
+ provider: KmsProvider;
83
+ posture: KiboPosture;
84
+ strategy?: KiboStrategy;
85
+ oracle_mode?: KiboOracleMode;
86
+ kms_cred: KiboCredential;
87
+ key_ref: KiboKeyRef;
88
+ provider_config: KiboProviderConfig;
89
+ attestation_tier: KiboAttestationTier;
90
+ encryption_context: KiboKvPair[];
91
+ /** Plaintext bytes to encrypt. */
92
+ plaintext: Uint8Array;
93
+ posture_policy?: KiboPosturePolicy;
94
+ }
95
+
96
+ /** All inputs to `decrypt` — mirrors Rust `DecryptInput`. `strategy`,
97
+ * `attestation_tier`, and `encryption_context` MUST be re-supplied (never read
98
+ * from the envelope — anti-envelope-substitution discipline). */
99
+ export interface KiboDecryptInput {
100
+ kms_cred: KiboCredential;
101
+ provider_config: KiboProviderConfig;
102
+ /** The canonical (`b"KIBO"`) envelope from a prior `encrypt`. */
103
+ envelope: Uint8Array;
104
+ strategy: KiboStrategy;
105
+ attestation_tier: KiboAttestationTier;
106
+ encryption_context: KiboKvPair[];
107
+ }
108
+
109
+ /** Output of `encrypt` — the opaque ZKFE envelope (pass straight to `decrypt`). */
110
+ export interface KiboEncryptOutput {
111
+ envelope: Uint8Array;
112
+ }
113
+
114
+ /** Output of `decrypt` — the recovered plaintext. */
115
+ export interface KiboDecryptOutput {
116
+ plaintext: Uint8Array;
117
+ }
package/src/crypto.ts ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * ZK encrypt/decrypt — the thin TS wrapper over the bound crypto core
3
+ * (`kibo-kms-rest-ffi`, piece C) compiled to wasm. ZERO crypto here: every
4
+ * wrap/unwrap, envelope framing, posture-floor enforcement, and KMS round-trip
5
+ * lives in the audited Rust core. This layer only marshals the typed input
6
+ * across the wasm boundary and maps the core's error string → `KError`.
7
+ *
8
+ * The core exposes `zk_encrypt`/`zk_decrypt` (async) taking/returning plain JS
9
+ * objects via serde-wasm-bindgen, and rejecting with the `ZkFfiError` display
10
+ * string (`"<K9O_CODE>: <message>"`, optionally with a posture-violation tail).
11
+ *
12
+ * Composes into `@k9o/core` as `client.kibo.encrypt`/`decrypt`; the F.5
13
+ * `vault.zkDeks.{store,fetch}` surface (envelope persistence) is separate +
14
+ * decoupled (the core never sees the store).
15
+ */
16
+
17
+ import { KError } from "@k9o/core/errors";
18
+ import type {
19
+ KiboEncryptInput,
20
+ KiboEncryptOutput,
21
+ KiboDecryptInput,
22
+ KiboDecryptOutput,
23
+ } from "./crypto-types.ts";
24
+
25
+ /** The minimal surface the bound ZK-core wasm exposes. */
26
+ export interface ZkWasm {
27
+ zk_encrypt(input: unknown): Promise<unknown>;
28
+ zk_decrypt(input: unknown): Promise<unknown>;
29
+ }
30
+
31
+ let cachedWasm: ZkWasm | undefined;
32
+
33
+ /**
34
+ * Inject a pre-loaded core wasm module. Hosts that bundle the wasm themselves
35
+ * (browser/RN, or a test) call this; otherwise `encrypt`/`decrypt` lazy-load
36
+ * the vendored per-provider artifact.
37
+ */
38
+ export function setZkWasm(mod: ZkWasm): void {
39
+ cachedWasm = mod;
40
+ }
41
+
42
+ /**
43
+ * Lazily load the bound core wasm. ONE all-provider artifact is generated from
44
+ * `kibo-kms-rest-ffi` (the core compiles every v2 KMS provider in; the
45
+ * `provider` input field selects at call time), vendored under `wasm/` by the
46
+ * publish pipeline and gitignored in-repo. The specifier is assembled at
47
+ * runtime so the bundler/typechecker must not hard-resolve it — the contract
48
+ * is the `ZkWasm` interface above.
49
+ */
50
+ async function loadWasm(): Promise<ZkWasm> {
51
+ if (cachedWasm) return cachedWasm;
52
+ const pkg = ["..", "wasm", "kibo_kms_rest_ffi.js"].join("/");
53
+ try {
54
+ cachedWasm = (await import(pkg)) as unknown as ZkWasm;
55
+ } catch {
56
+ // A package published without its native core (no bundle at publish time). Say so; never surface a bare
57
+ // module-resolution error, and do not cache the failure.
58
+ throw new KError({
59
+ code: "KIBO_WASM_ERROR",
60
+ message: "the Kibo zero-knowledge core (wasm) is not bundled in this build of @k9o/kibo; encrypt and decrypt are unavailable",
61
+ context: {},
62
+ recommendation: "Install a release of @k9o/kibo that ships the core, or load it yourself.",
63
+ });
64
+ }
65
+ return cachedWasm;
66
+ }
67
+
68
+ /**
69
+ * Encrypt `input.plaintext` via the customer KMS, client-side. Returns the
70
+ * opaque ZKFE envelope — store it via `vault.zkDeks.store` (F.5) or keep it
71
+ * yourself; it is meaningless to the platform.
72
+ */
73
+ export async function encrypt(input: KiboEncryptInput): Promise<KiboEncryptOutput> {
74
+ const wasm = await loadWasm();
75
+ let out: unknown;
76
+ try {
77
+ out = await wasm.zk_encrypt(input);
78
+ } catch (e) {
79
+ throw mapZkError(e);
80
+ }
81
+ return { envelope: toBytes((out as { envelope?: unknown }).envelope) };
82
+ }
83
+
84
+ /**
85
+ * Decrypt a ZKFE `input.envelope`. `strategy`, `attestation_tier`, and
86
+ * `encryption_context` MUST match the values used at encrypt — they are AAD-bound
87
+ * and never recovered from the envelope (anti-substitution discipline).
88
+ */
89
+ export async function decrypt(input: KiboDecryptInput): Promise<KiboDecryptOutput> {
90
+ const wasm = await loadWasm();
91
+ let out: unknown;
92
+ try {
93
+ out = await wasm.zk_decrypt(input);
94
+ } catch (e) {
95
+ throw mapZkError(e);
96
+ }
97
+ return { plaintext: toBytes((out as { plaintext?: unknown }).plaintext) };
98
+ }
99
+
100
+ /** Normalise wasm byte output (serde-wasm-bindgen emits `Vec<u8>` as a number
101
+ * array; some hosts return a `Uint8Array`) to `Uint8Array`. */
102
+ function toBytes(v: unknown): Uint8Array {
103
+ if (v instanceof Uint8Array) return v;
104
+ if (Array.isArray(v)) return Uint8Array.from(v as number[]);
105
+ throw new KError({
106
+ code: "KIBO_WASM_DECODE_ERROR",
107
+ message: "ZK core returned a non-byte value where bytes were expected",
108
+ context: {},
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Map the core's rejected error → `KError`. The wasm path flattens `ZkFfiError`
114
+ * to its display string: `"<CODE>: <message>"` where `<CODE>` is a `K9O_*` wire
115
+ * code (or `UPSTREAM_KMS_ERROR` for the customer's own KMS failures), optionally
116
+ * followed by `"(dimension: …, requested: …, declared: …)"` for a posture-floor
117
+ * violation. Codes are passed through (never hardcoded), per the KError discipline.
118
+ */
119
+ function mapZkError(e: unknown): KError {
120
+ if (e instanceof KError) return e;
121
+ const raw = e instanceof Error ? e.message : String(e);
122
+ const head = /^([A-Z][A-Z0-9_]*):\s*([\s\S]*)$/.exec(raw);
123
+ const code = head?.[1] ?? "KIBO_WASM_ERROR";
124
+ let message = head?.[2] ?? raw;
125
+
126
+ let context: Record<string, unknown> = {};
127
+ const pv = /\(dimension:\s*([^,]+),\s*requested:\s*([^,]+),\s*declared:\s*([^)]+)\)\s*$/.exec(message);
128
+ if (pv) {
129
+ context = { dimension: pv[1]!.trim(), requested: pv[2]!.trim(), declared: pv[3]!.trim() };
130
+ message = message.slice(0, pv.index).trim();
131
+ }
132
+ return new KError({ code, message, context });
133
+ }
package/src/index.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `@k9o/kibo` — Zero-Knowledge BYOK/HYOK vault SDK (client-side).
3
+ *
4
+ * Composes into `@k9o/core` as `client.kibo`. Two surfaces:
5
+ * - F.5 ZK-DEK store/fetch (ch08 §11.3.2) — `vault.zkDeks.{store,fetch}`;
6
+ * decoupled, gateway-only opaque-blob persistence.
7
+ * - ZK `encrypt`/`decrypt` (§11.3.1/§11.3.3.6) — thin wrappers over the
8
+ * audited core (piece C, `kibo-kms-rest-ffi` compiled to wasm).
9
+ *
10
+ * Zero crypto in this package: every wrap/unwrap, envelope framing, and
11
+ * posture-floor enforcement lives in the bound core; the SDK only marshals
12
+ * typed input across the wasm boundary + ships/retrieves opaque blobs.
13
+ */
14
+
15
+ export { createKiboClient, type KiboClient } from "./client-factory.ts";
16
+ export { makeVaultNamespace } from "./vault.ts";
17
+ export type {
18
+ KmsProvider, StoreZkDekInput, ZkDekHandle, ZkDekRecord,
19
+ SecretVisibility, CreateSecretInput, SecretSummary,
20
+ ListSecretsInput, ListSecretsResult, AttestationTier, RevealChallenge, RevealSecretResult,
21
+ UpdateSecretInput, UpdateSecretResult, RotateSecretResult, MoveSecretResult,
22
+ } from "./types.ts";
23
+
24
+ // ZK encrypt/decrypt (bound-core wasm). The ergonomic client-bound surface
25
+ // (gathering provider/posture/key-ref from config) composes per the
26
+ // method-shape contract; these are the FFI-mapped primitives it builds on.
27
+ export { encrypt, decrypt, setZkWasm, type ZkWasm } from "./crypto.ts";
28
+ export type {
29
+ KiboPosture, KiboStrategy, KiboOracleMode, KiboAttestationTier, KiboMinPosture,
30
+ KiboAllowedOracleModes, KiboPosturePolicy, KiboCredential, KiboKeyRef,
31
+ KiboProviderConfig, KiboKvPair, KiboEncryptInput, KiboEncryptOutput,
32
+ KiboDecryptInput, KiboDecryptOutput,
33
+ } from "./crypto-types.ts";
package/src/types.ts ADDED
@@ -0,0 +1,171 @@
1
+ /**
2
+ * `@k9o/kibo` — Zero-Knowledge BYOK/HYOK vault SDK types.
3
+ *
4
+ * v0.1.0 surface: the ZK-DEK store/fetch. The wrapped
5
+ * envelope is produced client-side by the audited ZK core (the
6
+ * `kibo-kms-rest` binding); this SDK ships it **verbatim and opaque** and never
7
+ * reads its interior — the strict-ZK invariant + envelope framing live in the
8
+ * core, never here.
9
+ */
10
+
11
+ /** Customer KMS/HSM provider — non-secret routing metadata (mirrors the ZK FFI provider selector). */
12
+ export type KmsProvider = "aws-kms" | "gcp-kms" | "azure-kv" | "hashicorp-vault";
13
+
14
+ /**
15
+ * Input to store an opaque customer-wrapped DEK.
16
+ * `provider` + `keyVersionRef` are explicit non-secret fields the SDK supplies
17
+ * (vault-ops never parses the envelope to derive them).
18
+ */
19
+ export type StoreZkDekInput = {
20
+ /** base64 opaque `WrappedDek` envelope (AEAD-sealed under the customer KEK). */
21
+ envelope: string;
22
+ /** Which customer KMS/HSM holds the wrapping KEK. */
23
+ provider: KmsProvider;
24
+ /** Customer key reference (KMS ARN / GCP resource / AKV id / Vault path). */
25
+ keyVersionRef: string;
26
+ };
27
+
28
+ /** Store response — the opaque `zkdek_<base62>` handle + creation timestamp. */
29
+ export type ZkDekHandle = {
30
+ /** `zkdek_<base62>` handle. */
31
+ id: string;
32
+ createdAt: string;
33
+ };
34
+
35
+ /** Fetch response — the stored record: opaque envelope + non-secret metadata. */
36
+ export type ZkDekRecord = {
37
+ id: string;
38
+ /** base64 opaque `WrappedDek` envelope, returned verbatim for the customer to unwrap. */
39
+ envelope: string;
40
+ provider: KmsProvider;
41
+ keyVersionRef: string;
42
+ createdAt: string;
43
+ };
44
+
45
+ /** §14.2 secret visibility — write ops (create/update) stay owner-only regardless of this tag. */
46
+ export type SecretVisibility =
47
+ | { kind: "private" }
48
+ | { kind: "shared"; principals?: string[]; roles?: string[] };
49
+
50
+ /** Input to create a vault secret (ch08 §14) — `POST /@<projectSlug>/vault/secrets/<name>?region=<region>`. */
51
+ export type CreateSecretInput = {
52
+ /** Hierarchical path the secret is addressed under, e.g. `byos/s3-prod` (also the `:name` URL segment). */
53
+ name: string;
54
+ /** The plaintext to seal, as a regular (non-base64) string — `vault.secrets.create` base64-encodes
55
+ * it for the wire itself (live-verified against staging: the route's OpenAPI description says
56
+ * "the plaintext to seal" but a raw non-base64 `value` is rejected as unparseable). */
57
+ value: string;
58
+ /** The authoritative region for this vault write (sent as `?region=`), REQUIRED — the vault-forward
59
+ * proxy fail-closes without it (live-verified against staging, not documented in the route's
60
+ * OpenAPI schema as of this writing). Distinct from any region carried inside `value`'s own
61
+ * envelope. */
62
+ region: string;
63
+ visibility?: SecretVisibility;
64
+ metadata?: Record<string, string>;
65
+ };
66
+
67
+ /** A secret WITHOUT its sealed ciphertext — the create/list/read metadata shape. */
68
+ export type SecretSummary = {
69
+ /** `sec_<base62>`. */
70
+ id: string;
71
+ name: string;
72
+ ownerId: string;
73
+ visibility: SecretVisibility;
74
+ version: number;
75
+ /** The wrapping-key id at this version. */
76
+ kid: string;
77
+ createdAt: string;
78
+ createdBy: string;
79
+ updatedAt: string;
80
+ updatedBy: string;
81
+ rotatedAt: string | null;
82
+ retiredAt: string | null;
83
+ metadata: Record<string, string>;
84
+ };
85
+
86
+ /** `client.kibo.vault.secrets.list()` input — none of these need `region` (live-verified: unlike every
87
+ * other secrets operation, list is NOT region-gated). */
88
+ export type ListSecretsInput = {
89
+ /** Filter to a path prefix. */
90
+ prefix?: string;
91
+ cursor?: string;
92
+ limit?: number;
93
+ };
94
+
95
+ export type ListSecretsResult = {
96
+ secrets: readonly SecretSummary[];
97
+ nextCursor: string | null;
98
+ };
99
+
100
+ /** §14.10 releasing-node observed attestation tier (K4) — present on every reveal. */
101
+ export type AttestationTier = {
102
+ /** `attestation:destination:region` trust-tier URN. */
103
+ urn: string;
104
+ /** Node provenance: `platform` (Kibo-operated) or `client` (Private Perimeter). */
105
+ operator: string;
106
+ /** Whether node attestation was verified against the vendor PKI on the URN's attestation segment. */
107
+ verified: boolean;
108
+ };
109
+
110
+ /** `revealChallenge()` result — a single-use challenge to present on the immediately-following `reveal()`. */
111
+ export type RevealChallenge = {
112
+ challenge: string;
113
+ expiresAt: string;
114
+ };
115
+
116
+ /** `reveal()` result. `value` is the decoded plaintext (the SDK base64-decodes the wire value, the
117
+ * inverse of `create`'s encode) — never the raw base64. */
118
+ export type RevealSecretResult = {
119
+ id: string;
120
+ name: string;
121
+ version: number;
122
+ value: string;
123
+ revealedAt: string;
124
+ attestationTier: AttestationTier;
125
+ };
126
+
127
+ /** `update()` input. */
128
+ export type UpdateSecretInput = {
129
+ /** The authoritative region for this write (sent as `?region=`), REQUIRED — same live-verified gate
130
+ * as `create`. */
131
+ region: string;
132
+ /** New plaintext — bumps `version`. The SDK base64-encodes it for the wire. */
133
+ value: string;
134
+ metadata?: Record<string, string>;
135
+ };
136
+
137
+ /**
138
+ * `update()` result — 🔴 live-verified NARROWER than the documented `SecretSummary`: the gateway
139
+ * returns only `{id, name, version}` on a real PUT, not the full summary the OpenAPI schema claims.
140
+ * Typed to what's actually observed rather than the aspirational doc shape; call `get()` afterward if
141
+ * the full summary is needed.
142
+ */
143
+ export type UpdateSecretResult = {
144
+ id: string;
145
+ name: string;
146
+ version: number;
147
+ };
148
+
149
+ /**
150
+ * `rotate()` result — 🔴 live-verified shape, not documented anywhere in the OpenAPI schema (the route
151
+ * only declares `t.Union([SecretSummary, RevealChallengeResponse])`, which this matches neither).
152
+ * `ledgerSequenceNumber` is undocumented; kept as-observed.
153
+ */
154
+ export type RotateSecretResult = {
155
+ id: string;
156
+ name: string;
157
+ version: number;
158
+ rotatedAt: string;
159
+ ledgerSequenceNumber: number;
160
+ };
161
+
162
+ /**
163
+ * `move()` result — 🔴 live-verified shape, also not the documented `SecretSummary`: no `version`, and
164
+ * an undocumented `event` field (`"SECRET_PATH_CHANGED"` observed; typed as `string` since only one
165
+ * sample was seen and a closed enum can't be asserted from one observation).
166
+ */
167
+ export type MoveSecretResult = {
168
+ id: string;
169
+ name: string;
170
+ event: string;
171
+ };
package/src/vault.ts ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * `client.kibo.vault.*` — the Kibo vault surface.
3
+ *
4
+ * v0.1.0: `vault.zkDeks.{store,fetch}` (ch08 §11.3.2 F.5) — member-plane,
5
+ * project-scoped storage of the opaque customer-wrapped DEK envelope. Zero
6
+ * crypto SDK-side: this is a plain authenticated REST round-trip carrying an
7
+ * opaque blob (the wrapping happens in the ZK core, piece C). The encryption
8
+ * surface (`kibo.encrypt`/`decrypt`) lands in a later version once the C
9
+ * binding is consumable.
10
+ */
11
+
12
+ import { request, type HttpClientConfig } from "@k9o/core/http";
13
+ import { projectPath } from "@k9o/core/url-grammar";
14
+ import { KError } from "@k9o/core/errors";
15
+ import type { Envelope } from "@k9o/core/envelope";
16
+ import type {
17
+ StoreZkDekInput, ZkDekHandle, ZkDekRecord,
18
+ CreateSecretInput, SecretSummary, ListSecretsInput, ListSecretsResult,
19
+ RevealChallenge, RevealSecretResult, UpdateSecretInput, UpdateSecretResult,
20
+ RotateSecretResult, MoveSecretResult,
21
+ } from "./types.ts";
22
+
23
+ /** UTF-8-safe base64 encode, usable across browser/Node/Bun (unlike `Buffer`) — the vault-secrets wire
24
+ * `value` field is base64 (live-verified; the OpenAPI "plaintext to seal" description does not mean
25
+ * raw-on-the-wire). */
26
+ function encodeBase64Utf8(plaintext: string): string {
27
+ return btoa(unescape(encodeURIComponent(plaintext)));
28
+ }
29
+
30
+ /** Inverse of {@link encodeBase64Utf8} — decodes a revealed wire `value` back to plaintext. */
31
+ function decodeBase64Utf8(b64: string): string {
32
+ return decodeURIComponent(escape(atob(b64)));
33
+ }
34
+
35
+ /** Both `vault.zkDeks` and `vault.secrets` require a project context (member-plane, ch08 §11.3/§14). */
36
+ function requireProjectSlug(config: HttpClientConfig): string {
37
+ if (config.projectSlug === undefined || config.projectSlug.length === 0) {
38
+ throw new KError({
39
+ code: "K9O_MISSING_PROJECT_CONTEXT",
40
+ message: "client.kibo.vault requires a bound projectSlug (member-plane resource)",
41
+ context: {},
42
+ recommendation: "Pass projectSlug when constructing the client.",
43
+ });
44
+ }
45
+ return config.projectSlug;
46
+ }
47
+
48
+ export function makeVaultNamespace(config: HttpClientConfig) {
49
+ return {
50
+ /** ZK-DEK opaque store/fetch (ch08 §11.3.2 F.5). */
51
+ zkDeks: {
52
+ /**
53
+ * Store an opaque customer-wrapped DEK envelope.
54
+ * `POST /@<projectSlug>/vault/zk-deks` → the `zkdek_<base62>` handle.
55
+ * The SDK ships the envelope verbatim; it is never parsed here.
56
+ */
57
+ async store(input: StoreZkDekInput): Promise<Envelope<ZkDekHandle>> {
58
+ return request<ZkDekHandle>(config, {
59
+ method: "POST",
60
+ path: projectPath(requireProjectSlug(config), "vault/zk-deks"),
61
+ body: input,
62
+ });
63
+ },
64
+
65
+ /**
66
+ * Fetch a stored `WrappedDek` by its handle.
67
+ * `GET /@<projectSlug>/vault/zk-deks/<id>` → the opaque envelope + the
68
+ * non-secret `provider`/`keyVersionRef` the caller needs to unwrap it.
69
+ */
70
+ async fetch(id: string): Promise<Envelope<ZkDekRecord>> {
71
+ return request<ZkDekRecord>(config, {
72
+ method: "GET",
73
+ path: projectPath(requireProjectSlug(config), `vault/zk-deks/${encodeURIComponent(id)}`),
74
+ });
75
+ },
76
+ },
77
+
78
+ /**
79
+ * §14 typed secrets surface (`services/gateway/src/routes/vault-secrets.ts`) — the full family:
80
+ * list/get/create/revealChallenge/reveal/update/rotate/move/delete. Every operation on a NAMED
81
+ * secret (everything except `list`) requires `region` — live-verified against staging, not
82
+ * documented in the route's OpenAPI schema. `list` is the one exception (verified it does NOT
83
+ * need `region`).
84
+ *
85
+ * Response shapes for `update`/`rotate`/`move` are typed to what the gateway ACTUALLY returns
86
+ * (live-verified), not the OpenAPI's documented (and inaccurate for these three) `SecretSummary` —
87
+ * see the 🔴 notes on `UpdateSecretResult`/`RotateSecretResult`/`MoveSecretResult` in `types.ts`.
88
+ */
89
+ secrets: {
90
+ /** List secrets (metadata only — never lists ciphertext). `GET /@<projectSlug>/vault/secrets`.
91
+ * The one secrets operation that does NOT need `region` (live-verified). */
92
+ async list(input?: ListSecretsInput): Promise<Envelope<ListSecretsResult>> {
93
+ return request<ListSecretsResult>(config, {
94
+ method: "GET",
95
+ path: projectPath(requireProjectSlug(config), "vault/secrets"),
96
+ query: { prefix: input?.prefix, cursor: input?.cursor, limit: input?.limit },
97
+ });
98
+ },
99
+
100
+ /**
101
+ * Read a secret's metadata (never its value — use `revealChallenge`+`reveal` for that).
102
+ * `GET /@<projectSlug>/vault/secrets/<name>?region=<region>`.
103
+ *
104
+ * 🔴 KNOWN LIVE BUG (staging, 2026-09-05): this call currently fails with
105
+ * `K9O_REVEAL_CHALLENGE_REQUIRED` on every attempt — the gateway/kibo does not honor the
106
+ * documented "no `X-K9O-Reveal-Challenge` header ⇒ return metadata" behavior; it demands a
107
+ * challenge unconditionally. Implemented per the documented contract (this is a backend defect,
108
+ * not a client workaround); `list({prefix: exactName})` is the current working alternative for a
109
+ * single secret's metadata until the gateway/kibo side is fixed.
110
+ */
111
+ async get(name: string, opts: { region: string }): Promise<Envelope<SecretSummary>> {
112
+ return request<SecretSummary>(config, {
113
+ method: "GET",
114
+ path: projectPath(requireProjectSlug(config), `vault/secrets/${encodeURIComponent(name)}`),
115
+ query: { region: opts.region },
116
+ });
117
+ },
118
+
119
+ /**
120
+ * Create a secret under the caller's own auth.
121
+ * `POST /@<projectSlug>/vault/secrets/<name>?region=<region>` → the `sec_<base62>` summary.
122
+ *
123
+ * 🔴 `region` is REQUIRED on the query string, live-verified against staging — the vault-forward
124
+ * proxy fail-closes with `K9O_INVALID_FIELD_VALUE` ("this request requires an authoritative
125
+ * region") without it. Distinct from any `region` carried inside `input.value`'s envelope (e.g.
126
+ * the BYOS aws_sigv4 STS-signing region): this one scopes the vault WRITE itself, mirroring the
127
+ * gateway's `gatewayRegion()` residency guard (region-guard.ts) that closed a 2026-08 wrong-region
128
+ * incident for the audit path — the request-shape unit tests never caught this because they don't
129
+ * exercise a real gateway.
130
+ */
131
+ async create(input: CreateSecretInput): Promise<Envelope<SecretSummary>> {
132
+ const { name, region, value, ...rest } = input;
133
+ return request<SecretSummary>(config, {
134
+ method: "POST",
135
+ path: projectPath(requireProjectSlug(config), `vault/secrets/${encodeURIComponent(name)}`),
136
+ query: { region },
137
+ // Live-verified against staging: the wire `value` MUST be base64 — a raw plaintext string
138
+ // (matching the route's own "the plaintext to seal" OpenAPI description literally) is
139
+ // rejected with K9O_INVALID_FIELD_VALUE "Request body could not be parsed." `input.value`
140
+ // stays the caller-facing plaintext; base64 is purely a wire-transport detail handled here.
141
+ body: { ...rest, value: encodeBase64Utf8(value) },
142
+ });
143
+ },
144
+
145
+ /** Mint a single-use reveal challenge — present it as `X-K9O-Reveal-Challenge` on the
146
+ * immediately-following `reveal()` call. `POST .../<name>?op=reveal-challenge&region=<region>`. */
147
+ async revealChallenge(name: string, opts: { region: string }): Promise<Envelope<RevealChallenge>> {
148
+ return request<RevealChallenge>(config, {
149
+ method: "POST",
150
+ path: projectPath(requireProjectSlug(config), `vault/secrets/${encodeURIComponent(name)}`),
151
+ query: { op: "reveal-challenge", region: opts.region },
152
+ });
153
+ },
154
+
155
+ /** Reveal a secret's plaintext value using a single-use challenge from `revealChallenge()`.
156
+ * `GET .../<name>?region=<region>` with `X-K9O-Reveal-Challenge`. Decodes the wire's base64
157
+ * `value` back to plaintext (live-verified: the reveal response's `value` is base64, symmetric
158
+ * with `create`'s encode). */
159
+ async reveal(name: string, opts: { region: string; challenge: string }): Promise<Envelope<RevealSecretResult>> {
160
+ const envelope = await request<RevealSecretResult>(config, {
161
+ method: "GET",
162
+ path: projectPath(requireProjectSlug(config), `vault/secrets/${encodeURIComponent(name)}`),
163
+ query: { region: opts.region },
164
+ headers: { "X-K9O-Reveal-Challenge": opts.challenge },
165
+ });
166
+ return { ...envelope, data: { ...envelope.data, value: decodeBase64Utf8(envelope.data.value) } };
167
+ },
168
+
169
+ /** Update a secret's value (bumps version) — owner-only. `PUT .../<name>?region=<region>`.
170
+ * 🔴 Returns only `{id, name, version}` live (see `UpdateSecretResult`), not the full summary
171
+ * the OpenAPI schema documents — call `get()` after if you need the rest. */
172
+ async update(name: string, input: UpdateSecretInput): Promise<Envelope<UpdateSecretResult>> {
173
+ return request<UpdateSecretResult>(config, {
174
+ method: "PUT",
175
+ path: projectPath(requireProjectSlug(config), `vault/secrets/${encodeURIComponent(name)}`),
176
+ query: { region: input.region },
177
+ body: { value: encodeBase64Utf8(input.value), ...(input.metadata !== undefined ? { metadata: input.metadata } : {}) },
178
+ });
179
+ },
180
+
181
+ /** Rotate a secret's wrapping key (re-wraps under a fresh `kid`; content unchanged) — owner-only.
182
+ * `POST .../<name>?op=rotate&region=<region>`. */
183
+ async rotate(name: string, opts: { region: string }): Promise<Envelope<RotateSecretResult>> {
184
+ return request<RotateSecretResult>(config, {
185
+ method: "POST",
186
+ path: projectPath(requireProjectSlug(config), `vault/secrets/${encodeURIComponent(name)}`),
187
+ query: { op: "rotate", region: opts.region },
188
+ });
189
+ },
190
+
191
+ /** Move (rename) a secret's hierarchical path — owner-only.
192
+ * `POST .../<name>?op=move&region=<region>`. */
193
+ async move(name: string, opts: { region: string; newPath: string }): Promise<Envelope<MoveSecretResult>> {
194
+ return request<MoveSecretResult>(config, {
195
+ method: "POST",
196
+ path: projectPath(requireProjectSlug(config), `vault/secrets/${encodeURIComponent(name)}`),
197
+ query: { op: "move", region: opts.region },
198
+ body: { newPath: opts.newPath },
199
+ });
200
+ },
201
+
202
+ /** Retire a secret — owner-only. `DELETE .../<name>?region=<region>` → `204 No Content`. */
203
+ async delete(name: string, opts: { region: string }): Promise<Envelope<void>> {
204
+ return request<void>(config, {
205
+ method: "DELETE",
206
+ path: projectPath(requireProjectSlug(config), `vault/secrets/${encodeURIComponent(name)}`),
207
+ query: { region: opts.region },
208
+ });
209
+ },
210
+ },
211
+ };
212
+ }