@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.
- package/README.md +178 -33
- package/dist/{access-B3qzBHye.js → access-B8lSDip4.js} +1 -1
- package/dist/{bridge-CdNdTN1V.d.ts → bridge-Cs9YfQWk.d.ts} +111 -38
- package/dist/{bridge-error-CFuU5zIz.js → bridge-error-BhJ77age.js} +14 -13
- package/dist/bridge.d.ts +2 -2
- package/dist/bridge.js +168 -6
- package/dist/cli-BPp7rdcA.d.ts +159 -0
- package/dist/{cli-CMQPQbii.js → cli-DLpY0QAo.js} +212 -30
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +1 -1
- package/dist/database.d.ts +29 -3
- package/dist/database.js +106 -15
- package/dist/declarations-C5XR3aKw.d.ts +58 -0
- package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
- package/dist/index.d.ts +145 -10
- package/dist/index.js +240 -7
- package/dist/internal/agent.d.ts +1 -1
- package/dist/internal/agent.js +2 -2
- package/dist/internal/connections.d.ts +1 -1
- package/dist/internal/connections.js +2 -2
- package/dist/internal/server.d.ts +3 -0
- package/dist/internal/server.js +2 -0
- package/dist/object-_dlsZ4lP.js +276 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-X1w--wds.js +30 -0
- package/dist/operations.d.ts +37 -0
- package/dist/operations.js +833 -0
- package/dist/runtime/public-env.d.ts +5 -0
- package/dist/runtime/public-env.js +8 -0
- package/dist/runtime/server-env.d.ts +22 -0
- package/dist/runtime/server-env.js +35 -0
- package/dist/schema-DMZ1_yhY.js +360 -0
- package/dist/seal.d.ts +8 -5
- package/dist/seal.js +9 -6
- package/dist/{secret.js → secret-DJd-fy5T.js} +1 -1
- package/dist/server-ChNL_Xc3.js +1279 -0
- package/dist/server-Dd8bjIKd.d.ts +145 -0
- package/dist/server.d.ts +3 -25
- package/dist/server.js +2 -2
- package/dist/virtual-module.d.ts +6 -6
- package/dist/vite.d.ts +59 -14
- package/dist/vite.js +304 -115
- package/package.json +27 -38
- package/dist/auth.d.ts +0 -32
- package/dist/auth.js +0 -44
- package/dist/cli-DEwcUIe0.d.ts +0 -81
- package/dist/declarations-CiRdb1qP.d.ts +0 -32
- package/dist/declarations-DAVgctKD.js +0 -236
- package/dist/error-diagnostics-CrxjYNYr.js +0 -43
- package/dist/http.d.ts +0 -2
- package/dist/http.js +0 -122
- package/dist/presets.d.ts +0 -20
- package/dist/presets.js +0 -44
- package/dist/provider.d.ts +0 -5
- package/dist/provider.js +0 -8
- package/dist/schema.d.ts +0 -15
- package/dist/schema.js +0 -55
- package/dist/secret-C2191nAa.d.ts +0 -11
- package/dist/secret.d.ts +0 -2
- package/dist/server-DufVswRJ.js +0 -670
- package/dist/values-D_r6V774.js +0 -148
package/README.md
CHANGED
|
@@ -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 "
|
|
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 {
|
|
78
|
+
import type { ViteHubContext } from "@vite-hub/runtime";
|
|
79
|
+
import { useServerEnv } from "vite-hub/env";
|
|
81
80
|
|
|
82
|
-
export async function sync(event:
|
|
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,15 +87,105 @@ 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
|
+
|
|
91
96
|
## Derive secrets from one root secret
|
|
92
97
|
|
|
93
|
-
`deriveSecret(purpose)` from
|
|
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).
|
|
94
99
|
|
|
95
|
-
##
|
|
100
|
+
## Seal a value
|
|
96
101
|
|
|
97
|
-
|
|
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.
|
|
98
103
|
|
|
99
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
|
|
100
189
|
// vite.config.ts
|
|
101
190
|
env: {
|
|
102
191
|
server: {
|
|
@@ -107,7 +196,38 @@ env: {
|
|
|
107
196
|
}
|
|
108
197
|
```
|
|
109
198
|
|
|
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.
|
|
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).
|
|
111
231
|
|
|
112
232
|
## `.env.example` schemas
|
|
113
233
|
|
|
@@ -118,8 +238,7 @@ import { envSchema, hubEnv } from "@vite-hub/env/vite";
|
|
|
118
238
|
import { defineConfig } from "vite";
|
|
119
239
|
|
|
120
240
|
export default defineConfig({
|
|
121
|
-
plugins: [hubEnv()],
|
|
122
|
-
env: envSchema(new URL("./.env.example", import.meta.url)),
|
|
241
|
+
plugins: [hubEnv(envSchema(new URL("./.env.example", import.meta.url)))],
|
|
123
242
|
});
|
|
124
243
|
```
|
|
125
244
|
|
|
@@ -142,22 +261,22 @@ Only `VITEHUB_PUBLIC_` names enter Public Env. Mark them `@public` or `@sensitiv
|
|
|
142
261
|
|
|
143
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.
|
|
144
263
|
|
|
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.
|
|
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.
|
|
146
265
|
|
|
147
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.
|
|
148
267
|
|
|
149
268
|
## Presets
|
|
150
269
|
|
|
151
|
-
Presets return ordinary `env.server` declarations. Import them from `@vite-hub/env
|
|
270
|
+
Presets return ordinary `env.server` declarations. Import them from `@vite-hub/env`.
|
|
152
271
|
|
|
153
272
|
| Preset | Declares |
|
|
154
273
|
| --- | --- |
|
|
155
274
|
| `openWorkflowEnv()` | OpenWorkflow namespace, Postgres URL, schema, and worker concurrency. |
|
|
156
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`). |
|
|
157
276
|
|
|
158
|
-
The preset allows a missing API key during Env resolution; Jev reports `GATEWAYS_R0002` when a request needs it. `defineAgent({ driver: { ask } })
|
|
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:
|
|
159
278
|
|
|
160
|
-
```ts
|
|
279
|
+
```ts fragment
|
|
161
280
|
env: {
|
|
162
281
|
server: {
|
|
163
282
|
typesafe: typesafeEnv(),
|
|
@@ -176,8 +295,6 @@ import { env, hubEnv } from "@vite-hub/env/vite"
|
|
|
176
295
|
export default {
|
|
177
296
|
plugins: [hubEnv({
|
|
178
297
|
providers: { credentials: "./server/env/credentials.ts" },
|
|
179
|
-
})],
|
|
180
|
-
env: {
|
|
181
298
|
server: {
|
|
182
299
|
gatewayKey: env({ secret: true }),
|
|
183
300
|
githubToken: env({
|
|
@@ -185,14 +302,14 @@ export default {
|
|
|
185
302
|
source: env.provider("credentials", "github/token"),
|
|
186
303
|
}),
|
|
187
304
|
},
|
|
188
|
-
},
|
|
305
|
+
})],
|
|
189
306
|
}
|
|
190
307
|
```
|
|
191
308
|
|
|
192
309
|
```ts
|
|
193
310
|
// server/env/credentials.ts
|
|
194
|
-
import { defineEnvProvider } from "@vite-hub/env
|
|
195
|
-
import type { SecretEnv } from "@vite-hub/env
|
|
311
|
+
import { defineEnvProvider } from "@vite-hub/env"
|
|
312
|
+
import type { SecretEnv } from "@vite-hub/env"
|
|
196
313
|
|
|
197
314
|
export default defineEnvProvider<{ gatewayKey: SecretEnv<string> }>({
|
|
198
315
|
async read({ env, keys, signal }) {
|
|
@@ -207,7 +324,7 @@ export default defineEnvProvider<{ gatewayKey: SecretEnv<string> }>({
|
|
|
207
324
|
```
|
|
208
325
|
|
|
209
326
|
```ts
|
|
210
|
-
import { loadServerEnv } from "
|
|
327
|
+
import { loadServerEnv } from "vite-hub/env"
|
|
211
328
|
|
|
212
329
|
const snapshot = await loadServerEnv()
|
|
213
330
|
const githubToken = snapshot.githubToken.unseal()
|
|
@@ -215,9 +332,9 @@ const githubToken = snapshot.githubToken.unseal()
|
|
|
215
332
|
|
|
216
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()`.
|
|
217
334
|
|
|
218
|
-
`env.source(["PRIMARY_TOKEN", "FALLBACK_TOKEN"]
|
|
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.
|
|
219
336
|
|
|
220
|
-
The
|
|
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.
|
|
221
338
|
|
|
222
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.
|
|
223
340
|
|
|
@@ -231,7 +348,7 @@ Install the shared runtime package before inspecting structured errors:
|
|
|
231
348
|
pnpm add @vite-hub/runtime
|
|
232
349
|
```
|
|
233
350
|
|
|
234
|
-
```ts
|
|
351
|
+
```ts fragment
|
|
235
352
|
import { getViteHubErrorShape } from "@vite-hub/runtime";
|
|
236
353
|
|
|
237
354
|
try {
|
|
@@ -248,7 +365,7 @@ Each `EnvErrorCode` owns a fixed public message and a bounded details shape. Sou
|
|
|
248
365
|
|
|
249
366
|
## Generated modules
|
|
250
367
|
|
|
251
|
-
Use `hubEnv()` in Vite to resolve public/build env, generate
|
|
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.
|
|
252
369
|
|
|
253
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.
|
|
254
371
|
|
|
@@ -274,13 +391,25 @@ export default {
|
|
|
274
391
|
};
|
|
275
392
|
```
|
|
276
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
|
+
|
|
277
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.
|
|
278
407
|
|
|
279
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).
|
|
280
409
|
|
|
281
410
|
### Declaration inventory
|
|
282
411
|
|
|
283
|
-
`describeServerEnv()` from
|
|
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.
|
|
284
413
|
|
|
285
414
|
`hubEnv()` contributes two CLI commands:
|
|
286
415
|
|
|
@@ -289,13 +418,29 @@ vitehub env inspect [--stage <name>] [--json]
|
|
|
289
418
|
vitehub env check [--stage <name>] [--json]
|
|
290
419
|
```
|
|
291
420
|
|
|
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.
|
|
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.
|
|
293
430
|
|
|
294
431
|
### Managed credentials
|
|
295
432
|
|
|
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
|
|
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]`.
|
|
297
442
|
|
|
298
|
-
`@vite-hub/env/seal` exports the AES-GCM helpers that the database store uses: `importSealKey`, `
|
|
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).
|
|
299
444
|
|
|
300
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.
|
|
301
446
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as envBridgeError } from "./bridge-error-
|
|
1
|
+
import { t as envBridgeError } from "./bridge-error-BhJ77age.js";
|
|
2
2
|
import { defineGrant } from "@vite-hub/runtime/internal/grant";
|
|
3
3
|
//#region src/internal/access.ts
|
|
4
4
|
/** Marks the type of contexts that Env creates. The bridge trusts only the `envAccess` grant registry, not this marker. */
|