@softr/sdk 0.0.11 → 0.0.13

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 (47) hide show
  1. package/dist/assertions.js +68 -0
  2. package/dist/auth/config.js +27 -0
  3. package/dist/auth/context.d.ts +18 -0
  4. package/dist/auth/isomorphic.d.ts +73 -0
  5. package/dist/auth/isomorphic.js +113 -0
  6. package/dist/auth/methods/password.d.ts +22 -0
  7. package/dist/auth/methods/password.js +51 -0
  8. package/dist/auth/methods/signup.d.ts +37 -0
  9. package/dist/auth/methods/signup.js +89 -0
  10. package/dist/auth/methods/utils.d.ts +15 -0
  11. package/dist/auth/methods/utils.js +13 -0
  12. package/dist/auth/permissions.d.ts +17 -0
  13. package/dist/auth/permissions.js +13 -0
  14. package/dist/auth/platform.js +138 -0
  15. package/dist/auth/server.d.ts +17 -0
  16. package/dist/auth/server.js +17 -0
  17. package/dist/auth/session.js +167 -0
  18. package/dist/{user-D23hwTsf.d.ts → auth/user.d.ts} +1 -1
  19. package/dist/client/timezone.d.ts +4 -0
  20. package/dist/client/timezone.js +11 -0
  21. package/dist/client.d.ts +1 -4
  22. package/dist/client.js +1 -9
  23. package/dist/cookies.js +47 -0
  24. package/dist/core/datasource.d.ts +21 -0
  25. package/dist/core/datasource.js +196 -0
  26. package/dist/core/integration.d.ts +7 -0
  27. package/dist/core/integration.js +32 -0
  28. package/dist/core/query.d.ts +354 -0
  29. package/dist/core/query.js +528 -0
  30. package/dist/core/workflow.d.ts +7 -0
  31. package/dist/core/workflow.js +19 -0
  32. package/dist/index.d.ts +8 -685
  33. package/dist/index.js +4 -1019
  34. package/dist/routes/discover.d.ts +9 -0
  35. package/dist/routes/discover.js +198 -0
  36. package/dist/routes/manifest.d.ts +17 -0
  37. package/dist/routes/manifest.js +148 -0
  38. package/dist/routes/mem-fs.js +71 -0
  39. package/dist/routes/visibility.d.ts +142 -0
  40. package/dist/routes/visibility.js +125 -0
  41. package/dist/server.d.ts +5 -84
  42. package/dist/server.js +5 -194
  43. package/dist/types.d.ts +105 -0
  44. package/dist/vite.d.ts +1 -21
  45. package/dist/vite.js +2 -405
  46. package/package.json +4 -4
  47. package/dist/session-GUEI96C8.js +0 -360
@@ -1,360 +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
- function loadSessionConfig() {
107
- const missing = [];
108
- const applicationId = process.env.SOFTR_APPLICATION_ID;
109
- if (!applicationId) missing.push("SOFTR_APPLICATION_ID");
110
- const sessionSecret = process.env.SOFTR_SESSION_SECRET;
111
- if (!sessionSecret) missing.push("SOFTR_SESSION_SECRET");
112
- if (missing.length > 0) throw new Error(`Softr auth is not configured: missing ${missing.join(", ")}.`);
113
- assert(applicationId && sessionSecret);
114
- const rawMaxAge = process.env.SOFTR_SESSION_MAX_AGE;
115
- let sessionMaxAge = DEFAULT_SESSION_MAX_AGE;
116
- if (rawMaxAge) {
117
- sessionMaxAge = Number(rawMaxAge);
118
- if (!Number.isInteger(sessionMaxAge) || sessionMaxAge <= 0) throw new Error(`SOFTR_SESSION_MAX_AGE must be a positive whole number of seconds, got "${rawMaxAge}".`);
119
- }
120
- return {
121
- applicationId,
122
- sessionSecret,
123
- sessionMaxAge
124
- };
125
- }
126
- let cached;
127
- function sessionConfig() {
128
- cached ??= loadSessionConfig();
129
- return cached;
130
- }
131
-
132
- //#endregion
133
- //#region src/auth/platform.ts
134
- const contextSchema = z.object({ platformApiUrl: z.string() });
135
- /** Calls one of this app's user endpoints on the Softr platform. */
136
- async function platformFetch(path, init) {
137
- const { applicationId } = sessionConfig();
138
- const origin = await platformApiUrl();
139
- return fetch(`${origin}/v1/applications/${applicationId}/users/${path}`, init);
140
- }
141
- /** Origin of the Softr platform API, with no trailing slash. */
142
- async function platformApiUrl() {
143
- const pinned = process.env.SOFTR_PLATFORM_API_URL;
144
- if (pinned) return withoutTrailingSlash(pinned);
145
- const studioApiUrl = process.env.SOFTR_STUDIO_API_URL;
146
- if (!studioApiUrl || process.env.NODE_ENV === "production") panic("Softr auth is not configured: SOFTR_PLATFORM_API_URL is not set.");
147
- const { applicationId } = sessionConfig();
148
- const url = `${withoutTrailingSlash(studioApiUrl)}/v1/api/applications/${applicationId}/context/public`;
149
- let response;
150
- try {
151
- response = await fetch(url, { headers: { accept: "application/json" } });
152
- } catch {
153
- panic(`Could not reach studio-api: ${url}`);
154
- }
155
- if (response.status === 404) panic(`studio-api does not know application ${applicationId}`);
156
- if (!response.ok) panic(`studio-api answered ${response.status} for ${url}`);
157
- const body = contextSchema.safeParse(await response.json().catch(() => null));
158
- if (!body.success) panic(`studio-api returned no platformApiUrl: ${url}`);
159
- return withoutTrailingSlash(body.data.platformApiUrl);
160
- }
161
- function withoutTrailingSlash(url) {
162
- return url.replace(/\/+$/, "");
163
- }
164
-
165
- //#endregion
166
- //#region src/auth/me.ts
167
- /**
168
- * `null` means the platform refused the token — any 4xx, because `/me` answers
169
- * 400 rather than 401 for an expired one, so only the class of the status is
170
- * informative. Anything else that is not a 200 throws.
171
- */
172
- async function fetchVisitor(token) {
173
- const response = await platformFetch("me", {
174
- method: "GET",
175
- headers: {
176
- authorization: `Bearer ${token}`,
177
- accept: "application/json"
178
- }
179
- });
180
- if (response.status >= 400 && response.status < 500) return null;
181
- if (!response.ok) throw new Error(`Softr platform did not answer /me: ${response.status} ${response.statusText}`.trim());
182
- return toUser(await response.json());
183
- }
184
- const meSchema = z.object({
185
- id: z.string(),
186
- full_name: z.string().nullish(),
187
- credentials: z.object({ email: z.string().nullish() }).nullish()
188
- });
189
- function toUser(body) {
190
- const me = meSchema.safeParse(body);
191
- if (!me.success) throw new Error(`Softr platform answered /me with something that is not a user: ${z.prettifyError(me.error)}`);
192
- return {
193
- id: me.data.id,
194
- email: me.data.credentials?.email ?? "",
195
- name: me.data.full_name ?? "",
196
- userGroupIds: []
197
- };
198
- }
199
-
200
- //#endregion
201
- //#region src/auth/session.ts
202
- const SESSION_TOKEN = "session_token";
203
- const SESSION_DATA = "session_data";
204
- const SESSION_DATA_TTL_SECONDS = 300;
205
- /**
206
- * A browser refuses a `__Host-` cookie unless it is `Secure`, `Path=/` and free
207
- * of `Domain` — that last clause is the one worth having, since it stops a
208
- * sibling host planting a cookie of this name for us to honour.
209
- */
210
- const HOST_PREFIX = "__Host-";
211
- function requestIsSecure() {
212
- return getRequestProtocol() === "https";
213
- }
214
- function sessionCookie(base) {
215
- const secure = requestIsSecure();
216
- return {
217
- name: secure ? HOST_PREFIX + base : base,
218
- secure
219
- };
220
- }
221
- /** The platform token this request carries, or `null`. */
222
- function readSessionToken() {
223
- const { name } = sessionCookie(SESSION_TOKEN);
224
- return openEnvelope(readRequestCookies()[name], SESSION_TOKEN);
225
- }
226
- /** The cached visitor for `sessionToken`, or `null` on any kind of miss. */
227
- function readSessionData(sessionToken) {
228
- const { name } = sessionCookie(SESSION_DATA);
229
- const payload = parseSessionData(openEnvelope(readRequestCookies()[name], SESSION_DATA));
230
- if (payload === null) return null;
231
- if (payload.exp <= Math.floor(Date.now() / 1e3)) return null;
232
- if (payload.tb !== tokenBinding(sessionToken)) return null;
233
- return {
234
- id: payload.id,
235
- email: payload.email,
236
- name: payload.name,
237
- userGroupIds: payload.userGroupIds
238
- };
239
- }
240
- function makeSessionTokenCookie(token) {
241
- const { name, secure } = sessionCookie(SESSION_TOKEN);
242
- return serializeCookie(name, sealEnvelope(token, SESSION_TOKEN), {
243
- maxAge: sessionConfig().sessionMaxAge,
244
- secure
245
- });
246
- }
247
- function makeSessionDataCookie(user, sessionToken) {
248
- const { name, secure } = sessionCookie(SESSION_DATA);
249
- const payload = {
250
- id: user.id,
251
- email: user.email,
252
- name: user.name,
253
- userGroupIds: user.userGroupIds,
254
- exp: Math.floor(Date.now() / 1e3) + SESSION_DATA_TTL_SECONDS,
255
- tb: tokenBinding(sessionToken)
256
- };
257
- return serializeCookie(name, sealEnvelope(JSON.stringify(payload), SESSION_DATA), {
258
- maxAge: SESSION_DATA_TTL_SECONDS,
259
- secure
260
- });
261
- }
262
- /**
263
- * Writes rather than returns: a forgotten list would leave the session live.
264
- */
265
- function clearSession() {
266
- clearCookies([SESSION_TOKEN, SESSION_DATA]);
267
- }
268
- const sessionDataSchema = z.object({
269
- id: z.string(),
270
- email: z.string(),
271
- name: z.string(),
272
- userGroupIds: z.array(z.string()),
273
- exp: z.number(),
274
- tb: z.string()
275
- });
276
- /**
277
- * Both spellings on https: a jar can hold both pairs across a move between
278
- * schemes, and the one left behind would revive if the scheme changed back.
279
- */
280
- function clearCookies(bases) {
281
- const secure = requestIsSecure();
282
- writeCookies(bases.flatMap((base) => secure ? [HOST_PREFIX + base, base] : [base]).map((name) => serializeCookie(name, "", {
283
- maxAge: 0,
284
- secure
285
- })));
286
- }
287
- /**
288
- * Over the plaintext token, never the cookie value: that is resealed with a
289
- * fresh iv on every write, so a binding over its bytes would be a permanent
290
- * cache miss.
291
- */
292
- function tokenBinding(sessionToken) {
293
- return createHash("sha256").update(sessionToken).digest("base64url");
294
- }
295
- function parseSessionData(json) {
296
- if (json === null) return null;
297
- let payload;
298
- try {
299
- payload = JSON.parse(json);
300
- } catch {
301
- return null;
302
- }
303
- const data = sessionDataSchema.safeParse(payload);
304
- return data.success ? data.data : null;
305
- }
306
- const IV_BYTES = 12;
307
- const TAG_BYTES = 16;
308
- /** Iv + one byte of ciphertext + tag. Anything shorter is not ours. */
309
- const MIN_ENVELOPE_BYTES = IV_BYTES + TAG_BYTES + 1;
310
- /**
311
- * `Buffer.from(…, "base64url")` skips stray characters rather than throwing.
312
- */
313
- const BASE64URL = /^[A-Za-z0-9_-]+$/;
314
- /**
315
- * One key for both cookies. The application id goes in with the secret so a
316
- * cookie from staging is inert in production even when the two share a secret.
317
- */
318
- function sessionKey() {
319
- const { applicationId, sessionSecret } = sessionConfig();
320
- return createHash("sha256").update(Buffer.from(sessionSecret, "hex")).update(applicationId).digest();
321
- }
322
- /**
323
- * `base64url(iv ‖ ct ‖ tag)`, sealed with AES-256-GCM — an AEAD, so opening
324
- * throws on a single flipped bit and needs no separate signature. The iv must
325
- * be fresh per seal: nonce reuse under one key leaks the payloads and the
326
- * authentication subkey.
327
- *
328
- * The purpose is bound in as additional authenticated data rather than by
329
- * giving each cookie a key of its own: one key, and a `session_data` value
330
- * moved into the token slot then fails to open at all instead of opening into
331
- * a later field check.
332
- */
333
- function sealEnvelope(payload, purpose) {
334
- const iv = randomBytes(IV_BYTES);
335
- const cipher = createCipheriv("aes-256-gcm", sessionKey(), iv);
336
- cipher.setAAD(Buffer.from(purpose));
337
- const sealed = Buffer.concat([cipher.update(payload, "utf8"), cipher.final()]);
338
- return Buffer.concat([
339
- iv,
340
- sealed,
341
- cipher.getAuthTag()
342
- ]).toString("base64url");
343
- }
344
- /** `null` for anything that is not one of ours, with no reason attached. */
345
- function openEnvelope(raw, purpose) {
346
- if (!raw || !BASE64URL.test(raw)) return null;
347
- try {
348
- const bytes = Buffer.from(raw, "base64url");
349
- if (bytes.length < MIN_ENVELOPE_BYTES) return null;
350
- const decipher = createDecipheriv("aes-256-gcm", sessionKey(), bytes.subarray(0, IV_BYTES));
351
- decipher.setAAD(Buffer.from(purpose));
352
- decipher.setAuthTag(bytes.subarray(bytes.length - TAG_BYTES));
353
- return Buffer.concat([decipher.update(bytes.subarray(IV_BYTES, bytes.length - TAG_BYTES)), decipher.final()]).toString("utf8");
354
- } catch {
355
- return null;
356
- }
357
- }
358
-
359
- //#endregion
360
- 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, platformFetch as s, clearSession as t, panic as u };