@vite-hub/env 0.0.4 → 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 (57) hide show
  1. package/README.md +288 -23
  2. package/dist/access-B8lSDip4.js +54 -0
  3. package/dist/bridge-Cs9YfQWk.d.ts +447 -0
  4. package/dist/bridge-error-BhJ77age.js +66 -0
  5. package/dist/bridge.d.ts +2 -0
  6. package/dist/bridge.js +354 -0
  7. package/dist/cli-BPp7rdcA.d.ts +159 -0
  8. package/dist/cli-DLpY0QAo.js +669 -0
  9. package/dist/cli.d.ts +41 -0
  10. package/dist/cli.js +2 -0
  11. package/dist/database.d.ts +47 -0
  12. package/dist/database.js +274 -0
  13. package/dist/declarations-C5XR3aKw.d.ts +58 -0
  14. package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
  15. package/dist/index.d.ts +146 -11
  16. package/dist/index.js +240 -7
  17. package/dist/internal/agent.d.ts +5 -0
  18. package/dist/internal/agent.js +22 -0
  19. package/dist/internal/connections.d.ts +18 -0
  20. package/dist/internal/connections.js +31 -0
  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 +17 -0
  34. package/dist/seal.js +52 -0
  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 -8
  39. package/dist/server.js +2 -3
  40. package/dist/virtual-module.d.ts +9 -5
  41. package/dist/virtual.d.ts +1 -1
  42. package/dist/vite.d.ts +79 -21
  43. package/dist/vite.js +1095 -339
  44. package/package.json +81 -28
  45. package/dist/declarations-CoMmvRqH.js +0 -159
  46. package/dist/declarations-U6P3rvxC.d.ts +0 -24
  47. package/dist/errors-C4Xcs6Fi.js +0 -121
  48. package/dist/presets.d.ts +0 -11
  49. package/dist/presets.js +0 -25
  50. package/dist/provider.d.ts +0 -6
  51. package/dist/provider.js +0 -7
  52. package/dist/schema.d.ts +0 -16
  53. package/dist/schema.js +0 -37
  54. package/dist/secret-C2191nAa.d.ts +0 -11
  55. package/dist/secret.d.ts +0 -2
  56. package/dist/server-C16sFc1E.js +0 -303
  57. 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.
@@ -33,18 +33,17 @@ import { env, hubEnv } from "@vite-hub/env/vite";
33
33
  import { defineConfig } from "vite";
34
34
 
35
35
  export default defineConfig({
36
- plugins: [hubEnv()],
37
- env: {
36
+ plugins: [hubEnv({
38
37
  public: {
39
38
  appName: env({ default: "ViteHub App", mode: "build" }),
40
39
  },
41
- },
40
+ })],
42
41
  });
43
42
  ```
44
43
 
45
44
  ```ts
46
45
  // app/env.ts
47
- import { usePublicEnv } from "#vitehub/env/public";
46
+ import { usePublicEnv } from "vite-hub/env";
48
47
 
49
48
  console.log(usePublicEnv().appName); // ViteHub App
50
49
  ```
@@ -63,23 +62,23 @@ import { env, hubEnv } from "@vite-hub/env/vite";
63
62
  import { defineConfig } from "vite";
64
63
 
65
64
  export default defineConfig({
66
- plugins: [hubEnv()],
67
- env: {
65
+ plugins: [hubEnv({
68
66
  server: {
69
67
  airtableToken: env({
70
68
  secret: true,
71
69
  source: env.source("AIRTABLE_TOKEN"),
72
70
  }),
73
71
  },
74
- },
72
+ })],
75
73
  });
76
74
  ```
77
75
 
78
76
  ```ts
79
77
  // server/sync.ts
80
- import { useServerEnv } from "#vitehub/env/server";
78
+ import type { ViteHubContext } from "@vite-hub/runtime";
79
+ import { useServerEnv } from "vite-hub/env";
81
80
 
82
- export async function sync(event: unknown) {
81
+ export async function sync(event: ViteHubContext) {
83
82
  const { airtableToken } = useServerEnv(event);
84
83
 
85
84
  await fetch("https://api.airtable.com/v0/app/table", {
@@ -88,6 +87,203 @@ export async function sync(event: unknown) {
88
87
  }
89
88
  ```
90
89
 
90
+ ## Set the values on the host
91
+
92
+ The build writes the host variable names of each `env.server` declaration to `deployment.json`, never the values. `vitehub env diff` shows which names the linked host lacks, and `vitehub env push` sets them from the shell and `.env.<stage>` with the host CLI. See [Check and push host env](https://vitehub.dev/docs/development/cli#check-and-push-host-env).
93
+
94
+ To keep the values in git, encrypt `.env.<stage>` with [dotenvx](https://dotenvx.com/encryption) and keep the private key out of git. `vitehub env push` decrypts `encrypted:` values with `DOTENV_PRIVATE_KEY_<STAGE>` from the shell or `.env.keys`. See [Encrypted env files](https://vitehub.dev/docs/development/cli#encrypted-env-files).
95
+
96
+ ## Derive secrets from one root secret
97
+
98
+ `deriveSecret(purpose)` from `@vite-hub/env` derives a 32-byte hex secret from `VITEHUB_SECRET` with HKDF-SHA256, salt `vitehub`. Auth derives its secret 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).
99
+
100
+ ## Seal a value
101
+
102
+ `seal(purpose, value, { ttl })` from `@vite-hub/env` encrypts and signs a JSON value with AES-GCM. It returns a URL-safe string, so you can put it in a link, a cookie, or a hidden field. `unseal(purpose, sealed)` reads it back. Use it for upload tickets, signed links, OAuth state, and other tokens that the client must carry but must not read or change.
103
+
104
+ ```ts
105
+ // server/uploads.ts
106
+ import { seal, unseal } from "@vite-hub/env";
107
+ import * as v from "valibot";
108
+
109
+ const Upload = v.object({ userId: v.string() });
110
+
111
+ export async function uploadUrl(userId: string) {
112
+ const ticket = await seal("my-app:upload", { userId }, { ttl: 900 });
113
+ return `/api/uploads/${ticket}`;
114
+ }
115
+
116
+ export async function readTicket(ticket: string) {
117
+ const [error, upload] = await unseal("my-app:upload", ticket, { schema: Upload });
118
+ if (error) return undefined; // ENV_SEAL_EXPIRED, ENV_SEAL_INVALID, ENV_SEAL_SCHEMA_MISMATCH, ENV_SEAL_USED_UP, or ENV_SEAL_WRONG_PURPOSE
119
+ return upload;
120
+ }
121
+ ```
122
+
123
+ Each purpose gets its own key, derived from `VITEHUB_SECRET` with `deriveSecret()`, so a value sealed for one purpose does not open as another. `ttl` is in seconds; without it, the value does not expire. `schema` takes any Standard Schema and types the value; without it, the value is `unknown`. `unseal()` returns a `Result`; a missing root secret or a bad argument throws. Web Crypto does the work, so the same string opens on Node, Workers, Deno, and Bun.
124
+
125
+ To rotate `VITEHUB_SECRET`, put the old secret in `VITEHUB_SECRET_PREVIOUS` (one secret, or a comma-separated list). `seal()` uses `VITEHUB_SECRET`, and `unseal()` also tries each old secret, so open links and cookies keep working until they expire. For values that you store, such as provider credentials, pass a separate root secret: `seal("my-app:credentials", value, { secret: env.credentialsKey })`, with the same `secret` for `unseal()`. To rotate it, pass `[newKey, oldKey]`: `seal()` uses the first, and `unseal()` tries each. See [Sign and seal values](https://vitehub.dev/docs/env/seal).
126
+
127
+ ### Single-use values
128
+
129
+ Pass `uses` and a `db` to make a share link that opens once, or N times, and then is gone. Pass the same `db` to `unseal()`. Each read takes one use with one conditional `UPDATE`, so of two reads of the last use on any instances, one gets the value and the other gets `ENV_SEAL_USED_UP`.
130
+
131
+ ```ts
132
+ // server/api/share/[token].get.ts
133
+ import { defineEventHandler, getRouterParam, HTTPError } from "h3";
134
+ import { unseal } from "vite-hub/env";
135
+ import { db } from "vite-hub/database";
136
+
137
+ // Create the link elsewhere: await seal("my-app:share", { apiKey }, { uses: 1, ttl: 3600, db })
138
+ export default defineEventHandler(async (event) => {
139
+ const [error, shared] = await unseal("my-app:share", getRouterParam(event, "token")!, { db });
140
+ if (error) throw new HTTPError({ status: 410, message: error.why }); // ENV_SEAL_USED_UP, ENV_SEAL_EXPIRED, ...
141
+ return shared;
142
+ });
143
+ ```
144
+
145
+ The token holds the encrypted value. The `vitehub_env_seal_uses` table holds only a random id, the uses left, and the expiry, so a leak of the database does not leak values. `db` is a SQLite, libSQL, or D1 Drizzle database; KV cannot take a use atomically. A value that does not open, has expired, or does not match `schema` keeps its uses. `unseal()` without `db` throws `ENV_SEAL_ARGUMENT_INVALID` for a value sealed with `uses`.
146
+
147
+ ## Protect a machine route
148
+
149
+ `requireServiceToken(event, name)` from `vite-hub/env` checks that a request carries `Authorization: Bearer <token>` with a token from the server variable `name`. Use it for routes that scripts, CI runners, and webhooks call. It needs no Auth setup.
150
+
151
+ ```ts
152
+ // server/api/runs.post.ts
153
+ import { defineEventHandler } from "h3";
154
+ import { requireServiceToken } from "vite-hub/env";
155
+
156
+ export default defineEventHandler((event) => {
157
+ requireServiceToken(event, "INGEST_TOKEN");
158
+ return { ok: true };
159
+ });
160
+ ```
161
+
162
+ It compares in constant time. A wrong or missing token throws a `401` HTTP error with `ENV_SERVICE_TOKEN_INVALID`. When the variable has no token, every request fails with `503` and `ENV_SERVICE_TOKEN_UNSET`. The variable holds one token, or a comma-separated list while you rotate. `checkServiceToken(event, name)` returns the same result as `[error, undefined]`. See [Service tokens](https://vitehub.dev/docs/env/service-tokens).
163
+
164
+ ## Verify a webhook
165
+
166
+ `verifyWebhook(event, { provider, secret })` from `vite-hub/env` checks the signature of a Stripe, GitHub, or other HMAC-SHA256 webhook in a plain route. `secret` is the name of the server variable with the signing secret. It reads the raw body once, compares in constant time, and returns `[error, body]` with the parsed JSON body.
167
+
168
+ ```ts
169
+ // server/api/stripe/webhook.post.ts
170
+ import { defineEventHandler, HTTPError } from "h3";
171
+ import { verifyWebhook } from "vite-hub/env";
172
+
173
+ export default defineEventHandler(async (event) => {
174
+ const [error, stripeEvent] = await verifyWebhook<{ type: string }>(event, { provider: "stripe", secret: "STRIPE_WEBHOOK_SECRET" });
175
+ if (error) throw new HTTPError({ status: 400, message: error.message });
176
+ return { received: stripeEvent.type };
177
+ });
178
+ ```
179
+
180
+ `provider` is `"stripe"` (`Stripe-Signature`, at most `toleranceSeconds` old, default 300), `"github"` (`X-Hub-Signature-256`, with a JSON or form body), or `"hmac"` with a `header` and optional `prefix`, `encoding`, and `secretEncoding`. The codes are `ENV_WEBHOOK_SIGNATURE_INVALID`, `ENV_WEBHOOK_SECRET_UNSET`, and `ENV_WEBHOOK_BODY_INVALID`. The variable holds one secret, or a comma-separated list while you rotate. See [Verify webhooks](https://vitehub.dev/docs/env/webhooks).
181
+
182
+ `signWebhook(body, { provider, secret })` signs an outgoing body and returns the headers to send with it. `provider` is `"github"` (`x-hub-signature-256: sha256=<hex>`) or `"stripe"` (`stripe-signature: t=<unix>,v1=<hex>`). Here `secret` is the secret itself, not a variable name. Send the exact body that you signed, so `verifyWebhook()` and other standard receivers accept it.
183
+
184
+ ## Typed server values
185
+
186
+ Host variables are strings. Declare `env.boolean()`, `env.number()`, `env.enum()`, `env.list()`, or `env.json()` when server code needs another type. ViteHub parses the value when Server Env resolves and generates the exact type.
187
+
188
+ ```ts fragment
189
+ // vite.config.ts
190
+ env: {
191
+ server: {
192
+ dryRun: env.boolean({ default: true }), // true, false, 1, or 0
193
+ minConfidence: env.number({ default: 0.6 }), // finite number
194
+ mode: env.enum(["draft", "send"], { default: "draft" }),
195
+ },
196
+ }
197
+ ```
198
+
199
+ `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.
200
+
201
+ `env.list()` reads items separated by commas or line breaks: it trims each item and drops empty items. `env.list(env.number())` parses each item with the item helper. `env.json()` reads JSON text, and `env.json(env.schemaFrom("./server/env.schema.ts", "settings"))` checks it with a Standard Schema from a module:
202
+
203
+ ```ts fragment
204
+ // vite.config.ts
205
+ env: {
206
+ server: {
207
+ adminEmails: env.list({ default: [] }), // string[]
208
+ ports: env.list(env.number()), // number[]
209
+ settings: env.json(env.schemaFrom("./server/env.schema.ts", "settings")), // schema output
210
+ },
211
+ }
212
+ ```
213
+
214
+ Put `default`, `secret`, `source`, and `optional` on the list, not on the item helper. Text that is not JSON fails with `ENV_RUNTIME_VALUE_INVALID`. See [Lists and JSON values](https://vitehub.dev/docs/env/configure#lists-and-json-values).
215
+
216
+ For a pattern, a custom refinement, or a transform, export a Standard Schema from a module and point the declaration at it. The server build imports the module and runs the schema on the raw value:
217
+
218
+ ```ts fragment
219
+ // server/env.schema.ts
220
+ export const apiUrl = z.url().refine(url => url.startsWith("https://"))
221
+
222
+ // vite.config.ts
223
+ env: {
224
+ server: {
225
+ apiUrl: env({ schema: env.schemaFrom("./server/env.schema.ts", "apiUrl") }),
226
+ },
227
+ }
228
+ ```
229
+
230
+ The generated type is the schema output type. A secret keeps its `SecretEnv` wrapper, and its errors omit the schema messages. Read [Validate Server Env with your own schema](https://vitehub.dev/docs/env/configure#validate-server-env-with-your-own-schema).
231
+
232
+ ## `.env.example` schemas
233
+
234
+ Opt in with `envSchema()` when a committed `.env.example` should own variable names, types, requiredness, sensitivity, and defaults:
235
+
236
+ ```ts
237
+ import { envSchema, hubEnv } from "@vite-hub/env/vite";
238
+ import { defineConfig } from "vite";
239
+
240
+ export default defineConfig({
241
+ plugins: [hubEnv(envSchema(new URL("./.env.example", import.meta.url)))],
242
+ });
243
+ ```
244
+
245
+ ```dotenv
246
+ # @public
247
+ VITEHUB_PUBLIC_APP_NAME=Acme
248
+
249
+ # @type=number(min=1, max=10, isInt=true) @public
250
+ VITEHUB_RETRIES=3
251
+
252
+ # @example="get-this-from-your-secret-manager"
253
+ VITEHUB_API_TOKEN=
254
+ ```
255
+
256
+ 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.
257
+
258
+ 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.
259
+
260
+ 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>`.
261
+
262
+ `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.
263
+
264
+ 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. Empty host inputs count as missing for every field type: they use the default when present, otherwise required fields fail and optional fields return `undefined`. Explicit empty schema defaults remain valid where the schema permits them. Invalid nonempty inputs fail, even when a default exists. Generated declarations describe the validated accessors; raw `process.env` types stay unchanged.
265
+
266
+ 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.
267
+
268
+ ## Presets
269
+
270
+ Presets return ordinary `env.server` declarations. Import them from `@vite-hub/env`.
271
+
272
+ | Preset | Declares |
273
+ | --- | --- |
274
+ | `openWorkflowEnv()` | OpenWorkflow namespace, Postgres URL, schema, and worker concurrency. |
275
+ | `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`). |
276
+
277
+ The preset allows a missing API key during Env resolution; Jev reports `GATEWAYS_R0002` when a request needs it. `defineAgent({ driver: { ask } })` uses `typesafe()` when it gets no other gateway, and it reads this group:
278
+
279
+ ```ts fragment
280
+ env: {
281
+ server: {
282
+ typesafe: typesafeEnv(),
283
+ },
284
+ },
285
+ ```
286
+
91
287
  ## External runtime values
92
288
 
93
289
  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.
@@ -99,8 +295,6 @@ import { env, hubEnv } from "@vite-hub/env/vite"
99
295
  export default {
100
296
  plugins: [hubEnv({
101
297
  providers: { credentials: "./server/env/credentials.ts" },
102
- })],
103
- env: {
104
298
  server: {
105
299
  gatewayKey: env({ secret: true }),
106
300
  githubToken: env({
@@ -108,14 +302,14 @@ export default {
108
302
  source: env.provider("credentials", "github/token"),
109
303
  }),
110
304
  },
111
- },
305
+ })],
112
306
  }
113
307
  ```
114
308
 
115
309
  ```ts
116
310
  // server/env/credentials.ts
117
- import { defineEnvProvider } from "@vite-hub/env/provider"
118
- import type { SecretEnv } from "@vite-hub/env/secret"
311
+ import { defineEnvProvider } from "@vite-hub/env"
312
+ import type { SecretEnv } from "@vite-hub/env"
119
313
 
120
314
  export default defineEnvProvider<{ gatewayKey: SecretEnv<string> }>({
121
315
  async read({ env, keys, signal }) {
@@ -130,7 +324,7 @@ export default defineEnvProvider<{ gatewayKey: SecretEnv<string> }>({
130
324
  ```
131
325
 
132
326
  ```ts
133
- import { loadServerEnv } from "#vitehub/env/server"
327
+ import { loadServerEnv } from "vite-hub/env"
134
328
 
135
329
  const snapshot = await loadServerEnv()
136
330
  const githubToken = snapshot.githubToken.unseal()
@@ -138,7 +332,9 @@ const githubToken = snapshot.githubToken.unseal()
138
332
 
139
333
  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
334
 
141
- 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.
335
+ `env.source(["PRIMARY_TOKEN", "FALLBACK_TOKEN"])` reads the first variable that is set and not empty. An empty variable, such as `PRIMARY_TOKEN=`, counts as missing for every source. It does not shadow a later name, and it does not satisfy a required value or a secret.
336
+
337
+ The Server Env helpers of `@vite-hub/env` are not blocked from client builds. Keep their 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
338
 
143
339
  `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.
144
340
 
@@ -152,7 +348,7 @@ Install the shared runtime package before inspecting structured errors:
152
348
  pnpm add @vite-hub/runtime
153
349
  ```
154
350
 
155
- ```ts
351
+ ```ts fragment
156
352
  import { getViteHubErrorShape } from "@vite-hub/runtime";
157
353
 
158
354
  try {
@@ -165,11 +361,11 @@ try {
165
361
  }
166
362
  ```
167
363
 
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.
364
+ 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
365
 
170
366
  ## Generated modules
171
367
 
172
- Use `hubEnv()` in Vite to resolve public/build env, generate `#vitehub/env/public` and `#vitehub/env/server`, and keep environment declarations close to the app config. Runtime secrets are read from the host environment at request time and are wrapped in `SecretEnv` until explicitly unsealed.
368
+ Use `hubEnv()` in Vite to resolve public/build env, generate the Public Env and Server Env that `usePublicEnv()` and `useServerEnv()` read, and keep environment declarations close to the app config. Runtime secrets are read from the host environment at request time and are wrapped in `SecretEnv` until explicitly unsealed.
173
369
 
174
370
  `hubEnv()` writes generated env runtime modules to `.vitehub/env/` and generated env types to `.vitehub/types/env.d.ts`. Add `.vitehub/types/**/*.d.ts` to your `tsconfig.json` include list when TypeScript should see app-specific Public Env and Server Env fields.
175
371
 
@@ -195,6 +391,75 @@ export default {
195
391
  };
196
392
  ```
197
393
 
394
+ To type code without running Vite, such as in a test or a docs check, pass the same `env` options to `createEnvTypes()`. It returns the contents of `.vitehub/types/env.d.ts`:
395
+
396
+ ```ts
397
+ import { mkdirSync, writeFileSync } from "node:fs";
398
+ import { createEnvTypes, env } from "@vite-hub/env/vite";
399
+
400
+ mkdirSync(".vitehub/types", { recursive: true });
401
+ writeFileSync(".vitehub/types/env.d.ts", createEnvTypes({
402
+ server: { githubToken: env({ secret: true, source: env.source("GITHUB_TOKEN") }) },
403
+ }));
404
+ ```
405
+
198
406
  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
407
 
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).
408
+ 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).
409
+
410
+ ### Declaration inventory
411
+
412
+ `describeServerEnv()` from `@vite-hub/env` returns declaration metadata without reading host values or calling providers. It includes the declaration path, the `names` an env declaration reads in read order (the canonical name first unless `canonical: false` or `prefix: false` turns it off, then the `env.source()` names or the unprefixed path name), source kind, provider alias, secret and required flags, default presence, and the parsed value type. Values, defaults 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, `names`, the `name` that supplied an env value, 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.
413
+
414
+ `hubEnv()` contributes two CLI commands:
415
+
416
+ ```bash
417
+ vitehub env inspect [--stage <name>] [--json]
418
+ vitehub env check [--stage <name>] [--json]
419
+ ```
420
+
421
+ 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. `--json` also lists the host variable `names` of each env declaration. Values are never printed. `env check` exits with `1` when `loadServerEnv()` would fail.
422
+
423
+ `hubEnv()` also contributes the `env.inspect` operation. It asks the running app, not a local stage, so the CLI and the Console can check that a deployed app has its env. It answers on the signed `POST /_vitehub/rpc` endpoint like every other operation, and needs the `env` Console section (`env:read` is enough).
424
+
425
+ ```bash
426
+ vitehub env status --url https://my-app.example.com
427
+ ```
428
+
429
+ The result has `ok`, the `host` that the app runs on when it is known, and one entry per declaration: `path`, `names`, `name` (the host variable that supplied the value), `source`, `provider`, `required`, `secret`, `status`, and `blocking`. The status is `available`, `defaulted`, `missing`, `invalid`, or `error`, as in `inspectServerEnv()`. The result never holds a value, a preview, or a length.
430
+
431
+ ### Managed credentials
432
+
433
+ `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 keys in host configuration and back them up separately from the database.
434
+
435
+ `encryptionKeys` is a keyring: the current key first, then previous keys. Each value is stored as `v2:<keyId>:<iv>:<ciphertext>`, where `keyId` is `sealKeyId()` of the key that sealed it. A read picks the key by its id. A value from an older store, `<iv>:<ciphertext>` without a key id, reads with the current key, then each previous key. The AES-GCM additional data binds each value to its namespace, key, and revision, so a value moved to another row does not decrypt.
436
+
437
+ To rotate the key:
438
+
439
+ 1. Pass `encryptionKeys: [newKey, oldKey]`. New writes use `newKey`.
440
+ 2. Call `await store.rotate()`. It re-encrypts each value that another key sealed and returns `{ rotated, skipped }`. Revisions stay the same, so `revisionCondition()` and `expectedRevision` stay valid. A value that a write replaces during the rotation keeps the new write.
441
+ 3. Pass `encryptionKeys: [newKey]`.
442
+
443
+ `@vite-hub/env/seal` exports the AES-GCM helpers that the database store uses: `importSealKey`, `sealWithKey`, `unsealWithKey`, and `sealKeyId`. Other owner packages use them to store sealed values in the same format. To seal an app value with a key derived from `VITEHUB_SECRET`, use [`seal()` and `unseal()`](#seal-a-value).
444
+
445
+ 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.
446
+
447
+ `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.
448
+
449
+ Env creates every `EnvAccessContext`. Each producer gets only the identity that it can prove:
450
+
451
+ - `createEnvBridge({ runtimeActor })`: the runtime reads with its own fixed actor, on that bridge only. `runtimeAttribution` can add trace and invocation IDs.
452
+ - `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`.
453
+ - The ViteHub Agent runtime: `agent:<name>` for the Agent Definition that runs, through Connections.
454
+
455
+ 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.
456
+
457
+ Migration: replace `runtimeContext: () => ({ actor })` with `runtimeActor: actor`. Get request contexts from `createEnvAuthenticator()`. A custom `authenticate` must return the context from `createEnvAuthenticator()`.
458
+
459
+ `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.
460
+
461
+ 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.
462
+
463
+ 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.
464
+
465
+ 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-BhJ77age.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 };