@softr/sdk 1.2.3-alpha.0 → 1.3.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 (38) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/auth/isomorphic.d.ts +8 -1
  3. package/dist/auth/isomorphic.js +5 -2
  4. package/dist/auth/methods/sso.d.ts +19 -0
  5. package/dist/auth/methods/sso.js +28 -0
  6. package/dist/auth/platform.js +46 -2
  7. package/dist/auth/returnPath.js +17 -15
  8. package/dist/auth/server.d.ts +2 -0
  9. package/dist/auth/server.js +2 -0
  10. package/dist/auth/session.js +45 -2
  11. package/dist/auth/sso.d.ts +24 -0
  12. package/dist/auth/sso.js +204 -0
  13. package/dist/cookies.js +2 -2
  14. package/dist/fetch.js +2 -11
  15. package/dist/index.d.ts +2 -1
  16. package/dist/index.js +2 -1
  17. package/dist/mcp.d.ts +2 -2
  18. package/dist/package.js +1 -1
  19. package/dist/softr-config.schema.js +2 -1
  20. package/package.json +1 -1
  21. package/schema/softr.schema.json +10 -1
  22. package/skills/softr-sdk/SKILL.md +1 -1
  23. package/skills/softr-sdk/ai/SKILL.md +1 -1
  24. package/skills/softr-sdk/auth/SKILL.md +1 -1
  25. package/skills/softr-sdk/auth/references/single-sign-on.md +50 -0
  26. package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
  27. package/skills/softr-sdk/current-user/SKILL.md +1 -1
  28. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  29. package/skills/softr-sdk/formatting/SKILL.md +1 -1
  30. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  31. package/skills/softr-sdk/mcp/SKILL.md +1 -1
  32. package/skills/softr-sdk/push-notifications/SKILL.md +1 -1
  33. package/skills/softr-sdk/pwa/SKILL.md +1 -1
  34. package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
  35. package/skills/softr-sdk/record-queries/SKILL.md +1 -1
  36. package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
  37. package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
  38. package/skills/softr-sdk/workflows/SKILL.md +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @softr/sdk
2
2
 
3
+ ## 1.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Single sign-on: `ssoSignInHref`, `useAuthSettings().sso`, `auth.discoverSso` and the optional `auth.routes.sso` page (default `/sso-authentication`). Action: add the `/sso-authentication` page, and show a "Continue with SSO" link to `ssoSignInHref(...)` on the login page when `sso` is set.
8
+
3
9
  ## 1.2.2
4
10
 
5
11
  ### Patch Changes
@@ -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>], {
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>], {
25
25
  user: User | null;
26
26
  permissions: {
27
27
  datasources: {};
@@ -70,6 +70,13 @@ type AuthOptions = {
70
70
  google: {
71
71
  clientId: string;
72
72
  } | null;
73
+ /**
74
+ * Single sign-on through the app's identity provider: a link to
75
+ * `ssoSignInHref`, and `auth.discoverSso` to route by email.
76
+ */
77
+ sso: {
78
+ type: "SAML" | "OPEN_ID";
79
+ } | null;
73
80
  /** `auth.signUp`, then `auth.confirmSignUp` */
74
81
  signUp: boolean;
75
82
  /** The builder asked for strong passwords whenever a visitor sets one. */
@@ -4,6 +4,7 @@ import { sessionConfig } from "./config.js";
4
4
  import { makePlatform } from "./platform.js";
5
5
  import { clearSession, makeSessionDataCookie, readSessionData, readSessionToken } from "./session.js";
6
6
  import { readSoftrContext } from "./context.js";
7
+ import { ssoMiddleware } from "./sso.js";
7
8
  import { defaultFormatting, resolveFormatting } from "../formatting.js";
8
9
  import { readLocaleSettings } from "../locale-settings.js";
9
10
  import { settings } from "./methods/settings.js";
@@ -13,9 +14,9 @@ import { pushMiddleware } from "../push.js";
13
14
  import { faviconMiddleware } from "../favicon.js";
14
15
  import { embeddingMiddleware } from "../embedding.js";
15
16
  import { appIdentityMiddleware } from "../app-identity.js";
16
- import { getRequestHeader } from "@tanstack/react-start/server";
17
17
  import { createContext, useContext } from "react";
18
18
  import { createMiddleware, createServerFn } from "@tanstack/react-start";
19
+ import { getRequestHeader } from "@tanstack/react-start/server";
19
20
  import { rootRouteId, useRouteContext } from "@tanstack/react-router";
20
21
  import { jsx } from "react/jsx-runtime";
21
22
 
@@ -41,7 +42,8 @@ function softrAuthMiddleware() {
41
42
  bootErrorMiddleware(),
42
43
  pwaMiddleware(),
43
44
  pushMiddleware(),
44
- faviconMiddleware()
45
+ faviconMiddleware(),
46
+ ssoMiddleware()
45
47
  ]).server(async ({ next }) => {
46
48
  async function getSession() {
47
49
  const token = readSessionToken();
@@ -129,6 +131,7 @@ const getAuthSettings = createServerFn({ method: "GET" }).handler(async () => {
129
131
  emailCode: emailMethods.includes("EMAIL_CODE"),
130
132
  magicLink: on("MAGIC_LINK"),
131
133
  google: on("GOOGLE") && clientId ? { clientId } : null,
134
+ sso: on("SSO") && raw.sso?.type ? { type: raw.sso.type } : null,
132
135
  signUp: raw.loginEnabled && (raw.signUpPolicy === "OPEN_TO_PUBLIC" || raw.signUpPolicy === "DOMAIN_RESTRICTED"),
133
136
  strongPasswords: on("EMAIL") && (raw.emailAuth?.strongPasswords ?? false)
134
137
  };
@@ -0,0 +1,19 @@
1
+ import { AuthError, Result } from "./utils.js";
2
+
3
+ //#region src/auth/methods/sso.d.ts
4
+
5
+ /**
6
+ * Whether a visitor with this email signs in with single sign-on, for a login
7
+ * page that asks for the email first and routes from there.
8
+ *
9
+ * Decided by the email's domain against the domains the builder set for single
10
+ * sign-on in Softr. It says nothing about whether an account exists, and an
11
+ * address that is not an email answers `false`.
12
+ */
13
+ declare function discoverSso(details: {
14
+ email: string;
15
+ }): Promise<Result<{
16
+ sso: boolean;
17
+ }, AuthError>>;
18
+ //#endregion
19
+ export { discoverSso };
@@ -0,0 +1,28 @@
1
+ import { panic } from "../../assertions.js";
2
+ import { sessionConfig } from "../config.js";
3
+ import { makePlatform } from "../platform.js";
4
+ import { authError } from "./utils.js";
5
+
6
+ //#region src/auth/methods/sso.ts
7
+ /**
8
+ * Whether a visitor with this email signs in with single sign-on, for a login
9
+ * page that asks for the email first and routes from there.
10
+ *
11
+ * Decided by the email's domain against the domains the builder set for single
12
+ * sign-on in Softr. It says nothing about whether an account exists, and an
13
+ * address that is not an email answers `false`.
14
+ */
15
+ async function discoverSso(details) {
16
+ const result = await makePlatform(sessionConfig().applicationId).ssoDiscover(details);
17
+ if (!result.ok) {
18
+ if (result.status === 429) return authError("tooManyAttempts", result.message);
19
+ panic(`Expected to learn whether that email signs in with single sign-on, but got ${result.status}: ` + result.message);
20
+ }
21
+ return {
22
+ success: true,
23
+ data: result.data
24
+ };
25
+ }
26
+
27
+ //#endregion
28
+ export { discoverSso };
@@ -54,6 +54,24 @@ function makePlatform(applicationId) {
54
54
  properties
55
55
  };
56
56
  });
57
+ const ssoSignInSchema = z.object({
58
+ result: z.object({
59
+ status: z.enum(["AUTHENTICATED", "MFA_REQUIRED"]),
60
+ session: z.object({
61
+ jwt: z.string(),
62
+ user: userSchema
63
+ }).nullish(),
64
+ mfa: z.object({
65
+ action: z.enum([
66
+ "VERIFICATION_REQUIRED",
67
+ "SETUP_REQUIRED",
68
+ "SETUP_OPTIONAL"
69
+ ]),
70
+ challengeToken: z.string()
71
+ }).nullish()
72
+ }),
73
+ returnPath: z.string()
74
+ });
57
75
  return {
58
76
  authSettings: () => request(`/v1/vibe/applications/${applicationId}/users/auth-settings`, { method: "GET" }, authSettingsSchema),
59
77
  session: async (token) => {
@@ -164,6 +182,30 @@ function makePlatform(applicationId) {
164
182
  challengeToken: z.string()
165
183
  }).nullish()
166
184
  })),
185
+ ssoStart: (body) => request(`/v1/vibe/applications/${applicationId}/users/sso/start`, {
186
+ method: "POST",
187
+ json: body
188
+ }, z.object({
189
+ protocol: z.enum(["OPEN_ID", "SAML"]),
190
+ bindingToken: z.string(),
191
+ returnPath: z.string(),
192
+ redirectUrl: z.string().nullable(),
193
+ formAction: z.string().nullable(),
194
+ samlRequest: z.string().nullable(),
195
+ relayState: z.string().nullable()
196
+ })),
197
+ signInWithOpenId: (body) => request(`/v1/vibe/applications/${applicationId}/users/tokens/with-openid${withAttributes}`, {
198
+ method: "POST",
199
+ json: body
200
+ }, ssoSignInSchema),
201
+ signInWithSaml: (body) => request(`/v1/vibe/applications/${applicationId}/users/tokens/with-saml${withAttributes}`, {
202
+ method: "POST",
203
+ json: body
204
+ }, ssoSignInSchema),
205
+ ssoDiscover: (body) => request(`/v1/vibe/applications/${applicationId}/users/sso/discover`, {
206
+ method: "POST",
207
+ json: body
208
+ }, z.object({ sso: z.boolean() })),
167
209
  forgotPassword: (body) => request(`/v1/vibe/applications/${applicationId}/users/forgot-password`, {
168
210
  method: "POST",
169
211
  json: body
@@ -328,11 +370,13 @@ async function request(path, init, schema, parse = (response$1) => response$1.js
328
370
  ...init.form === void 0 ? {} : { body: init.form }
329
371
  });
330
372
  if (!response.ok) {
331
- const error = errorSchema.safeParse(await response.json().catch(() => null));
373
+ const body = await response.json().catch(() => null);
374
+ const error = errorSchema.safeParse(body);
332
375
  return {
333
376
  ok: false,
334
377
  status: response.status,
335
- message: error.success && error.data.message ? error.data.message : response.statusText
378
+ message: error.success && error.data.message ? error.data.message : response.statusText,
379
+ body
336
380
  };
337
381
  }
338
382
  const parsed = schema.safeParse(await parse(response).catch(() => null));
@@ -14,24 +14,26 @@ import { softrConfig } from "../softr-config.js";
14
14
  function toReturnPath(location) {
15
15
  const { auth } = softrConfig();
16
16
  const target = location.search[auth.routes.login.redirectParam];
17
- if (typeof target === "string" && target.startsWith("/") && new URL(target, "https://app.invalid").origin === "https://app.invalid") return {
18
- href: target,
19
- reloadDocument: true
20
- };
21
- const fallback = auth.guard.alreadyAuthenticated;
22
- if (typeof fallback === "string") return {
23
- href: fallback,
24
- reloadDocument: true
25
- };
26
- if (fallback.strategy === "redirect") return {
27
- href: fallback.to,
28
- reloadDocument: true
29
- };
30
17
  return {
31
- href: "/",
18
+ href: resolveReturnPath(target),
32
19
  reloadDocument: true
33
20
  };
34
21
  }
22
+ /**
23
+ * `target` when it is a path on this app, else where
24
+ * `auth.guard.alreadyAuthenticated` in softr.json points, else `/`.
25
+ */
26
+ function resolveReturnPath(target) {
27
+ if (isAppPath(target)) return target;
28
+ const fallback = softrConfig().auth.guard.alreadyAuthenticated;
29
+ if (typeof fallback === "string") return fallback;
30
+ if (fallback.strategy === "redirect") return fallback.to;
31
+ return "/";
32
+ }
33
+ /** It starts with `/` and names no other host, however that is spelled. */
34
+ function isAppPath(target) {
35
+ return typeof target === "string" && target.startsWith("/") && new URL(target, "https://app.invalid").origin === "https://app.invalid";
36
+ }
35
37
 
36
38
  //#endregion
37
- export { toReturnPath };
39
+ export { resolveReturnPath, toReturnPath };
@@ -5,6 +5,7 @@ import { signInWithMagicLink } from "./methods/magicLink.js";
5
5
  import { signIn, signOut } from "./methods/password.js";
6
6
  import { checkPasswordLink, requestPasswordReset, setPasswordWithLink } from "./methods/passwordLink.js";
7
7
  import { settings } from "./methods/settings.js";
8
+ import { discoverSso } from "./methods/sso.js";
8
9
  import { confirmSignUp, signUp } from "./methods/signup.js";
9
10
  import { signInWithGoogle } from "./methods/social.js";
10
11
  import { removeAvatar, updateProfile } from "./methods/profile.js";
@@ -25,6 +26,7 @@ declare const auth: {
25
26
  signInWithCode: typeof signInWithCode;
26
27
  signInWithGoogle: typeof signInWithGoogle;
27
28
  signInWithMagicLink: typeof signInWithMagicLink;
29
+ discoverSso: typeof discoverSso;
28
30
  requestPasswordReset: typeof requestPasswordReset;
29
31
  checkPasswordLink: typeof checkPasswordLink;
30
32
  setPasswordWithLink: typeof setPasswordWithLink;
@@ -5,6 +5,7 @@ import { resendEmailCode, verifyEmailCode } from "./methods/emailCode2fa.js";
5
5
  import { signInWithMagicLink } from "./methods/magicLink.js";
6
6
  import { signIn, signOut } from "./methods/password.js";
7
7
  import { checkPasswordLink, requestPasswordReset, setPasswordWithLink } from "./methods/passwordLink.js";
8
+ import { discoverSso } from "./methods/sso.js";
8
9
  import { confirmSignUp, signUp } from "./methods/signup.js";
9
10
  import { signInWithGoogle } from "./methods/social.js";
10
11
  import { removeAvatar, updateProfile } from "./methods/profile.js";
@@ -24,6 +25,7 @@ const auth = {
24
25
  signInWithCode,
25
26
  signInWithGoogle,
26
27
  signInWithMagicLink,
28
+ discoverSso,
27
29
  requestPasswordReset,
28
30
  checkPasswordLink,
29
31
  setPasswordWithLink,
@@ -3,21 +3,24 @@ import { expireCookie, expireOtherCopy, readRequestCookies, serializeCookie, wri
3
3
  import { sessionConfig } from "./config.js";
4
4
  import { makePlatform } from "./platform.js";
5
5
  import { userSchema } from "./user.js";
6
- import { getRequestProtocol } from "@tanstack/react-start/server";
7
6
  import { z } from "zod";
8
7
  import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
9
8
  import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { getRequestProtocol } from "@tanstack/react-start/server";
10
10
 
11
11
  //#region src/auth/session.ts
12
12
  const SESSION_TOKEN = "session_token";
13
13
  const SESSION_DATA = "session_data";
14
14
  const PENDING_AUTH = "pending_auth";
15
+ const SSO_BINDING = "softr_sso_binding";
15
16
  const SESSION_DATA_TTL_SECONDS = 300;
16
17
  /**
17
18
  * How long a visitor has to answer a second factor. The platform expires the
18
19
  * challenge token itself. This only decides how long the browser carries it.
19
20
  */
20
21
  const PENDING_AUTH_TTL_SECONDS = 600;
22
+ /** How long a visitor has to finish signing in at their identity provider. */
23
+ const SSO_BINDING_TTL_SECONDS = 600;
21
24
  /**
22
25
  * A browser refuses a `__Host-` cookie unless it is `Secure`, `Path=/` and free
23
26
  * of `Domain` — that last clause is the one worth having, since it stops a
@@ -134,6 +137,42 @@ function clearPendingAuth() {
134
137
  clearCookies([PENDING_AUTH]);
135
138
  }
136
139
  /**
140
+ * Ties a single sign-on round trip to the browser that started it. The
141
+ * platform checks its token against the one the identity provider sends back,
142
+ * so a response started in another browser can't sign this one in.
143
+ *
144
+ * Cross-site, because a SAML identity provider posts its answer from its own
145
+ * site, and a Lax cookie is not sent with that.
146
+ *
147
+ * Not partitioned, unlike the session cookies of an embedded app. An identity
148
+ * provider refuses to load in an iframe, so single sign-on only ever runs top
149
+ * level, where a partition adds nothing.
150
+ */
151
+ function makeSsoBindingCookie(binding) {
152
+ const { name, secure } = sessionCookie(SSO_BINDING);
153
+ return serializeCookie(name, sealEnvelope(JSON.stringify(binding), SSO_BINDING), {
154
+ maxAge: SSO_BINDING_TTL_SECONDS,
155
+ secure,
156
+ crossSite: true
157
+ });
158
+ }
159
+ /** The binding this browser holds, or `null`. */
160
+ function readSsoBinding() {
161
+ const { name } = sessionCookie(SSO_BINDING);
162
+ const json = openEnvelope(readRequestCookies()[name], SSO_BINDING);
163
+ if (json === null) return null;
164
+ try {
165
+ const binding = ssoBindingSchema.safeParse(JSON.parse(json));
166
+ return binding.success ? binding.data : null;
167
+ } catch {
168
+ return null;
169
+ }
170
+ }
171
+ /** Single use: every answer from the identity provider spends it. */
172
+ function clearSsoBinding() {
173
+ clearCookies([SSO_BINDING]);
174
+ }
175
+ /**
137
176
  * Writes rather than returns: a forgotten list would leave the session live.
138
177
  */
139
178
  function clearSession() {
@@ -159,6 +198,10 @@ const sessionDataSchema = z.object({
159
198
  exp: z.number(),
160
199
  tb: z.string()
161
200
  });
201
+ const ssoBindingSchema = z.object({
202
+ bindingToken: z.string(),
203
+ returnPath: z.string()
204
+ });
162
205
  /**
163
206
  * Both spellings on https: a jar can hold both pairs across a move between
164
207
  * schemes, and the one left behind would revive if the scheme changed back.
@@ -241,4 +284,4 @@ function openEnvelope(raw, purpose) {
241
284
  }
242
285
 
243
286
  //#endregion
244
- export { clearPendingAuth, clearSession, clearSessionData, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readFreshUser, readPendingAuthToken, readSessionData, readSessionToken, readStandInUser, withSessionToken };
287
+ export { clearPendingAuth, clearSession, clearSessionData, clearSsoBinding, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, makeSsoBindingCookie, readFreshUser, readPendingAuthToken, readSessionData, readSessionToken, readSsoBinding, readStandInUser, withSessionToken };
@@ -0,0 +1,24 @@
1
+ import "@tanstack/react-start";
2
+
3
+ //#region src/auth/sso.d.ts
4
+
5
+ /**
6
+ * Where a link or button sends a visitor to sign in with single sign-on. They
7
+ * come back to `returnPath` once signed in. Without one, they land where
8
+ * `auth.guard.alreadyAuthenticated` in softr.json points, as after any sign-in.
9
+ *
10
+ * A full page load, not a router navigation: the visitor leaves the app for
11
+ * their identity provider.
12
+ *
13
+ * @example
14
+ * <a href={ssoSignInHref(toReturnPath(location).href)}>Continue with SSO</a>
15
+ */
16
+ declare function ssoSignInHref(returnPath?: string): string;
17
+ /**
18
+ * Why single sign-on did not finish, as the `error` search param of the SSO
19
+ * page. Never the platform's own message: that is for the builder, and it would
20
+ * sit in the visitor's address bar.
21
+ */
22
+ type SsoError = "host" | "idp" | "not-enabled" | "sign-up-disabled" | "restricted" | "expired" | "failed";
23
+ //#endregion
24
+ export { SsoError, ssoSignInHref };
@@ -0,0 +1,204 @@
1
+ import { assert } from "../assertions.js";
2
+ import { logger } from "../logger.js";
3
+ import { softrConfig } from "../softr-config.js";
4
+ import { writeCookies } from "../cookies.js";
5
+ import { sessionConfig } from "./config.js";
6
+ import { makePlatform } from "./platform.js";
7
+ import { clearPendingAuth, clearSsoBinding, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, makeSsoBindingCookie, readSsoBinding } from "./session.js";
8
+ import { resolveReturnPath } from "./returnPath.js";
9
+ import { z } from "zod";
10
+ import { createMiddleware } from "@tanstack/react-start";
11
+
12
+ //#region src/auth/sso.ts
13
+ const START_PATH = "/_softr/sso/start";
14
+ const OPEN_ID_CALLBACK_PATH = "/open-id/code";
15
+ const SAML_CALLBACK_PATH = "/saml/SSO";
16
+ const DEFAULT_SSO_PATH = "/sso-authentication";
17
+ /**
18
+ * Where a link or button sends a visitor to sign in with single sign-on. They
19
+ * come back to `returnPath` once signed in. Without one, they land where
20
+ * `auth.guard.alreadyAuthenticated` in softr.json points, as after any sign-in.
21
+ *
22
+ * A full page load, not a router navigation: the visitor leaves the app for
23
+ * their identity provider.
24
+ *
25
+ * @example
26
+ * <a href={ssoSignInHref(toReturnPath(location).href)}>Continue with SSO</a>
27
+ */
28
+ function ssoSignInHref(returnPath) {
29
+ return returnPath ? `${START_PATH}?return=${encodeURIComponent(returnPath)}` : START_PATH;
30
+ }
31
+ /**
32
+ * Starts single sign-on and finishes it when the identity provider answers.
33
+ * Every other request passes through.
34
+ *
35
+ * The start is a GET the visitor's browser makes, so a link can begin it. The
36
+ * identity provider answers OpenID Connect with a redirect, and SAML with a
37
+ * form it posts from its own site.
38
+ */
39
+ function ssoMiddleware() {
40
+ return createMiddleware({ type: "request" }).server(async ({ next, request, pathname }) => {
41
+ switch (pathname) {
42
+ case START_PATH:
43
+ if (request.method !== "GET") return methodNotAllowed("GET");
44
+ return await start(new URL(request.url));
45
+ case OPEN_ID_CALLBACK_PATH: {
46
+ if (request.method !== "GET") return methodNotAllowed("GET");
47
+ const url = new URL(request.url);
48
+ const code = url.searchParams.get("code");
49
+ const binding = readSsoBinding();
50
+ clearSsoBinding();
51
+ if (code === null) return toSsoPage({ error: "idp" });
52
+ if (binding === null) return toSsoPage({ error: "expired" });
53
+ return await finish(await platform().signInWithOpenId({
54
+ code,
55
+ state: url.searchParams.get("state") ?? "",
56
+ ...binding
57
+ }));
58
+ }
59
+ case SAML_CALLBACK_PATH: {
60
+ if (request.method !== "POST") return methodNotAllowed("POST");
61
+ const form = await request.formData().catch(() => null);
62
+ const samlResponse = form?.get("SAMLResponse");
63
+ const binding = readSsoBinding();
64
+ clearSsoBinding();
65
+ if (typeof samlResponse !== "string" || samlResponse === "") return toSsoPage({ error: "idp" });
66
+ if (binding === null) return toSsoPage({ error: "expired" });
67
+ const relayState = form?.get("RelayState");
68
+ return await finish(await platform().signInWithSaml({
69
+ samlResponse,
70
+ relayState: typeof relayState === "string" ? relayState : "",
71
+ ...binding
72
+ }));
73
+ }
74
+ default: return await next();
75
+ }
76
+ });
77
+ }
78
+ async function start(url) {
79
+ const result = await platform().ssoStart({
80
+ origin: url.origin,
81
+ returnPath: resolveReturnPath(url.searchParams.get("return"))
82
+ });
83
+ if (!result.ok) return toSsoPage(failure(result));
84
+ const started = result.data;
85
+ const binding = makeSsoBindingCookie({
86
+ bindingToken: started.bindingToken,
87
+ returnPath: started.returnPath
88
+ });
89
+ if (started.protocol === "OPEN_ID") {
90
+ assert(started.redirectUrl, "Expected where to send the visitor for OpenID sign-in, but got none");
91
+ writeCookies([binding]);
92
+ return new Response(null, {
93
+ status: 302,
94
+ headers: {
95
+ location: started.redirectUrl,
96
+ "cache-control": "no-store"
97
+ }
98
+ });
99
+ }
100
+ assert(started.formAction && started.samlRequest && started.relayState, "Expected the SAML request to post, but it came back incomplete");
101
+ writeCookies([binding]);
102
+ return samlForm(started.formAction, started.samlRequest, started.relayState);
103
+ }
104
+ async function finish(result) {
105
+ if (!result.ok) return toSsoPage(failure(result));
106
+ const { result: signIn, returnPath } = result.data;
107
+ if (signIn.status === "MFA_REQUIRED") {
108
+ const { mfa } = signIn;
109
+ assert(mfa, "Expected a challenge from single sign-on, but got none");
110
+ writeCookies([makePendingAuthCookie(mfa.challengeToken)]);
111
+ return toSsoPage({
112
+ authenticator: mfa.action === "VERIFICATION_REQUIRED" ? "verify" : mfa.action === "SETUP_REQUIRED" ? "setup" : "setupOptional",
113
+ returnPath: resolveReturnPath(returnPath)
114
+ });
115
+ }
116
+ const { session } = signIn;
117
+ assert(session, "Expected a session from single sign-on, but got none");
118
+ writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({ user: session.user }, session.jwt)]);
119
+ clearPendingAuth();
120
+ return seeOther(resolveReturnPath(returnPath));
121
+ }
122
+ const ssoErrorBodySchema = z.object({ code: z.string() });
123
+ function failure(result) {
124
+ const body = ssoErrorBodySchema.safeParse(result.body);
125
+ const code = body.success ? body.data.code : null;
126
+ switch (code) {
127
+ case "SSO_HOST_MISMATCH": return { error: "host" };
128
+ case "SSO_IDP_REJECTED": return { error: "idp" };
129
+ case "SSO_NOT_ENABLED":
130
+ case "SSO_NOT_IN_PLAN":
131
+ case "SSO_MISCONFIGURED": return { error: "not-enabled" };
132
+ case "SSO_SIGN_UP_DISABLED": return { error: "sign-up-disabled" };
133
+ case "USER_DEACTIVATED":
134
+ case "SIGN_IN_RESTRICTED": return { error: "restricted" };
135
+ case "SSO_BINDING_INVALID": return { error: "expired" };
136
+ default:
137
+ logger.warn(`Single sign-on failed with ${result.status} ${code ?? "(no code)"}: ${result.message}`);
138
+ return { error: "failed" };
139
+ }
140
+ }
141
+ /**
142
+ * The app's SSO page, for a second factor or a failure. The return path rides
143
+ * in the login page's redirect param, where the page's own "done" step looks
144
+ * for it.
145
+ */
146
+ function toSsoPage(search) {
147
+ const { routes } = softrConfig().auth;
148
+ const params = new URLSearchParams();
149
+ if ("error" in search) params.set("error", search.error);
150
+ else {
151
+ params.set("authenticator", search.authenticator);
152
+ params.set(routes.login.redirectParam, search.returnPath);
153
+ }
154
+ return seeOther(`${routes.sso?.path ?? DEFAULT_SSO_PATH}?${params}`);
155
+ }
156
+ function seeOther(location) {
157
+ return new Response(null, {
158
+ status: 303,
159
+ headers: {
160
+ location,
161
+ "cache-control": "no-store"
162
+ }
163
+ });
164
+ }
165
+ function methodNotAllowed(allowed) {
166
+ return new Response(null, {
167
+ status: 405,
168
+ headers: { allow: allowed }
169
+ });
170
+ }
171
+ /**
172
+ * SAML's POST binding: a form the browser posts to the identity provider. The
173
+ * script submits it at once. Without scripts, the visitor presses the button.
174
+ */
175
+ function samlForm(action, samlRequest, relayState) {
176
+ const body = `<!doctype html>
177
+ <html>
178
+ <head><meta charset="utf-8"><meta name="robots" content="noindex"><title>Signing in…</title></head>
179
+ <body>
180
+ <form method="post" action="${escapeHtml(action)}">
181
+ <input type="hidden" name="SAMLRequest" value="${escapeHtml(samlRequest)}">
182
+ <input type="hidden" name="RelayState" value="${escapeHtml(relayState)}">
183
+ <noscript><button type="submit">Continue to sign in</button></noscript>
184
+ </form>
185
+ <script>document.forms[0].submit()<\/script>
186
+ </body>
187
+ </html>`;
188
+ return new Response(body, {
189
+ status: 200,
190
+ headers: {
191
+ "content-type": "text/html; charset=utf-8",
192
+ "cache-control": "no-store"
193
+ }
194
+ });
195
+ }
196
+ function escapeHtml(value) {
197
+ return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
198
+ }
199
+ function platform() {
200
+ return makePlatform(sessionConfig().applicationId);
201
+ }
202
+
203
+ //#endregion
204
+ export { ssoMiddleware, ssoSignInHref };
package/dist/cookies.js CHANGED
@@ -25,7 +25,7 @@ function decode(value) {
25
25
  function readRequestCookies() {
26
26
  return parseCookieHeader(getRequestHeader("cookie"));
27
27
  }
28
- function serializeCookie(name, value, { maxAge, secure }) {
28
+ function serializeCookie(name, value, { maxAge, secure, crossSite = false }) {
29
29
  if (name.startsWith("__Host-") && !secure) throw new Error(`Refusing to write ${name} without Secure: a __Host- cookie is only valid when Secure, Path=/ and free of Domain, and a browser silently discards one that is not.`);
30
30
  const parts = [
31
31
  `${name}=${encodeURIComponent(value)}`,
@@ -33,7 +33,7 @@ function serializeCookie(name, value, { maxAge, secure }) {
33
33
  "HttpOnly"
34
34
  ];
35
35
  if (secure) parts.push("Secure");
36
- parts.push(...sameSiteAttributes(secure), `Max-Age=${maxAge}`);
36
+ parts.push(...crossSite && secure ? ["SameSite=None"] : sameSiteAttributes(secure), `Max-Age=${maxAge}`);
37
37
  return parts.join("; ");
38
38
  }
39
39
  function sameSiteAttributes(secure) {
package/dist/fetch.js CHANGED
@@ -2,25 +2,17 @@ import { version } from "./package.js";
2
2
  import { assert, requireDefined } from "./assertions.js";
3
3
  import { logger } from "./logger.js";
4
4
  import { softrApiUrl } from "./softr-api.js";
5
- import { getRequestHeader } from "@tanstack/react-start/server";
6
5
 
7
6
  //#region src/fetch.ts
8
- const CLIENT_IP_HEADER = "x-softr-client-ip";
9
7
  const fetch = async (input, init) => {
10
8
  const url = input instanceof Request ? input.url : String(input);
11
- const platformBase = softrApiUrl("SOFTR_PLATFORM_API_URL");
12
9
  if ([
13
- platformBase,
10
+ softrApiUrl("SOFTR_PLATFORM_API_URL"),
14
11
  softrApiUrl("SOFTR_DATASOURCE_API_URL"),
15
12
  softrApiUrl("SOFTR_WORKFLOWS_API_URL")
16
13
  ].some((base) => url.startsWith(`${base}/`))) {
17
14
  const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
18
15
  headers.set("user-agent", `softr-sdk/${version}`);
19
- headers.delete(CLIENT_IP_HEADER);
20
- if (url.startsWith(`${platformBase}/`)) try {
21
- const clientIp = getRequestHeader("cf-connecting-ip");
22
- if (clientIp) headers.set(CLIENT_IP_HEADER, clientIp);
23
- } catch {}
24
16
  init = {
25
17
  ...init,
26
18
  headers
@@ -50,7 +42,7 @@ const fetch = async (input, init) => {
50
42
  * id (`<environment>/<applicationId>/<master number>`) is copied into the signature as is so the verifier can
51
43
  * derive the same key.
52
44
  *
53
- * The signature covers the method, authority, path, query and, when sent, the Authorization and client IP headers. The body is
45
+ * The signature covers the method, authority, path, query and, when sent, the Authorization header. The body is
54
46
  * not covered: TLS protects it in transit, and signing is there to tell the app's own server from anyone holding a
55
47
  * user token, which needs no body coverage. So nothing is buffered here and the body streams through as given.
56
48
  */
@@ -71,7 +63,6 @@ async function sign(input, init) {
71
63
  };
72
64
  const fields = Object.keys(derived);
73
65
  if (headers.has("authorization")) fields.push("authorization");
74
- if (headers.has(CLIENT_IP_HEADER)) fields.push(CLIENT_IP_HEADER);
75
66
  const created = Math.floor(Date.now() / 1e3);
76
67
  const params = `(${fields.map((field) => `"${field}"`).join(" ")});created=${created};keyid="${keyId}";tag="softr-code-app"`;
77
68
  const base = [...fields.map((field) => `"${field}": ${derived[field] ?? requireDefined(headers.get(field), field)}`), `"@signature-params": ${params}`].join("\n");
package/dist/index.d.ts CHANGED
@@ -10,6 +10,7 @@ import { checkAccess, defineVisibility, isAuthorized } from "./route/visibility.
10
10
  import { Page, PageSettings, definePage, pageHead } from "./route/page.js";
11
11
  import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./route/route.js";
12
12
  import { toReturnPath } from "./auth/returnPath.js";
13
+ import { SsoError, ssoSignInHref } from "./auth/sso.js";
13
14
  import { AuthOptions, AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
14
15
  import { softrMcpMiddleware } from "./mcp.js";
15
16
  import { FieldShape, SoftrFieldRegistry, fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
@@ -19,4 +20,4 @@ import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
19
20
  import { PushNotifications, PushPrompt, usePushNotifications } from "./push.js";
20
21
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
21
22
  import { Audience } from "./route/audience.js";
22
- 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 FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, 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 User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
23
+ 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 FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, 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 User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import { checkAccess, defineVisibility, isAuthorized } from "./route/visibility.
4
4
  import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./route/route.js";
5
5
  import { definePage, pageHead } from "./route/page.js";
6
6
  import { toReturnPath } from "./auth/returnPath.js";
7
+ import { ssoSignInHref } from "./auth/sso.js";
7
8
  import { FormattedDate, FormattingScope, formatDate, formatDateTime, formatNumber, useFormatting } from "./formatting.js";
8
9
  import { SoftrPwaHead, usePwaInstall } from "./pwa.js";
9
10
  import { usePushNotifications } from "./push.js";
@@ -15,4 +16,4 @@ import { useUserTimezone } from "./timezone.js";
15
16
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
16
17
  import { Audience } from "./route/audience.js";
17
18
 
18
- export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
19
+ export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
package/dist/mcp.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DatasourceAction } from "./action.js";
2
- import * as _tanstack_react_start0 from "@tanstack/react-start";
2
+ import * as _tanstack_react_start10 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_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>;
34
+ declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start10.RequestMiddlewareAfterServer<{}, undefined, undefined>;
35
35
  //#endregion
36
36
  export { softrMcpMiddleware };
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.2.3-alpha.0";
2
+ var version = "1.3.0";
3
3
 
4
4
  //#endregion
5
5
  export { version };
@@ -40,7 +40,8 @@ const SoftrConfigSchema = z.object({
40
40
  magicLink: z.strictObject({
41
41
  path: AppPath,
42
42
  tokenParam: z.string()
43
- })
43
+ }),
44
+ sso: z.strictObject({ path: AppPath }).optional()
44
45
  }),
45
46
  guard: z.strictObject({
46
47
  unauthenticated: AccessBehaviour,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "1.2.3-alpha.0",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -26,7 +26,16 @@
26
26
  },
27
27
  "resetPassword": { "$ref": "#/$defs/tokenRoute", "description": "The page a password reset email links to." },
28
28
  "acceptInvitation": { "$ref": "#/$defs/tokenRoute", "description": "The page an invitation email links to." },
29
- "magicLink": { "$ref": "#/$defs/tokenRoute", "description": "The page a magic link email links to." }
29
+ "magicLink": { "$ref": "#/$defs/tokenRoute", "description": "The page a magic link email links to." },
30
+ "sso": {
31
+ "type": "object",
32
+ "description": "The page single sign-on comes back to when it needs an authenticator code or failed. Defaults to /sso-authentication.",
33
+ "properties": {
34
+ "path": { "$ref": "#/$defs/appPath" }
35
+ },
36
+ "required": ["path"],
37
+ "additionalProperties": false
38
+ }
30
39
  },
31
40
  "required": ["login", "resetPassword", "acceptInvitation", "magicLink"],
32
41
  "additionalProperties": false
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: core
12
12
  library: softr-sdk
13
- library_version: 1.2.3-alpha.0
13
+ library_version: 1.3.0
14
14
  ---
15
15
 
16
16
  # 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.2.3-alpha.0
16
+ library_version: 1.3.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.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.2.3-alpha.0
12
+ library_version: 1.3.0
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.
@@ -0,0 +1,50 @@
1
+ # Single sign-on
2
+
3
+ The visitor signs in at the app's identity provider (Okta, Entra ID, Google Workspace and the like), which the builder set up in Softr. There is no server function to write. A link starts it, and the visitor comes back signed in:
4
+
5
+ ```tsx
6
+ import { useLocation } from '@tanstack/react-router'
7
+ import { ssoSignInHref, toReturnPath, useAuthSettings } from '@softr/sdk'
8
+
9
+ const options = useAuthSettings()
10
+ const location = useLocation()
11
+
12
+ {options.sso ? (
13
+ <Button nativeButton={false} render={<a href={ssoSignInHref(toReturnPath(location).href)} />}>
14
+ Continue with SSO
15
+ </Button>
16
+ ) : null}
17
+ ```
18
+
19
+ A plain `<a href>`, never `<Link>` or `navigate`: the visitor leaves the app for the identity provider. They land on the path passed in, which only works for a path on this app. Without one, they land where `auth.guard.alreadyAuthenticated` in `softr.json` points, as after any other sign-in.
20
+
21
+ Sign-in starts in the app, always. A sign-in started at the identity provider, from an app tile on its dashboard, is not supported: it arrives without the app's record of having started and ends in `expired`.
22
+
23
+ When single sign-on needs more from the visitor, or fails, they come back to the page `auth.routes.sso.path` in `softr.json` names, `/sso-authentication` when it is not set. That page must exist. It reads two search params:
24
+
25
+ | Param | Means | Show |
26
+ | --- | --- | --- |
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
+ | `error` | why it did not finish, one of the codes below | a message, a "Try again" link to `ssoSignInHref()`, and a link to the login page |
29
+
30
+ | `error` | Means |
31
+ | --- | --- |
32
+ | `host` | Single sign-on works only on the published app, not in the preview. Say so. Never link to a URL from the search params: anyone can put one there |
33
+ | `idp` | The identity provider refused or the visitor cancelled there |
34
+ | `not-enabled` | Single sign-on is off or not set up completely |
35
+ | `sign-up-disabled` | No account for this visitor, and the app does not let new people sign up |
36
+ | `restricted` | The account is deactivated, or the app has no room for another user |
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 |
38
+ | `failed` | Anything else |
39
+
40
+ With neither param, redirect to `toReturnPath(location)`.
41
+
42
+ An app whose only way in is single sign-on still has a login page, with the button on it.
43
+
44
+ ## Three login pages
45
+
46
+ Three ways to put it on the login page. Build the one the builder asks for:
47
+
48
+ 1. **A button**, as above, next to the other methods. The default.
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.
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.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.2.3-alpha.0
12
+ library_version: 1.3.0
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: 1.2.3-alpha.0
12
+ library_version: 1.3.0
13
13
  ---
14
14
 
15
15
  # The current user
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 1.2.3-alpha.0
10
+ library_version: 1.3.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.2.3-alpha.0
11
+ library_version: 1.3.0
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: 1.2.3-alpha.0
10
+ library_version: 1.3.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.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.2.3-alpha.0
12
+ library_version: 1.3.0
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: 1.2.3-alpha.0
12
+ library_version: 1.3.0
13
13
  ---
14
14
 
15
15
  # Push notifications
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.2.3-alpha.0
12
+ library_version: 1.3.0
13
13
  ---
14
14
 
15
15
  # Installing the app
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.2.3-alpha.0
12
+ library_version: 1.3.0
13
13
  ---
14
14
 
15
15
  **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.
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.2.3-alpha.0
13
+ library_version: 1.3.0
14
14
  ---
15
15
 
16
16
  **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.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.2.3-alpha.0
12
+ library_version: 1.3.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.2.3-alpha.0
12
+ library_version: 1.3.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.2.3-alpha.0
12
+ library_version: 1.3.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.