@barqjs/start 0.0.0-stage → 0.2.0-next.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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +817 -2
  3. package/dist/client-BsyxVCyu.js +1554 -0
  4. package/dist/client-BsyxVCyu.js.map +1 -0
  5. package/dist/client-DidH0F2e.d.ts +450 -0
  6. package/dist/client-DidH0F2e.d.ts.map +1 -0
  7. package/dist/client.d.ts +25 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-Bhk_aIkx.d.ts +47 -0
  10. package/dist/env-Bhk_aIkx.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +43 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-B4o7eyCr.d.ts +925 -0
  15. package/dist/index-B4o7eyCr.d.ts.map +1 -0
  16. package/dist/index.d.ts +18 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-B-tI8QHQ.d.ts +574 -0
  19. package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +281 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +118 -0
  24. package/dist/prerender.d.ts.map +1 -0
  25. package/dist/prerender.js +289 -0
  26. package/dist/prerender.js.map +1 -0
  27. package/dist/protocol.d.ts +56 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +25 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +144 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +221 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-DG6jb_NA.js +1253 -0
  36. package/dist/server-DG6jb_NA.js.map +1 -0
  37. package/dist/server.d.ts +159 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-odXG7kLA.js +1151 -0
  41. package/dist/src-odXG7kLA.js.map +1 -0
  42. package/dist/static-fn-CXjJi-It.js +122 -0
  43. package/dist/static-fn-CXjJi-It.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +698 -0
  46. package/src/context.ts +699 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +121 -0
  50. package/src/frames-client.ts +1220 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +740 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +292 -0
  56. package/src/middleware.ts +994 -0
  57. package/src/prerender.ts +477 -0
  58. package/src/protocol.ts +61 -0
  59. package/src/rate-limit.ts +202 -0
  60. package/src/serve.ts +153 -0
  61. package/src/server.ts +1026 -0
  62. package/src/session.ts +449 -0
  63. package/src/start-instance.ts +147 -0
  64. package/src/static-fn.ts +181 -0
  65. package/src/static.ts +302 -0
  66. package/src/stubs.ts +32 -0
  67. package/src/timing.ts +29 -0
  68. package/src/wire-types.ts +138 -0
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Rate limiting, as a middleware — so one closure guards a server function and
3
+ * a route handler alike.
4
+ *
5
+ * THE STORE HAS NO DEFAULT, and that is the whole design of this file.
6
+ *
7
+ * An in-memory counter is correct for exactly one process. Behind a load
8
+ * balancer with three instances it permits three times the limit, and behind an
9
+ * autoscaler it permits an unbounded multiple — while passing every test, on
10
+ * every machine, in every CI run. That is the silent failure this codebase
11
+ * refuses: a limiter that reads as working and protects nothing. Requiring the
12
+ * store makes the distributed question unavoidable at the call site, which is
13
+ * the only place it can be answered.
14
+ *
15
+ * `memoryStore()` ships beside it and is named for what it is. Use it for a
16
+ * single instance, and know that is what you have chosen.
17
+ *
18
+ * WHAT THIS IS NOT: a defence against a distributed flood. A limiter in the
19
+ * application has already paid for the TLS handshake, the routing and the
20
+ * middleware above it. It is here to stop credential stuffing, scraping and one
21
+ * client hammering an expensive handler — the things a proxy in front cannot see
22
+ * because they are shaped like ordinary traffic. Volumetric denial of service is
23
+ * the edge's problem and always was.
24
+ */
25
+
26
+ import { type ForwardedForTrust, assertForwardedForTrust, getRequestIP } from "./context.ts";
27
+ import type { Middleware } from "./index.ts";
28
+
29
+ /** One key's usage, as the store hands it back. */
30
+ export interface RateLimitCount {
31
+ /** How many requests this key has made in the current window. */
32
+ readonly count: number;
33
+ /** When the current window ends, as a millisecond timestamp. */
34
+ readonly resetAt: number;
35
+ }
36
+
37
+ /**
38
+ * Where the counts live.
39
+ *
40
+ * ONE METHOD, and it is atomic by contract: `hit` must increment and return the
41
+ * new value in a single step. A `get` then `set` pair is a race — two requests
42
+ * read the same count and both write it — and a limiter that loses increments
43
+ * under load is one that stops working exactly when it is needed. Redis does
44
+ * this with `INCR` plus `PEXPIRE`; the memory store below does it by being
45
+ * single-threaded.
46
+ */
47
+ export interface RateLimitStore {
48
+ hit(key: string, windowMs: number): RateLimitCount | Promise<RateLimitCount>;
49
+ }
50
+
51
+ export interface RateLimitOptions {
52
+ /** How many requests a key may make per window. */
53
+ readonly limit: number;
54
+ /** The window, in milliseconds. */
55
+ readonly windowMs: number;
56
+ /**
57
+ * What counts as one caller.
58
+ *
59
+ * There is no default, for the same reason the store has none: keying by IP is
60
+ * right for a public endpoint and wrong for an authenticated one behind a
61
+ * corporate NAT, where it limits a whole building as though it were one user.
62
+ * Key by user id where there is one, and by IP only where there is not.
63
+ *
64
+ * Returning `null` EXEMPTS the request — an internal caller, a health check.
65
+ */
66
+ readonly key: () => string | null | Promise<string | null>;
67
+ readonly store: RateLimitStore;
68
+ /**
69
+ * What to answer when the limit is reached. A 429 with `Retry-After` by
70
+ * default, which is what a well-behaved client backs off on.
71
+ */
72
+ readonly onLimit?: (info: RateLimitCount & { readonly limit: number }) => Response;
73
+ }
74
+
75
+ /**
76
+ * A store for ONE PROCESS. Named so the choice is visible at the call site.
77
+ *
78
+ * Correct for a single instance and wrong for every other deployment — see the
79
+ * header. It is here because "no store at all" would push everyone to write this
80
+ * same map badly, not because it is the one to reach for.
81
+ *
82
+ * Expired entries are swept by a `hit` rather than on a timer: a timer keeps
83
+ * the process alive on Node and has to be unref'd. A key is one caller and most
84
+ * callers are never seen again (a scan, a client rotating through an IPv6
85
+ * prefix), so an entry dropped only when its own key came back would stay for
86
+ * the life of the process and the map would grow with every address ever seen.
87
+ *
88
+ * The sweep runs at most once per the longest window in use, so an entry that
89
+ * has expired is gone by the second sweep after it was made, and the map holds
90
+ * what the last two such windows saw rather than everything since boot.
91
+ */
92
+ export function memoryStore(): RateLimitStore {
93
+ const windows = new Map<string, { count: number; resetAt: number }>();
94
+ let longest = 0;
95
+ let sweepAt = 0;
96
+ return {
97
+ hit(key, windowMs) {
98
+ const now = Date.now();
99
+ if (windowMs > longest) longest = windowMs;
100
+ if (now >= sweepAt) {
101
+ for (const [seen, window] of windows) {
102
+ if (window.resetAt <= now) windows.delete(seen);
103
+ }
104
+ sweepAt = now + longest;
105
+ }
106
+ const found = windows.get(key);
107
+ if (found === undefined || found.resetAt <= now) {
108
+ const resetAt = now + windowMs;
109
+ windows.set(key, { count: 1, resetAt });
110
+ return { count: 1, resetAt };
111
+ }
112
+ found.count += 1;
113
+ // A COPY, because the record goes on counting. A caller reads this after
114
+ // an `await`, and by then the hits that arrived behind it have landed.
115
+ return { count: found.count, resetAt: found.resetAt };
116
+ },
117
+ };
118
+ }
119
+
120
+ /**
121
+ * Key a limit by client address.
122
+ *
123
+ * `xForwardedFor` IS OFF BY DEFAULT and turning it on is a claim about the
124
+ * deployment: `X-Forwarded-For` is a header a CLIENT can send, so trusting it
125
+ * where no proxy overwrites it lets any caller pick their own bucket and the
126
+ * limit stops existing. See `getRequestIP`.
127
+ *
128
+ * `true` reads the LEFTMOST entry, which is the client only when the edge proxy
129
+ * overwrites the header. Behind a proxy that appends, pass
130
+ * `{ trustedProxies: n }` for the `n` proxies you run: it reads the entry the
131
+ * outermost of them wrote and ignores anything a caller put in front of it.
132
+ *
133
+ * A request with no address at all keys as `"unknown"`, which pools every such
134
+ * caller into one bucket — strict rather than exempt, because the alternative is
135
+ * a bucket an attacker can opt into by arranging to have no address.
136
+ */
137
+ export function byIP(options: { readonly xForwardedFor?: ForwardedForTrust } = {}): () => string {
138
+ // Here and not on the first request: `rateLimit` fails OPEN when its key
139
+ // throws, so a bad hop count found per call would switch the limit off.
140
+ assertForwardedForTrust(options.xForwardedFor);
141
+ return () => getRequestIP(options) ?? "unknown";
142
+ }
143
+
144
+ function tooMany(info: RateLimitCount & { limit: number }): Response {
145
+ const seconds = Math.max(1, Math.ceil((info.resetAt - Date.now()) / 1000));
146
+ return new Response("too many requests", {
147
+ status: 429,
148
+ headers: {
149
+ "retry-after": String(seconds),
150
+ "ratelimit-limit": String(info.limit),
151
+ "ratelimit-remaining": "0",
152
+ "ratelimit-reset": String(seconds),
153
+ },
154
+ });
155
+ }
156
+
157
+ /**
158
+ * The middleware.
159
+ *
160
+ * It runs BEFORE the handler and before validation, which is the whole point:
161
+ * refusing after the body has been parsed is a refusal that already did the
162
+ * work. That ordering is `serverRpc`'s and the route dispatch's, and it is why
163
+ * this is a middleware rather than something a handler calls.
164
+ *
165
+ * A STORE THAT THROWS FAILS OPEN, deliberately and loudly. If Redis is down,
166
+ * refusing every request turns a limiter into the outage — so the request
167
+ * proceeds and the failure is reported. That is the right trade for a limiter
168
+ * and the wrong one for an authorization check, which is why this is not one.
169
+ */
170
+ export function rateLimit(options: RateLimitOptions): Middleware {
171
+ const { limit, windowMs, key, store, onLimit = tooMany } = options;
172
+ if (!Number.isInteger(limit) || limit < 1) {
173
+ throw new RangeError(
174
+ `[barq] \`rateLimit({ limit })\` must be a positive integer, and it is ${limit}. Pass how many requests one key may make per window, such as \`limit: 10\`.`,
175
+ );
176
+ }
177
+ if (!Number.isFinite(windowMs) || windowMs <= 0) {
178
+ throw new RangeError(
179
+ `[barq] \`rateLimit({ windowMs })\` must be a positive number of milliseconds, and it is ${windowMs}. Pass the window length, such as \`windowMs: 60_000\`.`,
180
+ );
181
+ }
182
+
183
+ return async (next) => {
184
+ let info: RateLimitCount;
185
+ try {
186
+ const bucket = await key();
187
+ // `null` exempts — an internal caller, a health check.
188
+ if (bucket === null) return next();
189
+ info = await store.hit(bucket, windowMs);
190
+ } catch (error) {
191
+ // FAIL OPEN. A limiter that refuses everything when its store is down has
192
+ // become the outage it exists to prevent.
193
+ console.error(
194
+ "[barq] The rate-limit `store` or `key` threw, so this request was let through without being counted. The error:",
195
+ error,
196
+ );
197
+ return next();
198
+ }
199
+ if (info.count > limit) throw onLimit({ ...info, limit });
200
+ return next();
201
+ };
202
+ }
package/src/serve.ts ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The production entry — runtime-agnostic.
3
+ *
4
+ * `srvx`'s root export resolves by runtime condition (`deno`, `bun`, `workerd`,
5
+ * `node`, and a generic default), so one entry serves Node, Deno, Bun and
6
+ * Cloudflare without a per-runtime adapter here. The handler below is an
7
+ * ordinary `Request -> Response` function, which is the only shape all of them
8
+ * agree on.
9
+ *
10
+ * The dev half is deliberately NOT this: Vite's middleware pipeline is
11
+ * Connect-shaped and hands over a Node request/response pair, so `vite.ts`
12
+ * adapts with `srvx/node`. That is adapting Vite, not choosing a runtime.
13
+ */
14
+
15
+ import { type Server, type ServerOptions, serve } from "srvx";
16
+
17
+ import { type HandlerOptions, handleServerFn } from "./server.ts";
18
+ import { type StaticOptions, assetMiddleware } from "./static.ts";
19
+
20
+ export type { AssetManifest, PrerenderedAsset, StaticOptions } from "./static.ts";
21
+ export { ASSET_MANIFEST_FILE, assetMiddleware } from "./static.ts";
22
+
23
+ export interface BarqServeOptions extends Omit<ServerOptions, "fetch">, HandlerOptions {
24
+ /**
25
+ * What answers everything that is not a server function — a page render, a
26
+ * static file, an API route.
27
+ *
28
+ * A 404 is the default rather than an error: a server that only exposes
29
+ * server functions is a legitimate deployment, and inventing a page handler
30
+ * for it would be worse than saying nothing is there.
31
+ */
32
+ fetch?: (request: Request) => Response | Promise<Response>;
33
+ /**
34
+ * Serve the build's own files, in front of everything else.
35
+ *
36
+ * `true` serves `dist/client` through the manifest the build wrote. Omitted,
37
+ * nothing static is served — which is right for a deployment whose assets are
38
+ * on a CDN and for a server that only answers server functions, and wrong
39
+ * enough to notice for anything else.
40
+ *
41
+ * `static.ts` explains why a manifest rather than a `stat`: the common request
42
+ * is a MISS, and answering it without touching the disk is worth 0.5 us.
43
+ */
44
+ static?: boolean | StaticOptions;
45
+ /**
46
+ * The document to answer a page request with, for a deployment that renders
47
+ * its pages in the browser.
48
+ *
49
+ * A path to the built `index.html`, or a `file:` URL of it. Consulted only
50
+ * after everything else has declined — the assets, the server functions and
51
+ * the route handlers all run first — so `/api/health` still answers JSON and
52
+ * `/_barq/fn/<id>` is still reserved. Nothing else can do this job: the asset
53
+ * middleware answers what the build WROTE, and an SPA's routes are exactly the
54
+ * paths it did not.
55
+ */
56
+ spa?: string | URL;
57
+ }
58
+
59
+ /**
60
+ * One request, in the order the checks have to happen.
61
+ *
62
+ * Server functions are matched FIRST. Their URL is reserved, so a page handler
63
+ * that also matched it would be shadowing an endpoint rather than serving a
64
+ * page — and the failure that produces is a mutation quietly answered with
65
+ * HTML.
66
+ */
67
+ export function createFetchHandler(
68
+ options: BarqServeOptions = {},
69
+ ): (request: Request) => Promise<Response> {
70
+ const page = options.fetch ?? (() => new Response("not found", { status: 404 }));
71
+ const document = options.spa;
72
+ // Read once and held, per handler: two in one process have two documents.
73
+ let body: Promise<string> | undefined;
74
+ const spaDocument = async (path: string | URL, missing: Response): Promise<Response> => {
75
+ // `node:fs` is imported here rather than at module scope, for the reason
76
+ // `static.ts` gives: this module resolves on workerd too, where there is none.
77
+ body ??= import("node:fs/promises").then((fs) => fs.readFile(path, "utf8"));
78
+ try {
79
+ return new Response(await body, {
80
+ headers: { "content-type": "text/html; charset=utf-8" },
81
+ });
82
+ } catch {
83
+ // The 404 the handler already produced, rather than a 500 about a file the
84
+ // caller never asked for.
85
+ body = undefined;
86
+ return missing;
87
+ }
88
+ };
89
+ return async (request: Request): Promise<Response> => {
90
+ const answered = await handleServerFn(request, options);
91
+ if (answered !== null) return answered;
92
+ const response = await page(request);
93
+ if (document === undefined || response.status !== 404) return response;
94
+ // Only a navigation. A 404 for a missing asset or an XHR is an answer the
95
+ // caller has to see, and handing it a document instead is the failure every
96
+ // SPA fallback that matches on "not a file" eventually produces.
97
+ if (request.method !== "GET" && request.method !== "HEAD") return response;
98
+ if (!(request.headers.get("accept") ?? "").includes("text/html")) return response;
99
+ return spaDocument(document, response);
100
+ };
101
+ }
102
+
103
+ /**
104
+ * What a caller is told when something threw: that it failed, and nothing else.
105
+ *
106
+ * Installed because a runtime's own answer is not that. Bun outside
107
+ * `NODE_ENV=production` answers with the message, the stack and the source
108
+ * around the throw, and a message can name a table, a column or a path. The
109
+ * error goes to the log, where the operator is.
110
+ */
111
+ function failed(error: unknown): Response {
112
+ console.error(error);
113
+ return new Response("internal server error", { status: 500 });
114
+ }
115
+
116
+ /**
117
+ * Serve on whatever runtime this is.
118
+ *
119
+ * Mount the generated manifest before calling this — importing
120
+ * `virtual:barq-server-fns` is what puts the ids in the registry, and without
121
+ * it every call is a 404.
122
+ */
123
+ export function serveBarq(options: BarqServeOptions = {}): Server {
124
+ // `reachable` and `static` come out too. They were not, so both were handed
125
+ // to `serve()` as options it has never heard of — harmless, and exactly the
126
+ // drift that spreads once one key leaks.
127
+ const {
128
+ fetch: _page,
129
+ allowedOrigins: _origins,
130
+ maxBodySize: _body,
131
+ maxFormSize: _form,
132
+ reachable: _reachable,
133
+ static: assets,
134
+ spa: _spa,
135
+ middleware,
136
+ ...rest
137
+ } = options;
138
+
139
+ // FIRST in the chain, so a hashed chunk never enters the page handler. Ahead
140
+ // of a project's own middleware too: those exist to shape application
141
+ // responses, and an asset is not one.
142
+ const chain =
143
+ assets === undefined || assets === false
144
+ ? middleware
145
+ : [assetMiddleware(assets === true ? {} : assets), ...(middleware ?? [])];
146
+
147
+ return serve({
148
+ ...rest,
149
+ error: rest.error ?? failed,
150
+ middleware: chain,
151
+ fetch: createFetchHandler(options),
152
+ });
153
+ }