@vite-hub/kv 0.1.0 → 0.3.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.
Files changed (67) hide show
  1. package/README.md +86 -15
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +4 -2
  5. package/dist/cli.js +98 -77
  6. package/dist/cloudflare-env-lOtHHsgP.js +46 -0
  7. package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
  8. package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
  9. package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
  10. package/dist/config-BXEVoZE3.js +250 -0
  11. package/dist/{create-storage-29gMzf41.js → create-storage-BGsrQKw3.js} +206 -50
  12. package/dist/{cursor-history-dqYDlsaD.js → cursor-history-BqIQePNP.js} +31 -14
  13. package/dist/database-72Jk3VVk.js +250 -0
  14. package/dist/{deno-kv-CSYGvRx4.js → deno-kv-BM9mYdUp.js} +12 -4
  15. package/dist/dev-peer-CHafxbtj.js +238 -0
  16. package/dist/driver-BwxgaQ-f.d.ts +15 -0
  17. package/dist/durability.d.ts +17 -0
  18. package/dist/durability.js +53 -0
  19. package/dist/error-diagnostics-BxqvtEIb.js +147 -0
  20. package/dist/errors-DbwufFZp.js +60 -0
  21. package/dist/errors.d.ts +12 -1
  22. package/dist/errors.js +2 -2
  23. package/dist/fs-lite-BLZId9_P.js +386 -0
  24. package/dist/fs-lite-RAoxu8L0.js +2 -0
  25. package/dist/index.d.ts +7 -2
  26. package/dist/index.js +302 -75
  27. package/dist/inspect-BIKQsqX4.js +118 -0
  28. package/dist/invariant-DolT9EEx.js +22 -0
  29. package/dist/main-F3Y22_uV.js +2353 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  32. package/dist/operations-B-WZ7P1h.js +1351 -0
  33. package/dist/{operations-pn8_eGob.js → operations-Ch-gKaey.js} +67 -58
  34. package/dist/operations.d.ts +15 -8
  35. package/dist/operations.js +55 -192
  36. package/dist/redis-shared-E5mahECF.js +94 -0
  37. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  38. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  39. package/dist/runtime/cloudflare-kv.js +1 -99
  40. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  41. package/dist/runtime/cloudflare-request-env.js +11 -0
  42. package/dist/runtime/nitro-plugin.d.ts +12 -0
  43. package/dist/runtime/nitro-plugin.js +22 -0
  44. package/dist/runtime/redis-driver.d.ts +11 -0
  45. package/dist/runtime/redis-driver.js +113 -0
  46. package/dist/runtime/unstorage-driver.d.ts +14 -0
  47. package/dist/runtime/unstorage-driver.js +33 -0
  48. package/dist/runtime/upstash-driver.d.ts +2 -2
  49. package/dist/runtime/upstash-driver.js +58 -98
  50. package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
  51. package/dist/types-DEiKew_3.d.ts +312 -0
  52. package/dist/upstash-DDlqTttY.js +40 -0
  53. package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
  54. package/dist/virtual-module.d.ts +2 -0
  55. package/dist/vite.d.ts +152 -11
  56. package/dist/vite.js +888 -2836
  57. package/package.json +30 -21
  58. package/dist/cli-Cniq99iX.d.ts +0 -85
  59. package/dist/cloudflare-env-C5rM7kUY.js +0 -74
  60. package/dist/config-DR6_5ZwI.js +0 -124
  61. package/dist/continuations-DPyH_vr1.js +0 -63
  62. package/dist/error-diagnostics-D_cQeZTi.js +0 -82
  63. package/dist/errors-Dc2oiW-Y.js +0 -38
  64. package/dist/fs-lite-CbLKxLut.js +0 -90
  65. package/dist/object-B1NW521B.js +0 -7
  66. package/dist/operations-ByuDE12r.js +0 -1442
  67. package/dist/types-CMDvN0Wr.d.ts +0 -81
@@ -0,0 +1,250 @@
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
2
+ import { t as chunks } from "./batch--v0ri69O.js";
3
+ //#region src/runtime/database.ts
4
+ /** The table that keeps the keys of every `database` store. Each store has its rows under its own `namespace`. */
5
+ const kvTable = "vitehub_kv";
6
+ function hasMethod(value, name) {
7
+ if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
8
+ return typeof Reflect.get(value, name) === "function";
9
+ }
10
+ /**
11
+ * A SQL client over the Drizzle database of the app. It reads `$client` on each query, because a Postgres Database on
12
+ * Cloudflare has a client per request.
13
+ */
14
+ function kvSqlClientFromDatabase(db, database) {
15
+ const client = () => Reflect.get(db, "$client");
16
+ const first = client();
17
+ const dialect = hasMethod(first, "unsafe") ? "postgresql" : hasMethod(first, "execute") ? "sqlite" : void 0;
18
+ if (!dialect) throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
19
+ database,
20
+ problem: "unsupported"
21
+ });
22
+ return {
23
+ dialect,
24
+ async query(sql, params) {
25
+ if (dialect === "postgresql") return await client().unsafe(sql, params);
26
+ return (await client().execute({
27
+ sql,
28
+ args: params
29
+ })).rows;
30
+ }
31
+ };
32
+ }
33
+ /** Once cleanup catches up, wait this long before checking for newly expired keys. */
34
+ const sweepIntervalMs = 6e4;
35
+ const sweepBatchSize = 1e3;
36
+ /** Rows per batch statement. It keeps the parameters below SQLite's oldest limit of 999. */
37
+ const batchRows = 200;
38
+ function ttlMilliseconds(ttl) {
39
+ if (!Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
40
+ const ms = Math.ceil(ttl * 1e3);
41
+ if (!Number.isSafeInteger(ms)) throw kvErrorDiagnostics.KV_INVALID_TTL();
42
+ return ms;
43
+ }
44
+ function decodeCursor(cursor) {
45
+ if (!cursor) return void 0;
46
+ try {
47
+ const value = JSON.parse(decodeURIComponent(cursor));
48
+ const after = typeof value === "object" && value !== null ? Reflect.get(value, "after") : void 0;
49
+ if (typeof after === "string") return after;
50
+ } catch {}
51
+ throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
52
+ }
53
+ /**
54
+ * KV in a table of the app's Database. Each atomic operation is one statement, so two servers that write one key at
55
+ * the same time get one winner. Expiry uses the clock of the Database. Works on Postgres and on SQLite 3.35 or later,
56
+ * such as libSQL.
57
+ */
58
+ function createDatabaseKVDriver(options, connect) {
59
+ const table = kvTable;
60
+ const namespace = options.namespace;
61
+ let pending;
62
+ let sweptAt = 0;
63
+ let sweeping = false;
64
+ let sweepWarned = false;
65
+ async function ready() {
66
+ pending ??= (async () => {
67
+ const client = await connect();
68
+ const columns = `(namespace text not null, "key" text not null, value text not null, expires_at bigint, primary key (namespace, "key"))`;
69
+ const index = `create index if not exists ${table}_expires_at on ${table} (expires_at)`;
70
+ try {
71
+ await client.query(`select 1 from ${table} limit 0`, []);
72
+ return client;
73
+ } catch {}
74
+ if (client.dialect === "postgresql") await client.query(`do $$ begin perform pg_advisory_xact_lock(hashtext('${table}')); create table if not exists ${table} ${columns}; ${index}; end $$`, []);
75
+ else {
76
+ await client.query(`create table if not exists ${table} ${columns}`, []);
77
+ await client.query(index, []);
78
+ }
79
+ return client;
80
+ })();
81
+ pending.catch(() => {
82
+ pending = void 0;
83
+ });
84
+ return pending;
85
+ }
86
+ /** Runs SQL written with `?` placeholders, which become `$1`, `$2`, ... on Postgres. `{now}` is the Database clock in ms. */
87
+ async function query(sql, params) {
88
+ const client = await ready();
89
+ const now = client.dialect === "postgresql" ? "(extract(epoch from statement_timestamp()) * 1000)::bigint" : "cast((julianday('now') - 2440587.5) * 86400000 as integer)";
90
+ let index = 0;
91
+ const text = sql.replaceAll("{now}", now);
92
+ return client.query(client.dialect === "postgresql" ? text.replace(/\?/g, () => `$${++index}`) : text, params);
93
+ }
94
+ const live = `(expires_at is null or expires_at > {now})`;
95
+ /**
96
+ * Deletes expired rows of this namespace in background batches. A full batch lets the next write sweep again;
97
+ * otherwise cleanup waits a minute. Reads already skip expired rows. A failed sweep, for example on a lock
98
+ * timeout, does not fail the write that runs it. It warns once and runs again a minute later.
99
+ */
100
+ async function sweep() {
101
+ if (sweeping || Date.now() - sweptAt < sweepIntervalMs) return;
102
+ sweeping = true;
103
+ sweptAt = Date.now();
104
+ try {
105
+ const { dialect } = await ready();
106
+ if ((await query(`delete from ${table} where (namespace, "key") in (
107
+ select namespace, "key" from ${table} where namespace = ? and expires_at <= {now} limit ${sweepBatchSize}${dialect === "postgresql" ? " for update skip locked" : ""}
108
+ ) returning 1`, [namespace])).length === sweepBatchSize) sweptAt = 0;
109
+ } catch (error) {
110
+ if (!sweepWarned) console.warn(`[vitehub] KV could not delete expired rows from ${table}. It tries again every minute.`, error);
111
+ sweepWarned = true;
112
+ } finally {
113
+ sweeping = false;
114
+ }
115
+ }
116
+ /** Matches keys that start with `prefix`. `substr()` counts characters on both dialects, unlike `LIKE` on SQLite, which ignores case. */
117
+ function prefixFilter(prefix) {
118
+ if (!prefix) return ["", []];
119
+ return [` and substr("key", 1, ?) = ?`, [[...prefix].length, prefix]];
120
+ }
121
+ async function keys(prefix) {
122
+ const [filter, params] = prefixFilter(prefix);
123
+ return (await query(`select "key" from ${table} where namespace = ? and ${live}${filter} order by "key"`, [namespace, ...params])).map((row) => String(row.key));
124
+ }
125
+ async function upsert(items, setOptions) {
126
+ sweep();
127
+ const ttl = setOptions?.ttl;
128
+ if (ttl !== void 0 && ttl !== null && ttl !== 0 && typeof ttl !== "number") throw kvErrorDiagnostics.KV_INVALID_TTL();
129
+ const ms = typeof ttl === "number" && ttl !== 0 ? ttlMilliseconds(ttl) : void 0;
130
+ const row = `(?, ?, ?, ${ms === void 0 ? "null" : "{now} + cast(? as bigint)"})`;
131
+ for (const batch of chunks(items, batchRows)) await query(`insert into ${table} (namespace, "key", value, expires_at) values ${batch.map(() => row).join(", ")}
132
+ on conflict (namespace, "key") do update set value = excluded.value, expires_at = excluded.expires_at`, batch.flatMap((item) => ms === void 0 ? [
133
+ namespace,
134
+ item.key,
135
+ item.value
136
+ ] : [
137
+ namespace,
138
+ item.key,
139
+ item.value,
140
+ ms
141
+ ]));
142
+ }
143
+ return {
144
+ name: "vitehub-kv-database",
145
+ options,
146
+ async hasItem(key) {
147
+ return (await query(`select 1 as found from ${table} where namespace = ? and "key" = ? and ${live}`, [namespace, key])).length > 0;
148
+ },
149
+ async getItem(key) {
150
+ const [row] = await query(`select value from ${table} where namespace = ? and "key" = ? and ${live}`, [namespace, key]);
151
+ return row ? String(row.value) : null;
152
+ },
153
+ async getItems(items) {
154
+ const values = /* @__PURE__ */ new Map();
155
+ for (const batch of chunks([...new Set(items.map((item) => item.key))], batchRows)) {
156
+ const rows = await query(`select "key", value from ${table} where namespace = ? and "key" in (${batch.map(() => "?").join(", ")}) and ${live}`, [namespace, ...batch]);
157
+ for (const row of rows) values.set(String(row.key), String(row.value));
158
+ }
159
+ return items.map((item) => ({
160
+ key: item.key,
161
+ value: values.get(item.key) ?? null
162
+ }));
163
+ },
164
+ setItem: (key, value, setOptions) => upsert([{
165
+ key,
166
+ value
167
+ }], setOptions),
168
+ setItems: (items, setOptions) => upsert(items, setOptions),
169
+ async removeItem(key) {
170
+ await query(`delete from ${table} where namespace = ? and "key" = ?`, [namespace, key]);
171
+ },
172
+ getKeys: (base) => keys(base),
173
+ async clear(base) {
174
+ const [filter, params] = prefixFilter(base);
175
+ await query(`delete from ${table} where namespace = ?${filter}`, [namespace, ...params]);
176
+ },
177
+ async listKeys({ cursor, limit, prefix }) {
178
+ const after = decodeCursor(cursor);
179
+ const [filter, params] = prefixFilter(prefix);
180
+ const rows = await query(`select "key" from ${table} where namespace = ? and ${live}${filter}${after === void 0 ? "" : ` and "key" > ?`} order by "key" limit ?`, [
181
+ namespace,
182
+ ...params,
183
+ ...after === void 0 ? [] : [after],
184
+ limit + 1
185
+ ]);
186
+ const page = rows.slice(0, limit).map((row) => String(row.key));
187
+ if (rows.length <= limit) return { keys: page };
188
+ return {
189
+ keys: page,
190
+ cursor: encodeURIComponent(JSON.stringify({ after: page.at(-1) }))
191
+ };
192
+ },
193
+ async setIfAbsentItem(key, value, ttl) {
194
+ sweep();
195
+ const ms = ttl === void 0 ? void 0 : ttlMilliseconds(ttl);
196
+ return (await query(`insert into ${table} (namespace, "key", value, expires_at) values (?, ?, ?, ${ms === void 0 ? "null" : "{now} + cast(? as bigint)"})
197
+ on conflict (namespace, "key") do update set value = excluded.value, expires_at = excluded.expires_at
198
+ where ${table}.expires_at is not null and ${table}.expires_at <= {now}
199
+ returning "key"`, ms === void 0 ? [
200
+ namespace,
201
+ key,
202
+ value
203
+ ] : [
204
+ namespace,
205
+ key,
206
+ value,
207
+ ms
208
+ ])).length > 0;
209
+ },
210
+ async getAndDeleteItem(key) {
211
+ const [row] = await query(`delete from ${table} where namespace = ? and "key" = ? returning value, ${live} as live`, [namespace, key]);
212
+ if (!row || !(row.live === true || Number(row.live) === 1)) return null;
213
+ return String(row.value);
214
+ },
215
+ async incrementItem(key, ttl) {
216
+ const ms = ttlMilliseconds(ttl);
217
+ sweep();
218
+ const { dialect } = await ready();
219
+ const value = `${table}.value`;
220
+ const counter = `(case when ${dialect === "postgresql" ? `${value} ~ '^(0|-{0,1}[1-9][0-9]{0,15})$'` : `(length(${value}) <= 17 and (${value} = '0' or (${value} glob '[1-9]*' and ${value} not glob '*[^0-9]*') or (${value} glob '-[1-9]*' and substr(${value}, 2) not glob '*[^0-9]*')))`} then cast(${value} as bigint) end)`;
221
+ const expired = `${table}.expires_at is not null and ${table}.expires_at <= {now}`;
222
+ const rows = await query(`insert into ${table} (namespace, "key", value, expires_at) values (?, ?, '1', {now} + cast(? as bigint))
223
+ on conflict (namespace, "key") do update set
224
+ value = case when ${expired} then '1' else cast(${counter} + 1 as text) end,
225
+ expires_at = case when ${expired} then excluded.expires_at else ${table}.expires_at end
226
+ where (${expired}) or ${counter} between -9007199254740992 and 9007199254740990
227
+ returning value`, [
228
+ namespace,
229
+ key,
230
+ ms
231
+ ]);
232
+ if (rows.length === 0) throw kvErrorDiagnostics.KV_INVALID_COUNTER();
233
+ const counterValue = Number(rows[0].value);
234
+ if (!Number.isSafeInteger(counterValue)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "The counter exceeds the JavaScript safe integer range." });
235
+ return counterValue;
236
+ },
237
+ async deleteIfEqualsItem(key, expected) {
238
+ return (await query(`delete from ${table} where namespace = ? and "key" = ? and value = ? and ${live} returning "key"`, [
239
+ namespace,
240
+ key,
241
+ expected
242
+ ])).length > 0;
243
+ },
244
+ async dispose() {
245
+ pending = void 0;
246
+ }
247
+ };
248
+ }
249
+ //#endregion
250
+ export { createDatabaseKVDriver as default, kvSqlClientFromDatabase };
@@ -1,5 +1,6 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
2
- import { n as recordCursor, t as createCursorHistory } from "./cursor-history-dqYDlsaD.js";
1
+ import { t as invariant } from "./invariant-DolT9EEx.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
3
+ import { n as recordCursor, t as createCursorHistory } from "./cursor-history-BqIQePNP.js";
3
4
  //#region src/runtime/deno-kv.ts
4
5
  function getDenoRuntime() {
5
6
  return globalThis.Deno;
@@ -70,7 +71,7 @@ function createDenoKVDriver(options = { driver: "deno-kv" }) {
70
71
  return (await matchingKeys(base)).flatMap((key) => fromDenoKey(key) ?? []).sort();
71
72
  },
72
73
  async listKeys({ cursor, limit, prefix = "" }) {
73
- if (disposed) throw new Error("KV storage has been disposed.");
74
+ invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
74
75
  const continuation = cursor ? cursorHistories.take(cursor) : {
75
76
  providerCursor: void 0,
76
77
  history: /* @__PURE__ */ new Set(),
@@ -91,7 +92,7 @@ function createDenoKVDriver(options = { driver: "deno-kv" }) {
91
92
  cursorHistories.complete(cursor);
92
93
  return { keys };
93
94
  }
94
- if (disposed) throw new Error("KV storage has been disposed.");
95
+ invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
95
96
  if (cursors.has(iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV list returned a repeated pagination cursor." });
96
97
  if (!recordCursor(cursors, iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV rejected pagination after the cursor history limit was reached." });
97
98
  const nextCursor = cursorHistories.store(iterator.cursor, cursors);
@@ -111,6 +112,13 @@ function createDenoKVDriver(options = { driver: "deno-kv" }) {
111
112
  async removeItem(key) {
112
113
  await (await open()).delete(toDenoKey(key));
113
114
  },
115
+ async setIfAbsentItem(key, value, ttl) {
116
+ const denoKey = toDenoKey(key);
117
+ return (await (await open()).atomic().check({
118
+ key: denoKey,
119
+ versionstamp: null
120
+ }).set(denoKey, value, toDenoExpireIn(ttl)).commit()).ok;
121
+ },
114
122
  async setItem(key, value, writeOptions) {
115
123
  await (await open()).set(toDenoKey(key), value, toDenoExpireIn(writeOptions?.ttl));
116
124
  }
@@ -0,0 +1,238 @@
1
+ //#region ../internal/src/dev-peer.ts
2
+ /**
3
+ * Proof that a development request came from this machine, for dev servers that run the app behind a proxy.
4
+ *
5
+ * Nitro 3 runs the app in a worker behind an env-runner proxy. The worker never sees the client's address
6
+ * (https://github.com/unjs/env-runner/issues/113):
7
+ * over a Unix socket it sees none, and over TCP it sees the proxy on `127.0.0.1`. The proxy forwards a client
8
+ * `x-forwarded-for` as is. The front process sees the real socket, so its Nitro dev handler removes any client copy
9
+ * of {@link viteHubDevPeerHeader} and, for a loopback socket only, adds an HMAC over the method, the path, a
10
+ * timestamp, and a nonce. The key is random for each process and reaches the worker only through its environment
11
+ * ({@link viteHubDevPeerKeyEnv}), never through a header. The worker takes the key out of its environment, so the
12
+ * processes that the app starts do not inherit it.
13
+ *
14
+ * A tunnel or a reverse proxy on this machine, such as `cloudflared`, `ngrok`, `tailscale serve`, or Caddy, connects
15
+ * from a loopback socket too. Such a request is not from this machine, so the front process signs no request that
16
+ * names another host or carries a forwarding header ({@link isViteHubForwardedRequest}). A forwarder that copies raw
17
+ * TCP bytes, such as `ssh -R`, sends no such sign. Only sign-in protects a dev server behind one.
18
+ *
19
+ * The worker calls {@link verifyViteHubDevPeer}. Each piece of evidence is valid once, for one method and path, for a
20
+ * short time. This module uses Web Crypto and no Node import, so the check also runs in Worker runtimes.
21
+ */
22
+ /** The request header that carries the evidence from the front process to the worker. */
23
+ const viteHubDevPeerHeader = "x-vitehub-dev-peer";
24
+ /** The environment variable that carries the per-process key from the front process to the worker. */
25
+ const viteHubDevPeerKeyEnv = "VITEHUB_DEV_PEER_KEY";
26
+ /** How long evidence stays valid. A dev worker that is still starting can hold a request for some seconds. */
27
+ const viteHubDevPeerMaxAgeMs = 6e4;
28
+ const futureSkewMs = 5e3;
29
+ const version = "v1";
30
+ const evidencePattern = /^v1\.(\d{13})\.([\w-]{22})\.([\w-]{43})$/;
31
+ const encoder = new TextEncoder();
32
+ const stateKey = Symbol.for("vitehub.dev-peer");
33
+ const scope = globalThis;
34
+ const state = scope[stateKey] ??= {
35
+ keys: /* @__PURE__ */ new Map(),
36
+ nonces: /* @__PURE__ */ new Map(),
37
+ verified: /* @__PURE__ */ new WeakMap()
38
+ };
39
+ function base64url(bytes) {
40
+ let binary = "";
41
+ for (const byte of bytes) binary += String.fromCharCode(byte);
42
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
43
+ }
44
+ function fromBase64url(value) {
45
+ const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/"));
46
+ const bytes = new Uint8Array(binary.length);
47
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
48
+ return bytes;
49
+ }
50
+ function random(length) {
51
+ return base64url(crypto.getRandomValues(new Uint8Array(length)));
52
+ }
53
+ function importKey(key) {
54
+ let imported = state.keys.get(key);
55
+ if (!imported) {
56
+ imported = crypto.subtle.importKey("raw", encoder.encode(key), {
57
+ hash: "SHA-256",
58
+ name: "HMAC"
59
+ }, false, ["sign", "verify"]);
60
+ state.keys.set(key, imported);
61
+ }
62
+ return imported;
63
+ }
64
+ function pathnameOf(path) {
65
+ return new URL(`http://localhost${path}`).pathname;
66
+ }
67
+ function payload(method, path, timestamp, nonce) {
68
+ return encoder.encode(`vitehub-dev-peer\n${version}\n${method.toUpperCase()}\n${pathnameOf(path)}\n${timestamp}\n${nonce}`);
69
+ }
70
+ /** Whether a socket address is a loopback address. A missing address, such as a Unix socket peer, is not. */
71
+ function isViteHubLoopbackAddress(address) {
72
+ if (!address) return false;
73
+ const v4 = address.toLowerCase().startsWith("::ffff:") ? address.slice(7) : address;
74
+ return v4 === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v4);
75
+ }
76
+ /**
77
+ * The key of this process, created on the first call and written to `process.env` so a dev worker that starts later
78
+ * inherits it. A value that the process inherited, for example from a parent process or a shell, is replaced.
79
+ * Call it only in the front process of a development server.
80
+ */
81
+ function useViteHubDevPeerKey() {
82
+ state.key ??= random(32);
83
+ process.env[viteHubDevPeerKeyEnv] = state.key;
84
+ return state.key;
85
+ }
86
+ /**
87
+ * The key that this process verifies with: its own key in the front process, or the key that a dev worker inherited
88
+ * from its front process. `undefined` when no front process set one.
89
+ *
90
+ * A dev worker removes the key from its `process.env` on the first read, so a child process that the app starts, such
91
+ * as a shell command of an Agent, does not inherit it. The module also reads once when it loads.
92
+ */
93
+ function readViteHubDevPeerKey() {
94
+ const env = globalThis.process?.env;
95
+ const value = env?.[viteHubDevPeerKeyEnv];
96
+ if (state.key && value === state.key) return state.key;
97
+ if (env && value !== void 0) {
98
+ Reflect.deleteProperty(env, viteHubDevPeerKeyEnv);
99
+ state.inherited = typeof value === "string" && value.length >= 32 ? value : void 0;
100
+ }
101
+ return state.inherited;
102
+ }
103
+ /** Create the evidence for one request that came from a loopback socket. */
104
+ async function signViteHubDevPeer(key, request, now = Date.now()) {
105
+ const timestamp = String(Math.trunc(now)).padStart(13, "0");
106
+ const nonce = random(16);
107
+ const signature = await crypto.subtle.sign("HMAC", await importKey(key), payload(request.method, request.path, timestamp, nonce));
108
+ return `${version}.${timestamp}.${nonce}.${base64url(new Uint8Array(signature))}`;
109
+ }
110
+ function forgetExpiredNonces(now) {
111
+ for (const [nonce, expires] of state.nonces) if (expires <= now) state.nonces.delete(nonce);
112
+ }
113
+ /**
114
+ * Whether `request` carries valid evidence from the front process: signed with `key`, for this method and path, not
115
+ * older than {@link viteHubDevPeerMaxAgeMs}, and not used by another request. A second check of the same `Request`
116
+ * object gives the same answer. Missing, malformed, tampered, expired, and replayed evidence gives `false`.
117
+ */
118
+ async function verifyViteHubDevPeer(request, key, now = Date.now()) {
119
+ const known = state.verified.get(request);
120
+ if (known !== void 0) return known;
121
+ const verified = await verify(request, key, now);
122
+ state.verified.set(request, verified);
123
+ return verified;
124
+ }
125
+ async function verify(request, key, now) {
126
+ const match = evidencePattern.exec(request.headers.get("x-vitehub-dev-peer") ?? "");
127
+ if (!match) return false;
128
+ const [, timestamp = "", nonce = "", signature = ""] = match;
129
+ const issued = Number(timestamp);
130
+ if (issued < now - 6e4 || issued > now + futureSkewMs) return false;
131
+ forgetExpiredNonces(now);
132
+ if (state.nonces.has(nonce)) return false;
133
+ const bytes = fromBase64url(signature);
134
+ if (base64url(bytes) !== signature) return false;
135
+ const path = new URL(request.url).pathname;
136
+ if (!await crypto.subtle.verify("HMAC", await importKey(key), bytes, payload(request.method, path, timestamp, nonce))) return false;
137
+ if (state.nonces.has(nonce)) return false;
138
+ state.nonces.set(nonce, issued + viteHubDevPeerMaxAgeMs + futureSkewMs);
139
+ return true;
140
+ }
141
+ /**
142
+ * Whether a development request came from this machine. The socket or signed front-process evidence proves the peer.
143
+ * - A dev server whose front process signs loopback requests gives its worker a key. The worker then trusts only
144
+ * that evidence, because its own peer is the proxy of the front process.
145
+ * - Without a key, require a loopback `remoteAddress` from the host adapter and no forwarding headers. An unknown
146
+ * peer is refused. A signed request can carry forwarding headers that Nitro's own proxy added after signing.
147
+ */
148
+ async function isViteHubLoopbackPeer(request, remoteAddress) {
149
+ if (remoteAddress && !isViteHubLoopbackAddress(remoteAddress)) return false;
150
+ const key = readViteHubDevPeerKey();
151
+ return key ? verifyViteHubDevPeer(request, key) : isViteHubLoopbackAddress(remoteAddress) && !isViteHubForwardedRequest(Object.fromEntries(request.headers));
152
+ }
153
+ const forwardingHeaders = /* @__PURE__ */ new Set([
154
+ "cdn-loop",
155
+ "fastly-client-ip",
156
+ "fly-client-ip",
157
+ "forwarded",
158
+ "true-client-ip",
159
+ "via",
160
+ "x-client-ip",
161
+ "x-cluster-client-ip",
162
+ "x-original-forwarded-for",
163
+ "x-real-ip",
164
+ "x-vercel-forwarded-for"
165
+ ]);
166
+ const forwardingHeaderPrefixes = [
167
+ "x-forwarded-",
168
+ "cf-",
169
+ "ngrok-",
170
+ "tailscale-"
171
+ ];
172
+ /**
173
+ * Whether a request carries a header that a proxy, a tunnel, or a CDN adds for the client that it forwards. The front
174
+ * process signs no such request, because it came from somewhere else through a program on this machine.
175
+ */
176
+ function isViteHubForwardedRequest(headers) {
177
+ return Object.keys(headers).some((name) => {
178
+ const lower = name.toLowerCase();
179
+ return forwardingHeaders.has(lower) || forwardingHeaderPrefixes.some((prefix) => lower.startsWith(prefix));
180
+ });
181
+ }
182
+ /** Whether a `Host` header names this machine: `localhost`, a `.localhost` name, a `127.0.0.0/8` address, or `[::1]`. */
183
+ function isViteHubLoopbackHost(host) {
184
+ if (!host || /[/?#@\\]/.test(host)) return false;
185
+ let name;
186
+ try {
187
+ name = new URL(`http://${host}`).hostname;
188
+ } catch {
189
+ return false;
190
+ }
191
+ return name === "localhost" || name.endsWith(".localhost") || name === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(name);
192
+ }
193
+ /**
194
+ * Remove a client copy of the evidence. Returns the request to sign when it came from a loopback socket, names this
195
+ * machine in `Host`, and carries no forwarding header.
196
+ */
197
+ function takeSignableRequest(node) {
198
+ delete node.headers[viteHubDevPeerHeader];
199
+ if (!isViteHubLoopbackAddress(node.socket?.remoteAddress) || !node.method || !node.url?.startsWith("/")) return;
200
+ const authority = node.headers[":authority"];
201
+ if (authority !== void 0 && node.headers.host !== void 0 && node.headers.host !== authority) return;
202
+ const host = authority ?? node.headers.host;
203
+ if (typeof host !== "string" || !isViteHubLoopbackHost(host) || isViteHubForwardedRequest(node.headers)) return;
204
+ return {
205
+ method: node.method,
206
+ path: node.url
207
+ };
208
+ }
209
+ /**
210
+ * The Nitro dev handler that runs in the front process before Nitro forwards a request to its worker. It never
211
+ * answers a request itself.
212
+ */
213
+ async function viteHubDevPeerDevHandler(event) {
214
+ const node = event.runtime?.node?.req;
215
+ const web = node ? event.req?.headers : void 0;
216
+ web?.delete(viteHubDevPeerHeader);
217
+ if (!node) return;
218
+ const request = takeSignableRequest(node);
219
+ if (!request) return;
220
+ const evidence = await signViteHubDevPeer(useViteHubDevPeerKey(), request);
221
+ node.headers[viteHubDevPeerHeader] = evidence;
222
+ web?.set(viteHubDevPeerHeader, evidence);
223
+ }
224
+ const devHandlerMark = Symbol.for("vitehub.dev-peer.dev-handler");
225
+ const devHandler = Object.assign(viteHubDevPeerDevHandler, { [devHandlerMark]: true });
226
+ /**
227
+ * Put the dev handler first in Nitro's `devHandlers`, once, and create the key of this process. Call it while Nitro
228
+ * is configured for development, before its worker starts.
229
+ */
230
+ function addViteHubDevPeerDevHandler(devHandlers) {
231
+ useViteHubDevPeerKey();
232
+ const index = devHandlers.findIndex((entry) => typeof entry.handler === "function" && devHandlerMark in entry.handler);
233
+ if (index !== -1) devHandlers.splice(index, 1);
234
+ devHandlers.unshift({ handler: devHandler });
235
+ }
236
+ readViteHubDevPeerKey();
237
+ //#endregion
238
+ export { isViteHubLoopbackPeer as n, addViteHubDevPeerDevHandler as t };
@@ -0,0 +1,15 @@
1
+ import { i as TransactionOptions, t as Driver } from "./types-Bj3EQoRg.js";
2
+ import { g as KVListPage, h as KVListOptions } from "./types-DEiKew_3.js";
3
+ //#region src/runtime/driver.d.ts
4
+ type KVRuntimeDriver = Driver & Record<string, unknown> & {
5
+ validateBatch?: (items: Parameters<NonNullable<Driver["setItems"]>>[0], removals: string[], options?: TransactionOptions) => void | Promise<void>;
6
+ /** Deletes the key when it holds the serialized `expected` value. Resolves `true` when this call deleted it. */
7
+ deleteIfEqualsItem?: (key: string, expected: string) => Promise<boolean>;
8
+ getAndDeleteItem?: <T = unknown>(key: string) => Promise<T | null>;
9
+ incrementItem?: (key: string, ttl: number) => Promise<number>;
10
+ listKeys: (options: KVListOptions) => Promise<KVListPage>;
11
+ /** Writes the serialized value only when the key is missing. Resolves `true` when this call wrote it. */
12
+ setIfAbsentItem?: (key: string, value: string, ttl?: number) => Promise<boolean>;
13
+ };
14
+ //#endregion
15
+ export { KVRuntimeDriver as t };
@@ -0,0 +1,17 @@
1
+ import { Durability, DurabilityContext } from "@vite-hub/runtime/durability";
2
+ //#region src/durability.d.ts
3
+ /** One KV store as the build resolves it, without credentials. */
4
+ export interface KVDurabilityStore {
5
+ /** The folder of a file store. */
6
+ base?: string;
7
+ /** The Database of a `database` store. Default: `default`. */
8
+ database?: string;
9
+ driver: string;
10
+ }
11
+ /** What the build passes to `kvDurability()`. */
12
+ export interface KVDurabilityInput {
13
+ stores: Record<string, KVDurabilityStore>;
14
+ }
15
+ /** The durability of each KV store, from its driver. A `database` store follows the Database that holds its rows. */
16
+ export declare function kvDurability(input: KVDurabilityInput, context: DurabilityContext): Durability[];
17
+ //#endregion
@@ -0,0 +1,53 @@
1
+ //#region src/durability.ts
2
+ const sharedStores = {
3
+ "cloudflare": "A Cloudflare KV namespace that every Worker reads.",
4
+ "deno-kv": "Deno KV, which Deno Deploy shares between isolates.",
5
+ "redis": "Redis.",
6
+ "upstash": "Upstash Redis over HTTP."
7
+ };
8
+ function classify(store, context) {
9
+ const shared = sharedStores[store.driver];
10
+ if (shared) return {
11
+ store: store.driver,
12
+ scope: "shared",
13
+ reason: shared
14
+ };
15
+ if (store.driver === "database") {
16
+ const name = store.database ?? "default";
17
+ const database = context.find("database", name);
18
+ if (!database) return {
19
+ store: "database",
20
+ scope: "process",
21
+ reason: `The ${name} Database is off.`,
22
+ fix: "Turn on the Database, or use a Redis store."
23
+ };
24
+ return {
25
+ store: `database (${database.store})`,
26
+ scope: database.scope,
27
+ reason: `Rows in the ${name} Database. ${database.reason}`,
28
+ ...database.fix ? { fix: database.fix } : {}
29
+ };
30
+ }
31
+ if (store.driver === "memory") return {
32
+ store: "memory",
33
+ scope: "process",
34
+ reason: "Values live in the memory of this process.",
35
+ fix: "Set `kv: { driver: \"redis\" }` and supply REDIS_URL to every instance, or use a Postgres Default Database."
36
+ };
37
+ return {
38
+ store: store.driver,
39
+ scope: "host",
40
+ reason: `Files in ${store.base ?? "the KV folder"} on this host.`,
41
+ fix: "Set `kv: { driver: \"redis\" }` and supply REDIS_URL to every instance, or select a shared Database store."
42
+ };
43
+ }
44
+ /** The durability of each KV store, from its driver. A `database` store follows the Database that holds its rows. */
45
+ function kvDurability(input, context) {
46
+ return Object.entries(input.stores).map(([name, store]) => ({
47
+ primitive: "kv",
48
+ ...name === "default" ? {} : { name },
49
+ ...classify(store, context)
50
+ }));
51
+ }
52
+ //#endregion
53
+ export { kvDurability };