@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.
- package/LICENSE +21 -0
- package/README.md +817 -2
- package/dist/client-BsyxVCyu.js +1554 -0
- package/dist/client-BsyxVCyu.js.map +1 -0
- package/dist/client-DidH0F2e.d.ts +450 -0
- package/dist/client-DidH0F2e.d.ts.map +1 -0
- package/dist/client.d.ts +25 -0
- package/dist/client.js +4 -0
- package/dist/env-Bhk_aIkx.d.ts +47 -0
- package/dist/env-Bhk_aIkx.d.ts.map +1 -0
- package/dist/env.d.ts +2 -0
- package/dist/env.js +43 -0
- package/dist/env.js.map +1 -0
- package/dist/index-B4o7eyCr.d.ts +925 -0
- package/dist/index-B4o7eyCr.d.ts.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +6 -0
- package/dist/middleware-B-tI8QHQ.d.ts +574 -0
- package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.js +281 -0
- package/dist/middleware.js.map +1 -0
- package/dist/prerender.d.ts +118 -0
- package/dist/prerender.d.ts.map +1 -0
- package/dist/prerender.js +289 -0
- package/dist/prerender.js.map +1 -0
- package/dist/protocol.d.ts +56 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +25 -0
- package/dist/protocol.js.map +1 -0
- package/dist/serve.d.ts +144 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +221 -0
- package/dist/serve.js.map +1 -0
- package/dist/server-DG6jb_NA.js +1253 -0
- package/dist/server-DG6jb_NA.js.map +1 -0
- package/dist/server.d.ts +159 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1 -0
- package/dist/src-odXG7kLA.js +1151 -0
- package/dist/src-odXG7kLA.js.map +1 -0
- package/dist/static-fn-CXjJi-It.js +122 -0
- package/dist/static-fn-CXjJi-It.js.map +1 -0
- package/package.json +106 -4
- package/src/client.ts +698 -0
- package/src/context.ts +699 -0
- package/src/cookies.ts +229 -0
- package/src/env.ts +86 -0
- package/src/fn-error.ts +121 -0
- package/src/frames-client.ts +1220 -0
- package/src/frames-server.ts +464 -0
- package/src/frames.ts +285 -0
- package/src/index.ts +740 -0
- package/src/live-client.ts +50 -0
- package/src/live-server.ts +292 -0
- package/src/middleware.ts +994 -0
- package/src/prerender.ts +477 -0
- package/src/protocol.ts +61 -0
- package/src/rate-limit.ts +202 -0
- package/src/serve.ts +153 -0
- package/src/server.ts +1026 -0
- package/src/session.ts +449 -0
- package/src/start-instance.ts +147 -0
- package/src/static-fn.ts +181 -0
- package/src/static.ts +302 -0
- package/src/stubs.ts +32 -0
- package/src/timing.ts +29 -0
- package/src/wire-types.ts +138 -0
package/src/session.ts
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sealed-cookie sessions, on WebCrypto and nothing else.
|
|
3
|
+
*
|
|
4
|
+
* The session lives in the cookie, encrypted and authenticated, so there is no
|
|
5
|
+
* store to run and no sticky routing to arrange. That is h3's design and
|
|
6
|
+
* therefore TanStack's, and the interface
|
|
7
|
+
* below is theirs — `{ id, data, update, clear }` from `useSession({ password
|
|
8
|
+
* })` — so the shape a reader already knows is the shape here.
|
|
9
|
+
*
|
|
10
|
+
* THE SEALING IS NOT THEIRS, and the divergence is deliberate. h3 uses iron,
|
|
11
|
+
* which is AES-256-CBC for confidentiality plus a separate HMAC-SHA256 for
|
|
12
|
+
* integrity, composed by hand. barq uses AES-GCM, which is AEAD: one primitive,
|
|
13
|
+
* authenticated by construction, with no encrypt-then-MAC composition to get
|
|
14
|
+
* wrong and no separate integrity key to derive. It is in WebCrypto, which Node,
|
|
15
|
+
* Bun, Deno and workerd all have, so it costs no dependency. The consequence is
|
|
16
|
+
* stated rather than hidden: a cookie sealed by h3 does not open here and one
|
|
17
|
+
* sealed here does not open there.
|
|
18
|
+
*
|
|
19
|
+
* WHAT A SEALED COOKIE IS AND IS NOT. It is tamper-proof and unreadable by the
|
|
20
|
+
* client. It is NOT revocable — a cookie already issued stays valid until it
|
|
21
|
+
* expires, because nothing on the server is consulted to open it. That is the
|
|
22
|
+
* trade the whole design makes, and an application that needs revocation needs a
|
|
23
|
+
* store; `maxAge` bounds the damage and is enforced on unseal, not merely on the
|
|
24
|
+
* cookie, so a client that keeps replaying an expired token gets nothing.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { getCookie, getRequest, openSessions, replaceCookie } from "./context.ts";
|
|
28
|
+
import type { CookieOptions } from "./cookies.ts";
|
|
29
|
+
|
|
30
|
+
/** What a session holds. An application narrows it with the type argument. */
|
|
31
|
+
export type SessionData = Record<string, unknown>;
|
|
32
|
+
|
|
33
|
+
export interface Session<T extends SessionData = SessionData> {
|
|
34
|
+
/** Stable for the life of the session. Useful as a log correlation key. */
|
|
35
|
+
readonly id: string;
|
|
36
|
+
/** When it was first sealed, as a millisecond timestamp. */
|
|
37
|
+
readonly createdAt: number;
|
|
38
|
+
readonly data: Partial<T>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface SessionManager<T extends SessionData = SessionData> {
|
|
42
|
+
readonly id: string;
|
|
43
|
+
/** When the session was first sealed, as a millisecond timestamp. */
|
|
44
|
+
readonly createdAt: number;
|
|
45
|
+
readonly data: Partial<T>;
|
|
46
|
+
/** Merge and re-seal. A function receives the current data. */
|
|
47
|
+
update(
|
|
48
|
+
patch: Partial<T> | ((current: Partial<T>) => Partial<T> | undefined),
|
|
49
|
+
): Promise<SessionManager<T>>;
|
|
50
|
+
/** Drop it and expire the cookie. */
|
|
51
|
+
clear(): Promise<SessionManager<T>>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface SessionConfig {
|
|
55
|
+
/**
|
|
56
|
+
* The key the cookie is sealed with. At least 32 characters.
|
|
57
|
+
*
|
|
58
|
+
* It is a SECRET and belongs in the environment, never in source. Rotating it
|
|
59
|
+
* invalidates every live session, which is the intended way to log everyone
|
|
60
|
+
* out.
|
|
61
|
+
*/
|
|
62
|
+
readonly password: string;
|
|
63
|
+
/** Cookie name. Default `barq-session`. */
|
|
64
|
+
readonly name?: string;
|
|
65
|
+
/**
|
|
66
|
+
* How long a sealed cookie stays valid, in seconds. Default 7 days.
|
|
67
|
+
*
|
|
68
|
+
* Enforced on UNSEAL as well as on the cookie, because the cookie's own expiry
|
|
69
|
+
* is a request the client is free to ignore — the timestamp inside the sealed
|
|
70
|
+
* payload is the one that cannot be edited.
|
|
71
|
+
*/
|
|
72
|
+
readonly maxAge?: number;
|
|
73
|
+
/**
|
|
74
|
+
* Cookie attributes. The defaults are the strict ones — `httpOnly`, `secure`,
|
|
75
|
+
* `sameSite: "lax"`, `path: "/"` — because a session cookie readable from
|
|
76
|
+
* script is a session cookie an XSS takes.
|
|
77
|
+
*/
|
|
78
|
+
readonly cookie?: CookieOptions;
|
|
79
|
+
/**
|
|
80
|
+
* Has this session been revoked? Asked on every unseal.
|
|
81
|
+
*
|
|
82
|
+
* THE ONE THING A SEALED COOKIE CANNOT DO BY ITSELF. Nothing on the server is
|
|
83
|
+
* consulted to open one, so "log out everywhere" and "ban this account now"
|
|
84
|
+
* are otherwise impossible — an issued cookie is valid until it expires, and
|
|
85
|
+
* that is the trade the whole design makes.
|
|
86
|
+
*
|
|
87
|
+
* This is the smallest seam that closes it. The fast path stays stateless:
|
|
88
|
+
* without the hook there is no lookup, and with it an application keeps only a
|
|
89
|
+
* set of revoked IDS until they expire, which `maxAge` bounds. That is a much
|
|
90
|
+
* smaller thing to store than a session per user, and it is only ever written
|
|
91
|
+
* when somebody signs out or is banned.
|
|
92
|
+
*
|
|
93
|
+
* A REVOKED SESSION READS AS ABSENT, like every other reason a cookie will not
|
|
94
|
+
* open — see `unsealSession`. Throwing here would tell a caller the difference
|
|
95
|
+
* between "forged" and "revoked", which is an oracle.
|
|
96
|
+
*
|
|
97
|
+
* It is asked AFTER the cookie is authenticated, so an unauthenticated client
|
|
98
|
+
* cannot make the application do a lookup by sending a garbage cookie.
|
|
99
|
+
*/
|
|
100
|
+
readonly isRevoked?: (id: string) => boolean | Promise<boolean>;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const DEFAULT_NAME = "barq-session";
|
|
104
|
+
const DEFAULT_MAX_AGE = 60 * 60 * 24 * 7;
|
|
105
|
+
/** Below this a password is not a key, whatever the KDF does with it. */
|
|
106
|
+
const MINIMUM_PASSWORD = 32;
|
|
107
|
+
/** Recognises our own envelope, and refuses another version rather than guessing. */
|
|
108
|
+
const VERSION = "b2";
|
|
109
|
+
/**
|
|
110
|
+
* The envelope that authenticates no cookie name. Opened, never written.
|
|
111
|
+
*
|
|
112
|
+
* Refusing it would sign every visitor out on the deploy that stopped sealing
|
|
113
|
+
* it, and the price of not doing that is stated: a `b1` value opens under ANY
|
|
114
|
+
* cookie name sharing the password until its sealed timestamp passes `maxAge`.
|
|
115
|
+
*/
|
|
116
|
+
const NAMELESS_VERSION = "b1";
|
|
117
|
+
/** Leads the additional data, so another layout of it is never read as this one. */
|
|
118
|
+
const NAME_BINDING = 2;
|
|
119
|
+
const IV_BYTES = 12;
|
|
120
|
+
const SALT_BYTES = 16;
|
|
121
|
+
/** Domain separation for the KDF — see `deriveKey`. */
|
|
122
|
+
const HKDF_INFO = new TextEncoder().encode("barq.session.v1");
|
|
123
|
+
/**
|
|
124
|
+
* What a browser will actually store.
|
|
125
|
+
*
|
|
126
|
+
* RFC 6265 §6.1 requires at least 4096 bytes per cookie, and every browser
|
|
127
|
+
* treats that as the limit — over it the cookie is DROPPED, silently, which
|
|
128
|
+
* looks exactly like a user who is not signed in. A session that quietly stops
|
|
129
|
+
* working once a field grows is the worst failure this file could have, so the
|
|
130
|
+
* seal refuses instead and says what to do.
|
|
131
|
+
*/
|
|
132
|
+
const MAX_COOKIE_BYTES = 4096;
|
|
133
|
+
|
|
134
|
+
interface Sealed {
|
|
135
|
+
readonly id: string;
|
|
136
|
+
readonly createdAt: number;
|
|
137
|
+
readonly data: SessionData;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* A session as one request holds it: what the cookie said, then every `update`
|
|
142
|
+
* and `clear` since.
|
|
143
|
+
*/
|
|
144
|
+
export interface OpenSession {
|
|
145
|
+
current: Sealed;
|
|
146
|
+
/** Settles when the write in flight has, whichever way it went. */
|
|
147
|
+
writing: Promise<unknown>;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function base64url(bytes: Uint8Array): string {
|
|
151
|
+
let binary = "";
|
|
152
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
153
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// `Uint8Array<ArrayBuffer>`, not the default `ArrayBufferLike`: WebCrypto's
|
|
157
|
+
// `BufferSource` requires the narrower one, and typing it here is what keeps a
|
|
158
|
+
// cast off every call site — where the lint rightly objects to one that does not
|
|
159
|
+
// change the type.
|
|
160
|
+
function fromBase64url(value: string): Uint8Array<ArrayBuffer> {
|
|
161
|
+
const padded = value.replaceAll("-", "+").replaceAll("_", "/");
|
|
162
|
+
const binary = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, "="));
|
|
163
|
+
const bytes = new Uint8Array(binary.length);
|
|
164
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
|
165
|
+
return bytes;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The key, derived per SALT rather than used raw.
|
|
170
|
+
*
|
|
171
|
+
* HKDF AND NOT PBKDF2, and the reason is correctness AND a denial of service.
|
|
172
|
+
*
|
|
173
|
+
* PBKDF2 exists to STRETCH a low-entropy secret — a human password — so that
|
|
174
|
+
* guessing it costs an attacker real time. This input is not that: `password` is
|
|
175
|
+
* refused below 32 characters and is documented as a key. Stretching something
|
|
176
|
+
* already high-entropy buys nothing, and HKDF is the KDF for exactly this case.
|
|
177
|
+
*
|
|
178
|
+
* The cost of getting it wrong was MEASURED on this machine: PBKDF2 at 100,000
|
|
179
|
+
* iterations is 7.93 ms and HKDF is 0.014 ms — 566x — per REQUEST, on every
|
|
180
|
+
* request that touches a session. Worse, it is per request an ATTACKER makes:
|
|
181
|
+
* the salt comes out of the cookie, so an unauthenticated client sending garbage
|
|
182
|
+
* cookies chooses how much CPU each packet costs. Eight milliseconds a packet is
|
|
183
|
+
* an amplifier, and HKDF removes it rather than bounding it.
|
|
184
|
+
*
|
|
185
|
+
* A fresh salt per seal still keeps two seals of the same data under the same
|
|
186
|
+
* password from sharing a key, so the ciphertexts stay incomparable.
|
|
187
|
+
*/
|
|
188
|
+
async function deriveKey(password: string, salt: Uint8Array<ArrayBuffer>): Promise<CryptoKey> {
|
|
189
|
+
const material = await crypto.subtle.importKey(
|
|
190
|
+
"raw",
|
|
191
|
+
new TextEncoder().encode(password),
|
|
192
|
+
"HKDF",
|
|
193
|
+
false,
|
|
194
|
+
["deriveKey"],
|
|
195
|
+
);
|
|
196
|
+
return crypto.subtle.deriveKey(
|
|
197
|
+
// `info` DOMAIN-SEPARATES the output, so a key derived here is not the key
|
|
198
|
+
// the same secret would derive for anything else.
|
|
199
|
+
{ name: "HKDF", salt, info: HKDF_INFO, hash: "SHA-256" },
|
|
200
|
+
material,
|
|
201
|
+
{ name: "AES-GCM", length: 256 },
|
|
202
|
+
false,
|
|
203
|
+
["encrypt", "decrypt"],
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Keys this process has derived AND seen authenticate, by password, then salt.
|
|
209
|
+
*
|
|
210
|
+
* A signed-in visitor sends one cookie on every request, so its salt and its
|
|
211
|
+
* key repeat. WebCrypto answers on another thread, and measured on this machine
|
|
212
|
+
* the derivation is 42 us of the 73 us an unseal costs; held, a repeat visit
|
|
213
|
+
* pays for the decryption alone.
|
|
214
|
+
*
|
|
215
|
+
* Only a key that OPENED something is kept, or one this process sealed with. A
|
|
216
|
+
* caller sending garbage cookies therefore adds nothing here and evicts no one,
|
|
217
|
+
* which is what would otherwise make a cache of attacker-chosen salts a way to
|
|
218
|
+
* push real visitors out of it.
|
|
219
|
+
*/
|
|
220
|
+
const DERIVED = new Map<string, Map<string, CryptoKey>>();
|
|
221
|
+
/** Per password. The oldest goes first, and a key that is used is the newest. */
|
|
222
|
+
const DERIVED_KEYS = 1000;
|
|
223
|
+
|
|
224
|
+
function keep(password: string, salt: string, key: CryptoKey): void {
|
|
225
|
+
let keys = DERIVED.get(password);
|
|
226
|
+
if (keys === undefined) {
|
|
227
|
+
keys = new Map();
|
|
228
|
+
DERIVED.set(password, keys);
|
|
229
|
+
}
|
|
230
|
+
keys.delete(salt);
|
|
231
|
+
keys.set(salt, key);
|
|
232
|
+
if (keys.size <= DERIVED_KEYS) return;
|
|
233
|
+
const oldest = keys.keys().next().value;
|
|
234
|
+
if (oldest !== undefined) keys.delete(oldest);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* What the tag covers beside the ciphertext: the cookie the session was sealed
|
|
239
|
+
* FOR.
|
|
240
|
+
*
|
|
241
|
+
* One password commonly seals more than one cookie, and a tag that covers the
|
|
242
|
+
* payload alone makes the value issued as `barq-session` a valid
|
|
243
|
+
* `barq-session-admin` for anyone who renames it.
|
|
244
|
+
*/
|
|
245
|
+
function nameBinding(config: SessionConfig): Uint8Array<ArrayBuffer> {
|
|
246
|
+
const name = new TextEncoder().encode(config.name ?? DEFAULT_NAME);
|
|
247
|
+
const binding = new Uint8Array(name.length + 1);
|
|
248
|
+
binding[0] = NAME_BINDING;
|
|
249
|
+
binding.set(name, 1);
|
|
250
|
+
return binding;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function assertPassword(password: string): void {
|
|
254
|
+
if (password.length < MINIMUM_PASSWORD) {
|
|
255
|
+
throw new TypeError(
|
|
256
|
+
`[barq] A session \`password\` must be at least ${MINIMUM_PASSWORD} characters, and this one is ${password.length}. ` +
|
|
257
|
+
"It is the key that encrypts the cookie, so a short one can be guessed. " +
|
|
258
|
+
"Generate one with `crypto.randomUUID() + crypto.randomUUID()` and read it from an environment variable.",
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Encrypt and sign a session. Exported for code that seals outside a request. */
|
|
264
|
+
export async function sealSession(config: SessionConfig, session: Sealed): Promise<string> {
|
|
265
|
+
assertPassword(config.password);
|
|
266
|
+
const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
|
|
267
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
268
|
+
const key = await deriveKey(config.password, salt);
|
|
269
|
+
const plaintext = new TextEncoder().encode(JSON.stringify(session));
|
|
270
|
+
const salted = base64url(salt);
|
|
271
|
+
const sealed = new Uint8Array(
|
|
272
|
+
await crypto.subtle.encrypt(
|
|
273
|
+
{ name: "AES-GCM", iv, additionalData: nameBinding(config) },
|
|
274
|
+
key,
|
|
275
|
+
plaintext,
|
|
276
|
+
),
|
|
277
|
+
);
|
|
278
|
+
const value = [VERSION, salted, base64url(iv), base64url(sealed)].join(".");
|
|
279
|
+
// Name and value together, which is the sum a browser measures.
|
|
280
|
+
const size = (config.name ?? DEFAULT_NAME).length + value.length;
|
|
281
|
+
if (size > MAX_COOKIE_BYTES) {
|
|
282
|
+
throw new RangeError(
|
|
283
|
+
`[barq] This session is ${size} bytes once encrypted, counting the cookie name, and a browser drops any cookie over ${MAX_COOKIE_BYTES} bytes without an error. ` +
|
|
284
|
+
"The user would appear signed out. Keep only an id in the session and the rest in a store on the server.",
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
keep(config.password, salted, key);
|
|
288
|
+
return value;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Decrypt and verify, or `null`.
|
|
293
|
+
*
|
|
294
|
+
* `null` for EVERY failure — a wrong password, a tampered ciphertext, an expired
|
|
295
|
+
* timestamp, a envelope from a future version — and never a throw. A session
|
|
296
|
+
* that will not open is not an error the request should fail on; it is a visitor
|
|
297
|
+
* who is not signed in, and the two must be indistinguishable to the caller so
|
|
298
|
+
* that a forged cookie cannot be told apart from an absent one.
|
|
299
|
+
*/
|
|
300
|
+
export async function unsealSession(config: SessionConfig, sealed: string): Promise<Sealed | null> {
|
|
301
|
+
assertPassword(config.password);
|
|
302
|
+
const parts = sealed.split(".");
|
|
303
|
+
if (parts.length !== 4) return null;
|
|
304
|
+
const bound = parts[0] === VERSION;
|
|
305
|
+
if (!bound && parts[0] !== NAMELESS_VERSION) return null;
|
|
306
|
+
try {
|
|
307
|
+
const key =
|
|
308
|
+
DERIVED.get(config.password)?.get(parts[1]) ??
|
|
309
|
+
(await deriveKey(config.password, fromBase64url(parts[1])));
|
|
310
|
+
const plaintext = await crypto.subtle.decrypt(
|
|
311
|
+
bound
|
|
312
|
+
? { name: "AES-GCM", iv: fromBase64url(parts[2]), additionalData: nameBinding(config) }
|
|
313
|
+
: { name: "AES-GCM", iv: fromBase64url(parts[2]) },
|
|
314
|
+
key,
|
|
315
|
+
fromBase64url(parts[3]),
|
|
316
|
+
);
|
|
317
|
+
keep(config.password, parts[1], key);
|
|
318
|
+
const session = JSON.parse(new TextDecoder().decode(plaintext)) as Sealed;
|
|
319
|
+
if (typeof session.id !== "string" || typeof session.createdAt !== "number") return null;
|
|
320
|
+
// The cookie's own expiry is a REQUEST the client is free to ignore. The
|
|
321
|
+
// timestamp inside the sealed payload is the one that cannot be edited, so
|
|
322
|
+
// it is the one that decides.
|
|
323
|
+
const maxAge = config.maxAge ?? DEFAULT_MAX_AGE;
|
|
324
|
+
if (Date.now() - session.createdAt > maxAge * 1000) return null;
|
|
325
|
+
// AFTER the tag has verified, never before: asking first would let an
|
|
326
|
+
// unauthenticated client drive a lookup with a garbage cookie, which is the
|
|
327
|
+
// same amplifier the KDF used to be.
|
|
328
|
+
if (config.isRevoked !== undefined && (await config.isRevoked(session.id))) return null;
|
|
329
|
+
return session;
|
|
330
|
+
} catch {
|
|
331
|
+
// AES-GCM's tag failed, or the envelope was not ours. Same answer either way.
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function cookieOptions(config: SessionConfig): CookieOptions {
|
|
337
|
+
return {
|
|
338
|
+
httpOnly: true,
|
|
339
|
+
secure: true,
|
|
340
|
+
sameSite: "lax",
|
|
341
|
+
path: "/",
|
|
342
|
+
maxAge: config.maxAge ?? DEFAULT_MAX_AGE,
|
|
343
|
+
...config.cookie,
|
|
344
|
+
// The sealed value is base64url and a `.` separator, every character of
|
|
345
|
+
// which a cookie carries as it stands — so it stays readable in devtools
|
|
346
|
+
// rather than becoming a wall of `%3D`.
|
|
347
|
+
encode: (value) => value,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* The session for this request, opening the cookie if there is one.
|
|
353
|
+
*
|
|
354
|
+
* Always answers a manager, never `null`: a visitor with no session has an empty
|
|
355
|
+
* one, which is the same thing from the application's side and removes the
|
|
356
|
+
* branch that is easy to get backwards.
|
|
357
|
+
*
|
|
358
|
+
* NOTHING IS WRITTEN until `update` is called. Reading a session must not
|
|
359
|
+
* re-issue its cookie, or every page render would refresh an expiry the user did
|
|
360
|
+
* not earn — and on a page that also sets `Cache-Control: public` that
|
|
361
|
+
* `Set-Cookie` is a cache poisoning waiting to happen.
|
|
362
|
+
*/
|
|
363
|
+
export async function useSession<T extends SessionData = SessionData>(
|
|
364
|
+
config: SessionConfig,
|
|
365
|
+
): Promise<SessionManager<T>> {
|
|
366
|
+
assertPassword(config.password);
|
|
367
|
+
const name = config.name ?? DEFAULT_NAME;
|
|
368
|
+
// `getRequest` first, so the error outside a request names the real problem
|
|
369
|
+
// rather than surfacing as an empty session.
|
|
370
|
+
getRequest();
|
|
371
|
+
|
|
372
|
+
// OPENED ONCE PER REQUEST AND NAME. The cookie on the request is what the
|
|
373
|
+
// browser held before this request wrote anything, so a second reader that
|
|
374
|
+
// unsealed it again would not see the first one's `update`, and would seal its
|
|
375
|
+
// own change over it. Every manager for a name works on the one record.
|
|
376
|
+
const sessions = openSessions();
|
|
377
|
+
let opening = sessions.get(name);
|
|
378
|
+
if (opening === undefined) {
|
|
379
|
+
opening = open(config, getCookie(name));
|
|
380
|
+
sessions.set(name, opening);
|
|
381
|
+
}
|
|
382
|
+
const session = await opening;
|
|
383
|
+
|
|
384
|
+
// ONE WRITE AT A TIME. A write reads the record, seals across an `await` and
|
|
385
|
+
// then stores what it sealed, so two that overlapped would both start from the
|
|
386
|
+
// same record and the later cookie would drop the earlier change.
|
|
387
|
+
const write = (change: (current: Sealed) => Promise<Sealed>): Promise<SessionManager<T>> => {
|
|
388
|
+
const written = session.writing.then(async () => {
|
|
389
|
+
session.current = await change(session.current);
|
|
390
|
+
return manage();
|
|
391
|
+
});
|
|
392
|
+
session.writing = written.catch(() => undefined);
|
|
393
|
+
return written;
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
const manage = (): SessionManager<T> => ({
|
|
397
|
+
id: session.current.id,
|
|
398
|
+
createdAt: session.current.createdAt,
|
|
399
|
+
data: session.current.data as Partial<T>,
|
|
400
|
+
update: (patch) =>
|
|
401
|
+
write(async (current) => {
|
|
402
|
+
const next = typeof patch === "function" ? patch(current.data as Partial<T>) : patch;
|
|
403
|
+
const merged: Sealed = { ...current, data: { ...current.data, ...next } };
|
|
404
|
+
replaceCookie(name, await sealSession(config, merged), cookieOptions(config));
|
|
405
|
+
return merged;
|
|
406
|
+
}),
|
|
407
|
+
clear: () =>
|
|
408
|
+
write(async () => {
|
|
409
|
+
// EXPIRED, not re-sealed empty: an empty session cookie is still a cookie
|
|
410
|
+
// the browser sends, and the user asked for it to be gone.
|
|
411
|
+
replaceCookie(name, "", { ...cookieOptions(config), maxAge: 0, expires: new Date(0) });
|
|
412
|
+
return { id: crypto.randomUUID(), createdAt: Date.now(), data: {} };
|
|
413
|
+
}),
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
return manage();
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
async function open(config: SessionConfig, cookie: string | undefined): Promise<OpenSession> {
|
|
420
|
+
const opened = cookie === undefined ? null : await unsealSession(config, cookie);
|
|
421
|
+
return {
|
|
422
|
+
current: opened ?? { id: crypto.randomUUID(), createdAt: Date.now(), data: {} },
|
|
423
|
+
writing: Promise.resolve(),
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** The session's data, for code that only reads. */
|
|
428
|
+
export async function getSession<T extends SessionData = SessionData>(
|
|
429
|
+
config: SessionConfig,
|
|
430
|
+
): Promise<Session<T>> {
|
|
431
|
+
const manager = await useSession<T>(config);
|
|
432
|
+
// The SEALED timestamp, not now. `Date.now()` here reported every session as
|
|
433
|
+
// brand new, which is exactly wrong for the one thing `createdAt` is for —
|
|
434
|
+
// deciding how old a session is.
|
|
435
|
+
return { id: manager.id, createdAt: manager.createdAt, data: manager.data };
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Merge into the session and re-seal it. */
|
|
439
|
+
export async function updateSession<T extends SessionData = SessionData>(
|
|
440
|
+
config: SessionConfig,
|
|
441
|
+
patch: Partial<T> | ((current: Partial<T>) => Partial<T> | undefined),
|
|
442
|
+
): Promise<SessionManager<T>> {
|
|
443
|
+
return (await useSession<T>(config)).update(patch);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** Drop the session and expire its cookie. */
|
|
447
|
+
export async function clearSession(config: SessionConfig): Promise<void> {
|
|
448
|
+
await (await useSession(config)).clear();
|
|
449
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The application-wide middleware, declared once.
|
|
3
|
+
*
|
|
4
|
+
* TanStack Start's `createStart`, written in a project's `src/start.ts`:
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* export const startInstance = createStart(() => ({
|
|
8
|
+
* requestMiddleware: [logging],
|
|
9
|
+
* functionMiddleware: [requireSession],
|
|
10
|
+
* }));
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* Its own module, importing nothing that reaches `node:async_hooks`, because
|
|
14
|
+
* the client stub reads it: a global function middleware's client half runs in
|
|
15
|
+
* the browser around every call.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { type AnySerializationAdapter, registerSerializationAdapters } from "@barqjs/server/codec";
|
|
19
|
+
|
|
20
|
+
import type { ChainContribution, Empty, Middleware } from "./middleware.ts";
|
|
21
|
+
|
|
22
|
+
export interface StartOptions {
|
|
23
|
+
/** Runs for every request the server answers: a page, a route handler, a server function. */
|
|
24
|
+
readonly requestMiddleware?: readonly Middleware[];
|
|
25
|
+
/** Runs for every server function, ahead of the function's own chain. */
|
|
26
|
+
readonly functionMiddleware?: readonly Middleware[];
|
|
27
|
+
/**
|
|
28
|
+
* How a type only the application knows crosses the wire, in a server
|
|
29
|
+
* function's input and result and in the page's seed. Installed when the
|
|
30
|
+
* options are first read, which both sides do before they encode anything.
|
|
31
|
+
*/
|
|
32
|
+
readonly serializationAdapters?: readonly AnySerializationAdapter[];
|
|
33
|
+
/**
|
|
34
|
+
* What a route that says nothing about `ssr` does, for every route: `true`,
|
|
35
|
+
* `false` (rendered in the browser alone) or `"data-only"` (loaders run on
|
|
36
|
+
* the server, the component in the browser). Wins over the router's own
|
|
37
|
+
* `defaultSsr`, as TanStack's does.
|
|
38
|
+
*/
|
|
39
|
+
readonly defaultSsr?: boolean | "data-only";
|
|
40
|
+
readonly serverFns?: {
|
|
41
|
+
/**
|
|
42
|
+
* The `fetch` every call goes out through, in place of the global one. A
|
|
43
|
+
* client middleware's `next({ fetch })` and the call's own `fetch` win
|
|
44
|
+
* over it.
|
|
45
|
+
*/
|
|
46
|
+
readonly fetch?: typeof fetch;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface StartInstance<Options extends StartOptions = StartOptions> {
|
|
51
|
+
getOptions(): Options;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
declare const UNREGISTERED: unique symbol;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Where an application tells the types about its `src/start.ts`:
|
|
58
|
+
*
|
|
59
|
+
* ```ts
|
|
60
|
+
* declare module "@barqjs/start" {
|
|
61
|
+
* interface Register {
|
|
62
|
+
* start: typeof startInstance;
|
|
63
|
+
* }
|
|
64
|
+
* }
|
|
65
|
+
* ```
|
|
66
|
+
*
|
|
67
|
+
* With that, what the global middleware passes to `next({ context })` is typed
|
|
68
|
+
* in every server function's `context` and in `getGlobalStartContext()`.
|
|
69
|
+
* Without it they are untyped, never wrong. The member below exists so the
|
|
70
|
+
* interface is not the empty object type before anything augments it.
|
|
71
|
+
*/
|
|
72
|
+
export interface Register {
|
|
73
|
+
readonly [UNREGISTERED]?: never;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
type RegisteredInstance = Register extends { readonly start: infer Instance }
|
|
77
|
+
? Instance
|
|
78
|
+
: StartInstance;
|
|
79
|
+
|
|
80
|
+
/** What an instance's request middleware adds, for the whole request. */
|
|
81
|
+
export type RequestContextOf<Instance> =
|
|
82
|
+
Instance extends StartInstance<infer Options>
|
|
83
|
+
? ChainContribution<NonNullable<Options["requestMiddleware"]>>["context"]
|
|
84
|
+
: Empty;
|
|
85
|
+
|
|
86
|
+
/** What an instance's middleware hands every server function: request, then function. */
|
|
87
|
+
export type FunctionContextOf<Instance> =
|
|
88
|
+
Instance extends StartInstance<infer Options>
|
|
89
|
+
? RequestContextOf<Instance> &
|
|
90
|
+
ChainContribution<NonNullable<Options["functionMiddleware"]>>["context"]
|
|
91
|
+
: Empty;
|
|
92
|
+
|
|
93
|
+
/** What the registered global request middleware adds, for the whole request. */
|
|
94
|
+
export type GlobalRequestContext = RequestContextOf<RegisteredInstance>;
|
|
95
|
+
|
|
96
|
+
/** What every server function's `context` starts from. */
|
|
97
|
+
export type GlobalFunctionContext = FunctionContextOf<RegisteredInstance>;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* One instance for the process, whichever copy of this module asks.
|
|
101
|
+
*
|
|
102
|
+
* It is configuration, fixed once the application has loaded, so it has none
|
|
103
|
+
* of the hazards an ambient request would: nothing a visitor does changes it.
|
|
104
|
+
* On the global registry for the reason the server-function registry is: a
|
|
105
|
+
* build compiles this module into its server bundle, and a host serving that
|
|
106
|
+
* bundle through its own `serveBarq` has imported a second copy.
|
|
107
|
+
*/
|
|
108
|
+
const REGISTERED = ((globalThis as Record<symbol, unknown>)[Symbol.for("barq.start.instance")] ??= {
|
|
109
|
+
instance: null,
|
|
110
|
+
}) as { instance: StartInstance | null };
|
|
111
|
+
|
|
112
|
+
const NONE: StartOptions = Object.freeze({});
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Declare the application's global middleware.
|
|
116
|
+
*
|
|
117
|
+
* The function is called once, the first time anything asks, so a middleware
|
|
118
|
+
* module that imports this one back is fully evaluated by then.
|
|
119
|
+
*/
|
|
120
|
+
export function createStart<const Options extends StartOptions>(
|
|
121
|
+
options: () => Options,
|
|
122
|
+
): StartInstance<Options> {
|
|
123
|
+
let resolved: Options | undefined;
|
|
124
|
+
const instance: StartInstance<Options> = {
|
|
125
|
+
getOptions: () => {
|
|
126
|
+
if (resolved === undefined) {
|
|
127
|
+
resolved = options();
|
|
128
|
+
if (resolved.serializationAdapters !== undefined) {
|
|
129
|
+
registerSerializationAdapters(resolved.serializationAdapters);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return resolved;
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
REGISTERED.instance = instance;
|
|
136
|
+
return instance;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** What the application declared, or nothing. */
|
|
140
|
+
export function startOptions(): StartOptions {
|
|
141
|
+
return REGISTERED.instance?.getOptions() ?? NONE;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Test seam. Not for application use. */
|
|
145
|
+
export function clearStart(): void {
|
|
146
|
+
REGISTERED.instance = null;
|
|
147
|
+
}
|