@softr/sdk 0.0.88-signing.0 → 0.0.88

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 (41) hide show
  1. package/dist/auth/isomorphic.d.ts +3 -2
  2. package/dist/auth/isomorphic.js +4 -1
  3. package/dist/auth/methods/authenticator.js +3 -3
  4. package/dist/auth/methods/code.js +1 -1
  5. package/dist/auth/methods/magicLink.js +1 -1
  6. package/dist/auth/methods/password.js +1 -1
  7. package/dist/auth/methods/passwordLink.js +1 -1
  8. package/dist/auth/methods/signup.js +1 -1
  9. package/dist/auth/methods/social.js +1 -1
  10. package/dist/auth/platform.js +2 -2
  11. package/dist/auth/session.js +8 -7
  12. package/dist/codegen/datasource-docs.js +9 -3
  13. package/dist/cookies.js +29 -3
  14. package/dist/core/file-upload.js +1 -1
  15. package/dist/core/workflow.js +1 -1
  16. package/dist/datasource/record.js +1 -1
  17. package/dist/embedding.js +33 -0
  18. package/dist/fetch.js +1 -61
  19. package/dist/locale-settings.js +1 -1
  20. package/dist/mcp.d.ts +2 -2
  21. package/dist/mcp.js +2 -2
  22. package/dist/package.js +1 -1
  23. package/dist/pwa.js +2 -2
  24. package/dist/route/route.js +1 -1
  25. package/dist/softr-config.schema.js +3 -1
  26. package/package.json +1 -1
  27. package/schema/softr.schema.json +5 -0
  28. package/skills/softr-sdk/SKILL.md +10 -5
  29. package/skills/softr-sdk/auth/SKILL.md +1 -1
  30. package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
  31. package/skills/softr-sdk/current-user/SKILL.md +9 -5
  32. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  33. package/skills/softr-sdk/formatting/SKILL.md +1 -1
  34. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  35. package/skills/softr-sdk/mcp/SKILL.md +1 -1
  36. package/skills/softr-sdk/pwa/SKILL.md +1 -1
  37. package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
  38. package/skills/softr-sdk/record-queries/SKILL.md +2 -2
  39. package/skills/softr-sdk/region-visibility/SKILL.md +3 -5
  40. package/skills/softr-sdk/routes-and-visibility/SKILL.md +85 -44
  41. package/skills/softr-sdk/workflows/SKILL.md +1 -1
@@ -14,14 +14,15 @@ import * as _tanstack_react_start0 from "@tanstack/react-start";
14
14
  * to read.
15
15
  *
16
16
  * Register it once, as a global request middleware in the app's `src/start.ts`.
17
- * It writes nothing but the session cookie.
17
+ * It writes the session cookie, and in production a header that stops other
18
+ * sites from embedding the app.
18
19
  *
19
20
  * @example
20
21
  * export const startInstance = createStart(() => ({
21
22
  * requestMiddleware: [softrAuthMiddleware()],
22
23
  * }))
23
24
  */
24
- declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
25
+ declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
25
26
  user: User | null;
26
27
  permissions: Permissions;
27
28
  formatting: Formatting;
@@ -9,6 +9,7 @@ import { settings } from "./methods/settings.js";
9
9
  import { bootErrorMiddleware } from "../boot-error.js";
10
10
  import { pwaMiddleware } from "../pwa.js";
11
11
  import { faviconMiddleware } from "../favicon.js";
12
+ import { embeddingMiddleware } from "../embedding.js";
12
13
  import { createContext, useContext } from "react";
13
14
  import { createMiddleware, createServerFn, getGlobalStartContext } from "@tanstack/react-start";
14
15
  import { getRequestHeader } from "@tanstack/react-start/server";
@@ -22,7 +23,8 @@ import { jsx } from "react/jsx-runtime";
22
23
  * to read.
23
24
  *
24
25
  * Register it once, as a global request middleware in the app's `src/start.ts`.
25
- * It writes nothing but the session cookie.
26
+ * It writes the session cookie, and in production a header that stops other
27
+ * sites from embedding the app.
26
28
  *
27
29
  * @example
28
30
  * export const startInstance = createStart(() => ({
@@ -31,6 +33,7 @@ import { jsx } from "react/jsx-runtime";
31
33
  */
32
34
  function softrAuthMiddleware() {
33
35
  return createMiddleware({ type: "request" }).middleware([
36
+ embeddingMiddleware(),
34
37
  bootErrorMiddleware(),
35
38
  pwaMiddleware(),
36
39
  faviconMiddleware()
@@ -46,7 +46,7 @@ async function confirmAuthenticatorSetup(details) {
46
46
  throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`);
47
47
  }
48
48
  const { session, backupCodes } = result.data;
49
- writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
49
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
50
50
  user: session.user,
51
51
  permissions: session.permissions
52
52
  }, session.jwt)]);
@@ -75,7 +75,7 @@ async function skipAuthenticatorSetup() {
75
75
  }
76
76
  const { session } = result.data;
77
77
  assert(session, "Expected a session from skipping setup, but got none");
78
- writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
78
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
79
79
  user: session.user,
80
80
  permissions: session.permissions
81
81
  }, session.jwt)]);
@@ -101,7 +101,7 @@ async function verifyAuthenticator(credentials) {
101
101
  }
102
102
  const { session } = result.data;
103
103
  assert(session, "Expected a session from verification, but got none");
104
- writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
104
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
105
105
  user: session.user,
106
106
  permissions: session.permissions
107
107
  }, session.jwt)]);
@@ -56,7 +56,7 @@ async function signInWithCode(credentials) {
56
56
  }
57
57
  const { session } = result.data;
58
58
  assert(session, "Expected a session from sign-in, but got none");
59
- writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
59
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
60
60
  user: session.user,
61
61
  permissions: session.permissions
62
62
  }, session.jwt)]);
@@ -36,7 +36,7 @@ async function signInWithMagicLink(credentials) {
36
36
  }
37
37
  const { session } = result.data;
38
38
  assert(session, "Expected a session from magic-link sign-in, but got none");
39
- writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
39
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
40
40
  user: session.user,
41
41
  permissions: session.permissions
42
42
  }, session.jwt)]);
@@ -35,7 +35,7 @@ async function signIn(credentials) {
35
35
  }
36
36
  const { session } = result.data;
37
37
  assert(session, "Expected a session from sign-in, but got none");
38
- writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
38
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
39
39
  user: session.user,
40
40
  permissions: session.permissions
41
41
  }, session.jwt)]);
@@ -68,7 +68,7 @@ async function setPasswordWithLink(details) {
68
68
  }
69
69
  const { session } = result.data;
70
70
  assert(session, "Expected a session from setting a password, but got none");
71
- writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
71
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
72
72
  user: session.user,
73
73
  permissions: session.permissions
74
74
  }, session.jwt)]);
@@ -66,7 +66,7 @@ async function confirmSignUp(details) {
66
66
  }
67
67
  const { session } = result.data;
68
68
  assert(session, "Expected a session from sign-up, but got none");
69
- writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
69
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
70
70
  user: session.user,
71
71
  permissions: session.permissions
72
72
  }, session.jwt)]);
@@ -41,7 +41,7 @@ async function signInWithGoogle(credentials) {
41
41
  }
42
42
  const { session } = result.data;
43
43
  assert(session, "Expected a session from Google sign-in, but got none");
44
- writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
44
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
45
45
  user: session.user,
46
46
  permissions: session.permissions
47
47
  }, session.jwt)]);
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../assertions.js";
2
- import { softrApiUrl } from "../softr-api.js";
3
2
  import { fetch } from "../fetch.js";
4
- import { permissionsSchema } from "./permissions.js";
5
3
  import { softrConfig } from "../softr-config.js";
4
+ import { permissionsSchema } from "./permissions.js";
5
+ import { softrApiUrl } from "../softr-api.js";
6
6
  import { z } from "zod";
7
7
 
8
8
  //#region src/auth/platform.ts
@@ -1,4 +1,4 @@
1
- import { readRequestCookies, serializeCookie, writeCookies } from "../cookies.js";
1
+ import { expireCookie, expireOtherCopy, readRequestCookies, serializeCookie, writeCookies } from "../cookies.js";
2
2
  import { permissionsSchema } from "./permissions.js";
3
3
  import { sessionConfig } from "./config.js";
4
4
  import { userSchema } from "./user.js";
@@ -65,12 +65,16 @@ function readSessionData(sessionToken) {
65
65
  permissions: payload.permissions
66
66
  };
67
67
  }
68
+ /**
69
+ * The token cookie, after a deletion of any copy from before `allowEmbedding`
70
+ * changed. Both would be sent, and the old one could be read instead.
71
+ */
68
72
  function makeSessionTokenCookie(token) {
69
73
  const { name, secure } = sessionCookie(SESSION_TOKEN);
70
- return serializeCookie(name, sealEnvelope(token, SESSION_TOKEN), {
74
+ return [...expireOtherCopy(name, secure), serializeCookie(name, sealEnvelope(token, SESSION_TOKEN), {
71
75
  maxAge: sessionConfig().sessionMaxAge,
72
76
  secure
73
- });
77
+ })];
74
78
  }
75
79
  function makeSessionDataCookie(session, sessionToken) {
76
80
  const { name, secure } = sessionCookie(SESSION_DATA);
@@ -141,10 +145,7 @@ const sessionDataSchema = z.object({
141
145
  */
142
146
  function clearCookies(bases) {
143
147
  const secure = requestIsSecure();
144
- writeCookies(bases.flatMap((base) => secure ? [sessionCookieName(base, secure), base] : [base]).map((name) => serializeCookie(name, "", {
145
- maxAge: 0,
146
- secure
147
- })));
148
+ writeCookies(bases.flatMap((base) => secure ? [sessionCookieName(base, secure), base] : [base]).flatMap((name) => expireCookie(name, secure)));
148
149
  }
149
150
  /**
150
151
  * Over the plaintext token, never the cookie value: that is resealed with a
@@ -73,15 +73,16 @@ function renderUserPropertiesDoc(users, context) {
73
73
  "",
74
74
  "```tsx",
75
75
  "import { createFileRoute, redirect } from '@tanstack/react-router'",
76
- "import { assertRouteAccess, defineVisibility } from '@softr/sdk'",
76
+ "import { assertRouteAccess, definePage, pageHead } from '@softr/sdk'",
77
77
  "",
78
- "const visibility = defineVisibility({ userGroupTypes: ['LOGGED_IN_USERS'] })",
78
+ "const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] }, title: 'Example' })",
79
79
  "",
80
80
  "export const Route = createFileRoute('/example')({",
81
81
  " beforeLoad: (opts) => {",
82
- " assertRouteAccess(visibility, opts)",
82
+ " assertRouteAccess(pageSettings, opts)",
83
83
  ` if (opts.context.user.properties.${first} == null) throw redirect({ to: '/' })`,
84
84
  " },",
85
+ " head: pageHead(pageSettings),",
85
86
  "})",
86
87
  "```",
87
88
  "",
@@ -90,14 +91,19 @@ function renderUserPropertiesDoc(users, context) {
90
91
  "```tsx",
91
92
  "import { createFileRoute } from '@tanstack/react-router'",
92
93
  "import { createServerFn } from '@tanstack/react-start'",
94
+ "import { definePage, guardRoute, pageHead } from '@softr/sdk'",
93
95
  "",
94
96
  `const get${pascalCase(first)} = createServerFn().handler(async ({ context }) => {`,
95
97
  " if (!context.user) throw new Error('Not signed in')",
96
98
  ` return context.user.properties.${first}`,
97
99
  "})",
98
100
  "",
101
+ "const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] }, title: 'Example' })",
102
+ "",
99
103
  "export const Route = createFileRoute('/example')({",
104
+ " beforeLoad: guardRoute(pageSettings),",
100
105
  ` loader: () => get${pascalCase(first)}(),`,
106
+ " head: pageHead(pageSettings),",
101
107
  " component: Example,",
102
108
  "})",
103
109
  "",
package/dist/cookies.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { softAssert } from "./assertions.js";
2
+ import { softrConfig } from "./softr-config.js";
2
3
  import { getRequestHeader, getResponseHeaders, setResponseHeader } from "@tanstack/react-start/server";
3
4
 
4
5
  //#region src/cookies.ts
@@ -36,8 +37,33 @@ function serializeCookie(name, value, { maxAge, secure }) {
36
37
  return parts.join("; ");
37
38
  }
38
39
  function sameSiteAttributes(secure) {
39
- if (secure && process.env.NODE_ENV !== "production") return ["SameSite=None", "Partitioned"];
40
- return ["SameSite=Lax"];
40
+ return partitions(secure) ? ["SameSite=None", "Partitioned"] : ["SameSite=Lax"];
41
+ }
42
+ function partitions(secure) {
43
+ return secure && (process.env.NODE_ENV !== "production" || (softrConfig().allowEmbedding ?? []).length > 0);
44
+ }
45
+ function expired(name, partitioned) {
46
+ return partitioned ? `${name}=; Path=/; HttpOnly; Secure; SameSite=None; Partitioned; Max-Age=0` : `${name}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;
47
+ }
48
+ /**
49
+ * The deletions for one cookie. A browser keeps a partitioned and a plain
50
+ * cookie of one name apart, and sends both. Which one the app wrote can change
51
+ * between sign-in and sign-out, when `allowEmbedding` changes. So over https,
52
+ * delete both. The one left behind would keep the visitor signed in.
53
+ */
54
+ function expireCookie(name, secure) {
55
+ if (!secure) return [serializeCookie(name, "", {
56
+ maxAge: 0,
57
+ secure
58
+ })];
59
+ return [expired(name, false), expired(name, true)];
60
+ }
61
+ /**
62
+ * The deletion of the copy the other mode would write. Sent with a new cookie,
63
+ * so a copy from before `allowEmbedding` changed can't be read in its place.
64
+ */
65
+ function expireOtherCopy(name, secure) {
66
+ return secure ? [expired(name, !partitions(secure))] : [];
41
67
  }
42
68
  const USER_TIMEZONE_COOKIE = "user-timezone";
43
69
  function readUserTimezone() {
@@ -56,4 +82,4 @@ function writeCookies(cookies) {
56
82
  }
57
83
 
58
84
  //#endregion
59
- export { readRequestCookies, readUserTimezone, serializeCookie, writeCookies };
85
+ export { expireCookie, expireOtherCopy, readRequestCookies, readUserTimezone, serializeCookie, writeCookies };
@@ -1,7 +1,7 @@
1
- import { softrApiUrl } from "../softr-api.js";
2
1
  import { fetch } from "../fetch.js";
3
2
  import { sessionConfig } from "../auth/config.js";
4
3
  import { readSessionToken } from "../auth/session.js";
4
+ import { softrApiUrl } from "../softr-api.js";
5
5
  import { randomUUID } from "node:crypto";
6
6
 
7
7
  //#region src/core/file-upload.ts
@@ -1,7 +1,7 @@
1
- import { softrApiUrl } from "../softr-api.js";
2
1
  import { fetch } from "../fetch.js";
3
2
  import { sessionConfig } from "../auth/config.js";
4
3
  import { readSessionToken } from "../auth/session.js";
4
+ import { softrApiUrl } from "../softr-api.js";
5
5
 
6
6
  //#region src/core/workflow.ts
7
7
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../assertions.js";
2
- import { softrApiUrl } from "../softr-api.js";
3
2
  import { fetch } from "../fetch.js";
4
3
  import { readUserTimezone } from "../cookies.js";
5
4
  import { readSessionToken } from "../auth/session.js";
5
+ import { softrApiUrl } from "../softr-api.js";
6
6
  import { isDatasourceAction } from "../action.js";
7
7
  import { buildFilterCriteria, buildOrderBy, dealiasFilterCriteria, dealiasOrderBy } from "./filter.js";
8
8
  import { andAll, makeFieldSet, makeSortSet } from "./fields.js";
@@ -0,0 +1,33 @@
1
+ import { softrConfig } from "./softr-config.js";
2
+ import { createMiddleware } from "@tanstack/react-start";
3
+
4
+ //#region src/embedding.ts
5
+ /**
6
+ * Stops other sites from showing the published app in an iframe. The origins
7
+ * softr.json lists in `allowEmbedding` still can.
8
+ *
9
+ * Production only. The dev server runs in the preview pod, and Studio shows
10
+ * that preview in an iframe on another site.
11
+ */
12
+ function embeddingMiddleware() {
13
+ return createMiddleware({ type: "request" }).server(async ({ next }) => {
14
+ const result = await next();
15
+ if (process.env.NODE_ENV !== "production") return result;
16
+ const policy = [
17
+ "frame-ancestors",
18
+ "'self'",
19
+ ...softrConfig().allowEmbedding ?? []
20
+ ].join(" ");
21
+ try {
22
+ result.response.headers.append("content-security-policy", policy);
23
+ return result;
24
+ } catch {
25
+ const response = new Response(result.response.body, result.response);
26
+ response.headers.append("content-security-policy", policy);
27
+ return response;
28
+ }
29
+ });
30
+ }
31
+
32
+ //#endregion
33
+ export { embeddingMiddleware };
package/dist/fetch.js CHANGED
@@ -1,29 +1,9 @@
1
- import { version } from "./package.js";
2
- import { assert, requireDefined } from "./assertions.js";
3
1
  import { logger } from "./logger.js";
4
- import { softrApiUrl } from "./softr-api.js";
5
2
 
6
3
  //#region src/fetch.ts
7
4
  const fetch = async (input, init) => {
8
- const url = input instanceof Request ? input.url : String(input);
9
- if ([
10
- softrApiUrl("SOFTR_PLATFORM_API_URL"),
11
- softrApiUrl("SOFTR_DATASOURCE_API_URL"),
12
- softrApiUrl("SOFTR_WORKFLOWS_API_URL")
13
- ].some((base) => url.startsWith(`${base}/`))) {
14
- const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
15
- headers.set("user-agent", `softr-sdk/${version}`);
16
- init = {
17
- ...init,
18
- headers
19
- };
20
- const signed = await sign(input, init);
21
- if (signed) {
22
- input = signed;
23
- init = void 0;
24
- }
25
- }
26
5
  if (process.env.NODE_ENV === "production") return globalThis.fetch(input, init);
6
+ const url = input instanceof Request ? input.url : String(input);
27
7
  const method = init?.method ?? (input instanceof Request ? input.method : "GET");
28
8
  const started = Date.now();
29
9
  try {
@@ -36,46 +16,6 @@ const fetch = async (input, init) => {
36
16
  throw error;
37
17
  }
38
18
  };
39
- async function sign(input, init) {
40
- const key = process.env.SOFTR_REQUEST_SIGNING_KEY;
41
- const keyId = process.env.SOFTR_REQUEST_SIGNING_KEY_ID;
42
- if (!key || !keyId) return void 0;
43
- assert(/^[0-9a-f]{64}$/i.test(key), "SOFTR_REQUEST_SIGNING_KEY must be 64 hex characters");
44
- assert(!/["\\]/.test(keyId), "SOFTR_REQUEST_SIGNING_KEY_ID must not contain quotes or backslashes");
45
- const request = new Request(input, init);
46
- const headers = new Headers(request.headers);
47
- const { host, pathname, search } = new URL(request.url);
48
- const derived = {
49
- "@method": request.method,
50
- "@authority": host,
51
- "@path": pathname,
52
- "@query": search || "?"
53
- };
54
- const fields = Object.keys(derived);
55
- const body = request.body ? new Uint8Array(await request.arrayBuffer()) : void 0;
56
- if (body) {
57
- headers.set("content-digest", `sha-256=:${base64(await crypto.subtle.digest("SHA-256", body))}:`);
58
- fields.push("content-type", "content-digest");
59
- }
60
- if (headers.has("authorization")) fields.push("authorization");
61
- const created = Math.floor(Date.now() / 1e3);
62
- const params = `(${fields.map((field) => `"${field}"`).join(" ")});created=${created};keyid="${keyId}";tag="softr-code-app"`;
63
- const base = [...fields.map((field) => `"${field}": ${derived[field] ?? requireDefined(headers.get(field), field)}`), `"@signature-params": ${params}`].join("\n");
64
- const hmacKey = await crypto.subtle.importKey("raw", Uint8Array.from(key.match(/../g) ?? [], (byte) => parseInt(byte, 16)), {
65
- name: "HMAC",
66
- hash: "SHA-256"
67
- }, false, ["sign"]);
68
- const signature = base64(await crypto.subtle.sign("HMAC", hmacKey, new TextEncoder().encode(base)));
69
- headers.set("signature-input", `softr=${params}`);
70
- headers.set("signature", `softr=:${signature}:`);
71
- return new Request(request, {
72
- headers,
73
- body
74
- });
75
- }
76
- function base64(bytes) {
77
- return btoa(String.fromCharCode(...new Uint8Array(bytes)));
78
- }
79
19
 
80
20
  //#endregion
81
21
  export { fetch };
@@ -1,8 +1,8 @@
1
1
  import { logger } from "./logger.js";
2
- import { softrApiUrl } from "./softr-api.js";
3
2
  import { fetch } from "./fetch.js";
4
3
  import { readRequestCookies, serializeCookie, writeCookies } from "./cookies.js";
5
4
  import { sessionConfig } from "./auth/config.js";
5
+ import { softrApiUrl } from "./softr-api.js";
6
6
  import { localeSettingsSchema } from "./formatting.js";
7
7
  import { getRequestProtocol } from "@tanstack/react-start/server";
8
8
 
package/dist/mcp.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DatasourceAction } from "./action.js";
2
- import * as _tanstack_react_start5 from "@tanstack/react-start";
2
+ import * as _tanstack_react_start6 from "@tanstack/react-start";
3
3
 
4
4
  //#region src/mcp.d.ts
5
5
 
@@ -31,6 +31,6 @@ type SoftrMcpOptions = {
31
31
  * ],
32
32
  * }))
33
33
  */
34
- declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start5.RequestMiddlewareAfterServer<{}, undefined, undefined>;
34
+ declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start6.RequestMiddlewareAfterServer<{}, undefined, undefined>;
35
35
  //#endregion
36
36
  export { softrMcpMiddleware };
package/dist/mcp.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { assert } from "./assertions.js";
2
- import { softrApiUrl } from "./softr-api.js";
3
2
  import { fetch } from "./fetch.js";
3
+ import { softrConfig } from "./softr-config.js";
4
4
  import { sessionConfig } from "./auth/config.js";
5
5
  import { readSessionToken, withSessionToken } from "./auth/session.js";
6
+ import { softrApiUrl } from "./softr-api.js";
6
7
  import { isDatasourceAction } from "./action.js";
7
- import { softrConfig } from "./softr-config.js";
8
8
  import { makePlatform } from "./auth/platform.js";
9
9
  import { ds } from "./datasource/datasource.js";
10
10
  import { z } from "zod";
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.0.88-signing.0";
2
+ var version = "0.0.88";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/pwa.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { logger } from "./logger.js";
2
- import { softrApiUrl } from "./softr-api.js";
3
2
  import { fetch } from "./fetch.js";
4
3
  import { sessionConfig } from "./auth/config.js";
4
+ import { softrApiUrl } from "./softr-api.js";
5
5
  import { z } from "zod";
6
6
  import { Fragment, createElement, useEffect, useState } from "react";
7
7
  import { createMiddleware } from "@tanstack/react-start";
@@ -125,7 +125,7 @@ function usePwaInstall() {
125
125
  useEffect(() => {
126
126
  if (window.matchMedia("(display-mode: standalone)").matches || "standalone" in navigator && navigator.standalone === true) return;
127
127
  let cancelled = false;
128
- globalThis.fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then(async (response) => {
128
+ fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then(async (response) => {
129
129
  if (!response.ok) return;
130
130
  const parsed = installSchema.safeParse(await response.json());
131
131
  if (!parsed.success || cancelled) return;
@@ -1,6 +1,6 @@
1
1
  import { panic } from "../assertions.js";
2
- import { ACCESS_REASONS, checkRule } from "./visibility.js";
3
2
  import { softrConfig } from "../softr-config.js";
3
+ import { ACCESS_REASONS, checkRule } from "./visibility.js";
4
4
  import { redirect } from "@tanstack/react-router";
5
5
 
6
6
  //#region src/route/route.ts
@@ -21,6 +21,7 @@ const AccessBehaviour = z.union([
21
21
  z.object({ strategy: z.literal("throw") })
22
22
  ], { error: "must be a path like \"/login\", { \"strategy\": \"redirect\", \"to\": \"/login\" } or { \"strategy\": \"throw\" }" });
23
23
  const AppPath = z.string().refine((path$1) => path$1.startsWith("/") && !path$1.includes("?") && !path$1.includes("#") && new URL(path$1, "https://app.invalid").origin === "https://app.invalid", { error: "must be a path on this app like \"/login\", with no \"?\" or \"#\"" });
24
+ const Origin = z.union([z.literal("*"), z.string().regex(/^https:\/\/[^/\\?#@\s;,]+$/).refine(URL.canParse).transform((origin) => new URL(origin).origin)], { error: "must be an https origin like \"https://partner.com\", with no path or trailing \"/\", or \"*\" for any site" });
24
25
  const SoftrConfigSchema = z.object({
25
26
  auth: z.strictObject({
26
27
  routes: z.strictObject({
@@ -47,7 +48,8 @@ const SoftrConfigSchema = z.object({
47
48
  alreadyAuthenticated: AccessBehaviour
48
49
  })
49
50
  }),
50
- user: z.strictObject({ properties: z.record(z.string(), z.string()) }).optional()
51
+ user: z.strictObject({ properties: z.record(z.string(), z.string()) }).optional(),
52
+ allowEmbedding: z.array(Origin).optional()
51
53
  });
52
54
  function loadSoftrConfig(root) {
53
55
  const file = path.join(root, SOFTR_CONFIG_FILE);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "0.0.88-signing.0",
3
+ "version": "0.0.88",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -67,6 +67,11 @@
67
67
  },
68
68
  "required": ["properties"],
69
69
  "additionalProperties": false
70
+ },
71
+ "allowEmbedding": {
72
+ "type": "array",
73
+ "description": "Sites that may show the published app in an iframe, signed-in pages included, as https origins like \"https://partner.com\", or \"*\" for any site. Any other site is still blocked. With at least one, session cookies use SameSite=None, which drops the browser's CSRF protection. Empty by default.",
74
+ "items": { "type": "string", "pattern": "^(\\*|https://[^/\\\\?#@\\s;,]+)$" }
70
75
  }
71
76
  },
72
77
  "required": ["auth"],
@@ -3,12 +3,13 @@ name: softr-sdk
3
3
  description: >-
4
4
  Entry point for @softr/sdk: its four entrypoints (@softr/sdk, /server,
5
5
  /client, /vite) and their client-server boundary, softrAuthMiddleware and the
6
- Softr context, and which sub-skill covers each task. Load it when unsure which
7
- sub-skill applies, or when touching the wiring.
6
+ Softr context, embedding the app in another site's iframe, and which sub-skill
7
+ covers each task. Load it when unsure which sub-skill applies, when touching
8
+ the wiring, or when the user wants the app embedded elsewhere.
8
9
  metadata:
9
10
  type: core
10
11
  library: softr-sdk
11
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
12
13
  ---
13
14
 
14
15
  # Softr SDK core
@@ -17,7 +18,7 @@ metadata:
17
18
 
18
19
  > **CRITICAL**: The SDK is split across four entrypoints and the split is enforced. `ds` and `auth` exist only on `@softr/sdk/server` and only run inside a `createServerFn` handler. Importing them anywhere else fails the build.
19
20
  >
20
- > **CRITICAL**: Every route file must declare its audience with `defineVisibility` and guard itself with that rule in `beforeLoad`. There is no default and nothing is inherited from a sibling.
21
+ > **CRITICAL**: Every route file must declare its settings with `definePage`, guard itself with them in `beforeLoad` and render them in `head`. There is no default and nothing is inherited from a sibling.
21
22
  >
22
23
  > **CRITICAL**: The app is already wired. `src/start.ts`, `src/router.tsx` and `src/routes/__root.tsx` register `softrAuthMiddleware` and resolve the session. Do not add a second registration of it. `softrMcpMiddleware` is the one thing an app adds to `src/start.ts` itself — load the `softr-sdk/mcp` sub-skill before doing so.
23
24
  >
@@ -29,7 +30,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
29
30
 
30
31
  | Import | Runs | Holds |
31
32
  | --- | --- | --- |
32
- | `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
33
+ | `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
33
34
  | `@softr/sdk/server` | Server only | `ds`, `auth`, `workflow`, `integration` |
34
35
  | `@softr/sdk/client` | Browser only | `useFileUpload` |
35
36
  | `@softr/sdk/vite` | Build | `softr()`, already in `vite.config.ts` |
@@ -148,3 +149,7 @@ type User = {
148
149
  userGroupIds: Array<SoftrUserGroupId> // the app's own group ids
149
150
  }
150
151
  ```
152
+
153
+ ## Embedding the app in another site
154
+
155
+ The published app refuses to load inside another site's iframe. The Studio preview is not affected. When the user asks to embed the app on their site, list that site's origin in `softr.json`: `"allowEmbedding": ["https://partner.com"]`. Ask for the exact origin if you don't have it. Only listed sites can embed the app. Use `["*"]` only when the user wants any site to embed it. Remove the list to block embedding again. Sign-in then works inside the embed. Session cookies switch from SameSite=Lax to None, so the app loses the browser's CSRF protection. Only set it when the user asks. There are two more limits to tell the user: Safari may not keep the visitor signed in, and links from emails (magic link, password reset) open the app in a new tab, not in the embed.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
13
13
  ---
14
14
 
15
15
  **Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
13
13
  ---
14
14
 
15
15
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
13
13
  ---
14
14
 
15
15
  # The current user
@@ -55,12 +55,16 @@ It returns `User | null` and never suspends or fetches. It selects off root rout
55
55
 
56
56
  ```tsx
57
57
  export const Route = createFileRoute('/_app/invoices')({
58
- beforeLoad: guardRoute(visibility),
59
- loader: ({ context }) => fetchInvoicesFor({ data: { userId: context.user!.id } }),
58
+ beforeLoad: guardRoute(pageSettings),
59
+ loader: (opts) => {
60
+ assertRouteAccess(pageSettings, opts)
61
+ return fetchInvoicesFor({ data: { userId: opts.context.user.id } })
62
+ },
63
+ head: pageHead(pageSettings),
60
64
  })
61
65
  ```
62
66
 
63
- A `guardRoute` in `beforeLoad` guarantees a visitor at runtime, but it does not change what the compiler sees. `context.user` is still `User | null` further down the route. `isAuthorized(visibility, context)` is the check that narrows it, so prefer that over `!`. See [routes-and-visibility](../routes-and-visibility/SKILL.md).
67
+ A `guardRoute` in `beforeLoad` guarantees a visitor at runtime, but it does not change what the compiler sees. `context.user` is still `User | null` in the loader. `assertRouteAccess(pageSettings, opts)` at the top of the loader narrows it there, so prefer that over `!`. Take `opts` whole: a destructured `context` does not narrow. See [routes-and-visibility](../routes-and-visibility/SKILL.md).
64
68
 
65
69
  ### In a server function: `context`
66
70
 
@@ -94,7 +98,7 @@ For every group's name and id, read `docs/user-groups.md`. It lists every group
94
98
 
95
99
  ## References
96
100
 
97
- - [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md): `isAuthorized` narrows `context.user` while applying the route's rule
101
+ - [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md): `assertRouteAccess` narrows `context.user` while applying the route's rule
98
102
  - [region-visibility/SKILL.md](../region-visibility/SKILL.md): rendering a region only to the visitors a rule admits
99
103
  - [record-queries/SKILL.md](../record-queries/SKILL.md): filtering a query by the visitor, and who really authorizes the read
100
104
  - [auth/SKILL.md](../auth/SKILL.md): what changes the value `useCurrentUser` returns
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 0.0.88-signing.0
10
+ library_version: 0.0.88
11
11
  ---
12
12
 
13
13
  **Boundary.** `upload` lives on `@softr/sdk/server` and runs inside server functions. `useFileUpload` and `FileItem` live on `@softr/sdk` and run in components. `FileAttachment` comes from `@softr/sdk` and can be imported anywhere.
@@ -8,7 +8,7 @@ description: >-
8
8
  metadata:
9
9
  type: sub-skill
10
10
  library: softr-sdk
11
- library_version: 0.0.88-signing.0
11
+ library_version: 0.0.88
12
12
  ---
13
13
 
14
14
  # Dates, times and numbers
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 0.0.88-signing.0
10
+ library_version: 0.0.88
11
11
  ---
12
12
 
13
13
  **Boundary.** `integration` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineIntegration` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
13
13
  ---
14
14
 
15
15
  **Boundary.** `softrMcpMiddleware` lives on `@softr/sdk` and is registered once, in `src/start.ts`. The actions you hand it are the same `defineQuery` / `defineMutation` values the app's own pages use — declared wherever they already live, not duplicated for MCP.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
13
13
  ---
14
14
 
15
15
  # Installing the app
@@ -8,7 +8,7 @@ description: >-
8
8
  metadata:
9
9
  type: sub-skill
10
10
  library: softr-sdk
11
- library_version: 0.0.88-signing.0
11
+ library_version: 0.0.88
12
12
  ---
13
13
 
14
14
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineMutation` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
13
13
  ---
14
14
 
15
15
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. The same holds for any helper that calls `ds`: declare it inside the handler. A function at module level that calls `ds` keeps the server-only import in the browser bundle, and every page stops loading until it moves. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -53,7 +53,7 @@ const publishedPosts = defineQuery({
53
53
  - `{ userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] }`: everyone, signed out included. `customGroups` narrows only the signed-in half.
54
54
  - `{ userGroupTypes: ['NON_LOGGED_IN_USERS'] }`: signed-out visitors only.
55
55
  - `{ userGroupTypes: ['LOGGED_IN_USERS'] }`: any signed-in visitor, narrowed to particular groups with `customGroups: ['00000000-0000-0000-0000-00000000000a']`. `customGroups` is added to `userGroupTypes`, never written in place of it.
56
- - Write each group id as a literal in `permissions`. An id taken from a `const` is a lint error, as it is in a route's visibility.
56
+ - Write each group id as a literal in `permissions`. An id taken from a `const` is a lint error.
57
57
  - Write the object inline in the `defineQuery` call. Passing the declaration or its `fields` through a variable, or spreading one in, widens the field ids to `string` and the types stop checking.
58
58
 
59
59
  A query fixes the table and the columns, not the rows: filters, sorting and paging stay at the call site, because a list screen changes them as the user types. Declare as many queries over one datasource as the app needs, each carrying the fields its own screen touches.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
13
13
  ---
14
14
 
15
15
  **Boundary.** `Audience` and `defineVisibility` come from `@softr/sdk` and work anywhere.
@@ -47,11 +47,9 @@ The rules are the same four a route uses, and [routes-and-visibility](../routes-
47
47
 
48
48
  ### Where the rule is declared
49
49
 
50
- A region's rule is an ordinary value. It can sit beside the component, or come from a module the whole app shares so several regions read the same one. A route's rule cannot. Softr reads that one out of the route file, so it has to be declared there.
50
+ A region's rule is an ordinary value. It can sit beside the component, in the route file, or in a module the whole app shares so several regions read the same one.
51
51
 
52
- Two files cannot hold a region's rule. Any declaration in `__root.tsx` is a build error. In the lazy half of a split route, Softr takes the first declaration as the route's own. Put the rule in the component's file or a shared module and import it.
53
-
54
- A route file may declare a region's rule alongside its own. The route's rule is the one `beforeLoad` names.
52
+ It is separate from the route's own rule. That one is the `visibility` of the route's `definePage`, which `beforeLoad` applies: see [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md).
55
53
 
56
54
  ### Hiding a control is not authorization
57
55
 
@@ -1,21 +1,22 @@
1
1
  ---
2
2
  name: routes-and-visibility
3
3
  description: >-
4
- Add a route file and declare who may see it: defineVisibility with
5
- LOGGED_IN_USERS, NON_LOGGED_IN_USERS and customGroups, guardRoute and
6
- assertRouteAccess in a route, isAuthorized and checkAccess anywhere, rendering
7
- an access error, and the lint rule that requires the declaration.
4
+ Add a route file and declare its settings: definePage with its visibility
5
+ (LOGGED_IN_USERS, NON_LOGGED_IN_USERS and customGroups) and its title,
6
+ guardRoute or assertRouteAccess in beforeLoad, pageHead in head,
7
+ isAuthorized and checkAccess anywhere, rendering an access error, and the
8
+ lint rules that require the declaration.
8
9
  metadata:
9
10
  type: sub-skill
10
11
  library: softr-sdk
11
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
12
13
  ---
13
14
 
14
- **Boundary.** `defineVisibility`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
15
+ **Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
15
16
 
16
17
  # Route visibility
17
18
 
18
- Every route file in a Softr app declares who may see it. Softr reads that declaration out of the source text without executing it and publishes it to Softr Studio, which shows the app owner every route and its audience. That is why the rules below are strict: a rule Softr cannot read is a rule Studio cannot show.
19
+ Every route file in a Softr app declares its settings: who may see it, its title and its SEO tags. Softr reads them out of the source text without executing it and shows them in Softr Studio, where the app owner sees every route and its audience and can change them. That is why the rules below are strict: a setting Softr cannot read is a setting Studio cannot show.
19
20
 
20
21
  ## Setup
21
22
 
@@ -23,12 +24,16 @@ Every route file, without exception, looks like this:
23
24
 
24
25
  ```tsx
25
26
  import { createFileRoute } from '@tanstack/react-router'
26
- import { defineVisibility, guardRoute } from '@softr/sdk'
27
+ import { definePage, guardRoute, pageHead } from '@softr/sdk'
27
28
 
28
- const visibility = defineVisibility({ userGroupTypes: ['LOGGED_IN_USERS'] })
29
+ const pageSettings = definePage({
30
+ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] },
31
+ title: 'Billing',
32
+ })
29
33
 
30
34
  export const Route = createFileRoute('/_app/billing')({
31
- beforeLoad: guardRoute(visibility),
35
+ beforeLoad: guardRoute(pageSettings),
36
+ head: pageHead(pageSettings),
32
37
  component: Billing,
33
38
  })
34
39
 
@@ -37,30 +42,31 @@ function Billing() {
37
42
  }
38
43
  ```
39
44
 
40
- The route's rule is one `defineVisibility` call at module scope, with an inline object literal as its argument.
45
+ The route's settings are one `definePage` call at module scope, with an inline object literal as its argument. It always states `visibility`, and a page states its `title` too. `beforeLoad` applies the visibility, and `head` renders the title and the SEO tags.
41
46
 
42
- Four constraints on that shape, because Softr reads the file rather than running it:
47
+ These constraints hold, because Softr reads the file rather than running it:
43
48
 
44
49
  - The call must initialise a top-level `const`.
45
50
  - The import must be a direct named import from `@softr/sdk`.
46
- - The route guards itself in `beforeLoad`, naming a rule declared in the same file. A rule imported from elsewhere is rejected.
47
- - Every value inside the literal is written there too. A group id taken from a `const`, a spread or an import is rejected, even when two routes share it: repeat the id on each.
48
- - Never declare on `__root.tsx`. The root cannot carry an audience, so a declaration there would gate nothing while looking like it does. Softr rejects it. Put the rule on a layout below the root instead.
51
+ - A route file has one `definePage`. The route names it in `beforeLoad` and in `head`. A page imported from elsewhere is rejected.
52
+ - Every value inside the literal is written there too. A group id taken from a `const`, a spread or an import still type-checks, but Studio can no longer change that setting. Repeat the id on each route, even when two routes share it.
53
+ - A head setting that depends on the route's data is a function of its head context: `title: ({ loaderData }) => loaderData?.name`.
54
+ - Never state `visibility` on `__root.tsx`. The root cannot carry an audience, so a rule there would gate nothing while looking like it does. Its `definePage` holds the app-wide head defaults only. Put the rule on a layout below the root instead.
49
55
 
50
56
  `userGroupTypes` is a set, so a rule names one audience or several:
51
57
 
52
58
  ```ts
53
- defineVisibility({ userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] }) // everyone, signed in or not
54
- defineVisibility({ userGroupTypes: ['NON_LOGGED_IN_USERS'] }) // signed-out only: login, signup
55
- defineVisibility({ userGroupTypes: ['LOGGED_IN_USERS'] }) // any signed-in visitor
56
- defineVisibility({ // those groups only
59
+ visibility: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] } // everyone, signed in or not
60
+ visibility: { userGroupTypes: ['NON_LOGGED_IN_USERS'] } // signed-out only: login, signup
61
+ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] } // any signed-in visitor
62
+ visibility: { // those groups only
57
63
  userGroupTypes: ['LOGGED_IN_USERS'],
58
64
  customGroups: ['00000000-0000-0000-0000-00000000000a'],
59
- })
60
- defineVisibility({ // signed-out visitors AND those groups
65
+ }
66
+ visibility: { // signed-out visitors AND those groups
61
67
  userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'],
62
68
  customGroups: ['00000000-0000-0000-0000-00000000000a'],
63
- })
69
+ }
64
70
  ```
65
71
 
66
72
  Everyone is both audiences, as in the first line above. A set names each audience at most once and is never empty — the type and the build both reject one that does not. `customGroups` never stands alone: it narrows the `LOGGED_IN_USERS` half of the set, so the rule still names that half, and one without `userGroupTypes` is a type error. Absent or empty it means **any** signed-in visitor, not "nobody".
@@ -74,17 +80,20 @@ Take every id in `customGroups` from `docs/user-groups.md`, which lists each gro
74
80
  ```tsx
75
81
  // src/routes/_app.tsx: guards every route under /_app
76
82
  import { Outlet, createFileRoute } from '@tanstack/react-router'
77
- import { defineVisibility, guardRoute } from '@softr/sdk'
83
+ import { definePage, guardRoute, pageHead } from '@softr/sdk'
78
84
 
79
- const visibility = defineVisibility({ userGroupTypes: ['LOGGED_IN_USERS'] })
85
+ const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] } })
80
86
 
81
87
  export const Route = createFileRoute('/_app')({
82
- beforeLoad: guardRoute(visibility),
88
+ beforeLoad: guardRoute(pageSettings),
89
+ head: pageHead(pageSettings),
83
90
  component: () => <Outlet />,
84
91
  })
85
92
  ```
86
93
 
87
- The whole match chain runs, so a layout guards everything beneath it. Sibling routes do not guard each other. `/admin/index.tsx` does nothing for `/admin/users.tsx` unless an `admin.tsx` layout exists. A route below a guarded layout declares and guards its own rule too.
94
+ A pathless layout like this one is not a page, so it needs no `title`.
95
+
96
+ The whole match chain runs, so a layout guards everything beneath it. Sibling routes do not guard each other. `/admin/index.tsx` does nothing for `/admin/users.tsx` unless an `admin.tsx` layout exists. A route below a guarded layout declares and guards its own settings too.
88
97
 
89
98
  A thrown error renders in place of the guarded route's component. A shell layout guarded with `LOGGED_IN_USERS`, where `unauthenticated` redirects, sends a signed-out visitor away before anything renders there. A rule that can _throw_ — a `customGroups` rule with `forbidden` set to throw — should not sit on the shell itself, or the error replaces the nav and chrome. Put it on a layout inside the shell, or on the restricted routes, so the error renders inside the chrome.
90
99
 
@@ -93,9 +102,9 @@ A thrown error renders in place of the guarded route's component. A shell layout
93
102
  `guardRoute` takes per-reason overrides as a second argument. A bare string is shorthand for a redirect.
94
103
 
95
104
  ```ts
96
- beforeLoad: guardRoute(visibility, { unauthenticated: '/marketing/sign-up' }),
97
- beforeLoad: guardRoute(visibility, { forbidden: { strategy: 'throw' } }),
98
- beforeLoad: guardRoute(visibility, {
105
+ beforeLoad: guardRoute(pageSettings, { unauthenticated: '/marketing/sign-up' }),
106
+ beforeLoad: guardRoute(pageSettings, { forbidden: { strategy: 'throw' } }),
107
+ beforeLoad: guardRoute(pageSettings, {
99
108
  unauthenticated: { strategy: 'redirect', to: '/marketing/sign-up' },
100
109
  forbidden: { strategy: 'throw' },
101
110
  }),
@@ -142,15 +151,19 @@ That file covers every route at once; a route's own overrides win over it. A rul
142
151
 
143
152
  ```tsx
144
153
  import { createFileRoute } from '@tanstack/react-router'
145
- import { defineVisibility, guardRoute, isAccessError, isForbiddenError } from '@softr/sdk'
154
+ import { definePage, guardRoute, isAccessError, isForbiddenError, pageHead } from '@softr/sdk'
146
155
 
147
- const visibility = defineVisibility({
148
- userGroupTypes: ['LOGGED_IN_USERS'],
149
- customGroups: ['00000000-0000-0000-0000-00000000000a'],
156
+ const pageSettings = definePage({
157
+ visibility: {
158
+ userGroupTypes: ['LOGGED_IN_USERS'],
159
+ customGroups: ['00000000-0000-0000-0000-00000000000a'],
160
+ },
161
+ title: 'Billing',
150
162
  })
151
163
 
152
164
  export const Route = createFileRoute('/_app/billing')({
153
- beforeLoad: guardRoute(visibility),
165
+ beforeLoad: guardRoute(pageSettings),
166
+ head: pageHead(pageSettings),
154
167
  component: Billing,
155
168
  errorComponent: ({ error }: { error: unknown }) => {
156
169
  if (isForbiddenError(error)) return <UpgradePrompt />
@@ -166,25 +179,53 @@ Use the predicates: `isAccessError` for any of the three, and `isUnauthenticated
166
179
 
167
180
  ### Run the check and then keep going
168
181
 
169
- `guardRoute` covers almost everything. When a route needs its own logic afterwards, `assertRouteAccess(visibility, opts)` applies the same rule to the whole `beforeLoad` argument and throws the same access error, using the default behaviour for each reason. It takes no overrides.
182
+ `guardRoute` covers almost everything. When a route needs its own logic afterwards, `assertRouteAccess(pageSettings, opts)` applies the same rule to the whole `beforeLoad` argument and throws the same access error, using the default behaviour for each reason. It takes no overrides.
170
183
 
171
184
  It also narrows `opts.context.user` for the rest of the handler, where the set names one audience and no other: `User` under `['LOGGED_IN_USERS']`, `null` under `['NON_LOGGED_IN_USERS']`. A set naming both admits either kind of visitor, so it narrows to neither. `guardRoute` cannot, because it hands `beforeLoad` a function rather than running inside one.
172
185
 
173
- ```ts
174
- import { redirect } from '@tanstack/react-router'
175
- import { assertRouteAccess } from '@softr/sdk'
186
+ ```tsx
187
+ import { createFileRoute, redirect } from '@tanstack/react-router'
188
+ import { assertRouteAccess, definePage, pageHead } from '@softr/sdk'
189
+
190
+ const pageSettings = definePage({
191
+ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] },
192
+ title: 'Reports',
193
+ })
176
194
 
177
- beforeLoad: (opts) => {
178
- assertRouteAccess(visibility, opts)
179
- if (opts.context.user.email.endsWith('@example.com')) throw redirect({ to: '/internal' })
180
- },
195
+ export const Route = createFileRoute('/_app/reports')({
196
+ beforeLoad: (opts) => {
197
+ assertRouteAccess(pageSettings, opts)
198
+ if (opts.context.user.email.endsWith('@example.com')) throw redirect({ to: '/internal' })
199
+ },
200
+ head: pageHead(pageSettings),
201
+ component: Reports,
202
+ })
181
203
  ```
182
204
 
183
205
  Take `opts` whole. A `context` destructured in the parameter list does not narrow.
184
206
 
185
- Reach for `assertRouteAccess` when the route wants the error thrown for it, `isAuthorized(visibility, context)` when it wants the same narrowing without a throw, and `checkAccess(visibility, context)` when it needs to branch on why. `checkAccess` returns `{ ok: true } | { ok: false, reason }` and throws nothing. All of them are synchronous and make no request.
207
+ `guardRoute` and `assertRouteAccess` throw router redirects, so they belong in a route and nowhere else. That is what `Route` in their names marks.
208
+
209
+ ### Check a rule without a throw
210
+
211
+ `isAuthorized(rule, context)` and `checkAccess(rule, context)` answer the same question and throw nothing, so they work anywhere: in a loader, a component or a server function. They take a rule from `defineVisibility`, not a page. Use `isAuthorized` for the same narrowing of `context.user` as `assertRouteAccess`, and `checkAccess` to branch on why: it returns `{ ok: true } | { ok: false, reason }`. All of them are synchronous and make no request.
212
+
213
+ ```tsx
214
+ import { defineVisibility, isAuthorized, useCurrentUser } from '@softr/sdk'
215
+
216
+ const staffOnly = defineVisibility({
217
+ userGroupTypes: ['LOGGED_IN_USERS'],
218
+ customGroups: ['00000000-0000-0000-0000-00000000000a'],
219
+ })
220
+
221
+ function StaffNote() {
222
+ const context = { user: useCurrentUser() }
223
+ if (!isAuthorized(staffOnly, context)) return null
224
+ return <p>Signed in as staff: {context.user.email}</p>
225
+ }
226
+ ```
186
227
 
187
- `guardRoute` and `assertRouteAccess` throw router redirects, so they belong in a route and nowhere else. That is what `Route` in their names marks. `isAuthorized` and `checkAccess` throw nothing and answer anywhere, in a loader, a component or a server function.
228
+ To show or hide a part of a page, `Audience` is simpler: see [region-visibility/SKILL.md](../region-visibility/SKILL.md).
188
229
 
189
230
  ## References
190
231
 
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.88-signing.0
12
+ library_version: 0.0.88
13
13
  ---
14
14
 
15
15
  **Boundary.** `workflow` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineWorkflow` and every type come from `@softr/sdk` and can be imported anywhere.