@vite-hub/env 0.1.0 → 0.3.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 (61) hide show
  1. package/README.md +178 -33
  2. package/dist/{access-B3qzBHye.js → access-B8lSDip4.js} +1 -1
  3. package/dist/{bridge-CdNdTN1V.d.ts → bridge-Cs9YfQWk.d.ts} +111 -38
  4. package/dist/{bridge-error-CFuU5zIz.js → bridge-error-BhJ77age.js} +14 -13
  5. package/dist/bridge.d.ts +2 -2
  6. package/dist/bridge.js +168 -6
  7. package/dist/cli-BPp7rdcA.d.ts +159 -0
  8. package/dist/{cli-CMQPQbii.js → cli-DLpY0QAo.js} +212 -30
  9. package/dist/cli.d.ts +2 -2
  10. package/dist/cli.js +1 -1
  11. package/dist/database.d.ts +29 -3
  12. package/dist/database.js +106 -15
  13. package/dist/declarations-C5XR3aKw.d.ts +58 -0
  14. package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
  15. package/dist/index.d.ts +145 -10
  16. package/dist/index.js +240 -7
  17. package/dist/internal/agent.d.ts +1 -1
  18. package/dist/internal/agent.js +2 -2
  19. package/dist/internal/connections.d.ts +1 -1
  20. package/dist/internal/connections.js +2 -2
  21. package/dist/internal/server.d.ts +3 -0
  22. package/dist/internal/server.js +2 -0
  23. package/dist/object-_dlsZ4lP.js +276 -0
  24. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  25. package/dist/operations-X1w--wds.js +30 -0
  26. package/dist/operations.d.ts +37 -0
  27. package/dist/operations.js +833 -0
  28. package/dist/runtime/public-env.d.ts +5 -0
  29. package/dist/runtime/public-env.js +8 -0
  30. package/dist/runtime/server-env.d.ts +22 -0
  31. package/dist/runtime/server-env.js +35 -0
  32. package/dist/schema-DMZ1_yhY.js +360 -0
  33. package/dist/seal.d.ts +8 -5
  34. package/dist/seal.js +9 -6
  35. package/dist/{secret.js → secret-DJd-fy5T.js} +1 -1
  36. package/dist/server-ChNL_Xc3.js +1279 -0
  37. package/dist/server-Dd8bjIKd.d.ts +145 -0
  38. package/dist/server.d.ts +3 -25
  39. package/dist/server.js +2 -2
  40. package/dist/virtual-module.d.ts +6 -6
  41. package/dist/vite.d.ts +59 -14
  42. package/dist/vite.js +304 -115
  43. package/package.json +27 -38
  44. package/dist/auth.d.ts +0 -32
  45. package/dist/auth.js +0 -44
  46. package/dist/cli-DEwcUIe0.d.ts +0 -81
  47. package/dist/declarations-CiRdb1qP.d.ts +0 -32
  48. package/dist/declarations-DAVgctKD.js +0 -236
  49. package/dist/error-diagnostics-CrxjYNYr.js +0 -43
  50. package/dist/http.d.ts +0 -2
  51. package/dist/http.js +0 -122
  52. package/dist/presets.d.ts +0 -20
  53. package/dist/presets.js +0 -44
  54. package/dist/provider.d.ts +0 -5
  55. package/dist/provider.js +0 -8
  56. package/dist/schema.d.ts +0 -15
  57. package/dist/schema.js +0 -55
  58. package/dist/secret-C2191nAa.d.ts +0 -11
  59. package/dist/secret.d.ts +0 -2
  60. package/dist/server-DufVswRJ.js +0 -670
  61. package/dist/values-D_r6V774.js +0 -148
@@ -1,4 +1,3 @@
1
- import { t as SecretEnv } from "./secret-C2191nAa.js";
2
1
  //#region src/internal/access.d.ts
3
2
  /** Marks the type of contexts that Env creates. The bridge trusts only the `envAccess` grant registry, not this marker. */
4
3
  declare const envAccessGrant: unique symbol;
@@ -7,22 +6,41 @@ interface EnvAttribution {
7
6
  invocationId?: string;
8
7
  }
9
8
  //#endregion
9
+ //#region src/secret.d.ts
10
+ declare class SecretEnv<T = string> {
11
+ #private;
12
+ constructor(value: T);
13
+ unseal(): T;
14
+ toString(): string;
15
+ toJSON(): string;
16
+ [Symbol.toPrimitive](): string;
17
+ }
18
+ //#endregion
10
19
  //#region src/http.d.ts
11
20
  interface EnvManagement {
12
21
  bridge: EnvBridge;
13
22
  authenticate(request: Request): EnvAccessContext | null | Promise<EnvAccessContext | null>;
14
23
  }
24
+ /**
25
+ * Options that server code passes to one management request. A request never sets them.
26
+ * `allowedOrigin` is a browser origin that the caller already accepted for this request, such as the Console with a
27
+ * verified bearer token from `console.origins`. The bridge still authenticates the request and checks permissions.
28
+ */
29
+ interface EnvBridgeRequestOptions {
30
+ allowedOrigin?: string;
31
+ }
15
32
  type EnvManagementResolver = (path: string) => {
16
33
  key: string;
17
34
  management: EnvManagement;
18
35
  } | undefined;
19
36
  /** Mount only on a server route. resolve selects declared credentials, never arbitrary store keys. */
20
- declare function createEnvBridgeHandler(resolve: EnvManagementResolver): (request: Request) => Promise<Response>;
37
+ declare function createEnvBridgeHandler(resolve: EnvManagementResolver): (request: Request, options?: EnvBridgeRequestOptions) => Promise<Response>;
21
38
  //#endregion
22
39
  //#region src/types.d.ts
23
40
  type EnvDiagnostics = "off" | "summary" | "trace";
24
41
  type EnvMode = "build" | "runtime";
25
- interface EnvIntegrationOptions {
42
+ /** Options of `vitehub({ env })` and `hubEnv()`: the Env declarations and how ViteHub resolves them. */
43
+ interface EnvOptions extends EnvDeclarations {
26
44
  diagnostics?: EnvDiagnostics;
27
45
  /**
28
46
  * Prefix of canonical variable names. Every env-backed declaration first reads the prefix plus its
@@ -43,14 +61,13 @@ interface EnvSourceContext {
43
61
  };
44
62
  env: Record<string, string | undefined>;
45
63
  git: {
64
+ /** Reads `GIT_BRANCH`, then `GITHUB_HEAD_REF`, then `GITHUB_REF_NAME` on a GitHub branch ref, then local Git. */
46
65
  branch: () => Promise<string>;
66
+ /** Reads `GIT_SHA`, then `GITHUB_SHA`, then local Git. */
47
67
  commit: (options?: {
48
68
  short?: boolean;
49
69
  }) => Promise<string>;
50
- ref: () => Promise<string>;
51
- sha: (options?: {
52
- short?: boolean;
53
- }) => Promise<string>;
70
+ /** Reads `GIT_TAG`, then `GITHUB_REF_NAME` on a GitHub tag ref, then local Git. */
54
71
  tag: () => Promise<string | undefined>;
55
72
  };
56
73
  mode: EnvMode;
@@ -70,8 +87,6 @@ type EnvSource = {
70
87
  names?: string[];
71
88
  /** The canonical name, `VITEHUB_<PATH>`, which the ordered names read first. */
72
89
  canonical?: string | false;
73
- /** Treat empty host values as missing when reading the ordered names. */
74
- skipEmpty?: boolean;
75
90
  serializable: true;
76
91
  } | {
77
92
  kind: "git-branch";
@@ -82,15 +97,6 @@ type EnvSource = {
82
97
  label: "git:commit";
83
98
  serializable: true;
84
99
  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
100
  } | {
95
101
  kind: "git-tag";
96
102
  label: "git:tag";
@@ -121,20 +127,27 @@ interface EnvVariableDeclaration {
121
127
  source?: EnvSource;
122
128
  type?: string;
123
129
  }
124
- interface EnvVariableOptions {
125
- default?: unknown;
130
+ interface EnvVariableBaseOptions {
126
131
  mode?: EnvMode;
127
- optional?: boolean;
128
- required?: boolean;
129
132
  schema?: unknown;
130
133
  secret?: boolean;
131
134
  source?: EnvSource | EnvSourceResolver;
132
135
  type?: string;
133
136
  }
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"> {
137
+ /**
138
+ * A value is required by default. `optional: true` lets it be missing.
139
+ * A `default` makes the value always present, so it cannot be combined with `optional: true`.
140
+ */
141
+ type EnvRequirednessOptions<TValue> = {
136
142
  default?: TValue;
137
- }
143
+ optional?: false;
144
+ } | {
145
+ default?: never;
146
+ optional: true;
147
+ };
148
+ type EnvVariableOptions = EnvVariableBaseOptions & EnvRequirednessOptions<unknown>;
149
+ /** Options for `env.boolean()`, `env.number()`, `env.enum()`, `env.list()`, and `env.json()`. The helper owns the parser and type. */
150
+ type EnvTypedVariableOptions<TValue> = Omit<EnvVariableBaseOptions, "schema" | "type"> & EnvRequirednessOptions<TValue>;
138
151
  /** Serializable parser for one Server Env value. Host and provider values are strings before parsing. */
139
152
  type EnvValueSchema = {
140
153
  kind: "boolean";
@@ -159,15 +172,37 @@ type EnvValueSchema = {
159
172
  } | {
160
173
  kind: "object";
161
174
  properties?: Record<string, EnvValueSchema>;
175
+ } | {
176
+ kind: "list";
177
+ items?: EnvValueSchema;
178
+ } | {
179
+ kind: "json";
162
180
  };
181
+ /**
182
+ * A Standard Schema that the server build imports from a module. Server Env runs it on the raw value when it resolves,
183
+ * so refinements and transforms work. Create it with `env.schemaFrom()`.
184
+ */
185
+ interface EnvSchemaModuleReference {
186
+ kind: "schema-module";
187
+ /** Module specifier. A relative path resolves from the project root, like `hubEnv({ providers })`. */
188
+ module: string;
189
+ /** Name of the export that holds the schema. */
190
+ export: string;
191
+ /** `json` parses a string value as JSON before the schema runs. `env.json()` sets it. */
192
+ input?: "json";
193
+ }
163
194
  type EnvBuildStaticValue = null | string | number | boolean | EnvBuildStaticValue[];
164
195
  type EnvBuildConfigValue = EnvBuildConfigOptions | EnvBuildStaticValue | EnvVariableDeclaration;
165
196
  interface EnvBuildConfigOptions {
166
197
  [key: string]: EnvBuildConfigValue;
167
198
  }
168
- interface EnvViteConfigOptions {
199
+ /** Declarations of Public Env, Server Env, and build-time replacements. */
200
+ interface EnvDeclarations {
201
+ /** Values that replace identifiers at build time. */
169
202
  define?: Record<string, EnvBuildConfigValue>;
203
+ /** Public Env, resolved at build time and readable in browser code. Each declaration uses `mode: "build"`. */
170
204
  public?: Record<string, EnvVariableDeclaration>;
205
+ /** Server Env, resolved at runtime and readable only in server code. */
171
206
  server?: EnvRuntimeConfigOptions;
172
207
  }
173
208
  type EnvRuntimeStaticValue = null | string | number | boolean | EnvRuntimeStaticValue[];
@@ -175,10 +210,6 @@ type EnvRuntimeConfigValue = EnvRuntimeConfigOptions | EnvRuntimeStaticValue | E
175
210
  interface EnvRuntimeConfigOptions {
176
211
  [key: string]: EnvRuntimeConfigValue;
177
212
  }
178
- type EnvConfigOptions = EnvViteConfigOptions;
179
- interface EnvViteUserConfig {
180
- env?: EnvViteConfigOptions;
181
- }
182
213
  interface EnvDiagnosticEntry {
183
214
  exposed: string;
184
215
  key: string;
@@ -193,6 +224,7 @@ interface EnvRegistryEntry {
193
224
  default?: unknown;
194
225
  required: boolean;
195
226
  schema?: EnvValueSchema;
227
+ schemaModule?: EnvSchemaModuleReference;
196
228
  secret: boolean;
197
229
  source: Extract<EnvSource, {
198
230
  kind: "env" | "provider";
@@ -208,10 +240,11 @@ interface EnvRuntimeRegistry<TServerEnv extends Record<string, unknown> = Record
208
240
  [key: string]: EnvRuntimeRegistryValue;
209
241
  readonly [serverEnvType]?: (value: TServerEnv) => void;
210
242
  }
211
- interface ServerEnv {
212
- [key: string]: unknown;
213
- }
214
- type PublicEnv = Record<string, unknown>;
243
+ /** Server Env. ViteHub generates its fields from the Env declarations into `.vitehub/types/`. */
244
+ interface ServerEnv {}
245
+ /** Public Env. ViteHub generates its fields from the Env declarations into `.vitehub/types/`. */
246
+ interface PublicEnv {}
247
+ type ReadonlyServerEnv = DeepReadonly<ServerEnv>;
215
248
  interface EnvProviderContext<TEnv extends Record<string, unknown> = Record<string, unknown>> {
216
249
  env: DeepReadonly<TEnv>;
217
250
  access?: EnvAccessContext;
@@ -235,6 +268,10 @@ type ServerEnvInspectionStatus = "available" | "defaulted" | "error" | "invalid"
235
268
  interface ServerEnvInspectionEntry {
236
269
  /** The declaration is secret. Inspection never returns values. */
237
270
  masked: boolean;
271
+ /** The host variable names of an env declaration, in read order. See `ServerEnvDescriptionEntry.names`. */
272
+ names?: readonly string[];
273
+ /** The host variable name that supplied the value, one of `names`. Omitted when no name is set. */
274
+ name?: string;
238
275
  path?: string;
239
276
  /** Provider alias for provider-backed declarations. */
240
277
  provider?: string;
@@ -248,8 +285,12 @@ interface ServerEnvInspectionEntry {
248
285
  }
249
286
  interface ServerEnvDescriptionEntry {
250
287
  path?: string;
251
- /** The canonical variable name of an env declaration, such as `VITEHUB_CLIPROXY_API_KEY`. It is read first. */
252
- canonicalName?: string;
288
+ /**
289
+ * The host variable names of an env declaration, in read order: the canonical name such as `VITEHUB_CLIPROXY_API_KEY`
290
+ * first, unless `canonical: false` or `prefix: false` disables it, then the `env.source()` names or the unprefixed path
291
+ * name. The first name that is set supplies the value. Omitted for literal and provider declarations.
292
+ */
293
+ names?: readonly string[];
253
294
  source: "env" | "literal" | "provider";
254
295
  provider?: string;
255
296
  secret: boolean;
@@ -265,6 +306,37 @@ interface ServerEnvInspection {
265
306
  entries: readonly ServerEnvInspectionEntry[];
266
307
  }
267
308
  //#endregion
309
+ //#region src/auth.d.ts
310
+ interface EnvHumanSession {
311
+ user: {
312
+ id: string;
313
+ };
314
+ }
315
+ interface EnvAgentSession {
316
+ agent: {
317
+ id: string;
318
+ };
319
+ }
320
+ type EnvAgentScope = EnvAccessScope;
321
+ interface EnvAuthenticatorOptions<Human extends EnvHumanSession, Agent extends EnvAgentSession> {
322
+ /** Pass Better Auth's auth.api.getSession, preserving the incoming headers. */
323
+ getSession(input: {
324
+ headers: Headers;
325
+ }): Promise<Human | null>;
326
+ /** Application policy; authentication alone never grants administrator access. */
327
+ isAdmin(session: Human): boolean | Promise<boolean>;
328
+ agents?: {
329
+ /** Must verify the credential, e.g. auth.api.getAgentSession from Agent Auth. */
330
+ getSession(input: {
331
+ headers: Headers;
332
+ }): Promise<Agent | null>;
333
+ /** Map verified capability grants AND their constraints to exact store keys. */
334
+ scope(session: Agent): EnvAgentScope | null | Promise<EnvAgentScope | null>;
335
+ };
336
+ }
337
+ /** Authenticate management requests without coupling Env to a particular Better Auth plugin version. */
338
+ declare function createEnvAuthenticator<Human extends EnvHumanSession, Agent extends EnvAgentSession = EnvAgentSession>(options: EnvAuthenticatorOptions<Human, Agent>): (request: Request) => Promise<EnvAccessContext | null>;
339
+ //#endregion
268
340
  //#region src/bridge.d.ts
269
341
  type EnvPermission = "inspect" | "preview" | "replace" | "use";
270
342
  interface EnvActor {
@@ -321,7 +393,8 @@ interface EnvActivity {
321
393
  timestamp: string;
322
394
  actor: EnvActor;
323
395
  key: string;
324
- action: "inspect" | "preview" | "replace" | "resolve" | "use" | "grant" | "revoke";
396
+ /** `remove`: a store deleted the key, such as the env values of a Console. The bridge never writes it. */
397
+ action: "inspect" | "preview" | "replace" | "remove" | "resolve" | "use" | "grant" | "revoke";
325
398
  outcome: "started" | "succeeded" | "failed" | "denied";
326
399
  revision?: string;
327
400
  operation?: string;
@@ -371,4 +444,4 @@ interface EnvBridge extends EnvProvider {
371
444
  }
372
445
  declare function createEnvBridge(options: EnvBridgeOptions): EnvBridge;
373
446
  //#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 };
447
+ export { EnvAttribution as $, EnvRuntimeRegistry as A, PublicEnv as B, EnvMode as C, EnvProviderValues as D, EnvProviderContext as E, EnvTypedVariableOptions as F, ServerEnvInspection as G, ServerEnv as H, EnvValueSchema as I, EnvBridgeRequestOptions as J, ServerEnvInspectionEntry as K, EnvVariableDeclaration as L, EnvSource as M, EnvSourceContext as N, EnvProviders as O, EnvSourceResolver as P, SecretEnv as Q, EnvVariableOptions as R, EnvDiagnostics as S, EnvProvider as T, ServerEnvDescription as U, ReadonlyServerEnv as V, ServerEnvDescriptionEntry as W, EnvManagementResolver as X, EnvManagement as Y, createEnvBridgeHandler as Z, EnvHumanSession as _, EnvActor as a, EnvDeclarations as b, EnvGrant as c, EnvSecretMetadata as d, EnvSecretStore as f, EnvAuthenticatorOptions as g, EnvAgentSession as h, EnvActivity as i, EnvSchemaModuleReference as j, EnvRuntimeConfigOptions as k, EnvPermission as l, EnvAgentScope as m, EnvAccessScope as n, EnvBridge as o, createEnvBridge as p, ServerEnvInspectionStatus as q, EnvAccessStore as r, EnvBridgeOptions as s, EnvAccessContext as t, EnvReplacement as u, createEnvAuthenticator as v, EnvOptions as w, EnvDiagnosticEntry as x, DeepReadonly as y, LoadServerEnvOptions as z };
@@ -13,22 +13,23 @@ const messages = {
13
13
  function envBridgeError(code) {
14
14
  return new ViteHubError(`ENV_BRIDGE_${code.toUpperCase()}`, messages[code]);
15
15
  }
16
- const docs = "https://vitehub.dev/docs/env/bridge#structured-errors";
17
16
  const guidance = (fix) => ({
18
17
  why: ({ message }) => message,
19
- fix,
20
- docs
18
+ fix
21
19
  });
22
20
  /** 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
- } });
21
+ const envBridgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
22
+ docsBase: "https://vitehub.dev/docs/env/diagnostics",
23
+ 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
+ });
32
33
  /** The JSON error body of a sanitized bridge error: `code`, `message` (the why), `fix`, and `docs`. */
33
34
  function envBridgeErrorBody(error) {
34
35
  const code = error.code;
@@ -45,7 +46,7 @@ function envBridgeErrorBody(error) {
45
46
  };
46
47
  }
47
48
  function isEnvBridgeDiagnosticCode(code) {
48
- return Object.hasOwn(envBridgeDiagnostics, code);
49
+ return Object.keys(envBridgeDiagnostics).includes(code);
49
50
  }
50
51
  function sanitizeEnvBridgeError(error) {
51
52
  if (isViteHubError(error)) {
package/dist/bridge.d.ts CHANGED
@@ -1,2 +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 };
1
+ import { J as EnvBridgeRequestOptions, X as EnvManagementResolver, Y as EnvManagement, Z as createEnvBridgeHandler, _ as EnvHumanSession, a as EnvActor, c as EnvGrant, d as EnvSecretMetadata, f as EnvSecretStore, g as EnvAuthenticatorOptions, h as EnvAgentSession, i as EnvActivity, l as EnvPermission, m as EnvAgentScope, n as EnvAccessScope, o as EnvBridge, p as createEnvBridge, r as EnvAccessStore, s as EnvBridgeOptions, t as EnvAccessContext, u as EnvReplacement, v as createEnvAuthenticator } from "./bridge-Cs9YfQWk.js";
2
+ export { EnvAccessContext, EnvAccessScope, EnvAccessStore, EnvActivity, EnvActor, type EnvAgentScope, type EnvAgentSession, type EnvAuthenticatorOptions, EnvBridge, EnvBridgeOptions, type EnvBridgeRequestOptions, EnvGrant, type EnvHumanSession, type EnvManagement, type EnvManagementResolver, EnvPermission, EnvReplacement, EnvSecretMetadata, EnvSecretStore, createEnvAuthenticator, createEnvBridge, createEnvBridgeHandler };
package/dist/bridge.js CHANGED
@@ -1,6 +1,168 @@
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";
1
+ import { t as SecretEnv } from "./secret-DJd-fy5T.js";
2
+ import { n as envBridgeErrorBody, r as sanitizeEnvBridgeError, t as envBridgeError } from "./bridge-error-BhJ77age.js";
3
+ import { i as validateEnvActor, n as envIdentifier, r as grantEnvAccess, t as envAccessAuthority } from "./access-B8lSDip4.js";
4
+ //#region src/auth.ts
5
+ const permissions$1 = [
6
+ "inspect",
7
+ "preview",
8
+ "replace",
9
+ "use"
10
+ ];
11
+ function identifier(value) {
12
+ return typeof value === "string" && value.length > 0 && value.length <= 512 && !/[\u0000-\u001f]/.test(value);
13
+ }
14
+ /** Authenticate management requests without coupling Env to a particular Better Auth plugin version. */
15
+ function createEnvAuthenticator(options) {
16
+ return async (request) => {
17
+ try {
18
+ const authorization = request.headers.get("authorization");
19
+ if (authorization !== null) {
20
+ if (!/^Bearer\s+\S+$/i.test(authorization) || !options.agents) return null;
21
+ const session = await options.agents.getSession({ headers: request.headers });
22
+ if (!session || !identifier(session.agent.id)) return null;
23
+ const scope = await options.agents.scope(session);
24
+ if (!Array.isArray(scope) || scope.some((grant) => !identifier(grant.key) || !Array.isArray(grant.permissions) || grant.permissions.some((permission) => !permissions$1.includes(permission)))) return null;
25
+ return grantEnvAccess({ actor: {
26
+ kind: "agent",
27
+ id: session.agent.id
28
+ } }, {
29
+ kind: "actor",
30
+ scope
31
+ });
32
+ }
33
+ const session = await options.getSession({ headers: request.headers });
34
+ if (!session || !identifier(session.user.id)) return null;
35
+ const actor = {
36
+ kind: "user",
37
+ id: session.user.id
38
+ };
39
+ return grantEnvAccess({ actor }, await options.isAdmin(session) === true ? { kind: "admin" } : { kind: "actor" });
40
+ } catch {
41
+ return null;
42
+ }
43
+ };
44
+ }
45
+ //#endregion
46
+ //#region src/http.ts
47
+ function record(value) {
48
+ return value !== null && typeof value === "object" && !Array.isArray(value);
49
+ }
50
+ function actor(value) {
51
+ if (!record(value) || typeof value.id !== "string" || value.kind !== "user" && value.kind !== "agent" && value.kind !== "service") throw envBridgeError("invalid");
52
+ return {
53
+ id: value.id,
54
+ kind: value.kind
55
+ };
56
+ }
57
+ const permissions = [
58
+ "inspect",
59
+ "preview",
60
+ "replace",
61
+ "use"
62
+ ];
63
+ async function body(request) {
64
+ const reader = request.body?.getReader();
65
+ if (!reader) throw envBridgeError("invalid");
66
+ const decoder = new TextDecoder();
67
+ let size = 0;
68
+ let text = "";
69
+ try {
70
+ while (true) {
71
+ const chunk = await reader.read();
72
+ if (chunk.done) break;
73
+ size += chunk.value.byteLength;
74
+ if (size > 65536) {
75
+ await reader.cancel();
76
+ throw envBridgeError("invalid");
77
+ }
78
+ text += decoder.decode(chunk.value, { stream: true });
79
+ }
80
+ const value = JSON.parse(text + decoder.decode());
81
+ if (!record(value)) throw envBridgeError("invalid");
82
+ return value;
83
+ } catch {
84
+ throw envBridgeError("invalid");
85
+ } finally {
86
+ reader.releaseLock();
87
+ }
88
+ }
89
+ function response(value, status = 200) {
90
+ return Response.json(value, {
91
+ status,
92
+ headers: {
93
+ "cache-control": "no-store",
94
+ "x-content-type-options": "nosniff",
95
+ "x-robots-tag": "noindex, nofollow"
96
+ }
97
+ });
98
+ }
99
+ /** Mount only on a server route. resolve selects declared credentials, never arbitrary store keys. */
100
+ function createEnvBridgeHandler(resolve) {
101
+ return async (request, options = {}) => {
102
+ if (request.method !== "POST") return response({ message: "Method not allowed." }, 405);
103
+ const origin = request.headers.get("origin");
104
+ if (origin ? origin !== new URL(request.url).origin && origin !== options.allowedOrigin : !/^Bearer\s+\S+$/i.test(request.headers.get("authorization") ?? "")) return response({ message: "Request origin is not allowed." }, 403);
105
+ try {
106
+ const input = await body(request);
107
+ if (typeof input.path !== "string" || input.path.length > 256) throw envBridgeError("invalid");
108
+ const target = resolve(input.path);
109
+ if (!target) return response({ message: "This variable is not managed." }, 404);
110
+ const context = await target.management.authenticate(request);
111
+ if (!context) return response({ message: "Authentication required." }, 401);
112
+ const { bridge } = target.management;
113
+ const key = target.key;
114
+ switch (input.action) {
115
+ case "permissions": return response({
116
+ permissions: await bridge.permissions(context, key),
117
+ admin: Boolean(context.admin && !context.scope)
118
+ });
119
+ case "inspect": return response({
120
+ metadata: await bridge.inspect(context, key) ?? null,
121
+ permissions: await bridge.permissions(context, key),
122
+ admin: Boolean(context.admin && !context.scope)
123
+ });
124
+ case "preview": {
125
+ const metadata = await bridge.preview(context, key);
126
+ return response({ metadata: metadata ? { preview: metadata.preview } : null });
127
+ }
128
+ case "replace": {
129
+ if (typeof input.value !== "string" || !(input.expectedRevision === null || typeof input.expectedRevision === "string")) throw envBridgeError("invalid");
130
+ const result = await bridge.replace(context, {
131
+ key,
132
+ value: input.value,
133
+ expectedRevision: input.expectedRevision
134
+ });
135
+ return response({
136
+ revision: result.revision,
137
+ updatedAt: result.updatedAt,
138
+ activation: result.activation
139
+ });
140
+ }
141
+ case "activity":
142
+ if (input.before !== void 0 && typeof input.before !== "string") throw envBridgeError("invalid");
143
+ return response({ events: await bridge.activity(context, key, input.before) });
144
+ case "grants": return response({ grants: await bridge.grants(context, key) });
145
+ case "grant":
146
+ if (!Array.isArray(input.permissions) || input.permissions.some((value) => !permissions.includes(value))) throw envBridgeError("invalid");
147
+ await bridge.grant(context, {
148
+ actor: actor(input.actor),
149
+ key,
150
+ permissions: input.permissions
151
+ });
152
+ return response({ ok: true });
153
+ case "revoke":
154
+ await bridge.revoke(context, actor(input.actor), key);
155
+ return response({ ok: true });
156
+ default: throw envBridgeError("invalid");
157
+ }
158
+ } catch (error) {
159
+ const safe = sanitizeEnvBridgeError(error);
160
+ const status = safe.code === "ENV_BRIDGE_DENIED" ? 403 : safe.code === "ENV_BRIDGE_CONFLICT" ? 409 : safe.code === "ENV_BRIDGE_INVALID" ? 400 : 503;
161
+ return response(envBridgeErrorBody(safe), status);
162
+ }
163
+ };
164
+ }
165
+ //#endregion
4
166
  //#region src/bridge.ts
5
167
  async function safe(run) {
6
168
  try {
@@ -31,7 +193,7 @@ function createEnvBridge(options) {
31
193
  if (authority.scope && !authority.scope.some((grant) => grant.key === key && grant.permissions.includes(permission))) return false;
32
194
  return await safe(async () => {
33
195
  const grants = await options.access.grants(key);
34
- if (!Array.isArray(grants)) throw new TypeError("Invalid access grants.");
196
+ if (!Array.isArray(grants)) throw envBridgeError("operation_failed");
35
197
  for (const grant of grants) {
36
198
  if (!grant || typeof grant !== "object" || typeof grant.key !== "string" || !grant.actor || typeof grant.actor !== "object" || typeof grant.actor.id !== "string" || ![
37
199
  "user",
@@ -42,7 +204,7 @@ function createEnvBridge(options) {
42
204
  "preview",
43
205
  "replace",
44
206
  "use"
45
- ].includes(value))) throw new TypeError("Invalid access grant.");
207
+ ].includes(value))) throw envBridgeError("operation_failed");
46
208
  if (grant.key === key && grant.actor.id === context.actor.id && grant.actor.kind === context.actor.kind && grant.permissions.includes(permission)) return true;
47
209
  }
48
210
  return false;
@@ -189,4 +351,4 @@ function createEnvBridge(options) {
189
351
  return bridge;
190
352
  }
191
353
  //#endregion
192
- export { createEnvBridge };
354
+ export { createEnvAuthenticator, createEnvBridge, createEnvBridgeHandler };