@softr/sdk 0.0.6 → 0.0.10

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.
@@ -0,0 +1,85 @@
1
+ import { r as User } from "./user-D23hwTsf.js";
2
+ import "@tanstack/react-start/server-only";
3
+
4
+ //#region src/auth/methods/utils.d.ts
5
+ type Result<T, E = Error> = {
6
+ success: false;
7
+ error: E;
8
+ } | {
9
+ success: true;
10
+ data: T;
11
+ };
12
+ type AuthError = {
13
+ code: AuthErrorCode;
14
+ message: string;
15
+ };
16
+ type AuthErrorCode = "invalidCredentials" | "tooManyAttempts" | "emailTaken" | "invalidDetails" | "invalidCode";
17
+ //#endregion
18
+ //#region src/auth/methods/password.d.ts
19
+ /**
20
+ * Signs a visitor in with an email and password.
21
+ *
22
+ * The cache is primed from the same `/me` the resolver would have called anyway,
23
+ * so the next request costs no round-trip.
24
+ */
25
+ declare function signIn(credentials: {
26
+ email: string;
27
+ password: string;
28
+ }): Promise<Result<User, AuthError>>;
29
+ /**
30
+ * Signs the visitor out and clears the session cookies.
31
+ *
32
+ * This revokes **every** outstanding session for that user in this app, on every
33
+ * device: the platform stamps `tokensInvalidatedAt` and rejects anything issued
34
+ * before it. There is no per-device sign-out.
35
+ *
36
+ * A platform that could not revoke leaves the caller signed out here and
37
+ * possibly still signed in elsewhere — loud outside production, logged in it,
38
+ * because the local half already succeeded.
39
+ */
40
+ declare function signOut(): Promise<void>;
41
+ //#endregion
42
+ //#region src/auth/methods/signup.d.ts
43
+ /**
44
+ * Starts a sign-up flow by emailing a verification code.
45
+ *
46
+ * User only exists once `confirmSignUp` returns the code.
47
+ */
48
+ declare function signUp(details: {
49
+ email: string;
50
+ name?: string;
51
+ }): Promise<Result<null, AuthError>>;
52
+ /**
53
+ * Finishes sign-up flow with the emailed code and signs the visitor in.
54
+ *
55
+ * The platform splits on how the app is configured: a code-only app creates the
56
+ * user on the second `sign-up` request and answers with a token, while a
57
+ * password app answers it with an empty 200 and expects the password on
58
+ * `users/new`.
59
+ */
60
+ declare function confirmSignUp(details: {
61
+ email: string;
62
+ /**
63
+ * What `users/new` creates the account with, and unused on a code-only app,
64
+ * which never reaches that request.
65
+ *
66
+ * TODO: temporary in one respect — it is spent a second time on the
67
+ * 400-after-create workaround below, which goes away with the platform fix.
68
+ */
69
+ password: string;
70
+ code: string;
71
+ name?: string;
72
+ }): Promise<Result<User, AuthError>>;
73
+ //#endregion
74
+ //#region src/auth/server.d.ts
75
+ /**
76
+ * Server-only auth methods, should be called from the app's own `createServerFn` handlers.
77
+ */
78
+ declare const auth: {
79
+ signIn: typeof signIn;
80
+ signOut: typeof signOut;
81
+ signUp: typeof signUp;
82
+ confirmSignUp: typeof confirmSignUp;
83
+ };
84
+ //#endregion
85
+ export { auth };
package/dist/server.js ADDED
@@ -0,0 +1,202 @@
1
+ import { a as readSessionToken, c as writeCookies, d as softAssert, f as todo, n as makeSessionDataCookie, o as fetchVisitor, r as makeSessionTokenCookie, s as sessionConfig, t as clearSession, u as panic } from "./session-Blx62HHJ.js";
2
+ import { z } from "zod";
3
+ import "@tanstack/react-start/server-only";
4
+
5
+ //#region src/auth/methods/utils.ts
6
+ function authError(code, message) {
7
+ return {
8
+ success: false,
9
+ error: {
10
+ code,
11
+ message
12
+ }
13
+ };
14
+ }
15
+ const errorSchema = z.object({ message: z.string() });
16
+ async function describe(response, action) {
17
+ const body = errorSchema.safeParse(await response.json().catch(() => null));
18
+ const said = body.success && body.data.message ? body.data.message : response.statusText;
19
+ return `Softr platform refused the ${action}: ${response.status} ${said}`.trim();
20
+ }
21
+ function endpoint(config, path) {
22
+ return `${config.platformApiUrl}/v1/applications/${config.applicationId}/users/${path}`;
23
+ }
24
+
25
+ //#endregion
26
+ //#region src/auth/methods/password.ts
27
+ const signInBody = z.object({
28
+ jwt: z.string().nullish(),
29
+ authenticatorAppAction: z.string().nullish()
30
+ });
31
+ /**
32
+ * Signs a visitor in with an email and password.
33
+ *
34
+ * The cache is primed from the same `/me` the resolver would have called anyway,
35
+ * so the next request costs no round-trip.
36
+ */
37
+ async function signIn(credentials) {
38
+ const config = sessionConfig();
39
+ const response = await fetch(endpoint(config, "sign-in"), {
40
+ method: "POST",
41
+ headers: {
42
+ "content-type": "application/json",
43
+ accept: "application/json"
44
+ },
45
+ body: JSON.stringify(credentials)
46
+ });
47
+ if (response.status === 401 || response.status === 429) return authError(response.status === 401 ? "invalidCredentials" : "tooManyAttempts", await describe(response, "sign-in"));
48
+ if (response.status >= 500) panic(await describe(response, "sign-in"));
49
+ if (response.status === 400) todo(await describe(response, "sign-in"));
50
+ if (!response.ok) throw new Error(`${await describe(response, "sign-in")}. Check SOFTR_APPLICATION_ID and that the app allows sign-in.`);
51
+ const raw = await response.text();
52
+ const body = signInBody.parse(raw.length === 0 ? {} : JSON.parse(raw));
53
+ if (body.authenticatorAppAction) todo(`Softr platform asked for an authenticator step (${body.authenticatorAppAction}) to finish the sign-in. This app requires an authenticator app, which the SDK cannot finish yet.`);
54
+ const token = body.jwt;
55
+ if (!token) todo("Softr platform answered the sign-in by emailing a one-time code. This app is configured for passwordless sign-in, which the SDK cannot finish yet.");
56
+ const user = await fetchVisitor(token);
57
+ if (!user) panic("Session token issued, but no user could be resolved for it.");
58
+ writeCookies([makeSessionTokenCookie(token), makeSessionDataCookie(user, token)]);
59
+ return {
60
+ success: true,
61
+ data: user
62
+ };
63
+ }
64
+ /**
65
+ * Signs the visitor out and clears the session cookies.
66
+ *
67
+ * This revokes **every** outstanding session for that user in this app, on every
68
+ * device: the platform stamps `tokensInvalidatedAt` and rejects anything issued
69
+ * before it. There is no per-device sign-out.
70
+ *
71
+ * A platform that could not revoke leaves the caller signed out here and
72
+ * possibly still signed in elsewhere — loud outside production, logged in it,
73
+ * because the local half already succeeded.
74
+ */
75
+ async function signOut() {
76
+ const config = sessionConfig();
77
+ const token = readSessionToken();
78
+ clearSession();
79
+ if (!token) return;
80
+ const response = await fetch(endpoint(config, "sign-out"), {
81
+ method: "POST",
82
+ headers: {
83
+ authorization: `Bearer ${token}`,
84
+ accept: "application/json"
85
+ }
86
+ });
87
+ softAssert(response.ok || response.status < 500, () => `Softr platform could not revoke the session: ${response.status}. This browser is signed out, but other devices may still be.`);
88
+ }
89
+
90
+ //#endregion
91
+ //#region src/auth/methods/signup.ts
92
+ /**
93
+ * Starts a sign-up flow by emailing a verification code.
94
+ *
95
+ * User only exists once `confirmSignUp` returns the code.
96
+ */
97
+ async function signUp(details) {
98
+ const response = await fetch(endpoint(sessionConfig(), "sign-up"), {
99
+ method: "POST",
100
+ headers: {
101
+ "content-type": "application/json",
102
+ accept: "application/json"
103
+ },
104
+ body: JSON.stringify(signUpBody(details))
105
+ });
106
+ if (response.status >= 500) panic(await describe(response, "sign-up"));
107
+ if (response.status === 409) return authError("emailTaken", await describe(response, "sign-up"));
108
+ if (!response.ok) return authError("invalidDetails", await describe(response, "sign-up"));
109
+ return {
110
+ success: true,
111
+ data: null
112
+ };
113
+ }
114
+ /**
115
+ * Finishes sign-up flow with the emailed code and signs the visitor in.
116
+ *
117
+ * The platform splits on how the app is configured: a code-only app creates the
118
+ * user on the second `sign-up` request and answers with a token, while a
119
+ * password app answers it with an empty 200 and expects the password on
120
+ * `users/new`.
121
+ */
122
+ async function confirmSignUp(details) {
123
+ const config = sessionConfig();
124
+ const verified = await fetch(endpoint(config, "sign-up"), {
125
+ method: "POST",
126
+ headers: {
127
+ "content-type": "application/json",
128
+ accept: "application/json"
129
+ },
130
+ body: JSON.stringify({
131
+ ...signUpBody(details),
132
+ token: details.code
133
+ })
134
+ });
135
+ if (verified.status >= 500) panic(await describe(verified, "sign-up"));
136
+ if (verified.status === 409) return authError("emailTaken", await describe(verified, "sign-up"));
137
+ if (!verified.ok) return authError("invalidCode", await describe(verified, "sign-up"));
138
+ const verifiedBody = await verified.text();
139
+ let token = tokenBody.parse(verifiedBody.length === 0 ? {} : JSON.parse(verifiedBody)).jwt;
140
+ if (!token) {
141
+ const created = await fetch(endpoint(config, "new"), {
142
+ method: "POST",
143
+ headers: {
144
+ "content-type": "application/json",
145
+ accept: "application/json"
146
+ },
147
+ body: JSON.stringify({
148
+ ...signUpBody(details),
149
+ password: details.password,
150
+ token: details.code
151
+ })
152
+ });
153
+ if (created.status >= 500) panic(await describe(created, "sign-up"));
154
+ if (created.status === 409) return authError("emailTaken", await describe(created, "sign-up"));
155
+ if (created.ok) {
156
+ const createdBody = await created.text();
157
+ token = tokenBody.parse(createdBody.length === 0 ? {} : JSON.parse(createdBody)).jwt;
158
+ } else {
159
+ const signedIn = await signIn({
160
+ email: details.email,
161
+ password: details.password
162
+ });
163
+ if (!signedIn.success) return authError("invalidCode", await describe(created, "sign-up"));
164
+ return signedIn;
165
+ }
166
+ }
167
+ if (!token) todo("Softr platform accepted the sign-up and returned no session token. This app is configured for a sign-up flow the SDK cannot finish yet.");
168
+ const user = await fetchVisitor(token);
169
+ if (!user) panic("Session token issued, but no user could be resolved for it.");
170
+ writeCookies([makeSessionTokenCookie(token), makeSessionDataCookie(user, token)]);
171
+ return {
172
+ success: true,
173
+ data: user
174
+ };
175
+ }
176
+ /**
177
+ * `name` is dropped when absent rather than sent as `undefined`: the platform's
178
+ * validator runs on whatever key is present, and an explicit null is not the
179
+ * same request as no name at all.
180
+ */
181
+ function signUpBody(details) {
182
+ return details.name === void 0 ? { email: details.email } : {
183
+ email: details.email,
184
+ name: details.name
185
+ };
186
+ }
187
+ const tokenBody = z.object({ jwt: z.string().nullish() });
188
+
189
+ //#endregion
190
+ //#region src/auth/server.ts
191
+ /**
192
+ * Server-only auth methods, should be called from the app's own `createServerFn` handlers.
193
+ */
194
+ const auth = {
195
+ signIn,
196
+ signOut,
197
+ signUp,
198
+ confirmSignUp
199
+ };
200
+
201
+ //#endregion
202
+ export { auth };
@@ -0,0 +1,334 @@
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 };
@@ -0,0 +1,28 @@
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 };
package/dist/vite.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import "@tanstack/router-generator";
2
- import { Plugin } from "vite";
2
+ import { PluginOption } from "vite";
3
3
 
4
4
  //#region src/routes/discover.d.ts
5
5
 
@@ -25,7 +25,10 @@ type Manifest = {
25
25
  declare const MANIFEST_RELATIVE_PATH: string;
26
26
  /** Writes `<root>/dist/routes.json` and returns its path. Throws on a rule it cannot read. */
27
27
  declare function generateManifest(root: string): Promise<string>;
28
- /** Plugin order does not matter: this puts nothing into the module graph. */
29
- declare function softr(): Plugin;
28
+ /**
29
+ * Everything Softr adds to an app's Vite config: the build-time routes manifest, plus the studio
30
+ * edit engine when the pod supplies one.
31
+ */
32
+ declare function softr(): PluginOption[];
30
33
  //#endregion
31
34
  export { MANIFEST_RELATIVE_PATH, type Manifest, type ManifestNode, generateManifest, softr };