@vite-hub/env 0.3.1 → 0.4.1
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 +15 -12
- package/dist/{cli-DLpY0QAo.js → cli-C51D6V-M.js} +79 -79
- package/dist/cli.js +1 -1
- package/dist/{error-diagnostics-B8RFjQ1V.js → error-diagnostics-DsDPsST_.js} +1 -1
- package/dist/index.d.ts +16 -6
- package/dist/index.js +14 -22
- package/dist/internal/server.d.ts +1 -1
- package/dist/internal/server.js +1 -1
- package/dist/{object-_dlsZ4lP.js → object-C7Jt4ez2.js} +5 -1
- package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
- package/dist/{operations-X1w--wds.js → operations-B1PFpKzy.js} +1 -1
- package/dist/operations.d.ts +1 -1
- package/dist/operations.js +2 -2
- package/dist/runtime/public-env.js +1 -1
- package/dist/runtime/server-env.js +1 -1
- package/dist/{schema-DMZ1_yhY.js → schema-C_a0WZyd.js} +2 -2
- package/dist/{server-ChNL_Xc3.js → server-B9-8r6MZ.js} +24 -13
- package/dist/{server-Dd8bjIKd.d.ts → server-CgKAEAE6.d.ts} +7 -4
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +5 -5
- package/package.json +4 -4
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://
|
|
5
|
-
<img alt="TypeScript" src="https://
|
|
6
|
-
<img alt="Vite" src="https://
|
|
4
|
+
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/static/v1?label=ViteHub&message=vitehub.dev&color=blue"></a>
|
|
5
|
+
<img alt="TypeScript" src="https://img.shields.io/static/v1?label=TypeScript&message=ready&color=blue">
|
|
6
|
+
<img alt="Vite" src="https://img.shields.io/static/v1?label=Vite&message=public+env&color=blue">
|
|
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.
|
|
@@ -89,9 +89,9 @@ export async function sync(event: ViteHubContext) {
|
|
|
89
89
|
|
|
90
90
|
## Set the values on the host
|
|
91
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/
|
|
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/cli/primitives#check-and-push-host-env).
|
|
93
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/
|
|
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/cli/primitives#encrypted-env-files).
|
|
95
95
|
|
|
96
96
|
## Derive secrets from one root secret
|
|
97
97
|
|
|
@@ -109,7 +109,7 @@ import * as v from "valibot";
|
|
|
109
109
|
const Upload = v.object({ userId: v.string() });
|
|
110
110
|
|
|
111
111
|
export async function uploadUrl(userId: string) {
|
|
112
|
-
const ticket = await seal("my-app:upload", { userId }, { ttl:
|
|
112
|
+
const ticket = await seal("my-app:upload", { userId }, { ttl: "15m" });
|
|
113
113
|
return `/api/uploads/${ticket}`;
|
|
114
114
|
}
|
|
115
115
|
|
|
@@ -120,7 +120,7 @@ export async function readTicket(ticket: string) {
|
|
|
120
120
|
}
|
|
121
121
|
```
|
|
122
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
|
|
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 a duration such as `"15m"`, or a number of 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
124
|
|
|
125
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
126
|
|
|
@@ -134,7 +134,7 @@ import { defineEventHandler, getRouterParam, HTTPError } from "h3";
|
|
|
134
134
|
import { unseal } from "vite-hub/env";
|
|
135
135
|
import { db } from "vite-hub/database";
|
|
136
136
|
|
|
137
|
-
// Create the link elsewhere: await seal("my-app:share", { apiKey }, { uses: 1, ttl:
|
|
137
|
+
// Create the link elsewhere: await seal("my-app:share", { apiKey }, { uses: 1, ttl: "1h", db })
|
|
138
138
|
export default defineEventHandler(async (event) => {
|
|
139
139
|
const [error, shared] = await unseal("my-app:share", getRouterParam(event, "token")!, { db });
|
|
140
140
|
if (error) throw new HTTPError({ status: 410, message: error.why }); // ENV_SEAL_USED_UP, ENV_SEAL_EXPIRED, ...
|
|
@@ -163,21 +163,24 @@ It compares in constant time. A wrong or missing token throws a `401` HTTP error
|
|
|
163
163
|
|
|
164
164
|
## Verify a webhook
|
|
165
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.
|
|
166
|
+
`verifyWebhook(event, { provider, secret, schema })` 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. `schema` is a Standard Schema, such as a Valibot or Zod schema: it checks the body and types it. Without `schema`, `body` is `unknown`.
|
|
167
167
|
|
|
168
168
|
```ts
|
|
169
169
|
// server/api/stripe/webhook.post.ts
|
|
170
170
|
import { defineEventHandler, HTTPError } from "h3";
|
|
171
|
+
import * as v from "valibot";
|
|
171
172
|
import { verifyWebhook } from "vite-hub/env";
|
|
172
173
|
|
|
174
|
+
const schema = v.object({ type: v.string() });
|
|
175
|
+
|
|
173
176
|
export default defineEventHandler(async (event) => {
|
|
174
|
-
const [error, stripeEvent] = await verifyWebhook
|
|
177
|
+
const [error, stripeEvent] = await verifyWebhook(event, { provider: "stripe", secret: "STRIPE_WEBHOOK_SECRET", schema });
|
|
175
178
|
if (error) throw new HTTPError({ status: 400, message: error.message });
|
|
176
179
|
return { received: stripeEvent.type };
|
|
177
180
|
});
|
|
178
181
|
```
|
|
179
182
|
|
|
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 `
|
|
183
|
+
`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`, `ENV_WEBHOOK_BODY_INVALID`, and `ENV_WEBHOOK_SCHEMA_MISMATCH`. The variable holds one secret, or a comma-separated list while you rotate. See [Verify webhooks](https://vitehub.dev/docs/env/webhooks).
|
|
181
184
|
|
|
182
185
|
`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
186
|
|
|
@@ -361,7 +364,7 @@ try {
|
|
|
361
364
|
}
|
|
362
365
|
```
|
|
363
366
|
|
|
364
|
-
Each `EnvErrorCode` owns a
|
|
367
|
+
Each `EnvErrorCode` owns a public message and a bounded details shape. Source details use stable identifiers such as `git:branch`, `package.json`, `env`, or `custom`. `ENV_REQUIRED_MISSING` is the one code whose message and `details.names` name the variables to set, so the operator knows what is missing; it never holds a value. Other raw labels, 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.
|
|
365
368
|
|
|
366
369
|
## Generated modules
|
|
367
370
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as envErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { C as deriveViteHubSecret, E as readViteHubSecret, a as isBlockingServerEnvEntry, f as invariant } from "./server-
|
|
1
|
+
import { t as envErrorDiagnostics } from "./error-diagnostics-DsDPsST_.js";
|
|
2
|
+
import { C as deriveViteHubSecret, E as readViteHubSecret, a as isBlockingServerEnvEntry, f as invariant } from "./server-B9-8r6MZ.js";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import * as v from "valibot";
|
|
5
5
|
import { existsSync, statSync } from "node:fs";
|
|
@@ -7,6 +7,83 @@ import { basename, dirname, join, parse, resolve } from "node:path";
|
|
|
7
7
|
import { pathToFileURL } from "node:url";
|
|
8
8
|
import { tmpdir } from "node:os";
|
|
9
9
|
import { randomBytes } from "node:crypto";
|
|
10
|
+
//#region ../internal/src/cli.ts
|
|
11
|
+
const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
|
|
12
|
+
const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
|
|
13
|
+
const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
|
|
14
|
+
const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
|
|
15
|
+
const stdoutRedirectGlobal = globalThis;
|
|
16
|
+
/**
|
|
17
|
+
* Sends `process.stdout` writes to stderr while `run` loads project config.
|
|
18
|
+
* Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
|
|
19
|
+
*/
|
|
20
|
+
async function withStdoutOnStderr(run, stderr = process.stderr) {
|
|
21
|
+
getStableStdoutWrite();
|
|
22
|
+
const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
|
|
23
|
+
let release;
|
|
24
|
+
stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
|
|
25
|
+
release = resolve;
|
|
26
|
+
});
|
|
27
|
+
await previous;
|
|
28
|
+
const write = process.stdout.write;
|
|
29
|
+
if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
|
|
30
|
+
stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
|
|
31
|
+
stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
|
|
32
|
+
}
|
|
33
|
+
stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
|
|
34
|
+
process.stdout.write = ((chunk, encoding, callback) => {
|
|
35
|
+
const done = typeof encoding === "function" ? encoding : callback;
|
|
36
|
+
let called = false;
|
|
37
|
+
const onComplete = (error) => {
|
|
38
|
+
if (called) return;
|
|
39
|
+
called = true;
|
|
40
|
+
done?.(error);
|
|
41
|
+
};
|
|
42
|
+
const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
|
|
43
|
+
if (done && !called) {
|
|
44
|
+
if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
|
|
45
|
+
else if (stderr.write.length < 2) onComplete();
|
|
46
|
+
}
|
|
47
|
+
return result;
|
|
48
|
+
});
|
|
49
|
+
try {
|
|
50
|
+
return await run();
|
|
51
|
+
} finally {
|
|
52
|
+
process.stdout.write = write;
|
|
53
|
+
stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
|
|
54
|
+
release();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
|
|
59
|
+
* Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
|
|
60
|
+
* config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
|
|
61
|
+
* then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
|
|
62
|
+
*/
|
|
63
|
+
function createCliDiscoveryNitroCloser() {
|
|
64
|
+
const instances = [];
|
|
65
|
+
return {
|
|
66
|
+
close: async () => {
|
|
67
|
+
await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
|
|
68
|
+
},
|
|
69
|
+
plugin: {
|
|
70
|
+
name: "vite-hub/cli-discovery-nitro",
|
|
71
|
+
nitro: { setup: (nitro) => {
|
|
72
|
+
instances.push(nitro);
|
|
73
|
+
} }
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/** Returns the unredirected process stdout writer for payload output. */
|
|
78
|
+
function getStableStdoutWrite() {
|
|
79
|
+
const current = process.stdout.write;
|
|
80
|
+
if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
|
|
81
|
+
stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
|
|
82
|
+
stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
|
|
83
|
+
}
|
|
84
|
+
return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
10
87
|
//#region ../internal/src/build/vite.ts
|
|
11
88
|
const projectRootDirectoryMarkers = [
|
|
12
89
|
["server", "agents"],
|
|
@@ -115,83 +192,6 @@ function createViteHubEnvImportAliases(root) {
|
|
|
115
192
|
};
|
|
116
193
|
}
|
|
117
194
|
//#endregion
|
|
118
|
-
//#region ../internal/src/cli.ts
|
|
119
|
-
const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
|
|
120
|
-
const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
|
|
121
|
-
const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
|
|
122
|
-
const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
|
|
123
|
-
const stdoutRedirectGlobal = globalThis;
|
|
124
|
-
/**
|
|
125
|
-
* Sends `process.stdout` writes to stderr while `run` loads project config.
|
|
126
|
-
* Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
|
|
127
|
-
*/
|
|
128
|
-
async function withStdoutOnStderr(run, stderr = process.stderr) {
|
|
129
|
-
getStableStdoutWrite();
|
|
130
|
-
const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
|
|
131
|
-
let release;
|
|
132
|
-
stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
|
|
133
|
-
release = resolve;
|
|
134
|
-
});
|
|
135
|
-
await previous;
|
|
136
|
-
const write = process.stdout.write;
|
|
137
|
-
if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
|
|
138
|
-
stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
|
|
139
|
-
stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
|
|
140
|
-
}
|
|
141
|
-
stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
|
|
142
|
-
process.stdout.write = ((chunk, encoding, callback) => {
|
|
143
|
-
const done = typeof encoding === "function" ? encoding : callback;
|
|
144
|
-
let called = false;
|
|
145
|
-
const onComplete = (error) => {
|
|
146
|
-
if (called) return;
|
|
147
|
-
called = true;
|
|
148
|
-
done?.(error);
|
|
149
|
-
};
|
|
150
|
-
const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
|
|
151
|
-
if (done && !called) {
|
|
152
|
-
if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
|
|
153
|
-
else if (stderr.write.length < 2) onComplete();
|
|
154
|
-
}
|
|
155
|
-
return result;
|
|
156
|
-
});
|
|
157
|
-
try {
|
|
158
|
-
return await run();
|
|
159
|
-
} finally {
|
|
160
|
-
process.stdout.write = write;
|
|
161
|
-
stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
|
|
162
|
-
release();
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
|
|
167
|
-
* Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
|
|
168
|
-
* config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
|
|
169
|
-
* then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
|
|
170
|
-
*/
|
|
171
|
-
function createCliDiscoveryNitroCloser() {
|
|
172
|
-
const instances = [];
|
|
173
|
-
return {
|
|
174
|
-
close: async () => {
|
|
175
|
-
await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
|
|
176
|
-
},
|
|
177
|
-
plugin: {
|
|
178
|
-
name: "vite-hub/cli-discovery-nitro",
|
|
179
|
-
nitro: { setup: (nitro) => {
|
|
180
|
-
instances.push(nitro);
|
|
181
|
-
} }
|
|
182
|
-
}
|
|
183
|
-
};
|
|
184
|
-
}
|
|
185
|
-
/** Returns the unredirected process stdout writer for payload output. */
|
|
186
|
-
function getStableStdoutWrite() {
|
|
187
|
-
const current = process.stdout.write;
|
|
188
|
-
if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
|
|
189
|
-
stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
|
|
190
|
-
stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
|
|
191
|
-
}
|
|
192
|
-
return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
|
|
193
|
-
}
|
|
194
|
-
//#endregion
|
|
195
195
|
//#region ../internal/src/vite-stage.ts
|
|
196
196
|
/**
|
|
197
197
|
* Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as secretCliFeatures, t as createEnvCliContributor } from "./cli-
|
|
1
|
+
import { n as secretCliFeatures, t as createEnvCliContributor } from "./cli-C51D6V-M.js";
|
|
2
2
|
export { createEnvCliContributor, secretCliFeatures };
|
|
@@ -17,7 +17,7 @@ const envErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
17
17
|
ENV_R0006: withFix("Remove `required`: a value is required by default. Set `optional: true` for a value that can be missing, or a `default` for a fallback value, not both."),
|
|
18
18
|
ENV_R0008: withFix("Change the Env declaration at the path in the error details, as the message says."),
|
|
19
19
|
ENV_R0009: withFix("Load Server Env with `await loadServerEnv()`, or run the code in `runWithServerEnv()`. A provider value cannot be read without `await`."),
|
|
20
|
-
ENV_R0010: withFix("Give the variable a value at its source: set
|
|
20
|
+
ENV_R0010: withFix("Give the variable a value at its source: set a variable that the error names in `.env` or in the host environment, or return it from the provider or the custom source. Or set `optional: true` on the declaration, or a `default` if the variable is not secret. Run `vitehub env check` to list the missing variables."),
|
|
21
21
|
ENV_R0011: withFix("Change the value at its source, or the `default` of the declaration, so that it matches the type of the variable. The message names each issue. If the message names a provider, make its `read()` return a plain object with a value for each key, not a getter."),
|
|
22
22
|
ENV_R0012: withFix("Make package.json contain one JSON object."),
|
|
23
23
|
ENV_R0013: withFix("Pass an object with a `read({ env, keys, signal })` method to `defineEnvProvider()`."),
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { A as EnvRuntimeRegistry, B as PublicEnv, C as EnvMode, D as EnvProviderValues, E as EnvProviderContext, F as EnvTypedVariableOptions, G as ServerEnvInspection, H as ServerEnv, I as EnvValueSchema, K as ServerEnvInspectionEntry, L as EnvVariableDeclaration, M as EnvSource, N as EnvSourceContext, O as EnvProviders, P as EnvSourceResolver, Q as SecretEnv, R as EnvVariableOptions, S as EnvDiagnostics, T as EnvProvider, U as ServerEnvDescription, V as ReadonlyServerEnv, W as ServerEnvDescriptionEntry, b as EnvDeclarations, j as EnvSchemaModuleReference, k as EnvRuntimeConfigOptions, q as ServerEnvInspectionStatus, w as EnvOptions, x as EnvDiagnosticEntry, y as DeepReadonly, z as LoadServerEnvOptions } from "./bridge-Cs9YfQWk.js";
|
|
2
2
|
import { t as env } from "./declarations-C5XR3aKw.js";
|
|
3
|
-
import { C as parseSchema, S as StandardSchemaV1, _ as unseal, b as StandardSchemaResultFailure, d as SealOptions, f as UnsealErrorCode, g as seal, m as UnsealSchemaOptions, p as UnsealOptions, s as isBlockingServerEnvEntry, v as SealUsesDatabase, x as StandardSchemaResultSuccess, y as RequestEvent } from "./server-
|
|
3
|
+
import { C as parseSchema, S as StandardSchemaV1, _ as unseal, b as StandardSchemaResultFailure, d as SealOptions, f as UnsealErrorCode, g as seal, m as UnsealSchemaOptions, p as UnsealOptions, s as isBlockingServerEnvEntry, v as SealUsesDatabase, x as StandardSchemaResultSuccess, y as RequestEvent } from "./server-CgKAEAE6.js";
|
|
4
4
|
import { Result, ViteHubError } from "@vite-hub/runtime";
|
|
5
5
|
import { deriveSecret, describeServerEnv, inspectServerEnv, loadServerEnv, runWithServerEnv, useServerEnv } from "#vitehub/env/server";
|
|
6
6
|
import { usePublicEnv } from "#vitehub/env/public";
|
|
@@ -70,7 +70,7 @@ export declare function requireServiceToken(event: ServiceTokenEvent, name: stri
|
|
|
70
70
|
//#endregion
|
|
71
71
|
//#region src/webhook.d.ts
|
|
72
72
|
/** The codes that `verifyWebhook()` returns. */
|
|
73
|
-
type WebhookErrorCode = "ENV_WEBHOOK_BODY_INVALID" | "ENV_WEBHOOK_SECRET_UNSET" | "ENV_WEBHOOK_SIGNATURE_INVALID";
|
|
73
|
+
type WebhookErrorCode = "ENV_WEBHOOK_BODY_INVALID" | "ENV_WEBHOOK_SCHEMA_MISMATCH" | "ENV_WEBHOOK_SECRET_UNSET" | "ENV_WEBHOOK_SIGNATURE_INVALID";
|
|
74
74
|
/** How `verifyWebhook()` checks the signature. `secret` is the name of the server variable that holds the signing secret. */
|
|
75
75
|
type VerifyWebhookOptions = {
|
|
76
76
|
/** `Stripe-Signature: t=<time>,v1=<HMAC-SHA256 of "<time>.<body>">`. */
|
|
@@ -98,25 +98,34 @@ type VerifyWebhookOptions = {
|
|
|
98
98
|
/** How the variable encodes the key. `"base64"` decodes it first. Default: `"utf8"`. */
|
|
99
99
|
secretEncoding?: "utf8" | "base64";
|
|
100
100
|
};
|
|
101
|
+
/** `VerifyWebhookOptions` with a Standard Schema, such as a Valibot or Zod schema, that checks the body. */
|
|
102
|
+
type VerifyWebhookSchemaOptions<TBody> = VerifyWebhookOptions & {
|
|
103
|
+
/** Checks the parsed body. `verifyWebhook()` returns its output, or `ENV_WEBHOOK_SCHEMA_MISMATCH`. */
|
|
104
|
+
schema: StandardSchemaV1<TBody>;
|
|
105
|
+
};
|
|
101
106
|
/**
|
|
102
107
|
* Checks the signature of a webhook that Stripe, GitHub, or another provider sends to a route, and returns
|
|
103
108
|
* `[error, body]` with the parsed JSON body. For a GitHub delivery with the form content type, `body` is the JSON
|
|
104
|
-
* of its `payload` field.
|
|
109
|
+
* of its `payload` field. Pass `schema` to check the body and type it; without it, `body` is `unknown`.
|
|
110
|
+
* It reads the raw body once, so do not read the body before you call it.
|
|
105
111
|
* It reads the secret from the server variable `secret` on each request. The variable holds one secret, or a
|
|
106
112
|
* comma-separated list while you rotate. It compares in constant time and runs on every host.
|
|
107
113
|
*
|
|
108
114
|
* ```ts [server/api/stripe/webhook.post.ts]
|
|
109
115
|
* import { defineEventHandler, HTTPError } from "h3"
|
|
116
|
+
* import * as v from "valibot"
|
|
110
117
|
* import { verifyWebhook } from "vite-hub/env"
|
|
111
118
|
*
|
|
112
119
|
* export default defineEventHandler(async (event) => {
|
|
113
|
-
* const
|
|
120
|
+
* const schema = v.object({ type: v.string() })
|
|
121
|
+
* const [error, stripeEvent] = await verifyWebhook(event, { provider: "stripe", secret: "STRIPE_WEBHOOK_SECRET", schema })
|
|
114
122
|
* if (error) throw new HTTPError({ status: 400, message: error.message })
|
|
115
123
|
* return { received: stripeEvent.type }
|
|
116
124
|
* })
|
|
117
125
|
* ```
|
|
118
126
|
*/
|
|
119
|
-
export declare function verifyWebhook<TBody
|
|
127
|
+
export declare function verifyWebhook<TBody>(event: RequestEvent, options: VerifyWebhookSchemaOptions<TBody>): Promise<Result<TBody, WebhookErrorCode>>;
|
|
128
|
+
export declare function verifyWebhook(event: RequestEvent, options: VerifyWebhookOptions): Promise<Result<unknown, WebhookErrorCode>>;
|
|
120
129
|
/** How `signWebhook()` signs an outgoing body. */
|
|
121
130
|
interface SignWebhookOptions {
|
|
122
131
|
/** `"github"` sets `x-hub-signature-256`. `"stripe"` sets `stripe-signature` with the time. */
|
|
@@ -160,6 +169,7 @@ interface EnvErrorDetailsByCode {
|
|
|
160
169
|
path?: string;
|
|
161
170
|
};
|
|
162
171
|
ENV_REQUIRED_MISSING: {
|
|
172
|
+
names?: string[];
|
|
163
173
|
path?: string;
|
|
164
174
|
source?: EnvSourceIdentifier;
|
|
165
175
|
};
|
|
@@ -173,4 +183,4 @@ interface EnvErrorDetailsByCode {
|
|
|
173
183
|
}
|
|
174
184
|
type EnvErrorDetails<TCode extends EnvErrorCode = EnvErrorCode> = EnvErrorDetailsByCode[TCode];
|
|
175
185
|
//#endregion
|
|
176
|
-
export { type DeepReadonly, type EnvDeclarations, type EnvDiagnosticEntry, type EnvDiagnostics, type EnvErrorCode, type EnvErrorDetails, type EnvMode, type EnvOptions, type EnvProvider, type EnvProviderContext, type EnvProviderValues, type EnvProviders, type EnvRuntimeConfigOptions, type EnvRuntimeRegistry, type EnvSchemaModuleReference, type EnvSource, type EnvSourceContext, type EnvSourceIdentifier, type EnvSourceResolver, type EnvTypedVariableOptions, type EnvValueSchema, type EnvVariableDeclaration, type EnvVariableOptions, type LoadServerEnvOptions, type OpenWorkflowEnvOptions, type PublicEnv, type ReadonlyServerEnv, type SealOptions, type SealUsesDatabase, SecretEnv, type ServerEnv, type ServerEnvDescription, type ServerEnvDescriptionEntry, type ServerEnvInspection, type ServerEnvInspectionEntry, type ServerEnvInspectionStatus, type ServiceTokenErrorCode, type ServiceTokenEvent, type SignWebhookOptions, type StandardSchemaResultFailure, type StandardSchemaResultSuccess, type StandardSchemaV1, type TypesafeEnvOptions, type UnsealErrorCode, type UnsealOptions, type UnsealSchemaOptions, type VerifyWebhookOptions, type WebhookErrorCode, deriveSecret, describeServerEnv, env, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, parseSchema, runWithServerEnv, seal, unseal, usePublicEnv, useServerEnv };
|
|
186
|
+
export { type DeepReadonly, type EnvDeclarations, type EnvDiagnosticEntry, type EnvDiagnostics, type EnvErrorCode, type EnvErrorDetails, type EnvMode, type EnvOptions, type EnvProvider, type EnvProviderContext, type EnvProviderValues, type EnvProviders, type EnvRuntimeConfigOptions, type EnvRuntimeRegistry, type EnvSchemaModuleReference, type EnvSource, type EnvSourceContext, type EnvSourceIdentifier, type EnvSourceResolver, type EnvTypedVariableOptions, type EnvValueSchema, type EnvVariableDeclaration, type EnvVariableOptions, type LoadServerEnvOptions, type OpenWorkflowEnvOptions, type PublicEnv, type ReadonlyServerEnv, type SealOptions, type SealUsesDatabase, SecretEnv, type ServerEnv, type ServerEnvDescription, type ServerEnvDescriptionEntry, type ServerEnvInspection, type ServerEnvInspectionEntry, type ServerEnvInspectionStatus, type ServiceTokenErrorCode, type ServiceTokenEvent, type SignWebhookOptions, type StandardSchemaResultFailure, type StandardSchemaResultSuccess, type StandardSchemaV1, type TypesafeEnvOptions, type UnsealErrorCode, type UnsealOptions, type UnsealSchemaOptions, type VerifyWebhookOptions, type VerifyWebhookSchemaOptions, type WebhookErrorCode, deriveSecret, describeServerEnv, env, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, parseSchema, runWithServerEnv, seal, unseal, usePublicEnv, useServerEnv };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as envErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { r as env, t as parseSchema } from "./schema-
|
|
3
|
-
import { D as verifyViteHubHmacSignature, O as verifyViteHubStripeSignature, T as isViteHubBearerSecretEqual, _ as runtimeEnv, a as isBlockingServerEnvEntry, d as unseal, k as viteHubHmacSha256, u as seal, v as standardSource, w as githubHmacSignatureFormat } from "./server-
|
|
1
|
+
import { t as envErrorDiagnostics } from "./error-diagnostics-DsDPsST_.js";
|
|
2
|
+
import { r as env, t as parseSchema } from "./schema-C_a0WZyd.js";
|
|
3
|
+
import { D as verifyViteHubHmacSignature, O as verifyViteHubStripeSignature, T as isViteHubBearerSecretEqual, _ as runtimeEnv, a as isBlockingServerEnvEntry, d as unseal, k as viteHubHmacSha256, u as seal, v as standardSource, w as githubHmacSignatureFormat } from "./server-B9-8r6MZ.js";
|
|
4
4
|
import { t as SecretEnv } from "./secret-DJd-fy5T.js";
|
|
5
5
|
import { defineErrors } from "@vite-hub/runtime";
|
|
6
6
|
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
@@ -136,6 +136,11 @@ const webhookErrors = /*#__PURE__*/ defineErrors({
|
|
|
136
136
|
why: "The webhook has a valid signature, but its body is not JSON, or a GitHub form delivery has no JSON `payload` field.",
|
|
137
137
|
fix: "Set the provider to send JSON. GitHub can send `application/json` or `application/x-www-form-urlencoded`, and `verifyWebhook()` reads both."
|
|
138
138
|
},
|
|
139
|
+
ENV_WEBHOOK_SCHEMA_MISMATCH: {
|
|
140
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_webhook_schema_mismatch",
|
|
141
|
+
why: "The webhook has a valid signature and a JSON body, but the body does not match `schema`.",
|
|
142
|
+
fix: "Read `error.cause` for the schema issues. Check that the provider sends the event that the route expects, and change `schema` when the provider changed the shape of its events."
|
|
143
|
+
},
|
|
139
144
|
ENV_WEBHOOK_SECRET_UNSET: {
|
|
140
145
|
docs: "https://vitehub.dev/docs/env/diagnostics/env_webhook_secret_unset",
|
|
141
146
|
why: ({ name }) => `\`${name}\` has no webhook secret on this server, so every delivery is refused.`,
|
|
@@ -165,24 +170,6 @@ function webhookJson(options, headers, text) {
|
|
|
165
170
|
if (options.provider !== "github" || !headers.get("content-type")?.toLowerCase().startsWith("application/x-www-form-urlencoded")) return text;
|
|
166
171
|
return new URLSearchParams(text).get("payload");
|
|
167
172
|
}
|
|
168
|
-
/**
|
|
169
|
-
* Checks the signature of a webhook that Stripe, GitHub, or another provider sends to a route, and returns
|
|
170
|
-
* `[error, body]` with the parsed JSON body. For a GitHub delivery with the form content type, `body` is the JSON
|
|
171
|
-
* of its `payload` field. It reads the raw body once, so do not read the body before you call it.
|
|
172
|
-
* It reads the secret from the server variable `secret` on each request. The variable holds one secret, or a
|
|
173
|
-
* comma-separated list while you rotate. It compares in constant time and runs on every host.
|
|
174
|
-
*
|
|
175
|
-
* ```ts [server/api/stripe/webhook.post.ts]
|
|
176
|
-
* import { defineEventHandler, HTTPError } from "h3"
|
|
177
|
-
* import { verifyWebhook } from "vite-hub/env"
|
|
178
|
-
*
|
|
179
|
-
* export default defineEventHandler(async (event) => {
|
|
180
|
-
* const [error, stripeEvent] = await verifyWebhook<{ type: string }>(event, { provider: "stripe", secret: "STRIPE_WEBHOOK_SECRET" })
|
|
181
|
-
* if (error) throw new HTTPError({ status: 400, message: error.message })
|
|
182
|
-
* return { received: stripeEvent.type }
|
|
183
|
-
* })
|
|
184
|
-
* ```
|
|
185
|
-
*/
|
|
186
173
|
async function verifyWebhook(event, options) {
|
|
187
174
|
const source = standardSource(event);
|
|
188
175
|
const name = options.secret;
|
|
@@ -204,11 +191,16 @@ async function verifyWebhook(event, options) {
|
|
|
204
191
|
}), void 0];
|
|
205
192
|
const json = webhookJson(options, request.headers, new TextDecoder().decode(body));
|
|
206
193
|
if (json === null) return [webhookErrors.ENV_WEBHOOK_BODY_INVALID(), void 0];
|
|
194
|
+
let parsed;
|
|
207
195
|
try {
|
|
208
|
-
|
|
196
|
+
parsed = JSON.parse(json);
|
|
209
197
|
} catch (cause) {
|
|
210
198
|
return [webhookErrors.ENV_WEBHOOK_BODY_INVALID({ cause }), void 0];
|
|
211
199
|
}
|
|
200
|
+
if (!options.schema) return [void 0, parsed];
|
|
201
|
+
const result = await options.schema["~standard"].validate(parsed);
|
|
202
|
+
if (result.issues) return [webhookErrors.ENV_WEBHOOK_SCHEMA_MISMATCH({ cause: result.issues }), void 0];
|
|
203
|
+
return [void 0, result.value];
|
|
212
204
|
}
|
|
213
205
|
function toHex(bytes) {
|
|
214
206
|
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { G as ServerEnvInspection, K as ServerEnvInspectionEntry, q as ServerEnvInspectionStatus, t as EnvAccessContext } from "../bridge-Cs9YfQWk.js";
|
|
2
|
-
import { _ as unseal, a as describeServerEnv, c as loadServerEnv, d as SealOptions, f as UnsealErrorCode, g as seal, h as createSealing, i as deriveSecret, l as resolveServerEnv, m as UnsealSchemaOptions, n as ViteHubContext, o as inspectServerEnv, p as UnsealOptions, r as bindServerEnvSchemas, s as isBlockingServerEnvEntry, t as DeriveSecretOptions, u as runWithCloudflareEnv } from "../server-
|
|
2
|
+
import { _ as unseal, a as describeServerEnv, c as loadServerEnv, d as SealOptions, f as UnsealErrorCode, g as seal, h as createSealing, i as deriveSecret, l as resolveServerEnv, m as UnsealSchemaOptions, n as ViteHubContext, o as inspectServerEnv, p as UnsealOptions, r as bindServerEnvSchemas, s as isBlockingServerEnvEntry, t as DeriveSecretOptions, u as runWithCloudflareEnv } from "../server-CgKAEAE6.js";
|
|
3
3
|
export { DeriveSecretOptions, type EnvAccessContext, type SealOptions, type ServerEnvInspection, type ServerEnvInspectionEntry, type ServerEnvInspectionStatus, type UnsealErrorCode, type UnsealOptions, type UnsealSchemaOptions, type ViteHubContext, bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
|
package/dist/internal/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as isBlockingServerEnvEntry, c as runWithCloudflareEnv, d as unseal, i as inspectServerEnv, l as createSealing, n as deriveSecret, o as loadServerEnv, r as describeServerEnv, s as resolveServerEnv, t as bindServerEnvSchemas, u as seal } from "../server-
|
|
1
|
+
import { a as isBlockingServerEnvEntry, c as runWithCloudflareEnv, d as unseal, i as inspectServerEnv, l as createSealing, n as deriveSecret, o as loadServerEnv, r as describeServerEnv, s as resolveServerEnv, t as bindServerEnvSchemas, u as seal } from "../server-B9-8r6MZ.js";
|
|
2
2
|
export { bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
|
|
@@ -170,7 +170,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
170
170
|
},
|
|
171
171
|
INTERNAL_R0004: {
|
|
172
172
|
...dynamicError,
|
|
173
|
-
fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `
|
|
173
|
+
fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `url()` Source options, or ask the server for a smaller response."
|
|
174
174
|
},
|
|
175
175
|
INTERNAL_R0005: {
|
|
176
176
|
...dynamicError,
|
|
@@ -216,6 +216,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
216
216
|
why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
|
|
217
217
|
fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
|
|
218
218
|
},
|
|
219
|
+
INTERNAL_DEV_SERVER_NOT_FOUND: {
|
|
220
|
+
why: ({ command }) => `[vitehub] No dev server of this project is running, and --url is not set, so \`vitehub ${command}\` has no app to call.`,
|
|
221
|
+
fix: "Start the dev server of this project, such as with `pnpm dev`, or pass --url with the app URL, such as --url http://localhost:3000."
|
|
222
|
+
},
|
|
219
223
|
INTERNAL_FORGE_NOT_INSTALLED: {
|
|
220
224
|
why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
|
|
221
225
|
fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
|
|
@@ -115,6 +115,11 @@ interface OperationContext {
|
|
|
115
115
|
surface: "console" | "cli" | "mcp" | "agent";
|
|
116
116
|
/** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
|
|
117
117
|
development?: boolean;
|
|
118
|
+
/**
|
|
119
|
+
* The project root of a development server, for operations that read build files, such as `bundle.report`. Hosts set
|
|
120
|
+
* it only with `development`, so a deployed server never reads project files through it.
|
|
121
|
+
*/
|
|
122
|
+
projectRoot?: string;
|
|
118
123
|
env?: Record<string, unknown>;
|
|
119
124
|
waitUntil?: (task: Promise<unknown>) => void;
|
|
120
125
|
request?: Request;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as isBlockingServerEnvEntry, c as runWithCloudflareEnv } from "./server-
|
|
1
|
+
import { a as isBlockingServerEnvEntry, c as runWithCloudflareEnv } from "./server-B9-8r6MZ.js";
|
|
2
2
|
import { detectHost } from "@vite-hub/runtime";
|
|
3
3
|
import { inspectServerEnv } from "#vitehub/env/server";
|
|
4
4
|
//#region src/runtime/operations.ts
|
package/dist/operations.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { K as ServerEnvInspectionEntry, q as ServerEnvInspectionStatus } from "./bridge-Cs9YfQWk.js";
|
|
2
|
-
import { t as AnyOperation } from "./operation-definition-
|
|
2
|
+
import { t as AnyOperation } from "./operation-definition-nmRu_O3V.js";
|
|
3
3
|
import { ViteHubHost } from "@vite-hub/runtime";
|
|
4
4
|
//#region src/runtime/operations.d.ts
|
|
5
5
|
/** One Server Env declaration as the running app sees it. It never holds a value, a preview, or a length. */
|
package/dist/operations.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as isRecordOrFunction, r as internalErrorDiagnostics } from "./object-
|
|
1
|
+
import { n as isRecordOrFunction, r as internalErrorDiagnostics } from "./object-C7Jt4ez2.js";
|
|
2
2
|
import * as v from "valibot";
|
|
3
3
|
//#region ../internal/src/standard-schema.ts
|
|
4
4
|
function readOwn(value, key) {
|
|
@@ -817,7 +817,7 @@ function operationInputJsonSchema(operation) {
|
|
|
817
817
|
}
|
|
818
818
|
//#endregion
|
|
819
819
|
//#region src/operations.ts
|
|
820
|
-
const runtime = () => import("./operations-
|
|
820
|
+
const runtime = () => import("./operations-B1PFpKzy.js");
|
|
821
821
|
/** The `env.*` operations. The Console, the CLI, and agents run them on the signed `POST /_vitehub/rpc` endpoint. */
|
|
822
822
|
const envOperations = [defineOperation({
|
|
823
823
|
cli: { command: "status" },
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as envErrorDiagnostics } from "../error-diagnostics-
|
|
1
|
+
import { t as envErrorDiagnostics } from "../error-diagnostics-DsDPsST_.js";
|
|
2
2
|
//#region src/runtime/public-env.ts
|
|
3
3
|
/** Reads the declared Public Env. Its values are fixed when the app builds. */
|
|
4
4
|
function usePublicEnv() {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as envErrorDiagnostics } from "../error-diagnostics-
|
|
1
|
+
import { t as envErrorDiagnostics } from "../error-diagnostics-DsDPsST_.js";
|
|
2
2
|
//#region src/runtime/server-env.ts
|
|
3
3
|
function notGenerated(accessor) {
|
|
4
4
|
throw envErrorDiagnostics.ENV_NOT_GENERATED({ accessor });
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as envErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { A as envValueTypeName, F as stringValueSchema, M as parseEnvValue, N as readJsonInput, j as listItemKinds } from "./server-
|
|
1
|
+
import { t as envErrorDiagnostics } from "./error-diagnostics-DsDPsST_.js";
|
|
2
|
+
import { A as envValueTypeName, F as stringValueSchema, M as parseEnvValue, N as readJsonInput, j as listItemKinds } from "./server-B9-8r6MZ.js";
|
|
3
3
|
//#region src/internal/runtime-type.ts
|
|
4
4
|
function isRuntimeRecord(value) {
|
|
5
5
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { t as envErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as envErrorDiagnostics } from "./error-diagnostics-DsDPsST_.js";
|
|
2
2
|
import { t as SecretEnv } from "./secret-DJd-fy5T.js";
|
|
3
|
-
import { r as internalErrorDiagnostics, t as isRecord } from "./object-
|
|
3
|
+
import { r as internalErrorDiagnostics, t as isRecord } from "./object-C7Jt4ez2.js";
|
|
4
4
|
import { defineDiagnostics } from "nostics";
|
|
5
5
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
|
-
import { ViteHubError, defineErrors, isViteHubError } from "@vite-hub/runtime";
|
|
6
|
+
import { ViteHubError, defineErrors, isViteHubError, parseDuration } from "@vite-hub/runtime";
|
|
7
7
|
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
8
8
|
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
9
9
|
import * as v from "valibot";
|
|
@@ -354,9 +354,9 @@ const envSourceIdentifierSet = /* @__PURE__ */ new Set([
|
|
|
354
354
|
"package.json",
|
|
355
355
|
"provider"
|
|
356
356
|
]);
|
|
357
|
-
function createEnvError(options) {
|
|
357
|
+
function createEnvError(options, message = envErrorMessages[options.code]) {
|
|
358
358
|
const { code, cause, details } = options;
|
|
359
|
-
return new ViteHubError(code,
|
|
359
|
+
return new ViteHubError(code, message, {
|
|
360
360
|
...cause === void 0 ? {} : { cause },
|
|
361
361
|
...details === void 0 || Object.keys(details).length === 0 ? {} : { details }
|
|
362
362
|
});
|
|
@@ -378,16 +378,27 @@ function asyncServerEnvRequired(path) {
|
|
|
378
378
|
details: optionalPath(path)
|
|
379
379
|
});
|
|
380
380
|
}
|
|
381
|
-
|
|
381
|
+
/**
|
|
382
|
+
* The message and details name the declaration path and the variables that can supply it, so the operator
|
|
383
|
+
* knows what to set. Names are not secret; the value never appears because there is none.
|
|
384
|
+
*/
|
|
385
|
+
function missingRequiredEnv(source, diagnostic, path, names = []) {
|
|
382
386
|
const pathDetails = optionalPath(path);
|
|
387
|
+
const variables = names.filter(isEnvVariableName).slice(0, 8);
|
|
388
|
+
const subject = pathDetails.path ? `Required Env value ${pathDetails.path} is missing.` : "Required Env value is missing.";
|
|
389
|
+
const supply = variables.length ? ` Set ${variables.join(" or ")}.` : "";
|
|
383
390
|
return createEnvError({
|
|
384
391
|
cause: envErrorDiagnostics.ENV_R0010({ message: diagnostic }),
|
|
385
392
|
code: "ENV_REQUIRED_MISSING",
|
|
386
393
|
details: {
|
|
394
|
+
...variables.length ? { names: variables } : {},
|
|
387
395
|
...pathDetails,
|
|
388
396
|
source: publicSourceIdentifier(source)
|
|
389
397
|
}
|
|
390
|
-
});
|
|
398
|
+
}, `[vitehub] ${subject}${supply}`);
|
|
399
|
+
}
|
|
400
|
+
function isEnvVariableName(name) {
|
|
401
|
+
return /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(name);
|
|
391
402
|
}
|
|
392
403
|
function invalidRuntimeEnvValue(source, diagnostic, path) {
|
|
393
404
|
return createEnvError({
|
|
@@ -596,7 +607,7 @@ const sealErrors = /*#__PURE__*/ defineErrors({
|
|
|
596
607
|
ENV_SEAL_ARGUMENT_INVALID: {
|
|
597
608
|
docs: "https://vitehub.dev/docs/env/diagnostics/env_seal_argument_invalid",
|
|
598
609
|
why: ({ problem }) => problem,
|
|
599
|
-
fix: "Pass a purpose such as \"my-app:upload\", a JSON value, a `ttl` in seconds, `uses` as a positive integer with a `db`, and a `secret` of at least 32 characters, or a non-empty list of such secrets."
|
|
610
|
+
fix: "Pass a purpose such as \"my-app:upload\", a JSON value, a `ttl` in seconds or as a duration such as \"15m\", `uses` as a positive integer with a `db`, and a `secret` of at least 32 characters, or a non-empty list of such secrets."
|
|
600
611
|
}
|
|
601
612
|
}
|
|
602
613
|
});
|
|
@@ -686,8 +697,8 @@ function createSealing(derive) {
|
|
|
686
697
|
return {
|
|
687
698
|
async seal(purpose, value, options = {}) {
|
|
688
699
|
checkPurpose(purpose);
|
|
689
|
-
const
|
|
690
|
-
if (ttl !== void 0 && (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0)) argumentError("`ttl` must be a positive number of seconds.");
|
|
700
|
+
const ttl = typeof options.ttl === "string" ? parseDuration(options.ttl) / 1e3 : options.ttl;
|
|
701
|
+
if (ttl !== void 0 && (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0)) argumentError("`ttl` must be a positive number of seconds or a duration such as \"15m\".");
|
|
691
702
|
const { uses, db } = options;
|
|
692
703
|
if (uses !== void 0 && (typeof uses !== "number" || !Number.isSafeInteger(uses) || uses < 1)) argumentError("`uses` must be a positive integer.");
|
|
693
704
|
const usesDb = uses === void 0 ? void 0 : usesDatabase(db, "`uses` needs a `db`, such as `db` from `vite-hub/database`, that every instance of the app shares.");
|
|
@@ -771,7 +782,7 @@ const sealing = createSealing((purpose, event, root) => deriveSecret(purpose, {
|
|
|
771
782
|
* Throws `ENV_REQUIRED_MISSING` when no root secret is set, and `ENV_SEAL_ARGUMENT_INVALID` for a bad argument.
|
|
772
783
|
*
|
|
773
784
|
* @example
|
|
774
|
-
* const ticket = await seal("my-app:upload", { userId }, { ttl:
|
|
785
|
+
* const ticket = await seal("my-app:upload", { userId }, { ttl: "15m" })
|
|
775
786
|
*/
|
|
776
787
|
function seal(purpose, value, options) {
|
|
777
788
|
return sealing.seal(purpose, value, options);
|
|
@@ -799,7 +810,7 @@ let warnedGeneratedSecret = false;
|
|
|
799
810
|
async function deriveSecret(purpose, options = {}, development = {}) {
|
|
800
811
|
const env = runtimeEnv(options.event);
|
|
801
812
|
const root = options.root ?? readViteHubSecret(env) ?? (development.envKey ? env[development.envKey] : void 0);
|
|
802
|
-
if (!root) throw missingRequiredEnv("env", "deriveSecret() requires VITEHUB_SECRET. Generate one with `openssl rand -base64 32`.", "VITEHUB_SECRET");
|
|
813
|
+
if (!root) throw missingRequiredEnv("env", "deriveSecret() requires VITEHUB_SECRET. Generate one with `openssl rand -base64 32`.", void 0, ["VITEHUB_SECRET"]);
|
|
803
814
|
if (root.length < 32) throw invalidRuntimeEnvValue("env", `VITEHUB_SECRET must be at least 32 characters. Generate one with \`openssl rand -base64 32\`.`, "VITEHUB_SECRET");
|
|
804
815
|
if ((development.generated || env.VITEHUB_SECRET_GENERATED === "1") && !warnedGeneratedSecret) {
|
|
805
816
|
warnedGeneratedSecret = true;
|
|
@@ -907,7 +918,7 @@ function formatSchemaIssues(issues) {
|
|
|
907
918
|
function resolvedRuntimeValue(entry, value, found, path, snapshot = false) {
|
|
908
919
|
const resolved = found ? value : entry.default;
|
|
909
920
|
if (typeof resolved === "undefined") {
|
|
910
|
-
if (entry.required) throw missingRequiredEnv(entry.source.kind, missingRuntimeValueMessage(entry, path), path);
|
|
921
|
+
if (entry.required) throw missingRequiredEnv(entry.source.kind, missingRuntimeValueMessage(entry, path), path, entry.source.kind === "env" ? entry.source.names || [entry.source.name] : []);
|
|
911
922
|
return;
|
|
912
923
|
}
|
|
913
924
|
const parsed = parseRuntimeValue(entry, resolved, path);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { A as EnvRuntimeRegistry, G as ServerEnvInspection, K as ServerEnvInspectionEntry, Q as SecretEnv, U as ServerEnvDescription, y as DeepReadonly, z as LoadServerEnvOptions } from "./bridge-Cs9YfQWk.js";
|
|
2
|
-
import { Result, ViteHubContext, ViteHubContext as ViteHubContext$1 } from "@vite-hub/runtime";
|
|
2
|
+
import { Duration, Result, ViteHubContext, ViteHubContext as ViteHubContext$1 } from "@vite-hub/runtime";
|
|
3
3
|
//#region src/schema.d.ts
|
|
4
4
|
interface StandardSchemaResultSuccess<T = unknown> {
|
|
5
5
|
issues?: undefined;
|
|
@@ -58,8 +58,11 @@ interface UnsealSchemaOptions<T> extends UnsealOptions {
|
|
|
58
58
|
schema: StandardSchemaV1<T>;
|
|
59
59
|
}
|
|
60
60
|
interface SealOptions extends UnsealOptions {
|
|
61
|
-
/**
|
|
62
|
-
|
|
61
|
+
/**
|
|
62
|
+
* How long until `unseal()` returns `ENV_SEAL_EXPIRED`: a number of seconds, or a duration such as `"15m"`. Without
|
|
63
|
+
* it, the value does not expire.
|
|
64
|
+
*/
|
|
65
|
+
ttl?: number | Duration;
|
|
63
66
|
/**
|
|
64
67
|
* How many times `unseal()` can read the value. Each read takes one use atomically in `db`, so of two reads of the last
|
|
65
68
|
* use, one gets the value and the other gets `ENV_SEAL_USED_UP`. Without it, the value opens any number of times.
|
|
@@ -83,7 +86,7 @@ declare function createSealing(derive: SealSecretDerivation): Sealing;
|
|
|
83
86
|
* Throws `ENV_REQUIRED_MISSING` when no root secret is set, and `ENV_SEAL_ARGUMENT_INVALID` for a bad argument.
|
|
84
87
|
*
|
|
85
88
|
* @example
|
|
86
|
-
* const ticket = await seal("my-app:upload", { userId }, { ttl:
|
|
89
|
+
* const ticket = await seal("my-app:upload", { userId }, { ttl: "15m" })
|
|
87
90
|
*/
|
|
88
91
|
declare function seal(purpose: string, value: unknown, options?: SealOptions): Promise<string>;
|
|
89
92
|
/**
|
package/dist/server.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { G as ServerEnvInspection, K as ServerEnvInspectionEntry, q as ServerEnvInspectionStatus, t as EnvAccessContext } from "./bridge-Cs9YfQWk.js";
|
|
2
|
-
import { _ as unseal, a as describeServerEnv, c as loadServerEnv, d as SealOptions, f as UnsealErrorCode, g as seal, h as createSealing, i as deriveSecret, l as resolveServerEnv, m as UnsealSchemaOptions, n as ViteHubContext, o as inspectServerEnv, p as UnsealOptions, r as bindServerEnvSchemas, s as isBlockingServerEnvEntry, t as DeriveSecretOptions, u as runWithCloudflareEnv } from "./server-
|
|
2
|
+
import { _ as unseal, a as describeServerEnv, c as loadServerEnv, d as SealOptions, f as UnsealErrorCode, g as seal, h as createSealing, i as deriveSecret, l as resolveServerEnv, m as UnsealSchemaOptions, n as ViteHubContext, o as inspectServerEnv, p as UnsealOptions, r as bindServerEnvSchemas, s as isBlockingServerEnvEntry, t as DeriveSecretOptions, u as runWithCloudflareEnv } from "./server-CgKAEAE6.js";
|
|
3
3
|
export { DeriveSecretOptions, type EnvAccessContext, type SealOptions, type ServerEnvInspection, type ServerEnvInspectionEntry, type ServerEnvInspectionStatus, type UnsealErrorCode, type UnsealOptions, type UnsealSchemaOptions, type ViteHubContext, bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as isBlockingServerEnvEntry, c as runWithCloudflareEnv, d as unseal, i as inspectServerEnv, l as createSealing, n as deriveSecret, o as loadServerEnv, r as describeServerEnv, s as resolveServerEnv, t as bindServerEnvSchemas, u as seal } from "./server-
|
|
1
|
+
import { a as isBlockingServerEnvEntry, c as runWithCloudflareEnv, d as unseal, i as inspectServerEnv, l as createSealing, n as deriveSecret, o as loadServerEnv, r as describeServerEnv, s as resolveServerEnv, t as bindServerEnvSchemas, u as seal } from "./server-B9-8r6MZ.js";
|
|
2
2
|
export { bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { A as EnvRuntimeRegistry, b as EnvDeclarations, k as EnvRuntimeConfigOptions, w as EnvOptions } from "./bridge-Cs9YfQWk.js";
|
|
2
2
|
import { n as ViteHubCliContributor } from "./cli-BPp7rdcA.js";
|
|
3
3
|
import { t as env } from "./declarations-C5XR3aKw.js";
|
|
4
|
-
import { n as OperationContributionEntry } from "./operation-definition-
|
|
4
|
+
import { n as OperationContributionEntry } from "./operation-definition-nmRu_O3V.js";
|
|
5
5
|
import { Plugin, UserConfig } from "vite";
|
|
6
6
|
//#region ../internal/src/deployment.d.ts
|
|
7
7
|
/** The host that ViteHub builds for: the `host` option of `vitehub()` and the value of `VITEHUB_HOST`. */
|
package/dist/vite.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { t as envErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { a as schemaModuleReference, i as runtimeValueSchema, n as descriptorVariable, r as env, t as parseSchema } from "./schema-
|
|
3
|
-
import { A as envValueTypeName, E as readViteHubSecret, F as stringValueSchema, I as isEnvSchemaValue, M as parseEnvValue, P as schemaContainsEnum, S as missingRequiredEnv, b as invalidEnvDeclaration, f as invariant, g as runtimeRegistryEntries, h as isRuntimeProviderEntry, m as isRuntimeLiteralEntry, p as isRuntimeEnvEntry, r as describeServerEnv, x as isAbortError, y as envSourceFailed } from "./server-
|
|
4
|
-
import { a as VITEHUB_ENV_SERVER, c as createViteHubEnvImportAliases, d as viteHubEnvAmbientTypesPath, f as viteHubEnvDescriptionModulePath, g as viteHubEnvServerModuleTypesPath, h as viteHubEnvServerModulePath, i as VITEHUB_ENV_PUBLIC_ID, l as isServerEnvironment, m as viteHubEnvPublicModuleTypesPath, o as VITEHUB_ENV_SERVER_ID, p as viteHubEnvPublicModulePath, r as loadAllEnv, s as createNoExternalAddition, t as createEnvCliContributor, u as resolveViteHubProjectRoot } from "./cli-
|
|
1
|
+
import { t as envErrorDiagnostics } from "./error-diagnostics-DsDPsST_.js";
|
|
2
|
+
import { a as schemaModuleReference, i as runtimeValueSchema, n as descriptorVariable, r as env, t as parseSchema } from "./schema-C_a0WZyd.js";
|
|
3
|
+
import { A as envValueTypeName, E as readViteHubSecret, F as stringValueSchema, I as isEnvSchemaValue, M as parseEnvValue, P as schemaContainsEnum, S as missingRequiredEnv, b as invalidEnvDeclaration, f as invariant, g as runtimeRegistryEntries, h as isRuntimeProviderEntry, m as isRuntimeLiteralEntry, p as isRuntimeEnvEntry, r as describeServerEnv, x as isAbortError, y as envSourceFailed } from "./server-B9-8r6MZ.js";
|
|
4
|
+
import { a as VITEHUB_ENV_SERVER, c as createViteHubEnvImportAliases, d as viteHubEnvAmbientTypesPath, f as viteHubEnvDescriptionModulePath, g as viteHubEnvServerModuleTypesPath, h as viteHubEnvServerModulePath, i as VITEHUB_ENV_PUBLIC_ID, l as isServerEnvironment, m as viteHubEnvPublicModuleTypesPath, o as VITEHUB_ENV_SERVER_ID, p as viteHubEnvPublicModulePath, r as loadAllEnv, s as createNoExternalAddition, t as createEnvCliContributor, u as resolveViteHubProjectRoot } from "./cli-C51D6V-M.js";
|
|
5
5
|
import { Diagnostic } from "nostics";
|
|
6
6
|
import { isViteHubError } from "@vite-hub/runtime";
|
|
7
7
|
import { existsSync, readFileSync } from "node:fs";
|
|
@@ -372,7 +372,7 @@ async function resolveBuildDeclaration(declaration, path, input, canonical = tru
|
|
|
372
372
|
const defaulted = typeof resolvedSource.value === "undefined";
|
|
373
373
|
const valueForSchema = defaulted ? defaultValue : resolvedSource.value;
|
|
374
374
|
if (typeof valueForSchema === "undefined") {
|
|
375
|
-
if (declaration.required) throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
|
|
375
|
+
if (declaration.required) throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path, source.kind === "env" ? source.names || [source.name] : []);
|
|
376
376
|
return {
|
|
377
377
|
source: resolvedSource.label,
|
|
378
378
|
status: "missing",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vite-hub/env",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Safe build and runtime environment variables for ViteHub.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"env",
|
|
@@ -97,7 +97,7 @@
|
|
|
97
97
|
},
|
|
98
98
|
"dependencies": {
|
|
99
99
|
"@env-spec/parser": "0.6.2",
|
|
100
|
-
"@vite-hub/runtime": "0.
|
|
100
|
+
"@vite-hub/runtime": "0.4.1",
|
|
101
101
|
"nostics": "1.4.0",
|
|
102
102
|
"valibot": "^1.5.0"
|
|
103
103
|
},
|
|
@@ -118,7 +118,7 @@
|
|
|
118
118
|
"peerDependencies": {
|
|
119
119
|
"vite": ">=8.0.0",
|
|
120
120
|
"drizzle-orm": "1.0.0-rc.5 || ^1.0.0",
|
|
121
|
-
"@vite-hub/agent": "0.
|
|
121
|
+
"@vite-hub/agent": "0.4.1",
|
|
122
122
|
"nitro": "3.0.261102-rc || ^3.0.261103-rc"
|
|
123
123
|
},
|
|
124
124
|
"peerDependenciesMeta": {
|
|
@@ -133,7 +133,7 @@
|
|
|
133
133
|
}
|
|
134
134
|
},
|
|
135
135
|
"engines": {
|
|
136
|
-
"node": ">=
|
|
136
|
+
"node": ">=24.15.0"
|
|
137
137
|
},
|
|
138
138
|
"scripts": {
|
|
139
139
|
"build": "vp pack",
|