@vite-hub/env 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +243 -28
  3. package/dist/access-B3qzBHye.js +54 -0
  4. package/dist/auth.d.ts +32 -0
  5. package/dist/auth.js +44 -0
  6. package/dist/bridge-CdNdTN1V.d.ts +374 -0
  7. package/dist/bridge-error-CFuU5zIz.js +65 -0
  8. package/dist/bridge.d.ts +2 -0
  9. package/dist/bridge.js +192 -0
  10. package/dist/cli-CMQPQbii.js +487 -0
  11. package/dist/cli-DEwcUIe0.d.ts +81 -0
  12. package/dist/cli.d.ts +41 -0
  13. package/dist/cli.js +2 -0
  14. package/dist/database.d.ts +21 -0
  15. package/dist/database.js +183 -0
  16. package/dist/declarations-CiRdb1qP.d.ts +32 -0
  17. package/dist/declarations-DAVgctKD.js +236 -0
  18. package/dist/error-diagnostics-CrxjYNYr.js +43 -0
  19. package/dist/http.d.ts +2 -0
  20. package/dist/http.js +122 -0
  21. package/dist/index.d.ts +13 -8
  22. package/dist/index.js +5 -4
  23. package/dist/internal/agent.d.ts +5 -0
  24. package/dist/internal/agent.js +22 -0
  25. package/dist/internal/connections.d.ts +18 -0
  26. package/dist/internal/connections.js +31 -0
  27. package/dist/presets.d.ts +15 -6
  28. package/dist/presets.js +21 -2
  29. package/dist/provider.d.ts +5 -0
  30. package/dist/provider.js +8 -0
  31. package/dist/schema.d.ts +5 -6
  32. package/dist/schema.js +26 -8
  33. package/dist/seal.d.ts +14 -0
  34. package/dist/seal.js +49 -0
  35. package/dist/secret-C2191nAa.d.ts +11 -0
  36. package/dist/secret.d.ts +1 -10
  37. package/dist/server-DufVswRJ.js +670 -0
  38. package/dist/server.d.ts +23 -4
  39. package/dist/server.js +2 -3
  40. package/dist/values-D_r6V774.js +148 -0
  41. package/dist/virtual-module.d.ts +34 -0
  42. package/dist/virtual.d.ts +2 -15
  43. package/dist/vite.d.ts +37 -14
  44. package/dist/vite.js +1058 -292
  45. package/package.json +84 -16
  46. package/dist/declarations-BIBfEwer.d.ts +0 -23
  47. package/dist/declarations-Cy5XamUA.js +0 -144
  48. package/dist/errors-RUmAFDJn.js +0 -112
  49. package/dist/server-B2Dp8Nc0.js +0 -59
  50. package/dist/types-FcnPKias.d.ts +0 -153
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,80 +1,252 @@
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
- `@vite-hub/env` declares environment values once, then generates typed public and server env access.
9
+ `@vite-hub/env` declares environment values once, then generates typed public and server-oriented access plus untyped build-time replacements for Vite applications.
10
+
11
+ Most applications install `vite-hub` and enable Env through the framework preset. Install this owner package directly when a library or focused Vite integration needs Env without the rest of ViteHub.
10
12
 
11
13
  ## Install
12
14
 
13
15
  ```sh
14
16
  pnpm add @vite-hub/env
17
+ pnpm add -D vite
15
18
  ```
16
19
 
17
- ## Minimal API
20
+ ## Choose an Env section
21
+
22
+ | Section | Read when | Visible to client code | Use it for |
23
+ | ------------ | ------------------------- | ---------------------- | --------------------------------------------------------------- |
24
+ | `env.public` | Build time | Yes | Browser-safe application configuration. |
25
+ | `env.define` | Build transform | Yes, where bundled | Untyped compile-time replacements such as a release identifier. |
26
+ | `env.server` | Request or server runtime | By caller convention | Host-supplied server configuration and source-only credentials. |
27
+
28
+ ## First result
18
29
 
19
30
  ```ts
20
31
  // vite.config.ts
21
- import { env, hubEnv } from "@vite-hub/env/vite"
22
- import { defineConfig } from "vite"
32
+ import { env, hubEnv } from "@vite-hub/env/vite";
33
+ import { defineConfig } from "vite";
23
34
 
24
35
  export default defineConfig({
25
- plugins: [hubEnv({ prefix: "VITEHUB_" })],
36
+ plugins: [hubEnv()],
26
37
  env: {
27
38
  public: {
28
39
  appName: env({ default: "ViteHub App", mode: "build" }),
29
40
  },
30
- server: {
31
- airtableToken: env({ secret: true }),
32
- },
33
41
  },
34
- })
42
+ });
35
43
  ```
36
44
 
37
45
  ```ts
38
46
  // app/env.ts
39
- import { publicEnv } from "#vitehub/env/public"
47
+ import { usePublicEnv } from "#vitehub/env/public";
48
+
49
+ console.log(usePublicEnv().appName); // ViteHub App
50
+ ```
51
+
52
+ Run that file through the application's Vite dev or build pipeline. `hubEnv()` generates the stable `#vitehub/env/public` module and its field-level types; it is not a package import that plain Node resolves outside the configured application.
53
+
54
+ Add `.vitehub/types/**/*.d.ts` to the application's `tsconfig.json` `include` list when TypeScript should see the generated fields.
55
+
56
+ ## Read a server secret
57
+
58
+ Declare a secret under `env.server`, then read it only from server code:
59
+
60
+ ```ts
61
+ // vite.config.ts
62
+ import { env, hubEnv } from "@vite-hub/env/vite";
63
+ import { defineConfig } from "vite";
40
64
 
41
- export const appName = publicEnv.appName
65
+ export default defineConfig({
66
+ plugins: [hubEnv()],
67
+ env: {
68
+ server: {
69
+ airtableToken: env({
70
+ secret: true,
71
+ source: env.source("AIRTABLE_TOKEN"),
72
+ }),
73
+ },
74
+ },
75
+ });
42
76
  ```
43
77
 
44
78
  ```ts
45
79
  // server/sync.ts
46
- import { useServerEnv } from "#vitehub/env/server"
80
+ import { useServerEnv } from "#vitehub/env/server";
47
81
 
48
82
  export async function sync(event: unknown) {
49
- const { airtableToken } = useServerEnv(event)
83
+ const { airtableToken } = useServerEnv(event);
50
84
 
51
85
  await fetch("https://api.airtable.com/v0/app/table", {
52
86
  headers: { Authorization: `Bearer ${airtableToken.unseal()}` },
53
- })
87
+ });
88
+ }
89
+ ```
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
+ },
54
107
  }
55
108
  ```
56
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
+
168
+ ## External runtime values
169
+
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.
171
+
172
+ ```ts
173
+ // vite.config.ts
174
+ import { env, hubEnv } from "@vite-hub/env/vite"
175
+
176
+ export default {
177
+ plugins: [hubEnv({
178
+ providers: { credentials: "./server/env/credentials.ts" },
179
+ })],
180
+ env: {
181
+ server: {
182
+ gatewayKey: env({ secret: true }),
183
+ githubToken: env({
184
+ secret: true,
185
+ source: env.provider("credentials", "github/token"),
186
+ }),
187
+ },
188
+ },
189
+ }
190
+ ```
191
+
192
+ ```ts
193
+ // server/env/credentials.ts
194
+ import { defineEnvProvider } from "@vite-hub/env/provider"
195
+ import type { SecretEnv } from "@vite-hub/env/secret"
196
+
197
+ export default defineEnvProvider<{ gatewayKey: SecretEnv<string> }>({
198
+ async read({ env, keys, signal }) {
199
+ const response = await fetch("https://credentials.internal/env", {
200
+ headers: { authorization: `Bearer ${env.gatewayKey.unseal()}` },
201
+ signal,
202
+ })
203
+ const values = await response.json() as Record<string, string | undefined>
204
+ return Object.fromEntries(keys.map(key => [key, values[key]]))
205
+ },
206
+ })
207
+ ```
208
+
209
+ ```ts
210
+ import { loadServerEnv } from "#vitehub/env/server"
211
+
212
+ const snapshot = await loadServerEnv()
213
+ const githubToken = snapshot.githubToken.unseal()
214
+ ```
215
+
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()`.
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
+
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.
221
+
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.
223
+
57
224
  ## Structured errors
58
225
 
59
226
  ViteHub-owned Env resolution failures use the shared `ViteHubError` contract with Env-specific codes. Custom source resolvers keep application-owned errors unchanged, so callers can preserve their own error contract without translating it through ViteHub.
60
227
 
228
+ Install the shared runtime package before inspecting structured errors:
229
+
230
+ ```sh
231
+ pnpm add @vite-hub/runtime
232
+ ```
233
+
61
234
  ```ts
62
- import { getViteHubErrorShape } from "@vite-hub/runtime"
235
+ import { getViteHubErrorShape } from "@vite-hub/runtime";
63
236
 
64
237
  try {
65
- await resolveVaultEnv()
66
- }
67
- catch (error) {
238
+ await resolveVaultEnv();
239
+ } catch (error) {
68
240
  if (getViteHubErrorShape(error)?.code === "ENV_SOURCE_FAILED") {
69
- console.error("Env source failed")
241
+ console.error("Env source failed");
70
242
  }
71
- throw error
243
+ throw error;
72
244
  }
73
245
  ```
74
246
 
75
- 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.
76
248
 
77
- ## Vite Integration
249
+ ## Generated modules
78
250
 
79
251
  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.
80
252
 
@@ -83,7 +255,7 @@ Use `hubEnv()` in Vite to resolve public/build env, generate `#vitehub/env/publi
83
255
  For hosts that do not consume Vite plugin aliases directly, compose the generated modules explicitly:
84
256
 
85
257
  ```ts
86
- import { createEnvImportAliases, createEnvTypeScriptPaths, hubEnv } from "@vite-hub/env/vite"
258
+ import { createEnvImportAliases, createEnvTypeScriptPaths, hubEnv } from "@vite-hub/env/vite";
87
259
 
88
260
  export default {
89
261
  nitro: {
@@ -99,7 +271,50 @@ export default {
99
271
  vite: {
100
272
  plugins: [hubEnv()],
101
273
  },
102
- }
274
+ };
275
+ ```
276
+
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.
278
+
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]
103
290
  ```
104
291
 
105
- Learn more at [vitehub.dev](https://vitehub.dev).
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