@vite-hub/env 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +178 -33
- package/dist/{access-B3qzBHye.js → access-B8lSDip4.js} +1 -1
- package/dist/{bridge-CdNdTN1V.d.ts → bridge-Cs9YfQWk.d.ts} +111 -38
- package/dist/{bridge-error-CFuU5zIz.js → bridge-error-BhJ77age.js} +14 -13
- package/dist/bridge.d.ts +2 -2
- package/dist/bridge.js +168 -6
- package/dist/cli-BPp7rdcA.d.ts +159 -0
- package/dist/{cli-CMQPQbii.js → cli-DLpY0QAo.js} +212 -30
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +1 -1
- package/dist/database.d.ts +29 -3
- package/dist/database.js +106 -15
- package/dist/declarations-C5XR3aKw.d.ts +58 -0
- package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
- package/dist/index.d.ts +145 -10
- package/dist/index.js +240 -7
- package/dist/internal/agent.d.ts +1 -1
- package/dist/internal/agent.js +2 -2
- package/dist/internal/connections.d.ts +1 -1
- package/dist/internal/connections.js +2 -2
- package/dist/internal/server.d.ts +3 -0
- package/dist/internal/server.js +2 -0
- package/dist/object-_dlsZ4lP.js +276 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-X1w--wds.js +30 -0
- package/dist/operations.d.ts +37 -0
- package/dist/operations.js +833 -0
- package/dist/runtime/public-env.d.ts +5 -0
- package/dist/runtime/public-env.js +8 -0
- package/dist/runtime/server-env.d.ts +22 -0
- package/dist/runtime/server-env.js +35 -0
- package/dist/schema-DMZ1_yhY.js +360 -0
- package/dist/seal.d.ts +8 -5
- package/dist/seal.js +9 -6
- package/dist/{secret.js → secret-DJd-fy5T.js} +1 -1
- package/dist/server-ChNL_Xc3.js +1279 -0
- package/dist/server-Dd8bjIKd.d.ts +145 -0
- package/dist/server.d.ts +3 -25
- package/dist/server.js +2 -2
- package/dist/virtual-module.d.ts +6 -6
- package/dist/vite.d.ts +59 -14
- package/dist/vite.js +304 -115
- package/package.json +27 -38
- package/dist/auth.d.ts +0 -32
- package/dist/auth.js +0 -44
- package/dist/cli-DEwcUIe0.d.ts +0 -81
- package/dist/declarations-CiRdb1qP.d.ts +0 -32
- package/dist/declarations-DAVgctKD.js +0 -236
- package/dist/error-diagnostics-CrxjYNYr.js +0 -43
- package/dist/http.d.ts +0 -2
- package/dist/http.js +0 -122
- package/dist/presets.d.ts +0 -20
- package/dist/presets.js +0 -44
- package/dist/provider.d.ts +0 -5
- package/dist/provider.js +0 -8
- package/dist/schema.d.ts +0 -15
- package/dist/schema.js +0 -55
- package/dist/secret-C2191nAa.d.ts +0 -11
- package/dist/secret.d.ts +0 -2
- package/dist/server-DufVswRJ.js +0 -670
- package/dist/values-D_r6V774.js +0 -148
|
@@ -0,0 +1,1279 @@
|
|
|
1
|
+
import { t as envErrorDiagnostics } from "./error-diagnostics-B8RFjQ1V.js";
|
|
2
|
+
import { t as SecretEnv } from "./secret-DJd-fy5T.js";
|
|
3
|
+
import { r as internalErrorDiagnostics, t as isRecord } from "./object-_dlsZ4lP.js";
|
|
4
|
+
import { defineDiagnostics } from "nostics";
|
|
5
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
|
+
import { ViteHubError, defineErrors, isViteHubError } from "@vite-hub/runtime";
|
|
7
|
+
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
8
|
+
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
9
|
+
import * as v from "valibot";
|
|
10
|
+
//#region src/core/json-value.ts
|
|
11
|
+
/** JSON values accepted at the environment boundary, without prototype or internal keys. */
|
|
12
|
+
function isEnvSchemaValue(value, depth = 0) {
|
|
13
|
+
if (depth > 64) return false;
|
|
14
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
15
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
16
|
+
if (Array.isArray(value)) return value.every((item) => isEnvSchemaValue(item, depth + 1));
|
|
17
|
+
if (typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) return false;
|
|
18
|
+
return Object.entries(value).every(([key, item]) => ![
|
|
19
|
+
"__proto__",
|
|
20
|
+
"prototype",
|
|
21
|
+
"constructor",
|
|
22
|
+
"__envSchemaUnset"
|
|
23
|
+
].includes(key) && isEnvSchemaValue(item, depth + 1));
|
|
24
|
+
}
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/core/values.ts
|
|
27
|
+
const stringValueSchema = Object.freeze({ kind: "string" });
|
|
28
|
+
/** Parse one host, provider, or default value with a serializable Server Env value schema. */
|
|
29
|
+
function parseEnvValue(schema, input) {
|
|
30
|
+
switch (schema.kind) {
|
|
31
|
+
case "array":
|
|
32
|
+
case "object":
|
|
33
|
+
case "json": {
|
|
34
|
+
const json = readJsonInput(input);
|
|
35
|
+
if (!json.success) return json;
|
|
36
|
+
return isEnvSchemaValue(json.data) && (schema.kind === "json" || matchesJsonType(schema, json.data)) ? {
|
|
37
|
+
data: typeof input === "string" ? json.data : structuredClone(json.data),
|
|
38
|
+
success: true
|
|
39
|
+
} : {
|
|
40
|
+
success: false,
|
|
41
|
+
message: schema.kind === "json" ? "Expected a JSON value." : "JSON value does not match the declared type."
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
case "list": return parseList(schema.items ?? stringValueSchema, input);
|
|
45
|
+
case "string": return typeof input === "string" && (schema.minLength === void 0 || input.length >= schema.minLength) && (schema.maxLength === void 0 || input.length <= schema.maxLength) ? {
|
|
46
|
+
data: input,
|
|
47
|
+
success: true
|
|
48
|
+
} : {
|
|
49
|
+
message: schema.minLength === void 0 && schema.maxLength === void 0 ? "Expected a string." : "Expected a string within the declared length constraints.",
|
|
50
|
+
success: false
|
|
51
|
+
};
|
|
52
|
+
case "boolean": return parseBoolean(input);
|
|
53
|
+
case "number": return parseNumber(input, schema);
|
|
54
|
+
case "url": return parseUrl(input);
|
|
55
|
+
case "enum": return typeof input === "string" && schema.values.includes(input) ? {
|
|
56
|
+
data: input,
|
|
57
|
+
success: true
|
|
58
|
+
} : {
|
|
59
|
+
message: `Expected one of ${schema.values.map((value) => JSON.stringify(value)).join(", ")}.`,
|
|
60
|
+
success: false
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Return the TypeScript type that a value schema produces. */
|
|
65
|
+
function envValueTypeName(schema) {
|
|
66
|
+
switch (schema.kind) {
|
|
67
|
+
case "array": return `Array<${schema.items ? envValueTypeName(schema.items) : "unknown"}>`;
|
|
68
|
+
case "object": {
|
|
69
|
+
if (!schema.properties) return "Record<string, unknown>";
|
|
70
|
+
const properties = Object.entries(schema.properties);
|
|
71
|
+
return properties.length ? `{ ${properties.map(([key, property]) => `${JSON.stringify(key)}: ${envValueTypeName(property)}`).join("; ")} }` : "Record<string, never>";
|
|
72
|
+
}
|
|
73
|
+
case "list": return `Array<${envValueTypeName(schema.items ?? stringValueSchema)}>`;
|
|
74
|
+
case "json": return "unknown";
|
|
75
|
+
case "enum": return schema.values.map((value) => JSON.stringify(value)).join(" | ");
|
|
76
|
+
case "url": return "string";
|
|
77
|
+
default: return schema.kind;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Item kinds that `env.list()` accepts. Each one parses a single string. */
|
|
81
|
+
const listItemKinds = /* @__PURE__ */ new Set([
|
|
82
|
+
"boolean",
|
|
83
|
+
"enum",
|
|
84
|
+
"number",
|
|
85
|
+
"string",
|
|
86
|
+
"url"
|
|
87
|
+
]);
|
|
88
|
+
/** Read a string as JSON text. Other values, such as a default or a typed host binding, are already parsed. */
|
|
89
|
+
function readJsonInput(input) {
|
|
90
|
+
if (typeof input !== "string") return {
|
|
91
|
+
data: input,
|
|
92
|
+
success: true
|
|
93
|
+
};
|
|
94
|
+
try {
|
|
95
|
+
return {
|
|
96
|
+
data: JSON.parse(input),
|
|
97
|
+
success: true
|
|
98
|
+
};
|
|
99
|
+
} catch {
|
|
100
|
+
return {
|
|
101
|
+
success: false,
|
|
102
|
+
message: "Expected valid JSON."
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function parseList(item, input) {
|
|
107
|
+
const items = typeof input === "string" ? input.split(/[,\n]/).map((value) => value.trim()).filter(Boolean) : input;
|
|
108
|
+
if (!Array.isArray(items)) return {
|
|
109
|
+
message: "Expected a comma-separated list.",
|
|
110
|
+
success: false
|
|
111
|
+
};
|
|
112
|
+
const data = [];
|
|
113
|
+
for (const [index, value] of items.entries()) {
|
|
114
|
+
const result = parseEnvValue(item, value);
|
|
115
|
+
if (!result.success) return {
|
|
116
|
+
message: `Item ${index + 1}: ${result.message}`,
|
|
117
|
+
success: false
|
|
118
|
+
};
|
|
119
|
+
data.push(result.data);
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
data,
|
|
123
|
+
success: true
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function parseBoolean(input) {
|
|
127
|
+
if (typeof input === "boolean") return {
|
|
128
|
+
data: input,
|
|
129
|
+
success: true
|
|
130
|
+
};
|
|
131
|
+
const normalized = typeof input === "string" ? input.trim().toLowerCase() : void 0;
|
|
132
|
+
if (normalized === "true" || normalized === "1") return {
|
|
133
|
+
data: true,
|
|
134
|
+
success: true
|
|
135
|
+
};
|
|
136
|
+
if (normalized === "false" || normalized === "0") return {
|
|
137
|
+
data: false,
|
|
138
|
+
success: true
|
|
139
|
+
};
|
|
140
|
+
return {
|
|
141
|
+
message: "Expected a boolean: true, false, 1, or 0.",
|
|
142
|
+
success: false
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function parseNumber(input, schema) {
|
|
146
|
+
if (schema.decimal && typeof input === "string" && !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(input.trim())) return {
|
|
147
|
+
message: "Expected a finite decimal number.",
|
|
148
|
+
success: false
|
|
149
|
+
};
|
|
150
|
+
const value = typeof input === "string" && input.trim() ? Number(input) : input;
|
|
151
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return {
|
|
152
|
+
message: "Expected a finite number.",
|
|
153
|
+
success: false
|
|
154
|
+
};
|
|
155
|
+
if (schema.isInt && !Number.isSafeInteger(value) || schema.min !== void 0 && value < schema.min || schema.max !== void 0 && value > schema.max) return {
|
|
156
|
+
message: "Expected a number within the declared constraints.",
|
|
157
|
+
success: false
|
|
158
|
+
};
|
|
159
|
+
return {
|
|
160
|
+
data: value,
|
|
161
|
+
success: true
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
function parseUrl(input) {
|
|
165
|
+
if (typeof input === "string") try {
|
|
166
|
+
if (new URL(input).protocol) return {
|
|
167
|
+
data: input,
|
|
168
|
+
success: true
|
|
169
|
+
};
|
|
170
|
+
} catch {}
|
|
171
|
+
return {
|
|
172
|
+
message: "Expected an absolute URL.",
|
|
173
|
+
success: false
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function matchesJsonType(schema, value) {
|
|
177
|
+
switch (schema.kind) {
|
|
178
|
+
case "array": return Array.isArray(value) && (!schema.items || value.every((item) => schema.items && matchesJsonType(schema.items, item)));
|
|
179
|
+
case "object": return value !== null && typeof value === "object" && !Array.isArray(value) && (!schema.properties || Object.keys(value).length === Object.keys(schema.properties).length && Object.entries(schema.properties).every(([key, property]) => Object.hasOwn(value, key) && matchesJsonType(property, Reflect.get(value, key))));
|
|
180
|
+
case "boolean": return typeof value === "boolean";
|
|
181
|
+
case "number": return typeof value === "number" && parseEnvValue(schema, value).success;
|
|
182
|
+
default: return typeof value === "string" && parseEnvValue(schema, value).success;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function schemaContainsEnum(schema) {
|
|
186
|
+
switch (schema.kind) {
|
|
187
|
+
case "enum": return true;
|
|
188
|
+
case "array":
|
|
189
|
+
case "list": return !!schema.items && schemaContainsEnum(schema.items);
|
|
190
|
+
case "object": return Object.values(schema.properties ?? {}).some(schemaContainsEnum);
|
|
191
|
+
default: return false;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region ../internal/src/runtime/cloudflare-env-lookup.ts
|
|
196
|
+
/** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
|
|
197
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
198
|
+
let activeEnv;
|
|
199
|
+
/** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
|
|
200
|
+
function getScopedCloudflareEnv() {
|
|
201
|
+
return globalThis[activeEnvStorageKey]?.getStore();
|
|
202
|
+
}
|
|
203
|
+
function getActiveCloudflareEnv() {
|
|
204
|
+
const scoped = getScopedCloudflareEnv();
|
|
205
|
+
if (scoped) return scoped.env;
|
|
206
|
+
const host = globalThis;
|
|
207
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
208
|
+
}
|
|
209
|
+
//#endregion
|
|
210
|
+
//#region ../internal/src/runtime/cloudflare-env.ts
|
|
211
|
+
const runtimeGlobal = globalThis;
|
|
212
|
+
const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
|
|
213
|
+
function runWithActiveCloudflareEnv(env, callback) {
|
|
214
|
+
return activeEnvStorage.run({ env }, callback);
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region ../internal/src/secret.ts
|
|
218
|
+
const secretEncoder = new TextEncoder();
|
|
219
|
+
/**
|
|
220
|
+
* Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
|
|
221
|
+
* when either value is missing or empty. It uses no Node API, so it also runs in Worker runtimes.
|
|
222
|
+
*/
|
|
223
|
+
function isViteHubSecretEqual(actual, expected) {
|
|
224
|
+
if (!actual || !expected) return false;
|
|
225
|
+
const left = secretEncoder.encode(actual);
|
|
226
|
+
const right = secretEncoder.encode(expected);
|
|
227
|
+
let difference = left.length ^ right.length;
|
|
228
|
+
for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
|
|
229
|
+
return difference === 0;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Compares the token of a `Bearer` `Authorization` header with an expected secret in constant time. The scheme is
|
|
233
|
+
* case-insensitive. Returns `false` for another scheme or a missing value.
|
|
234
|
+
*/
|
|
235
|
+
function isViteHubBearerSecretEqual(authorization, expected) {
|
|
236
|
+
return isViteHubSecretEqual(/^Bearer\s+(.+)$/i.exec(authorization ?? "")?.[1], expected);
|
|
237
|
+
}
|
|
238
|
+
/** HKDF salt for every ViteHub-derived secret. A different salt than Nuxt's keeps both derivations apart for one shared root. */
|
|
239
|
+
const viteHubSecretSalt = "vitehub";
|
|
240
|
+
function hex(buffer) {
|
|
241
|
+
return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
242
|
+
}
|
|
243
|
+
/** Reads the root app secret, `VITEHUB_SECRET`, from an env record. Returns `undefined` when it is not a non-empty string. */
|
|
244
|
+
function readViteHubSecret(env) {
|
|
245
|
+
const value = env.VITEHUB_SECRET;
|
|
246
|
+
return typeof value === "string" && value ? value : void 0;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Derives a 32-byte secret for one purpose from the root secret, hex-encoded. It uses HKDF-SHA256 with the salt
|
|
250
|
+
* `vitehub` and the purpose as `info`. The result is stable while the root is unchanged and distinct for every purpose.
|
|
251
|
+
* Throws a coded error when the root is shorter than 32 characters or the purpose is empty. It uses no Node API.
|
|
252
|
+
*/
|
|
253
|
+
async function deriveViteHubSecret(root, purpose) {
|
|
254
|
+
if (root.length < 32) throw internalErrorDiagnostics.INTERNAL_SECRET_TOO_SHORT({ minimum: 32 });
|
|
255
|
+
if (!purpose) throw internalErrorDiagnostics.INTERNAL_SECRET_PURPOSE_MISSING();
|
|
256
|
+
const key = await globalThis.crypto.subtle.importKey("raw", secretEncoder.encode(root), "HKDF", false, ["deriveBits"]);
|
|
257
|
+
return hex(await globalThis.crypto.subtle.deriveBits({
|
|
258
|
+
hash: "SHA-256",
|
|
259
|
+
info: secretEncoder.encode(purpose),
|
|
260
|
+
name: "HKDF",
|
|
261
|
+
salt: secretEncoder.encode(viteHubSecretSalt)
|
|
262
|
+
}, key, 256));
|
|
263
|
+
}
|
|
264
|
+
/** The format of GitHub's `X-Hub-Signature-256` header. */
|
|
265
|
+
const githubHmacSignatureFormat = Object.freeze({ prefix: "sha256=" });
|
|
266
|
+
/** Decodes a canonical base64 key. Returns `undefined` for malformed or empty input, so verification fails closed. */
|
|
267
|
+
function decodeViteHubBase64Key(value) {
|
|
268
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value) || value.length % 4 === 1) return void 0;
|
|
269
|
+
let binary;
|
|
270
|
+
try {
|
|
271
|
+
binary = atob(value);
|
|
272
|
+
} catch {
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (!binary.length || btoa(binary).replace(/=+$/, "") !== value.replace(/=+$/, "")) return void 0;
|
|
276
|
+
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
277
|
+
}
|
|
278
|
+
/** The HMAC-SHA256 of `value`. It uses Web Crypto, so it also runs in Worker runtimes. */
|
|
279
|
+
async function viteHubHmacSha256(key, value) {
|
|
280
|
+
const raw = typeof key === "string" ? secretEncoder.encode(key) : key;
|
|
281
|
+
const data = typeof value === "string" ? secretEncoder.encode(value) : value;
|
|
282
|
+
const cryptoKey = await globalThis.crypto.subtle.importKey("raw", raw, {
|
|
283
|
+
hash: "SHA-256",
|
|
284
|
+
name: "HMAC"
|
|
285
|
+
}, false, ["sign"]);
|
|
286
|
+
return new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", cryptoKey, data));
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Checks a webhook signature header of the form `<prefix><digest>`, where the digest is the HMAC-SHA256 of the raw
|
|
290
|
+
* body. It compares in constant time. Returns `false` for a missing header, an empty secret, or a key that does not
|
|
291
|
+
* decode. Pass `githubHmacSignatureFormat` for GitHub's `X-Hub-Signature-256`. It uses no Node API.
|
|
292
|
+
*/
|
|
293
|
+
async function verifyViteHubHmacSignature(secret, header, body, format = {}) {
|
|
294
|
+
const prefix = format.prefix ?? "";
|
|
295
|
+
if (!secret || !header || !header.startsWith(prefix)) return false;
|
|
296
|
+
const key = format.secretEncoding === "base64" ? decodeViteHubBase64Key(secret) : secretEncoder.encode(secret);
|
|
297
|
+
if (!key) return false;
|
|
298
|
+
const digest = await viteHubHmacSha256(key, body);
|
|
299
|
+
const received = header.slice(prefix.length);
|
|
300
|
+
if (format.encoding === "base64") return isViteHubSecretEqual(received, btoa(String.fromCharCode(...digest)));
|
|
301
|
+
return isViteHubSecretEqual(received.toLowerCase(), hex(digest.buffer));
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Checks a `Stripe-Signature` header: `t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`. Any matching `v1`
|
|
305
|
+
* passes, as Stripe sends one for each active secret while you roll a secret. A timestamp older than
|
|
306
|
+
* `toleranceSeconds` before `receivedAt` (milliseconds, default now) fails. It compares in constant time and uses no
|
|
307
|
+
* Node API.
|
|
308
|
+
*/
|
|
309
|
+
async function verifyViteHubStripeSignature(secret, header, body, options = {}) {
|
|
310
|
+
const toleranceSeconds = options.toleranceSeconds ?? 300;
|
|
311
|
+
if (!secret || !header || !Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) return false;
|
|
312
|
+
let timestamp;
|
|
313
|
+
let signatureCount = 0;
|
|
314
|
+
const signatures = [];
|
|
315
|
+
for (const part of header.split(",")) {
|
|
316
|
+
const separator = part.indexOf("=");
|
|
317
|
+
if (separator <= 0) continue;
|
|
318
|
+
const key = part.slice(0, separator).trim();
|
|
319
|
+
const value = part.slice(separator + 1).trim();
|
|
320
|
+
if (key === "t") timestamp = value;
|
|
321
|
+
else if (key === "v1") {
|
|
322
|
+
if (++signatureCount > 32) return false;
|
|
323
|
+
if (/^[a-f0-9]{64}$/.test(value)) signatures.push(value);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (!timestamp || !/^\d+$/.test(timestamp) || !signatures.length) return false;
|
|
327
|
+
const timestampSeconds = Number(timestamp);
|
|
328
|
+
if (!Number.isSafeInteger(timestampSeconds)) return false;
|
|
329
|
+
if (Math.floor((options.receivedAt ?? Date.now()) / 1e3) - timestampSeconds > toleranceSeconds) return false;
|
|
330
|
+
const prefix = secretEncoder.encode(`${timestamp}.`);
|
|
331
|
+
const payload = new Uint8Array(prefix.length + body.length);
|
|
332
|
+
payload.set(prefix);
|
|
333
|
+
payload.set(body, prefix.length);
|
|
334
|
+
const expected = hex((await viteHubHmacSha256(secret, payload)).buffer);
|
|
335
|
+
let verified = false;
|
|
336
|
+
for (const signature of signatures) verified = isViteHubSecretEqual(signature, expected) || verified;
|
|
337
|
+
return verified;
|
|
338
|
+
}
|
|
339
|
+
//#endregion
|
|
340
|
+
//#region src/core/errors.ts
|
|
341
|
+
const envErrorMessages = {
|
|
342
|
+
ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.",
|
|
343
|
+
ENV_ASYNC_REQUIRED: "[vitehub] Server Env requires asynchronous loading.",
|
|
344
|
+
ENV_REQUIRED_MISSING: "[vitehub] Required Env value is missing.",
|
|
345
|
+
ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.",
|
|
346
|
+
ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed."
|
|
347
|
+
};
|
|
348
|
+
const envSourceIdentifierSet = /* @__PURE__ */ new Set([
|
|
349
|
+
"custom",
|
|
350
|
+
"env",
|
|
351
|
+
"git:branch",
|
|
352
|
+
"git:commit",
|
|
353
|
+
"git:tag",
|
|
354
|
+
"package.json",
|
|
355
|
+
"provider"
|
|
356
|
+
]);
|
|
357
|
+
function createEnvError(options) {
|
|
358
|
+
const { code, cause, details } = options;
|
|
359
|
+
return new ViteHubError(code, envErrorMessages[code], {
|
|
360
|
+
...cause === void 0 ? {} : { cause },
|
|
361
|
+
...details === void 0 || Object.keys(details).length === 0 ? {} : { details }
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
function invalidEnvDeclaration(path, diagnostic, cause) {
|
|
365
|
+
return createEnvError({
|
|
366
|
+
cause: envErrorDiagnostics.ENV_R0008({
|
|
367
|
+
message: diagnostic,
|
|
368
|
+
...cause === void 0 ? {} : { cause }
|
|
369
|
+
}),
|
|
370
|
+
code: "ENV_DECLARATION_INVALID",
|
|
371
|
+
details: optionalPath(path)
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
function asyncServerEnvRequired(path) {
|
|
375
|
+
return createEnvError({
|
|
376
|
+
cause: envErrorDiagnostics.ENV_R0009({ message: `Server Env at ${path} uses env.provider(). Use loadServerEnv() or runWithServerEnv().` }),
|
|
377
|
+
code: "ENV_ASYNC_REQUIRED",
|
|
378
|
+
details: optionalPath(path)
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
function missingRequiredEnv(source, diagnostic, path) {
|
|
382
|
+
const pathDetails = optionalPath(path);
|
|
383
|
+
return createEnvError({
|
|
384
|
+
cause: envErrorDiagnostics.ENV_R0010({ message: diagnostic }),
|
|
385
|
+
code: "ENV_REQUIRED_MISSING",
|
|
386
|
+
details: {
|
|
387
|
+
...pathDetails,
|
|
388
|
+
source: publicSourceIdentifier(source)
|
|
389
|
+
}
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
function invalidRuntimeEnvValue(source, diagnostic, path) {
|
|
393
|
+
return createEnvError({
|
|
394
|
+
cause: envErrorDiagnostics.ENV_R0011({ message: diagnostic }),
|
|
395
|
+
code: "ENV_RUNTIME_VALUE_INVALID",
|
|
396
|
+
details: {
|
|
397
|
+
...optionalPath(path),
|
|
398
|
+
source: publicSourceIdentifier(source)
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
function envSourceFailed(source, cause) {
|
|
403
|
+
return createEnvError({
|
|
404
|
+
cause,
|
|
405
|
+
code: "ENV_SOURCE_FAILED",
|
|
406
|
+
details: { source: publicSourceIdentifier(source) }
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
function isAbortError(value) {
|
|
410
|
+
if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
|
|
411
|
+
try {
|
|
412
|
+
return value.name === "AbortError";
|
|
413
|
+
} catch {
|
|
414
|
+
return false;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
function publicSourceIdentifier(source) {
|
|
418
|
+
if (envSourceIdentifierSet.has(source)) return source;
|
|
419
|
+
if (source.startsWith("env:")) return "env";
|
|
420
|
+
if (source.startsWith("package.json:")) return "package.json";
|
|
421
|
+
return "custom";
|
|
422
|
+
}
|
|
423
|
+
function optionalPath(path) {
|
|
424
|
+
const normalized = safePath(path);
|
|
425
|
+
return normalized ? { path: normalized } : {};
|
|
426
|
+
}
|
|
427
|
+
function safePath(path) {
|
|
428
|
+
if (typeof path !== "string" || path.length > 256) return void 0;
|
|
429
|
+
return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? path : void 0;
|
|
430
|
+
}
|
|
431
|
+
//#endregion
|
|
432
|
+
//#region src/internal/runtime-env.ts
|
|
433
|
+
function processEnv() {
|
|
434
|
+
return typeof process === "object" && process && process.env ? process.env : {};
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* The Cloudflare bindings in the request's Standard Context, else the bindings of the active Cloudflare request.
|
|
438
|
+
* Installs Standard Context on H3 events when needed. A value without an event request, such as Auth's `Request`,
|
|
439
|
+
* reads the active bindings.
|
|
440
|
+
*/
|
|
441
|
+
function cloudflareEnv(event) {
|
|
442
|
+
if (!event) return getActiveCloudflareEnv();
|
|
443
|
+
let standard;
|
|
444
|
+
try {
|
|
445
|
+
standard = getStandardContext(event);
|
|
446
|
+
} catch (error) {
|
|
447
|
+
if (error?.name !== "RUNTIME_R0015") throw error;
|
|
448
|
+
return getActiveCloudflareEnv();
|
|
449
|
+
}
|
|
450
|
+
return standard.runtime?.cloudflare?.env ?? getActiveCloudflareEnv();
|
|
451
|
+
}
|
|
452
|
+
/** The host variables of a request. In app tests, the values of `setEnv()` from `vite-hub/test` win over every other source. */
|
|
453
|
+
function runtimeEnv(event) {
|
|
454
|
+
return {
|
|
455
|
+
...processEnv(),
|
|
456
|
+
...cloudflareEnv(event),
|
|
457
|
+
...getViteHubTestMode()?.env
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
/** An H3 event without Standard Context reads it from its Request, which carries the same host data. */
|
|
461
|
+
function standardSource(event) {
|
|
462
|
+
if ("~standard" in event) return event;
|
|
463
|
+
return event instanceof Request ? event : event.req;
|
|
464
|
+
}
|
|
465
|
+
//#endregion
|
|
466
|
+
//#region src/core/registry.ts
|
|
467
|
+
const envEntrySchema = v.object({
|
|
468
|
+
required: v.boolean(),
|
|
469
|
+
secret: v.boolean(),
|
|
470
|
+
source: v.object({
|
|
471
|
+
kind: v.literal("env"),
|
|
472
|
+
name: v.string()
|
|
473
|
+
})
|
|
474
|
+
});
|
|
475
|
+
const providerEntrySchema = v.object({
|
|
476
|
+
required: v.boolean(),
|
|
477
|
+
secret: v.boolean(),
|
|
478
|
+
source: v.object({
|
|
479
|
+
key: v.string(),
|
|
480
|
+
kind: v.literal("provider"),
|
|
481
|
+
provider: v.string()
|
|
482
|
+
})
|
|
483
|
+
});
|
|
484
|
+
function isRuntimeLiteralEntry(value) {
|
|
485
|
+
return isRecord(value) && value.kind === "literal";
|
|
486
|
+
}
|
|
487
|
+
function isRuntimeEnvEntry(value) {
|
|
488
|
+
return isRecord(value) && isRecord(value.source) && v.is(envEntrySchema, value);
|
|
489
|
+
}
|
|
490
|
+
function isRuntimeProviderEntry(value) {
|
|
491
|
+
return isRecord(value) && isRecord(value.source) && v.is(providerEntrySchema, value);
|
|
492
|
+
}
|
|
493
|
+
/** Visits declarations once. Literal values and declaration metadata are opaque to traversal. */
|
|
494
|
+
function* runtimeRegistryEntries(value, path = "env.server") {
|
|
495
|
+
if (isRuntimeLiteralEntry(value) || isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) {
|
|
496
|
+
yield {
|
|
497
|
+
entry: value,
|
|
498
|
+
path
|
|
499
|
+
};
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
if (!isRecord(value)) return;
|
|
503
|
+
for (const [key, child] of Object.entries(value)) yield* runtimeRegistryEntries(child, `${path}.${key.includes(".") ? "!" : ""}${key}`);
|
|
504
|
+
}
|
|
505
|
+
//#endregion
|
|
506
|
+
//#region ../internal/src/invariant.ts
|
|
507
|
+
const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
508
|
+
docsBase: "https://vitehub.dev/docs/development/diagnostics",
|
|
509
|
+
codes: { INTERNAL_INVARIANT_FAILED: {
|
|
510
|
+
why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
|
|
511
|
+
fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
|
|
512
|
+
} }
|
|
513
|
+
});
|
|
514
|
+
/**
|
|
515
|
+
* The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
|
|
516
|
+
* Use a code from the package catalog when a developer can cause the error or fix it.
|
|
517
|
+
*/
|
|
518
|
+
function invariantError(what) {
|
|
519
|
+
return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
|
|
520
|
+
}
|
|
521
|
+
/** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
|
|
522
|
+
function invariant(condition, what) {
|
|
523
|
+
if (!condition) throw invariantError(what);
|
|
524
|
+
}
|
|
525
|
+
//#endregion
|
|
526
|
+
//#region src/seal-uses.ts
|
|
527
|
+
const table = "vitehub_env_seal_uses";
|
|
528
|
+
const ready = /* @__PURE__ */ new WeakMap();
|
|
529
|
+
function checkId(id) {
|
|
530
|
+
invariant(/^[\da-f]{32}$/.test(id), "a seal id must be 32 lowercase hex characters");
|
|
531
|
+
return id;
|
|
532
|
+
}
|
|
533
|
+
function initialize(db) {
|
|
534
|
+
let promise = ready.get(db);
|
|
535
|
+
if (!promise) {
|
|
536
|
+
promise = (async () => {
|
|
537
|
+
await db.all(`CREATE TABLE IF NOT EXISTS ${table} (id TEXT PRIMARY KEY, uses INTEGER NOT NULL, expires_at INTEGER)`);
|
|
538
|
+
await db.all(`CREATE INDEX IF NOT EXISTS ${table}_expires_at ON ${table} (expires_at)`);
|
|
539
|
+
})();
|
|
540
|
+
promise.catch(() => ready.delete(db));
|
|
541
|
+
ready.set(db, promise);
|
|
542
|
+
}
|
|
543
|
+
return promise;
|
|
544
|
+
}
|
|
545
|
+
/** Keeps `uses` for a new id. The row holds no part of the value. */
|
|
546
|
+
async function createSealUses(db, id, uses, expiresAt) {
|
|
547
|
+
invariant(Number.isSafeInteger(uses) && uses >= 1, "`uses` must be a positive integer");
|
|
548
|
+
await initialize(db);
|
|
549
|
+
const now = Date.now();
|
|
550
|
+
await db.all(`DELETE FROM ${table} WHERE expires_at IS NOT NULL AND expires_at <= ${now}`);
|
|
551
|
+
await db.all(`INSERT INTO ${table} (id, uses, expires_at) VALUES ('${checkId(id)}', ${uses}, ${expiresAt === void 0 ? "NULL" : Math.ceil(expiresAt)})`);
|
|
552
|
+
}
|
|
553
|
+
/** Takes one use in one statement, so of two calls on the last use, one gets it. Returns false when no use is left. */
|
|
554
|
+
async function takeSealUse(db, id) {
|
|
555
|
+
await initialize(db);
|
|
556
|
+
const key = checkId(id);
|
|
557
|
+
if (!(await db.all(`UPDATE ${table} SET uses = uses - 1 WHERE id = '${key}' AND uses > 0 RETURNING uses`)).length) return false;
|
|
558
|
+
await db.all(`DELETE FROM ${table} WHERE id = '${key}' AND uses <= 0`);
|
|
559
|
+
return true;
|
|
560
|
+
}
|
|
561
|
+
/** Deletes the uses of an id, such as one whose value expired. */
|
|
562
|
+
async function deleteSealUses(db, id) {
|
|
563
|
+
await initialize(db);
|
|
564
|
+
await db.all(`DELETE FROM ${table} WHERE id = '${checkId(id)}'`);
|
|
565
|
+
}
|
|
566
|
+
//#endregion
|
|
567
|
+
//#region src/seal-value.ts
|
|
568
|
+
const sealErrors = /*#__PURE__*/ defineErrors({
|
|
569
|
+
docs: "https://vitehub.dev/docs/env/diagnostics",
|
|
570
|
+
codes: {
|
|
571
|
+
ENV_SEAL_EXPIRED: {
|
|
572
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_seal_expired",
|
|
573
|
+
why: ({ expiresAt }) => `The sealed value expired at ${new Date(expiresAt).toISOString()}.`,
|
|
574
|
+
fix: "Seal a new value. Give `seal()` a longer `ttl` when the value must live longer."
|
|
575
|
+
},
|
|
576
|
+
ENV_SEAL_INVALID: {
|
|
577
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_seal_invalid",
|
|
578
|
+
why: "The string is not a sealed value, someone changed it, or another root secret sealed it.",
|
|
579
|
+
fix: "Treat the string as untrusted and seal a new value. When you rotate `VITEHUB_SECRET`, put the old secret in `VITEHUB_SECRET_PREVIOUS`, so that values sealed with it still open until they expire."
|
|
580
|
+
},
|
|
581
|
+
ENV_SEAL_SCHEMA_MISMATCH: {
|
|
582
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_seal_schema_mismatch",
|
|
583
|
+
why: "The sealed value opened, but it does not match `schema`.",
|
|
584
|
+
fix: "Read `error.cause` for the schema issues. A value sealed by an older deployment can have an older shape: seal a new value."
|
|
585
|
+
},
|
|
586
|
+
ENV_SEAL_USED_UP: {
|
|
587
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_seal_used_up",
|
|
588
|
+
why: "The sealed value was read as many times as its `uses` allow, so it is gone.",
|
|
589
|
+
fix: "Seal a new value. Give `seal()` more `uses` when several people or requests must read it."
|
|
590
|
+
},
|
|
591
|
+
ENV_SEAL_WRONG_PURPOSE: {
|
|
592
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_seal_wrong_purpose",
|
|
593
|
+
why: ({ purpose }) => `The value was sealed for another purpose than "${purpose}".`,
|
|
594
|
+
fix: "Pass the purpose that `seal()` used. Each purpose has its own key, so a value cannot pass as a value of another purpose."
|
|
595
|
+
},
|
|
596
|
+
ENV_SEAL_ARGUMENT_INVALID: {
|
|
597
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_seal_argument_invalid",
|
|
598
|
+
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."
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
const version = 1;
|
|
604
|
+
const countedVersion = 2;
|
|
605
|
+
const headerLength = 13;
|
|
606
|
+
const idLength = 16;
|
|
607
|
+
const ivLength = 12;
|
|
608
|
+
const tagLength = 16;
|
|
609
|
+
const encoder = new TextEncoder();
|
|
610
|
+
function argumentError(problem) {
|
|
611
|
+
throw sealErrors.ENV_SEAL_ARGUMENT_INVALID({ problem });
|
|
612
|
+
}
|
|
613
|
+
function checkPurpose(purpose) {
|
|
614
|
+
if (typeof purpose !== "string" || !purpose) argumentError("`purpose` must be a non-empty string.");
|
|
615
|
+
}
|
|
616
|
+
function checkJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
|
|
617
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
618
|
+
if (typeof value === "number" && Number.isFinite(value)) return;
|
|
619
|
+
if (typeof value !== "object" || value === null || ancestors.has(value)) argumentError("`value` must contain only JSON values and no cycles.");
|
|
620
|
+
const array = Array.isArray(value);
|
|
621
|
+
const prototype = Object.getPrototypeOf(value);
|
|
622
|
+
if (!array && prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length) argumentError("`value` must contain only plain JSON objects and arrays.");
|
|
623
|
+
ancestors.add(value);
|
|
624
|
+
if (array) {
|
|
625
|
+
if (Object.keys(value).length !== value.length) argumentError("`value` must not contain sparse arrays or extra array properties.");
|
|
626
|
+
for (let index = 0; index < value.length; index++) {
|
|
627
|
+
if (!Object.hasOwn(value, index)) argumentError("`value` must not contain sparse arrays.");
|
|
628
|
+
checkJsonValue(value[index], ancestors);
|
|
629
|
+
}
|
|
630
|
+
} else for (const member of Object.values(value)) checkJsonValue(member, ancestors);
|
|
631
|
+
ancestors.delete(value);
|
|
632
|
+
}
|
|
633
|
+
function rootSecret(secret) {
|
|
634
|
+
const value = secret instanceof SecretEnv ? secret.unseal() : secret;
|
|
635
|
+
if (typeof value !== "string" || value.length < 32) argumentError(`\`secret\` must be a string of at least 32 characters, or a non-empty list of them.`);
|
|
636
|
+
return value;
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* The root secrets in order: the one that seals first, then the old ones that `unseal()` also tries. `undefined` is
|
|
640
|
+
* `VITEHUB_SECRET` (or the development secret). Only `unseal()` passes `previous`, to add `VITEHUB_SECRET_PREVIOUS`.
|
|
641
|
+
*/
|
|
642
|
+
function rootSecrets(options, previous) {
|
|
643
|
+
const { secret } = options;
|
|
644
|
+
if (secret === void 0) return previous ? [void 0, ...previousSecrets(options.event)] : [void 0];
|
|
645
|
+
const list = typeof secret === "string" || secret instanceof SecretEnv ? [secret] : secret;
|
|
646
|
+
if (!Array.isArray(list) || !list.length) argumentError("`secret` must be a string, a Secret Env value, or a non-empty list of them.");
|
|
647
|
+
return list.map(rootSecret);
|
|
648
|
+
}
|
|
649
|
+
function previousSecrets(event) {
|
|
650
|
+
const value = runtimeEnv(event).VITEHUB_SECRET_PREVIOUS;
|
|
651
|
+
if (typeof value !== "string") return [];
|
|
652
|
+
const secrets = value.split(",").map((secret) => secret.trim()).filter(Boolean);
|
|
653
|
+
if (secrets.some((secret) => secret.length < 32)) throw invalidRuntimeEnvValue("env", `Each secret in VITEHUB_SECRET_PREVIOUS must be at least 32 characters. Separate old secrets with a comma.`, "VITEHUB_SECRET_PREVIOUS");
|
|
654
|
+
return secrets;
|
|
655
|
+
}
|
|
656
|
+
function toBase64Url(bytes) {
|
|
657
|
+
let binary = "";
|
|
658
|
+
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
|
|
659
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
660
|
+
}
|
|
661
|
+
function fromBase64Url(text) {
|
|
662
|
+
if (!/^[\w-]+$/.test(text)) return void 0;
|
|
663
|
+
try {
|
|
664
|
+
return Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0));
|
|
665
|
+
} catch {
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
function toHex(bytes) {
|
|
670
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
671
|
+
}
|
|
672
|
+
function usesDatabase(db, problem) {
|
|
673
|
+
if (typeof db !== "object" || db === null || typeof Reflect.get(db, "all") !== "function") argumentError(problem);
|
|
674
|
+
return db;
|
|
675
|
+
}
|
|
676
|
+
async function fingerprint(purpose) {
|
|
677
|
+
return new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(purpose))).slice(0, 4);
|
|
678
|
+
}
|
|
679
|
+
async function purposeKey(derive, purpose, event, root, usage) {
|
|
680
|
+
const hex = await derive(`vitehub:seal:${purpose}`, event, root);
|
|
681
|
+
const raw = Uint8Array.from(hex.match(/../g), (byte) => Number.parseInt(byte, 16));
|
|
682
|
+
return await crypto.subtle.importKey("raw", raw, "AES-GCM", false, [usage]);
|
|
683
|
+
}
|
|
684
|
+
/** Builds `seal()` and `unseal()` on a key derivation. The generated `#vitehub/env/server` module uses it. */
|
|
685
|
+
function createSealing(derive) {
|
|
686
|
+
return {
|
|
687
|
+
async seal(purpose, value, options = {}) {
|
|
688
|
+
checkPurpose(purpose);
|
|
689
|
+
const { ttl } = options;
|
|
690
|
+
if (ttl !== void 0 && (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0)) argumentError("`ttl` must be a positive number of seconds.");
|
|
691
|
+
const { uses, db } = options;
|
|
692
|
+
if (uses !== void 0 && (typeof uses !== "number" || !Number.isSafeInteger(uses) || uses < 1)) argumentError("`uses` must be a positive integer.");
|
|
693
|
+
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.");
|
|
694
|
+
checkJsonValue(value);
|
|
695
|
+
let json;
|
|
696
|
+
try {
|
|
697
|
+
json = JSON.stringify(value);
|
|
698
|
+
} catch (cause) {
|
|
699
|
+
argumentError(`\`value\` cannot be serialized as JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
700
|
+
}
|
|
701
|
+
if (json === void 0) argumentError("`value` must be a JSON value, not undefined or a function.");
|
|
702
|
+
const [root] = rootSecrets(options, false);
|
|
703
|
+
const expiresAt = ttl === void 0 ? 0 : Date.now() + ttl * 1e3;
|
|
704
|
+
const header = new Uint8Array(uses === void 0 ? headerLength : 29);
|
|
705
|
+
header[0] = uses === void 0 ? version : countedVersion;
|
|
706
|
+
header.set(await fingerprint(purpose), 1);
|
|
707
|
+
new DataView(header.buffer).setFloat64(5, expiresAt);
|
|
708
|
+
if (uses !== void 0 && usesDb) {
|
|
709
|
+
const id = crypto.getRandomValues(new Uint8Array(idLength));
|
|
710
|
+
header.set(id, headerLength);
|
|
711
|
+
await createSealUses(usesDb, toHex(id), uses, expiresAt || void 0);
|
|
712
|
+
}
|
|
713
|
+
const iv = crypto.getRandomValues(new Uint8Array(ivLength));
|
|
714
|
+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
|
|
715
|
+
name: "AES-GCM",
|
|
716
|
+
iv,
|
|
717
|
+
additionalData: header
|
|
718
|
+
}, await purposeKey(derive, purpose, options.event, root, "encrypt"), encoder.encode(json)));
|
|
719
|
+
const sealed = new Uint8Array(header.length + ivLength + ciphertext.length);
|
|
720
|
+
sealed.set(header);
|
|
721
|
+
sealed.set(iv, header.length);
|
|
722
|
+
sealed.set(ciphertext, header.length + ivLength);
|
|
723
|
+
return toBase64Url(sealed);
|
|
724
|
+
},
|
|
725
|
+
async unseal(purpose, sealed, options = {}) {
|
|
726
|
+
checkPurpose(purpose);
|
|
727
|
+
const [current, ...previous] = rootSecrets(options, true);
|
|
728
|
+
const key = await purposeKey(derive, purpose, options.event, current, "decrypt");
|
|
729
|
+
const bytes = typeof sealed === "string" ? fromBase64Url(sealed) : void 0;
|
|
730
|
+
const counted = bytes?.[0] === countedVersion;
|
|
731
|
+
const length = counted ? 29 : headerLength;
|
|
732
|
+
if (!bytes || bytes.length < length + ivLength + tagLength || bytes[0] !== version && !counted) return [sealErrors.ENV_SEAL_INVALID(), void 0];
|
|
733
|
+
const header = bytes.subarray(0, length);
|
|
734
|
+
if ((await fingerprint(purpose)).some((byte, index) => header[1 + index] !== byte)) return [sealErrors.ENV_SEAL_WRONG_PURPOSE({ purpose }), void 0];
|
|
735
|
+
const decrypt = (candidate) => crypto.subtle.decrypt({
|
|
736
|
+
name: "AES-GCM",
|
|
737
|
+
iv: bytes.subarray(length, length + ivLength),
|
|
738
|
+
additionalData: header
|
|
739
|
+
}, candidate, bytes.subarray(length + ivLength)).catch(() => void 0);
|
|
740
|
+
let plaintext = await decrypt(key);
|
|
741
|
+
for (const root of previous) {
|
|
742
|
+
if (plaintext) break;
|
|
743
|
+
plaintext = await decrypt(await purposeKey(derive, purpose, options.event, root, "decrypt"));
|
|
744
|
+
}
|
|
745
|
+
if (!plaintext) return [sealErrors.ENV_SEAL_INVALID(), void 0];
|
|
746
|
+
const db = counted ? usesDatabase(options.db, "This value was sealed with `uses`. Pass the same `db` to `unseal()`, so that it can take a use.") : void 0;
|
|
747
|
+
const expiresAt = new DataView(header.buffer, header.byteOffset).getFloat64(5);
|
|
748
|
+
const id = db && toHex(header.subarray(headerLength));
|
|
749
|
+
if (expiresAt !== 0 && Date.now() >= expiresAt) {
|
|
750
|
+
if (db && id) await deleteSealUses(db, id);
|
|
751
|
+
return [sealErrors.ENV_SEAL_EXPIRED({ expiresAt }), void 0];
|
|
752
|
+
}
|
|
753
|
+
let value = JSON.parse(new TextDecoder().decode(plaintext));
|
|
754
|
+
if (options.schema) {
|
|
755
|
+
const result = await options.schema["~standard"].validate(value);
|
|
756
|
+
if (result.issues) return [sealErrors.ENV_SEAL_SCHEMA_MISMATCH({ cause: result.issues }), void 0];
|
|
757
|
+
value = result.value;
|
|
758
|
+
}
|
|
759
|
+
if (db && id && !await takeSealUse(db, id)) return [sealErrors.ENV_SEAL_USED_UP(), void 0];
|
|
760
|
+
return [void 0, value];
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
const sealing = createSealing((purpose, event, root) => deriveSecret(purpose, {
|
|
765
|
+
event,
|
|
766
|
+
root
|
|
767
|
+
}));
|
|
768
|
+
/**
|
|
769
|
+
* Encrypts and signs a JSON value for one purpose, with a key that ViteHub derives from `VITEHUB_SECRET`.
|
|
770
|
+
* Returns a URL-safe string that only `unseal()` with the same purpose can read.
|
|
771
|
+
* Throws `ENV_REQUIRED_MISSING` when no root secret is set, and `ENV_SEAL_ARGUMENT_INVALID` for a bad argument.
|
|
772
|
+
*
|
|
773
|
+
* @example
|
|
774
|
+
* const ticket = await seal("my-app:upload", { userId }, { ttl: 900 })
|
|
775
|
+
*/
|
|
776
|
+
function seal(purpose, value, options) {
|
|
777
|
+
return sealing.seal(purpose, value, options);
|
|
778
|
+
}
|
|
779
|
+
function unseal(purpose, sealed, options) {
|
|
780
|
+
return sealing.unseal(purpose, sealed, options);
|
|
781
|
+
}
|
|
782
|
+
//#endregion
|
|
783
|
+
//#region src/server.ts
|
|
784
|
+
/**
|
|
785
|
+
* Run `callback` with `env` as the active Cloudflare bindings. Server Env reads them when a call gets no request
|
|
786
|
+
* event, such as for the module bindings of `cloudflare:workers` outside a request.
|
|
787
|
+
*/
|
|
788
|
+
function runWithCloudflareEnv(env, callback) {
|
|
789
|
+
return runWithActiveCloudflareEnv(env, callback);
|
|
790
|
+
}
|
|
791
|
+
let warnedGeneratedSecret = false;
|
|
792
|
+
/**
|
|
793
|
+
* Derives a 32-byte hex secret for one purpose from the root app secret, `VITEHUB_SECRET`.
|
|
794
|
+
* It uses HKDF-SHA256, so the result is stable while the root is unchanged and distinct for every purpose.
|
|
795
|
+
* Namespace the purpose to its owner, such as `my-module:session`. ViteHub reserves the `vitehub:` prefix.
|
|
796
|
+
* Throws `ENV_REQUIRED_MISSING` when no root secret is set, and `ENV_RUNTIME_VALUE_INVALID` when it is shorter than 32 characters.
|
|
797
|
+
* Only the generated `#vitehub/env/server` module passes `development`, with the project's development secret.
|
|
798
|
+
*/
|
|
799
|
+
async function deriveSecret(purpose, options = {}, development = {}) {
|
|
800
|
+
const env = runtimeEnv(options.event);
|
|
801
|
+
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");
|
|
803
|
+
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
|
+
if ((development.generated || env.VITEHUB_SECRET_GENERATED === "1") && !warnedGeneratedSecret) {
|
|
805
|
+
warnedGeneratedSecret = true;
|
|
806
|
+
console.warn("[vitehub] A generated development VITEHUB_SECRET is in use. Set VITEHUB_SECRET for deployments: builds never generate one.");
|
|
807
|
+
}
|
|
808
|
+
return await deriveViteHubSecret(root, purpose);
|
|
809
|
+
}
|
|
810
|
+
/** An empty variable counts as missing, so it never shadows a later name or satisfies a required value. */
|
|
811
|
+
function hasRuntimeName(env, name) {
|
|
812
|
+
return Object.hasOwn(env, name) && env[name] !== void 0 && env[name] !== "";
|
|
813
|
+
}
|
|
814
|
+
function readRuntimeSource(entry, env) {
|
|
815
|
+
for (const name of entry.source.names || [entry.source.name]) if (hasRuntimeName(env, name)) return {
|
|
816
|
+
found: true,
|
|
817
|
+
name,
|
|
818
|
+
value: env[name]
|
|
819
|
+
};
|
|
820
|
+
return { found: false };
|
|
821
|
+
}
|
|
822
|
+
/** Report which kind of name supplied the value, and whether a shadowed conventional name holds another value. */
|
|
823
|
+
function runtimeSourceOrigin(entry, env, source) {
|
|
824
|
+
const canonical = entry.source.canonical;
|
|
825
|
+
if (!source.found || canonical === void 0 || canonical === false) return {};
|
|
826
|
+
if (source.name !== canonical) return { via: "conventional" };
|
|
827
|
+
return (entry.source.names || [entry.source.name]).some((name) => name !== canonical && hasRuntimeName(env, name) && env[name] !== source.value) ? {
|
|
828
|
+
conflict: true,
|
|
829
|
+
via: "canonical"
|
|
830
|
+
} : { via: "canonical" };
|
|
831
|
+
}
|
|
832
|
+
/** Server Env resolves every declaration together, so the message must say why reading another value fails. */
|
|
833
|
+
function missingRuntimeValueMessage(entry, path) {
|
|
834
|
+
const supply = entry.source.kind === "env" ? `Set ${(entry.source.names || [entry.source.name]).join(" or ")}` : "Return it from the provider";
|
|
835
|
+
return `${path} is required and has no value. Server Env checks every declared value together, so this fails even when code reads only another value. ${entry.secret ? `${supply} or declare it with optional: true.` : `${supply}, give it a default, or declare it with optional: true.`}`;
|
|
836
|
+
}
|
|
837
|
+
const boundSchemas = /* @__PURE__ */ new WeakMap();
|
|
838
|
+
/**
|
|
839
|
+
* Attach the schemas that `env.schemaFrom()` declarations name. The generated `#vitehub/env/server` module imports
|
|
840
|
+
* each schema module and calls this once, so a missing or wrong export fails when the server starts.
|
|
841
|
+
*/
|
|
842
|
+
function bindServerEnvSchemas(registry, modules) {
|
|
843
|
+
for (const { entry, path } of runtimeRegistryEntries(registry)) {
|
|
844
|
+
if (!(isRuntimeEnvEntry(entry) || isRuntimeProviderEntry(entry)) || !entry.schemaModule) continue;
|
|
845
|
+
const reference = entry.schemaModule;
|
|
846
|
+
const module = Object.hasOwn(modules, reference.module) ? modules[reference.module] : void 0;
|
|
847
|
+
const schema = module && Object.hasOwn(module, reference.export) ? module[reference.export] : void 0;
|
|
848
|
+
if (!isBoundStandardSchema(schema)) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(${JSON.stringify(reference.module)}, ${JSON.stringify(reference.export)}), but that export is not a Standard Schema.`);
|
|
849
|
+
boundSchemas.set(entry, schema);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
function isBoundStandardSchema(value) {
|
|
853
|
+
if (typeof value !== "object" && typeof value !== "function" || value === null) return false;
|
|
854
|
+
const standard = value["~standard"];
|
|
855
|
+
return typeof standard === "object" && standard !== null && typeof standard.validate === "function";
|
|
856
|
+
}
|
|
857
|
+
function parseRuntimeValue(entry, value, path) {
|
|
858
|
+
if (!entry.schemaModule) return parseEnvValue(entry.schema ?? stringValueSchema, value);
|
|
859
|
+
const schema = boundSchemas.get(entry);
|
|
860
|
+
if (!schema) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(), but no schema module was loaded for it. Only env.server declarations of hubEnv() support env.schemaFrom().`);
|
|
861
|
+
let input = value;
|
|
862
|
+
if (entry.schemaModule.input === "json") {
|
|
863
|
+
const json = readJsonInput(value);
|
|
864
|
+
if (!json.success) return json;
|
|
865
|
+
input = json.data;
|
|
866
|
+
}
|
|
867
|
+
let result;
|
|
868
|
+
try {
|
|
869
|
+
result = schema["~standard"].validate(input);
|
|
870
|
+
} catch (error) {
|
|
871
|
+
return {
|
|
872
|
+
message: `The schema threw: ${error instanceof Error ? error.message : String(error)}`,
|
|
873
|
+
success: false
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
if (isPromiseLike(result)) {
|
|
877
|
+
Promise.resolve(result).catch(() => void 0);
|
|
878
|
+
return {
|
|
879
|
+
message: "The schema is async. Server Env runs schemas synchronously.",
|
|
880
|
+
success: false
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
const issues = isRecord(result) ? result.issues : void 0;
|
|
884
|
+
if (Array.isArray(issues) && issues.length) return {
|
|
885
|
+
message: formatSchemaIssues(issues),
|
|
886
|
+
success: false
|
|
887
|
+
};
|
|
888
|
+
if (!isRecord(result) || !("value" in result)) return {
|
|
889
|
+
message: "The schema returned no value.",
|
|
890
|
+
success: false
|
|
891
|
+
};
|
|
892
|
+
return {
|
|
893
|
+
data: result.value,
|
|
894
|
+
success: true
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
function isPromiseLike(value) {
|
|
898
|
+
return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
|
|
899
|
+
}
|
|
900
|
+
function formatSchemaIssues(issues) {
|
|
901
|
+
return issues.map((issue) => {
|
|
902
|
+
const message = isRecord(issue) && typeof issue.message === "string" ? issue.message : "Invalid value.";
|
|
903
|
+
const segments = isRecord(issue) && Array.isArray(issue.path) ? issue.path.map((segment) => isRecord(segment) ? segment.key : segment).filter((segment) => typeof segment === "string" || typeof segment === "number") : [];
|
|
904
|
+
return segments.length ? `${segments.join(".")}: ${message}` : message;
|
|
905
|
+
}).join("; ");
|
|
906
|
+
}
|
|
907
|
+
function resolvedRuntimeValue(entry, value, found, path, snapshot = false) {
|
|
908
|
+
const resolved = found ? value : entry.default;
|
|
909
|
+
if (typeof resolved === "undefined") {
|
|
910
|
+
if (entry.required) throw missingRequiredEnv(entry.source.kind, missingRuntimeValueMessage(entry, path), path);
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
const parsed = parseRuntimeValue(entry, resolved, path);
|
|
914
|
+
if (!parsed.success) {
|
|
915
|
+
const message = entry.secret ? entry.schemaModule ? "The value does not match its schema." : "The value does not match its declared type." : parsed.message;
|
|
916
|
+
throw invalidRuntimeEnvValue(entry.source.kind, `Invalid ${path} from ${entry.source.kind}. ${message}`, path);
|
|
917
|
+
}
|
|
918
|
+
const data = snapshot ? snapshotValue(parsed.data) : parsed.data;
|
|
919
|
+
return entry.secret ? new SecretEnv(data) : data;
|
|
920
|
+
}
|
|
921
|
+
function resolveRegistryValue(value, env, path) {
|
|
922
|
+
if (isRuntimeLiteralEntry(value)) return value.value;
|
|
923
|
+
if (isRuntimeEnvEntry(value)) {
|
|
924
|
+
const source = readRuntimeSource(value, env);
|
|
925
|
+
return resolvedRuntimeValue(value, source.value, source.found, path);
|
|
926
|
+
}
|
|
927
|
+
if (isRuntimeProviderEntry(value)) throw asyncServerEnvRequired(path);
|
|
928
|
+
if (!isRecord(value)) return void 0;
|
|
929
|
+
const output = Object.create(null);
|
|
930
|
+
for (const [key, child] of Object.entries(value)) {
|
|
931
|
+
const childPath = `${path}.${key}`;
|
|
932
|
+
if (isRuntimeProviderEntry(child)) Object.defineProperty(output, key, {
|
|
933
|
+
enumerable: true,
|
|
934
|
+
get() {
|
|
935
|
+
throw asyncServerEnvRequired(childPath);
|
|
936
|
+
}
|
|
937
|
+
});
|
|
938
|
+
else output[key] = resolveRegistryValue(child, env, childPath);
|
|
939
|
+
}
|
|
940
|
+
return output;
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* Copy the namespace records of a resolved registry, so a caller that changes its result does not change the cached
|
|
944
|
+
* one. resolveRegistryValue() creates each namespace without a prototype, and provider getters keep their descriptor.
|
|
945
|
+
*/
|
|
946
|
+
function copyNamespaces(value) {
|
|
947
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
948
|
+
for (const descriptor of Object.values(descriptors)) if (isNamespace(descriptor.value)) descriptor.value = copyNamespaces(descriptor.value);
|
|
949
|
+
return Object.create(null, descriptors);
|
|
950
|
+
}
|
|
951
|
+
function isNamespace(value) {
|
|
952
|
+
return typeof value === "object" && value !== null && Object.getPrototypeOf(value) === null;
|
|
953
|
+
}
|
|
954
|
+
function providerFor(name, providers) {
|
|
955
|
+
let provider;
|
|
956
|
+
try {
|
|
957
|
+
const configured = providers && Object.hasOwn(providers, name) ? providers[name] : void 0;
|
|
958
|
+
if (configured && typeof configured === "object" && typeof configured.read === "function") {
|
|
959
|
+
const read = configured.read;
|
|
960
|
+
provider = { read: (input) => read.call(configured, input) };
|
|
961
|
+
}
|
|
962
|
+
} catch (cause) {
|
|
963
|
+
throw envSourceFailed("provider", cause);
|
|
964
|
+
}
|
|
965
|
+
if (!provider) throw envErrorDiagnostics.ENV_R0019({ message: "The configured Server Env provider is unavailable or invalid." });
|
|
966
|
+
return provider;
|
|
967
|
+
}
|
|
968
|
+
function abortReason(signal) {
|
|
969
|
+
return signal.reason === void 0 ? Object.assign(envErrorDiagnostics.ENV_R0020({ message: "Server Env loading was aborted." }), { name: "AbortError" }) : signal.reason;
|
|
970
|
+
}
|
|
971
|
+
async function withAbort(operation, signal) {
|
|
972
|
+
if (!signal) return await operation();
|
|
973
|
+
if (signal.aborted) throw abortReason(signal);
|
|
974
|
+
return await new Promise((resolve, reject) => {
|
|
975
|
+
const abort = () => reject(abortReason(signal));
|
|
976
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
977
|
+
Promise.resolve().then(() => {
|
|
978
|
+
if (signal.aborted) throw abortReason(signal);
|
|
979
|
+
return operation();
|
|
980
|
+
}).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
function isCancellation(error, signal) {
|
|
984
|
+
return Boolean(signal?.aborted && error === abortReason(signal));
|
|
985
|
+
}
|
|
986
|
+
async function readProvider(provider, input, signal) {
|
|
987
|
+
try {
|
|
988
|
+
return await withAbort(() => provider.read(input), signal);
|
|
989
|
+
} catch (cause) {
|
|
990
|
+
if (isCancellation(cause, signal)) throw cause;
|
|
991
|
+
throw envSourceFailed("provider", cause);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
function collectProviderKeys(value) {
|
|
995
|
+
const requests = /* @__PURE__ */ new Map();
|
|
996
|
+
for (const { entry } of runtimeRegistryEntries(value)) {
|
|
997
|
+
if (!isRuntimeProviderEntry(entry)) continue;
|
|
998
|
+
let keys = requests.get(entry.source.provider);
|
|
999
|
+
if (!keys) {
|
|
1000
|
+
keys = /* @__PURE__ */ new Set();
|
|
1001
|
+
requests.set(entry.source.provider, keys);
|
|
1002
|
+
}
|
|
1003
|
+
keys.add(entry.source.key);
|
|
1004
|
+
}
|
|
1005
|
+
return requests;
|
|
1006
|
+
}
|
|
1007
|
+
function normalizeProviderValues(value, keys) {
|
|
1008
|
+
let record;
|
|
1009
|
+
try {
|
|
1010
|
+
if (isRecord(value)) record = value;
|
|
1011
|
+
} catch (cause) {
|
|
1012
|
+
throw envSourceFailed("provider", cause);
|
|
1013
|
+
}
|
|
1014
|
+
if (!record) throw invalidRuntimeEnvValue("provider", "A Server Env provider must return a plain record.");
|
|
1015
|
+
let prototype;
|
|
1016
|
+
try {
|
|
1017
|
+
prototype = Object.getPrototypeOf(record);
|
|
1018
|
+
} catch (cause) {
|
|
1019
|
+
throw envSourceFailed("provider", cause);
|
|
1020
|
+
}
|
|
1021
|
+
if (prototype !== null && prototype !== Object.prototype) throw invalidRuntimeEnvValue("provider", "A Server Env provider must return a plain record.");
|
|
1022
|
+
const output = /* @__PURE__ */ new Map();
|
|
1023
|
+
for (const key of keys) {
|
|
1024
|
+
let descriptor;
|
|
1025
|
+
try {
|
|
1026
|
+
descriptor = Object.getOwnPropertyDescriptor(record, key);
|
|
1027
|
+
} catch (cause) {
|
|
1028
|
+
throw envSourceFailed("provider", cause);
|
|
1029
|
+
}
|
|
1030
|
+
if (!descriptor) {
|
|
1031
|
+
output.set(key, void 0);
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
if (!("value" in descriptor)) throw invalidRuntimeEnvValue("provider", "A Server Env provider returned an accessor instead of a value.");
|
|
1035
|
+
output.set(key, descriptor.value);
|
|
1036
|
+
}
|
|
1037
|
+
return output;
|
|
1038
|
+
}
|
|
1039
|
+
function createProviderLoads(registry, localEnv, options) {
|
|
1040
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
1041
|
+
const loads = /* @__PURE__ */ new Map();
|
|
1042
|
+
for (const [name, requested] of collectProviderKeys(registry)) {
|
|
1043
|
+
const keys = Object.freeze([...requested]);
|
|
1044
|
+
const load = Promise.resolve().then(() => providerFor(name, options.providers)).then((provider) => readProvider(provider, {
|
|
1045
|
+
env: localEnv,
|
|
1046
|
+
keys,
|
|
1047
|
+
signal: options.signal,
|
|
1048
|
+
...options.access ? { access: options.access } : {}
|
|
1049
|
+
}, options.signal)).then((value) => normalizeProviderValues(value, keys)).catch((cause) => {
|
|
1050
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
1051
|
+
if (isCancellation(cause, options.signal) || isViteHubError(cause)) throw cause;
|
|
1052
|
+
throw envSourceFailed("provider", cause);
|
|
1053
|
+
});
|
|
1054
|
+
loads.set(name, load);
|
|
1055
|
+
}
|
|
1056
|
+
return loads;
|
|
1057
|
+
}
|
|
1058
|
+
async function providerValue(entry, loads) {
|
|
1059
|
+
const load = loads.get(entry.source.provider);
|
|
1060
|
+
if (!load) throw envSourceFailed("provider", envErrorDiagnostics.ENV_R0021({ message: "The Server Env provider was not loaded." }));
|
|
1061
|
+
return (await load).get(entry.source.key);
|
|
1062
|
+
}
|
|
1063
|
+
const skipProviderValue = Symbol("vitehub.env.skip-provider");
|
|
1064
|
+
function localRegistryValue(value, env, tolerateInvalid, path) {
|
|
1065
|
+
if (isRuntimeLiteralEntry(value)) return snapshotValue(value.value);
|
|
1066
|
+
if (isRuntimeProviderEntry(value)) return skipProviderValue;
|
|
1067
|
+
if (isRuntimeEnvEntry(value)) try {
|
|
1068
|
+
const source = readRuntimeSource(value, env);
|
|
1069
|
+
return resolvedRuntimeValue(value, source.value, source.found, path, true);
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
if (!tolerateInvalid) throw error;
|
|
1072
|
+
return skipProviderValue;
|
|
1073
|
+
}
|
|
1074
|
+
if (!isRecord(value)) return skipProviderValue;
|
|
1075
|
+
const output = Object.create(null);
|
|
1076
|
+
for (const [key, child] of Object.entries(value)) {
|
|
1077
|
+
const resolved = localRegistryValue(child, env, tolerateInvalid, `${path}.${key}`);
|
|
1078
|
+
if (resolved !== skipProviderValue) output[key] = resolved;
|
|
1079
|
+
}
|
|
1080
|
+
return Object.freeze(output);
|
|
1081
|
+
}
|
|
1082
|
+
function createLocalEnv(registry, env, tolerateInvalid) {
|
|
1083
|
+
return localRegistryValue(registry, env, tolerateInvalid, "env.server");
|
|
1084
|
+
}
|
|
1085
|
+
async function loadRegistryValue(value, env, loads, path) {
|
|
1086
|
+
if (isRuntimeLiteralEntry(value)) return snapshotValue(value.value);
|
|
1087
|
+
if (isRuntimeEnvEntry(value)) {
|
|
1088
|
+
const source = readRuntimeSource(value, env);
|
|
1089
|
+
return resolvedRuntimeValue(value, source.value, source.found, path, true);
|
|
1090
|
+
}
|
|
1091
|
+
if (isRuntimeProviderEntry(value)) {
|
|
1092
|
+
const resolved = await providerValue(value, loads);
|
|
1093
|
+
return resolvedRuntimeValue(value, resolved, typeof resolved !== "undefined", path, true);
|
|
1094
|
+
}
|
|
1095
|
+
if (!isRecord(value)) return void 0;
|
|
1096
|
+
const output = Object.create(null);
|
|
1097
|
+
for (const [key, child] of Object.entries(value)) output[key] = await loadRegistryValue(child, env, loads, `${path}.${key}`);
|
|
1098
|
+
return Object.freeze(output);
|
|
1099
|
+
}
|
|
1100
|
+
function snapshotValue(value) {
|
|
1101
|
+
if (Array.isArray(value)) return Object.freeze(value.map(snapshotValue));
|
|
1102
|
+
if (isRecord(value) && Object.getPrototypeOf(value) === Object.prototype) return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshotValue(item)])));
|
|
1103
|
+
return value;
|
|
1104
|
+
}
|
|
1105
|
+
function inspectionStatus(entry, value, found, path) {
|
|
1106
|
+
if (!found && typeof entry.default !== "undefined") return !entry.schemaModule || parseRuntimeValue(entry, entry.default, path).success ? "defaulted" : "invalid";
|
|
1107
|
+
if (!found || typeof value === "undefined") return "missing";
|
|
1108
|
+
return parseRuntimeValue(entry, value, path).success ? "available" : "invalid";
|
|
1109
|
+
}
|
|
1110
|
+
function inspectionPath(path) {
|
|
1111
|
+
if (path.length > 256) return {};
|
|
1112
|
+
return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? { path } : {};
|
|
1113
|
+
}
|
|
1114
|
+
const hostVariableName = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
1115
|
+
/** The host variable names an env declaration reads, in read order. Never values. */
|
|
1116
|
+
function inspectionNames(entry) {
|
|
1117
|
+
const names = (entry.source.names || [entry.source.name]).filter((name) => hostVariableName.test(name));
|
|
1118
|
+
return names.length ? { names } : {};
|
|
1119
|
+
}
|
|
1120
|
+
function inspectionProvider(entry) {
|
|
1121
|
+
return /^[A-Za-z0-9_-]{1,64}$/.test(entry.source.provider) ? { provider: entry.source.provider } : {};
|
|
1122
|
+
}
|
|
1123
|
+
async function inspectRegistryEntry(value, env, options, loads, path, entries) {
|
|
1124
|
+
if (isRuntimeLiteralEntry(value)) {
|
|
1125
|
+
entries.push({
|
|
1126
|
+
masked: false,
|
|
1127
|
+
...inspectionPath(path),
|
|
1128
|
+
required: false,
|
|
1129
|
+
source: "literal",
|
|
1130
|
+
status: "available"
|
|
1131
|
+
});
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
if (isRuntimeEnvEntry(value)) {
|
|
1135
|
+
const source = readRuntimeSource(value, env);
|
|
1136
|
+
const name = source.name !== void 0 && hostVariableName.test(source.name) ? { name: source.name } : {};
|
|
1137
|
+
entries.push({
|
|
1138
|
+
masked: value.secret,
|
|
1139
|
+
...inspectionNames(value),
|
|
1140
|
+
...name,
|
|
1141
|
+
...inspectionPath(path),
|
|
1142
|
+
required: value.required,
|
|
1143
|
+
source: "env",
|
|
1144
|
+
status: inspectionStatus(value, source.value, source.found, path),
|
|
1145
|
+
...runtimeSourceOrigin(value, env, source)
|
|
1146
|
+
});
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
if (isRuntimeProviderEntry(value)) {
|
|
1150
|
+
try {
|
|
1151
|
+
const resolved = await providerValue(value, loads);
|
|
1152
|
+
entries.push({
|
|
1153
|
+
masked: value.secret,
|
|
1154
|
+
...inspectionPath(path),
|
|
1155
|
+
...inspectionProvider(value),
|
|
1156
|
+
required: value.required,
|
|
1157
|
+
source: "provider",
|
|
1158
|
+
status: inspectionStatus(value, resolved, typeof resolved !== "undefined", path)
|
|
1159
|
+
});
|
|
1160
|
+
} catch (error) {
|
|
1161
|
+
if (isCancellation(error, options.signal)) throw error;
|
|
1162
|
+
entries.push({
|
|
1163
|
+
masked: value.secret,
|
|
1164
|
+
...inspectionPath(path),
|
|
1165
|
+
...inspectionProvider(value),
|
|
1166
|
+
required: value.required,
|
|
1167
|
+
source: "provider",
|
|
1168
|
+
status: "error"
|
|
1169
|
+
});
|
|
1170
|
+
}
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
const registryEnvNames = /* @__PURE__ */ new WeakMap();
|
|
1175
|
+
const resolvedServerEnvs = /* @__PURE__ */ new WeakMap();
|
|
1176
|
+
/** The env names a registry reads, or null when it declares an array, list, JSON value, or object, since each call returns its own copy. */
|
|
1177
|
+
function reusableEnvNames(registry) {
|
|
1178
|
+
const known = registryEnvNames.get(registry);
|
|
1179
|
+
if (known !== void 0) return known;
|
|
1180
|
+
let names = [];
|
|
1181
|
+
for (const { entry } of runtimeRegistryEntries(registry)) {
|
|
1182
|
+
if (!isRuntimeEnvEntry(entry)) continue;
|
|
1183
|
+
if (entry.schemaModule || entry.schema?.kind === "array" || entry.schema?.kind === "json" || entry.schema?.kind === "list" || entry.schema?.kind === "object") {
|
|
1184
|
+
names = null;
|
|
1185
|
+
break;
|
|
1186
|
+
}
|
|
1187
|
+
names.push(...entry.source.names || [entry.source.name]);
|
|
1188
|
+
}
|
|
1189
|
+
registryEnvNames.set(registry, names);
|
|
1190
|
+
return names;
|
|
1191
|
+
}
|
|
1192
|
+
/** The values of every name the registry reads, as one string. Undefined when the result must not be reused. */
|
|
1193
|
+
function serverEnvKey(registry, event) {
|
|
1194
|
+
const names = reusableEnvNames(registry);
|
|
1195
|
+
if (!names || getViteHubTestMode()) return void 0;
|
|
1196
|
+
const host = processEnv();
|
|
1197
|
+
const cloudflare = cloudflareEnv(event) ?? {};
|
|
1198
|
+
let key = "";
|
|
1199
|
+
for (const name of names) {
|
|
1200
|
+
const value = Object.hasOwn(cloudflare, name) ? cloudflare[name] : Object.hasOwn(host, name) ? host[name] : void 0;
|
|
1201
|
+
if (value === void 0) key += `${name}\0`;
|
|
1202
|
+
else if (typeof value === "string") key += `${name}=s${value.length}:${value}\0`;
|
|
1203
|
+
else if (typeof value === "number" || typeof value === "boolean") key += `${name}=${typeof value === "number" ? "n" : "b"}${String(value)}\0`;
|
|
1204
|
+
else return void 0;
|
|
1205
|
+
}
|
|
1206
|
+
return key;
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* Apps call `useServerEnv()` on hot paths, often once per listed row. The result is reused while every name the
|
|
1210
|
+
* registry reads holds the same value, so a call does not copy the whole env and parse each declaration again. Each
|
|
1211
|
+
* call still gets its own records.
|
|
1212
|
+
*/
|
|
1213
|
+
function resolveServerEnv(registry, event) {
|
|
1214
|
+
const key = serverEnvKey(registry, event);
|
|
1215
|
+
if (key === void 0) return resolveRegistryValue(registry, runtimeEnv(event), "env.server");
|
|
1216
|
+
let cached = resolvedServerEnvs.get(registry);
|
|
1217
|
+
if (cached?.key !== key) {
|
|
1218
|
+
cached = {
|
|
1219
|
+
key,
|
|
1220
|
+
value: resolveRegistryValue(registry, runtimeEnv(event), "env.server")
|
|
1221
|
+
};
|
|
1222
|
+
resolvedServerEnvs.set(registry, cached);
|
|
1223
|
+
}
|
|
1224
|
+
return isNamespace(cached.value) ? copyNamespaces(cached.value) : cached.value;
|
|
1225
|
+
}
|
|
1226
|
+
async function loadServerEnv(registry, event, options = {}) {
|
|
1227
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
1228
|
+
const env = runtimeEnv(event);
|
|
1229
|
+
const loads = createProviderLoads(registry, createLocalEnv(registry, env, false), options);
|
|
1230
|
+
await Promise.all(loads.values());
|
|
1231
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
1232
|
+
const value = await loadRegistryValue(registry, env, loads, "env.server");
|
|
1233
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
1234
|
+
return value;
|
|
1235
|
+
}
|
|
1236
|
+
/** Describe declarations without loading host values or calling providers. */
|
|
1237
|
+
function describeServerEnv(registry) {
|
|
1238
|
+
const entries = [];
|
|
1239
|
+
for (const { entry: value, path } of runtimeRegistryEntries(registry)) {
|
|
1240
|
+
if (isRuntimeLiteralEntry(value)) {
|
|
1241
|
+
entries.push({
|
|
1242
|
+
...inspectionPath(path),
|
|
1243
|
+
source: "literal",
|
|
1244
|
+
secret: false,
|
|
1245
|
+
required: false,
|
|
1246
|
+
hasDefault: false
|
|
1247
|
+
});
|
|
1248
|
+
continue;
|
|
1249
|
+
}
|
|
1250
|
+
if (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) entries.push({
|
|
1251
|
+
...inspectionPath(path),
|
|
1252
|
+
...isRuntimeEnvEntry(value) ? inspectionNames(value) : {},
|
|
1253
|
+
source: value.source.kind,
|
|
1254
|
+
...isRuntimeProviderEntry(value) ? inspectionProvider(value) : {},
|
|
1255
|
+
secret: value.secret,
|
|
1256
|
+
required: value.required,
|
|
1257
|
+
hasDefault: value.default !== void 0,
|
|
1258
|
+
type: value.schemaModule ? "unknown" : value.secret && value.schema?.kind === "enum" ? "enum" : envValueTypeName(value.schema ?? stringValueSchema)
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
return { entries };
|
|
1262
|
+
}
|
|
1263
|
+
/** Returns whether an inspection entry makes `loadServerEnv()` fail: invalid, provider error, or required and missing. */
|
|
1264
|
+
function isBlockingServerEnvEntry(entry) {
|
|
1265
|
+
return entry.status === "invalid" || entry.status === "error" || entry.required && entry.status === "missing";
|
|
1266
|
+
}
|
|
1267
|
+
async function inspectServerEnv(registry, event, options = {}) {
|
|
1268
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
1269
|
+
const env = runtimeEnv(event);
|
|
1270
|
+
const loads = createProviderLoads(registry, createLocalEnv(registry, env, true), options);
|
|
1271
|
+
await Promise.allSettled(loads.values());
|
|
1272
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
1273
|
+
const entries = [];
|
|
1274
|
+
for (const { entry, path } of runtimeRegistryEntries(registry)) await inspectRegistryEntry(entry, env, options, loads, path, entries);
|
|
1275
|
+
if (options.signal?.aborted) throw abortReason(options.signal);
|
|
1276
|
+
return Object.freeze({ entries: Object.freeze(entries.map((entry) => Object.freeze(entry))) });
|
|
1277
|
+
}
|
|
1278
|
+
//#endregion
|
|
1279
|
+
export { envValueTypeName as A, deriveViteHubSecret as C, verifyViteHubHmacSignature as D, readViteHubSecret as E, stringValueSchema as F, isEnvSchemaValue as I, parseEnvValue as M, readJsonInput as N, verifyViteHubStripeSignature as O, schemaContainsEnum as P, missingRequiredEnv as S, isViteHubBearerSecretEqual as T, runtimeEnv as _, isBlockingServerEnvEntry as a, invalidEnvDeclaration as b, runWithCloudflareEnv as c, unseal as d, invariant as f, runtimeRegistryEntries as g, isRuntimeProviderEntry as h, inspectServerEnv as i, listItemKinds as j, viteHubHmacSha256 as k, createSealing as l, isRuntimeLiteralEntry as m, deriveSecret as n, loadServerEnv as o, isRuntimeEnvEntry as p, describeServerEnv as r, resolveServerEnv as s, bindServerEnvSchemas as t, seal as u, standardSource as v, githubHmacSignatureFormat as w, isAbortError as x, envSourceFailed as y };
|