@vite-hub/env 0.0.4 → 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 +288 -23
- package/dist/access-B8lSDip4.js +54 -0
- package/dist/bridge-Cs9YfQWk.d.ts +447 -0
- package/dist/bridge-error-BhJ77age.js +66 -0
- package/dist/bridge.d.ts +2 -0
- package/dist/bridge.js +354 -0
- package/dist/cli-BPp7rdcA.d.ts +159 -0
- package/dist/cli-DLpY0QAo.js +669 -0
- package/dist/cli.d.ts +41 -0
- package/dist/cli.js +2 -0
- package/dist/database.d.ts +47 -0
- package/dist/database.js +274 -0
- package/dist/declarations-C5XR3aKw.d.ts +58 -0
- package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
- package/dist/index.d.ts +146 -11
- package/dist/index.js +240 -7
- package/dist/internal/agent.d.ts +5 -0
- package/dist/internal/agent.js +22 -0
- package/dist/internal/connections.d.ts +18 -0
- package/dist/internal/connections.js +31 -0
- 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 +17 -0
- package/dist/seal.js +52 -0
- 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 -8
- package/dist/server.js +2 -3
- package/dist/virtual-module.d.ts +9 -5
- package/dist/virtual.d.ts +1 -1
- package/dist/vite.d.ts +79 -21
- package/dist/vite.js +1095 -339
- package/package.json +81 -28
- package/dist/declarations-CoMmvRqH.js +0 -159
- package/dist/declarations-U6P3rvxC.d.ts +0 -24
- package/dist/errors-C4Xcs6Fi.js +0 -121
- package/dist/presets.d.ts +0 -11
- package/dist/presets.js +0 -25
- package/dist/provider.d.ts +0 -6
- package/dist/provider.js +0 -7
- package/dist/schema.d.ts +0 -16
- package/dist/schema.js +0 -37
- package/dist/secret-C2191nAa.d.ts +0 -11
- package/dist/secret.d.ts +0 -2
- package/dist/server-C16sFc1E.js +0 -303
- package/dist/types-CsB6DTGE.d.ts +0 -190
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,146 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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
|
|
10
144
|
//#region src/core/errors.d.ts
|
|
11
145
|
declare const envErrorMessages: {
|
|
12
146
|
readonly ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.";
|
|
@@ -15,7 +149,7 @@ declare const envErrorMessages: {
|
|
|
15
149
|
readonly ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.";
|
|
16
150
|
readonly ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed.";
|
|
17
151
|
};
|
|
18
|
-
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"];
|
|
19
153
|
type EnvErrorCode = keyof typeof envErrorMessages;
|
|
20
154
|
type EnvSourceIdentifier = typeof envSourceIdentifiers[number];
|
|
21
155
|
interface EnvErrorDetailsByCode {
|
|
@@ -30,6 +164,7 @@ interface EnvErrorDetailsByCode {
|
|
|
30
164
|
source?: EnvSourceIdentifier;
|
|
31
165
|
};
|
|
32
166
|
ENV_RUNTIME_VALUE_INVALID: {
|
|
167
|
+
path?: string;
|
|
33
168
|
source?: EnvSourceIdentifier;
|
|
34
169
|
};
|
|
35
170
|
ENV_SOURCE_FAILED: {
|
|
@@ -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 };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,240 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { SecretEnv } from "./secret.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
1
|
+
import { t as envErrorDiagnostics } from "./error-diagnostics-B8RFjQ1V.js";
|
|
2
|
+
import { r as env, t as parseSchema } from "./schema-DMZ1_yhY.js";
|
|
3
|
+
import { D as verifyViteHubHmacSignature, O as verifyViteHubStripeSignature, T as isViteHubBearerSecretEqual, _ as runtimeEnv, a as isBlockingServerEnvEntry, d as unseal, k as viteHubHmacSha256, u as seal, v as standardSource, w as githubHmacSignatureFormat } from "./server-ChNL_Xc3.js";
|
|
4
|
+
import { t as SecretEnv } from "./secret-DJd-fy5T.js";
|
|
5
|
+
import { defineErrors } from "@vite-hub/runtime";
|
|
6
|
+
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
7
|
+
import { deriveSecret, describeServerEnv, inspectServerEnv, loadServerEnv, runWithServerEnv, useServerEnv } from "#vitehub/env/server";
|
|
8
|
+
import { usePublicEnv } from "#vitehub/env/public";
|
|
9
|
+
import { HTTPError } from "nitro/h3";
|
|
10
|
+
//#region src/presets.ts
|
|
11
|
+
function openWorkflowEnv(options = {}) {
|
|
12
|
+
return {
|
|
13
|
+
namespaceId: env({
|
|
14
|
+
default: options.namespaceId || "production",
|
|
15
|
+
source: env.source("OPENWORKFLOW_NAMESPACE_ID")
|
|
16
|
+
}),
|
|
17
|
+
postgresUrl: env({
|
|
18
|
+
optional: true,
|
|
19
|
+
secret: true,
|
|
20
|
+
source: env.source(["OPENWORKFLOW_POSTGRES_URL", "DATABASE_URL"])
|
|
21
|
+
}),
|
|
22
|
+
schema: env({
|
|
23
|
+
default: options.schema || "openworkflow",
|
|
24
|
+
source: env.source("OPENWORKFLOW_SCHEMA")
|
|
25
|
+
}),
|
|
26
|
+
workerConcurrency: env({
|
|
27
|
+
default: options.workerConcurrency || "10",
|
|
28
|
+
source: env.source("OPENWORKFLOW_WORKER_CONCURRENCY")
|
|
29
|
+
})
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Declares the Server Env of the `typesafe()` AI gateway from `vite-hub/gateways`: Secret `apiKey`
|
|
34
|
+
* (`TYPESAFE_API_KEY`) and `model` (`TYPESAFE_DEFAULT_MODEL`). `defineAgent({ driver: { ask } })` uses `typesafe()`
|
|
35
|
+
* when it gets no other gateway. The values are optional here: Jev diagnoses a
|
|
36
|
+
* missing key when it runs, so an application without AI still starts.
|
|
37
|
+
*/
|
|
38
|
+
function typesafeEnv(options = {}) {
|
|
39
|
+
return {
|
|
40
|
+
apiKey: env({
|
|
41
|
+
optional: true,
|
|
42
|
+
secret: true,
|
|
43
|
+
source: env.source("TYPESAFE_API_KEY")
|
|
44
|
+
}),
|
|
45
|
+
model: env({
|
|
46
|
+
default: options.model || "jev-latest",
|
|
47
|
+
source: env.source("TYPESAFE_DEFAULT_MODEL")
|
|
48
|
+
})
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
//#region src/provider.ts
|
|
53
|
+
function defineEnvProvider(provider) {
|
|
54
|
+
if (typeof provider !== "object" || provider === null || Array.isArray(provider) || typeof provider.read !== "function") throw envErrorDiagnostics.ENV_R0013({ message: "[vitehub] defineEnvProvider() requires a provider with a read({ env, keys, signal }) method." });
|
|
55
|
+
return provider;
|
|
56
|
+
}
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/service-token.ts
|
|
59
|
+
const serviceTokenErrors = /*#__PURE__*/ defineErrors({
|
|
60
|
+
docs: "https://vitehub.dev/docs/env/diagnostics",
|
|
61
|
+
codes: {
|
|
62
|
+
ENV_SERVICE_TOKEN_INVALID: {
|
|
63
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_service_token_invalid",
|
|
64
|
+
why: ({ name }) => `The request has no \`Authorization: Bearer\` token that matches a token in \`${name}\`.`,
|
|
65
|
+
fix: "Send the header `Authorization: Bearer <token>` with a token that the server variable holds. The variable holds one token, or a comma-separated list while you rotate tokens."
|
|
66
|
+
},
|
|
67
|
+
ENV_SERVICE_TOKEN_UNSET: {
|
|
68
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_service_token_unset",
|
|
69
|
+
why: ({ name }) => `\`${name}\` has no token on this server, so every request is refused.`,
|
|
70
|
+
fix: "Set the variable to a long random token, such as the output of `openssl rand -base64 32`: in `.env` for `vite dev`, and as a secret on the host for production. To rotate, set the old and the new token separated by a comma, then remove the old one."
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
function readTokens(value) {
|
|
75
|
+
return typeof value === "string" ? value.split(",").map((token) => token.trim()).filter(Boolean) : [];
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Checks that a request carries `Authorization: Bearer <token>` with a token from the host variable `name`, and
|
|
79
|
+
* returns `[error, undefined]`. The variable holds one token, or a comma-separated list, so the old and the new token
|
|
80
|
+
* both pass while you rotate. It compares in constant time. Without a token in the variable, every request fails with
|
|
81
|
+
* `ENV_SERVICE_TOKEN_UNSET`.
|
|
82
|
+
*
|
|
83
|
+
* ```ts [server/api/health.get.ts]
|
|
84
|
+
* import { defineEventHandler } from "h3"
|
|
85
|
+
* import { checkServiceToken } from "vite-hub/env"
|
|
86
|
+
*
|
|
87
|
+
* export default defineEventHandler((event) => {
|
|
88
|
+
* const [error] = checkServiceToken(event, "ADMIN_TOKEN")
|
|
89
|
+
* return error ? { ok: true } : { ok: true, queue: 3 }
|
|
90
|
+
* })
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
function checkServiceToken(event, name) {
|
|
94
|
+
const source = standardSource(event);
|
|
95
|
+
const tokens = readTokens(runtimeEnv(source)[name]);
|
|
96
|
+
if (!tokens.length) return [serviceTokenErrors.ENV_SERVICE_TOKEN_UNSET({ name }), void 0];
|
|
97
|
+
const authorization = getStandardContext(source).req.headers.get("authorization");
|
|
98
|
+
let valid = false;
|
|
99
|
+
for (const token of tokens) valid = isViteHubBearerSecretEqual(authorization, token) || valid;
|
|
100
|
+
return valid ? [void 0, void 0] : [serviceTokenErrors.ENV_SERVICE_TOKEN_INVALID({ name }), void 0];
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Returns when a request carries `Authorization: Bearer <token>` with a token from the host variable `name`. Otherwise
|
|
104
|
+
* it throws an `HTTPError`: `401` with `ENV_SERVICE_TOKEN_INVALID`, or `503` with `ENV_SERVICE_TOKEN_UNSET` when the
|
|
105
|
+
* variable has no token. Use it for routes that scripts, runners, and webhooks call.
|
|
106
|
+
*
|
|
107
|
+
* ```ts [server/api/ingest.post.ts]
|
|
108
|
+
* import { defineEventHandler } from "h3"
|
|
109
|
+
* import { requireServiceToken } from "vite-hub/env"
|
|
110
|
+
*
|
|
111
|
+
* export default defineEventHandler((event) => {
|
|
112
|
+
* requireServiceToken(event, "INGEST_TOKEN")
|
|
113
|
+
* return { ok: true }
|
|
114
|
+
* })
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
function requireServiceToken(event, name) {
|
|
118
|
+
const [error] = checkServiceToken(event, name);
|
|
119
|
+
if (!error) return;
|
|
120
|
+
const unset = error.code === "ENV_SERVICE_TOKEN_UNSET";
|
|
121
|
+
throw new HTTPError({
|
|
122
|
+
cause: error,
|
|
123
|
+
data: { code: error.code },
|
|
124
|
+
headers: unset ? void 0 : { "www-authenticate": "Bearer" },
|
|
125
|
+
message: error.message,
|
|
126
|
+
status: unset ? 503 : 401
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
//#endregion
|
|
130
|
+
//#region src/webhook.ts
|
|
131
|
+
const webhookErrors = /*#__PURE__*/ defineErrors({
|
|
132
|
+
docs: "https://vitehub.dev/docs/env/diagnostics",
|
|
133
|
+
codes: {
|
|
134
|
+
ENV_WEBHOOK_BODY_INVALID: {
|
|
135
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_webhook_body_invalid",
|
|
136
|
+
why: "The webhook has a valid signature, but its body is not JSON, or a GitHub form delivery has no JSON `payload` field.",
|
|
137
|
+
fix: "Set the provider to send JSON. GitHub can send `application/json` or `application/x-www-form-urlencoded`, and `verifyWebhook()` reads both."
|
|
138
|
+
},
|
|
139
|
+
ENV_WEBHOOK_SECRET_UNSET: {
|
|
140
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_webhook_secret_unset",
|
|
141
|
+
why: ({ name }) => `\`${name}\` has no webhook secret on this server, so every delivery is refused.`,
|
|
142
|
+
fix: "Set the variable to the signing secret that the provider shows for this endpoint, such as Stripe's `whsec_...` value: in `.env` for `vite dev`, and as a secret on the host for production. To rotate, set the old and the new secret separated by a comma, then remove the old one."
|
|
143
|
+
},
|
|
144
|
+
ENV_WEBHOOK_SIGNATURE_INVALID: {
|
|
145
|
+
docs: "https://vitehub.dev/docs/env/diagnostics/env_webhook_signature_invalid",
|
|
146
|
+
why: ({ header, name }) => `The \`${header}\` header is missing, or it does not match the body signed with a secret in \`${name}\`.`,
|
|
147
|
+
fix: "Set the variable to the signing secret of this endpoint, and do not change the body before `verifyWebhook()` reads it. A Stripe signature also fails when it is older than `toleranceSeconds` (default 300), so check the server clock. Answer with `400`, so the provider shows the failed delivery and sends it again."
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
function readSecrets(value) {
|
|
152
|
+
return typeof value === "string" ? value.split(",").map((secret) => secret.trim()).filter(Boolean) : [];
|
|
153
|
+
}
|
|
154
|
+
function signatureHeader(options) {
|
|
155
|
+
if (options.provider === "stripe") return "stripe-signature";
|
|
156
|
+
if (options.provider === "github") return "x-hub-signature-256";
|
|
157
|
+
return options.header.toLowerCase();
|
|
158
|
+
}
|
|
159
|
+
function verifySignature(options, secret, header, body) {
|
|
160
|
+
if (options.provider === "stripe") return verifyViteHubStripeSignature(secret, header, body, { toleranceSeconds: options.toleranceSeconds });
|
|
161
|
+
if (options.provider === "github") return verifyViteHubHmacSignature(secret, header, body, githubHmacSignatureFormat);
|
|
162
|
+
return verifyViteHubHmacSignature(secret, header, body, options);
|
|
163
|
+
}
|
|
164
|
+
function webhookJson(options, headers, text) {
|
|
165
|
+
if (options.provider !== "github" || !headers.get("content-type")?.toLowerCase().startsWith("application/x-www-form-urlencoded")) return text;
|
|
166
|
+
return new URLSearchParams(text).get("payload");
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Checks the signature of a webhook that Stripe, GitHub, or another provider sends to a route, and returns
|
|
170
|
+
* `[error, body]` with the parsed JSON body. For a GitHub delivery with the form content type, `body` is the JSON
|
|
171
|
+
* of its `payload` field. It reads the raw body once, so do not read the body before you call it.
|
|
172
|
+
* It reads the secret from the server variable `secret` on each request. The variable holds one secret, or a
|
|
173
|
+
* comma-separated list while you rotate. It compares in constant time and runs on every host.
|
|
174
|
+
*
|
|
175
|
+
* ```ts [server/api/stripe/webhook.post.ts]
|
|
176
|
+
* import { defineEventHandler, HTTPError } from "h3"
|
|
177
|
+
* import { verifyWebhook } from "vite-hub/env"
|
|
178
|
+
*
|
|
179
|
+
* export default defineEventHandler(async (event) => {
|
|
180
|
+
* const [error, stripeEvent] = await verifyWebhook<{ type: string }>(event, { provider: "stripe", secret: "STRIPE_WEBHOOK_SECRET" })
|
|
181
|
+
* if (error) throw new HTTPError({ status: 400, message: error.message })
|
|
182
|
+
* return { received: stripeEvent.type }
|
|
183
|
+
* })
|
|
184
|
+
* ```
|
|
185
|
+
*/
|
|
186
|
+
async function verifyWebhook(event, options) {
|
|
187
|
+
const source = standardSource(event);
|
|
188
|
+
const name = options.secret;
|
|
189
|
+
const secrets = readSecrets(runtimeEnv(source)[name]);
|
|
190
|
+
if (!secrets.length) return [webhookErrors.ENV_WEBHOOK_SECRET_UNSET({ name }), void 0];
|
|
191
|
+
const request = getStandardContext(source).req;
|
|
192
|
+
const headerName = signatureHeader(options);
|
|
193
|
+
const header = request.headers.get(headerName);
|
|
194
|
+
if (!header) return [webhookErrors.ENV_WEBHOOK_SIGNATURE_INVALID({
|
|
195
|
+
header: headerName,
|
|
196
|
+
name
|
|
197
|
+
}), void 0];
|
|
198
|
+
const body = new Uint8Array(await request.arrayBuffer());
|
|
199
|
+
let valid = false;
|
|
200
|
+
for (const secret of secrets) valid = await verifySignature(options, secret, header, body) || valid;
|
|
201
|
+
if (!valid) return [webhookErrors.ENV_WEBHOOK_SIGNATURE_INVALID({
|
|
202
|
+
header: headerName,
|
|
203
|
+
name
|
|
204
|
+
}), void 0];
|
|
205
|
+
const json = webhookJson(options, request.headers, new TextDecoder().decode(body));
|
|
206
|
+
if (json === null) return [webhookErrors.ENV_WEBHOOK_BODY_INVALID(), void 0];
|
|
207
|
+
try {
|
|
208
|
+
return [void 0, JSON.parse(json)];
|
|
209
|
+
} catch (cause) {
|
|
210
|
+
return [webhookErrors.ENV_WEBHOOK_BODY_INVALID({ cause }), void 0];
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
function toHex(bytes) {
|
|
214
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Signs the raw body of an outgoing webhook with HMAC-SHA256 and returns the headers to send with it. The receiver
|
|
218
|
+
* checks them with `verifyWebhook()` or the provider's own SDK. Send the exact `body` that you signed. It uses Web
|
|
219
|
+
* Crypto only, so it runs on every host.
|
|
220
|
+
*
|
|
221
|
+
* ```ts
|
|
222
|
+
* import { signWebhook } from "vite-hub/env"
|
|
223
|
+
*
|
|
224
|
+
* const body = JSON.stringify({ type: "deploy.finished" })
|
|
225
|
+
* const headers = await signWebhook(body, { provider: "github", secret: process.env.HOOK_SECRET! })
|
|
226
|
+
* await fetch("https://example.com/hook", { method: "POST", body, headers: { ...headers, "content-type": "application/json" } })
|
|
227
|
+
* ```
|
|
228
|
+
*/
|
|
229
|
+
async function signWebhook(body, options) {
|
|
230
|
+
const bytes = typeof body === "string" ? new TextEncoder().encode(body) : body;
|
|
231
|
+
if (options.provider === "github") return { "x-hub-signature-256": `sha256=${toHex(await viteHubHmacSha256(options.secret, bytes))}` };
|
|
232
|
+
const timestamp = options.timestamp ?? Math.floor(Date.now() / 1e3);
|
|
233
|
+
const prefix = new TextEncoder().encode(`${timestamp}.`);
|
|
234
|
+
const payload = new Uint8Array(prefix.length + bytes.length);
|
|
235
|
+
payload.set(prefix);
|
|
236
|
+
payload.set(bytes, prefix.length);
|
|
237
|
+
return { "stripe-signature": `t=${timestamp},v1=${toHex(await viteHubHmacSha256(options.secret, payload))}` };
|
|
238
|
+
}
|
|
239
|
+
//#endregion
|
|
240
|
+
export { SecretEnv, checkServiceToken, defineEnvProvider, deriveSecret, describeServerEnv, env, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, openWorkflowEnv, parseSchema, requireServiceToken, runWithServerEnv, seal, signWebhook, typesafeEnv, unseal, usePublicEnv, useServerEnv, verifyWebhook };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { $ as EnvAttribution, t as EnvAccessContext } from "../bridge-Cs9YfQWk.js";
|
|
2
|
+
//#region src/internal/agent.d.ts
|
|
3
|
+
/** Mint only for an identity registered by Agent Definition resolution. Names and copies are untrusted. */
|
|
4
|
+
export declare function agentEnvAccess(agent: unknown, attribution?: EnvAttribution): EnvAccessContext;
|
|
5
|
+
//#endregion
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { t as envBridgeError } from "../bridge-error-BhJ77age.js";
|
|
2
|
+
import { r as grantEnvAccess } from "../access-B8lSDip4.js";
|
|
3
|
+
import { readAgentEnvIdentity, readAgentEnvParents } from "@vite-hub/agent/env-identity";
|
|
4
|
+
//#region src/internal/agent.ts
|
|
5
|
+
/** Mint only for an identity registered by Agent Definition resolution. Names and copies are untrusted. */
|
|
6
|
+
function agentEnvAccess(agent, attribution = {}) {
|
|
7
|
+
const name = readAgentEnvIdentity(agent);
|
|
8
|
+
if (name === void 0) throw envBridgeError("untrusted");
|
|
9
|
+
return grantEnvAccess({
|
|
10
|
+
actor: {
|
|
11
|
+
kind: "agent",
|
|
12
|
+
id: name
|
|
13
|
+
},
|
|
14
|
+
traceId: attribution.traceId,
|
|
15
|
+
invocationId: attribution.invocationId
|
|
16
|
+
}, {
|
|
17
|
+
kind: "agent",
|
|
18
|
+
parents: readAgentEnvParents(agent)
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
export { agentEnvAccess };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { a as EnvActor, o as EnvBridge, t as EnvAccessContext } from "../bridge-Cs9YfQWk.js";
|
|
2
|
+
//#region src/internal/connections.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Internal to `@vite-hub/connections`. Call it only after the Connection access policy allows the call.
|
|
5
|
+
* The context works on one bridge, for one Connection token key and one permission.
|
|
6
|
+
*/
|
|
7
|
+
export declare function connectionEnvAccess(bridge: EnvBridge, input: {
|
|
8
|
+
actor: EnvActor;
|
|
9
|
+
name: string;
|
|
10
|
+
permission: "activity" | "replace" | "use";
|
|
11
|
+
traceId?: string;
|
|
12
|
+
invocationId?: string;
|
|
13
|
+
}): EnvAccessContext;
|
|
14
|
+
/** Return the actor of a context that Env created. Other values fail with `ENV_BRIDGE_UNTRUSTED`. */
|
|
15
|
+
export declare function envAccessActor(context: EnvAccessContext): EnvActor;
|
|
16
|
+
/** The registered Agents that the Agent of a context extends, nearest first. Other contexts fail with `ENV_BRIDGE_UNTRUSTED`. */
|
|
17
|
+
export declare function envAccessAgentParents(context: EnvAccessContext): string[];
|
|
18
|
+
//#endregion
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { t as envBridgeError } from "../bridge-error-BhJ77age.js";
|
|
2
|
+
import { r as grantEnvAccess, t as envAccessAuthority } from "../access-B8lSDip4.js";
|
|
3
|
+
//#region src/internal/connections.ts
|
|
4
|
+
/**
|
|
5
|
+
* Internal to `@vite-hub/connections`. Call it only after the Connection access policy allows the call.
|
|
6
|
+
* The context works on one bridge, for one Connection token key and one permission.
|
|
7
|
+
*/
|
|
8
|
+
function connectionEnvAccess(bridge, input) {
|
|
9
|
+
return grantEnvAccess(input, {
|
|
10
|
+
kind: "key",
|
|
11
|
+
bridge,
|
|
12
|
+
key: `connection/${input.name}`,
|
|
13
|
+
permissions: [input.permission]
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
/** Return the actor of a context that Env created. Other values fail with `ENV_BRIDGE_UNTRUSTED`. */
|
|
17
|
+
function envAccessActor(context) {
|
|
18
|
+
if (envAccessAuthority(context).kind !== "agent") throw envBridgeError("untrusted");
|
|
19
|
+
return {
|
|
20
|
+
id: context.actor.id,
|
|
21
|
+
kind: context.actor.kind
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** The registered Agents that the Agent of a context extends, nearest first. Other contexts fail with `ENV_BRIDGE_UNTRUSTED`. */
|
|
25
|
+
function envAccessAgentParents(context) {
|
|
26
|
+
const authority = envAccessAuthority(context);
|
|
27
|
+
if (authority.kind !== "agent") throw envBridgeError("untrusted");
|
|
28
|
+
return [...authority.parents ?? []];
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { connectionEnvAccess, envAccessActor, envAccessAgentParents };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { G as ServerEnvInspection, K as ServerEnvInspectionEntry, q as ServerEnvInspectionStatus, t as EnvAccessContext } from "../bridge-Cs9YfQWk.js";
|
|
2
|
+
import { _ as unseal, a as describeServerEnv, c as loadServerEnv, d as SealOptions, f as UnsealErrorCode, g as seal, h as createSealing, i as deriveSecret, l as resolveServerEnv, m as UnsealSchemaOptions, n as ViteHubContext, o as inspectServerEnv, p as UnsealOptions, r as bindServerEnvSchemas, s as isBlockingServerEnvEntry, t as DeriveSecretOptions, u as runWithCloudflareEnv } from "../server-Dd8bjIKd.js";
|
|
3
|
+
export { DeriveSecretOptions, type EnvAccessContext, type SealOptions, type ServerEnvInspection, type ServerEnvInspectionEntry, type ServerEnvInspectionStatus, type UnsealErrorCode, type UnsealOptions, type UnsealSchemaOptions, type ViteHubContext, bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as isBlockingServerEnvEntry, c as runWithCloudflareEnv, d as unseal, i as inspectServerEnv, l as createSealing, n as deriveSecret, o as loadServerEnv, r as describeServerEnv, s as resolveServerEnv, t as bindServerEnvSchemas, u as seal } from "../server-ChNL_Xc3.js";
|
|
2
|
+
export { bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
|