@crvouga/mockingbird-preview 0.0.0-reserved → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +297 -1
- package/dist/chunk-CFLI52WY.js +362 -0
- package/dist/chunk-CFLI52WY.js.map +7 -0
- package/dist/index.d.ts +234 -0
- package/dist/index.js +1018 -0
- package/dist/index.js.map +7 -0
- package/dist/node.d.ts +14 -0
- package/dist/node.js +76 -0
- package/dist/node.js.map +7 -0
- package/dist/sandbox-proxy.d.ts +121 -0
- package/dist/sandbox-proxy.js +15 -0
- package/dist/sandbox-proxy.js.map +7 -0
- package/dist/types-CQYnWD6z.d.ts +27 -0
- package/package.json +52 -6
package/README.md
CHANGED
|
@@ -1,3 +1,299 @@
|
|
|
1
1
|
# @crvouga/mockingbird-preview
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Local emulators. Real API contracts. Part of [Mockingbird](https://github.com/crvouga-organization/mockingbird).
|
|
4
|
+
|
|
5
|
+
Reusable infrastructure for static application previews: a streaming Fetch bridge over MessagePort,
|
|
6
|
+
shared worker lifecycle, verified compressed assets, a Node test adapter, and Cloudflare named
|
|
7
|
+
Worker Preview deployment. App entrypoints, schemas, synthetic fixtures, credentials acquisition,
|
|
8
|
+
cloud identities and organization CI policy remain in the consuming application.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @crvouga/mockingbird-preview
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
A module worker creates its application once, and attaches each visiting page to that same system:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { createPreviewHost, installPreviewWorkerHost } from "@crvouga/mockingbird-preview"
|
|
22
|
+
|
|
23
|
+
const host = createPreviewHost({
|
|
24
|
+
artifact: "sha256:the-build-identity",
|
|
25
|
+
boot: async ({ generation, signal }) => ({
|
|
26
|
+
fetch: (request) => Response.json({ generation, path: new URL(request.url).pathname }),
|
|
27
|
+
dispose: async () => {},
|
|
28
|
+
}),
|
|
29
|
+
allow: (url) => url.hostname === "app.preview",
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
installPreviewWorkerHost(host, self)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The page uses `connectSharedPreviewWorker("/worker.js", { application: "demo", artifact:
|
|
36
|
+
"sha256:the-build-identity", generation: 0 })` and its returned `fetch`. The browser's normal
|
|
37
|
+
same-origin restrictions apply to the worker URL. Each connected page has isolated in-flight
|
|
38
|
+
requests. Disconnecting a page does not dispose the shared system. Call `host.reset()` to abort
|
|
39
|
+
connections, dispose state and boot the next generation; reconnect clients afterwards. A failed
|
|
40
|
+
boot is visible through `status()` and returns HTTP 503. Calling `dispose()` terminates the host.
|
|
41
|
+
The application must honor the boot/request AbortSignals to terminate work it started.
|
|
42
|
+
|
|
43
|
+
## API
|
|
44
|
+
|
|
45
|
+
- `createPreviewClient(port, options)` exposes `fetch`, `dispose()` and the number of pending
|
|
46
|
+
requests. `timeoutMs` covers response headers and the complete response stream (30 seconds by
|
|
47
|
+
default); configure it for intentionally long-lived streams. Worker death without a port error
|
|
48
|
+
is detected by this deadline. `allow(url)` optionally restricts destinations at the client.
|
|
49
|
+
- `servePreviewPort(port, fetch, options)` handles requests through the application's Fetch
|
|
50
|
+
handler. Responses use transferable ArrayBuffers and one chunk per consumer pull; cancellation
|
|
51
|
+
aborts the handler's signal and reader. Pre-header failures reject fetch and post-header failures
|
|
52
|
+
error its body. Error messages are opaque to avoid leaking server details. `maxRequests`
|
|
53
|
+
bounds concurrent requests per port, default 128. `onClose` supports connection accounting.
|
|
54
|
+
- `createPreviewHost({ artifact, boot, allow })` serializes boot/reset/dispose and exposes
|
|
55
|
+
`connect`, `fetch`, `status`, `ready`, `reset` and `dispose`. It owns no emulator-specific state:
|
|
56
|
+
use a fleet's lifecycle inside the boot/dispose callbacks.
|
|
57
|
+
- `sharedPreviewWorkerName({ application, artifact, generation })` creates an unambiguous worker
|
|
58
|
+
identity; changing artifact or generation creates a distinct SharedWorker.
|
|
59
|
+
- `connectSharedPreviewWorker(url, options)` opens a module SharedWorker and connects its port.
|
|
60
|
+
`connectDedicatedPreviewWorker(url, options)` uses a dedicated module Worker and transferred
|
|
61
|
+
MessageChannel. Both expose `fetch`, `pending`, `worker` and `dispose`; worker errors reject
|
|
62
|
+
pending requests. Dedicated disposal also terminates its worker.
|
|
63
|
+
- `installPreviewWorkerHost(host, scope)` accepts SharedWorker connection events and dedicated
|
|
64
|
+
worker MessagePort handshakes. Returns an async disposer.
|
|
65
|
+
- `createPreviewArtifact(bytes, { commit, url, encoding })` records format version, source commit,
|
|
66
|
+
exact packed byte count and SHA-256. `parsePreviewArtifact(value)` validates this manifest.
|
|
67
|
+
`digestPreviewBytes(bytes)` returns a lowercase SHA-256 digest.
|
|
68
|
+
- `loadPreviewArtifact(manifest, options)` fetches with `no-store`, no credentials and redirect
|
|
69
|
+
refusal; checks expected commit, size and hash before optional gzip decompression. Packed and
|
|
70
|
+
decompressed sizes are bounded by `maximumBytes` (128 MiB default). The result is bytes; the
|
|
71
|
+
caller deliberately chooses how to execute or persist trusted application code. It never evals
|
|
72
|
+
arbitrary fetched source.
|
|
73
|
+
- `selectPreviewAction(currentFacts, builtCommit)` chooses deploy/remove/skip from current PR
|
|
74
|
+
state. Closed PRs select removal; forks and stale build heads cannot deploy.
|
|
75
|
+
- `planPreviewSweep({ previews, openNames, owns, now, retentionMs, capacity })` is a pure plan
|
|
76
|
+
listing managed names removed for orphaning, expiry or capacity. It never removes unmanaged
|
|
77
|
+
names or performs cloud operations. Capacity eviction retains the newest managed previews.
|
|
78
|
+
- `createCloudflarePreviews({ accountId, workerName, token, fetch })` returns `deploy`, `list` and
|
|
79
|
+
`remove`. `deploy` takes explicit static files, source commit, a name and a `currentPullRequest`
|
|
80
|
+
callback. It checks current facts before upload and immediately before deployment, sends only
|
|
81
|
+
missing assets, preserves optional `_headers` text and uses content identity to avoid repeating
|
|
82
|
+
an already identical deployment. `list` follows pages and throws on API failures; `remove`
|
|
83
|
+
treats HTTP 404 as success. No production Worker deployment is changed.
|
|
84
|
+
- `previewNodeHandler(fetch)` and `listenPreview(fetch, { port, hostname })`, from the `/node`
|
|
85
|
+
export, expose the same Fetch handler or browser bridge to a Node HTTP test runner. The default
|
|
86
|
+
listener is loopback on an ephemeral port. Responses are always `Cache-Control: no-store` to
|
|
87
|
+
avoid browser worker-asset cache failures. Stream errors destroy the response instead of
|
|
88
|
+
creating a successful EOF. Call the returned `close()` to release the listener.
|
|
89
|
+
- `createSandboxProxy({ providers, env, accessKey?, basePath?, allowOrigins?, fetch? })`, from the
|
|
90
|
+
`/sandbox-proxy` export (also re-exported from the package root), is the sandbox proxy's Fetch
|
|
91
|
+
handler; `sandboxProxyWorker(options)` wraps it as a Cloudflare Worker `{ fetch(request, env) }`.
|
|
92
|
+
`sandboxProviders` holds the Stripe, Junction, Resend, Slack, Twilio and FCM providers;
|
|
93
|
+
`SANDBOX_KEY_HEADER` names the access-key header and `safeEqual(a, b)` is the constant-time
|
|
94
|
+
comparison it uses. See [Sandbox mode](#sandbox-mode).
|
|
95
|
+
- `createSandbox({ proxyUrl?, storage?, fetch? })` is the browser side: `upstream(id)` for an
|
|
96
|
+
emulator's `createRuntime({ upstream })` and `controls(services)` for the System screen.
|
|
97
|
+
`SANDBOX_MESSAGES` holds its status sentences and `SANDBOX_STORAGE_KEYS` its storage keys.
|
|
98
|
+
|
|
99
|
+
## Cookies, redirects and trust
|
|
100
|
+
|
|
101
|
+
The bridge defaults to removing Cookie and Set-Cookie headers. It does not borrow browser cookies
|
|
102
|
+
or impersonate the page origin. For a fully virtual application, both bridge ends may opt into
|
|
103
|
+
`cookies: true`; that carries explicitly supplied cookie headers, but supplies no cookie jar and
|
|
104
|
+
never writes `document.cookie`. The host must own a jar per intended user/session if needed.
|
|
105
|
+
Responses preserve redirect statuses and Location; redirects are always manual, including when a
|
|
106
|
+
Request uses its usual `follow` default. Follow redirects explicitly through the same allowlisted
|
|
107
|
+
Fetch boundary. Do not forward authorization/cookies to a new origin. These deliberate rules avoid
|
|
108
|
+
silently following an allowed virtual request into a real production host.
|
|
109
|
+
|
|
110
|
+
Request bodies are buffered before transfer; response bodies stream with backpressure. This is
|
|
111
|
+
not a streaming request-upload implementation. Ports are trusted capabilities, not an untrusted
|
|
112
|
+
RPC/authentication boundary. Browser-delivered code, environment values and files remain visible
|
|
113
|
+
and editable by the visitor. Never put production or shared secret values in these artifacts.
|
|
114
|
+
|
|
115
|
+
Cloudflare helpers require an existing parent Worker and explicit account credentials on the
|
|
116
|
+
trusted CI/server side. They create named Preview resources with base-config inheritance disabled,
|
|
117
|
+
no environment bindings, and assets-only deployments. Existing organization ownership/naming
|
|
118
|
+
rules remain the caller's responsibility. Per-PR deployment jobs must be serialized externally:
|
|
119
|
+
the final head re-read narrows, but cannot eliminate, races without a provider compare-and-swap.
|
|
120
|
+
A retry after an ambiguous create response should re-read the named preview before retrying.
|
|
121
|
+
No live cloud credentials were used for the package's acceptance tests.
|
|
122
|
+
|
|
123
|
+
Cloudflare protocol references:
|
|
124
|
+
[official Preview API implementation](https://github.com/cloudflare/workers-sdk/blob/main/packages/deploy-helpers/src/preview/api.ts),
|
|
125
|
+
[asset upload documentation](https://developers.cloudflare.com/workers/static-assets/direct-upload/),
|
|
126
|
+
[Worker Previews](https://developers.cloudflare.com/workers/previews/).
|
|
127
|
+
|
|
128
|
+
## Sandbox mode
|
|
129
|
+
|
|
130
|
+
A preview runs every third-party service as an in-browser emulator. Sandbox mode lets a viewer
|
|
131
|
+
flip one service at a time from **Emulated** to **Sandbox**: that emulator's runtime switches to
|
|
132
|
+
forward mode (`PUT /__admin/upstream {"mode":"forward"}`) and sends the app's API calls to the
|
|
133
|
+
vendor's real sandbox or test account. The browser never holds a vendor secret. A small Fetch
|
|
134
|
+
handler, the **sandbox proxy** (`@crvouga/mockingbird-preview/sandbox-proxy`), sits next to the
|
|
135
|
+
static preview, holds the secrets in its environment and attaches them per request.
|
|
136
|
+
|
|
137
|
+
```mermaid
|
|
138
|
+
sequenceDiagram
|
|
139
|
+
participant App as App code (browser)
|
|
140
|
+
participant Emu as Emulator runtime (browser)
|
|
141
|
+
participant Proxy as Sandbox proxy (Worker / server)
|
|
142
|
+
participant Vendor as Vendor sandbox
|
|
143
|
+
App->>Emu: POST /v1/customers (Authorization: Bearer sk_test_fake)
|
|
144
|
+
Note over Emu: mode = forward (System screen chose "Sandbox")
|
|
145
|
+
Emu->>Proxy: POST /__sandbox/stripe/v1/customers<br/>x-mockingbird-sandbox-key: viewer key<br/>(Authorization dropped)
|
|
146
|
+
Note over Proxy: check access key (constant time)<br/>check STRIPE_SECRET_KEY is sk_test_/rk_test_<br/>strip cookie, origin, x-mockingbird-*, ...
|
|
147
|
+
Proxy->>Vendor: POST https://api.stripe.com/v1/customers<br/>Authorization: Bearer STRIPE_SECRET_KEY
|
|
148
|
+
Vendor-->>Proxy: 200 {"id": "cus_..."}
|
|
149
|
+
Proxy-->>Emu: 200 (set-cookie dropped, secrets redacted)
|
|
150
|
+
Emu-->>App: 200 {"id": "cus_..."}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Providers
|
|
154
|
+
|
|
155
|
+
`sandboxProviders` holds the vendors the proxy knows; pass the ones you want to offer.
|
|
156
|
+
|
|
157
|
+
| id | Sandbox host | Env secrets | Live-key guard | Notes and limitations |
|
|
158
|
+
| --- | --- | --- | --- | --- |
|
|
159
|
+
| `stripe` | `api.stripe.com` | `STRIPE_SECRET_KEY` | must start `sk_test_` or `rk_test_` | Only `/v1/*`. Prices, products, coupons and webhook endpoints the app names must exist in the test account. |
|
|
160
|
+
| `junction` | `api.sandbox.tryvital.io` (`api.sandbox.eu.tryvital.io` for `sk_eu_` keys) | `JUNCTION_API_KEY` | must start `sk_us_` or `sk_eu_` | Only `/v<n>/*`, sent as `x-vital-api-key`. Lab test ids and users must exist in the sandbox team. |
|
|
161
|
+
| `resend` | `api.resend.com` | `RESEND_API_KEY` | none (Resend keys have no test prefix) | Real email is sent: use a sending domain and recipients you own. |
|
|
162
|
+
| `slack` | `slack.com` | `SLACK_BOT_TOKEN` | none | Only `/api/*`. Channels and users must exist in the workspace the bot is in. |
|
|
163
|
+
| `twilio` | `api.twilio.com`, `verify.twilio.com`, `lookups.twilio.com`, `messaging.twilio.com` (by path) | `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN` | none (use test credentials or a trial account) | Any `/Accounts/<sid>/` is rewritten to the real SID. Sender numbers, Messaging Service SIDs and Verify Service SIDs must exist in that account. `/v1/Services` always goes to Messaging, so Conversations' `/v1/Services` is ambiguous and not reachable. |
|
|
164
|
+
| `fcm` | `fcm.googleapis.com` | `FCM_ACCESS_TOKEN`, `FCM_PROJECT_ID` | none | Only `POST /v1/projects/*/messages:send`; the project id is rewritten to `FCM_PROJECT_ID`. The access token is a short-lived OAuth token (about an hour): refresh it out of band. |
|
|
165
|
+
|
|
166
|
+
For every provider: vendor webhooks are **not** relayed back to the browser emulator, and
|
|
167
|
+
forwarded responses are relayed as-is (emulators with a forwarded-response hook, such as Resend,
|
|
168
|
+
FCM and Twilio, record a receipt; Stripe and Junction do not mirror sandbox objects into their
|
|
169
|
+
state). A path a provider does not map answers `501`.
|
|
170
|
+
|
|
171
|
+
### Security model
|
|
172
|
+
|
|
173
|
+
- **Fails closed.** Without `SANDBOX_PROXY_TOKEN` (or the env name passed as `accessKey`) the
|
|
174
|
+
manifest reports `access: "disabled"` and every relay answers `503`. A caller must send that
|
|
175
|
+
value in `x-mockingbird-sandbox-key`; it is compared in constant time, and a wrong or missing
|
|
176
|
+
key gets `401`. Only a caller with the key learns which providers are configured.
|
|
177
|
+
- **Allowlisted hosts only.** Each provider builds the vendor URL on a fixed origin from the
|
|
178
|
+
path; a crafted path cannot change the host, and unmapped paths answer `501`. Redirects are
|
|
179
|
+
returned, never followed.
|
|
180
|
+
- **Secrets never reach the browser.** The proxy drops the caller's `authorization`, `cookie`,
|
|
181
|
+
`origin`, `referer`, `x-mockingbird-*`, `cf-*`, `x-forwarded-*` and `forwarded` headers,
|
|
182
|
+
attaches the credential itself, drops `set-cookie` from the answer, and redacts every secret
|
|
183
|
+
value from its own errors and from text responses (account identifiers such as the Twilio
|
|
184
|
+
Account SID stay). Errors are `{ "error": { "code", "message" } }`.
|
|
185
|
+
- **A live key is refused.** `check` rejects Stripe live keys and Junction production keys before
|
|
186
|
+
anything is sent (`503`, and the System screen shows why).
|
|
187
|
+
- **Access key per viewer.** The browser keeps the access key and chosen modes in its own
|
|
188
|
+
`localStorage`; share the key only with people who may spend the sandbox accounts. CORS is off
|
|
189
|
+
unless `allowOrigins` lists the page's origin; mounting the proxy on the page's own origin (as
|
|
190
|
+
below) needs none.
|
|
191
|
+
|
|
192
|
+
### Mounting the proxy
|
|
193
|
+
|
|
194
|
+
A Cloudflare Worker that serves the static preview and the proxy on one origin (set the secrets
|
|
195
|
+
with `wrangler secret put SANDBOX_PROXY_TOKEN`, `wrangler secret put STRIPE_SECRET_KEY`, ...):
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
import { sandboxProviders, sandboxProxyWorker } from "@crvouga/mockingbird-preview/sandbox-proxy"
|
|
199
|
+
|
|
200
|
+
const proxy = sandboxProxyWorker({
|
|
201
|
+
basePath: "/__sandbox",
|
|
202
|
+
providers: Object.values(sandboxProviders),
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
export default {
|
|
206
|
+
fetch(request: Request, env: Record<string, string | undefined> & { ASSETS: { fetch(request: Request): Promise<Response> } }) {
|
|
207
|
+
const { pathname } = new URL(request.url)
|
|
208
|
+
if (pathname === "/__sandbox" || pathname.startsWith("/__sandbox/")) {
|
|
209
|
+
const { ASSETS: _assets, ...secrets } = env
|
|
210
|
+
return proxy.fetch(request, secrets)
|
|
211
|
+
}
|
|
212
|
+
return env.ASSETS.fetch(request)
|
|
213
|
+
},
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
A Bun server (Node 18+ and Deno work the same with any Fetch-handler server), secrets from
|
|
218
|
+
`.env.local` / the process environment:
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
import { createSandboxProxy, sandboxProviders } from "@crvouga/mockingbird-preview/sandbox-proxy"
|
|
222
|
+
|
|
223
|
+
const sandbox = createSandboxProxy({
|
|
224
|
+
basePath: "/__sandbox",
|
|
225
|
+
providers: [sandboxProviders.stripe, sandboxProviders.resend],
|
|
226
|
+
env: process.env,
|
|
227
|
+
allowOrigins: ["http://localhost:5173"], // only when the page is on another origin
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
Bun.serve({
|
|
231
|
+
port: 8787,
|
|
232
|
+
fetch: (request) =>
|
|
233
|
+
new URL(request.url).pathname.startsWith("/__sandbox")
|
|
234
|
+
? sandbox(request)
|
|
235
|
+
: new Response("Not found", { status: 404 }),
|
|
236
|
+
})
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`GET /__sandbox/` answers the manifest:
|
|
240
|
+
`{ access: "granted" | "denied" | "disabled", providers: [{ id, label, configured, missing, error? }] }`.
|
|
241
|
+
|
|
242
|
+
### Browser wiring
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
import { createSandbox } from "@crvouga/mockingbird-preview"
|
|
246
|
+
import { createRuntime as createStripe } from "@crvouga/mockingbird-service-stripe"
|
|
247
|
+
import { createRuntime as createResend } from "@crvouga/mockingbird-service-resend"
|
|
248
|
+
|
|
249
|
+
const sandbox = createSandbox({ proxyUrl: "/__sandbox" }) // omit proxyUrl: sandbox not offered
|
|
250
|
+
|
|
251
|
+
// Each emulator forwards through the proxy when switched to Sandbox; it boots emulated.
|
|
252
|
+
const stripe = createStripe({ upstream: sandbox.upstream("stripe") })
|
|
253
|
+
const resend = createResend({ upstream: sandbox.upstream("resend") })
|
|
254
|
+
|
|
255
|
+
// The System screen's service list (`mountSystemHarness(host, surfaces, { services })`).
|
|
256
|
+
const services = sandbox.controls([
|
|
257
|
+
{ id: "stripe", label: "Stripe", category: "Payments", admin: (r) => stripe.fetch(r) },
|
|
258
|
+
{ id: "resend", label: "Resend", category: "Email", admin: (r) => resend.fetch(r) },
|
|
259
|
+
{
|
|
260
|
+
id: "keycloak",
|
|
261
|
+
label: "Keycloak",
|
|
262
|
+
admin: async () => Response.json({ mode: "emulated" }),
|
|
263
|
+
unsupported: "Runs in this browser; there is no vendor sandbox",
|
|
264
|
+
},
|
|
265
|
+
])
|
|
266
|
+
|
|
267
|
+
await services.setAccessKey("the key the proxy's SANDBOX_PROXY_TOKEN holds")
|
|
268
|
+
await services.setMode("stripe", "sandbox") // throws a readable reason when unavailable
|
|
269
|
+
const { sandbox: status, services: rows } = await services.list()
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
`upstream(id)` gives `{ baseUrl: "<proxy>/<id>", fetch, rewriteAuth }`: `fetch` adds the stored
|
|
273
|
+
access key, `rewriteAuth` drops the app's fake `authorization`. `controls()` reads each
|
|
274
|
+
emulator's mode from `GET /__admin/upstream`, and its `unavailable` reason follows this order:
|
|
275
|
+
the spec's `unsupported`, no proxy configured, proxy unreachable, proxy without
|
|
276
|
+
`SANDBOX_PROXY_TOKEN`, access key missing or wrong, provider secrets missing, the provider's
|
|
277
|
+
`check` error. Chosen modes persist per viewer; because emulator state resets on reload, the first
|
|
278
|
+
`list()` re-applies stored Sandbox choices that are still available.
|
|
279
|
+
|
|
280
|
+
## Validation
|
|
281
|
+
|
|
282
|
+
Tests exercise concurrent requests, first-chunk delivery, cancellation, deadlines, failures on
|
|
283
|
+
both sides of response headers, target restrictions, two virtual apps sharing a real Chromium
|
|
284
|
+
SharedWorker, reset/disconnect, compressed integrity/size limits, the Node HTTP adapter, and injected
|
|
285
|
+
Cloudflare upload/pagination/stale-head/deletion failures. Cloudflare behavior is based on official
|
|
286
|
+
API source and documentation, not a live-account parity claim.
|
|
287
|
+
|
|
288
|
+
## Runtime compatibility
|
|
289
|
+
|
|
290
|
+
`@crvouga/mockingbird-runtime/preview/*` delegates to this package, preserving its legacy signatures.
|
|
291
|
+
`loadPreviewArtifact` also accepts `LegacyPreviewArtifact` (`version: 1`, `sha256`, `url`, optional
|
|
292
|
+
`compression: "gzip"`), whose hash covers decoded bytes. Legacy downloads still enforce the same
|
|
293
|
+
bounded loading, no-store and redirect policy; they cannot satisfy `expectedCommit` because they
|
|
294
|
+
carry no commit. New manifests cover packed bytes, size and source commit.
|
|
295
|
+
|
|
296
|
+
The bridge's `exposeErrors: true` option on both ends exists for trusted legacy compatibility.
|
|
297
|
+
It forwards original error messages and must not be enabled on a boundary that needs opaque
|
|
298
|
+
errors. Both ends must also opt into `cookies: true` to transport explicit virtual cookie headers.
|
|
299
|
+
These options do not create a browser cookie jar or expose server-held credentials.
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
// src/sandbox-proxy.ts
|
|
2
|
+
var withoutTrailingSlashes = (value) => {
|
|
3
|
+
let end = value.length;
|
|
4
|
+
while (end > 0 && value.charCodeAt(end - 1) === 47) end--;
|
|
5
|
+
return value.slice(0, end);
|
|
6
|
+
};
|
|
7
|
+
var SANDBOX_KEY_HEADER = "x-mockingbird-sandbox-key";
|
|
8
|
+
var on = (origin, path, search) => {
|
|
9
|
+
const url = new URL(origin);
|
|
10
|
+
url.pathname = path.startsWith("/") ? path : `/${path}`;
|
|
11
|
+
url.search = search;
|
|
12
|
+
return url;
|
|
13
|
+
};
|
|
14
|
+
var withUrl = (request, url) => new Request(url, {
|
|
15
|
+
method: request.method,
|
|
16
|
+
headers: request.headers,
|
|
17
|
+
redirect: "manual",
|
|
18
|
+
signal: request.signal,
|
|
19
|
+
...request.body ? { body: request.body, duplex: "half" } : {}
|
|
20
|
+
});
|
|
21
|
+
var missingSecrets = (provider, env) => provider.secrets.filter((name) => !env[name]);
|
|
22
|
+
var startsWithAny = (value, prefixes) => prefixes.some((prefix) => value.startsWith(prefix));
|
|
23
|
+
var basic = (user, password) => {
|
|
24
|
+
const bytes = new TextEncoder().encode(`${user}:${password}`);
|
|
25
|
+
let binary = "";
|
|
26
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
27
|
+
return `Basic ${btoa(binary)}`;
|
|
28
|
+
};
|
|
29
|
+
var bearer = (request, token) => {
|
|
30
|
+
request.headers.set("authorization", `Bearer ${token}`);
|
|
31
|
+
return request;
|
|
32
|
+
};
|
|
33
|
+
var STRIPE_TEST_PREFIXES = ["sk_test_", "rk_test_"];
|
|
34
|
+
var JUNCTION_SANDBOX_PREFIXES = ["sk_us_", "sk_eu_"];
|
|
35
|
+
var twilioHost = (path) => {
|
|
36
|
+
if (/^\/2010-04-01(?:\/|$)/.test(path)) return "https://api.twilio.com";
|
|
37
|
+
if (/^\/v2\/(?:Services|Attempts|Forms|SafeList)(?:\/|$)/.test(path))
|
|
38
|
+
return "https://verify.twilio.com";
|
|
39
|
+
if (/^\/v[12]\/PhoneNumbers(?:\/|$)/.test(path)) return "https://lookups.twilio.com";
|
|
40
|
+
if (/^\/v1\/Services(?:\/|$)/.test(path)) return "https://messaging.twilio.com";
|
|
41
|
+
return void 0;
|
|
42
|
+
};
|
|
43
|
+
var FCM_SEND = /^\/v1\/projects\/[^/]+\/messages:send$/;
|
|
44
|
+
var sandboxProviders = {
|
|
45
|
+
stripe: {
|
|
46
|
+
id: "stripe",
|
|
47
|
+
label: "Stripe",
|
|
48
|
+
secrets: ["STRIPE_SECRET_KEY"],
|
|
49
|
+
check: (env) => {
|
|
50
|
+
const key = env.STRIPE_SECRET_KEY ?? "";
|
|
51
|
+
if (!startsWithAny(key, STRIPE_TEST_PREFIXES))
|
|
52
|
+
throw new Error(
|
|
53
|
+
"STRIPE_SECRET_KEY is not a test-mode key (expected sk_test_ or rk_test_); sandbox mode refuses live keys"
|
|
54
|
+
);
|
|
55
|
+
},
|
|
56
|
+
target: (path, search) => /^\/v1\//.test(path) ? on("https://api.stripe.com", path, search) : void 0,
|
|
57
|
+
authorize: (request, env) => bearer(request, env.STRIPE_SECRET_KEY ?? "")
|
|
58
|
+
},
|
|
59
|
+
junction: {
|
|
60
|
+
id: "junction",
|
|
61
|
+
label: "Junction",
|
|
62
|
+
secrets: ["JUNCTION_API_KEY"],
|
|
63
|
+
check: (env) => {
|
|
64
|
+
const key = env.JUNCTION_API_KEY ?? "";
|
|
65
|
+
if (!startsWithAny(key, JUNCTION_SANDBOX_PREFIXES))
|
|
66
|
+
throw new Error(
|
|
67
|
+
"JUNCTION_API_KEY is not a sandbox key (expected sk_us_ or sk_eu_); sandbox mode refuses production keys"
|
|
68
|
+
);
|
|
69
|
+
},
|
|
70
|
+
target: (path, search) => /^\/v\d+\//.test(path) ? on("https://api.sandbox.tryvital.io", path, search) : void 0,
|
|
71
|
+
authorize: (request, env) => {
|
|
72
|
+
const key = env.JUNCTION_API_KEY ?? "";
|
|
73
|
+
let out = request;
|
|
74
|
+
if (key.startsWith("sk_eu_")) {
|
|
75
|
+
const url = new URL(request.url);
|
|
76
|
+
url.hostname = "api.sandbox.eu.tryvital.io";
|
|
77
|
+
out = withUrl(request, url);
|
|
78
|
+
}
|
|
79
|
+
out.headers.set("x-vital-api-key", key);
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
resend: {
|
|
84
|
+
id: "resend",
|
|
85
|
+
label: "Resend",
|
|
86
|
+
secrets: ["RESEND_API_KEY"],
|
|
87
|
+
target: (path, search) => on("https://api.resend.com", path, search),
|
|
88
|
+
authorize: (request, env) => bearer(request, env.RESEND_API_KEY ?? "")
|
|
89
|
+
},
|
|
90
|
+
slack: {
|
|
91
|
+
id: "slack",
|
|
92
|
+
label: "Slack",
|
|
93
|
+
secrets: ["SLACK_BOT_TOKEN"],
|
|
94
|
+
target: (path, search) => /^\/api\//.test(path) ? on("https://slack.com", path, search) : void 0,
|
|
95
|
+
authorize: (request, env) => bearer(request, env.SLACK_BOT_TOKEN ?? "")
|
|
96
|
+
},
|
|
97
|
+
twilio: {
|
|
98
|
+
id: "twilio",
|
|
99
|
+
label: "Twilio",
|
|
100
|
+
secrets: ["TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN"],
|
|
101
|
+
identifiers: ["TWILIO_ACCOUNT_SID"],
|
|
102
|
+
target: (path, search) => {
|
|
103
|
+
const host = twilioHost(path);
|
|
104
|
+
return host ? on(host, path, search) : void 0;
|
|
105
|
+
},
|
|
106
|
+
authorize: (request, env) => {
|
|
107
|
+
const sid = env.TWILIO_ACCOUNT_SID ?? "";
|
|
108
|
+
const url = new URL(request.url);
|
|
109
|
+
const rewritten = url.pathname.replace(
|
|
110
|
+
/\/Accounts\/[^/.]+(?=[/.]|$)/,
|
|
111
|
+
`/Accounts/${encodeURIComponent(sid)}`
|
|
112
|
+
);
|
|
113
|
+
let out = request;
|
|
114
|
+
if (rewritten !== url.pathname) {
|
|
115
|
+
url.pathname = rewritten;
|
|
116
|
+
out = withUrl(request, url);
|
|
117
|
+
}
|
|
118
|
+
out.headers.set("authorization", basic(sid, env.TWILIO_AUTH_TOKEN ?? ""));
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
fcm: {
|
|
123
|
+
id: "fcm",
|
|
124
|
+
label: "Firebase Cloud Messaging",
|
|
125
|
+
secrets: ["FCM_ACCESS_TOKEN", "FCM_PROJECT_ID"],
|
|
126
|
+
identifiers: ["FCM_PROJECT_ID"],
|
|
127
|
+
methods: ["POST"],
|
|
128
|
+
target: (path, search) => FCM_SEND.test(path) ? on("https://fcm.googleapis.com", path, search) : void 0,
|
|
129
|
+
authorize: (request, env) => {
|
|
130
|
+
const url = new URL(request.url);
|
|
131
|
+
url.pathname = url.pathname.replace(
|
|
132
|
+
/^\/v1\/projects\/[^/]+\//,
|
|
133
|
+
`/v1/projects/${encodeURIComponent(env.FCM_PROJECT_ID ?? "")}/`
|
|
134
|
+
);
|
|
135
|
+
return bearer(withUrl(request, url), env.FCM_ACCESS_TOKEN ?? "");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
var DROP_REQUEST = /* @__PURE__ */ new Set([
|
|
140
|
+
"host",
|
|
141
|
+
"cookie",
|
|
142
|
+
"authorization",
|
|
143
|
+
"forwarded",
|
|
144
|
+
"origin",
|
|
145
|
+
"referer",
|
|
146
|
+
"connection",
|
|
147
|
+
"keep-alive",
|
|
148
|
+
"content-length",
|
|
149
|
+
"transfer-encoding",
|
|
150
|
+
"accept-encoding",
|
|
151
|
+
"proxy-authorization",
|
|
152
|
+
"x-real-ip",
|
|
153
|
+
"true-client-ip"
|
|
154
|
+
]);
|
|
155
|
+
var DROP_REQUEST_PREFIX = ["x-mockingbird-", "cf-", "x-forwarded-"];
|
|
156
|
+
var DROP_RESPONSE = /* @__PURE__ */ new Set([
|
|
157
|
+
"set-cookie",
|
|
158
|
+
"set-cookie2",
|
|
159
|
+
"content-encoding",
|
|
160
|
+
"content-length",
|
|
161
|
+
"transfer-encoding",
|
|
162
|
+
"connection",
|
|
163
|
+
"keep-alive",
|
|
164
|
+
"alt-svc"
|
|
165
|
+
]);
|
|
166
|
+
var NULL_BODY = /* @__PURE__ */ new Set([101, 204, 205, 304]);
|
|
167
|
+
var TEXT_TYPE = /^(?:text\/|application\/(?:[\w.+-]*\+)?(?:json|xml|x-www-form-urlencoded))/i;
|
|
168
|
+
var safeEqual = (a, b) => {
|
|
169
|
+
const left = new TextEncoder().encode(a);
|
|
170
|
+
const right = new TextEncoder().encode(b);
|
|
171
|
+
const length = Math.max(left.length, right.length);
|
|
172
|
+
let diff = left.length ^ right.length;
|
|
173
|
+
for (let index = 0; index < length; index++) diff |= (left[index] ?? 0) ^ (right[index] ?? 0);
|
|
174
|
+
return diff === 0;
|
|
175
|
+
};
|
|
176
|
+
var matchesOrigin = (origin, allow) => allow.some((entry) => typeof entry === "string" ? entry === origin : entry.test(origin));
|
|
177
|
+
var createSandboxProxy = (options) => {
|
|
178
|
+
const accessKeyName = options.accessKey ?? "SANDBOX_PROXY_TOKEN";
|
|
179
|
+
const basePath = withoutTrailingSlashes(options.basePath ?? "");
|
|
180
|
+
const allowOrigins = options.allowOrigins ?? [];
|
|
181
|
+
const send = options.fetch ?? ((request) => globalThis.fetch(request));
|
|
182
|
+
const providers = new Map(options.providers.map((provider) => [provider.id, provider]));
|
|
183
|
+
if (providers.size !== options.providers.length)
|
|
184
|
+
throw new Error("sandbox providers must have distinct ids");
|
|
185
|
+
return async (request) => {
|
|
186
|
+
const env = typeof options.env === "function" ? options.env(request) : options.env;
|
|
187
|
+
const origin = request.headers.get("origin");
|
|
188
|
+
const corsOrigin = origin && matchesOrigin(origin, allowOrigins) ? origin : void 0;
|
|
189
|
+
const secretValues = (credentialsOnly) => {
|
|
190
|
+
const values = /* @__PURE__ */ new Set();
|
|
191
|
+
const accessValue = env[accessKeyName];
|
|
192
|
+
if (accessValue) values.add(accessValue);
|
|
193
|
+
for (const provider2 of options.providers)
|
|
194
|
+
for (const name of provider2.secrets) {
|
|
195
|
+
if (credentialsOnly && provider2.identifiers?.includes(name)) continue;
|
|
196
|
+
const value = env[name];
|
|
197
|
+
if (value && value.length >= 4) values.add(value);
|
|
198
|
+
}
|
|
199
|
+
return [...values].sort((a, b) => b.length - a.length);
|
|
200
|
+
};
|
|
201
|
+
const redact = (text, credentialsOnly = false) => {
|
|
202
|
+
let out = text;
|
|
203
|
+
for (const value of secretValues(credentialsOnly)) out = out.split(value).join("[redacted]");
|
|
204
|
+
return out;
|
|
205
|
+
};
|
|
206
|
+
const decorate = (response2) => {
|
|
207
|
+
const headers2 = new Headers(response2.headers);
|
|
208
|
+
if (corsOrigin) {
|
|
209
|
+
headers2.set("access-control-allow-origin", corsOrigin);
|
|
210
|
+
const exposed = [...headers2.keys()].filter((name) => !name.startsWith("access-control-"));
|
|
211
|
+
if (exposed.length > 0) headers2.set("access-control-expose-headers", exposed.join(", "));
|
|
212
|
+
}
|
|
213
|
+
const vary = headers2.get("vary");
|
|
214
|
+
if (!vary) headers2.set("vary", "Origin");
|
|
215
|
+
else if (!/\borigin\b/i.test(vary)) headers2.set("vary", `${vary}, Origin`);
|
|
216
|
+
return new Response(response2.body, {
|
|
217
|
+
status: response2.status,
|
|
218
|
+
statusText: response2.statusText,
|
|
219
|
+
headers: headers2
|
|
220
|
+
});
|
|
221
|
+
};
|
|
222
|
+
const fail = (status, code, message) => decorate(
|
|
223
|
+
Response.json(
|
|
224
|
+
{ error: { code, message: redact(message) } },
|
|
225
|
+
{ status, headers: { "cache-control": "no-store" } }
|
|
226
|
+
)
|
|
227
|
+
);
|
|
228
|
+
const url = new URL(request.url);
|
|
229
|
+
if (basePath && url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`))
|
|
230
|
+
return fail(404, "not_found", "Not a sandbox proxy path");
|
|
231
|
+
const rest = url.pathname.slice(basePath.length);
|
|
232
|
+
if (request.method === "OPTIONS") {
|
|
233
|
+
const headers2 = new Headers({ vary: "Origin" });
|
|
234
|
+
if (corsOrigin) {
|
|
235
|
+
const requested = (request.headers.get("access-control-request-headers") ?? "").split(",").map((name) => name.trim().toLowerCase()).filter((name) => name && !DROP_REQUEST.has(name));
|
|
236
|
+
const allowed = /* @__PURE__ */ new Set([SANDBOX_KEY_HEADER, "content-type", ...requested]);
|
|
237
|
+
headers2.set("access-control-allow-origin", corsOrigin);
|
|
238
|
+
headers2.set("access-control-allow-methods", "GET, HEAD, POST, PUT, PATCH, DELETE");
|
|
239
|
+
headers2.set("access-control-allow-headers", [...allowed].join(", "));
|
|
240
|
+
headers2.set("access-control-max-age", "600");
|
|
241
|
+
}
|
|
242
|
+
return new Response(null, { status: 204, headers: headers2 });
|
|
243
|
+
}
|
|
244
|
+
const expected = env[accessKeyName];
|
|
245
|
+
const presented = request.headers.get(SANDBOX_KEY_HEADER) ?? "";
|
|
246
|
+
const access = !expected ? "disabled" : presented && safeEqual(presented, expected) ? "granted" : "denied";
|
|
247
|
+
if (rest === "" || rest === "/") {
|
|
248
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
249
|
+
return fail(405, "method_not_allowed", "The manifest only answers GET");
|
|
250
|
+
const manifest = {
|
|
251
|
+
access,
|
|
252
|
+
providers: options.providers.map((provider2) => {
|
|
253
|
+
if (access !== "granted")
|
|
254
|
+
return { id: provider2.id, label: provider2.label, configured: false, missing: [] };
|
|
255
|
+
const missing2 = missingSecrets(provider2, env);
|
|
256
|
+
let error;
|
|
257
|
+
if (missing2.length === 0 && provider2.check) {
|
|
258
|
+
try {
|
|
259
|
+
provider2.check(env);
|
|
260
|
+
} catch (caught) {
|
|
261
|
+
error = redact(caught instanceof Error ? caught.message : String(caught));
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
id: provider2.id,
|
|
266
|
+
label: provider2.label,
|
|
267
|
+
configured: missing2.length === 0 && error === void 0,
|
|
268
|
+
missing: missing2,
|
|
269
|
+
...error !== void 0 ? { error } : {}
|
|
270
|
+
};
|
|
271
|
+
})
|
|
272
|
+
};
|
|
273
|
+
return decorate(
|
|
274
|
+
Response.json(manifest, { headers: { "cache-control": "no-store" } })
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
if (access === "disabled")
|
|
278
|
+
return fail(
|
|
279
|
+
503,
|
|
280
|
+
"sandbox_disabled",
|
|
281
|
+
`The proxy has no ${accessKeyName}, so sandbox mode is off`
|
|
282
|
+
);
|
|
283
|
+
if (access === "denied")
|
|
284
|
+
return fail(401, "access_denied", `Send a valid access key in ${SANDBOX_KEY_HEADER}`);
|
|
285
|
+
const match = /^\/([^/]+)(\/.*)?$/.exec(rest);
|
|
286
|
+
const provider = match ? providers.get(decodeURIComponent(match[1] ?? "")) : void 0;
|
|
287
|
+
if (!match || !provider) return fail(404, "unknown_provider", "No such sandbox provider");
|
|
288
|
+
const path = match[2] ?? "/";
|
|
289
|
+
const missing = missingSecrets(provider, env);
|
|
290
|
+
if (missing.length > 0)
|
|
291
|
+
return fail(503, "not_configured", `Missing ${missing.join(", ")} on the proxy`);
|
|
292
|
+
try {
|
|
293
|
+
provider.check?.(env);
|
|
294
|
+
} catch (caught) {
|
|
295
|
+
return fail(
|
|
296
|
+
503,
|
|
297
|
+
"refused_credential",
|
|
298
|
+
caught instanceof Error ? caught.message : String(caught)
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
const target = provider.methods?.includes(request.method.toUpperCase()) === false ? void 0 : provider.target(path, url.search);
|
|
302
|
+
if (!target)
|
|
303
|
+
return fail(
|
|
304
|
+
501,
|
|
305
|
+
"unsupported_operation",
|
|
306
|
+
`${provider.label} sandbox does not relay ${request.method} ${path}`
|
|
307
|
+
);
|
|
308
|
+
const headers = new Headers();
|
|
309
|
+
for (const [name, value] of request.headers) {
|
|
310
|
+
const lower = name.toLowerCase();
|
|
311
|
+
if (DROP_REQUEST.has(lower) || DROP_REQUEST_PREFIX.some((prefix) => lower.startsWith(prefix)))
|
|
312
|
+
continue;
|
|
313
|
+
headers.append(name, value);
|
|
314
|
+
}
|
|
315
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD" && request.body !== null;
|
|
316
|
+
let outgoing = new Request(target, {
|
|
317
|
+
method: request.method,
|
|
318
|
+
headers,
|
|
319
|
+
redirect: "manual",
|
|
320
|
+
signal: request.signal,
|
|
321
|
+
...hasBody ? { body: request.body, duplex: "half" } : {}
|
|
322
|
+
});
|
|
323
|
+
let response;
|
|
324
|
+
try {
|
|
325
|
+
outgoing = await provider.authorize(outgoing, env);
|
|
326
|
+
response = await send(outgoing);
|
|
327
|
+
} catch (caught) {
|
|
328
|
+
return fail(
|
|
329
|
+
502,
|
|
330
|
+
"upstream_unreachable",
|
|
331
|
+
`${provider.label} sandbox could not be reached: ${caught instanceof Error ? caught.message : String(caught)}`
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
const responseHeaders = new Headers();
|
|
335
|
+
for (const [name, value] of response.headers) {
|
|
336
|
+
if (DROP_RESPONSE.has(name.toLowerCase())) continue;
|
|
337
|
+
responseHeaders.append(name, value);
|
|
338
|
+
}
|
|
339
|
+
let body = NULL_BODY.has(response.status) ? null : response.body;
|
|
340
|
+
if (body !== null && TEXT_TYPE.test(response.headers.get("content-type") ?? ""))
|
|
341
|
+
body = redact(await response.text(), true);
|
|
342
|
+
return decorate(
|
|
343
|
+
new Response(body, {
|
|
344
|
+
status: response.status,
|
|
345
|
+
statusText: response.statusText,
|
|
346
|
+
headers: responseHeaders
|
|
347
|
+
})
|
|
348
|
+
);
|
|
349
|
+
};
|
|
350
|
+
};
|
|
351
|
+
var sandboxProxyWorker = (options) => ({
|
|
352
|
+
fetch: (request, env) => createSandboxProxy({ ...options, env })(request)
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
export {
|
|
356
|
+
SANDBOX_KEY_HEADER,
|
|
357
|
+
sandboxProviders,
|
|
358
|
+
safeEqual,
|
|
359
|
+
createSandboxProxy,
|
|
360
|
+
sandboxProxyWorker
|
|
361
|
+
};
|
|
362
|
+
//# sourceMappingURL=chunk-CFLI52WY.js.map
|