@softr/sdk 0.0.10 → 0.0.12

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.
@@ -1,334 +0,0 @@
1
- import { getRequestHeader, getRequestProtocol, getResponseHeaders, setResponseHeader } from "@tanstack/react-start/server";
2
- import { z } from "zod";
3
- import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
4
-
5
- //#region src/assertions.ts
6
- function assert(condition, message) {
7
- if (!condition) throwAtCaller(assert, new AssertionError(unwrapErrorMessage(message)));
8
- }
9
- /**
10
- * Shorthand for throw new AssertionError("Error message")
11
- * Useful because it is an expression instead of a statement.
12
- * Can be assigned to any value, because it never returns.
13
- */
14
- function panic(message) {
15
- throwAtCaller(panic, new AssertionError(unwrapErrorMessage(message)));
16
- }
17
- function todo(message) {
18
- throwAtCaller(todo, new UnimplementedError(unwrapErrorMessage(message)));
19
- }
20
- /**
21
- * A soft assertion that throws an error in non prod environments, including
22
- * staging, but logs an error in production mode.
23
- * This is useful for cases where something unexpected happens, but you can still
24
- * continue in a slightly broken state.
25
- * For example, if a block has defined a style control with a hardcoded id and
26
- * that style control is not found, this is definitely a bug, but it's still
27
- * possible to go on rendering with a fallback value for this style.
28
- * It is recommended to liberally use soft assertions so that we fail loudly in
29
- * staging and local environments.
30
- *
31
- * A hard assertion would be more appropriate if we wanted to display some data
32
- * from an object but that object is null. It's better to throw an assertion
33
- * error at the place we detect this, instead of continuing and potentially
34
- * causing an exception in an unrelated part of the code.
35
- */
36
- function softAssert(condition, message) {
37
- if (!condition) if (process.env.NODE_ENV !== "production") throwAtCaller(softAssert, new SoftAssertionError(unwrapErrorMessage(message)));
38
- else console.error(`Assertion failed: ${unwrapErrorMessage(message)}`);
39
- }
40
- var AssertionError = class extends Error {
41
- name = "AssertionError";
42
- };
43
- var SoftAssertionError = class extends Error {
44
- name = "SoftAssertionError";
45
- };
46
- var UnimplementedError = class extends Error {
47
- name = "UnimplementedError";
48
- };
49
- function unwrapErrorMessage(message) {
50
- return typeof message === "function" ? message() : message ?? "";
51
- }
52
- /**
53
- * Uses chrome's non-standard Error.captureStackTrace to set the top of the stack
54
- * trace to start from the caller of the supplied function {@param f}.
55
- * Useful in assertion functions to make sure that the stack trace shows the spot
56
- * where the assertion failed, not the place where the assertion was thrown.
57
- */
58
- function throwAtCaller(f, ex) {
59
- if (Error.captureStackTrace) Error.captureStackTrace(ex, f);
60
- throw ex;
61
- }
62
-
63
- //#endregion
64
- //#region src/cookies.ts
65
- function parseCookieHeader(header) {
66
- const cookies = {};
67
- if (!header) return cookies;
68
- for (const pair of header.split(";")) {
69
- const separator = pair.indexOf("=");
70
- if (separator === -1) continue;
71
- const name = pair.slice(0, separator).trim();
72
- if (name.length === 0) continue;
73
- cookies[name] = decode(pair.slice(separator + 1).trim());
74
- }
75
- return cookies;
76
- }
77
- function decode(value) {
78
- try {
79
- return decodeURIComponent(value);
80
- } catch {
81
- return value;
82
- }
83
- }
84
- function readRequestCookies() {
85
- return parseCookieHeader(getRequestHeader("cookie"));
86
- }
87
- function serializeCookie(name, value, { maxAge, secure }) {
88
- if (name.startsWith("__Host-") && !secure) throw new Error(`Refusing to write ${name} without Secure: a __Host- cookie is only valid when Secure, Path=/ and free of Domain, and a browser silently discards one that is not.`);
89
- const parts = [
90
- `${name}=${encodeURIComponent(value)}`,
91
- "Path=/",
92
- "HttpOnly"
93
- ];
94
- if (secure) parts.push("Secure");
95
- parts.push("SameSite=Lax", `Max-Age=${maxAge}`);
96
- return parts.join("; ");
97
- }
98
- function writeCookies(cookies) {
99
- if (cookies.length === 0) return;
100
- setResponseHeader("Set-Cookie", [...getResponseHeaders().getSetCookie(), ...cookies]);
101
- }
102
-
103
- //#endregion
104
- //#region src/auth/config.ts
105
- const DEFAULT_SESSION_MAX_AGE = 2160 * 60 * 60;
106
- /** 32 bytes, hex encoded. */
107
- const SESSION_SECRET = /^[0-9a-f]{64}$/i;
108
- function loadSessionConfig() {
109
- const missing = [];
110
- const applicationId = process.env.SOFTR_APPLICATION_ID;
111
- if (!applicationId) missing.push("SOFTR_APPLICATION_ID");
112
- const sessionSecret = process.env.SOFTR_SESSION_SECRET;
113
- if (!sessionSecret) missing.push("SOFTR_SESSION_SECRET");
114
- const platformApiUrl = process.env.SOFTR_PLATFORM_API_URL;
115
- if (!platformApiUrl) missing.push("SOFTR_PLATFORM_API_URL");
116
- if (missing.length > 0) throw new Error(`Softr auth is not configured: missing ${missing.join(", ")}.`);
117
- assert(applicationId && sessionSecret && platformApiUrl);
118
- if (!SESSION_SECRET.test(sessionSecret)) throw new Error("SOFTR_SESSION_SECRET must be 32 random bytes encoded as hex.\nGenerate one with: openssl rand -hex 32");
119
- const rawMaxAge = process.env.SOFTR_SESSION_MAX_AGE;
120
- let sessionMaxAge = DEFAULT_SESSION_MAX_AGE;
121
- if (rawMaxAge) {
122
- sessionMaxAge = Number(rawMaxAge);
123
- if (!Number.isInteger(sessionMaxAge) || sessionMaxAge <= 0) throw new Error(`SOFTR_SESSION_MAX_AGE must be a positive whole number of seconds, got "${rawMaxAge}".`);
124
- }
125
- return {
126
- applicationId,
127
- sessionSecret,
128
- platformApiUrl,
129
- sessionMaxAge
130
- };
131
- }
132
- let cached;
133
- function sessionConfig() {
134
- cached ??= loadSessionConfig();
135
- return cached;
136
- }
137
-
138
- //#endregion
139
- //#region src/auth/me.ts
140
- /**
141
- * `null` means the platform refused the token — any 4xx, because `/me` answers
142
- * 400 rather than 401 for an expired one, so only the class of the status is
143
- * informative. Anything else that is not a 200 throws.
144
- */
145
- async function fetchVisitor(token) {
146
- const config = sessionConfig();
147
- const response = await fetch(`${config.platformApiUrl}/v1/applications/${config.applicationId}/users/me`, {
148
- method: "GET",
149
- headers: {
150
- authorization: `Bearer ${token}`,
151
- accept: "application/json"
152
- }
153
- });
154
- if (response.status >= 400 && response.status < 500) return null;
155
- if (!response.ok) throw new Error(`Softr platform did not answer /me: ${response.status} ${response.statusText}`.trim());
156
- return toUser(await response.json());
157
- }
158
- const meSchema = z.object({
159
- id: z.string(),
160
- full_name: z.string().nullish(),
161
- credentials: z.object({ email: z.string().nullish() }).nullish()
162
- });
163
- function toUser(body) {
164
- const me = meSchema.safeParse(body);
165
- if (!me.success) throw new Error(`Softr platform answered /me with something that is not a user: ${z.prettifyError(me.error)}`);
166
- return {
167
- id: me.data.id,
168
- email: me.data.credentials?.email ?? "",
169
- name: me.data.full_name ?? "",
170
- userGroupIds: []
171
- };
172
- }
173
-
174
- //#endregion
175
- //#region src/auth/session.ts
176
- const SESSION_TOKEN = "session_token";
177
- const SESSION_DATA = "session_data";
178
- const SESSION_DATA_TTL_SECONDS = 300;
179
- /**
180
- * A browser refuses a `__Host-` cookie unless it is `Secure`, `Path=/` and free
181
- * of `Domain` — that last clause is the one worth having, since it stops a
182
- * sibling host planting a cookie of this name for us to honour.
183
- */
184
- const HOST_PREFIX = "__Host-";
185
- function requestIsSecure() {
186
- return getRequestProtocol() === "https";
187
- }
188
- function sessionCookie(base) {
189
- const secure = requestIsSecure();
190
- return {
191
- name: secure ? HOST_PREFIX + base : base,
192
- secure
193
- };
194
- }
195
- /** The platform token this request carries, or `null`. */
196
- function readSessionToken() {
197
- const { name } = sessionCookie(SESSION_TOKEN);
198
- return openEnvelope(readRequestCookies()[name], SESSION_TOKEN);
199
- }
200
- /** The cached visitor for `sessionToken`, or `null` on any kind of miss. */
201
- function readSessionData(sessionToken) {
202
- const { name } = sessionCookie(SESSION_DATA);
203
- const payload = parseSessionData(openEnvelope(readRequestCookies()[name], SESSION_DATA));
204
- if (payload === null) return null;
205
- if (payload.exp <= Math.floor(Date.now() / 1e3)) return null;
206
- if (payload.tb !== tokenBinding(sessionToken)) return null;
207
- return {
208
- id: payload.id,
209
- email: payload.email,
210
- name: payload.name,
211
- userGroupIds: payload.userGroupIds
212
- };
213
- }
214
- function makeSessionTokenCookie(token) {
215
- const { name, secure } = sessionCookie(SESSION_TOKEN);
216
- return serializeCookie(name, sealEnvelope(token, SESSION_TOKEN), {
217
- maxAge: sessionConfig().sessionMaxAge,
218
- secure
219
- });
220
- }
221
- function makeSessionDataCookie(user, sessionToken) {
222
- const { name, secure } = sessionCookie(SESSION_DATA);
223
- const payload = {
224
- id: user.id,
225
- email: user.email,
226
- name: user.name,
227
- userGroupIds: user.userGroupIds,
228
- exp: Math.floor(Date.now() / 1e3) + SESSION_DATA_TTL_SECONDS,
229
- tb: tokenBinding(sessionToken)
230
- };
231
- return serializeCookie(name, sealEnvelope(JSON.stringify(payload), SESSION_DATA), {
232
- maxAge: SESSION_DATA_TTL_SECONDS,
233
- secure
234
- });
235
- }
236
- /**
237
- * Writes rather than returns: a forgotten list would leave the session live.
238
- */
239
- function clearSession() {
240
- clearCookies([SESSION_TOKEN, SESSION_DATA]);
241
- }
242
- const sessionDataSchema = z.object({
243
- id: z.string(),
244
- email: z.string(),
245
- name: z.string(),
246
- userGroupIds: z.array(z.string()),
247
- exp: z.number(),
248
- tb: z.string()
249
- });
250
- /**
251
- * Both spellings on https: a jar can hold both pairs across a move between
252
- * schemes, and the one left behind would revive if the scheme changed back.
253
- */
254
- function clearCookies(bases) {
255
- const secure = requestIsSecure();
256
- writeCookies(bases.flatMap((base) => secure ? [HOST_PREFIX + base, base] : [base]).map((name) => serializeCookie(name, "", {
257
- maxAge: 0,
258
- secure
259
- })));
260
- }
261
- /**
262
- * Over the plaintext token, never the cookie value: that is resealed with a
263
- * fresh iv on every write, so a binding over its bytes would be a permanent
264
- * cache miss.
265
- */
266
- function tokenBinding(sessionToken) {
267
- return createHash("sha256").update(sessionToken).digest("base64url");
268
- }
269
- function parseSessionData(json) {
270
- if (json === null) return null;
271
- let payload;
272
- try {
273
- payload = JSON.parse(json);
274
- } catch {
275
- return null;
276
- }
277
- const data = sessionDataSchema.safeParse(payload);
278
- return data.success ? data.data : null;
279
- }
280
- const IV_BYTES = 12;
281
- const TAG_BYTES = 16;
282
- /** Iv + one byte of ciphertext + tag. Anything shorter is not ours. */
283
- const MIN_ENVELOPE_BYTES = IV_BYTES + TAG_BYTES + 1;
284
- /**
285
- * `Buffer.from(…, "base64url")` skips stray characters rather than throwing.
286
- */
287
- const BASE64URL = /^[A-Za-z0-9_-]+$/;
288
- /**
289
- * One key for both cookies. The application id goes in with the secret so a
290
- * cookie from staging is inert in production even when the two share a secret.
291
- */
292
- function sessionKey() {
293
- const { applicationId, sessionSecret } = sessionConfig();
294
- return createHash("sha256").update(Buffer.from(sessionSecret, "hex")).update(applicationId).digest();
295
- }
296
- /**
297
- * `base64url(iv ‖ ct ‖ tag)`, sealed with AES-256-GCM — an AEAD, so opening
298
- * throws on a single flipped bit and needs no separate signature. The iv must
299
- * be fresh per seal: nonce reuse under one key leaks the payloads and the
300
- * authentication subkey.
301
- *
302
- * The purpose is bound in as additional authenticated data rather than by
303
- * giving each cookie a key of its own: one key, and a `session_data` value
304
- * moved into the token slot then fails to open at all instead of opening into
305
- * a later field check.
306
- */
307
- function sealEnvelope(payload, purpose) {
308
- const iv = randomBytes(IV_BYTES);
309
- const cipher = createCipheriv("aes-256-gcm", sessionKey(), iv);
310
- cipher.setAAD(Buffer.from(purpose));
311
- const sealed = Buffer.concat([cipher.update(payload, "utf8"), cipher.final()]);
312
- return Buffer.concat([
313
- iv,
314
- sealed,
315
- cipher.getAuthTag()
316
- ]).toString("base64url");
317
- }
318
- /** `null` for anything that is not one of ours, with no reason attached. */
319
- function openEnvelope(raw, purpose) {
320
- if (!raw || !BASE64URL.test(raw)) return null;
321
- try {
322
- const bytes = Buffer.from(raw, "base64url");
323
- if (bytes.length < MIN_ENVELOPE_BYTES) return null;
324
- const decipher = createDecipheriv("aes-256-gcm", sessionKey(), bytes.subarray(0, IV_BYTES));
325
- decipher.setAAD(Buffer.from(purpose));
326
- decipher.setAuthTag(bytes.subarray(bytes.length - TAG_BYTES));
327
- return Buffer.concat([decipher.update(bytes.subarray(IV_BYTES, bytes.length - TAG_BYTES)), decipher.final()]).toString("utf8");
328
- } catch {
329
- return null;
330
- }
331
- }
332
-
333
- //#endregion
334
- export { readSessionToken as a, writeCookies as c, softAssert as d, todo as f, readSessionData as i, assert as l, makeSessionDataCookie as n, fetchVisitor as o, makeSessionTokenCookie as r, sessionConfig as s, clearSession as t, panic as u };
@@ -1,28 +0,0 @@
1
- //#region src/auth/user.d.ts
2
- /**
3
- * Declare this interface in your app to narrow every group id the SDK takes and
4
- * returns. Without a declaration, a group id is a plain `string`.
5
- *
6
- * @example
7
- * declare module "@softr/sdk" {
8
- * interface SoftrUserGroups {
9
- * ids:
10
- * | "b1f2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d"
11
- * | "f9e8d7c6-5b4a-4938-8271-605f4e3d2c1b"
12
- * }
13
- * }
14
- */
15
- interface SoftrUserGroups {}
16
- /** A Softr user group id, narrowed to your own ids if you declare {@link SoftrUserGroups}. */
17
- type SoftrUserGroupId = SoftrUserGroups extends {
18
- ids: infer Id extends string;
19
- } ? Id : string;
20
- /** The signed-in visitor. */
21
- type User = {
22
- id: string;
23
- email: string;
24
- name: string;
25
- userGroupIds: Array<SoftrUserGroupId>;
26
- };
27
- //#endregion
28
- export { SoftrUserGroups as n, User as r, SoftrUserGroupId as t };