@alineo-labs/vault 0.2.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,194 @@
1
+ import { CredentialBinding, CredentialBroker } from "@alineo-labs/core";
2
+ import { ControlClient } from "@alineo-labs/opensandbox";
3
+
4
+ //#region src/broker.d.ts
5
+ /**
6
+ * Thrown when a `CredentialBinding.injection` has no equivalent in the sidecar's real `Auth`
7
+ * model. Only header injection (`{ type: "header" }`) maps onto it today — it supports
8
+ * `bearer`/`basic`/`apiKey`/`customHeaders` header injection and placeholder `substitutions`
9
+ * (for path/query/body), but not an arbitrary named query param or path segment the way this
10
+ * package's `{ type: "query" }`/`{ type: "path" }` binding shapes imply. Wire those up to
11
+ * `substitutions` (which needs a literal placeholder string in the request, a different model
12
+ * from "inject a named param") before lifting this restriction.
13
+ */
14
+ declare class UnsupportedInjectionError extends Error {
15
+ constructor(injectionType: string);
16
+ }
17
+ /**
18
+ * Default `CredentialBroker` implementation, backed by OpenSandbox's own Credential Vault.
19
+ *
20
+ * `Sandbox` (from `@alineo-labs/sandbox`) constructs one of these automatically, wired to its
21
+ * own internal `ControlClient`, when `SandboxClientOptions.credentialBroker` is omitted — most
22
+ * callers never need to construct this directly.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const sb = await client.sandbox({
27
+ * image: "node:22",
28
+ * resources: { cpu: "500m", memory: "512Mi" },
29
+ * networkPolicy: { defaultAction: "deny", egress: [{ action: "allow", target: "api.github.com" }] },
30
+ * credentialProxy: true,
31
+ * });
32
+ * await sb.credentials.set("github", process.env.GH_TOKEN!, {
33
+ * host: "api.github.com",
34
+ * injection: { type: "header", name: "Authorization" },
35
+ * });
36
+ * ```
37
+ */
38
+ declare class OpenSandboxCredentialBroker implements CredentialBroker {
39
+ private readonly useServerProxy?;
40
+ private readonly vault;
41
+ constructor(control: ControlClient, useServerProxy?: boolean | undefined);
42
+ set(sandboxId: string, name: string, value: string, binding: CredentialBinding): Promise<void>;
43
+ /**
44
+ * Both `changes.value` and `changes.binding` are required — the vault's `GET` response never
45
+ * echoes credential values back (by design, for security), so there is no way to preserve
46
+ * "the current value" while only replacing the binding, or vice versa. Pass both.
47
+ */
48
+ patch(sandboxId: string, name: string, changes: Partial<{
49
+ value: string;
50
+ binding: CredentialBinding;
51
+ }>): Promise<void>;
52
+ remove(sandboxId: string, name: string): Promise<void>;
53
+ listBindings(sandboxId: string): Promise<Array<{
54
+ name: string;
55
+ binding: CredentialBinding;
56
+ }>>;
57
+ }
58
+ //#endregion
59
+ //#region src/vault-client.d.ts
60
+ /** Thrown for a non-2xx response from the egress sidecar's Credential Vault API. */
61
+ declare class VaultClientError extends Error {
62
+ readonly status: number;
63
+ constructor(message: string, status: number);
64
+ }
65
+ /**
66
+ * A credential's value, as the sidecar's Go source (`components/egress/pkg/credentialvault`)
67
+ * accepts it. `inline` is the only source type registered by default — the sidecar's
68
+ * `SourceRegistry` supports others (e.g. vault-backed) but nothing this package emits uses them.
69
+ */
70
+ type WireCredentialSource = {
71
+ type: "inline";
72
+ value: string;
73
+ };
74
+ interface WireCredential {
75
+ name: string;
76
+ source: WireCredentialSource;
77
+ }
78
+ interface WireMatch {
79
+ hosts: string[];
80
+ schemes?: string[];
81
+ methods?: string[];
82
+ paths?: string[];
83
+ }
84
+ interface WireCustomHeaderEntry {
85
+ name: string;
86
+ credential: string;
87
+ }
88
+ interface WireSubstitution {
89
+ credential: string;
90
+ placeholder: string;
91
+ in: Array<"path" | "query" | "header" | "body">;
92
+ }
93
+ /**
94
+ * `bearer`/`basic` inject `Authorization: Bearer|Basic <value>` (header name is fixed).
95
+ * `apiKey` injects `<value>` under a caller-chosen header name — this is what alineo's
96
+ * `{ type: "header", name }` binding maps to, since it carries the value unprefixed.
97
+ * `customHeaders`/`passthrough`/substitutions exist on the wire but nothing in this package
98
+ * produces them yet.
99
+ */
100
+ interface WireAuth {
101
+ type: "bearer" | "basic" | "apiKey" | "customHeaders" | "passthrough";
102
+ credential?: string;
103
+ name?: string;
104
+ headers?: WireCustomHeaderEntry[];
105
+ substitutions?: WireSubstitution[];
106
+ }
107
+ interface WireBinding {
108
+ name: string;
109
+ match: WireMatch;
110
+ auth: WireAuth;
111
+ }
112
+ interface WireCredentialMetadata {
113
+ name: string;
114
+ sourceType: string;
115
+ revision: number;
116
+ }
117
+ interface WireAuthMetadata {
118
+ type: string;
119
+ name?: string;
120
+ }
121
+ interface WireBindingMetadata {
122
+ name: string;
123
+ revision: number;
124
+ match: WireMatch;
125
+ auth: WireAuthMetadata;
126
+ }
127
+ /** `GET /credential-vault` response — sanitized: no credential values, ever. */
128
+ interface VaultState {
129
+ revision: number;
130
+ credentials: WireCredentialMetadata[];
131
+ bindings: WireBindingMetadata[];
132
+ }
133
+ interface CreateRequest {
134
+ credentials: WireCredential[];
135
+ bindings: WireBinding[];
136
+ }
137
+ interface MutationSet<T> {
138
+ add?: T[];
139
+ replace?: T[];
140
+ delete?: string[];
141
+ }
142
+ interface MutationRequest {
143
+ expectedRevision?: number;
144
+ credentials?: MutationSet<WireCredential>;
145
+ bindings?: MutationSet<WireBinding>;
146
+ }
147
+ /**
148
+ * Talks directly to a sandbox's egress sidecar Credential Vault management API (port `18080`),
149
+ * resolved the same way `resolveExecClient()` resolves execd's endpoint — via
150
+ * `ControlClient.getEndpoint()` — but against the sidecar's port instead of execd's `44772`.
151
+ *
152
+ * The vault is sidecar-local, runtime-only state (OSEP-0012): it does not survive the sidecar
153
+ * restarting or being rescheduled, and isn't restored by OpenSandbox's own snapshot/checkpoint
154
+ * mechanism. `OpenSandboxCredentialBroker` (this package's `CredentialBroker` implementation)
155
+ * builds on top of this client — most callers should use that rather than `VaultClient` directly.
156
+ *
157
+ * Request/response schema verified against `opensandbox-group/OpenSandbox`'s
158
+ * `components/egress/pkg/credentialvault` Go source directly (not just its docs) — the vault has
159
+ * exactly one resource, created once and then mutated: `POST /credential-vault` creates it
160
+ * (409 if it already exists), `PATCH /credential-vault` adds/replaces/deletes individual
161
+ * credentials and bindings by name, `GET /credential-vault` returns sanitized metadata only
162
+ * (values and full auth config are never echoed back), and `DELETE /credential-vault` removes
163
+ * the whole vault — there is no per-credential DELETE route.
164
+ */
165
+ declare class VaultClient {
166
+ private readonly control;
167
+ private static readonly PORT;
168
+ constructor(control: ControlClient);
169
+ private request;
170
+ /** Creates the sandbox's Credential Vault. Throws `VaultClientError` with `status: 409` if one already exists — see `createOrPatch()`. */
171
+ create(sandboxId: string, req: CreateRequest, useServerProxy?: boolean): Promise<VaultState>;
172
+ /** Adds/replaces/deletes individual credentials and bindings on an existing vault. */
173
+ patch(sandboxId: string, req: MutationRequest, useServerProxy?: boolean): Promise<VaultState>;
174
+ /** Sanitized metadata only — never returns credential values or full auth config. */
175
+ get(sandboxId: string, useServerProxy?: boolean): Promise<VaultState>;
176
+ /** Deletes the *entire* vault (all credentials and bindings) — there is no per-credential delete route. */
177
+ remove(sandboxId: string, useServerProxy?: boolean): Promise<void>;
178
+ /**
179
+ * Upserts one credential+binding pair: creates the vault if this is the sandbox's first
180
+ * credential, otherwise patches it in (`replace` if a credential of this name already exists,
181
+ * `add` if it doesn't — an extra `get()` round-trip to tell those apart, since the wire API
182
+ * has no single "upsert" mutation).
183
+ *
184
+ * Retries the initial `create()` briefly on 500/502/412: right after a sandbox (or fork) is
185
+ * created, the egress sidecar's TCP listener can accept a connection a moment before its
186
+ * request-handling — auth-token check, mitmproxy/nftables readiness gate — is fully wired up,
187
+ * which surfaces as a generic proxy 500 (or the sidecar's own 412 "not ready") rather than a
188
+ * clean connection-refused. `set()` on an already-warm sandbox (the common case) succeeds on
189
+ * the first try; this only pays the retry cost right after creation.
190
+ */
191
+ createOrPatch(sandboxId: string, credential: WireCredential, binding: WireBinding, useServerProxy?: boolean): Promise<VaultState>;
192
+ }
193
+ //#endregion
194
+ export { type CreateRequest, type MutationRequest, OpenSandboxCredentialBroker, UnsupportedInjectionError, VaultClient, VaultClientError, type VaultState, type WireAuth, type WireBinding, type WireCredential, type WireCredentialSource, type WireMatch };
package/dist/index.mjs ADDED
@@ -0,0 +1,236 @@
1
+ //#region src/vault-client.ts
2
+ /** Thrown for a non-2xx response from the egress sidecar's Credential Vault API. */
3
+ var VaultClientError = class extends Error {
4
+ status;
5
+ constructor(message, status) {
6
+ super(message);
7
+ this.status = status;
8
+ this.name = "VaultClientError";
9
+ }
10
+ };
11
+ /**
12
+ * Talks directly to a sandbox's egress sidecar Credential Vault management API (port `18080`),
13
+ * resolved the same way `resolveExecClient()` resolves execd's endpoint — via
14
+ * `ControlClient.getEndpoint()` — but against the sidecar's port instead of execd's `44772`.
15
+ *
16
+ * The vault is sidecar-local, runtime-only state (OSEP-0012): it does not survive the sidecar
17
+ * restarting or being rescheduled, and isn't restored by OpenSandbox's own snapshot/checkpoint
18
+ * mechanism. `OpenSandboxCredentialBroker` (this package's `CredentialBroker` implementation)
19
+ * builds on top of this client — most callers should use that rather than `VaultClient` directly.
20
+ *
21
+ * Request/response schema verified against `opensandbox-group/OpenSandbox`'s
22
+ * `components/egress/pkg/credentialvault` Go source directly (not just its docs) — the vault has
23
+ * exactly one resource, created once and then mutated: `POST /credential-vault` creates it
24
+ * (409 if it already exists), `PATCH /credential-vault` adds/replaces/deletes individual
25
+ * credentials and bindings by name, `GET /credential-vault` returns sanitized metadata only
26
+ * (values and full auth config are never echoed back), and `DELETE /credential-vault` removes
27
+ * the whole vault — there is no per-credential DELETE route.
28
+ */
29
+ var VaultClient = class VaultClient {
30
+ control;
31
+ static PORT = 18080;
32
+ constructor(control) {
33
+ this.control = control;
34
+ }
35
+ async request(sandboxId, method, useServerProxy, body) {
36
+ const ep = await this.control.getEndpoint(sandboxId, VaultClient.PORT, useServerProxy);
37
+ const baseUrl = ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`;
38
+ const res = await fetch(`${baseUrl}/credential-vault`, {
39
+ method,
40
+ headers: {
41
+ ...ep.headers,
42
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
43
+ },
44
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
45
+ });
46
+ if (!res.ok) throw new VaultClientError(await res.text().catch(() => "") || "Credential Vault API error", res.status);
47
+ if (res.status === 204) return void 0;
48
+ return res.json();
49
+ }
50
+ /** Creates the sandbox's Credential Vault. Throws `VaultClientError` with `status: 409` if one already exists — see `createOrPatch()`. */
51
+ create(sandboxId, req, useServerProxy) {
52
+ return this.request(sandboxId, "POST", useServerProxy, req);
53
+ }
54
+ /** Adds/replaces/deletes individual credentials and bindings on an existing vault. */
55
+ patch(sandboxId, req, useServerProxy) {
56
+ return this.request(sandboxId, "PATCH", useServerProxy, req);
57
+ }
58
+ /** Sanitized metadata only — never returns credential values or full auth config. */
59
+ get(sandboxId, useServerProxy) {
60
+ return this.request(sandboxId, "GET", useServerProxy);
61
+ }
62
+ /** Deletes the *entire* vault (all credentials and bindings) — there is no per-credential delete route. */
63
+ remove(sandboxId, useServerProxy) {
64
+ return this.request(sandboxId, "DELETE", useServerProxy);
65
+ }
66
+ /**
67
+ * Upserts one credential+binding pair: creates the vault if this is the sandbox's first
68
+ * credential, otherwise patches it in (`replace` if a credential of this name already exists,
69
+ * `add` if it doesn't — an extra `get()` round-trip to tell those apart, since the wire API
70
+ * has no single "upsert" mutation).
71
+ *
72
+ * Retries the initial `create()` briefly on 500/502/412: right after a sandbox (or fork) is
73
+ * created, the egress sidecar's TCP listener can accept a connection a moment before its
74
+ * request-handling — auth-token check, mitmproxy/nftables readiness gate — is fully wired up,
75
+ * which surfaces as a generic proxy 500 (or the sidecar's own 412 "not ready") rather than a
76
+ * clean connection-refused. `set()` on an already-warm sandbox (the common case) succeeds on
77
+ * the first try; this only pays the retry cost right after creation.
78
+ */
79
+ async createOrPatch(sandboxId, credential, binding, useServerProxy) {
80
+ const delaysMs = [
81
+ 0,
82
+ 300,
83
+ 600,
84
+ 1200,
85
+ 2400
86
+ ];
87
+ for (let attempt = 0; attempt < delaysMs.length; attempt++) {
88
+ if (delaysMs[attempt] > 0) await new Promise((r) => setTimeout(r, delaysMs[attempt]));
89
+ try {
90
+ return await this.create(sandboxId, {
91
+ credentials: [credential],
92
+ bindings: [binding]
93
+ }, useServerProxy);
94
+ } catch (err) {
95
+ const retryable = err instanceof VaultClientError && (err.status === 500 || err.status === 502 || err.status === 412);
96
+ const isLastAttempt = attempt === delaysMs.length - 1;
97
+ if (!retryable || isLastAttempt) {
98
+ if (!(err instanceof VaultClientError) || err.status !== 409) throw err;
99
+ break;
100
+ }
101
+ }
102
+ }
103
+ const exists = (await this.get(sandboxId, useServerProxy)).credentials.some((c) => c.name === credential.name);
104
+ return this.patch(sandboxId, exists ? {
105
+ credentials: { replace: [credential] },
106
+ bindings: { replace: [binding] }
107
+ } : {
108
+ credentials: { add: [credential] },
109
+ bindings: { add: [binding] }
110
+ }, useServerProxy);
111
+ }
112
+ };
113
+ //#endregion
114
+ //#region src/broker.ts
115
+ /**
116
+ * Thrown when a `CredentialBinding.injection` has no equivalent in the sidecar's real `Auth`
117
+ * model. Only header injection (`{ type: "header" }`) maps onto it today — it supports
118
+ * `bearer`/`basic`/`apiKey`/`customHeaders` header injection and placeholder `substitutions`
119
+ * (for path/query/body), but not an arbitrary named query param or path segment the way this
120
+ * package's `{ type: "query" }`/`{ type: "path" }` binding shapes imply. Wire those up to
121
+ * `substitutions` (which needs a literal placeholder string in the request, a different model
122
+ * from "inject a named param") before lifting this restriction.
123
+ */
124
+ var UnsupportedInjectionError = class extends Error {
125
+ constructor(injectionType) {
126
+ super(`Credential injection type "${injectionType}" is not yet supported by @alineo-labs/vault — only { type: "header" } maps onto the egress sidecar's real Credential Vault API today.`);
127
+ this.name = "UnsupportedInjectionError";
128
+ }
129
+ };
130
+ function toWireAuth(name, injection) {
131
+ if (injection.type !== "header") throw new UnsupportedInjectionError(injection.type);
132
+ return {
133
+ type: "apiKey",
134
+ name: injection.name,
135
+ credential: name
136
+ };
137
+ }
138
+ function toWireBinding(name, binding) {
139
+ return {
140
+ name,
141
+ match: {
142
+ hosts: [binding.host],
143
+ ...binding.pathPrefix ? { paths: [`${binding.pathPrefix}*`] } : {}
144
+ },
145
+ auth: toWireAuth(name, binding.injection)
146
+ };
147
+ }
148
+ function fromWireBindingMetadata(meta) {
149
+ if (meta.auth.type !== "apiKey" || !meta.auth.name) throw new UnsupportedInjectionError(meta.auth.type);
150
+ const path = meta.match.paths?.[0];
151
+ return {
152
+ host: meta.match.hosts[0] ?? "",
153
+ ...path && path !== "/*" ? { pathPrefix: path.replace(/\*$/, "") } : {},
154
+ injection: {
155
+ type: "header",
156
+ name: meta.auth.name
157
+ }
158
+ };
159
+ }
160
+ /**
161
+ * Default `CredentialBroker` implementation, backed by OpenSandbox's own Credential Vault.
162
+ *
163
+ * `Sandbox` (from `@alineo-labs/sandbox`) constructs one of these automatically, wired to its
164
+ * own internal `ControlClient`, when `SandboxClientOptions.credentialBroker` is omitted — most
165
+ * callers never need to construct this directly.
166
+ *
167
+ * @example
168
+ * ```ts
169
+ * const sb = await client.sandbox({
170
+ * image: "node:22",
171
+ * resources: { cpu: "500m", memory: "512Mi" },
172
+ * networkPolicy: { defaultAction: "deny", egress: [{ action: "allow", target: "api.github.com" }] },
173
+ * credentialProxy: true,
174
+ * });
175
+ * await sb.credentials.set("github", process.env.GH_TOKEN!, {
176
+ * host: "api.github.com",
177
+ * injection: { type: "header", name: "Authorization" },
178
+ * });
179
+ * ```
180
+ */
181
+ var OpenSandboxCredentialBroker = class {
182
+ useServerProxy;
183
+ vault;
184
+ constructor(control, useServerProxy) {
185
+ this.useServerProxy = useServerProxy;
186
+ this.vault = new VaultClient(control);
187
+ }
188
+ async set(sandboxId, name, value, binding) {
189
+ const credential = {
190
+ name,
191
+ source: {
192
+ type: "inline",
193
+ value
194
+ }
195
+ };
196
+ const wireBinding = toWireBinding(name, binding);
197
+ try {
198
+ await this.vault.createOrPatch(sandboxId, credential, wireBinding, this.useServerProxy);
199
+ } catch (err) {
200
+ if (err instanceof VaultClientError && err.status === 404) throw new VaultClientError(`Sandbox ${sandboxId} has no Credential Vault — was it created with credentialProxy: true?`, 404);
201
+ throw err;
202
+ }
203
+ }
204
+ /**
205
+ * Both `changes.value` and `changes.binding` are required — the vault's `GET` response never
206
+ * echoes credential values back (by design, for security), so there is no way to preserve
207
+ * "the current value" while only replacing the binding, or vice versa. Pass both.
208
+ */
209
+ async patch(sandboxId, name, changes) {
210
+ if (changes.value === void 0 || changes.binding === void 0) throw new Error("OpenSandboxCredentialBroker.patch() requires both `value` and `binding` — the sidecar's Credential Vault never echoes values back, so a partial update can't preserve the unspecified half.");
211
+ await this.vault.patch(sandboxId, {
212
+ credentials: { replace: [{
213
+ name,
214
+ source: {
215
+ type: "inline",
216
+ value: changes.value
217
+ }
218
+ }] },
219
+ bindings: { replace: [toWireBinding(name, changes.binding)] }
220
+ }, this.useServerProxy);
221
+ }
222
+ async remove(sandboxId, name) {
223
+ await this.vault.patch(sandboxId, {
224
+ credentials: { delete: [name] },
225
+ bindings: { delete: [name] }
226
+ }, this.useServerProxy);
227
+ }
228
+ async listBindings(sandboxId) {
229
+ return (await this.vault.get(sandboxId, this.useServerProxy)).bindings.map((b) => ({
230
+ name: b.name,
231
+ binding: fromWireBindingMetadata(b)
232
+ }));
233
+ }
234
+ };
235
+ //#endregion
236
+ export { OpenSandboxCredentialBroker, UnsupportedInjectionError, VaultClient, VaultClientError };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@alineo-labs/vault",
3
+ "version": "0.2.0",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/DrejT/alineo.git",
8
+ "directory": "packages/adapters/vault"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "type": "module",
14
+ "main": "./dist/index.mjs",
15
+ "types": "./dist/index.d.mts",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.mjs",
19
+ "types": "./dist/index.d.mts"
20
+ }
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "provenance": true
25
+ },
26
+ "scripts": {
27
+ "build": "tsdown"
28
+ },
29
+ "dependencies": {
30
+ "@alineo-labs/core": "0.3.0",
31
+ "@alineo-labs/opensandbox": "0.2.0"
32
+ },
33
+ "devDependencies": {
34
+ "bun-types": "1.3.14",
35
+ "tsdown": "0.22.3",
36
+ "typescript": "6.0.3"
37
+ }
38
+ }