@vite-hub/env 0.0.3 → 0.1.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.
Files changed (50) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +243 -28
  3. package/dist/access-B3qzBHye.js +54 -0
  4. package/dist/auth.d.ts +32 -0
  5. package/dist/auth.js +44 -0
  6. package/dist/bridge-CdNdTN1V.d.ts +374 -0
  7. package/dist/bridge-error-CFuU5zIz.js +65 -0
  8. package/dist/bridge.d.ts +2 -0
  9. package/dist/bridge.js +192 -0
  10. package/dist/cli-CMQPQbii.js +487 -0
  11. package/dist/cli-DEwcUIe0.d.ts +81 -0
  12. package/dist/cli.d.ts +41 -0
  13. package/dist/cli.js +2 -0
  14. package/dist/database.d.ts +21 -0
  15. package/dist/database.js +183 -0
  16. package/dist/declarations-CiRdb1qP.d.ts +32 -0
  17. package/dist/declarations-DAVgctKD.js +236 -0
  18. package/dist/error-diagnostics-CrxjYNYr.js +43 -0
  19. package/dist/http.d.ts +2 -0
  20. package/dist/http.js +122 -0
  21. package/dist/index.d.ts +13 -8
  22. package/dist/index.js +5 -4
  23. package/dist/internal/agent.d.ts +5 -0
  24. package/dist/internal/agent.js +22 -0
  25. package/dist/internal/connections.d.ts +18 -0
  26. package/dist/internal/connections.js +31 -0
  27. package/dist/presets.d.ts +15 -6
  28. package/dist/presets.js +21 -2
  29. package/dist/provider.d.ts +5 -0
  30. package/dist/provider.js +8 -0
  31. package/dist/schema.d.ts +5 -6
  32. package/dist/schema.js +26 -8
  33. package/dist/seal.d.ts +14 -0
  34. package/dist/seal.js +49 -0
  35. package/dist/secret-C2191nAa.d.ts +11 -0
  36. package/dist/secret.d.ts +1 -10
  37. package/dist/server-DufVswRJ.js +670 -0
  38. package/dist/server.d.ts +23 -4
  39. package/dist/server.js +2 -3
  40. package/dist/values-D_r6V774.js +148 -0
  41. package/dist/virtual-module.d.ts +34 -0
  42. package/dist/virtual.d.ts +2 -15
  43. package/dist/vite.d.ts +37 -14
  44. package/dist/vite.js +1058 -292
  45. package/package.json +84 -16
  46. package/dist/declarations-BIBfEwer.d.ts +0 -23
  47. package/dist/declarations-Cy5XamUA.js +0 -144
  48. package/dist/errors-RUmAFDJn.js +0 -112
  49. package/dist/server-B2Dp8Nc0.js +0 -59
  50. package/dist/types-FcnPKias.d.ts +0 -153
package/dist/auth.js ADDED
@@ -0,0 +1,44 @@
1
+ import { r as grantEnvAccess } from "./access-B3qzBHye.js";
2
+ //#region src/auth.ts
3
+ const permissions = [
4
+ "inspect",
5
+ "preview",
6
+ "replace",
7
+ "use"
8
+ ];
9
+ function identifier(value) {
10
+ return typeof value === "string" && value.length > 0 && value.length <= 512 && !/[\u0000-\u001f]/.test(value);
11
+ }
12
+ /** Authenticate management requests without coupling Env to a particular Better Auth plugin version. */
13
+ function createEnvAuthenticator(options) {
14
+ return async (request) => {
15
+ try {
16
+ const authorization = request.headers.get("authorization");
17
+ if (authorization !== null) {
18
+ if (!/^Bearer\s+\S+$/i.test(authorization) || !options.agents) return null;
19
+ const session = await options.agents.getSession({ headers: request.headers });
20
+ if (!session || !identifier(session.agent.id)) return null;
21
+ const scope = await options.agents.scope(session);
22
+ if (!Array.isArray(scope) || scope.some((grant) => !identifier(grant.key) || !Array.isArray(grant.permissions) || grant.permissions.some((permission) => !permissions.includes(permission)))) return null;
23
+ return grantEnvAccess({ actor: {
24
+ kind: "agent",
25
+ id: session.agent.id
26
+ } }, {
27
+ kind: "actor",
28
+ scope
29
+ });
30
+ }
31
+ const session = await options.getSession({ headers: request.headers });
32
+ if (!session || !identifier(session.user.id)) return null;
33
+ const actor = {
34
+ kind: "user",
35
+ id: session.user.id
36
+ };
37
+ return grantEnvAccess({ actor }, await options.isAdmin(session) === true ? { kind: "admin" } : { kind: "actor" });
38
+ } catch {
39
+ return null;
40
+ }
41
+ };
42
+ }
43
+ //#endregion
44
+ export { createEnvAuthenticator };
@@ -0,0 +1,374 @@
1
+ import { t as SecretEnv } from "./secret-C2191nAa.js";
2
+ //#region src/internal/access.d.ts
3
+ /** Marks the type of contexts that Env creates. The bridge trusts only the `envAccess` grant registry, not this marker. */
4
+ declare const envAccessGrant: unique symbol;
5
+ interface EnvAttribution {
6
+ traceId?: string;
7
+ invocationId?: string;
8
+ }
9
+ //#endregion
10
+ //#region src/http.d.ts
11
+ interface EnvManagement {
12
+ bridge: EnvBridge;
13
+ authenticate(request: Request): EnvAccessContext | null | Promise<EnvAccessContext | null>;
14
+ }
15
+ type EnvManagementResolver = (path: string) => {
16
+ key: string;
17
+ management: EnvManagement;
18
+ } | undefined;
19
+ /** Mount only on a server route. resolve selects declared credentials, never arbitrary store keys. */
20
+ declare function createEnvBridgeHandler(resolve: EnvManagementResolver): (request: Request) => Promise<Response>;
21
+ //#endregion
22
+ //#region src/types.d.ts
23
+ type EnvDiagnostics = "off" | "summary" | "trace";
24
+ type EnvMode = "build" | "runtime";
25
+ interface EnvIntegrationOptions {
26
+ diagnostics?: EnvDiagnostics;
27
+ /**
28
+ * Prefix of canonical variable names. Every env-backed declaration first reads the prefix plus its
29
+ * path in upper snake case, then its conventional names. Defaults to `"VITEHUB_"`. `false` disables it.
30
+ */
31
+ prefix?: string | false;
32
+ projectRoot?: string;
33
+ providers?: Record<string, string>;
34
+ runtimeImports?: EnvRuntimeImportSpecifiers;
35
+ }
36
+ interface EnvRuntimeImportSpecifiers {
37
+ secret?: string;
38
+ server?: string;
39
+ }
40
+ interface EnvSourceContext {
41
+ build: {
42
+ timestamp: () => string;
43
+ };
44
+ env: Record<string, string | undefined>;
45
+ git: {
46
+ branch: () => Promise<string>;
47
+ commit: (options?: {
48
+ short?: boolean;
49
+ }) => Promise<string>;
50
+ ref: () => Promise<string>;
51
+ sha: (options?: {
52
+ short?: boolean;
53
+ }) => Promise<string>;
54
+ tag: () => Promise<string | undefined>;
55
+ };
56
+ mode: EnvMode;
57
+ packageJson: () => Promise<Record<string, unknown>>;
58
+ rootDir: string;
59
+ }
60
+ type EnvSourceResolver = (context: EnvSourceContext) => unknown | Promise<unknown>;
61
+ type EnvSource = {
62
+ kind: "custom";
63
+ label: string;
64
+ resolver: EnvSourceResolver;
65
+ serializable: false;
66
+ } | {
67
+ kind: "env";
68
+ label: string;
69
+ name: string;
70
+ names?: string[];
71
+ /** The canonical name, `VITEHUB_<PATH>`, which the ordered names read first. */
72
+ canonical?: string | false;
73
+ /** Treat empty host values as missing when reading the ordered names. */
74
+ skipEmpty?: boolean;
75
+ serializable: true;
76
+ } | {
77
+ kind: "git-branch";
78
+ label: "git:branch";
79
+ serializable: true;
80
+ } | {
81
+ kind: "git-commit";
82
+ label: "git:commit";
83
+ serializable: true;
84
+ short?: boolean;
85
+ } | {
86
+ kind: "git-ref";
87
+ label: "git:ref";
88
+ serializable: true;
89
+ } | {
90
+ kind: "git-sha";
91
+ label: "git:sha";
92
+ serializable: true;
93
+ short?: boolean;
94
+ } | {
95
+ kind: "git-tag";
96
+ label: "git:tag";
97
+ serializable: true;
98
+ } | {
99
+ kind: "build-timestamp";
100
+ label: "build:timestamp";
101
+ serializable: true;
102
+ } | {
103
+ kind: "package-json";
104
+ label: string;
105
+ path: string;
106
+ serializable: true;
107
+ } | {
108
+ key: string;
109
+ kind: "provider";
110
+ label: "provider";
111
+ provider: string;
112
+ serializable: true;
113
+ };
114
+ interface EnvVariableDeclaration {
115
+ default?: unknown;
116
+ kind: "env-variable";
117
+ mode: EnvMode;
118
+ required: boolean;
119
+ schema: unknown;
120
+ secret: boolean;
121
+ source?: EnvSource;
122
+ type?: string;
123
+ }
124
+ interface EnvVariableOptions {
125
+ default?: unknown;
126
+ mode?: EnvMode;
127
+ optional?: boolean;
128
+ required?: boolean;
129
+ schema?: unknown;
130
+ secret?: boolean;
131
+ source?: EnvSource | EnvSourceResolver;
132
+ type?: string;
133
+ }
134
+ /** Options for `env.boolean()`, `env.number()`, and `env.enum()`. The helper owns the parser and type. */
135
+ interface EnvTypedVariableOptions<TValue> extends Omit<EnvVariableOptions, "default" | "schema" | "type"> {
136
+ default?: TValue;
137
+ }
138
+ /** Serializable parser for one Server Env value. Host and provider values are strings before parsing. */
139
+ type EnvValueSchema = {
140
+ kind: "boolean";
141
+ } | {
142
+ kind: "enum";
143
+ values: readonly string[];
144
+ } | {
145
+ kind: "number";
146
+ min?: number;
147
+ max?: number;
148
+ isInt?: boolean;
149
+ decimal?: boolean;
150
+ } | {
151
+ kind: "string";
152
+ minLength?: number;
153
+ maxLength?: number;
154
+ } | {
155
+ kind: "url";
156
+ } | {
157
+ kind: "array";
158
+ items?: EnvValueSchema;
159
+ } | {
160
+ kind: "object";
161
+ properties?: Record<string, EnvValueSchema>;
162
+ };
163
+ type EnvBuildStaticValue = null | string | number | boolean | EnvBuildStaticValue[];
164
+ type EnvBuildConfigValue = EnvBuildConfigOptions | EnvBuildStaticValue | EnvVariableDeclaration;
165
+ interface EnvBuildConfigOptions {
166
+ [key: string]: EnvBuildConfigValue;
167
+ }
168
+ interface EnvViteConfigOptions {
169
+ define?: Record<string, EnvBuildConfigValue>;
170
+ public?: Record<string, EnvVariableDeclaration>;
171
+ server?: EnvRuntimeConfigOptions;
172
+ }
173
+ type EnvRuntimeStaticValue = null | string | number | boolean | EnvRuntimeStaticValue[];
174
+ type EnvRuntimeConfigValue = EnvRuntimeConfigOptions | EnvRuntimeStaticValue | EnvVariableDeclaration;
175
+ interface EnvRuntimeConfigOptions {
176
+ [key: string]: EnvRuntimeConfigValue;
177
+ }
178
+ type EnvConfigOptions = EnvViteConfigOptions;
179
+ interface EnvViteUserConfig {
180
+ env?: EnvViteConfigOptions;
181
+ }
182
+ interface EnvDiagnosticEntry {
183
+ exposed: string;
184
+ key: string;
185
+ masked: boolean;
186
+ mode: EnvMode;
187
+ source: string;
188
+ status: "defaulted" | "missing" | "valid";
189
+ timing: string;
190
+ type?: string;
191
+ }
192
+ interface EnvRegistryEntry {
193
+ default?: unknown;
194
+ required: boolean;
195
+ schema?: EnvValueSchema;
196
+ secret: boolean;
197
+ source: Extract<EnvSource, {
198
+ kind: "env" | "provider";
199
+ }>;
200
+ }
201
+ interface EnvRuntimeLiteralEntry {
202
+ kind: "literal";
203
+ value: EnvRuntimeStaticValue;
204
+ }
205
+ type EnvRuntimeRegistryValue = EnvRegistryEntry | EnvRuntimeLiteralEntry | EnvRuntimeRegistry;
206
+ declare const serverEnvType: unique symbol;
207
+ interface EnvRuntimeRegistry<TServerEnv extends Record<string, unknown> = Record<string, unknown>> {
208
+ [key: string]: EnvRuntimeRegistryValue;
209
+ readonly [serverEnvType]?: (value: TServerEnv) => void;
210
+ }
211
+ interface ServerEnv {
212
+ [key: string]: unknown;
213
+ }
214
+ type PublicEnv = Record<string, unknown>;
215
+ interface EnvProviderContext<TEnv extends Record<string, unknown> = Record<string, unknown>> {
216
+ env: DeepReadonly<TEnv>;
217
+ access?: EnvAccessContext;
218
+ signal?: AbortSignal;
219
+ }
220
+ type EnvProviderValues = Readonly<Record<string, string | undefined>>;
221
+ interface EnvProvider<TEnv extends Record<string, unknown> = Record<string, unknown>> {
222
+ management?: EnvManagement;
223
+ read(input: EnvProviderContext<TEnv> & {
224
+ keys: readonly string[];
225
+ }): EnvProviderValues | Promise<EnvProviderValues>;
226
+ }
227
+ type EnvProviders = Record<string, EnvProvider>;
228
+ interface LoadServerEnvOptions {
229
+ access?: EnvAccessContext;
230
+ providers?: EnvProviders;
231
+ signal?: AbortSignal;
232
+ }
233
+ type DeepReadonly<T> = T extends SecretEnv<unknown> ? T : T extends ((...args: infer TArguments) => infer TResult) ? (...args: TArguments) => TResult : T extends object ? { readonly [TKey in keyof T]: DeepReadonly<T[TKey]>; } : T;
234
+ type ServerEnvInspectionStatus = "available" | "defaulted" | "error" | "invalid" | "missing";
235
+ interface ServerEnvInspectionEntry {
236
+ /** The declaration is secret. Inspection never returns values. */
237
+ masked: boolean;
238
+ path?: string;
239
+ /** Provider alias for provider-backed declarations. */
240
+ provider?: string;
241
+ required: boolean;
242
+ source: "env" | "literal" | "provider";
243
+ status: ServerEnvInspectionStatus;
244
+ /** Which kind of variable name supplied an env value: the canonical `VITEHUB_<PATH>` name, or a conventional name. */
245
+ via?: "canonical" | "conventional";
246
+ /** The canonical name and a conventional name are both set to different values. The canonical name wins. */
247
+ conflict?: true;
248
+ }
249
+ interface ServerEnvDescriptionEntry {
250
+ path?: string;
251
+ /** The canonical variable name of an env declaration, such as `VITEHUB_CLIPROXY_API_KEY`. It is read first. */
252
+ canonicalName?: string;
253
+ source: "env" | "literal" | "provider";
254
+ provider?: string;
255
+ secret: boolean;
256
+ required: boolean;
257
+ hasDefault: boolean;
258
+ /** TypeScript type of the parsed value, for example `boolean` or `"draft" | "send"`. Omitted for literals. */
259
+ type?: string;
260
+ }
261
+ interface ServerEnvDescription {
262
+ entries: readonly ServerEnvDescriptionEntry[];
263
+ }
264
+ interface ServerEnvInspection {
265
+ entries: readonly ServerEnvInspectionEntry[];
266
+ }
267
+ //#endregion
268
+ //#region src/bridge.d.ts
269
+ type EnvPermission = "inspect" | "preview" | "replace" | "use";
270
+ interface EnvActor {
271
+ id: string;
272
+ kind: "user" | "agent" | "service";
273
+ }
274
+ /** A ceiling over durable grants, from a verified Agent token. */
275
+ type EnvAccessScope = readonly {
276
+ readonly key: string;
277
+ readonly permissions: readonly EnvPermission[];
278
+ }[];
279
+ /**
280
+ * A frozen context that only Env creates. Use the type in application code, but get the value from
281
+ * `createEnvAuthenticator()`, the bridge runtime, or a ViteHub integration. Keep it in trusted request code.
282
+ */
283
+ interface EnvAccessContext {
284
+ readonly [envAccessGrant]: true;
285
+ readonly actor: Readonly<EnvActor>;
286
+ /** Only `createEnvAuthenticator()` creates an administrator context. */
287
+ readonly admin?: true;
288
+ /** Optional credential/permission ceiling from a verified agent token. */
289
+ readonly scope?: EnvAccessScope;
290
+ readonly traceId?: string;
291
+ readonly invocationId?: string;
292
+ }
293
+ interface EnvGrant {
294
+ actor: EnvActor;
295
+ key: string;
296
+ permissions: readonly EnvPermission[];
297
+ }
298
+ interface EnvSecretMetadata {
299
+ revision: string;
300
+ updatedAt: string;
301
+ preview?: string;
302
+ }
303
+ interface EnvReplacement extends EnvSecretMetadata {
304
+ activation: "next-resolution" | "restart" | "deploy";
305
+ }
306
+ interface EnvSecretStore {
307
+ inspect(key: string): Promise<EnvSecretMetadata | undefined>;
308
+ read(key: string): Promise<{
309
+ value: string;
310
+ revision?: string;
311
+ } | undefined>;
312
+ replace(input: {
313
+ key: string;
314
+ value: string;
315
+ expectedRevision: string | null;
316
+ }): Promise<EnvReplacement>;
317
+ }
318
+ interface EnvActivity {
319
+ id: string;
320
+ operationId: string;
321
+ timestamp: string;
322
+ actor: EnvActor;
323
+ key: string;
324
+ action: "inspect" | "preview" | "replace" | "resolve" | "use" | "grant" | "revoke";
325
+ outcome: "started" | "succeeded" | "failed" | "denied";
326
+ revision?: string;
327
+ operation?: string;
328
+ target?: EnvActor;
329
+ permissions?: readonly EnvPermission[];
330
+ traceId?: string;
331
+ invocationId?: string;
332
+ }
333
+ interface EnvAccessStore {
334
+ append(event: EnvActivity): Promise<void>;
335
+ activity(input: {
336
+ key: string;
337
+ before?: string;
338
+ limit: number;
339
+ }): Promise<readonly EnvActivity[]>;
340
+ grants(key: string): Promise<readonly EnvGrant[]>;
341
+ setGrant(grant: EnvGrant): Promise<void>;
342
+ revokeGrant(actor: EnvActor, key: string): Promise<void>;
343
+ }
344
+ interface EnvBridgeOptions {
345
+ secrets: EnvSecretStore;
346
+ access: EnvAccessStore;
347
+ /** The identity of this runtime. Reads without an explicit access context get only its durable grants. */
348
+ runtimeActor: EnvActor;
349
+ /** Optional trace and invocation IDs for runtime reads, from trusted invocation context. */
350
+ runtimeAttribution?: () => EnvAttribution | undefined | Promise<EnvAttribution | undefined>;
351
+ /** Export already persisted events, for example through evlog. */
352
+ emit?: (event: EnvActivity) => void | Promise<void>;
353
+ }
354
+ interface EnvBridge extends EnvProvider {
355
+ permissions(context: EnvAccessContext, key: string): Promise<readonly EnvPermission[]>;
356
+ inspect(context: EnvAccessContext, key: string): Promise<EnvSecretMetadata | undefined>;
357
+ preview(context: EnvAccessContext, key: string): Promise<Pick<EnvSecretMetadata, "preview"> | undefined>;
358
+ replace(context: EnvAccessContext, input: {
359
+ key: string;
360
+ value: string;
361
+ expectedRevision: string | null;
362
+ }): Promise<EnvReplacement>;
363
+ /** Run with the read secret and its revision, when the store provides one. */
364
+ use<T>(context: EnvAccessContext, key: string, operation: string, run: (secret: SecretEnv<string>, metadata?: Readonly<{
365
+ revision?: string;
366
+ }>) => T | Promise<T>): Promise<T>;
367
+ activity(context: EnvAccessContext, key: string, before?: string): Promise<readonly EnvActivity[]>;
368
+ grants(context: EnvAccessContext, key: string): Promise<readonly EnvGrant[]>;
369
+ grant(context: EnvAccessContext, grant: EnvGrant): Promise<void>;
370
+ revoke(context: EnvAccessContext, actor: EnvActor, key: string): Promise<void>;
371
+ }
372
+ declare function createEnvBridge(options: EnvBridgeOptions): EnvBridge;
373
+ //#endregion
374
+ export { EnvValueSchema as A, ServerEnvInspection as B, EnvProviders as C, EnvSourceContext as D, EnvSource as E, LoadServerEnvOptions as F, createEnvBridgeHandler as G, ServerEnvInspectionStatus as H, PublicEnv as I, EnvAttribution as K, ServerEnv as L, EnvVariableOptions as M, EnvViteConfigOptions as N, EnvSourceResolver as O, EnvViteUserConfig as P, ServerEnvDescription as R, EnvProviderValues as S, EnvRuntimeRegistry as T, EnvManagement as U, ServerEnvInspectionEntry as V, EnvManagementResolver as W, EnvDiagnostics as _, EnvActor as a, EnvProvider as b, EnvGrant as c, EnvSecretMetadata as d, EnvSecretStore as f, EnvDiagnosticEntry as g, EnvConfigOptions as h, EnvActivity as i, EnvVariableDeclaration as j, EnvTypedVariableOptions as k, EnvPermission as l, DeepReadonly as m, EnvAccessScope as n, EnvBridge as o, createEnvBridge as p, EnvAccessStore as r, EnvBridgeOptions as s, EnvAccessContext as t, EnvReplacement as u, EnvIntegrationOptions as v, EnvRuntimeConfigOptions as w, EnvProviderContext as x, EnvMode as y, ServerEnvDescriptionEntry as z };
@@ -0,0 +1,65 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ import { ViteHubError, isViteHubError } from "@vite-hub/runtime";
3
+ //#region src/bridge-error.ts
4
+ const messages = {
5
+ denied: "Env access denied.",
6
+ conflict: "The credential changed. Refresh before replacing it.",
7
+ missing: "Credential unavailable.",
8
+ invalid: "Invalid Env request.",
9
+ operation_failed: "Env operation failed.",
10
+ audit_failed: "Env activity could not be persisted.",
11
+ untrusted: "Env did not create this access context."
12
+ };
13
+ function envBridgeError(code) {
14
+ return new ViteHubError(`ENV_BRIDGE_${code.toUpperCase()}`, messages[code]);
15
+ }
16
+ const docs = "https://vitehub.dev/docs/env/bridge#structured-errors";
17
+ const guidance = (fix) => ({
18
+ why: ({ message }) => message,
19
+ fix,
20
+ docs
21
+ });
22
+ /** Repair guidance that the management route adds to each bridge error body. */
23
+ const envBridgeDiagnostics = /*#__PURE__*/ defineDiagnostics({ codes: {
24
+ ENV_BRIDGE_DENIED: guidance("Ask an Env admin to grant the permission for this key."),
25
+ ENV_BRIDGE_CONFLICT: guidance("Reload the credential details, then replace it again."),
26
+ ENV_BRIDGE_MISSING: guidance("Store a value for this credential first."),
27
+ ENV_BRIDGE_INVALID: guidance("Check the request fields and the stored value limits, then send it again."),
28
+ ENV_BRIDGE_OPERATION_FAILED: guidance("Try again. If this continues, read the server logs for this request."),
29
+ ENV_BRIDGE_AUDIT_FAILED: guidance("Check the Env activity store, then try again."),
30
+ ENV_BRIDGE_UNTRUSTED: guidance("Create the access context with the Env bridge authenticate function.")
31
+ } });
32
+ /** The JSON error body of a sanitized bridge error: `code`, `message` (the why), `fix`, and `docs`. */
33
+ function envBridgeErrorBody(error) {
34
+ const code = error.code;
35
+ if (!isEnvBridgeDiagnosticCode(code)) return {
36
+ code,
37
+ message: error.message
38
+ };
39
+ const diagnostic = envBridgeDiagnostics[code]({ message: error.message });
40
+ return {
41
+ code,
42
+ docs: diagnostic.docs,
43
+ fix: diagnostic.fix,
44
+ message: error.message
45
+ };
46
+ }
47
+ function isEnvBridgeDiagnosticCode(code) {
48
+ return Object.hasOwn(envBridgeDiagnostics, code);
49
+ }
50
+ function sanitizeEnvBridgeError(error) {
51
+ if (isViteHubError(error)) {
52
+ for (const code of [
53
+ "denied",
54
+ "conflict",
55
+ "missing",
56
+ "invalid",
57
+ "operation_failed",
58
+ "audit_failed",
59
+ "untrusted"
60
+ ]) if (error.code === `ENV_BRIDGE_${code.toUpperCase()}`) return envBridgeError(code);
61
+ }
62
+ return envBridgeError("operation_failed");
63
+ }
64
+ //#endregion
65
+ export { envBridgeErrorBody as n, sanitizeEnvBridgeError as r, envBridgeError as t };
@@ -0,0 +1,2 @@
1
+ import { a as EnvActor, c as EnvGrant, d as EnvSecretMetadata, f as EnvSecretStore, i as EnvActivity, l as EnvPermission, n as EnvAccessScope, o as EnvBridge, p as createEnvBridge, r as EnvAccessStore, s as EnvBridgeOptions, t as EnvAccessContext, u as EnvReplacement } from "./bridge-CdNdTN1V.js";
2
+ export { EnvAccessContext, EnvAccessScope, EnvAccessStore, EnvActivity, EnvActor, EnvBridge, EnvBridgeOptions, EnvGrant, EnvPermission, EnvReplacement, EnvSecretMetadata, EnvSecretStore, createEnvBridge };
package/dist/bridge.js ADDED
@@ -0,0 +1,192 @@
1
+ import { SecretEnv } from "./secret.js";
2
+ import { r as sanitizeEnvBridgeError, t as envBridgeError } from "./bridge-error-CFuU5zIz.js";
3
+ import { i as validateEnvActor, n as envIdentifier, r as grantEnvAccess, t as envAccessAuthority } from "./access-B3qzBHye.js";
4
+ //#region src/bridge.ts
5
+ async function safe(run) {
6
+ try {
7
+ return await run();
8
+ } catch (error) {
9
+ throw sanitizeEnvBridgeError(error);
10
+ }
11
+ }
12
+ function createEnvBridge(options) {
13
+ async function persist(event) {
14
+ try {
15
+ await options.access.append(event);
16
+ } catch {
17
+ throw envBridgeError("audit_failed");
18
+ }
19
+ try {
20
+ await options.emit?.(structuredClone(event));
21
+ } catch {}
22
+ }
23
+ async function allowed(context, key, permission) {
24
+ const authority = envAccessAuthority(context);
25
+ envIdentifier(key);
26
+ validateEnvActor(context.actor);
27
+ if (authority.kind === "admin") return true;
28
+ if (authority.bridge && authority.bridge !== bridge) return false;
29
+ if (authority.kind === "key") return authority.key === key && permission !== "admin" && authority.permissions.includes(permission);
30
+ if (permission === "admin" || permission === "activity") return false;
31
+ if (authority.scope && !authority.scope.some((grant) => grant.key === key && grant.permissions.includes(permission))) return false;
32
+ return await safe(async () => {
33
+ const grants = await options.access.grants(key);
34
+ if (!Array.isArray(grants)) throw new TypeError("Invalid access grants.");
35
+ for (const grant of grants) {
36
+ if (!grant || typeof grant !== "object" || typeof grant.key !== "string" || !grant.actor || typeof grant.actor !== "object" || typeof grant.actor.id !== "string" || ![
37
+ "user",
38
+ "agent",
39
+ "service"
40
+ ].includes(grant.actor.kind) || !Array.isArray(grant.permissions) || !grant.permissions.every((value) => [
41
+ "inspect",
42
+ "preview",
43
+ "replace",
44
+ "use"
45
+ ].includes(value))) throw new TypeError("Invalid access grant.");
46
+ if (grant.key === key && grant.actor.id === context.actor.id && grant.actor.kind === context.actor.kind && grant.permissions.includes(permission)) return true;
47
+ }
48
+ return false;
49
+ });
50
+ }
51
+ async function audited(context, key, action, permission, run, operation, metadata) {
52
+ envAccessAuthority(context);
53
+ envIdentifier(key);
54
+ validateEnvActor(context.actor);
55
+ const base = {
56
+ operationId: crypto.randomUUID(),
57
+ actor: {
58
+ id: context.actor.id,
59
+ kind: context.actor.kind
60
+ },
61
+ key,
62
+ action,
63
+ ...context.traceId ? { traceId: context.traceId } : {},
64
+ ...context.invocationId ? { invocationId: context.invocationId } : {},
65
+ ...operation ? { operation } : {},
66
+ ...metadata?.target ? { target: metadata.target } : {},
67
+ ...metadata?.permissions ? { permissions: metadata.permissions } : {}
68
+ };
69
+ const event = (outcome) => ({
70
+ ...base,
71
+ id: crypto.randomUUID(),
72
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
73
+ outcome
74
+ });
75
+ if (!await allowed(context, key, permission)) {
76
+ await persist(event("denied"));
77
+ throw envBridgeError("denied");
78
+ }
79
+ await persist(event("started"));
80
+ let value;
81
+ try {
82
+ value = await run();
83
+ } catch (error) {
84
+ const revision = metadata?.revision?.();
85
+ await persist({
86
+ ...event("failed"),
87
+ ...revision ? { revision } : {}
88
+ });
89
+ throw sanitizeEnvBridgeError(error);
90
+ }
91
+ const revision = metadata?.revision?.();
92
+ await persist({
93
+ ...event("succeeded"),
94
+ ...revision ? { revision } : {}
95
+ });
96
+ return value;
97
+ }
98
+ const bridge = {
99
+ async permissions(context, key) {
100
+ return (await Promise.all([
101
+ "inspect",
102
+ "preview",
103
+ "replace",
104
+ "use"
105
+ ].map(async (permission) => await allowed(context, key, permission) ? permission : void 0))).filter((permission) => permission !== void 0);
106
+ },
107
+ async read({ keys, signal, access }) {
108
+ const context = access ?? grantEnvAccess({
109
+ ...await options.runtimeAttribution?.(),
110
+ actor: options.runtimeActor
111
+ }, {
112
+ kind: "actor",
113
+ bridge
114
+ });
115
+ const values = [];
116
+ for (const key of keys) {
117
+ signal?.throwIfAborted();
118
+ let revision;
119
+ const secret = await audited(context, key, "resolve", "use", async () => {
120
+ const secret = await options.secrets.read(key);
121
+ revision = secret?.revision;
122
+ return secret;
123
+ }, void 0, { revision: () => revision });
124
+ signal?.throwIfAborted();
125
+ values.push([key, secret?.value]);
126
+ }
127
+ return Object.fromEntries(values);
128
+ },
129
+ inspect: (context, key) => audited(context, key, "inspect", "inspect", async () => {
130
+ const value = await options.secrets.inspect(key);
131
+ return value ? {
132
+ revision: value.revision,
133
+ updatedAt: value.updatedAt
134
+ } : void 0;
135
+ }),
136
+ preview: (context, key) => audited(context, key, "preview", "preview", async () => {
137
+ const value = await options.secrets.inspect(key);
138
+ return value?.preview ? { preview: value.preview } : void 0;
139
+ }),
140
+ replace: (context, input) => {
141
+ let revision;
142
+ return audited(context, input.key, "replace", "replace", async () => {
143
+ if (!input.value || new TextEncoder().encode(input.value).length > 32768) throw envBridgeError("invalid");
144
+ const replacement = await options.secrets.replace(input);
145
+ revision = replacement.revision;
146
+ return replacement;
147
+ }, void 0, { revision: () => revision });
148
+ },
149
+ use: (context, key, operation, run) => {
150
+ envIdentifier(operation);
151
+ let revision;
152
+ return audited(context, key, "use", "use", async () => {
153
+ const secret = await options.secrets.read(key);
154
+ if (!secret) throw envBridgeError("missing");
155
+ revision = secret.revision;
156
+ return await run(new SecretEnv(secret.value), { revision });
157
+ }, operation, { revision: () => revision });
158
+ },
159
+ async activity(context, key, before) {
160
+ if (!await allowed(context, key, "activity")) throw envBridgeError("denied");
161
+ return await safe(() => options.access.activity({
162
+ key,
163
+ before,
164
+ limit: 100
165
+ }));
166
+ },
167
+ async grants(context, key) {
168
+ if (!await allowed(context, key, "admin")) throw envBridgeError("denied");
169
+ return await safe(() => options.access.grants(key));
170
+ },
171
+ async grant(context, grant) {
172
+ validateEnvActor(grant.actor);
173
+ if (!Array.isArray(grant.permissions) || !grant.permissions.length || grant.permissions.some((permission) => ![
174
+ "inspect",
175
+ "preview",
176
+ "replace",
177
+ "use"
178
+ ].includes(permission))) throw envBridgeError("invalid");
179
+ return audited(context, grant.key, "grant", "admin", () => options.access.setGrant(grant), void 0, {
180
+ target: grant.actor,
181
+ permissions: grant.permissions
182
+ });
183
+ },
184
+ async revoke(context, actor, key) {
185
+ validateEnvActor(actor);
186
+ return audited(context, key, "revoke", "admin", () => options.access.revokeGrant(actor, key), void 0, { target: actor });
187
+ }
188
+ };
189
+ return bridge;
190
+ }
191
+ //#endregion
192
+ export { createEnvBridge };