@softr/sdk 1.16.0-alpha.2 → 1.16.0-se23079.0

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 (45) hide show
  1. package/CHANGELOG.md +15 -2
  2. package/dist/auth/isomorphic.d.ts +1 -3
  3. package/dist/auth/isomorphic.js +3 -2
  4. package/dist/auth/methods/authenticator.js +7 -1
  5. package/dist/auth/methods/code.d.ts +3 -0
  6. package/dist/auth/methods/code.js +7 -1
  7. package/dist/auth/methods/emailCode2fa.js +4 -1
  8. package/dist/auth/methods/magicLink.js +3 -1
  9. package/dist/auth/methods/password.js +3 -1
  10. package/dist/auth/methods/passwordLink.js +4 -1
  11. package/dist/auth/methods/signup.js +5 -1
  12. package/dist/auth/methods/social.js +3 -1
  13. package/dist/auth/methods/utils.d.ts +3 -1
  14. package/dist/auth/methods/utils.js +22 -1
  15. package/dist/auth/platform.d.ts +0 -1
  16. package/dist/auth/platform.js +1 -14
  17. package/dist/auth/sso.d.ts +1 -24
  18. package/dist/auth/sso.js +9 -79
  19. package/dist/datasource/chart.js +5 -0
  20. package/dist/datasource/record.js +1 -0
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +2 -2
  23. package/dist/mcp.d.ts +2 -2
  24. package/dist/package.js +1 -1
  25. package/dist/route/access-denied-status.js +25 -0
  26. package/dist/route/route.js +15 -3
  27. package/package.json +1 -1
  28. package/skills/softr-sdk/SKILL.md +1 -1
  29. package/skills/softr-sdk/ai/SKILL.md +1 -1
  30. package/skills/softr-sdk/auth/SKILL.md +4 -4
  31. package/skills/softr-sdk/auth/references/single-sign-on.md +0 -25
  32. package/skills/softr-sdk/charts-and-metrics/SKILL.md +3 -1
  33. package/skills/softr-sdk/current-user/SKILL.md +1 -1
  34. package/skills/softr-sdk/email/SKILL.md +1 -1
  35. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  36. package/skills/softr-sdk/formatting/SKILL.md +6 -5
  37. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  38. package/skills/softr-sdk/mcp/SKILL.md +1 -1
  39. package/skills/softr-sdk/push-notifications/SKILL.md +1 -1
  40. package/skills/softr-sdk/pwa/SKILL.md +1 -1
  41. package/skills/softr-sdk/record-mutations/SKILL.md +4 -2
  42. package/skills/softr-sdk/record-queries/SKILL.md +21 -1
  43. package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
  44. package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
  45. package/skills/softr-sdk/workflows/SKILL.md +1 -1
package/CHANGELOG.md CHANGED
@@ -1,10 +1,23 @@
1
1
  # @softr/sdk
2
2
 
3
- ## 1.16.0-alpha.2
3
+ ## 1.16.0
4
4
 
5
5
  ### Minor Changes
6
6
 
7
- - Log in with Softr: workspace members sign in to the app with their Softr account. `softrSignInHref(returnPath?)` gives the link, and `AuthOptions.softr` tells the login page to show the button. A failed Softr login lands on the SSO page with `method=softr`, the login redirect param and an `error`, which is `softr-rejected` (type `SoftrLoginError`) when Softr did not let the account in, or `softr-sso-account` when the account signs in with the single sign-on that the app also offers. Action: on the SSO page, when `method` is `softr`, link "Try again" to `softrSignInHref(toReturnPath(location).href)`.
7
+ - Every `auth` call that signs a visitor in or up fails as `userLimitReached` when the plan of the app's workspace has no room for this user. Before, `auth.signIn` threw, and the other calls answered `invalidCode`, `invalidCredentials`, `invalidDetails` or `linkExpired`. Action: on the login and sign-up pages, give `userLimitReached` its own `case` and say the app has reached its user limit and the app owner can fix it.
8
+ - A sign-in or a sign-up that needs a one-time email code or an authenticator app fails as `notEnabled` when the plan of the app's workspace does not include it, as after a downgrade. For the email code these are `auth.sendSignInCode`, `auth.signInWithCode`, `auth.signUp` and `auth.confirmSignUp` without a password, `auth.verifyEmailCode`, `auth.resendEmailCode`, and `auth.signIn` in an app that asks for an emailed code after the password. For the authenticator app it is every call that signs a visitor in, in an app that asks that visitor for an authenticator step. Before, these calls worked on every plan. Action: on the login and sign-up pages, give `notEnabled` its own `case` and say this way to sign in is not available and the app owner can fix it.
9
+
10
+ ## 1.15.3
11
+
12
+ ### Patch Changes
13
+
14
+ - A `ds.get`, `ds.chart` or `ds.metric` builder reads again after a call such as `where` changes it, the same as `ds.list` and `ds.export`. Before, it answered the result of its first read and left out the new filter. Skills: record-queries and charts-and-metrics say that one builder is for one read, because `where` and `orderBy` add to the builder they are called on. No action is needed.
15
+
16
+ ## 1.15.2
17
+
18
+ ### Patch Changes
19
+
20
+ - A page that a route guard refuses with the `throw` strategy (`guardRoute`, `assertRouteAccess`) answers 403 instead of 500 when `softrAuthMiddleware` is registered, with an `x-softr-access-denied` header that names the reason. The page still shows the route's `errorComponent`. The guard no longer logs the refusal as an error, on the server or in the browser. Without `softrAuthMiddleware`, a refused page still answers 500. No action is needed.
8
21
 
9
22
  ## 1.15.1
10
23
 
@@ -21,7 +21,7 @@ import * as _tanstack_react_start0 from "@tanstack/react-start";
21
21
  * requestMiddleware: [softrAuthMiddleware()],
22
22
  * }))
23
23
  */
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>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
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>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _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
25
  user: User | null;
26
26
  permissions: {
27
27
  datasources: {};
@@ -77,8 +77,6 @@ type AuthOptions = {
77
77
  sso: {
78
78
  type: "SAML" | "OPEN_ID";
79
79
  } | null;
80
- /** Sign-in with a Softr Studio account: a link to `softrSignInHref`. */
81
- softr: boolean;
82
80
  /** `auth.signUp`, then `auth.confirmSignUp` */
83
81
  signUp: boolean;
84
82
  /** The builder asked for strong passwords whenever a visitor sets one. */
@@ -14,6 +14,7 @@ import { pushMiddleware } from "../push.js";
14
14
  import { faviconMiddleware } from "../favicon.js";
15
15
  import { embeddingMiddleware } from "../embedding.js";
16
16
  import { appIdentityMiddleware } from "../app-identity.js";
17
+ import { accessDeniedStatusMiddleware } from "../route/access-denied-status.js";
17
18
  import { getRequestHeader } from "@tanstack/react-start/server";
18
19
  import { createContext, useContext } from "react";
19
20
  import { createMiddleware, createServerFn } from "@tanstack/react-start";
@@ -43,7 +44,8 @@ function softrAuthMiddleware() {
43
44
  pwaMiddleware(),
44
45
  pushMiddleware(),
45
46
  faviconMiddleware(),
46
- ssoMiddleware()
47
+ ssoMiddleware(),
48
+ accessDeniedStatusMiddleware()
47
49
  ]).server(async ({ next }) => {
48
50
  async function getSession() {
49
51
  const token = readSessionToken();
@@ -132,7 +134,6 @@ const getAuthSettings = createServerFn({ method: "GET" }).handler(async () => {
132
134
  magicLink: on("MAGIC_LINK"),
133
135
  google: on("GOOGLE") && clientId ? { clientId } : null,
134
136
  sso: on("SSO") && raw.sso?.type ? { type: raw.sso.type } : null,
135
- softr: raw.loginEnabled && raw.softrLogin === true,
136
137
  signUp: raw.loginEnabled && (raw.signUpPolicy === "OPEN_TO_PUBLIC" || raw.signUpPolicy === "DOMAIN_RESTRICTED"),
137
138
  strongPasswords: on("EMAIL") && (raw.emailAuth?.strongPasswords ?? false)
138
139
  };
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js";
6
- import { authError } from "./utils.js";
6
+ import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/authenticator.ts
9
9
  /**
@@ -42,6 +42,8 @@ async function confirmAuthenticatorSetup(details) {
42
42
  assertCanChange("auth.confirmAuthenticatorSetup");
43
43
  const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupComplete(readPendingAuthToken() ?? readSessionToken(), details.code);
44
44
  if (!result.ok) {
45
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
46
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
45
47
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
46
48
  if (result.status === 429) return authError("tooManyAttempts", result.message);
47
49
  if (result.status >= 500) panic(`Expected authenticator setup to finish, but got ${result.status}: ` + result.message);
@@ -68,6 +70,8 @@ async function skipAuthenticatorSetup() {
68
70
  assertCanChange("auth.skipAuthenticatorSetup");
69
71
  const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupDismiss(readPendingAuthToken() ?? readSessionToken());
70
72
  if (!result.ok) {
73
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
74
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
71
75
  if (result.status === 401) return authError("notAuthenticated", result.message);
72
76
  if (result.status === 429) return authError("tooManyAttempts", result.message);
73
77
  if (result.status >= 500) panic(`Expected to skip authenticator setup, but got ${result.status}: ` + result.message);
@@ -92,6 +96,8 @@ async function verifyAuthenticator(credentials) {
92
96
  assertCanChange("auth.verifyAuthenticator");
93
97
  const result = await makePlatform(sessionConfig().applicationId).authenticatorVerify(readPendingAuthToken() ?? readSessionToken(), "code" in credentials ? { totpCode: credentials.code } : { backupCode: credentials.backupCode });
94
98
  if (!result.ok) {
99
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
100
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
95
101
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
96
102
  if (result.status === 429) return authError("tooManyAttempts", result.message);
97
103
  if (result.status >= 500) panic(`Expected to verify the authenticator, but got ${result.status}: ` + result.message);
@@ -9,6 +9,9 @@ import { AuthError, Result } from "./utils.js";
9
9
  *
10
10
  * An address with no account fails as `noAccount`, and a deactivated one as
11
11
  * `accountDeactivated`, so the visitor is not left waiting for an email.
12
+ *
13
+ * It fails as `notEnabled` when the app's plan no longer includes one-time
14
+ * email codes, as after a downgrade.
12
15
  */
13
16
  declare function sendSignInCode(details: {
14
17
  email: string;
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError } from "./utils.js";
6
+ import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/code.ts
9
9
  const SEND_CODE_ERRORS = new Map([["No account exists for this email.", "noAccount"], ["This account is deactivated. Please contact the application owner.", "accountDeactivated"]]);
@@ -13,11 +13,15 @@ const SEND_CODE_ERRORS = new Map([["No account exists for this email.", "noAccou
13
13
  *
14
14
  * An address with no account fails as `noAccount`, and a deactivated one as
15
15
  * `accountDeactivated`, so the visitor is not left waiting for an email.
16
+ *
17
+ * It fails as `notEnabled` when the app's plan no longer includes one-time
18
+ * email codes, as after a downgrade.
16
19
  */
17
20
  async function sendSignInCode(details) {
18
21
  assertCanChange("auth.sendSignInCode");
19
22
  const result = await makePlatform(sessionConfig().applicationId).sendSignInCode(details.email);
20
23
  if (!result.ok) {
24
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
21
25
  if (result.status === 429) return authError("tooManyAttempts", result.message);
22
26
  if (result.status === 400) return authError(SEND_CODE_ERRORS.get(result.message) ?? "invalidDetails", result.message);
23
27
  if (result.status >= 500) panic(`Expected the sign-in code to be emailed, but got ${result.status}: ` + result.message);
@@ -39,6 +43,8 @@ async function signInWithCode(credentials) {
39
43
  assertCanChange("auth.signInWithCode");
40
44
  const result = await makePlatform(sessionConfig().applicationId).signInWithCode(credentials);
41
45
  if (!result.ok) {
46
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
47
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
42
48
  if (result.status === 429) return authError("tooManyAttempts", result.message);
43
49
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
44
50
  if (result.status >= 500) panic(`Expected sign-in to succeed, but got ${result.status}: ` + result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js";
6
- import { authError } from "./utils.js";
6
+ import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/emailCode2fa.ts
9
9
  /**
@@ -18,6 +18,8 @@ async function verifyEmailCode(details) {
18
18
  assertCanChange("auth.verifyEmailCode");
19
19
  const result = await makePlatform(sessionConfig().applicationId).emailCodeVerify(readPendingAuthToken(), details.code);
20
20
  if (!result.ok) {
21
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
22
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
21
23
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
22
24
  if (result.status === 429) return authError("tooManyAttempts", result.message);
23
25
  if (result.status >= 500) panic(`Expected to verify the emailed code, but got ${result.status}: ` + result.message);
@@ -55,6 +57,7 @@ async function resendEmailCode() {
55
57
  assertCanChange("auth.resendEmailCode");
56
58
  const result = await makePlatform(sessionConfig().applicationId).emailCodeResend(readPendingAuthToken());
57
59
  if (!result.ok) {
60
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
58
61
  if (result.status === 401) return authError("notAuthenticated", result.message);
59
62
  if (result.status === 429) return authError("tooManyAttempts", result.message);
60
63
  if (result.status >= 500) panic(`Expected the code to be emailed again, but got ${result.status}: ` + result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError } from "./utils.js";
6
+ import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/magicLink.ts
9
9
  /**
@@ -18,6 +18,8 @@ async function signInWithMagicLink(credentials) {
18
18
  assertCanChange("auth.signInWithMagicLink");
19
19
  const result = await makePlatform(sessionConfig().applicationId).signInWithMagicLink(credentials);
20
20
  if (!result.ok) {
21
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
22
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
21
23
  if (result.status === 429) return authError("tooManyAttempts", result.message);
22
24
  if (result.status === 400 || result.status === 401) return authError("invalidCredentials", result.message);
23
25
  if (result.status >= 500) panic(`Expected magic-link sign-in to succeed, but got ${result.status}: ` + result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readSessionToken } from "../session.js";
6
- import { authError } from "./utils.js";
6
+ import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/password.ts
9
9
  /**
@@ -18,6 +18,8 @@ async function signIn(credentials) {
18
18
  assertCanChange("auth.signIn");
19
19
  const result = await makePlatform(sessionConfig().applicationId).tokens(credentials);
20
20
  if (!result.ok) {
21
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
22
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
21
23
  if (result.status === 401) return authError("invalidCredentials", result.message);
22
24
  if (result.status === 429) return authError("tooManyAttempts", result.message);
23
25
  if (result.status >= 500) panic(`Expected sign-in to succeed, but got ${result.status}: ` + result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError } from "./utils.js";
6
+ import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/passwordLink.ts
9
9
  /**
@@ -31,6 +31,7 @@ async function requestPasswordReset(details) {
31
31
  async function checkPasswordLink(details) {
32
32
  const result = await makePlatform(sessionConfig().applicationId).checkPasswordToken(details);
33
33
  if (!result.ok) {
34
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
34
35
  if (result.status === 429) return authError("tooManyAttempts", result.message);
35
36
  if (result.status === 400 || result.status === 401) return authError("linkExpired", result.message);
36
37
  panic(`Expected the link to be checked, but got ${result.status}: ${result.message}.`);
@@ -51,6 +52,8 @@ async function setPasswordWithLink(details) {
51
52
  assertCanChange("auth.setPasswordWithLink");
52
53
  const result = await makePlatform(sessionConfig().applicationId).setPassword(details);
53
54
  if (!result.ok) {
55
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
56
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
54
57
  if (result.status === 429) return authError("tooManyAttempts", result.message);
55
58
  if (result.status === 400 && result.message.startsWith("Password must be at least")) return authError("invalidDetails", result.message);
56
59
  if (result.status === 400 || result.status === 401) return authError("linkExpired", result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError } from "./utils.js";
6
+ import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/signup.ts
9
9
  /**
@@ -15,6 +15,8 @@ async function signUp(details) {
15
15
  assertCanChange("auth.signUp");
16
16
  const result = await makePlatform(sessionConfig().applicationId).sendSignUpCode(details);
17
17
  if (!result.ok) {
18
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
19
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
18
20
  if (result.status === 409) return authError("emailTaken", result.message);
19
21
  if (result.status === 429) return authError("tooManyAttempts", result.message);
20
22
  if (result.status === 400) return authError("invalidDetails", result.message);
@@ -48,6 +50,8 @@ async function confirmSignUp(details) {
48
50
  password
49
51
  });
50
52
  if (!result.ok) {
53
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
54
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
51
55
  if (result.status === 409) return authError("emailTaken", result.message);
52
56
  if (result.status === 429) return authError("tooManyAttempts", result.message);
53
57
  if (result.status === 400 && result.message.startsWith("Password must be at least")) return authError("invalidDetails", result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError } from "./utils.js";
6
+ import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
  import { z } from "zod";
8
8
 
9
9
  //#region src/auth/methods/social.ts
@@ -27,6 +27,8 @@ async function signInWithGoogle(credentials) {
27
27
  assertCanChange("auth.signInWithGoogle");
28
28
  const result = await makePlatform(sessionConfig().applicationId).signInWithGoogle(credentials);
29
29
  if (!result.ok) {
30
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
31
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
30
32
  if (result.status === 429) return authError("tooManyAttempts", result.message);
31
33
  const body = errorBodySchema.safeParse(result.body);
32
34
  if (body.success && body.data.code === "GOOGLE_NOT_IN_PLAN") return authError("notEnabled", result.message);
@@ -10,6 +10,8 @@ type AuthError = {
10
10
  code: AuthErrorCode;
11
11
  message: string;
12
12
  };
13
- type AuthErrorCode = "invalidCredentials" | "tooManyAttempts" | "emailTaken" | "invalidDetails" | "invalidCode" | "noAccount" | "accountDeactivated" | "notAuthenticated" | "emailDomainNotAllowed" | "notEnabled" | "linkExpired" | "invalidName" | "invalidPhoto" | "fileTooLarge" | "notAnImage" | "avatarNotSupported";
13
+ type AuthErrorCode = "invalidCredentials" | "tooManyAttempts" | "emailTaken" | "invalidDetails" | "invalidCode" | "noAccount" | "accountDeactivated" | "notAuthenticated" | "emailDomainNotAllowed"
14
+ /** The plan of the app's workspace no longer includes this way to sign in, as after a downgrade. */ | "notEnabled" | "linkExpired" | "invalidName" | "invalidPhoto" | "fileTooLarge" | "notAnImage" | "avatarNotSupported"
15
+ /** Any call that signs a visitor in or up: the plan of the app's workspace has no room for this user. */ | "userLimitReached";
14
16
  //#endregion
15
17
  export { AuthError, Result };
@@ -1,3 +1,5 @@
1
+ import { z } from "zod";
2
+
1
3
  //#region src/auth/methods/utils.ts
2
4
  function authError(code, message) {
3
5
  return {
@@ -8,6 +10,25 @@ function authError(code, message) {
8
10
  }
9
11
  };
10
12
  }
13
+ const errorBodySchema = z.object({ code: z.string() });
14
+ /**
15
+ * True when Softr refused because the plan of the app's workspace has no room
16
+ * for this user. It arrives as a 400, like a wrong code, so the status cannot
17
+ * tell them apart.
18
+ */
19
+ function isUserLimitReached(result) {
20
+ const body = errorBodySchema.safeParse(result.body);
21
+ return body.success && body.data.code === "USER_LIMIT_REACHED";
22
+ }
23
+ /**
24
+ * True when Softr refused because the plan of the app's workspace does not
25
+ * include the emailed code or the authenticator app this sign-in needs, as
26
+ * after a downgrade.
27
+ */
28
+ function isNotInPlan(result) {
29
+ const body = errorBodySchema.safeParse(result.body);
30
+ return body.success && (body.data.code === "EMAIL_CODE_NOT_IN_PLAN" || body.data.code === "AUTHENTICATOR_NOT_IN_PLAN");
31
+ }
11
32
 
12
33
  //#endregion
13
- export { authError };
34
+ export { authError, isNotInPlan, isUserLimitReached };
@@ -39,7 +39,6 @@ declare const authSettingsSchema: z.ZodObject<{
39
39
  OPEN_ID: "OPEN_ID";
40
40
  }>>;
41
41
  }, z.core.$strip>>;
42
- softrLogin: z.ZodOptional<z.ZodBoolean>;
43
42
  }, z.core.$strip>;
44
43
  type AuthSettings = z.infer<typeof authSettingsSchema>;
45
44
  //#endregion
@@ -29,8 +29,7 @@ const authSettingsSchema = z.object({
29
29
  clientId: z.string().nullable(),
30
30
  userType: z.enum(["INTERNAL", "EXTERNAL"]).nullable()
31
31
  }).nullable(),
32
- sso: z.object({ type: z.enum(["SAML", "OPEN_ID"]).nullable() }).nullable(),
33
- softrLogin: z.boolean().optional()
32
+ sso: z.object({ type: z.enum(["SAML", "OPEN_ID"]).nullable() }).nullable()
34
33
  });
35
34
  function makePlatform(applicationId) {
36
35
  const aliases = Object.entries(softrConfig().user?.properties ?? {});
@@ -217,18 +216,6 @@ function makePlatform(applicationId) {
217
216
  method: "POST",
218
217
  json: body
219
218
  }, ssoSignInSchema),
220
- softrLoginStart: (body) => request(`/v1/vibe/applications/${applicationId}/users/softr-login/start`, {
221
- method: "POST",
222
- json: body
223
- }, z.object({
224
- bindingToken: z.string(),
225
- returnPath: z.string(),
226
- redirectUrl: z.string()
227
- })),
228
- signInWithSoftr: (body) => request(`/v1/vibe/applications/${applicationId}/users/tokens/with-softr${withAttributes}`, {
229
- method: "POST",
230
- json: body
231
- }, ssoSignInSchema),
232
219
  ssoDiscover: (body) => request(`/v1/vibe/applications/${applicationId}/users/sso/discover`, {
233
220
  method: "POST",
234
221
  json: body
@@ -14,34 +14,11 @@ import "@tanstack/react-start";
14
14
  * <a href={ssoSignInHref(toReturnPath(location).href)}>Continue with SSO</a>
15
15
  */
16
16
  declare function ssoSignInHref(returnPath?: string): string;
17
- /**
18
- * Where a link or button sends a visitor to sign in with their Softr Studio
19
- * account. They come back to `returnPath` once signed in. Without one, they
20
- * land where `auth.guard.alreadyAuthenticated` in softr.json points, as after
21
- * any sign-in.
22
- *
23
- * A full page load, not a router navigation: the visitor leaves the app for
24
- * Softr Studio.
25
- *
26
- * @example
27
- * <a href={softrSignInHref(toReturnPath(location).href)}>Continue with Softr</a>
28
- */
29
- declare function softrSignInHref(returnPath?: string): string;
30
17
  /**
31
18
  * Why single sign-on did not finish, as the `error` search param of the SSO
32
19
  * page. Never the platform's own message: that is for the builder, and it would
33
20
  * sit in the visitor's address bar.
34
21
  */
35
22
  type SsoError = "host" | "idp" | "not-enabled" | "sign-up-disabled" | "restricted" | "expired" | "failed";
36
- /**
37
- * The extra reasons a sign-in with a Softr Studio account can fail, besides
38
- * the {@link SsoError} values. `softr-rejected`: Softr did not let this
39
- * account in. `softr-sso-account`: the account signs in with single sign-on,
40
- * which the app also offers. It is a separate type so that an existing
41
- * `Record<SsoError, ...>` keeps compiling.
42
- *
43
- * The SSO page gets it as its `error` search param, with `method=softr`.
44
- */
45
- type SoftrLoginError = "softr-rejected" | "softr-sso-account";
46
23
  //#endregion
47
- export { SoftrLoginError, SsoError, softrSignInHref, ssoSignInHref };
24
+ export { SsoError, ssoSignInHref };
package/dist/auth/sso.js CHANGED
@@ -11,8 +11,6 @@ import { createMiddleware } from "@tanstack/react-start";
11
11
 
12
12
  //#region src/auth/sso.ts
13
13
  const START_PATH = "/_softr/sso/start";
14
- const SOFTR_START_PATH = "/_softr/softr-login/start";
15
- const SOFTR_CALLBACK_PATH = "/_softr/softr-login/callback";
16
14
  const OPEN_ID_CALLBACK_PATH = "/open-id/code";
17
15
  const SAML_CALLBACK_PATH = "/saml/SSO";
18
16
  const DEFAULT_SSO_PATH = "/sso-authentication";
@@ -31,28 +29,12 @@ function ssoSignInHref(returnPath) {
31
29
  return returnPath ? `${START_PATH}?return=${encodeURIComponent(returnPath)}` : START_PATH;
32
30
  }
33
31
  /**
34
- * Where a link or button sends a visitor to sign in with their Softr Studio
35
- * account. They come back to `returnPath` once signed in. Without one, they
36
- * land where `auth.guard.alreadyAuthenticated` in softr.json points, as after
37
- * any sign-in.
38
- *
39
- * A full page load, not a router navigation: the visitor leaves the app for
40
- * Softr Studio.
41
- *
42
- * @example
43
- * <a href={softrSignInHref(toReturnPath(location).href)}>Continue with Softr</a>
44
- */
45
- function softrSignInHref(returnPath) {
46
- return returnPath ? `${SOFTR_START_PATH}?return=${encodeURIComponent(returnPath)}` : SOFTR_START_PATH;
47
- }
48
- /**
49
32
  * Starts single sign-on and finishes it when the identity provider answers.
50
- * It does the same for a sign-in with a Softr Studio account, where Studio is
51
- * the identity provider. Every other request passes through.
33
+ * Every other request passes through.
52
34
  *
53
35
  * The start is a GET the visitor's browser makes, so a link can begin it. The
54
36
  * identity provider answers OpenID Connect with a redirect, and SAML with a
55
- * form it posts from its own site. Studio answers with a redirect.
37
+ * form it posts from its own site.
56
38
  */
57
39
  function ssoMiddleware() {
58
40
  return createMiddleware({ type: "request" }).server(async ({ next, request, pathname }) => {
@@ -77,30 +59,6 @@ function ssoMiddleware() {
77
59
  ...binding
78
60
  }), binding.returnPath);
79
61
  }
80
- case SOFTR_START_PATH:
81
- if (request.method !== "GET") return methodNotAllowed("GET");
82
- return await softrStart(new URL(request.url));
83
- case SOFTR_CALLBACK_PATH: {
84
- if (request.method !== "GET") return methodNotAllowed("GET");
85
- const url = new URL(request.url);
86
- const code = url.searchParams.get("code");
87
- const binding = readSsoBinding();
88
- clearSsoBinding();
89
- if (code === null) return toSsoPage({
90
- error: "failed",
91
- returnPath: binding?.returnPath,
92
- method: "softr"
93
- });
94
- if (binding === null) return toSsoPage({
95
- error: "expired",
96
- method: "softr"
97
- });
98
- return await finish(await platform().signInWithSoftr({
99
- code,
100
- state: url.searchParams.get("state") ?? "",
101
- ...binding
102
- }), binding.returnPath, "softr");
103
- }
104
62
  case SAML_CALLBACK_PATH: {
105
63
  if (request.method !== "POST") return methodNotAllowed("POST");
106
64
  const form = await request.formData().catch(() => null);
@@ -153,39 +111,14 @@ async function start(url) {
153
111
  writeCookies([binding]);
154
112
  return samlForm(started.formAction, started.samlRequest, started.relayState);
155
113
  }
156
- async function softrStart(url) {
157
- const returnPath = resolveReturnPath(url.searchParams.get("return"));
158
- const result = await platform().softrLoginStart({
159
- origin: url.origin,
160
- returnPath
161
- });
162
- if (!result.ok) return toSsoPage({
163
- ...failure(result),
164
- returnPath,
165
- method: "softr"
166
- });
167
- const started = result.data;
168
- writeCookies([makeSsoBindingCookie({
169
- bindingToken: started.bindingToken,
170
- returnPath: started.returnPath
171
- })]);
172
- return new Response(null, {
173
- status: 302,
174
- headers: {
175
- location: started.redirectUrl,
176
- "cache-control": "no-store"
177
- }
178
- });
179
- }
180
114
  /**
181
115
  * `startedFor` is where the visitor wanted to go, so a retry after a failure
182
116
  * gets there.
183
117
  */
184
- async function finish(result, startedFor, method = "sso") {
118
+ async function finish(result, startedFor) {
185
119
  if (!result.ok) return toSsoPage({
186
120
  ...failure(result),
187
- returnPath: startedFor,
188
- method
121
+ returnPath: startedFor
189
122
  });
190
123
  const { result: signIn, returnPath } = result.data;
191
124
  if (signIn.status === "MFA_REQUIRED") {
@@ -212,13 +145,12 @@ function failure(result) {
212
145
  case "SSO_IDP_REJECTED": return { error: "idp" };
213
146
  case "SSO_NOT_ENABLED":
214
147
  case "SSO_NOT_IN_PLAN":
215
- case "SSO_MISCONFIGURED": return { error: "not-enabled" };
148
+ case "SSO_MISCONFIGURED":
149
+ case "AUTHENTICATOR_NOT_IN_PLAN": return { error: "not-enabled" };
216
150
  case "SSO_SIGN_UP_DISABLED": return { error: "sign-up-disabled" };
217
151
  case "USER_DEACTIVATED":
218
152
  case "SIGN_IN_RESTRICTED": return { error: "restricted" };
219
153
  case "SSO_BINDING_INVALID": return { error: "expired" };
220
- case "SOFTR_LOGIN_REJECTED": return { error: "softr-rejected" };
221
- case "SOFTR_LOGIN_SSO_ACCOUNT": return { error: "softr-sso-account" };
222
154
  default:
223
155
  logger.warn(`Single sign-on failed with ${result.status} ${code ?? "(no code)"}: ${result.message}`);
224
156
  return { error: "failed" };
@@ -233,10 +165,8 @@ function failure(result) {
233
165
  function toSsoPage(search) {
234
166
  const { routes } = softrConfig().auth;
235
167
  const params = new URLSearchParams();
236
- if ("error" in search) {
237
- params.set("error", search.error);
238
- if (search.method === "softr") params.set("method", "softr");
239
- } else params.set("authenticator", search.authenticator);
168
+ if ("error" in search) params.set("error", search.error);
169
+ else params.set("authenticator", search.authenticator);
240
170
  if (search.returnPath !== void 0) params.set(routes.login.redirectParam, resolveReturnPath(search.returnPath));
241
171
  return seeOther(`${routes.sso?.path ?? DEFAULT_SSO_PATH}?${params}`);
242
172
  }
@@ -288,4 +218,4 @@ function platform() {
288
218
  }
289
219
 
290
220
  //#endregion
291
- export { softrSignInHref, ssoMiddleware, ssoSignInHref };
221
+ export { ssoMiddleware, ssoSignInHref };
@@ -100,6 +100,7 @@ function chart(query) {
100
100
  const groups = entries;
101
101
  assert(groups.length < 2 || groups[0][1].fieldId !== groups[1][1].fieldId, "a chart may group by a field only once");
102
102
  state.groups = groups;
103
+ result = void 0;
103
104
  return builder;
104
105
  },
105
106
  metrics(build) {
@@ -114,15 +115,18 @@ function chart(query) {
114
115
  seen.add(pair);
115
116
  }
116
117
  state.metrics = metrics;
118
+ result = void 0;
117
119
  return builder;
118
120
  },
119
121
  where(build) {
120
122
  state.filters.push(build(makeFieldSet(aliases)));
123
+ result = void 0;
121
124
  return builder;
122
125
  },
123
126
  orderBy(build) {
124
127
  const sorting = build(makeSortSet([...state.groups ?? [], ...state.metrics ?? []].map(([key]) => key)));
125
128
  state.orderBys.push(...buildOrderBy(Array.isArray(sorting) ? sorting : [sorting]));
129
+ result = void 0;
126
130
  return builder;
127
131
  },
128
132
  then(onfulfilled, onrejected) {
@@ -238,6 +242,7 @@ function metric(query, pick) {
238
242
  [Symbol.toStringTag]: "MetricQuery",
239
243
  where(build) {
240
244
  filters.push(build(makeFieldSet(aliases)));
245
+ result = void 0;
241
246
  return builder;
242
247
  },
243
248
  then(onfulfilled, onrejected) {
@@ -228,6 +228,7 @@ function getRecord(query, options) {
228
228
  [Symbol.toStringTag]: "RecordFetch",
229
229
  where(build) {
230
230
  filters.push(build(makeFieldSet(aliases)));
231
+ record = void 0;
231
232
  return builder;
232
233
  },
233
234
  then(onfulfilled, onrejected) {
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ import { checkAccess, defineVisibility, isAuthorized } from "./route/visibility.
11
11
  import { Page, PageSettings, definePage, pageHead } from "./route/page.js";
12
12
  import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./route/route.js";
13
13
  import { toReturnPath } from "./auth/returnPath.js";
14
- import { SoftrLoginError, SsoError, softrSignInHref, ssoSignInHref } from "./auth/sso.js";
14
+ import { SsoError, ssoSignInHref } from "./auth/sso.js";
15
15
  import { AuthOptions, AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
16
16
  import { useIdleTimeout } from "./auth/idle-timeout.js";
17
17
  import { Tool, ToolDefinition, defineTool } from "./tool.js";
@@ -25,4 +25,4 @@ import { DefaultErrorOverlay } from "./default-error-overlay.js";
25
25
  import { Audience } from "./route/audience.js";
26
26
  import { Logo, LogoFile } from "./softr-config.schema.js";
27
27
  import { getLogo } from "./softr-config.js";
28
- export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type EmailErrorCode, type EmailSendInit, type EmailSent, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Logo, type LogoFile, type Page, type PageSettings, type PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, type SoftrLoginError, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type Tool, type ToolDefinition, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, softrSignInHref, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
28
+ export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type EmailErrorCode, type EmailSendInit, type EmailSent, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Logo, type LogoFile, type Page, type PageSettings, type PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type Tool, type ToolDefinition, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { checkAccess, defineVisibility, isAuthorized } from "./route/visibility.
5
5
  import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./route/route.js";
6
6
  import { definePage, pageHead } from "./route/page.js";
7
7
  import { toReturnPath } from "./auth/returnPath.js";
8
- import { softrSignInHref, ssoSignInHref } from "./auth/sso.js";
8
+ import { ssoSignInHref } from "./auth/sso.js";
9
9
  import { FormattedDate, FormattingScope, formatDate, formatDateTime, formatNumber, useFormatting } from "./formatting.js";
10
10
  import { SoftrPwaHead, usePwaInstall } from "./pwa.js";
11
11
  import { usePushNotifications } from "./push.js";
@@ -19,4 +19,4 @@ import { useUserTimezone } from "./timezone.js";
19
19
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
20
20
  import { Audience } from "./route/audience.js";
21
21
 
22
- export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, softrSignInHref, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
22
+ export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
package/dist/mcp.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { DatasourceAction } from "./action.js";
2
2
  import { Tool } from "./tool.js";
3
- import * as _tanstack_react_start10 from "@tanstack/react-start";
3
+ import * as _tanstack_react_start11 from "@tanstack/react-start";
4
4
 
5
5
  //#region src/mcp.d.ts
6
6
 
@@ -38,6 +38,6 @@ type SoftrMcpOptions = {
38
38
  * ],
39
39
  * }))
40
40
  */
41
- declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start10.RequestMiddlewareAfterServer<{}, undefined, undefined>;
41
+ declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start11.RequestMiddlewareAfterServer<{}, undefined, undefined>;
42
42
  //#endregion
43
43
  export { softrMcpMiddleware };
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.16.0-alpha.2";
2
+ var version = "1.16.0-se23079.0";
3
3
 
4
4
  //#endregion
5
5
  export { version };
@@ -0,0 +1,25 @@
1
+ import { ACCESS_DENIED_HEADER } from "./route.js";
2
+ import { getResponseHeader } from "@tanstack/react-start/server";
3
+ import { createMiddleware } from "@tanstack/react-start";
4
+
5
+ //#region src/route/access-denied-status.ts
6
+ /**
7
+ * Answers 403 for a page a guard refused by throwing, with the guard's mark.
8
+ * TanStack answers any thrown value with 500, which reads as a server error.
9
+ */
10
+ function accessDeniedStatusMiddleware() {
11
+ return createMiddleware({ type: "request" }).server(async ({ next }) => {
12
+ const result = await next();
13
+ const reason = getResponseHeader(ACCESS_DENIED_HEADER);
14
+ if (result.response.status !== 500 || reason === void 0) return result;
15
+ const headers = new Headers(result.response.headers);
16
+ headers.set(ACCESS_DENIED_HEADER, reason);
17
+ return new Response(result.response.body, {
18
+ status: 403,
19
+ headers
20
+ });
21
+ });
22
+ }
23
+
24
+ //#endregion
25
+ export { accessDeniedStatusMiddleware };
@@ -1,10 +1,22 @@
1
1
  import { panic } from "../assertions.js";
2
- import { logger } from "../logger.js";
3
2
  import { softrConfig } from "../softr-config.js";
4
3
  import { ACCESS_REASONS, checkRule } from "./visibility.js";
4
+ import { setResponseHeader } from "@tanstack/react-start/server";
5
+ import { createIsomorphicFn } from "@tanstack/react-start";
5
6
  import { redirect } from "@tanstack/react-router";
6
7
 
7
8
  //#region src/route/route.ts
9
+ /**
10
+ * Marks the answer of a page a guard refused by throwing, with the reason as its
11
+ * value. The pod reads it to tell a refusal from a server error, so its name and
12
+ * values stay as they are.
13
+ */
14
+ const ACCESS_DENIED_HEADER = "x-softr-access-denied";
15
+ const markRefused = createIsomorphicFn().server((reason) => {
16
+ try {
17
+ setResponseHeader(ACCESS_DENIED_HEADER, reason);
18
+ } catch {}
19
+ });
8
20
  function isAccessReason(value) {
9
21
  return ACCESS_REASONS.some((reason) => reason === value);
10
22
  }
@@ -62,7 +74,7 @@ function thrownFor(reason, overrides, location) {
62
74
  type: "access_error",
63
75
  reason
64
76
  };
65
- logger.error(/* @__PURE__ */ new Error(`Access to ${location.href} denied: ${ACCESS_DENIED_MESSAGES[reason]}`));
77
+ markRefused(reason);
66
78
  return error;
67
79
  }
68
80
  function ruleOf(page) {
@@ -104,4 +116,4 @@ function assertRouteAccess(page, opts) {
104
116
  }
105
117
 
106
118
  //#endregion
107
- export { ACCESS_DENIED_MESSAGES, assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError };
119
+ export { ACCESS_DENIED_HEADER, ACCESS_DENIED_MESSAGES, assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "1.16.0-alpha.2",
3
+ "version": "1.16.0-se23079.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -11,7 +11,7 @@ description: >-
11
11
  metadata:
12
12
  type: core
13
13
  library: softr-sdk
14
- library_version: 1.16.0-alpha.2
14
+ library_version: 1.16.0
15
15
  ---
16
16
 
17
17
  # Softr SDK core
@@ -13,7 +13,7 @@ description: >-
13
13
  metadata:
14
14
  type: sub-skill
15
15
  library: softr-sdk
16
- library_version: 1.16.0-alpha.2
16
+ library_version: 1.16.0
17
17
  ---
18
18
 
19
19
  **Boundary.** `ai` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineAiAction` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.16.0-alpha.2
13
+ library_version: 1.16.0
14
14
  ---
15
15
 
16
16
  **Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
@@ -134,10 +134,11 @@ type AuthErrorCode =
134
134
  | 'notAuthenticated' // a call that needs a signed-in visitor, made by one who is not
135
135
  | 'emailDomainNotAllowed' // signUp, signInWithGoogle: the app lets only some email domains sign up, and this is not one
136
136
  | 'linkExpired' // checkPasswordLink, setPasswordWithLink: the link is used, expired or no longer valid
137
- | 'notEnabled' // signInWithGoogle: the app's plan no longer includes Google sign-in
137
+ | 'notEnabled' // any call that signs a visitor in or up, or emails a code: the app's plan no longer includes Google sign-in, emailed codes or the authenticator app
138
+ | 'userLimitReached' // any call that signs a visitor in or up: the plan of the app's workspace has no room for this user
138
139
  ```
139
140
 
140
- Branch on `error.code` with a `switch` and write your own wording. Never put `error.message` in front of the visitor. The one exception is `invalidDetails` from `setPasswordWithLink` and `confirmSignUp`. Show its message: it names the password rule that failed.
141
+ Branch on `error.code` with a `switch` and write your own wording. Never put `error.message` in front of the visitor. The one exception is `invalidDetails` from `setPasswordWithLink` and `confirmSignUp`. Show its message: it names the password rule that failed. On `userLimitReached` the visitor did nothing wrong, and a retry does not help. Say the app has reached its user limit and that the app owner can fix it. Give it its own `case` on the login and sign-up pages, so it does not fall to a "wrong password" or "wrong code" message.
141
142
 
142
143
  `code` is typed as every code the SDK produces, not the ones a given call can answer, so a `switch` needs a `default` even when the cases above it are complete. Give it a message rather than leaving it out.
143
144
 
@@ -176,7 +177,6 @@ Each field names the `auth` call it unlocks:
176
177
  | `emailCode` | sign-in with a code, `auth.sendSignInCode` |
177
178
  | `magicLink` | the route that calls `auth.signInWithMagicLink` |
178
179
  | `google` | a Google button started with `google.clientId`. `null` means no Google. Never hardcode a client id. |
179
- | `softr` | a "Continue with Softr" link to `softrSignInHref(...)`, for people who sign in with their Softr Studio account. See [references/single-sign-on.md](./references/single-sign-on.md#log-in-with-softr) |
180
180
  | `signUp` | sign-up, `auth.signUp` |
181
181
  | `strongPasswords` | the strong-password rules, on every form that sets a new password. Check the password against them before submitting. |
182
182
 
@@ -26,7 +26,6 @@ When single sign-on needs more from the visitor, or fails, they come back to the
26
26
  | --- | --- | --- |
27
27
  | `authenticator` | `'verify'`, `'setup'` or `'setupOptional'`: the app asks for an authenticator app as well | the second-factor step, as for `authenticatorRequired` and its `step`. Finish with the same calls, then `toReturnPath(location)` |
28
28
  | `error` | why it did not finish, one of the codes below | a message, a "Try again" link to `ssoSignInHref(toReturnPath(location).href)`, and a link to the login page that keeps the redirect param, so either way the visitor ends where they wanted |
29
- | `method` | `'softr'` when [log in with Softr](#log-in-with-softr) failed, absent for single sign-on | the "Try again" link goes to `softrSignInHref(toReturnPath(location).href)` instead |
30
29
 
31
30
  | `error` | Means |
32
31
  | --- | --- |
@@ -37,8 +36,6 @@ When single sign-on needs more from the visitor, or fails, they come back to the
37
36
  | `restricted` | The account is deactivated, or the app has no room for another user |
38
37
  | `expired` | It took too long, another tab started a newer sign-in, or the sign-in started at the identity provider rather than in the app |
39
38
  | `failed` | Anything else |
40
- | `softr-rejected` | Log in with Softr only: Softr did not let this account in |
41
- | `softr-sso-account` | Log in with Softr only: this account signs in with single sign-on. Link to `ssoSignInHref(toReturnPath(location).href)` |
42
39
 
43
40
  With neither param, redirect to `toReturnPath(location)`.
44
41
 
@@ -51,25 +48,3 @@ Three ways to put it on the login page. Build the one the builder asks for:
51
48
  1. **A button**, as above, next to the other methods. The default.
52
49
  2. **Email first.** Ask for the email, then call `auth.discoverSso({ email })` from a server function. It answers a `Result` of `{ sso: boolean }`, decided by the email's domain alone, and fails only with `tooManyAttempts`. On `sso: true` send the visitor to `ssoSignInHref(...)` with `window.location.assign`, otherwise carry on with the password or code step. Never hardcode the domains: the builder changes them in Softr, and the app would not follow.
53
50
  3. **Straight to the identity provider** when single sign-on is the only method: send the visitor to `ssoSignInHref(...)` as the login page loads. Skip it when the login page has a `signedOut` search param, or the visitor is signed straight back in after signing out, since the identity provider still knows them. The sign-out server function adds it: `throw redirect({ to: '/login', search: { signedOut: true } })`, and so does the login link on the single sign-on page, or an error there sends the visitor to the identity provider and back to the same error. Keep the button on the page for that case.
54
-
55
- ## Log in with Softr
56
-
57
- People in the audience the builder chose in Softr sign in with their Softr Studio account. Softr Studio is their identity provider, so it works like single sign-on: a link starts it, and there is no server function to write.
58
-
59
- ```tsx
60
- import { useLocation } from '@tanstack/react-router'
61
- import { softrSignInHref, toReturnPath, useAuthSettings } from '@softr/sdk'
62
-
63
- const options = useAuthSettings()
64
- const location = useLocation()
65
-
66
- {options.softr ? (
67
- <Button nativeButton={false} render={<a href={softrSignInHref(toReturnPath(location).href)} />}>
68
- Continue with Softr
69
- </Button>
70
- ) : null}
71
- ```
72
-
73
- The same rules as `ssoSignInHref` apply: a plain `<a href>`, a return path on this app, or none. It comes back to the same page as single sign-on, with `method=softr` next to `error`, and with the same `authenticator` step. The other codes above can also come with `method=softr`, so name the method from `method`, not "single sign-on". Show `softr-rejected` as "you do not have access to this app", and offer no "Try again": only the app owner can change it.
74
-
75
- An app whose only way in is log in with Softr still has a login page, with the button on it. Do not send visitors to Softr as the page loads.
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.16.0-alpha.2
13
+ library_version: 1.16.0
14
14
  ---
15
15
 
16
16
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A helper that calls `ds` outside a handler goes in `createServerOnlyFn` from `@tanstack/react-start` (the `record-queries` boundary). `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -195,6 +195,8 @@ A chart can group, aggregate and `where` only on `fields`, not on `filterFields`
195
195
 
196
196
  `groupBy` comes first and exactly once; a chart cannot be awaited before it. `metrics` follows, at most once, or not at all for distinct values. `where` can be chained anywhere, repeatedly, and calling it more than once ands the filters together. `orderBy` sorts by the chart's own keys, group and metric alike, and only sees the keys declared so far, so call it last.
197
197
 
198
+ A builder is for one read. `where` adds to the builder it is called on, so a `ds.chart` or `ds.metric` kept in a variable and read again carries the filters of the earlier read. Start each figure from its own `ds.chart` or `ds.metric`, as the dashboard load above does.
199
+
198
200
  ## References
199
201
 
200
202
  - [references/aggregations.md](./references/aggregations.md): every bucket interval and its value type, and which aggregations each kind of field offers. Load it when choosing a bucket or when a field does not offer the aggregation you expected.
@@ -11,7 +11,7 @@ description: >-
11
11
  metadata:
12
12
  type: sub-skill
13
13
  library: softr-sdk
14
- library_version: 1.16.0-alpha.2
14
+ library_version: 1.16.0
15
15
  ---
16
16
 
17
17
  # The current user
@@ -12,7 +12,7 @@ description: >-
12
12
  metadata:
13
13
  type: sub-skill
14
14
  library: softr-sdk
15
- library_version: 1.16.0-alpha.2
15
+ library_version: 1.16.0
16
16
  ---
17
17
 
18
18
  **Boundary.** `email` and `EmailError` live on `@softr/sdk/server` and run only inside a `createServerFn` handler — importing them into a component fails the build. `defineEmailAction` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 1.16.0-alpha.2
10
+ library_version: 1.16.0
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: 1.16.0-alpha.2
11
+ library_version: 1.16.0
12
12
  ---
13
13
 
14
14
  # Dates, times and numbers
@@ -93,7 +93,7 @@ For a page or an area, wrap it in `FormattingScope`. Every `FormattedDate` and `
93
93
  For one value, pass `timeZone`. It wins over a scope. Use it for an event that shows in its own zone, from a record field or a DATETIME field whose `options` in the datasource schema name a `timezone` and a `timezoneType` other than `LOCAL`.
94
94
 
95
95
  ```tsx
96
- <FormattedDate value={event.fields.starts} time timeZone={event.fields.zone} />
96
+ <FormattedDate value={event.fields.starts} time timeZone={event.fields.zone ?? undefined} />
97
97
  ```
98
98
 
99
99
  Say which zone a fixed-zone time is in, so a visitor elsewhere does not read it as theirs: add `timeZoneName: 'short'` to `parts`, or write the zone next to it. An unknown zone or locale is ignored with a warning, so a bad record never breaks the page.
@@ -108,7 +108,7 @@ function BugRow({ bug }: { bug: Bug }) {
108
108
  return (
109
109
  <li title={`Created ${formatDateTime(bug.fields.created, formatting)}`}>
110
110
  {bug.fields.title}
111
- <span>{formatNumber(bug.fields.votes, formatting)}</span>
111
+ <span>{bug.fields.votes === null ? '—' : formatNumber(bug.fields.votes, formatting)}</span>
112
112
  <FormattedDate value={bug.fields.created} dateStyle="medium" />
113
113
  </li>
114
114
  )
@@ -166,10 +166,11 @@ For a shape the helpers do not give, such as a range (`Oct 6 – 8`), use `Intl`
166
166
 
167
167
  ```tsx
168
168
  const formatting = useFormatting()
169
- const range = formatting.timeZone === null
169
+ const { starts, ends } = trip.fields
170
+ const range = formatting.timeZone === null || starts === null || ends === null
170
171
  ? null
171
172
  : new Intl.DateTimeFormat(formatting.dateLocale, { month: 'short', day: 'numeric', timeZone: formatting.timeZone })
172
- .formatRange(new Date(trip.fields.starts), new Date(trip.fields.ends))
173
+ .formatRange(new Date(starts), new Date(ends))
173
174
  ```
174
175
 
175
176
  ### Relative time and now
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 1.16.0-alpha.2
10
+ library_version: 1.16.0
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.
@@ -11,7 +11,7 @@ description: >-
11
11
  metadata:
12
12
  type: sub-skill
13
13
  library: softr-sdk
14
- library_version: 1.16.0-alpha.2
14
+ library_version: 1.16.0
15
15
  ---
16
16
 
17
17
  **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. The tools you hand it come from `defineTool`, also on `@softr/sdk`, and call the same server logic the pages do.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.16.0-alpha.2
12
+ library_version: 1.16.0
13
13
  ---
14
14
 
15
15
  # Push notifications
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.16.0-alpha.2
13
+ library_version: 1.16.0
14
14
  ---
15
15
 
16
16
  # Installing the app
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.16.0-alpha.2
13
+ library_version: 1.16.0
14
14
  ---
15
15
 
16
16
  **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.
@@ -202,9 +202,11 @@ const projectDetail = defineQuery({
202
202
  })
203
203
 
204
204
  const project = await ds.get(projectDetail, { id })
205
+ if (project === null) throw notFound()
206
+ const status = project.fields.status
205
207
  await ds.update(updateProject, {
206
208
  id,
207
- data: { status: { id: project.fields.status.id } },
209
+ data: { status: status === null ? null : { id: status.id } },
208
210
  })
209
211
  ```
210
212
 
@@ -11,7 +11,7 @@ description: >-
11
11
  metadata:
12
12
  type: sub-skill
13
13
  library: softr-sdk
14
- library_version: 1.16.0-alpha.2
14
+ library_version: 1.16.0
15
15
  ---
16
16
 
17
17
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A route `loader` also runs in the browser, so it calls a server function, never `ds`. A helper that calls `ds` outside a handler, in this file or in another one, goes in `createServerOnlyFn` from `@tanstack/react-start`, or inside the handler. An exported helper without it keeps the server-only import in the browser bundle, and every page stops loading until it moves. Do not make such a helper a server function when it takes an id: any visitor can call a server function with any id. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -99,6 +99,26 @@ Calling `.where` more than once ands the filters together, and the query's `filt
99
99
  .orderBy((q) => [q.views.desc, q.title.asc]) // array for tie-breakers
100
100
  ```
101
101
 
102
+ ### One builder, one read
103
+
104
+ `where` and `orderBy` add to the builder they are called on and return that same builder. A builder kept in a variable carries its filters and sorts into every later read, with no error. Start each read from its own `ds.list`, `ds.get` or `ds.export`:
105
+
106
+ ```ts
107
+ // Wrong: the second read asks for open AND closed, and returns no records.
108
+ const list = ds.list(orders)
109
+ const open = await list.where((q) => q.status.is('open'))
110
+ const closed = await list.where((q) => q.status.is('closed'))
111
+
112
+ // Right: one builder for each read.
113
+ const open = await ds.list(orders).where((q) => q.status.is('open'))
114
+ const closed = await ds.list(orders).where((q) => q.status.is('closed'))
115
+ ```
116
+
117
+ - A loop with one filter per pass, such as one count per tab, starts a new builder on each pass.
118
+ - A second `orderBy` on the same builder only breaks the ties of the first.
119
+ - A reused `ds.export` builder writes a file with only the records that match every filter it collected.
120
+ - To add a filter only when an input is set, reassign the builder before its one read: `if (search) list = list.where(...)`, as in [Keep a large table on the server](#keep-a-large-table-on-the-server).
121
+
102
122
  ### Get one record
103
123
 
104
124
  ```ts
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.16.0-alpha.2
12
+ library_version: 1.16.0
13
13
  ---
14
14
 
15
15
  **Boundary.** `Audience` and `defineVisibility` come from `@softr/sdk` and work anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.16.0-alpha.2
12
+ library_version: 1.16.0
13
13
  ---
14
14
 
15
15
  **Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.16.0-alpha.2
12
+ library_version: 1.16.0
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.