@softr/sdk 1.3.0-alpha.0 → 1.3.1

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 (43) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/dist/auth/isomorphic.d.ts +11 -4
  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 +13 -2
  15. package/dist/formatting.d.ts +3 -3
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +2 -2
  18. package/dist/mcp.d.ts +2 -2
  19. package/dist/package.js +1 -1
  20. package/dist/pwa.d.ts +5 -4
  21. package/dist/pwa.js +54 -9
  22. package/dist/softr-config.schema.js +2 -1
  23. package/package.json +10 -34
  24. package/schema/softr.schema.json +10 -1
  25. package/skills/softr-sdk/SKILL.md +2 -2
  26. package/skills/softr-sdk/ai/SKILL.md +1 -1
  27. package/skills/softr-sdk/auth/SKILL.md +1 -1
  28. package/skills/softr-sdk/auth/references/single-sign-on.md +50 -0
  29. package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
  30. package/skills/softr-sdk/current-user/SKILL.md +1 -1
  31. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  32. package/skills/softr-sdk/formatting/SKILL.md +1 -1
  33. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  34. package/skills/softr-sdk/mcp/SKILL.md +1 -1
  35. package/skills/softr-sdk/push-notifications/SKILL.md +1 -1
  36. package/skills/softr-sdk/pwa/SKILL.md +7 -7
  37. package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
  38. package/skills/softr-sdk/record-queries/SKILL.md +1 -1
  39. package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
  40. package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
  41. package/skills/softr-sdk/workflows/SKILL.md +1 -1
  42. package/dist/auth/idle-timeout.d.ts +0 -17
  43. package/dist/auth/idle-timeout.js +0 -200
package/CHANGELOG.md CHANGED
@@ -1,10 +1,22 @@
1
1
  # @softr/sdk
2
2
 
3
+ ## 1.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Send the visitor's IP, signed, with calls to the Softr platform, so apps can log users out when the country they use the app from changes.
8
+
3
9
  ## 1.3.0
4
10
 
5
11
  ### Minor Changes
6
12
 
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()`.
13
+ - 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.
14
+
15
+ ## 1.2.2
16
+
17
+ ### Patch Changes
18
+
19
+ - `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
20
 
9
21
  ## 1.2.1
10
22
 
@@ -3,7 +3,7 @@ import { Formatting } from "../formatting.js";
3
3
  import { SoftrContext } from "./context.js";
4
4
  import * as react0 from "react";
5
5
  import { ReactNode } from "react";
6
- import * as _tanstack_react_start0 from "@tanstack/react-start";
6
+ import * as _tanstack_react_start1 from "@tanstack/react-start";
7
7
 
8
8
  //#region src/auth/isomorphic.d.ts
9
9
 
@@ -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_start1.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start1.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start1.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start1.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start1.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start1.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start1.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start1.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
25
25
  user: User | null;
26
26
  permissions: {
27
27
  datasources: {};
@@ -37,7 +37,7 @@ declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddleware
37
37
  * beforeLoad: async () => await getSoftrContext(),
38
38
  * })
39
39
  */
40
- declare const getSoftrContext: _tanstack_react_start0.OptionalFetcher<undefined, undefined, Promise<SoftrContext>>;
40
+ declare const getSoftrContext: _tanstack_react_start1.OptionalFetcher<undefined, undefined, Promise<SoftrContext>>;
41
41
  /**
42
42
  * The context to hand `createRouter`, before any request has resolved one.
43
43
  *
@@ -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. */
@@ -85,7 +92,7 @@ type AuthOptions = {
85
92
  * staleTime: 60_000,
86
93
  * })
87
94
  */
88
- declare const getAuthSettings: _tanstack_react_start0.OptionalFetcher<undefined, undefined, Promise<AuthOptions>>;
95
+ declare const getAuthSettings: _tanstack_react_start1.OptionalFetcher<undefined, undefined, Promise<AuthOptions>>;
89
96
  /**
90
97
  * Makes the auth options readable with {@link useAuthSettings} anywhere below.
91
98
  *
@@ -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";
17
+ import { getRequestHeader } from "@tanstack/react-start/server";
16
18
  import { createContext, useContext } from "react";
17
19
  import { createMiddleware, createServerFn } from "@tanstack/react-start";
18
- 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";
6
7
  import { z } from "zod";
7
8
  import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
8
9
  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) {