@vite-hub/env 0.0.4 → 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 (47) hide show
  1. package/README.md +125 -5
  2. package/dist/access-B3qzBHye.js +54 -0
  3. package/dist/auth.d.ts +32 -0
  4. package/dist/auth.js +44 -0
  5. package/dist/bridge-CdNdTN1V.d.ts +374 -0
  6. package/dist/bridge-error-CFuU5zIz.js +65 -0
  7. package/dist/bridge.d.ts +2 -0
  8. package/dist/bridge.js +192 -0
  9. package/dist/cli-CMQPQbii.js +487 -0
  10. package/dist/cli-DEwcUIe0.d.ts +81 -0
  11. package/dist/cli.d.ts +41 -0
  12. package/dist/cli.js +2 -0
  13. package/dist/database.d.ts +21 -0
  14. package/dist/database.js +183 -0
  15. package/dist/declarations-CiRdb1qP.d.ts +32 -0
  16. package/dist/declarations-DAVgctKD.js +236 -0
  17. package/dist/error-diagnostics-CrxjYNYr.js +43 -0
  18. package/dist/http.d.ts +2 -0
  19. package/dist/http.js +122 -0
  20. package/dist/index.d.ts +6 -6
  21. package/dist/index.js +4 -4
  22. package/dist/internal/agent.d.ts +5 -0
  23. package/dist/internal/agent.js +22 -0
  24. package/dist/internal/connections.d.ts +18 -0
  25. package/dist/internal/connections.js +31 -0
  26. package/dist/presets.d.ts +15 -6
  27. package/dist/presets.js +21 -2
  28. package/dist/provider.d.ts +3 -4
  29. package/dist/provider.js +2 -1
  30. package/dist/schema.d.ts +5 -6
  31. package/dist/schema.js +26 -8
  32. package/dist/seal.d.ts +14 -0
  33. package/dist/seal.js +49 -0
  34. package/dist/server-DufVswRJ.js +670 -0
  35. package/dist/server.d.ts +23 -6
  36. package/dist/server.js +2 -3
  37. package/dist/values-D_r6V774.js +148 -0
  38. package/dist/virtual-module.d.ts +7 -3
  39. package/dist/virtual.d.ts +1 -1
  40. package/dist/vite.d.ts +27 -14
  41. package/dist/vite.js +840 -273
  42. package/package.json +81 -17
  43. package/dist/declarations-CoMmvRqH.js +0 -159
  44. package/dist/declarations-U6P3rvxC.d.ts +0 -24
  45. package/dist/errors-C4Xcs6Fi.js +0 -121
  46. package/dist/server-C16sFc1E.js +0 -303
  47. package/dist/types-CsB6DTGE.d.ts +0 -190
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # @vite-hub/env
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
- <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
- <img alt="Vite" src="https://img.shields.io/badge/Vite-public%20env-646cff?style=flat-square">
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&amp;value=vitehub.dev"></a>
5
+ <img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&amp;value=ready">
6
+ <img alt="Vite" src="https://comark-ui.onmax.me/badge.svg?label=Vite&amp;value=public+env">
7
7
  </p>
8
8
 
9
9
  `@vite-hub/env` declares environment values once, then generates typed public and server-oriented access plus untyped build-time replacements for Vite applications.
@@ -88,6 +88,83 @@ export async function sync(event: unknown) {
88
88
  }
89
89
  ```
90
90
 
91
+ ## Derive secrets from one root secret
92
+
93
+ `deriveSecret(purpose)` from `#vitehub/env/server` derives a 32-byte hex secret from `VITEHUB_SECRET` (or `NUXT_APP_SECRET`) with HKDF-SHA256, salt `vitehub`. Console Auth and CLI dispatch derive their secrets the same way. The Vite development server generates and keeps a root secret in `.vitehub/env/secret` when none is set; builds never generate one. `vitehub secret generate` prints a new root secret and `vitehub secret derive <purpose>` prints a derived one. The root secret signs and authenticates; it does not encrypt stored data. See [App secret](https://vitehub.dev/docs/env/app-secret).
94
+
95
+ ## Typed server values
96
+
97
+ Host variables are strings. Declare `env.boolean()`, `env.number()`, or `env.enum()` when server code needs another type. ViteHub parses the value when Server Env resolves and generates the exact type.
98
+
99
+ ```ts
100
+ // vite.config.ts
101
+ env: {
102
+ server: {
103
+ dryRun: env.boolean({ default: true }), // true, false, 1, or 0
104
+ minConfidence: env.number({ default: 0.6 }), // finite number
105
+ mode: env.enum(["draft", "send"], { default: "draft" }),
106
+ },
107
+ }
108
+ ```
109
+
110
+ `useServerEnv().dryRun` is a `boolean`, `minConfidence` is a `number`, and `mode` is `"draft" | "send"`. Defaults use the parsed type. `env.enum()` cannot be secret because its allowed values are public metadata. An invalid value throws `ENV_RUNTIME_VALUE_INVALID` with the declaration path; the value is never included. `env.server` does not accept custom `schema` parsers because the generated runtime must serialize the parser.
111
+
112
+ ## `.env.example` schemas
113
+
114
+ Opt in with `envSchema()` when a committed `.env.example` should own variable names, types, requiredness, sensitivity, and defaults:
115
+
116
+ ```ts
117
+ import { envSchema, hubEnv } from "@vite-hub/env/vite";
118
+ import { defineConfig } from "vite";
119
+
120
+ export default defineConfig({
121
+ plugins: [hubEnv()],
122
+ env: envSchema(new URL("./.env.example", import.meta.url)),
123
+ });
124
+ ```
125
+
126
+ ```dotenv
127
+ # @public
128
+ VITEHUB_PUBLIC_APP_NAME=Acme
129
+
130
+ # @type=number(min=1, max=10, isInt=true) @public
131
+ VITEHUB_RETRIES=3
132
+
133
+ # @example="get-this-from-your-secret-manager"
134
+ VITEHUB_API_TOKEN=
135
+ ```
136
+
137
+ This uses the restricted `env-spec-v1` profile shared with the [Nuxt module](https://nuxt-safe-runtime-config.onmax.me). Its [@env-spec syntax](https://varlock.dev/env-spec/reference/) parser reads static metadata. It does not run Varlock, load developer `.env` files, or evaluate expansions and functions.
138
+
139
+ A nonempty assignment is a real default. `KEY=` has no default; `KEY=""` is an explicit empty string. Put documentation samples in `@example`, which never supplies a value. Review existing example assignments before opting in. All fields default to required and sensitive; the default type is always string, so `CODE=00123` preserves its zeroes.
140
+
141
+ Only `VITEHUB_PUBLIC_` names enter Public Env. Mark them `@public` or `@sensitive=false`; a sensitive public field is rejected. `@public` alone does not expose an unprefixed or private field. Private fields become runtime Server Env and do not require deployment secrets during prepare or build. For the example above, server code reads `useServerEnv().apiToken`, and the token is a `SecretEnv<string>`.
142
+
143
+ `envSchema(file, { prefix: "APP_", paths: { APP_DATABASE_URL: "database.url" } })` changes the prefix and maps exact schema keys to explicit output paths. The default mapping strips `VITEHUB_` and uses camel case, without guessing groups. With an empty prefix, `PUBLIC_` marks public fields. Public output paths stay flat. Every declaration reads its original schema key exactly; canonical aliases do not override it.
144
+
145
+ Supported types are string with `minLength`/`maxLength`, number with `min`/`max`/`isInt`, boolean, string enum, absolute URL, JSON arrays, and object shapes. URLs remain strings. Sensitive enums are rejected because their choices appear in metadata. Optional non-string empty inputs become missing before defaulting; optional strings preserve empty inputs and still obey length constraints. Required present empty or invalid inputs fail, even when a default exists. Generated declarations describe the validated accessors; raw `process.env` types stay unchanged.
146
+
147
+ The [runnable schema lab](./examples/schema-lab/README.md) builds a browser bundle and Node server from one contract. Its production test restarts the same artifact with different server values, checks startup failures and consumer types, and scans browser output for synthetic credentials. Public Env remains fixed at build time.
148
+
149
+ ## Presets
150
+
151
+ Presets return ordinary `env.server` declarations. Import them from `@vite-hub/env` or `@vite-hub/env/presets`.
152
+
153
+ | Preset | Declares |
154
+ | --- | --- |
155
+ | `openWorkflowEnv()` | OpenWorkflow namespace, Postgres URL, schema, and worker concurrency. |
156
+ | `typesafeEnv({ model? })` | The Server Env of the `typesafe()` AI gateway from `vite-hub/gateways`: Secret `apiKey` (`TYPESAFE_API_KEY`) and `model` (`TYPESAFE_DEFAULT_MODEL`, default `jev-latest`). |
157
+
158
+ The preset allows a missing API key during Env resolution; Jev reports `GATEWAYS_R0002` when a request needs it. `defineAgent({ driver: { ask } })`, `llmGate()`, and `llmRoute()` use `typesafe()` when they get no other gateway, and it reads this group:
159
+
160
+ ```ts
161
+ env: {
162
+ server: {
163
+ typesafe: typesafeEnv(),
164
+ },
165
+ },
166
+ ```
167
+
91
168
  ## External runtime values
92
169
 
93
170
  Use a read-only Env provider when application credentials live outside the host environment. Keep the provider's bootstrap credential in Kubernetes, Cloudflare, or the current host, then load the external values as one operation-scoped snapshot.
@@ -138,6 +215,8 @@ const githubToken = snapshot.githubToken.unseal()
138
215
 
139
216
  Each `loadServerEnv()` call batches requested keys once per provider and returns a fresh frozen snapshot. ViteHub does not cache across loads, so rotation appears on the next load. `useServerEnv()` stays synchronous for host-backed and literal values; provider-backed values require `loadServerEnv()` or `runWithServerEnv()`.
140
217
 
218
+ `env.source(["PRIMARY_TOKEN", "FALLBACK_TOKEN"], { skipEmpty: true })` skips empty host values. Without `skipEmpty`, a defined empty string remains a value. Generated built-in Channel sources use `skipEmpty` to preserve their host fallback behavior.
219
+
141
220
  The generated `#vitehub/env/server` module is not blocked from client builds. Keep its imports in server-only entry points, and supply credentials through `env.source(...)` without literals or defaults; static values and defaults can be serialized into the generated module.
142
221
 
143
222
  `SecretEnv` renders as `<redacted>` in string conversion, JSON, and Node inspection. Call `unseal()` only at the provider boundary that needs the raw value. Redaction is type friction, not complete leak prevention: never return, log, trace, or place an unsealed value in Agent input.
@@ -165,7 +244,7 @@ try {
165
244
  }
166
245
  ```
167
246
 
168
- Each `EnvErrorCode` owns a fixed public message and a bounded details shape. Source details use stable identifiers such as `git:branch`, `package.json`, `env`, or `custom`; raw variable names, package paths, and provider diagnostics stay behind `cause`, which `toJSON()` omits. Cancellation and existing `ViteHubError` instances pass through unchanged. Invalid `env()` calls remain `TypeError`, and `parseSchema()` keeps the schema library's ordinary error boundary.
247
+ Each `EnvErrorCode` owns a fixed public message and a bounded details shape. Source details use stable identifiers such as `git:branch`, `package.json`, `env`, or `custom`; raw variable names, package paths, and provider diagnostics stay behind `cause`, which `toJSON()` omits. Cancellation and existing `ViteHubError` instances pass through unchanged. Invalid declaration helper calls and schema results use package-owned `ENV_R####` diagnostics. Build integration defects use `ENV_B####` diagnostics.
169
248
 
170
249
  ## Generated modules
171
250
 
@@ -197,4 +276,45 @@ export default {
197
276
 
198
277
  Public Env and `env.define` values are compiled into client bundles. Never put credentials in either section. The host still owns secret storage and injection; Env owns declarations, resolution, generated accessors, validation, and default redaction.
199
278
 
200
- Read the complete [Env guide](https://vitehub.dev/docs/server-primitives/env), the [host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix), and the project's [pre-1.0 security policy](https://github.com/vite-hub/vitehub/blob/main/SECURITY.md).
279
+ Read the complete [Env guide](https://vitehub.dev/docs/env), the [host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix), and the project's [pre-1.0 security policy](https://github.com/vite-hub/vitehub/blob/main/SECURITY.md).
280
+
281
+ ### Declaration inventory
282
+
283
+ `describeServerEnv()` from `#vitehub/env/server` returns declaration metadata without reading host values or calling providers. It includes the declaration path, the canonical variable name of env declarations, source kind, provider alias, secret and required flags, default presence, and the parsed value type. Values, defaults, conventional host variable names and provider storage keys are omitted. Use `inspectServerEnv()` only when a status check that loads providers is intended. Its entries add the provider alias, required flag, and `available`, `defaulted`, `missing`, `invalid`, or `error` status, and never include values. Env entries also report `via: "canonical" | "conventional"` and `conflict: true` when the canonical and a conventional name hold different values. `isBlockingServerEnvEntry(entry)` from `@vite-hub/env` returns `true` when the entry makes `loadServerEnv()` fail.
284
+
285
+ `hubEnv()` contributes two CLI commands:
286
+
287
+ ```bash
288
+ vitehub env inspect [--stage <name>] [--json]
289
+ vitehub env check [--stage <name>] [--json]
290
+ ```
291
+
292
+ Both commands load the Vite config in the selected stage mode, including `.env.<stage>` files, with process environment values taking precedence. They list each declared variable with status, source, required, and secret flags. Values are never printed. `env check` exits with `1` when `loadServerEnv()` would fail.
293
+
294
+ ### Managed credentials
295
+
296
+ `createEnvBridge` from `@vite-hub/env/bridge` adapts a secret store to Env with credential-scoped permissions and durable activity. `createDatabaseEnvStore` from `@vite-hub/env/database` supplies encrypted storage, grants, and activity using a ViteHub SQLite/Drizzle database. Use `await store.revisionCondition(key, revision)` to build a SQL predicate that updates related metadata only while that secret revision is current. A `null` revision requires the secret to be absent. Keep its 32-byte encryption key in host configuration and back it up separately from the database.
297
+
298
+ `@vite-hub/env/seal` exports the AES-GCM helpers that the database store uses: `importSealKey`, `seal`, `unseal`, and `sealKeyId`. Other owner packages use them to store sealed values in the same format.
299
+
300
+ A bridge implements the existing `read()` provider contract. Its `replace()` operation requires the last inspected revision (or `null` to create), preventing lost updates. Existing snapshots remain unchanged; the next load resolves the replacement. A custom store returns its own activation requirement: next resolution, restart, or deployment.
301
+
302
+ `inspect`, `preview`, `replace`, and `use` are separate permissions. Only a trusted administrator can modify grants or inspect activity. A verified agent token can supply a narrower permission ceiling.
303
+
304
+ Env creates every `EnvAccessContext`. Each producer gets only the identity that it can prove:
305
+
306
+ - `createEnvBridge({ runtimeActor })`: the runtime reads with its own fixed actor, on that bridge only. `runtimeAttribution` can add trace and invocation IDs.
307
+ - `createEnvAuthenticator()`: the authenticated user, or the Agent of a verified Agent token. It creates an administrator context only when the application's `isAdmin` policy returns `true`.
308
+ - The ViteHub Agent runtime: `agent:<name>` for the Agent Definition that runs, through Connections.
309
+
310
+ The bridge rejects any context that Env did not create, including a literal such as `{ actor }`, a spread copy, or a JSON copy, with `ENV_BRIDGE_UNTRUSTED`. TypeScript also rejects a context that application code builds. Use `EnvAccessContext` as a type, and pass the value that Env gave you. `loadServerEnv(undefined, { access })` forwards that context to providers.
311
+
312
+ Migration: replace `runtimeContext: () => ({ actor })` with `runtimeActor: actor`. Get request contexts from `createEnvAuthenticator()`. A custom `authenticate` must return the context from `createEnvAuthenticator()`.
313
+
314
+ `bridge.use(context, key, operation, callback)` runs a trusted operation with a `SecretEnv` and records its outcome. The callback also receives `{ revision }` for the secret read when the store supplies a revision. Use that revision to fence related writes; a later inspection can refer to a replacement token. Ordinary provider reads record `resolve`, which does not claim to observe later use of copied plaintext. Activity is persisted before release or mutation and after completion. An interrupted operation can retain a `started` record; a remote store and the activity database do not share a transaction. Failed audit persistence blocks release. The optional `emit` callback exports persisted events to evlog or another sink; exporter failures do not erase durable activity.
315
+
316
+ Database previews are opt-in. Short and structured values have no preview. Previews remain protected metadata and are excluded from activity. The database adapter uses AES-256-GCM with per-write IVs and authenticates the namespace, key, and revision. Host administration and database backup security remain application responsibilities.
317
+
318
+ The Agent integration verifies the exact identity object registered during Agent Definition resolution. A name, a copied identity, or an authenticated Agent token cannot establish Agent runtime authority. The optional Agent peer is used only by this integration; the Env bridge and HTTP authenticator do not load it.
319
+
320
+ JSON types support nested constraints, for example `@type=array(string)` and `@type=object(enabled=boolean, retries=number(min=0))`. Defaults use quoted JSON such as `VITEHUB_TAGS='["one"]'`. Runtime JSON members must already match their types. Object shapes require every declared property and reject additional properties. Bare `array` and `object` accept JSON without a fixed shape. Sensitive declarations reject nested enums because enum choices are public metadata. Existing code-first declarations remain supported.
@@ -0,0 +1,54 @@
1
+ import { t as envBridgeError } from "./bridge-error-CFuU5zIz.js";
2
+ import { defineGrant } from "@vite-hub/runtime/internal/grant";
3
+ //#region src/internal/access.ts
4
+ /** Marks the type of contexts that Env creates. The bridge trusts only the `envAccess` grant registry, not this marker. */
5
+ const envAccessGrant = Symbol("vitehub.env.access-grant");
6
+ const envAccess = defineGrant("vitehub.env.access", (authority) => authority.kind === "key" ? Object.freeze({
7
+ ...authority,
8
+ permissions: Object.freeze([...authority.permissions])
9
+ }) : authority.kind === "agent" && authority.parents ? Object.freeze({
10
+ ...authority,
11
+ parents: Object.freeze([...authority.parents])
12
+ }) : Object.freeze({ ...authority }));
13
+ function envIdentifier(value) {
14
+ if (typeof value !== "string") throw envBridgeError("invalid");
15
+ if (!value || value.length > 512 || /[\u0000-\u001f]/.test(value)) throw envBridgeError("invalid");
16
+ }
17
+ function validateEnvActor(actor) {
18
+ envIdentifier(actor.id);
19
+ if (![
20
+ "user",
21
+ "agent",
22
+ "service"
23
+ ].includes(actor.kind)) throw envBridgeError("invalid");
24
+ }
25
+ /** Create a frozen context. Only Env modules call this after their own check. */
26
+ function grantEnvAccess(attribution, authority) {
27
+ validateEnvActor(attribution.actor);
28
+ const scope = authority.kind === "actor" && authority.scope ? Object.freeze(authority.scope.map((grant) => Object.freeze({
29
+ key: grant.key,
30
+ permissions: Object.freeze([...grant.permissions])
31
+ }))) : void 0;
32
+ return envAccess.issue({
33
+ ...authority,
34
+ ...scope ? { scope } : {}
35
+ }, {
36
+ [envAccessGrant]: true,
37
+ actor: Object.freeze({
38
+ id: attribution.actor.id,
39
+ kind: attribution.actor.kind
40
+ }),
41
+ ...authority.kind === "admin" ? { admin: true } : {},
42
+ ...scope ? { scope } : {},
43
+ ...attribution.traceId ? { traceId: attribution.traceId } : {},
44
+ ...attribution.invocationId ? { invocationId: attribution.invocationId } : {}
45
+ });
46
+ }
47
+ /** Return the authority that Env recorded. A context that Env did not create fails closed. */
48
+ function envAccessAuthority(context) {
49
+ const authority = envAccess.check(context);
50
+ if (!authority) throw envBridgeError("untrusted");
51
+ return authority;
52
+ }
53
+ //#endregion
54
+ export { validateEnvActor as i, envIdentifier as n, grantEnvAccess as r, envAccessAuthority as t };
package/dist/auth.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { n as EnvAccessScope, t as EnvAccessContext } from "./bridge-CdNdTN1V.js";
2
+ //#region src/auth.d.ts
3
+ export interface EnvHumanSession {
4
+ user: {
5
+ id: string;
6
+ };
7
+ }
8
+ export interface EnvAgentSession {
9
+ agent: {
10
+ id: string;
11
+ };
12
+ }
13
+ export type EnvAgentScope = EnvAccessScope;
14
+ export interface EnvAuthenticatorOptions<Human extends EnvHumanSession, Agent extends EnvAgentSession> {
15
+ /** Pass Better Auth's auth.api.getSession, preserving the incoming headers. */
16
+ getSession(input: {
17
+ headers: Headers;
18
+ }): Promise<Human | null>;
19
+ /** Application policy; authentication alone never grants administrator access. */
20
+ isAdmin(session: Human): boolean | Promise<boolean>;
21
+ agents?: {
22
+ /** Must verify the credential, e.g. auth.api.getAgentSession from Agent Auth. */
23
+ getSession(input: {
24
+ headers: Headers;
25
+ }): Promise<Agent | null>;
26
+ /** Map verified capability grants AND their constraints to exact store keys. */
27
+ scope(session: Agent): EnvAgentScope | null | Promise<EnvAgentScope | null>;
28
+ };
29
+ }
30
+ /** Authenticate management requests without coupling Env to a particular Better Auth plugin version. */
31
+ export declare function createEnvAuthenticator<Human extends EnvHumanSession, Agent extends EnvAgentSession = EnvAgentSession>(options: EnvAuthenticatorOptions<Human, Agent>): (request: Request) => Promise<EnvAccessContext | null>;
32
+ //#endregion
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 };