@softr/sdk 1.3.0-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.
package/CHANGELOG.md CHANGED
@@ -4,7 +4,13 @@
4
4
 
5
5
  ### Minor Changes
6
6
 
7
- - Add `useIdleTimeout()`, which signs the visitor out of this browser after the idle time set in Studio's "End session if idle", and sends them to `/`. Action: call it once in the root route's document component, next to `useUserTimezone()`.
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
+
9
+ ## 1.2.2
10
+
11
+ ### Patch Changes
12
+
13
+ - `SoftrPwaHead` now gives iOS the app's home screen name and launch screens, so an installed app opens on its splash screen instead of white and Add to Home Screen suggests the app's name, not the page title. An app already on an iPhone home screen picks this up only after it is removed and added again.
8
14
 
9
15
  ## 1.2.1
10
16
 
@@ -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";
@@ -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,
@@ -12,12 +12,15 @@ import { getRequestProtocol } from "@tanstack/react-start/server";
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) {
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import * as react2 from "react";
2
+ import * as react0 from "react";
3
3
  import { ReactNode } from "react";
4
4
 
5
5
  //#region src/formatting.d.ts
@@ -96,7 +96,7 @@ declare function FormattingScope({
96
96
  /** A BCP 47 locale, such as `de-DE`. It drops the app's fixed date format inside the scope. */
97
97
  locale?: string;
98
98
  children?: ReactNode;
99
- }): react2.FunctionComponentElement<react2.ProviderProps<Scope>>;
99
+ }): react0.FunctionComponentElement<react0.ProviderProps<Scope>>;
100
100
  /**
101
101
  * A date in the app's format, safe to render on the server. A timestamp whose
102
102
  * zone is not known yet renders `fallback` until the browser supplies it, so
@@ -118,6 +118,6 @@ declare function FormattedDate({
118
118
  time?: boolean;
119
119
  /** What renders while the visitor's zone is unknown. */
120
120
  fallback?: ReactNode;
121
- }): react2.FunctionComponentElement<react2.FragmentProps> | null;
121
+ }): react0.FunctionComponentElement<react0.FragmentProps> | null;
122
122
  //#endregion
123
123
  export { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, FormattedDate, Formatting, FormattingScope, WeekDay, formatDate, formatDateTime, formatNumber, useFormatting };
package/dist/index.d.ts CHANGED
@@ -10,8 +10,8 @@ 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
- import { useIdleTimeout } from "./auth/idle-timeout.js";
15
15
  import { softrMcpMiddleware } from "./mcp.js";
16
16
  import { FieldShape, SoftrFieldRegistry, fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
17
17
  import { useOverrides } from "./core/use-overrides.js";
@@ -20,4 +20,4 @@ import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
20
20
  import { PushNotifications, PushPrompt, usePushNotifications } from "./push.js";
21
21
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
22
22
  import { Audience } from "./route/audience.js";
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 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, useIdleTimeout, 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,11 +4,11 @@ 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";
10
11
  import { AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
11
- import { useIdleTimeout } from "./auth/idle-timeout.js";
12
12
  import { softrMcpMiddleware } from "./mcp.js";
13
13
  import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
14
14
  import { useOverrides } from "./core/use-overrides.js";
@@ -16,4 +16,4 @@ import { useUserTimezone } from "./timezone.js";
16
16
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
17
17
  import { Audience } from "./route/audience.js";
18
18
 
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, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, 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_start8 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_start8.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.3.0-alpha.0";
2
+ var version = "1.3.0";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/pwa.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- import * as react0 from "react";
1
+ import * as react4 from "react";
2
2
  import "@tanstack/react-start";
3
3
 
4
4
  //#region src/pwa.d.ts
5
5
 
6
6
  /**
7
- * The links that make the app installable: its manifest and its home screen
8
- * icon. Render it once, in `<head>` in the root route's `RootDocument`.
7
+ * The tags that make the app installable: its manifest, its home screen icon,
8
+ * and, while the app is installable, the name and launch screens iOS shows.
9
+ * Render it once, in `<head>` in the root route's `RootDocument`.
9
10
  *
10
11
  * @example
11
12
  * function RootDocument({ children }: { children: React.ReactNode }) {
@@ -23,7 +24,7 @@ import "@tanstack/react-start";
23
24
  * )
24
25
  * }
25
26
  */
26
- declare function SoftrPwaHead(): react0.FunctionComponentElement<react0.FragmentProps>;
27
+ declare function SoftrPwaHead(): react4.FunctionComponentElement<react4.FragmentProps>;
27
28
  type PwaPlatform = "ios" | "android" | "desktop";
28
29
  type PwaInstall = {
29
30
  available: false;
package/dist/pwa.js CHANGED
@@ -18,8 +18,13 @@ const pwaSchema = z.object({
18
18
  install: z.object({
19
19
  name: z.string(),
20
20
  iconUrl: z.string()
21
- })
21
+ }),
22
+ startupImages: z.array(z.object({
23
+ media: z.string(),
24
+ href: z.string()
25
+ })).default([])
22
26
  });
27
+ const iosHeadSchema = pwaSchema.pick({ startupImages: true }).extend({ name: z.string() });
23
28
  let cached;
24
29
  /** The app's PWA, or `null` when it is not installable right now. */
25
30
  function readPwa() {
@@ -49,7 +54,10 @@ function pwaMiddleware() {
49
54
  "content-type": "application/manifest+json",
50
55
  "cache-control": CACHE_CONTROL
51
56
  } });
52
- if (pathname === INSTALL_PATH) return Response.json(pwa.install, { headers: { "cache-control": CACHE_CONTROL } });
57
+ if (pathname === INSTALL_PATH) return Response.json({
58
+ ...pwa.install,
59
+ startupImages: pwa.startupImages
60
+ }, { headers: { "cache-control": CACHE_CONTROL } });
53
61
  try {
54
62
  const iconResponse = await fetch(pwa.install.iconUrl);
55
63
  if (!iconResponse.ok) return new Response(null, { status: 404 });
@@ -63,9 +71,21 @@ function pwaMiddleware() {
63
71
  }
64
72
  });
65
73
  }
74
+ let pendingInstallInfo;
66
75
  /**
67
- * The links that make the app installable: its manifest and its home screen
68
- * icon. Render it once, in `<head>` in the root route's `RootDocument`.
76
+ * What `/_softr/pwa.json` answers, or `null` when it does not. Callers that ask
77
+ * while a request is in flight share it; the next caller after it settles asks again.
78
+ */
79
+ function fetchInstallInfo() {
80
+ pendingInstallInfo ??= globalThis.fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then((response) => response.ok ? response.json() : null).catch(() => null).finally(() => {
81
+ pendingInstallInfo = void 0;
82
+ });
83
+ return pendingInstallInfo;
84
+ }
85
+ /**
86
+ * The tags that make the app installable: its manifest, its home screen icon,
87
+ * and, while the app is installable, the name and launch screens iOS shows.
88
+ * Render it once, in `<head>` in the root route's `RootDocument`.
69
89
  *
70
90
  * @example
71
91
  * function RootDocument({ children }: { children: React.ReactNode }) {
@@ -84,13 +104,39 @@ function pwaMiddleware() {
84
104
  * }
85
105
  */
86
106
  function SoftrPwaHead() {
107
+ const [iosHead, setIosHead] = useState(null);
108
+ useEffect(() => {
109
+ if (detectPlatform() !== "ios") return;
110
+ let cancelled = false;
111
+ fetchInstallInfo().then((installInfo) => {
112
+ const parsed = iosHeadSchema.safeParse(installInfo);
113
+ if (!parsed.success || cancelled) return;
114
+ setIosHead(parsed.data);
115
+ });
116
+ return () => {
117
+ cancelled = true;
118
+ };
119
+ }, []);
87
120
  return createElement(Fragment, null, createElement("link", {
88
121
  rel: "manifest",
89
122
  href: MANIFEST_PATH
90
123
  }), createElement("link", {
91
124
  rel: "apple-touch-icon",
92
125
  href: ICON_PATH
93
- }));
126
+ }), ...iosHead === null ? [] : [createElement("meta", {
127
+ key: "capable",
128
+ name: "apple-mobile-web-app-capable",
129
+ content: "yes"
130
+ }), createElement("meta", {
131
+ key: "title",
132
+ name: "apple-mobile-web-app-title",
133
+ content: iosHead.name
134
+ })], ...(iosHead?.startupImages ?? []).map((image) => createElement("link", {
135
+ key: image.href,
136
+ rel: "apple-touch-startup-image",
137
+ media: image.media,
138
+ href: image.href
139
+ })));
94
140
  }
95
141
  const installSchema = pwaSchema.shape.install;
96
142
  /**
@@ -111,16 +157,15 @@ function usePwaInstall() {
111
157
  useEffect(() => {
112
158
  if (isStandalone()) return;
113
159
  let cancelled = false;
114
- globalThis.fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then(async (response) => {
115
- if (!response.ok) return;
116
- const parsed = installSchema.safeParse(await response.json());
160
+ fetchInstallInfo().then((installInfo) => {
161
+ const parsed = installSchema.safeParse(installInfo);
117
162
  if (!parsed.success || cancelled) return;
118
163
  setInstall({
119
164
  available: true,
120
165
  platform: detectPlatform(),
121
166
  ...parsed.data
122
167
  });
123
- }).catch(() => {});
168
+ });
124
169
  return () => {
125
170
  cancelled = true;
126
171
  };
@@ -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,38 +1,16 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "1.3.0-alpha.0",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "exports": {
6
- ".": {
7
- "types": "./dist/index.d.ts",
8
- "import": "./dist/index.js"
9
- },
10
- "./client": {
11
- "types": "./dist/client.d.ts",
12
- "import": "./dist/client.js"
13
- },
14
- "./server": {
15
- "types": "./dist/server.d.ts",
16
- "import": "./dist/server.js"
17
- },
18
- "./vite": {
19
- "types": "./dist/vite.d.ts",
20
- "import": "./dist/vite.js"
21
- }
22
- },
23
- "bin": {
24
- "softr-sdk": "./dist/cli.js"
25
- },
26
- "files": [
27
- "dist",
28
- "schema",
29
- "skills",
30
- "!skills/_artifacts",
31
- "CHANGELOG.md"
32
- ],
33
- "publishConfig": {
34
- "access": "public"
35
- },
6
+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
7
+ "./client": { "types": "./dist/client.d.ts", "import": "./dist/client.js" },
8
+ "./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" },
9
+ "./vite": { "types": "./dist/vite.d.ts", "import": "./dist/vite.js" }
10
+ },
11
+ "bin": { "softr-sdk": "./dist/cli.js" },
12
+ "files": ["dist", "schema", "skills", "!skills/_artifacts", "CHANGELOG.md"],
13
+ "publishConfig": { "access": "public" },
36
14
  "scripts": {
37
15
  "build": "tsdown",
38
16
  "test": "node --import ./src/test-utils/setup.ts --test",
@@ -64,9 +42,7 @@
64
42
  "optional": true
65
43
  }
66
44
  },
67
- "keywords": [
68
- "tanstack-intent"
69
- ],
45
+ "keywords": ["tanstack-intent"],
70
46
  "intent": {
71
47
  "version": 1,
72
48
  "repo": "@softr/sdk",
@@ -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
@@ -33,7 +33,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
33
33
 
34
34
  | Import | Runs | Holds |
35
35
  | --- | --- | --- |
36
- | `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `defineAiAction`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `useIdleTimeout`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `usePushNotifications`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
36
+ | `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `defineAiAction`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `usePushNotifications`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
37
37
  | `@softr/sdk/server` | Server only | `ds`, `auth`, `workflow`, `integration`, `ai` |
38
38
  | `@softr/sdk/client` | Browser only | `useFileUpload` |
39
39
  | `@softr/sdk/vite` | Build | `softr()`, already in `vite.config.ts` |
@@ -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.
@@ -2,10 +2,10 @@
2
2
  name: pwa
3
3
  description: >-
4
4
  Let visitors install the app on their home screen: SoftrPwaHead for the
5
- manifest and icon links, usePwaInstall to decide whether to show an install
6
- button and which platform's steps to show, the PwaInstall and PwaPlatform
7
- types, and how to check that the app is installable. The manifest and icon are
8
- already served; never write them.
5
+ manifest, icon, iOS name and launch screen tags, usePwaInstall to decide
6
+ whether to show an install button and which platform's steps to show, the
7
+ PwaInstall and PwaPlatform types, and how to check that the app is
8
+ installable. The manifest and icon are already served; never write them.
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
@@ -16,7 +16,7 @@ metadata:
16
16
 
17
17
  The builder turns installing on in Studio, under Settings → Mobile app, and sets the name, colour and icon there. The app already answers with its manifest and icon once they do. What the app adds is two things: the links that point the browser at them, and a button that tells visitors how to install.
18
18
 
19
- > **CRITICAL**: Never write a web app manifest, icon files, a service worker, or `manifest` / `apple-touch-icon` links of your own, in `public/` or in `head()`. The app already serves them from Studio's settings, and a file of your own shadows those settings.
19
+ > **CRITICAL**: Never write a web app manifest, icon files, a service worker, or `manifest` / `apple-touch-icon` / `apple-touch-startup-image` links or an `apple-mobile-web-app-title` meta of your own, in `public/` or in `head()`. The app already serves them from Studio's settings, and a file or tag of your own shadows those settings.
20
20
  >
21
21
  > **CRITICAL**: Render an install button only while `usePwaInstall()` returns `available: true`. Never show it unconditionally, never cache the answer, never replace the check with your own. Softr can switch installing off for an app, and this check is the only way that reaches the button.
22
22
 
@@ -48,7 +48,7 @@ The builder switches installing on in Studio, and `usePwaInstall()` reads that s
48
48
 
49
49
  ### The links: `<SoftrPwaHead />`
50
50
 
51
- Render it once, in `<head>` next to `<HeadContent />`, in `RootDocument` in `src/routes/__root.tsx`.
51
+ Render it once, in `<head>` next to `<HeadContent />`, in `RootDocument` in `src/routes/__root.tsx`. While the app is installable it also renders the name iOS puts under the home screen icon and the iOS launch screens, so an installed app opens on its own splash screen instead of white.
52
52
 
53
53
  ```tsx
54
54
  function RootDocument({ children }: { children: React.ReactNode }) {
@@ -1,17 +0,0 @@
1
- //#region src/auth/idle-timeout.d.ts
2
- /**
3
- * Signs the visitor out of this browser after the idle time set in Studio's
4
- * "End session if idle", and sends them to `/`. Activity in any tab of the app
5
- * keeps the session alive. Does nothing for anonymous visitors.
6
- *
7
- * Call it once, in the root route's document component.
8
- *
9
- * @example
10
- * function RootDocument({ children }: { children: React.ReactNode }) {
11
- * useIdleTimeout()
12
- * // ...
13
- * }
14
- */
15
- declare function useIdleTimeout(): void;
16
- //#endregion
17
- export { useIdleTimeout };
@@ -1,200 +0,0 @@
1
- import { clearSession } from "./session.js";
2
- import { readSoftrContext } from "./context.js";
3
- import { settings } from "./methods/settings.js";
4
- import { useCurrentUser } from "./isomorphic.js";
5
- import { useEffect } from "react";
6
- import { createServerFn } from "@tanstack/react-start";
7
-
8
- //#region src/auth/idle-timeout.ts
9
- /**
10
- * The "End session if idle" setting from Studio, in milliseconds. `null` when it
11
- * does not apply: nobody is signed in, it is set to never, or this is not a
12
- * production build. Preview runs on a dev server and is the owner's own session.
13
- */
14
- const readIdleTimeout = createServerFn({ method: "GET" }).handler(async () => {
15
- if (process.env.NODE_ENV !== "production") return null;
16
- if (readSoftrContext().user === null) return null;
17
- const minutes = (await settings()).inactivityTimeoutMinutes;
18
- return minutes === null ? null : minutes * 6e4;
19
- });
20
- /**
21
- * Signs this browser out and nothing else. Unlike `auth.signOut()`, the user's
22
- * other devices stay signed in.
23
- */
24
- const endIdleSession = createServerFn({ method: "POST" }).handler(() => {
25
- clearSession();
26
- });
27
- /**
28
- * Signs the visitor out of this browser after the idle time set in Studio's
29
- * "End session if idle", and sends them to `/`. Activity in any tab of the app
30
- * keeps the session alive. Does nothing for anonymous visitors.
31
- *
32
- * Call it once, in the root route's document component.
33
- *
34
- * @example
35
- * function RootDocument({ children }: { children: React.ReactNode }) {
36
- * useIdleTimeout()
37
- * // ...
38
- * }
39
- */
40
- function useIdleTimeout() {
41
- const signedIn = useCurrentUser() !== null;
42
- useEffect(() => {
43
- if (!signedIn) return;
44
- let stop = null;
45
- let unmounted = false;
46
- readIdleTimeout().then((idleMs) => {
47
- if (unmounted || idleMs === null) return;
48
- stop = startIdleClock(idleMs);
49
- }, () => {});
50
- return () => {
51
- unmounted = true;
52
- stop?.();
53
- };
54
- }, [signedIn]);
55
- }
56
- const KEY_LAST_ACTIVITY = "softr.idle.v1.lastActivity";
57
- const KEY_SIGNED_OUT = "softr.idle.v1.signedOutAt";
58
- /** Shared clock writes at most this often, so a mousemove is not a storage write in every tab. */
59
- const WRITE_EVERY_MS = 5e3;
60
- /**
61
- * Activity events, listened for on the document in the capture phase. `scroll`
62
- * does not bubble, and capture still sees events a handler stops.
63
- */
64
- const ACTIVITY_EVENTS = [
65
- "pointerdown",
66
- "pointermove",
67
- "mousedown",
68
- "mousemove",
69
- "wheel",
70
- "keydown",
71
- "touchstart",
72
- "touchmove",
73
- "scroll",
74
- "click",
75
- "input",
76
- "focusin",
77
- "submit"
78
- ];
79
- /**
80
- * Starts the idle clock and returns what stops it.
81
- *
82
- * Idle time is checked against the wall clock on a tick, not with one long
83
- * timeout. Browsers delay timers in background tabs, and a laptop that wakes
84
- * from sleep resumes a pending timeout with its full delay left.
85
- */
86
- function startIdleClock(idleMs) {
87
- const tickMs = Math.min(15e3, Math.max(2e3, Math.floor(idleMs / 30)));
88
- const graceCapMs = idleMs;
89
- let localLast = Date.now();
90
- let lastWrite = 0;
91
- let graceUsed = 0;
92
- let ending = false;
93
- let finished = false;
94
- const listeners = new AbortController();
95
- function lastActivity() {
96
- const shared = Number(readStorage(KEY_LAST_ACTIVITY));
97
- return Number.isFinite(shared) && shared > localLast ? shared : localLast;
98
- }
99
- function mark(now) {
100
- if (now > localLast) localLast = now;
101
- if (now - lastWrite >= WRITE_EVERY_MS) {
102
- lastWrite = now;
103
- writeStorage(KEY_LAST_ACTIVITY, String(now));
104
- }
105
- }
106
- function onActivity() {
107
- graceUsed = 0;
108
- mark(Date.now());
109
- }
110
- function stop() {
111
- finished = true;
112
- clearInterval(ticker);
113
- listeners.abort();
114
- }
115
- function leave() {
116
- if (finished) return;
117
- stop();
118
- window.location.replace("/");
119
- }
120
- async function endSession() {
121
- if (ending) return;
122
- ending = true;
123
- try {
124
- await endIdleSession();
125
- } catch {
126
- ending = false;
127
- return;
128
- }
129
- writeStorage(KEY_SIGNED_OUT, String(Date.now()));
130
- leave();
131
- }
132
- function tick() {
133
- if (finished) return;
134
- if (readStorage(KEY_SIGNED_OUT)) {
135
- leave();
136
- return;
137
- }
138
- const now = Date.now();
139
- if (now - lastActivity() < idleMs) return;
140
- if (iframeHasFocus() && graceUsed < graceCapMs) {
141
- graceUsed += tickMs;
142
- mark(now);
143
- return;
144
- }
145
- endSession();
146
- }
147
- removeStorage(KEY_SIGNED_OUT);
148
- mark(Date.now());
149
- const ticker = setInterval(tick, tickMs);
150
- const { signal } = listeners;
151
- for (const event of ACTIVITY_EVENTS) document.addEventListener(event, onActivity, {
152
- capture: true,
153
- passive: true,
154
- signal
155
- });
156
- window.addEventListener("focus", onActivity, {
157
- capture: true,
158
- signal
159
- });
160
- document.addEventListener("visibilitychange", () => {
161
- if (document.visibilityState !== "visible") return;
162
- tick();
163
- if (!finished && !ending) onActivity();
164
- }, { signal });
165
- window.addEventListener("storage", (event) => {
166
- if (event.key === KEY_SIGNED_OUT && event.newValue) {
167
- leave();
168
- return;
169
- }
170
- if (event.key === KEY_LAST_ACTIVITY && event.newValue) {
171
- const shared = Number(event.newValue);
172
- if (Number.isFinite(shared) && shared > localLast) localLast = shared;
173
- }
174
- }, { signal });
175
- return stop;
176
- }
177
- function iframeHasFocus() {
178
- const active = document.activeElement;
179
- return active !== null && active.tagName === "IFRAME" && document.hasFocus();
180
- }
181
- function readStorage(key) {
182
- try {
183
- return window.localStorage.getItem(key);
184
- } catch {
185
- return null;
186
- }
187
- }
188
- function writeStorage(key, value) {
189
- try {
190
- window.localStorage.setItem(key, value);
191
- } catch {}
192
- }
193
- function removeStorage(key) {
194
- try {
195
- window.localStorage.removeItem(key);
196
- } catch {}
197
- }
198
-
199
- //#endregion
200
- export { useIdleTimeout };