@vite-hub/env 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +178 -33
- package/dist/{access-B3qzBHye.js → access-B8lSDip4.js} +1 -1
- package/dist/{bridge-CdNdTN1V.d.ts → bridge-Cs9YfQWk.d.ts} +111 -38
- package/dist/{bridge-error-CFuU5zIz.js → bridge-error-BhJ77age.js} +14 -13
- package/dist/bridge.d.ts +2 -2
- package/dist/bridge.js +168 -6
- package/dist/cli-BPp7rdcA.d.ts +159 -0
- package/dist/{cli-CMQPQbii.js → cli-DLpY0QAo.js} +212 -30
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +1 -1
- package/dist/database.d.ts +29 -3
- package/dist/database.js +106 -15
- package/dist/declarations-C5XR3aKw.d.ts +58 -0
- package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
- package/dist/index.d.ts +145 -10
- package/dist/index.js +240 -7
- package/dist/internal/agent.d.ts +1 -1
- package/dist/internal/agent.js +2 -2
- package/dist/internal/connections.d.ts +1 -1
- package/dist/internal/connections.js +2 -2
- package/dist/internal/server.d.ts +3 -0
- package/dist/internal/server.js +2 -0
- package/dist/object-_dlsZ4lP.js +276 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-X1w--wds.js +30 -0
- package/dist/operations.d.ts +37 -0
- package/dist/operations.js +833 -0
- package/dist/runtime/public-env.d.ts +5 -0
- package/dist/runtime/public-env.js +8 -0
- package/dist/runtime/server-env.d.ts +22 -0
- package/dist/runtime/server-env.js +35 -0
- package/dist/schema-DMZ1_yhY.js +360 -0
- package/dist/seal.d.ts +8 -5
- package/dist/seal.js +9 -6
- package/dist/{secret.js → secret-DJd-fy5T.js} +1 -1
- package/dist/server-ChNL_Xc3.js +1279 -0
- package/dist/server-Dd8bjIKd.d.ts +145 -0
- package/dist/server.d.ts +3 -25
- package/dist/server.js +2 -2
- package/dist/virtual-module.d.ts +6 -6
- package/dist/vite.d.ts +59 -14
- package/dist/vite.js +304 -115
- package/package.json +27 -38
- package/dist/auth.d.ts +0 -32
- package/dist/auth.js +0 -44
- package/dist/cli-DEwcUIe0.d.ts +0 -81
- package/dist/declarations-CiRdb1qP.d.ts +0 -32
- package/dist/declarations-DAVgctKD.js +0 -236
- package/dist/error-diagnostics-CrxjYNYr.js +0 -43
- package/dist/http.d.ts +0 -2
- package/dist/http.js +0 -122
- package/dist/presets.d.ts +0 -20
- package/dist/presets.js +0 -44
- package/dist/provider.d.ts +0 -5
- package/dist/provider.js +0 -8
- package/dist/schema.d.ts +0 -15
- package/dist/schema.js +0 -55
- package/dist/secret-C2191nAa.d.ts +0 -11
- package/dist/secret.d.ts +0 -2
- package/dist/server-DufVswRJ.js +0 -670
- package/dist/values-D_r6V774.js +0 -148
package/dist/database.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { t as envBridgeError } from "./bridge-error-
|
|
2
|
-
import { importSealKey,
|
|
1
|
+
import { t as envBridgeError } from "./bridge-error-BhJ77age.js";
|
|
2
|
+
import { importSealKey, sealKeyId, sealWithKey, sealedPayloadPattern, unsealWithKey } from "./seal.js";
|
|
3
|
+
import { ViteHubError } from "@vite-hub/runtime";
|
|
3
4
|
import * as v from "valibot";
|
|
4
5
|
import { sql } from "drizzle-orm";
|
|
5
6
|
//#region src/database.ts
|
|
7
|
+
/** A stored value: `v2:<keyId>:<iv>:<ciphertext>`, or a legacy `<iv>:<ciphertext>` without a key id. */
|
|
8
|
+
const storedPayloadPattern = new RegExp(`^(?:v2:[a-f0-9]{16}:)?${sealedPayloadPattern.source.slice(1, -1)}$`);
|
|
6
9
|
const identifier = v.pipe(v.string(), v.minLength(1), v.maxLength(512), v.regex(/^[^\u0000-\u001f]+$/));
|
|
7
10
|
const actor = v.object({
|
|
8
11
|
id: identifier,
|
|
@@ -29,6 +32,7 @@ const activity = v.object({
|
|
|
29
32
|
"inspect",
|
|
30
33
|
"preview",
|
|
31
34
|
"replace",
|
|
35
|
+
"remove",
|
|
32
36
|
"resolve",
|
|
33
37
|
"use",
|
|
34
38
|
"grant",
|
|
@@ -53,7 +57,7 @@ const grant = v.object({
|
|
|
53
57
|
permissions: v.pipe(v.array(permission), v.minLength(1))
|
|
54
58
|
});
|
|
55
59
|
const secretRow = v.object({
|
|
56
|
-
payload: v.pipe(v.string(), v.regex(
|
|
60
|
+
payload: v.pipe(v.string(), v.regex(storedPayloadPattern)),
|
|
57
61
|
revision: identifier,
|
|
58
62
|
updated_at: timestamp,
|
|
59
63
|
preview: v.nullable(v.string())
|
|
@@ -72,6 +76,33 @@ const grantRow = v.object({
|
|
|
72
76
|
actor_id: identifier
|
|
73
77
|
});
|
|
74
78
|
const revisionRow = v.object({ revision: identifier });
|
|
79
|
+
const listRow = v.object({
|
|
80
|
+
key: identifier,
|
|
81
|
+
revision: identifier,
|
|
82
|
+
updated_at: timestamp,
|
|
83
|
+
preview: v.nullable(v.string())
|
|
84
|
+
});
|
|
85
|
+
const namespaceRow = v.object({ namespace: v.string() });
|
|
86
|
+
/** Create the Env tables when they are missing. Each store and `listDatabaseEnvNamespaces()` calls it first. */
|
|
87
|
+
async function createEnvTables(db) {
|
|
88
|
+
await db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_env_secrets (namespace TEXT NOT NULL, key TEXT NOT NULL, payload TEXT NOT NULL, revision TEXT NOT NULL, updated_at TEXT NOT NULL, preview TEXT, PRIMARY KEY (namespace, key))`);
|
|
89
|
+
await db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_env_activity (sequence INTEGER PRIMARY KEY AUTOINCREMENT, namespace TEXT NOT NULL, key TEXT NOT NULL, id TEXT NOT NULL UNIQUE, payload TEXT NOT NULL)`);
|
|
90
|
+
await db.run(sql`CREATE INDEX IF NOT EXISTS vitehub_env_activity_key ON vitehub_env_activity (namespace, key, sequence)`);
|
|
91
|
+
await db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_env_grants (namespace TEXT NOT NULL, key TEXT NOT NULL, actor_kind TEXT NOT NULL, actor_id TEXT NOT NULL, payload TEXT NOT NULL, PRIMARY KEY (namespace, key, actor_kind, actor_id))`);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The namespaces that start with `prefix` and hold at least one key, in text order. A Console that keeps one namespace
|
|
95
|
+
* for each project and stage, such as `<project>:production`, finds the stages of a project with it.
|
|
96
|
+
*/
|
|
97
|
+
async function listDatabaseEnvNamespaces(db, prefix) {
|
|
98
|
+
await createEnvTables(db);
|
|
99
|
+
return (await db.all(sql`SELECT DISTINCT namespace FROM vitehub_env_secrets WHERE substr(namespace, 1, ${prefix.length}) = ${prefix} ORDER BY namespace`)).map((row) => v.parse(namespaceRow, row).namespace);
|
|
100
|
+
}
|
|
101
|
+
const rotationRow = v.object({
|
|
102
|
+
key: identifier,
|
|
103
|
+
payload: v.pipe(v.string(), v.regex(storedPayloadPattern)),
|
|
104
|
+
revision: identifier
|
|
105
|
+
});
|
|
75
106
|
function parseStoredJson(payload) {
|
|
76
107
|
try {
|
|
77
108
|
return JSON.parse(payload);
|
|
@@ -79,18 +110,40 @@ function parseStoredJson(payload) {
|
|
|
79
110
|
throw envBridgeError("invalid");
|
|
80
111
|
}
|
|
81
112
|
}
|
|
82
|
-
/**
|
|
113
|
+
/**
|
|
114
|
+
* Persistent encrypted values, activity, and grants on a ViteHub SQLite/Drizzle database.
|
|
115
|
+
* `encryptionKeys` is the keyring: the current 32-byte key first, then previous keys that still decrypt older values.
|
|
116
|
+
*/
|
|
83
117
|
function createDatabaseEnvStore(options) {
|
|
84
|
-
if (options.
|
|
118
|
+
if (!options.encryptionKeys.length || options.encryptionKeys.some((key) => key.byteLength !== 32)) throw envBridgeError("invalid");
|
|
85
119
|
const namespace = options.namespace ?? "default";
|
|
86
|
-
|
|
120
|
+
let keyring;
|
|
121
|
+
const keys = () => keyring ??= Promise.all(options.encryptionKeys.map(async (key) => ({
|
|
122
|
+
id: await sealKeyId(key),
|
|
123
|
+
key: await importSealKey(key)
|
|
124
|
+
})));
|
|
125
|
+
async function seal(key, revision, value) {
|
|
126
|
+
const [current] = await keys();
|
|
127
|
+
return `v2:${current.id}:${await sealWithKey(current.key, aad(key, revision), value)}`;
|
|
128
|
+
}
|
|
129
|
+
async function unseal(key, revision, payload) {
|
|
130
|
+
const additionalData = aad(key, revision);
|
|
131
|
+
if (payload.startsWith("v2:")) {
|
|
132
|
+
const id = payload.slice(3, 19);
|
|
133
|
+
const match = (await keys()).find((candidate) => candidate.id === id);
|
|
134
|
+
if (!match) throw new ViteHubError("SEAL_INVALID", `No configured encryption key has the key id ${id}. Add the key that sealed this value to the keyring.`);
|
|
135
|
+
return await unsealWithKey(match.key, additionalData, payload.slice(20));
|
|
136
|
+
}
|
|
137
|
+
let failure;
|
|
138
|
+
for (const candidate of await keys()) try {
|
|
139
|
+
return await unsealWithKey(candidate.key, additionalData, payload);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
failure ??= error;
|
|
142
|
+
}
|
|
143
|
+
throw failure;
|
|
144
|
+
}
|
|
87
145
|
let ready;
|
|
88
|
-
const initialize = () => ready ??= (
|
|
89
|
-
await options.db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_env_secrets (namespace TEXT NOT NULL, key TEXT NOT NULL, payload TEXT NOT NULL, revision TEXT NOT NULL, updated_at TEXT NOT NULL, preview TEXT, PRIMARY KEY (namespace, key))`);
|
|
90
|
-
await options.db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_env_activity (sequence INTEGER PRIMARY KEY AUTOINCREMENT, namespace TEXT NOT NULL, key TEXT NOT NULL, id TEXT NOT NULL UNIQUE, payload TEXT NOT NULL)`);
|
|
91
|
-
await options.db.run(sql`CREATE INDEX IF NOT EXISTS vitehub_env_activity_key ON vitehub_env_activity (namespace, key, sequence)`);
|
|
92
|
-
await options.db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_env_grants (namespace TEXT NOT NULL, key TEXT NOT NULL, actor_kind TEXT NOT NULL, actor_id TEXT NOT NULL, payload TEXT NOT NULL, PRIMARY KEY (namespace, key, actor_kind, actor_id))`);
|
|
93
|
-
})().catch((error) => {
|
|
146
|
+
const initialize = () => ready ??= createEnvTables(options.db).catch((error) => {
|
|
94
147
|
ready = void 0;
|
|
95
148
|
throw error;
|
|
96
149
|
});
|
|
@@ -107,10 +160,48 @@ function createDatabaseEnvStore(options) {
|
|
|
107
160
|
]));
|
|
108
161
|
}
|
|
109
162
|
return {
|
|
163
|
+
async rotate() {
|
|
164
|
+
await initialize();
|
|
165
|
+
const [current] = await keys();
|
|
166
|
+
const rows = await options.db.all(sql`SELECT key, payload, revision FROM vitehub_env_secrets WHERE namespace = ${namespace} ORDER BY key`);
|
|
167
|
+
let rotated = 0;
|
|
168
|
+
let skipped = 0;
|
|
169
|
+
for (const row of rows) {
|
|
170
|
+
const stored = v.parse(rotationRow, row);
|
|
171
|
+
if (stored.payload.startsWith(`v2:${current.id}:`)) {
|
|
172
|
+
skipped++;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
const value = await unseal(stored.key, stored.revision, stored.payload);
|
|
176
|
+
const payload = await seal(stored.key, stored.revision, value);
|
|
177
|
+
if ((await options.db.all(sql`UPDATE vitehub_env_secrets SET payload = ${payload} WHERE namespace = ${namespace} AND key = ${stored.key} AND revision = ${stored.revision} AND payload = ${stored.payload} RETURNING key`)).length) rotated++;
|
|
178
|
+
else skipped++;
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
rotated,
|
|
182
|
+
skipped
|
|
183
|
+
};
|
|
184
|
+
},
|
|
110
185
|
async revisionCondition(key, revision) {
|
|
111
186
|
await initialize();
|
|
112
187
|
return revision === null ? sql`NOT EXISTS (SELECT 1 FROM vitehub_env_secrets WHERE namespace = ${namespace} AND key = ${key})` : sql`EXISTS (SELECT 1 FROM vitehub_env_secrets WHERE namespace = ${namespace} AND key = ${key} AND revision = ${revision})`;
|
|
113
188
|
},
|
|
189
|
+
async list() {
|
|
190
|
+
await initialize();
|
|
191
|
+
return (await options.db.all(sql`SELECT key, revision, updated_at, preview FROM vitehub_env_secrets WHERE namespace = ${namespace} ORDER BY key`)).map((row) => {
|
|
192
|
+
const stored = v.parse(listRow, row);
|
|
193
|
+
return {
|
|
194
|
+
key: stored.key,
|
|
195
|
+
revision: stored.revision,
|
|
196
|
+
updatedAt: stored.updated_at,
|
|
197
|
+
...stored.preview ? { preview: stored.preview } : {}
|
|
198
|
+
};
|
|
199
|
+
});
|
|
200
|
+
},
|
|
201
|
+
async remove(key) {
|
|
202
|
+
await initialize();
|
|
203
|
+
return (await options.db.all(sql`DELETE FROM vitehub_env_secrets WHERE namespace = ${namespace} AND key = ${key} RETURNING revision`)).length > 0;
|
|
204
|
+
},
|
|
114
205
|
secrets: {
|
|
115
206
|
async inspect(key) {
|
|
116
207
|
const stored = await row(key);
|
|
@@ -124,7 +215,7 @@ function createDatabaseEnvStore(options) {
|
|
|
124
215
|
const stored = await row(key);
|
|
125
216
|
if (!stored) return;
|
|
126
217
|
return {
|
|
127
|
-
value: await unseal(
|
|
218
|
+
value: await unseal(key, stored.revision, stored.payload),
|
|
128
219
|
revision: stored.revision
|
|
129
220
|
};
|
|
130
221
|
},
|
|
@@ -132,7 +223,7 @@ function createDatabaseEnvStore(options) {
|
|
|
132
223
|
await initialize();
|
|
133
224
|
const revision = crypto.randomUUID();
|
|
134
225
|
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
135
|
-
const payload = await seal(
|
|
226
|
+
const payload = await seal(key, revision, value);
|
|
136
227
|
const preview = options.previews && value.length > 12 && /^[A-Za-z0-9_.-]+$/.test(value) ? `${value.slice(0, 4)}••••${value.slice(-4)}` : null;
|
|
137
228
|
const written = expectedRevision === null ? await options.db.all(sql`INSERT INTO vitehub_env_secrets (namespace, key, payload, revision, updated_at, preview) VALUES (${namespace}, ${key}, ${payload}, ${revision}, ${updatedAt}, ${preview}) ON CONFLICT (namespace, key) DO NOTHING RETURNING revision`) : await options.db.all(sql`UPDATE vitehub_env_secrets SET payload = ${payload}, revision = ${revision}, updated_at = ${updatedAt}, preview = ${preview} WHERE namespace = ${namespace} AND key = ${key} AND revision = ${expectedRevision} RETURNING revision`);
|
|
138
229
|
if (!written.length) throw envBridgeError("conflict");
|
|
@@ -180,4 +271,4 @@ function createDatabaseEnvStore(options) {
|
|
|
180
271
|
};
|
|
181
272
|
}
|
|
182
273
|
//#endregion
|
|
183
|
-
export { createDatabaseEnvStore };
|
|
274
|
+
export { createDatabaseEnvStore, listDatabaseEnvNamespaces };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { F as EnvTypedVariableOptions, L as EnvVariableDeclaration, M as EnvSource, P as EnvSourceResolver, R as EnvVariableOptions, j as EnvSchemaModuleReference } from "./bridge-Cs9YfQWk.js";
|
|
2
|
+
//#region src/core/declarations.d.ts
|
|
3
|
+
type EnvListItem = boolean | number | string;
|
|
4
|
+
interface StandardSchemaLike {
|
|
5
|
+
"~standard": {
|
|
6
|
+
validate: (value: unknown) => unknown;
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
interface EnvNamespace {
|
|
10
|
+
(options?: EnvVariableOptions): EnvVariableDeclaration;
|
|
11
|
+
/** Parse `true`, `false`, `1`, or `0` into a boolean. */
|
|
12
|
+
boolean: (options?: EnvTypedVariableOptions<boolean>) => EnvVariableDeclaration;
|
|
13
|
+
buildTimestamp: () => EnvSource;
|
|
14
|
+
custom: (label: string, resolver: EnvSourceResolver) => EnvSource;
|
|
15
|
+
/** Accept only the listed strings. The values are public metadata, so an enum cannot be secret. */
|
|
16
|
+
enum: <const TValues extends readonly [string, ...string[]]>(values: TValues, options?: EnvTypedVariableOptions<TValues[number]> & {
|
|
17
|
+
secret?: never;
|
|
18
|
+
}) => EnvVariableDeclaration;
|
|
19
|
+
/** The current branch: `GIT_BRANCH`, then `GITHUB_HEAD_REF`, then `GITHUB_REF_NAME` on a GitHub branch ref, then local Git. */
|
|
20
|
+
gitBranch: () => EnvSource;
|
|
21
|
+
/** The current commit SHA: `GIT_SHA`, then `GITHUB_SHA`, then local Git. `short` keeps 7 characters of a CI value. */
|
|
22
|
+
gitCommit: (options?: {
|
|
23
|
+
short?: boolean;
|
|
24
|
+
}) => EnvSource;
|
|
25
|
+
/** The current tag, or `undefined`: `GIT_TAG`, then `GITHUB_REF_NAME` on a GitHub tag ref, then local Git. */
|
|
26
|
+
gitTag: () => EnvSource;
|
|
27
|
+
/**
|
|
28
|
+
* Parse a JSON value. In `env.server`, validate it with `env.json(env.schemaFrom(module, exportName))`.
|
|
29
|
+
* With `mode: "build"`, pass the Standard Schema itself. Without a schema, the value is `unknown`.
|
|
30
|
+
*/
|
|
31
|
+
json: {
|
|
32
|
+
(options?: EnvTypedVariableOptions<unknown>): EnvVariableDeclaration;
|
|
33
|
+
(schema: EnvSchemaModuleReference | StandardSchemaLike, options?: EnvTypedVariableOptions<unknown>): EnvVariableDeclaration;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Parse a list separated by commas or line breaks. Items are trimmed and empty items are dropped. Pass `env.number()`, `env.boolean()`,
|
|
37
|
+
* or `env.enum()` to parse each item, for example `env.list(env.number())`.
|
|
38
|
+
*/
|
|
39
|
+
list: {
|
|
40
|
+
(options?: EnvTypedVariableOptions<readonly EnvListItem[]>): EnvVariableDeclaration;
|
|
41
|
+
(item: EnvVariableDeclaration, options?: EnvTypedVariableOptions<readonly EnvListItem[]>): EnvVariableDeclaration;
|
|
42
|
+
};
|
|
43
|
+
/** Parse a finite number. */
|
|
44
|
+
number: (options?: EnvTypedVariableOptions<number>) => EnvVariableDeclaration;
|
|
45
|
+
packageJson: (path: string) => EnvSource;
|
|
46
|
+
provider: (provider: string, key: string) => EnvSource;
|
|
47
|
+
/**
|
|
48
|
+
* Validate a Server Env value with a Standard Schema exported by a module, for example `env.schemaFrom("./server/env.schema.ts", "apiUrl")`.
|
|
49
|
+
* The server build imports the module, so refinements and transforms run on every resolution.
|
|
50
|
+
*/
|
|
51
|
+
schemaFrom: (module: string, exportName?: string) => EnvSchemaModuleReference;
|
|
52
|
+
source: (name: string | string[], options?: {
|
|
53
|
+
canonical?: boolean;
|
|
54
|
+
}) => EnvSource;
|
|
55
|
+
}
|
|
56
|
+
declare const env: EnvNamespace;
|
|
57
|
+
//#endregion
|
|
58
|
+
export { env as t };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { defineDiagnostics } from "nostics";
|
|
2
|
+
//#region src/error-diagnostics.ts
|
|
3
|
+
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
4
|
+
/** A code whose call site passes the message as `why`. Pass the fix as a string literal: the docs catalog reads only literals. */
|
|
5
|
+
const withFix = (fix) => ({
|
|
6
|
+
...dynamicError,
|
|
7
|
+
fix
|
|
8
|
+
});
|
|
9
|
+
const envErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
10
|
+
docsBase: "https://vitehub.dev/docs/env/diagnostics",
|
|
11
|
+
codes: {
|
|
12
|
+
ENV_R0001: withFix("Change the value so that it matches the type of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
|
|
13
|
+
ENV_R0002: withFix("Pass one or more variable names, for example `env.source('DATABASE_URL')`."),
|
|
14
|
+
ENV_R0003: withFix("Use a key of `vitehub({ env: { providers } })` or `hubEnv({ providers })` as the provider name, for example `env.provider('vault', 'db/password')`."),
|
|
15
|
+
ENV_R0004: withFix("Pass the key that the provider reads as the second argument, for example `env.provider('vault', 'db/password')`."),
|
|
16
|
+
ENV_R0005: withFix("Pass one plain options object, for example `env({ secret: true })`."),
|
|
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
|
+
ENV_R0008: withFix("Change the Env declaration at the path in the error details, as the message says."),
|
|
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 it 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
|
+
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
|
+
ENV_R0012: withFix("Make package.json contain one JSON object."),
|
|
23
|
+
ENV_R0013: withFix("Pass an object with a `read({ env, keys, signal })` method to `defineEnvProvider()`."),
|
|
24
|
+
ENV_R0014: withFix("Use a schema that validates without a Promise for this variable."),
|
|
25
|
+
ENV_R0015: withFix("Change the value so that it matches the schema of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
|
|
26
|
+
ENV_R0016: withFix("Change the value so that it matches the schema of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
|
|
27
|
+
ENV_R0017: withFix("Change the value so that it matches the schema of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
|
|
28
|
+
ENV_R0018: withFix("Change the value so that it matches the schema of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
|
|
29
|
+
ENV_R0019: withFix("Make the provider module default-export `defineEnvProvider({ read })`, and list it in `vitehub({ env: { providers } })` or `hubEnv({ providers })`. If you call `loadServerEnv()` directly, pass the provider in `options.providers`."),
|
|
30
|
+
ENV_R0020: withFix("The caller aborted the load. Load Server Env again with a signal that is not aborted."),
|
|
31
|
+
ENV_R0021: withFix("This is a ViteHub bug. Report it at https://github.com/vite-hub/vitehub/issues with the message and your Vite config."),
|
|
32
|
+
ENV_R0022: withFix("Pass unique, non-empty strings, for example `env.enum(['development', 'production'])`."),
|
|
33
|
+
ENV_R0023: withFix("Change the `default` so that it matches the schema, for example a number for `env.number()`."),
|
|
34
|
+
ENV_R0025: withFix("Put a stage name after `--stage`, for example `vitehub env check --stage production`."),
|
|
35
|
+
ENV_R0026: withFix("Remove the option. `vitehub env <command> --help` lists the options."),
|
|
36
|
+
ENV_R0027: withFix("Add `vitehub()` or `hubEnv()` to the Vite plugins of the selected stage."),
|
|
37
|
+
ENV_R0028: withFix("This is a ViteHub bug. Report it at https://github.com/vite-hub/vitehub/issues with the message and your Vite config."),
|
|
38
|
+
ENV_R0029: withFix("Pass a non-empty module specifier and an export name that is a JavaScript identifier, for example `env.schemaFrom('./server/env.schema.ts', 'apiUrl')`. Use `env.schemaFrom()` only in `env.server`. Elsewhere, pass the schema object itself."),
|
|
39
|
+
ENV_R0030: withFix("Configure Vite's SSR environment with a RunnableDevEnvironment so Env can import its server module."),
|
|
40
|
+
ENV_B0001: withFix("Add `vitehub()` or `hubEnv()` to the Vite plugins once. If it is there, report a ViteHub bug at https://github.com/vite-hub/vitehub/issues with your Vite config."),
|
|
41
|
+
ENV_B0002: withFix("Rename the key in `vitehub({ env: { providers } })` or `hubEnv({ providers })`, for example `vault` or `aws_secrets`. Use at most 64 characters."),
|
|
42
|
+
ENV_B0003: withFix("Set the provider to a module specifier, for example `'./server/env-provider.ts'` or a package name."),
|
|
43
|
+
ENV_B0004: withFix("Use a relative path, a normal absolute path, or a package name for the provider module."),
|
|
44
|
+
ENV_B0005: withFix("Add the provider to `vitehub({ env: { providers } })` or `hubEnv({ providers })`, or use a configured provider name in `env.provider()`."),
|
|
45
|
+
ENV_B0006: withFix("Change the env-spec schema file at the file and line that the message names, so that it follows the env-spec format."),
|
|
46
|
+
ENV_B0007: withFix("Stop other Vite processes of this project. If none runs, delete `.vitehub/env/secret.lock` and run the command again."),
|
|
47
|
+
ENV_JSON_SCHEMA_INVALID: withFix("In `env.server`, export the Standard Schema from a module and pass `env.json(env.schemaFrom('./server/env.schema.ts', 'settings'))`. With `mode: 'build'`, pass the schema object itself. Without a schema, call `env.json()` or `env.json({ default: {} })`."),
|
|
48
|
+
ENV_LIST_ITEM_INVALID: withFix("Pass the item parser without options, for example `env.list(env.number())` or `env.list(env.enum(['a', 'b']))`, and put `default`, `secret`, `source`, or `optional` on the list: `env.list(env.number(), { default: [1] })`."),
|
|
49
|
+
ENV_NOT_GENERATED: {
|
|
50
|
+
why: ({ accessor }) => `\`${accessor}()\` ran outside a Vite build, so ViteHub did not generate the Env registry that it reads.`,
|
|
51
|
+
fix: "Run the code through `vite dev`, `vite build`, or a framework that uses them, with `vitehub()` and Env on. A test that calls it needs the Vite plugin too."
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
//#endregion
|
|
56
|
+
export { envErrorDiagnostics as t };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,146 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { t as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
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
|
+
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-Dd8bjIKd.js";
|
|
4
|
+
import { Result, ViteHubError } from "@vite-hub/runtime";
|
|
5
|
+
import { deriveSecret, describeServerEnv, inspectServerEnv, loadServerEnv, runWithServerEnv, useServerEnv } from "#vitehub/env/server";
|
|
6
|
+
import { usePublicEnv } from "#vitehub/env/public";
|
|
7
|
+
//#region src/presets.d.ts
|
|
8
|
+
interface OpenWorkflowEnvOptions {
|
|
9
|
+
namespaceId?: string;
|
|
10
|
+
schema?: string;
|
|
11
|
+
workerConcurrency?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function openWorkflowEnv(options?: OpenWorkflowEnvOptions): EnvRuntimeConfigOptions;
|
|
14
|
+
interface TypesafeEnvOptions {
|
|
15
|
+
/** Default model when `TYPESAFE_DEFAULT_MODEL` is not set. Default: `jev-latest`. */
|
|
16
|
+
model?: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Declares the Server Env of the `typesafe()` AI gateway from `vite-hub/gateways`: Secret `apiKey`
|
|
20
|
+
* (`TYPESAFE_API_KEY`) and `model` (`TYPESAFE_DEFAULT_MODEL`). `defineAgent({ driver: { ask } })` uses `typesafe()`
|
|
21
|
+
* when it gets no other gateway. The values are optional here: Jev diagnoses a
|
|
22
|
+
* missing key when it runs, so an application without AI still starts.
|
|
23
|
+
*/
|
|
24
|
+
export declare function typesafeEnv(options?: TypesafeEnvOptions): EnvRuntimeConfigOptions;
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/provider.d.ts
|
|
27
|
+
export declare function defineEnvProvider<TEnv extends Record<string, unknown> = Record<string, unknown>, const TProvider extends EnvProvider<TEnv> = EnvProvider<TEnv>>(provider: TProvider): TProvider;
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/service-token.d.ts
|
|
30
|
+
/** The codes that `checkServiceToken()` returns. */
|
|
31
|
+
type ServiceTokenErrorCode = "ENV_SERVICE_TOKEN_INVALID" | "ENV_SERVICE_TOKEN_UNSET";
|
|
32
|
+
/**
|
|
33
|
+
* The request to check: an H3 event, another event with Standard Context, or a web `Request`. An H3 event matches
|
|
34
|
+
* `{ req }` even when the app does not load the types that add `~standard` to it.
|
|
35
|
+
*/
|
|
36
|
+
type ServiceTokenEvent = RequestEvent;
|
|
37
|
+
/**
|
|
38
|
+
* Checks that a request carries `Authorization: Bearer <token>` with a token from the host variable `name`, and
|
|
39
|
+
* returns `[error, undefined]`. The variable holds one token, or a comma-separated list, so the old and the new token
|
|
40
|
+
* both pass while you rotate. It compares in constant time. Without a token in the variable, every request fails with
|
|
41
|
+
* `ENV_SERVICE_TOKEN_UNSET`.
|
|
42
|
+
*
|
|
43
|
+
* ```ts [server/api/health.get.ts]
|
|
44
|
+
* import { defineEventHandler } from "h3"
|
|
45
|
+
* import { checkServiceToken } from "vite-hub/env"
|
|
46
|
+
*
|
|
47
|
+
* export default defineEventHandler((event) => {
|
|
48
|
+
* const [error] = checkServiceToken(event, "ADMIN_TOKEN")
|
|
49
|
+
* return error ? { ok: true } : { ok: true, queue: 3 }
|
|
50
|
+
* })
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export declare function checkServiceToken(event: ServiceTokenEvent, name: string): Result<void, ServiceTokenErrorCode>;
|
|
54
|
+
/**
|
|
55
|
+
* Returns when a request carries `Authorization: Bearer <token>` with a token from the host variable `name`. Otherwise
|
|
56
|
+
* it throws an `HTTPError`: `401` with `ENV_SERVICE_TOKEN_INVALID`, or `503` with `ENV_SERVICE_TOKEN_UNSET` when the
|
|
57
|
+
* variable has no token. Use it for routes that scripts, runners, and webhooks call.
|
|
58
|
+
*
|
|
59
|
+
* ```ts [server/api/ingest.post.ts]
|
|
60
|
+
* import { defineEventHandler } from "h3"
|
|
61
|
+
* import { requireServiceToken } from "vite-hub/env"
|
|
62
|
+
*
|
|
63
|
+
* export default defineEventHandler((event) => {
|
|
64
|
+
* requireServiceToken(event, "INGEST_TOKEN")
|
|
65
|
+
* return { ok: true }
|
|
66
|
+
* })
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export declare function requireServiceToken(event: ServiceTokenEvent, name: string): void;
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region src/webhook.d.ts
|
|
72
|
+
/** The codes that `verifyWebhook()` returns. */
|
|
73
|
+
type WebhookErrorCode = "ENV_WEBHOOK_BODY_INVALID" | "ENV_WEBHOOK_SECRET_UNSET" | "ENV_WEBHOOK_SIGNATURE_INVALID";
|
|
74
|
+
/** How `verifyWebhook()` checks the signature. `secret` is the name of the server variable that holds the signing secret. */
|
|
75
|
+
type VerifyWebhookOptions = {
|
|
76
|
+
/** `Stripe-Signature: t=<time>,v1=<HMAC-SHA256 of "<time>.<body>">`. */
|
|
77
|
+
provider: "stripe";
|
|
78
|
+
/** The name of the server variable with the endpoint's signing secret (`whsec_...`), such as `"STRIPE_WEBHOOK_SECRET"`. */
|
|
79
|
+
secret: string;
|
|
80
|
+
/** How old the signed time can be, in seconds. Default: `300`, as in Stripe's SDKs. */
|
|
81
|
+
toleranceSeconds?: number;
|
|
82
|
+
} | {
|
|
83
|
+
/** `X-Hub-Signature-256: sha256=<HMAC-SHA256 of the body>`. */
|
|
84
|
+
provider: "github";
|
|
85
|
+
/** The name of the server variable with the webhook secret, such as `"GITHUB_WEBHOOK_SECRET"`. */
|
|
86
|
+
secret: string;
|
|
87
|
+
} | {
|
|
88
|
+
/** `header` carries `prefix` followed by the HMAC-SHA256 of the body. */
|
|
89
|
+
provider: "hmac";
|
|
90
|
+
/** The name of the server variable with the signing key, such as `"AIRTABLE_WEBHOOK_SECRET"`. */
|
|
91
|
+
secret: string;
|
|
92
|
+
/** The header that carries the signature, such as `"x-airtable-content-mac"`. */
|
|
93
|
+
header: string;
|
|
94
|
+
/** The text before the digest, such as `"hmac-sha256="`. Default: none. */
|
|
95
|
+
prefix?: string;
|
|
96
|
+
/** The digest encoding in the header. Default: `"hex"`, compared without case. */
|
|
97
|
+
encoding?: "hex" | "base64";
|
|
98
|
+
/** How the variable encodes the key. `"base64"` decodes it first. Default: `"utf8"`. */
|
|
99
|
+
secretEncoding?: "utf8" | "base64";
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Checks the signature of a webhook that Stripe, GitHub, or another provider sends to a route, and returns
|
|
103
|
+
* `[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. It reads the raw body once, so do not read the body before you call it.
|
|
105
|
+
* It reads the secret from the server variable `secret` on each request. The variable holds one secret, or a
|
|
106
|
+
* comma-separated list while you rotate. It compares in constant time and runs on every host.
|
|
107
|
+
*
|
|
108
|
+
* ```ts [server/api/stripe/webhook.post.ts]
|
|
109
|
+
* import { defineEventHandler, HTTPError } from "h3"
|
|
110
|
+
* import { verifyWebhook } from "vite-hub/env"
|
|
111
|
+
*
|
|
112
|
+
* export default defineEventHandler(async (event) => {
|
|
113
|
+
* const [error, stripeEvent] = await verifyWebhook<{ type: string }>(event, { provider: "stripe", secret: "STRIPE_WEBHOOK_SECRET" })
|
|
114
|
+
* if (error) throw new HTTPError({ status: 400, message: error.message })
|
|
115
|
+
* return { received: stripeEvent.type }
|
|
116
|
+
* })
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
export declare function verifyWebhook<TBody = unknown>(event: RequestEvent, options: VerifyWebhookOptions): Promise<Result<TBody, WebhookErrorCode>>;
|
|
120
|
+
/** How `signWebhook()` signs an outgoing body. */
|
|
121
|
+
interface SignWebhookOptions {
|
|
122
|
+
/** `"github"` sets `x-hub-signature-256`. `"stripe"` sets `stripe-signature` with the time. */
|
|
123
|
+
provider: "github" | "stripe";
|
|
124
|
+
/** The signing secret itself, not the name of a variable. The receiver must have the same secret. */
|
|
125
|
+
secret: string;
|
|
126
|
+
/** The signed time for `"stripe"`, in Unix seconds. Default: now. */
|
|
127
|
+
timestamp?: number;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Signs the raw body of an outgoing webhook with HMAC-SHA256 and returns the headers to send with it. The receiver
|
|
131
|
+
* checks them with `verifyWebhook()` or the provider's own SDK. Send the exact `body` that you signed. It uses Web
|
|
132
|
+
* Crypto only, so it runs on every host.
|
|
133
|
+
*
|
|
134
|
+
* ```ts
|
|
135
|
+
* import { signWebhook } from "vite-hub/env"
|
|
136
|
+
*
|
|
137
|
+
* const body = JSON.stringify({ type: "deploy.finished" })
|
|
138
|
+
* const headers = await signWebhook(body, { provider: "github", secret: process.env.HOOK_SECRET! })
|
|
139
|
+
* await fetch("https://example.com/hook", { method: "POST", body, headers: { ...headers, "content-type": "application/json" } })
|
|
140
|
+
* ```
|
|
141
|
+
*/
|
|
142
|
+
export declare function signWebhook(body: string | Uint8Array<ArrayBuffer>, options: SignWebhookOptions): Promise<Record<string, string>>;
|
|
143
|
+
//#endregion
|
|
9
144
|
//#region src/core/errors.d.ts
|
|
10
145
|
declare const envErrorMessages: {
|
|
11
146
|
readonly ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.";
|
|
@@ -14,7 +149,7 @@ declare const envErrorMessages: {
|
|
|
14
149
|
readonly ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.";
|
|
15
150
|
readonly ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed.";
|
|
16
151
|
};
|
|
17
|
-
declare const envSourceIdentifiers: readonly ["custom", "env", "git:branch", "git:commit", "git:
|
|
152
|
+
declare const envSourceIdentifiers: readonly ["custom", "env", "git:branch", "git:commit", "git:tag", "package.json", "provider"];
|
|
18
153
|
type EnvErrorCode = keyof typeof envErrorMessages;
|
|
19
154
|
type EnvSourceIdentifier = typeof envSourceIdentifiers[number];
|
|
20
155
|
interface EnvErrorDetailsByCode {
|
|
@@ -38,4 +173,4 @@ interface EnvErrorDetailsByCode {
|
|
|
38
173
|
}
|
|
39
174
|
type EnvErrorDetails<TCode extends EnvErrorCode = EnvErrorCode> = EnvErrorDetailsByCode[TCode];
|
|
40
175
|
//#endregion
|
|
41
|
-
export { type DeepReadonly, type
|
|
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 };
|