@midsummer-ai/sdk 0.1.0-staging.3781 → 0.1.0-staging.3784

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.
@@ -3,8 +3,9 @@ import { d as userToken, o as connect, s as databaseUrl } from "./client-CrJkXd5
3
3
  import { sendSignInMail } from "./auth/mail.mjs";
4
4
  import "./files-DhPeWwcT.mjs";
5
5
  import { standIn } from "./auth/stand-in.mjs";
6
- import { a as ourWords, c as agentOfToken, d as credentialOf, f as remembering, l as challenge, n as REFUSALS, p as resourceOf, r as buildEngine, s as agentOfKey, t as JoinRefused, u as consentPage } from "./engine-o-3LFoL3.mjs";
7
- import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as setupKeyOf, n as qrSvg, o as ago, r as AUTH_CSS, s as defaultAppName } from "./qr-Br1sOBmT.mjs";
6
+ import { a as ourWords, c as agentOfToken, d as credentialOf, f as remembering, l as challenge, n as REFUSALS, p as resourceOf, r as buildEngine, s as agentOfKey, t as JoinRefused, u as consentPage } from "./engine-9WBvqNSV.mjs";
7
+ import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as screenName, n as textOn, o as ago, r as GEIST_WOFF2, s as defaultAppName, t as authCss, u as setupKeyOf } from "./style-CCFT-5rG.mjs";
8
+ import { i as iconSvg, n as qrSvg } from "./qr-BySxqLW6.mjs";
8
9
  //#region src/auth/store.ts
9
10
  const KIND = {
10
11
  create: "mutation",
@@ -623,10 +624,22 @@ function redirectOf(url) {
623
624
  const asked = url.searchParams.get("redirect") ?? "/";
624
625
  return asked.startsWith("/") && !asked.startsWith("//") && !asked.startsWith("/\\") ? asked : "/";
625
626
  }
627
+ let fontBytes;
628
+ /** The screens' typeface, kept for as long as a browser likes: it changes only with the SDK. */
629
+ function font() {
630
+ fontBytes ??= Uint8Array.from(atob(GEIST_WOFF2), (c) => c.charCodeAt(0));
631
+ return new Response(fontBytes, { headers: {
632
+ "Content-Type": "font/woff2",
633
+ "Cache-Control": "public, max-age=31536000, immutable",
634
+ "Access-Control-Allow-Origin": "*"
635
+ } });
636
+ }
626
637
  /** One hosted page, by its path under `/api/auth/ui`. */
627
638
  async function hostedPage(request, path, deps) {
639
+ if (path === "/font.woff2" && request.method === "GET") return font();
628
640
  const url = new URL(request.url), origin = url.origin;
629
641
  const settings = deps.settings, app = settings.branding.name;
642
+ const named = screenName(app, [url.hostname]);
630
643
  const cookie = request.headers.get("cookie") ?? "";
631
644
  const nonce = btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
632
645
  const cookies = [];
@@ -688,14 +701,30 @@ async function hostedPage(request, path, deps) {
688
701
  headers
689
702
  });
690
703
  };
691
- const shell = (title, body, options = {}) => page({
704
+ /** A sign-in screen in its card, with the scripts its forms need: showing a password, and `script` when given. */
705
+ const screen = (title, body, options = {}) => page({
706
+ title,
707
+ nonce,
708
+ settings,
709
+ script: [revealScript(), options.script ?? ""].filter(Boolean).join(";"),
710
+ body: card(settings, title, body, options.leadHtml ?? (options.lead ? escape(options.lead) : void 0))
711
+ });
712
+ /** A settings page: the way back, the header and its panels, with Copy and, when on, adding a passkey. */
713
+ const settingsPage = (title, body, script = "") => page({
692
714
  title,
693
- body,
694
715
  nonce,
695
716
  settings,
696
- ...options
717
+ wide: true,
718
+ script: [copyScript(), script].filter(Boolean).join(";"),
719
+ body: `<div class="msa-page">${back(named, redirect)}${body}</div>`
697
720
  });
698
721
  const redirect = redirectOf(url);
722
+ const here = (extra = {}) => {
723
+ const next = new URL(url);
724
+ for (const [key, value] of Object.entries(extra)) if (value === null) next.searchParams.delete(key);
725
+ else next.searchParams.set(key, value);
726
+ return `${next.pathname}${next.search}`;
727
+ };
699
728
  const oauthQuery = url.searchParams.has("sig") ? url.search.slice(1) : void 0;
700
729
  const withOauth = (body) => oauthQuery ? {
701
730
  ...body,
@@ -704,26 +733,27 @@ async function hostedPage(request, path, deps) {
704
733
  /** Where a sign-in goes on to: the MCP client's page that asks, when it came from one, else `redirect`. */
705
734
  const onward = (answer) => typeof answer?.next === "string" ? answer.next : answer?.redirect === true && typeof answer.url === "string" ? answer.url : redirect;
706
735
  const captchaToken = () => settings.captcha ? form[CAPTCHA_WIDGETS[settings.captcha.provider].field] : void 0;
736
+ const backToSignIn = links([`<a class="msa-link" href="${UI}/sign-in${escape(url.search)}">${escape(WORDS.confirm.back)}</a>`]);
707
737
  switch (path.replace(/\/+$/, "")) {
708
738
  case "/sign-in": {
709
- let problem = "", notice = "";
739
+ let problem = "";
740
+ const email = (form.email ?? "").trim();
710
741
  if (request.method === "POST") {
711
- const email = (form.email ?? "").trim();
712
742
  if (form.action === "password") {
713
743
  const signed = await call("/sign-in", withOauth({
714
744
  email,
715
745
  password: form.password ?? ""
716
746
  }), captchaToken());
717
747
  if (signed.ok && signed.json?.twoFactor) return away(`${UI}/two-factor${url.search}`);
718
- if (signed.ok && signed.json?.verifyEmail) notice = WORDS.confirm.sent(email);
719
- else if (signed.ok) return away(onward(signed.json));
720
- else problem = signed.message;
748
+ if (signed.ok && signed.json?.verifyEmail) return respond(screen(WORDS.confirm.title, `${note(WORDS.confirm.sent, email)}${backToSignIn}`));
749
+ if (signed.ok) return away(onward(signed.json));
750
+ problem = signed.message;
721
751
  } else if (form.action === "code") {
722
752
  const sent = await call("/email-otp/send-verification-otp", {
723
753
  email,
724
754
  type: "sign-in"
725
755
  }, captchaToken());
726
- if (sent.ok) return respond(shell(WORDS.signIn.title(app), codeForm(email, ""), { lead: WORDS.code.sent(email) }));
756
+ if (sent.ok) return respond(screen(WORDS.code.title, codeForm(email, "", url.search), { leadHtml: codeLead(email) }));
727
757
  problem = sent.message;
728
758
  } else if (form.action === "verify") {
729
759
  const signed = await call("/sign-in/email-otp", withOauth({
@@ -731,14 +761,14 @@ async function hostedPage(request, path, deps) {
731
761
  otp: (form.code ?? "").trim()
732
762
  }));
733
763
  if (signed.ok) return away(onward(signed.json));
734
- return respond(shell(WORDS.signIn.title(app), codeForm(email, signed.message), { lead: WORDS.code.sent(email) }), signed.status);
764
+ return respond(screen(WORDS.code.title, codeForm(email, signed.message, url.search), { leadHtml: codeLead(email) }), signed.status);
735
765
  } else if (form.action === "link") {
736
766
  const sent = await call("/sign-in/magic-link", {
737
767
  email,
738
768
  callbackURL: redirect
739
769
  }, captchaToken());
740
- if (sent.ok) notice = WORDS.link.sent(email);
741
- else problem = sent.message;
770
+ if (sent.ok) return respond(screen(WORDS.link.title, `${note(WORDS.link.sent, email)}${links([`<a class="msa-link" href="${UI}/sign-in${escape(url.search)}">${escape(WORDS.code.differentEmail)}</a>`])}`));
771
+ problem = sent.message;
742
772
  } else if (form.action === "google" || form.action === "github") {
743
773
  const started = await call("/sign-in/social", {
744
774
  provider: form.action,
@@ -748,7 +778,7 @@ async function hostedPage(request, path, deps) {
748
778
  problem = started.message;
749
779
  }
750
780
  }
751
- return respond(shell(WORDS.signIn.title(app), notice ? `<p class="msa-note" role="status">${escape(notice)}</p>${backTo(url.search)}` : signInForm(settings, problem, url.search), { script: settings.methods.passkey ? passkeyScript("sign-in", redirect) : "" }), problem ? 400 : 200);
781
+ return respond(screen(WORDS.signIn.title(named), signInForm(settings, problem, url.search, email), { script: settings.methods.passkey ? passkeyScript("sign-in", redirect) : "" }), problem ? 400 : 200);
752
782
  }
753
783
  case "/two-factor": {
754
784
  let problem = "";
@@ -763,11 +793,12 @@ async function hostedPage(request, path, deps) {
763
793
  problem = checked.message;
764
794
  }
765
795
  }
766
- const mailed = form.action === "send" || form.action === "mail-code";
767
- return respond(shell(WORDS.twoFactor.title, twoFactorForm(problem, mailed), { lead: mailed ? WORDS.twoFactor.mailed : WORDS.twoFactor.lead }), problem ? 400 : 200);
796
+ const way = form.action === "send" || form.action === "mail-code" ? "mail" : form.action === "backup" || url.searchParams.get("way") === "backup" ? "backup" : "app";
797
+ const lead = way === "mail" ? WORDS.twoFactor.mailed : way === "backup" ? WORDS.twoFactor.backupLead : WORDS.twoFactor.lead;
798
+ return respond(screen(WORDS.twoFactor.title, twoFactorForm(problem, way, here), { lead }), problem ? 400 : 200);
768
799
  }
769
800
  case "/sign-up": {
770
- let problem = "", notice = "";
801
+ let problem = "";
771
802
  if (request.method === "POST") {
772
803
  const email = (form.email ?? "").trim();
773
804
  const made = await call("/sign-up", withOauth({
@@ -775,12 +806,12 @@ async function hostedPage(request, path, deps) {
775
806
  email,
776
807
  password: form.password ?? ""
777
808
  }), captchaToken());
778
- if (made.ok && made.json?.verifyEmail) notice = WORDS.confirm.sent(email);
779
- else if (made.ok) return away(onward(made.json));
780
- else if (made.json?.code === "SIGN_UP_WAITLIST") notice = made.message;
781
- else problem = made.message;
809
+ if (made.ok && made.json?.verifyEmail) return respond(screen(WORDS.confirm.title, `${note(WORDS.confirm.sent, email)}${backToSignIn}`));
810
+ if (made.ok) return away(onward(made.json));
811
+ if (made.json?.code === "SIGN_UP_WAITLIST") return respond(screen(WORDS.signUp.waiting, `${note([WORDS.signUp.waitingLead, ` ${WORDS.signUp.waitingEnd}`], email)}${backToSignIn}`));
812
+ problem = made.message;
782
813
  }
783
- return respond(shell(WORDS.signUp.title(app), notice ? `<p class="msa-note" role="status">${escape(notice)}</p>${backTo(url.search)}` : signUpForm(settings, problem, url.search), settings.signUp.policy === "invite" ? { lead: WORDS.signUp.invite } : {}), problem ? 400 : 200);
814
+ return respond(screen(WORDS.signUp.title(named), signUpForm(settings, problem, url.search, form), settings.signUp.policy === "invite" ? { lead: WORDS.signUp.invite } : {}), problem ? 400 : 200);
784
815
  }
785
816
  case "/reset-password": {
786
817
  const token = url.searchParams.get("token");
@@ -790,10 +821,10 @@ async function hostedPage(request, path, deps) {
790
821
  token,
791
822
  newPassword: form.password ?? ""
792
823
  });
793
- if (reset.ok) return respond(shell(WORDS.reset.title, `<p class="msa-note" role="status">${escape(WORDS.reset.done)}</p><p class="msa-foot"><a href="${UI}/sign-in">${escape(WORDS.signIn.submit)}</a></p>`));
794
- return respond(shell(WORDS.reset.choose, newPasswordForm(reset.message)), 400);
824
+ if (reset.ok) return respond(screen(WORDS.reset.doneTitle, `<a class="msa-button msa-primary msa-block" href="${UI}/sign-in">${escape(WORDS.signIn.submit)}</a>`, { lead: WORDS.reset.done }));
825
+ return respond(screen(WORDS.reset.choose, newPasswordForm(reset.message)), 400);
795
826
  }
796
- return respond(shell(WORDS.reset.choose, newPasswordForm("")));
827
+ return respond(screen(WORDS.reset.choose, newPasswordForm("")));
797
828
  }
798
829
  if (request.method === "POST") {
799
830
  const email = (form.email ?? "").trim();
@@ -801,20 +832,19 @@ async function hostedPage(request, path, deps) {
801
832
  email,
802
833
  redirectTo: `${UI}/reset-password`
803
834
  }, captchaToken());
804
- if (asked.ok) return respond(shell(WORDS.reset.title, `<p class="msa-note" role="status">${escape(WORDS.reset.sent(email))}</p>`));
805
- return respond(shell(WORDS.reset.title, resetForm(settings, asked.message), { lead: WORDS.reset.lead }), 400);
835
+ if (asked.ok) return respond(screen(WORDS.reset.sentTitle, `${note(WORDS.reset.sent, email)}${backToSignIn}`));
836
+ return respond(screen(WORDS.reset.title, resetForm(settings, asked.message, email), { lead: WORDS.reset.lead }), 400);
806
837
  }
807
- return respond(shell(WORDS.reset.title, resetForm(settings, ""), { lead: WORDS.reset.lead }));
838
+ return respond(screen(WORDS.reset.title, resetForm(settings, "", ""), { lead: WORDS.reset.lead }));
808
839
  }
809
840
  case "/account": {
810
841
  const signedIn = (await call("/session")).json;
811
842
  if (!signedIn) return away(`${UI}/sign-in?redirect=${encodeURIComponent(`${UI}/account`)}`);
812
- let problem = "", notice = "", shown = "";
843
+ let problem = "", shown = "";
813
844
  if (request.method === "POST") {
814
- const done = async (work, said = WORDS.account.saved) => {
845
+ const done = async (work) => {
815
846
  const result = await work;
816
- if (result.ok) notice = said;
817
- else problem = result.message;
847
+ if (!result.ok) problem = result.message;
818
848
  return result;
819
849
  };
820
850
  switch (form.action) {
@@ -826,7 +856,7 @@ async function hostedPage(request, path, deps) {
826
856
  currentPassword: form.current ?? "",
827
857
  newPassword: form.next ?? "",
828
858
  revokeOtherSessions: true
829
- }), WORDS.account.passwordChanged);
859
+ }));
830
860
  break;
831
861
  case "two-factor-on": {
832
862
  const enabled = await call("/two-factor/enable", { password: form.password ?? "" });
@@ -843,6 +873,9 @@ async function hostedPage(request, path, deps) {
843
873
  case "session-revoke":
844
874
  await done(call("/revoke-session", { token: form.token ?? "" }));
845
875
  break;
876
+ case "sessions-revoke":
877
+ await done(call("/revoke-other-sessions", {}));
878
+ break;
846
879
  case "sign-out":
847
880
  await call("/sign-out", {});
848
881
  return away("/");
@@ -854,7 +887,7 @@ async function hostedPage(request, path, deps) {
854
887
  name: (form.name ?? "").trim(),
855
888
  scopes: Object.keys(form).filter((key) => key.startsWith("scope:")).map((key) => key.slice(6))
856
889
  });
857
- if (made.ok) shown = `<div class="msa-stack"><p class="msa-note" role="status">${escape(WORDS.account.keyShown)}</p>${secret(WORDS.account.keys, String(made.json?.key ?? ""))}</div>`;
890
+ if (made.ok) shown = row(WORDS.account.keyShown, "", "", secret(WORDS.account.keys, String(made.json?.key ?? "")));
858
891
  else problem = made.message;
859
892
  break;
860
893
  }
@@ -872,7 +905,7 @@ async function hostedPage(request, path, deps) {
872
905
  call("/account/grants").then((one) => Array.isArray(one.json) ? one.json : [])
873
906
  ]);
874
907
  const failed = problem ? SECTION_OF[form.action ?? ""] ?? "profile" : "";
875
- return respond(shell(WORDS.account.title, back(app, redirect) + accountBody({
908
+ return respond(settingsPage(WORDS.account.title, accountBody({
876
909
  settings,
877
910
  scopes: deps.scopes,
878
911
  signedIn: session,
@@ -882,14 +915,9 @@ async function hostedPage(request, path, deps) {
882
915
  grants,
883
916
  problem,
884
917
  failed,
885
- notice,
886
918
  shown,
887
919
  made: form.action ?? ""
888
- }), {
889
- lead: String(session.user.email),
890
- wide: true,
891
- script: [copyScript(), settings.methods.passkey ? passkeyScript("add", `${UI}/account`) : ""].join(";")
892
- }), problem ? 400 : 200);
920
+ }), settings.methods.passkey ? passkeyScript("add", `${UI}/account`) : ""), problem ? 400 : 200);
893
921
  }
894
922
  case "/organization": {
895
923
  const signedIn = (await call("/session")).json;
@@ -946,39 +974,38 @@ async function hostedPage(request, path, deps) {
946
974
  }
947
975
  const organizations = (await call("/organization/list")).json ?? [];
948
976
  const full = id ? (await call(`/organization/get-full-organization?organizationId=${encodeURIComponent(id)}`)).json : null;
949
- return respond(shell(full ? String(full.name) : WORDS.organizations.switch, back(app, redirect) + organizationBody({
977
+ return respond(settingsPage(full ? String(full.name) : WORDS.organizations.all, organizationBody({
950
978
  organizations,
951
979
  full,
952
980
  userId: String(signedIn.user.id),
953
981
  activeId: id,
954
- problem
955
- }), { wide: true }), problem ? 400 : 200);
982
+ problem,
983
+ failed: problem ? form.action ?? "" : ""
984
+ })), problem ? 400 : 200);
956
985
  }
957
986
  default: {
958
987
  const invitation = /^\/invitation\/([A-Za-z0-9_-]{1,100})$/.exec(path)?.[1];
959
- if (!invitation) return respond(shell(WORDS.errors.notFound, `<p class="msa-note">${escape(WORDS.errors.nothingHere)}</p><p class="msa-foot"><a href="${UI}/sign-in">${escape(WORDS.signIn.submit)}</a></p>`), 404);
960
- if (!(await call("/session")).json) return respond(shell(WORDS.invitation.title(app), `<p class="msa-note">${escape(WORDS.invitation.signInFirst)}</p><div class="msa-stack"><a href="${UI}/sign-in?redirect=${encodeURIComponent(path === "" ? "/" : `${UI}${path}`)}">${escape(WORDS.signIn.submit)}</a><a href="${UI}/sign-up?redirect=${encodeURIComponent(`${UI}${path}`)}">${escape(WORDS.signIn.signUp)}</a></div>`));
988
+ if (!invitation) return respond(screen(WORDS.errors.notFound, `${paragraph(WORDS.errors.nothingHere)}<a class="msa-button msa-secondary msa-block" href="${UI}/sign-in">${escape(WORDS.signIn.submit)}</a>`), 404);
989
+ if (!(await call("/session")).json) return respond(screen(WORDS.invitation.anyTitle, `<div class="msa-form"><a class="msa-button msa-primary msa-block" href="${UI}/sign-in?redirect=${encodeURIComponent(`${UI}${path}`)}">${escape(WORDS.signIn.submit)}</a><a class="msa-button msa-secondary msa-block" href="${UI}/sign-up?redirect=${encodeURIComponent(`${UI}${path}`)}">${escape(WORDS.invitation.createAccount)}</a></div>`, { lead: WORDS.invitation.signInFirst }));
961
990
  if (request.method === "POST") {
962
991
  const answered = await call(form.action === "reject" ? "/organization/reject-invitation" : "/organization/accept-invitation", { invitationId: invitation });
963
992
  if (answered.ok) return away(form.action === "reject" ? "/" : `${UI}/organization`);
964
- return respond(shell(WORDS.invitation.title(app), `<p class="msa-error" role="alert">${escape(answered.message)}</p>`), 400);
993
+ return respond(screen(WORDS.invitation.goneTitle, `<p class="msa-error" role="alert">${escape(answered.message)}</p>`), 400);
965
994
  }
966
995
  const found = await call(`/organization/get-invitation?id=${encodeURIComponent(invitation)}`);
967
- if (!found.ok || !found.json) return respond(shell(WORDS.invitation.title(app), `<p class="msa-note">${escape(WORDS.invitation.gone)}</p>`), 404);
996
+ if (!found.ok || !found.json) return respond(screen(WORDS.invitation.goneTitle, paragraph(WORDS.invitation.gone)), 404);
968
997
  const name = String(found.json.organizationName ?? app);
969
- return respond(shell(WORDS.invitation.title(name), `<form method="post"><button class="msa-primary" name="action" value="accept">${escape(WORDS.invitation.accept)}</button><button class="msa-quiet" name="action" value="reject">${escape(WORDS.invitation.reject)}</button></form>`, { lead: WORDS.invitation.lead(typeof found.json.inviterEmail === "string" ? found.json.inviterEmail : void 0, name, app) }));
998
+ return respond(screen(WORDS.invitation.title(name), `<form method="post" class="msa-form"><button class="msa-button msa-primary msa-block" name="action" value="accept">${escape(WORDS.invitation.accept)}</button><button class="msa-button msa-secondary msa-block" name="action" value="reject">${escape(WORDS.invitation.reject)}</button></form>`, { leadHtml: invitationLead(typeof found.json.inviterEmail === "string" ? found.json.inviterEmail : void 0, name, named) }));
970
999
  }
971
1000
  }
972
- function codeForm(email, problem) {
973
- return `<form method="post"><input type="hidden" name="email" value="${escape(email)}"><label>${escape(WORDS.fields.code)}<input name="code" required autocomplete="one-time-code" inputmode="numeric" autofocus></label><p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary" name="action" value="verify">${escape(WORDS.code.submit)}</button></form>`;
974
- }
975
1001
  }
976
- /** What a hosted page may load: its own styles, the person's own address for forms, and the bot check when set. */
1002
+ /** What a hosted page may load: its own styles and font, the person's own address for forms, and the bot check when set. */
977
1003
  function csp(nonce, settings) {
978
1004
  const captcha = settings.captcha ? new URL(CAPTCHA_WIDGETS[settings.captcha.provider].script).origin : "";
979
1005
  return [
980
1006
  `default-src 'none'`,
981
1007
  `style-src 'unsafe-inline'`,
1008
+ `font-src 'self'`,
982
1009
  `img-src https: data:`,
983
1010
  `script-src 'nonce-${nonce}'${captcha ? ` ${captcha}` : ""}`,
984
1011
  `frame-src ${captcha || "'none'"}`,
@@ -988,76 +1015,202 @@ function csp(nonce, settings) {
988
1015
  `base-uri 'none'`
989
1016
  ].join("; ");
990
1017
  }
1018
+ /** A whole page: the stylesheet, the app's colour as the brand, the body and its script under the page's nonce. */
991
1019
  function page(input) {
992
1020
  const { settings } = input;
993
1021
  const captcha = settings.captcha ? `<script src="${escape(CAPTCHA_WIDGETS[settings.captcha.provider].script)}" async defer><\/script>` : "";
994
- const brand = settings.branding.color ? ` style="--msa-brand:${escape(settings.branding.color)}"` : "";
1022
+ const color = settings.branding.color;
1023
+ const brand = color ? ` style="--msa-app-brand:${escape(color)};--msa-app-brand-text:${textOn(color)}"` : "";
995
1024
  return `<!doctype html>
996
1025
  <html lang="en">
997
1026
  <head>
998
1027
  <meta charset="utf-8">
999
1028
  <meta name="viewport" content="width=device-width, initial-scale=1">
1000
1029
  <meta name="robots" content="noindex">
1030
+ <meta name="color-scheme" content="light dark">
1001
1031
  <title>${escape(input.title)} · ${escape(settings.branding.name)}</title>
1002
- <style>body{margin:0;min-height:100vh;display:grid;place-items:center;padding:24px 16px;background:#fafafa;font-family:system-ui,-apple-system,sans-serif}@media (prefers-color-scheme:dark){body{background:#09090b}}${AUTH_CSS}</style>
1032
+ <style>${authCss()}</style>
1003
1033
  ${captcha}
1004
1034
  </head>
1005
- <body>
1006
- <main class="msa"${brand}>
1007
- <div class="msa-card${input.wide ? " msa-wide" : ""}">
1008
- ${settings.branding.logo ? `<img class="msa-logo" src="${escape(settings.branding.logo)}" alt="${escape(settings.branding.name)}">` : ""}
1009
- <h1>${escape(input.title)}</h1>
1010
- ${input.lead ? `<p class="msa-lead">${escape(input.lead)}</p>` : ""}
1035
+ <body class="msa msa-screen${input.wide ? " msa-screen-wide" : ""}"${brand}>
1011
1036
  ${input.body}
1012
- </div>
1013
- </main>
1014
1037
  ${input.script ? `<script nonce="${input.nonce}">${input.script}<\/script>` : ""}
1015
1038
  </body>
1016
1039
  </html>
1017
1040
  `;
1018
1041
  }
1042
+ /** A sign-in screen's card: the app's logo, the title and the line under it (`lead`, as markup), then the screen. */
1043
+ function card(settings, title, body, lead) {
1044
+ return `<main class="msa-card" aria-labelledby="msa-title"><header class="msa-head">${settings.branding.logo ? `<img class="msa-logo" src="${escape(settings.branding.logo)}" alt="${escape(settings.branding.name)}">` : ""}<div class="msa-titles"><h1 id="msa-title" class="msa-title">${escape(title)}</h1>${lead ? `<p class="msa-lead">${lead}</p>` : ""}</div></header><div class="msa-body">${body}</div></main>`;
1045
+ }
1019
1046
  /** The way back to the app from a page a person was sent to. */
1020
- const back = (app, to) => `<a class="msa-back" href="${escape(to)}">${escape(WORDS.account.back(app))}</a>`;
1047
+ const back = (app, to) => `<a class="msa-link msa-back" href="${escape(to)}">${escape(WORDS.account.back(app))}</a>`;
1048
+ const paragraph = (text) => `<p class="msa-note">${escape(text)}</p>`;
1049
+ /** A sentence about an address, set apart in it: `[before, after]` around it. */
1050
+ const note = (words, subject) => `<p class="msa-note" role="status">${escape(words[0])} <span class="msa-subject msa-inline">${escape(subject)}</span>${escape(words[1].startsWith(".") ? words[1] : ` ${words[1].trimStart()}`)}</p>`;
1051
+ /** Who invited the person, to what and where, the inviter and the organization set apart. */
1052
+ const invitationLead = (inviter, organization, app) => {
1053
+ const [middle, end] = WORDS.invitation.lead(app);
1054
+ return `<span class="msa-subject msa-inline">${escape(inviter ?? WORDS.invitation.someone)}</span> ${escape(middle)} <span class="msa-subject msa-inline">${escape(organization)}</span>${end === "." ? "." : ` ${escape(end)}`}`;
1055
+ };
1056
+ const codeLead = (email) => `${escape(WORDS.code.lead)} <span class="msa-subject">${escape(email)}</span>`;
1057
+ /** Quiet actions on one line, parted by dots. */
1058
+ const links = (items, align) => `<div class="msa-links"${align ? ` data-align="${align}"` : ""}>${items.filter(Boolean).join("<span aria-hidden=\"true\">·</span>")}</div>`;
1059
+ const problemLine = (problem) => `<p class="msa-error" role="alert">${escape(problem)}</p>`;
1060
+ let fields = 0;
1061
+ /** A labelled field; a password one has a button to show what is typed. */
1062
+ function field(input) {
1063
+ const id = `msa-field-${++fields}`;
1064
+ const attributes = [
1065
+ `id="${id}"`,
1066
+ `class="msa-input"`,
1067
+ `type="${input.type ?? "text"}"`,
1068
+ `name="${input.name}"`,
1069
+ input.required === false ? "" : "required",
1070
+ input.autocomplete ? `autocomplete="${input.autocomplete}"` : "",
1071
+ input.placeholder ? `placeholder="${escape(input.placeholder)}"` : "",
1072
+ input.value ? `value="${escape(input.value)}"` : "",
1073
+ input.autofocus ? "autofocus" : "",
1074
+ input.minlength ? `minlength="${input.minlength}"` : "",
1075
+ input.type === "email" ? `spellcheck="false" autocapitalize="none"` : ""
1076
+ ].filter(Boolean).join(" ");
1077
+ const label = `<label class="msa-label" for="${id}">${escape(input.label)}</label>`;
1078
+ const control = input.type === "password" ? `<div class="msa-secret-field"><input ${attributes}><button type="button" class="msa-reveal" aria-label="Show password" aria-pressed="false" data-msa-reveal>${iconSvg("eye")}${iconSvg("eyeSlash")}</button></div>` : `<input ${attributes}>`;
1079
+ return `<div class="msa-field">${input.aside ? `<div class="msa-label-row">${label}${input.aside}</div>` : label}${control}</div>`;
1080
+ }
1081
+ /** The code from a mail or an authenticator app, its label for screen readers: the line above explains it. */
1082
+ function codeField() {
1083
+ const id = `msa-field-${++fields}`;
1084
+ const boxes = Array.from({ length: 6 }, (_, index) => `<span class="msa-otp-box"${index ? "" : " data-active"}></span>`).join("");
1085
+ return `<div class="msa-field"><label class="msa-sr" for="${id}">${escape(WORDS.fields.code)}</label><div class="msa-otp"><input id="${id}" class="msa-input msa-code" name="code" required autocomplete="one-time-code" inputmode="numeric" maxlength="6" spellcheck="false" placeholder="${WORDS.placeholders.code}" autofocus><div class="msa-otp-boxes" aria-hidden="true">${boxes}</div></div></div>`;
1086
+ }
1087
+ const submit = (label, action) => `<button class="msa-button msa-primary msa-block"${action ? ` name="action" value="${action}"` : ""}>${escape(label)}</button>`;
1021
1088
  function captchaWidget(settings) {
1022
1089
  return settings.captcha ? `<div class="${CAPTCHA_WIDGETS[settings.captcha.provider].className}" data-sitekey="${escape(settings.captcha.siteKey)}"></div>` : "";
1023
1090
  }
1024
- function signInForm(settings, problem, search) {
1091
+ /** Google, GitHub and passkeys side by side over the form, set apart by "or"; each provider posts to the sign-in page. */
1092
+ function ways(settings, search, passkey) {
1093
+ const social = ["google", "github"].filter((one) => settings.methods[one]);
1094
+ const count = social.length + (passkey ? 1 : 0);
1095
+ if (!count) return "";
1096
+ const one = count === 1;
1097
+ const button = (icon, label, named, attributes) => `<button class="msa-button msa-secondary"${one ? "" : ` aria-label="${escape(named)}"`} ${attributes}>${iconSvg(icon)}<span class="msa-way-label">${escape(one ? named : label)}</span></button>`;
1098
+ return `<div class="msa-ways" data-count="${count}">${[...social.map((provider) => `<form method="post" action="${UI}/sign-in${escape(search)}">${button(provider, WORDS.ways[provider], WORDS.ways.continueWith(WORDS.ways[provider]), `name="action" value="${provider}"`)}</form>`), passkey ? button("passkey", WORDS.ways.passkey, WORDS.ways.passkeySignIn, `type="button" id="msa-passkey"`) : ""].join("")}</div><div class="msa-or">${escape(WORDS.ways.or)}</div>`;
1099
+ }
1100
+ function signInForm(settings, problem, search, email) {
1025
1101
  const { methods } = settings;
1026
- const social = ["google", "github"].filter((one) => methods[one]);
1027
- const quick = social.length || methods.passkey ? `<div class="msa-stack">${social.map((one) => `<form method="post"><button name="action" value="${one}">${escape(WORDS.ways[one])}</button></form>`).join("")}${methods.passkey ? `<button type="button" id="msa-passkey">${escape(WORDS.ways.passkey)}</button>` : ""}</div><div class="msa-or">${escape(WORDS.ways.or)}</div>` : "";
1028
- const password = methods.password ? `<label>${escape(WORDS.fields.password)}<input type="password" name="password" autocomplete="current-password"></label>` : "";
1029
- const others = [methods.code ? `<button class="msa-quiet" name="action" value="code" formnovalidate>${escape(WORDS.ways.code)}</button>` : "", methods.link ? `<button class="msa-quiet" name="action" value="link" formnovalidate>${escape(WORDS.ways.link)}</button>` : ""].join("");
1030
- const main = methods.password ? `<button class="msa-primary" name="action" value="password">${escape(WORDS.signIn.submit)}</button>` : methods.code ? `<button class="msa-primary" name="action" value="code">${escape(WORDS.ways.code)}</button>` : methods.link ? `<button class="msa-primary" name="action" value="link">${escape(WORDS.ways.link)}</button>` : "";
1031
- const foot = [methods.password ? `<a href="${UI}/reset-password">${escape(WORDS.signIn.forgot)}</a>` : "", settings.signUp.policy === "invite" ? "" : `${escape(WORDS.signIn.noAccount)} <a href="${UI}/sign-up${escape(search)}">${escape(WORDS.signIn.signUp)}</a>`].filter(Boolean).join(" · ");
1032
- return `${quick}<form method="post"><label>${escape(WORDS.fields.email)}<input type="email" name="email" required autocomplete="email"></label>${password}${captchaWidget(settings)}<p class="msa-error" role="alert">${escape(problem)}</p>${main}${methods.password && others ? `<div class="msa-stack">${others}</div>` : ""}</form><p class="msa-foot">${foot}</p>`;
1102
+ const byMail = methods.code ? "code" : methods.link ? "link" : null;
1103
+ const quiet = methods.password ? byMail : methods.code && methods.link ? "link" : null;
1104
+ const forgot = `<a class="msa-link" href="${UI}/reset-password">${escape(WORDS.signIn.forgot)}</a>`;
1105
+ const password = methods.password ? field({
1106
+ label: WORDS.fields.password,
1107
+ name: "password",
1108
+ type: "password",
1109
+ autocomplete: "current-password",
1110
+ placeholder: WORDS.placeholders.password,
1111
+ required: false,
1112
+ aside: forgot
1113
+ }) : "";
1114
+ const main = methods.password ? submit(WORDS.signIn.submit, "password") : byMail === "link" ? submit(WORDS.ways.link, "link") : byMail === "code" ? submit(WORDS.ways.code, "code") : "";
1115
+ const other = quiet ? links([`<button class="msa-link" name="action" value="${quiet}" formnovalidate>${escape(quiet === "code" ? WORDS.ways.codeInstead : WORDS.ways.linkInstead)}</button>`], "center") : "";
1116
+ const foot = settings.signUp.policy === "invite" ? "" : `<p class="msa-foot">${escape(WORDS.signIn.newHere)} <a class="msa-link" href="${UI}/sign-up${escape(search)}">${escape(WORDS.signIn.createAccount)}</a></p>`;
1117
+ return `${ways(settings, search, methods.passkey)}<form method="post" class="msa-form">${field({
1118
+ label: WORDS.fields.email,
1119
+ name: "email",
1120
+ type: "email",
1121
+ autocomplete: "email",
1122
+ placeholder: WORDS.placeholders.email,
1123
+ value: email
1124
+ })}${password}${captchaWidget(settings)}${problemLine(problem)}${main}${other}</form>${foot}`;
1033
1125
  }
1034
- /** The way back to the sign-in form from a note that a mail is on its way. */
1035
- const backTo = (search) => `<p class="msa-foot"><a href="${UI}/sign-in${escape(search)}">${escape(WORDS.confirm.back)}</a></p>`;
1036
- function signUpForm(settings, problem, search) {
1037
- return `<form method="post"><label>${escape(WORDS.fields.name)}<input name="name" required autocomplete="name"></label><label>${escape(WORDS.fields.email)}<input type="email" name="email" required autocomplete="email"></label><label>${escape(WORDS.fields.password)}<input type="password" name="password" required autocomplete="new-password" minlength="8"></label>${captchaWidget(settings)}<p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary">${escape(settings.signUp.policy === "waitlist" ? WORDS.signUp.waitlist : WORDS.signUp.submit)}</button></form><p class="msa-foot">${escape(WORDS.signUp.haveAccount)} <a href="${UI}/sign-in${escape(search)}">${escape(WORDS.signUp.signIn)}</a></p>`;
1126
+ function codeForm(email, problem, search) {
1127
+ return `<form method="post" class="msa-form"><input type="hidden" name="email" value="${escape(email)}">${codeField()}${problemLine(problem)}${submit(WORDS.code.submit, "verify")}</form>${links([`<form method="post"><input type="hidden" name="email" value="${escape(email)}"><button class="msa-link" name="action" value="code">${escape(WORDS.code.resend)}</button></form>`, `<a class="msa-link" href="${UI}/sign-in${escape(search)}">${escape(WORDS.code.differentEmail)}</a>`])}`;
1038
1128
  }
1039
- function twoFactorForm(problem, mailed) {
1040
- return `<form method="post"><label>${escape(WORDS.fields.code)}<input name="code" required autocomplete="one-time-code" inputmode="numeric" autofocus></label><p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary" name="action" value="${mailed ? "mail-code" : "totp"}">${escape(WORDS.twoFactor.submit)}</button></form><form method="post" class="msa-stack" style="margin-top:12px"><button class="msa-quiet" name="action" value="send">${escape(WORDS.twoFactor.byMail)}</button></form><form method="post" style="margin-top:12px"><label>${escape(WORDS.twoFactor.backupField)}<input name="code" required autocomplete="off"></label><button name="action" value="backup">${escape(WORDS.twoFactor.backup)}</button></form>`;
1129
+ function signUpForm(settings, problem, search, form) {
1130
+ const policy = settings.signUp.policy;
1131
+ return `${policy === "open" || policy === "domains" ? ways(settings, search, false) : ""}<form method="post" class="msa-form">${field({
1132
+ label: WORDS.fields.name,
1133
+ name: "name",
1134
+ autocomplete: "name",
1135
+ placeholder: WORDS.placeholders.name,
1136
+ value: form.name ?? ""
1137
+ })}${field({
1138
+ label: WORDS.fields.email,
1139
+ name: "email",
1140
+ type: "email",
1141
+ autocomplete: "email",
1142
+ placeholder: WORDS.placeholders.email,
1143
+ value: form.email ?? ""
1144
+ })}${field({
1145
+ label: WORDS.fields.password,
1146
+ name: "password",
1147
+ type: "password",
1148
+ autocomplete: "new-password",
1149
+ placeholder: WORDS.placeholders.newPassword,
1150
+ minlength: 8
1151
+ })}${captchaWidget(settings)}${problemLine(problem)}${submit(policy === "waitlist" ? WORDS.signUp.waitlist : WORDS.signUp.submit)}</form><p class="msa-foot">${escape(WORDS.signUp.haveAccount)} <a class="msa-link" href="${UI}/sign-in${escape(search)}">${escape(WORDS.signUp.signIn)}</a></p>`;
1041
1152
  }
1042
- function resetForm(settings, problem) {
1043
- return `<form method="post"><label>${escape(WORDS.fields.email)}<input type="email" name="email" required autocomplete="email"></label>${captchaWidget(settings)}<p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary">${escape(WORDS.reset.submit)}</button></form>`;
1153
+ function twoFactorForm(problem, way, here) {
1154
+ const code = way === "backup" ? field({
1155
+ label: WORDS.fields.backupCode,
1156
+ name: "code",
1157
+ autocomplete: "one-time-code",
1158
+ placeholder: WORDS.placeholders.backupCode,
1159
+ autofocus: true
1160
+ }) : codeField();
1161
+ const send = `<form method="post"><button class="msa-link" name="action" value="send">${escape(WORDS.twoFactor.byMail)}</button></form>`;
1162
+ const app = `<a class="msa-link" href="${escape(here({ way: null }))}">${escape(WORDS.twoFactor.app)}</a>`;
1163
+ const backup = `<a class="msa-link" href="${escape(here({ way: "backup" }))}">${escape(WORDS.twoFactor.backup)}</a>`;
1164
+ return `<form method="post" class="msa-form">${code}${problemLine(problem)}${submit(WORDS.twoFactor.submit, way === "backup" ? "backup" : way === "mail" ? "mail-code" : "totp")}</form>${links(way === "app" ? [send, backup] : way === "mail" ? [app, backup] : [app, send])}`;
1165
+ }
1166
+ function resetForm(settings, problem, email) {
1167
+ return `<form method="post" class="msa-form">${field({
1168
+ label: WORDS.fields.email,
1169
+ name: "email",
1170
+ type: "email",
1171
+ autocomplete: "email",
1172
+ placeholder: WORDS.placeholders.email,
1173
+ value: email
1174
+ })}${captchaWidget(settings)}${problemLine(problem)}${submit(WORDS.reset.submit)}</form><p class="msa-foot"><a class="msa-link" href="${UI}/sign-in">${escape(WORDS.confirm.back)}</a></p>`;
1044
1175
  }
1045
1176
  function newPasswordForm(problem) {
1046
- return `<form method="post"><label>${escape(WORDS.fields.newPassword)}<input type="password" name="password" required autocomplete="new-password" minlength="8"></label><p class="msa-error" role="alert">${escape(problem)}</p><button class="msa-primary">${escape(WORDS.reset.save)}</button></form>`;
1177
+ return `<form method="post" class="msa-form">${field({
1178
+ label: WORDS.fields.newPassword,
1179
+ name: "password",
1180
+ type: "password",
1181
+ autocomplete: "new-password",
1182
+ placeholder: WORDS.placeholders.newPassword,
1183
+ minlength: 8,
1184
+ autofocus: true
1185
+ })}${problemLine(problem)}${submit(WORDS.reset.save)}</form>`;
1047
1186
  }
1048
- /** A value shown once, on one line, with a Copy button that says when it copied (`copyScript`). */
1049
- const secret = (label, value) => `<div class="msa-secret"><code aria-label="${escape(label)}">${escape(value)}</code><button type="button" data-copy="${escape(value)}">${escape(WORDS.account.copy)}</button></div>`;
1050
- function twoFactorSetup(uri, codes) {
1051
- return `<div class="msa-stack"><p class="msa-note">${escape(WORDS.account.twoFactorSetup)}</p>${qrSvg(uri, WORDS.account.qr)}${secret(WORDS.account.setupKey, setupKeyOf(uri))}<a href="${escape(uri)}">${escape(WORDS.account.openInApp)}</a><p class="msa-note">${escape(WORDS.account.backupCodes)}</p><ul class="msa-codes">${codes.map((one) => `<li><code>${escape(one)}</code></li>`).join("")}</ul><div><button type="button" data-copy="${escape(codes.join("\n"))}">${escape(WORDS.account.copyCodes)}</button></div><form method="post"><label>${escape(WORDS.fields.code)}<input name="code" required autocomplete="one-time-code" inputmode="numeric"></label><button name="action" value="two-factor-verify">${escape(WORDS.twoFactor.submit)}</button></form></div>`;
1187
+ /** A value shown once, on one line, with a Copy button that shows Copied once it has (`copyScript`). */
1188
+ const secret = (label, value) => `<div class="msa-secret"><code aria-label="${escape(label)}">${escape(value)}</code><button type="button" class="msa-button msa-secondary msa-small" data-copy="${escape(value)}">${escape(WORDS.account.copy)}</button></div>`;
1189
+ /** A settings panel in the card material; `problem` is where a refusal of one of its forms is said. */
1190
+ function panel(input) {
1191
+ const id = `msa-panel-${input.section}`;
1192
+ const head = `<header class="msa-panel-head"><h2 id="${id}">${escape(input.title)}</h2>${input.line ? `<p>${escape(input.line)}</p>` : ""}</header>`;
1193
+ const problem = `<p class="msa-feedback" role="alert" data-for="${input.section}">${escape(input.problem)}</p>`;
1194
+ const single = !input.rows && !input.foot && input.action;
1195
+ return `<section class="msa-panel" aria-labelledby="${id}"${input.tone ? ` data-tone="${input.tone}"` : ""}>${single ? `<div class="msa-panel-single">${head}<div class="msa-panel-actions">${input.action}</div></div>` : head}${input.rows ? `<div class="msa-rows">${input.rows}</div>` : ""}${input.foot ? `<footer class="msa-panel-foot">${problem}<div class="msa-panel-actions">${input.foot}</div></footer>` : problem}</section>`;
1052
1196
  }
1053
- const row = (title, detail, action = "") => `<div class="msa-row"><div><strong>${escape(title)}</strong><span>${escape(detail)}</span></div>${action}</div>`;
1054
- /** A row's action; one that removes something asks first, by opening to its button for good. */
1055
- const rowButton = (action, words, fields = {}, confirm) => {
1056
- const hidden = Object.entries(fields).map(([name, value]) => `<input type="hidden" name="${escape(name)}" value="${escape(value)}">`).join("");
1057
- if (!confirm) return `<form method="post">${hidden}<button class="msa-quiet" name="action" value="${escape(action)}">${escape(words)}</button></form>`;
1058
- return `<details><summary class="msa-danger">${escape(words)}</summary><form method="post">${hidden}<button class="msa-danger" name="action" value="${escape(action)}">${escape(confirm)}</button></form></details>`;
1197
+ /** One setting: its name and value on the left, its control on the right, and `extra` under it. */
1198
+ const row = (title, detail, control = "", extra = "") => `<div class="msa-row"><div class="msa-row-main"><div class="msa-row-copy"><span class="msa-row-title">${escape(title)}</span>${detail ? `<span class="msa-row-detail">${escape(detail)}</span>` : ""}</div>${control ? `<div class="msa-row-control">${control}</div>` : ""}</div>${extra ? `<div class="msa-row-extra">${extra}</div>` : ""}</div>`;
1199
+ /** A field as a settings row: its label on the left, the field on the right. */
1200
+ function fieldRow(input) {
1201
+ const id = `msa-field-${++fields}`;
1202
+ return `<div class="msa-row" data-field><div class="msa-row-main"><div class="msa-row-copy"><label class="msa-row-title" for="${id}">${escape(input.label)}</label></div><div class="msa-row-control"><input id="${id}" class="msa-input" type="${input.type ?? "text"}" name="${input.name}" required autocomplete="${input.autocomplete ?? "off"}"${input.value ? ` value="${escape(input.value)}"` : ""}${input.placeholder ? ` placeholder="${escape(input.placeholder)}"` : ""}${input.maxlength ? ` maxlength="${input.maxlength}"` : ""}></div></div></div>`;
1203
+ }
1204
+ /** A row whose form opens under it from its button, with no script: a `details` whose summary is the row. */
1205
+ const disclose = (title, detail, button, form, open) => `<details class="msa-row msa-disclose"${open ? " open" : ""}><summary class="msa-row-main"><span class="msa-row-copy"><span class="msa-row-title">${escape(title)}</span>${detail ? `<span class="msa-row-detail">${escape(detail)}</span>` : ""}</span><span class="msa-row-control"><span class="msa-button msa-secondary msa-small"><span class="msa-closed">${escape(button)}</span><span class="msa-opened">${escape(WORDS.account.cancel)}</span></span></span></summary><div class="msa-row-extra">${form}</div></details>`;
1206
+ const actions = (label, action) => `<div class="msa-panel-actions"><button class="msa-button msa-primary msa-small" name="action" value="${action}">${escape(label)}</button></div>`;
1207
+ /** A row's action; one that removes something asks first, by opening to its button for good beside it. */
1208
+ const rowButton = (action, words, hidden = {}, confirm) => {
1209
+ const fieldsOf = Object.entries(hidden).map(([name, value]) => `<input type="hidden" name="${escape(name)}" value="${escape(value)}">`).join("");
1210
+ if (!confirm) return `<form method="post">${fieldsOf}<button class="msa-button msa-ghost msa-small" name="action" value="${escape(action)}">${escape(words)}</button></form>`;
1211
+ return `<details class="msa-confirm"><summary class="msa-button msa-ghost msa-small"><span class="msa-closed">${escape(words)}</span><span class="msa-opened">${escape(WORDS.account.cancel)}</span></summary><form method="post">${fieldsOf}<button class="msa-button msa-danger msa-small" name="action" value="${escape(action)}">${escape(confirm)}</button></form></details>`;
1059
1212
  };
1060
- /** The account page's section each of its forms belongs to, where a refusal of it is said. */
1213
+ /** The account page's panel each of its forms belongs to, where a refusal of it is said. */
1061
1214
  const SECTION_OF = {
1062
1215
  profile: "profile",
1063
1216
  password: "security",
@@ -1066,56 +1219,192 @@ const SECTION_OF = {
1066
1219
  "two-factor-off": "security",
1067
1220
  "passkey-remove": "passkeys",
1068
1221
  "session-revoke": "sessions",
1069
- "key-create": "agents",
1070
- "key-revoke": "agents",
1071
- "grant-revoke": "agents"
1222
+ "sessions-revoke": "sessions",
1223
+ "key-create": "keys",
1224
+ "key-revoke": "keys",
1225
+ "grant-revoke": "apps"
1072
1226
  };
1073
1227
  /** The few lines a Copy button needs: the value to the clipboard, and the button saying it copied. */
1074
1228
  function copyScript() {
1075
1229
  return `document.querySelectorAll("[data-copy]").forEach((b)=>b.addEventListener("click",()=>{if(navigator.clipboard)navigator.clipboard.writeText(b.getAttribute("data-copy")||"").then(()=>{b.textContent=${JSON.stringify(WORDS.account.copied)}},()=>{})}))`;
1076
1230
  }
1231
+ /**
1232
+ * The few lines a password field's button needs to show and hide what is typed, and a code field its six boxes: with
1233
+ * no script, the code field is a plain field.
1234
+ */
1235
+ function revealScript() {
1236
+ return "document.querySelectorAll(\"[data-msa-reveal]\").forEach((b)=>b.addEventListener(\"click\",()=>{const i=b.previousElementSibling,on=i.type===\"password\";i.type=on?\"text\":\"password\";b.setAttribute(\"aria-pressed\",String(on));b.setAttribute(\"aria-label\",on?\"Hide password\":\"Show password\")}));document.querySelectorAll(\".msa-otp\").forEach((o)=>{const i=o.querySelector(\"input\"),s=[...o.querySelectorAll(\".msa-otp-box\")];o.setAttribute(\"data-boxes\",\"\");const show=()=>{i.value=i.value.replace(/\\D/g,\"\").slice(0,6);s.forEach((b,n)=>{b.textContent=i.value[n]||\"\";b.toggleAttribute(\"data-active\",n===Math.min(i.value.length,5))});if(i.value.length===6&&i.form)i.form.requestSubmit()};i.addEventListener(\"input\",show);show()})";
1237
+ }
1238
+ function twoFactorSetup(uri, codes) {
1239
+ const id = `msa-field-${++fields}`;
1240
+ return `<div class="msa-setup"><p class="msa-note">${escape(WORDS.account.twoFactorSetup)}</p>${qrSvg(uri, WORDS.account.qr)}<div style="width:100%">${secret(WORDS.account.setupKey, setupKeyOf(uri))}</div><a class="msa-link" href="${escape(uri)}">${escape(WORDS.account.openInApp)}</a><div class="msa-field"><span class="msa-label">${escape(WORDS.account.backupCodes)}</span><p class="msa-lead">${escape(WORDS.account.backupCodesLead)}</p></div><ul class="msa-codes">${codes.map((one) => `<li><code>${escape(one)}</code></li>`).join("")}</ul><button type="button" class="msa-button msa-secondary msa-small" data-copy="${escape(codes.join("\n"))}">${escape(WORDS.account.copyCodes)}</button><form method="post" style="width:100%"><div class="msa-row" data-field><div class="msa-row-main"><div class="msa-row-copy"><label class="msa-row-title" for="${id}">${escape(WORDS.fields.code)}</label></div><div class="msa-row-control"><input id="${id}" class="msa-input" name="code" required autocomplete="one-time-code" inputmode="numeric"></div></div></div>${actions(WORDS.account.finish, "two-factor-verify")}</form></div>`;
1241
+ }
1077
1242
  function accountBody(input) {
1078
1243
  const { user, session } = input.signedIn;
1079
- /** Where a section says a refusal of one of its forms. */
1080
- const problemIn = (section) => `<p class="msa-error" role="alert" data-for="${section}">${input.failed === section ? escape(input.problem) : ""}</p>`;
1081
- /** What a form of a section made, such as a new key, shown under it. */
1082
- const shownIn = (section) => input.shown && SECTION_OF[input.made] === section ? input.shown : "";
1083
1244
  const words = WORDS.account;
1245
+ const problemIn = (section) => input.failed === section ? input.problem : "";
1246
+ /** What a form of a panel made, such as a new key, shown in it. */
1247
+ const shownIn = (section) => input.shown && SECTION_OF[input.made] === section ? input.shown : "";
1248
+ const who = String(user.name || user.email);
1249
+ const identity = `<header class="msa-identity"><span class="msa-avatar" data-size="large" aria-hidden="true">${typeof user.image === "string" && user.image ? `<img src="${escape(user.image)}" alt="">` : escape(who.slice(0, 1).toUpperCase())}</span><div class="msa-identity-copy"><h1 class="msa-identity-name">${escape(who)}</h1>${user.name ? `<p class="msa-identity-detail">${escape(user.email)}</p>` : ""}</div><form method="post"><button class="msa-button msa-secondary msa-small" name="action" value="sign-out">${iconSvg("door")}${escape(WORDS.user.signOut)}</button></form></header>`;
1250
+ const profile = `<form method="post">${panel({
1251
+ title: words.profile,
1252
+ section: "profile",
1253
+ problem: problemIn("profile"),
1254
+ rows: fieldRow({
1255
+ label: WORDS.fields.name,
1256
+ name: "name",
1257
+ value: String(user.name ?? ""),
1258
+ autocomplete: "name"
1259
+ }) + row(WORDS.fields.email, "", `<span class="msa-value">${escape(user.email)}</span>`),
1260
+ foot: `<button class="msa-button msa-secondary msa-small" name="action" value="profile">${escape(words.save)}</button>`
1261
+ })}</form>`;
1084
1262
  const twoFactor = user.twoFactorEnabled === true;
1085
- const profile = `<section><h2>${escape(words.profile)}</h2>${problemIn("profile")}<form method="post"><label>${escape(WORDS.fields.name)}<input name="name" value="${escape(user.name)}" required autocomplete="name"></label><div><button name="action" value="profile">${escape(words.save)}</button></div></form></section>`;
1086
- const password = input.settings.methods.password ? `<form method="post"><label>${escape(WORDS.fields.currentPassword)}<input type="password" name="current" required autocomplete="current-password"></label><label>${escape(WORDS.fields.newPassword)}<input type="password" name="next" required autocomplete="new-password" minlength="8"></label><div><button name="action" value="password">${escape(words.changePassword)}</button></div></form>` : "";
1087
- const twoFactorRow = `<div class="msa-row" style="margin-top:12px"><div><strong>${escape(twoFactor ? words.twoFactorOn : words.twoFactorOff)}</strong></div><form method="post" style="display:flex;gap:8px;align-items:end"><label>${escape(words.yourPassword)}<input type="password" name="password" required autocomplete="current-password"></label><button name="action" value="${twoFactor ? "two-factor-off" : "two-factor-on"}">${escape(twoFactor ? words.turnOff : words.turnOn)}</button></form></div>`;
1088
- const passkeys = input.settings.methods.passkey ? `<section><h2>${escape(words.passkeys)}</h2>${problemIn("passkeys")}${input.passkeys.length ? input.passkeys.map((one) => row(String(one.name || words.passkey), ago(one.createdAt), rowButton("passkey-remove", words.remove, { id: String(one.id) }, words.removeForGood))).join("") : `<p class="msa-note">${escape(words.noPasskeys)}</p>`}<div style="margin-top:12px"><button type="button" id="msa-passkey">${escape(words.addPasskey)}</button></div></section>` : "";
1089
- const sessions = `<section><h2>${escape(words.sessions)}</h2>${problemIn("sessions")}${input.sessions.map((one) => row(one.id === session.id ? words.thisDevice : deviceOf(one.userAgent) ?? words.unknownDevice, [
1090
- typeof one.impersonatedBy === "string" && one.impersonatedBy ? words.signedInBy(one.impersonatedBy) : "",
1091
- ago(one.createdAt),
1092
- typeof one.ipAddress === "string" ? one.ipAddress : ""
1093
- ].filter(Boolean).join(" · "), one.id === session.id ? "" : rowButton("session-revoke", words.signOut, { token: String(one.token) }))).join("")}<form method="post" style="margin-top:12px"><button name="action" value="sign-out">${escape(WORDS.user.signOut)}</button></form></section>`;
1263
+ const opened = problemIn("security") ? input.made : "";
1264
+ const password = input.settings.methods.password ? disclose(words.password, "", words.changePassword, `<form method="post">${fieldRow({
1265
+ label: WORDS.fields.currentPassword,
1266
+ name: "current",
1267
+ type: "password",
1268
+ autocomplete: "current-password"
1269
+ })}${fieldRow({
1270
+ label: WORDS.fields.newPassword,
1271
+ name: "next",
1272
+ type: "password",
1273
+ autocomplete: "new-password",
1274
+ placeholder: WORDS.placeholders.newPassword
1275
+ })}${actions(words.savePassword, "password")}</form>`, opened === "password") : "";
1276
+ const setup = shownIn("security");
1277
+ const twoFactorRow = setup ? row(words.twoFactor, twoFactor ? words.on : words.off, "", setup) : disclose(words.twoFactor, twoFactor ? words.on : words.off, twoFactor ? words.turnOff : words.turnOn, `<form method="post">${fieldRow({
1278
+ label: WORDS.fields.yourPassword,
1279
+ name: "password",
1280
+ type: "password",
1281
+ autocomplete: "current-password"
1282
+ })}${actions(twoFactor ? words.turnOff : words.turnOn, twoFactor ? "two-factor-off" : "two-factor-on")}</form>`, opened.startsWith("two-factor"));
1283
+ const security = panel({
1284
+ title: words.security,
1285
+ section: "security",
1286
+ problem: problemIn("security"),
1287
+ rows: password + twoFactorRow
1288
+ });
1289
+ const addPasskey = `<button type="button" class="msa-button msa-secondary msa-small" id="msa-passkey">${iconSvg("plus")}${escape(words.addPasskey)}</button>`;
1290
+ const passkeys = !input.settings.methods.passkey ? "" : input.passkeys.length ? panel({
1291
+ title: words.passkeys,
1292
+ section: "passkeys",
1293
+ problem: problemIn("passkeys"),
1294
+ rows: input.passkeys.map((one) => row(String(one.name || words.passkey), one.createdAt ? words.added(ago(one.createdAt)) : "", rowButton("passkey-remove", words.remove, { id: String(one.id) }, words.removeForGood))).join(""),
1295
+ foot: addPasskey
1296
+ }) : panel({
1297
+ title: words.passkeys,
1298
+ section: "passkeys",
1299
+ problem: problemIn("passkeys"),
1300
+ line: words.noPasskeys,
1301
+ action: addPasskey
1302
+ });
1303
+ const ordered = [...input.sessions].sort((a, b) => Number(b.id === session.id) - Number(a.id === session.id));
1304
+ const sessions = panel({
1305
+ title: words.sessions,
1306
+ section: "sessions",
1307
+ problem: problemIn("sessions"),
1308
+ rows: ordered.map((one) => row(deviceOf(one.userAgent) ?? words.unknownDevice, [
1309
+ typeof one.impersonatedBy === "string" && one.impersonatedBy ? words.signedInBy(one.impersonatedBy) : "",
1310
+ words.signedIn(ago(one.createdAt)),
1311
+ typeof one.ipAddress === "string" ? one.ipAddress : ""
1312
+ ].filter(Boolean).join(" · "), one.id === session.id ? `<span class="msa-tag">${escape(words.thisDevice)}</span>` : rowButton("session-revoke", words.signOut, { token: String(one.token) }))).join(""),
1313
+ ...ordered.length > 1 ? { foot: `<form method="post"><button class="msa-button msa-secondary msa-small" name="action" value="sessions-revoke">${escape(words.signOutOthers)}</button></form>` } : {}
1314
+ });
1094
1315
  const scopes = Object.entries(input.scopes);
1095
- const keys = scopes.length ? `${input.keys.length ? input.keys.map((one) => row(String(one.name ?? one.start ?? one.id), [(one.scopes ?? []).map((scope) => input.scopes[scope] ?? scope).join(", "), one.lastUsedAt ? words.lastUsed(ago(one.lastUsedAt)) : words.neverUsed].join(" · "), rowButton("key-revoke", words.revoke, { id: String(one.id) }, words.revokeForGood))).join("") : `<p class="msa-note">${escape(words.noKeys)}</p>`}<form method="post" style="margin-top:12px"><label>${escape(WORDS.fields.keyName)}<input name="name" required maxlength="32"></label><fieldset style="border:0;padding:0;margin:0;display:grid;gap:6px"><legend style="font-weight:500;font-size:14px;margin-bottom:6px">${escape(words.scopes)}</legend>${scopes.map(([scope, what]) => `<label style="display:flex;gap:8px;align-items:center;font-weight:400"><input type="checkbox" name="scope:${escape(scope)}" style="width:auto;min-height:0">${escape(what)}</label>`).join("")}</fieldset><div><button name="action" value="key-create">${escape(words.createKey)}</button></div></form>` : "";
1096
- const grants = `<h2 style="margin-top:20px">${escape(words.apps)}</h2>${input.grants.length ? input.grants.map((one) => row(String(one.client ?? one.clientId), (one.scopes ?? []).map((scope) => input.scopes[scope] ?? scope).join(", "), rowButton("grant-revoke", words.removeAccess, { id: String(one.id) }, words.removeAccessForGood))).join("") : `<p class="msa-note">${escape(words.noApps)}</p>`}`;
1097
- const agents = scopes.length || input.grants.length ? `<section><h2>${escape(words.agents)}</h2>${problemIn("agents")}${shownIn("agents")}${keys}${grants}</section>` : "";
1098
- return `${input.notice ? `<p class="msa-note" role="status">${escape(input.notice)}</p>` : ""}${profile}<section><h2>${escape(words.security)}</h2>${problemIn("security")}${password}${twoFactorRow}${shownIn("security")}</section>${passkeys}${sessions}${agents}`;
1316
+ const scopeWords = (list) => (list ?? []).map((scope) => input.scopes[scope] ?? scope).join(", ");
1317
+ return `${identity}${profile}${security}${passkeys}${sessions}${scopes.length ? panel({
1318
+ title: words.keys,
1319
+ section: "keys",
1320
+ problem: problemIn("keys"),
1321
+ ...input.keys.length ? {} : { line: words.noKeys },
1322
+ rows: input.keys.map((one) => row(String(one.name ?? one.start ?? one.id), [scopeWords(one.scopes), one.lastUsedAt ? words.lastUsed(ago(one.lastUsedAt)) : words.neverUsed].join(" · "), rowButton("key-revoke", words.revoke, { id: String(one.id) }, words.revokeForGood))).join("") + shownIn("keys") + `<form method="post" id="msa-key">${fieldRow({
1323
+ label: WORDS.fields.keyName,
1324
+ name: "name",
1325
+ placeholder: WORDS.placeholders.keyName,
1326
+ maxlength: 32
1327
+ })}${row(words.scopes, "", `<div class="msa-scopes">${scopes.map(([scope, what]) => `<label class="msa-check"><input type="checkbox" name="scope:${escape(scope)}">${escape(what)}</label>`).join("")}</div>`)}</form>`,
1328
+ foot: `<button class="msa-button msa-secondary msa-small" form="msa-key" name="action" value="key-create">${iconSvg("plus")}${escape(words.createKey)}</button>`
1329
+ }) : ""}${scopes.length || input.grants.length ? input.grants.length ? panel({
1330
+ title: words.apps,
1331
+ section: "apps",
1332
+ problem: problemIn("apps"),
1333
+ rows: input.grants.map((one) => row(String(one.client ?? one.clientId), scopeWords(one.scopes), rowButton("grant-revoke", words.removeAccess, { id: String(one.id) }, words.removeAccessForGood))).join("")
1334
+ }) : panel({
1335
+ title: words.apps,
1336
+ section: "apps",
1337
+ problem: "",
1338
+ line: words.noApps,
1339
+ action: ""
1340
+ }) : ""}`;
1099
1341
  }
1100
1342
  function organizationBody(input) {
1101
1343
  const words = WORDS.organizations, roles = words.roles;
1344
+ const problemIn = (actions) => actions.includes(input.failed) ? input.problem : "";
1102
1345
  const roleOptions = (chosen) => Object.keys(roles).map((one) => `<option value="${one}"${one === chosen ? " selected" : ""}>${escape(roles[one])}</option>`).join("");
1103
- const switcher = `<section><form method="post" style="display:flex;gap:8px;align-items:end"><label style="flex:1">${escape(words.switch)}<select name="id"><option value="">${escape(words.personal)}</option>${input.organizations.map((one) => `<option value="${escape(one.id)}"${one.id === input.activeId ? " selected" : ""}>${escape(one.name)}</option>`).join("")}</select></label><button name="action" value="switch">${escape(words.switchTo)}</button></form><form method="post" style="display:flex;gap:8px;align-items:end;margin-top:12px"><label style="flex:1">${escape(WORDS.fields.organization)}<input name="name" required></label><button name="action" value="create">${escape(words.create)}</button></form></section>`;
1346
+ const select = (name, label, options, small = true) => `<span class="msa-select"${small ? ` data-size="small"` : ""}><select name="${name}" aria-label="${escape(label)}">${options}</select>${iconSvg("grabber")}</span>`;
1347
+ const organizationOptions = `<option value="">${escape(words.personal)}</option>${input.organizations.map((one) => `<option value="${escape(one.id)}"${one.id === input.activeId ? " selected" : ""}>${escape(one.name)}</option>`).join("")}`;
1348
+ const newId = `msa-field-${++fields}`;
1349
+ const switcher = panel({
1350
+ title: words.all,
1351
+ section: "organizations",
1352
+ problem: problemIn([
1353
+ "switch",
1354
+ "create",
1355
+ ""
1356
+ ]),
1357
+ rows: `<form method="post">${row(words.workingIn, "", `${select("id", words.switch, organizationOptions)}<button class="msa-button msa-secondary msa-small" name="action" value="switch">${escape(words.switchTo)}</button>`)}</form><form method="post"><div class="msa-row"><div class="msa-row-main"><div class="msa-row-copy"><label class="msa-row-title" for="${newId}">${escape(words.newOrganization)}</label></div><div class="msa-row-control"><input id="${newId}" class="msa-input" name="name" required autocomplete="off" placeholder="${escape(WORDS.placeholders.organization)}" style="width:12rem"><button class="msa-button msa-secondary msa-small" name="action" value="create">${iconSvg("plus")}${escape(words.create)}</button></div></div></div></form>`
1358
+ });
1104
1359
  const full = input.full;
1105
- if (!full) return `<p class="msa-error" role="alert">${escape(input.problem)}</p>${switcher}`;
1360
+ if (!full) return switcher;
1106
1361
  const members = full.members ?? [];
1107
1362
  const me = members.find((member) => member.userId === input.userId);
1108
1363
  const manages = me?.role === "owner" || me?.role === "admin";
1364
+ const identity = `<header class="msa-identity"><span class="msa-avatar" data-size="large" data-shape="square" aria-hidden="true">${escape(String(full.name ?? "").slice(0, 1).toUpperCase())}</span><div class="msa-identity-copy"><h1 class="msa-identity-name">${escape(full.name)}</h1><p class="msa-identity-detail">${escape(full.slug)}</p></div></header>`;
1109
1365
  const memberRows = members.map((member) => {
1110
1366
  const user = member.user ?? {};
1111
- const action = manages && member.userId !== input.userId ? `<div style="display:flex;gap:8px"><form method="post" style="display:flex;gap:8px"><input type="hidden" name="member" value="${escape(member.id)}"><select name="role" aria-label="${escape(WORDS.fields.role)}, ${escape(user.email)}" style="width:auto">${roleOptions(String(member.role))}</select><button class="msa-quiet" name="action" value="role">${escape(words.save)}</button></form>${rowButton("remove", words.remove, { member: String(member.id) }, words.removeForGood)}</div>` : `<span>${escape(roles[member.role] ?? member.role)}</span>`;
1112
- return row(String(user.name || user.email), String(user.email ?? ""), action);
1367
+ const roleWords = roles[member.role] ?? String(member.role);
1368
+ const control = manages && member.userId !== input.userId ? `<form method="post" class="msa-row-control"><input type="hidden" name="member" value="${escape(member.id)}">${select("role", `${WORDS.fields.role}, ${String(user.email)}`, roleOptions(String(member.role)))}<button class="msa-button msa-ghost msa-small" name="action" value="role">${escape(words.save)}</button></form>${rowButton("remove", words.remove, { member: String(member.id) }, words.removeForGood)}` : `<span class="msa-tag">${escape(member.userId === input.userId ? `${words.you} · ${roleWords}` : roleWords)}</span>`;
1369
+ return row(String(user.name || user.email), user.name ? String(user.email ?? "") : "", control);
1113
1370
  }).join("");
1114
1371
  const pending = (full.invitations ?? []).filter((one) => one.status === "pending");
1115
- const invitations = manages ? `<section><h2>${escape(words.invitations)}</h2>${pending.length ? pending.map((one) => row(String(one.email), roles[one.role ?? "member"] ?? String(one.role), rowButton("cancel", words.cancel, { invitation: String(one.id) }, words.cancel))).join("") : `<p class="msa-note">${escape(words.noInvitations)}</p>`}<form method="post" style="margin-top:12px"><label>${escape(WORDS.fields.inviteEmail)}<input type="email" name="email" required autocomplete="off"></label><label>${escape(WORDS.fields.role)}<select name="role">${roleOptions("member")}</select></label><div><button name="action" value="invite">${escape(words.invite)}</button></div></form></section>` : "";
1116
- const rename = manages ? `<section><h2>${escape(words.settings)}</h2><form method="post"><label>${escape(WORDS.fields.organization)}<input name="name" value="${escape(full.name)}" required></label><div><button name="action" value="rename">${escape(words.save)}</button></div></form></section>` : "";
1117
- const leave = me && me.role !== "owner" ? `<section>${rowButton("leave", words.leave, {}, words.leaveForGood)}</section>` : "";
1118
- return `<p class="msa-error" role="alert">${escape(input.problem)}</p>${switcher}${rename}<section><h2>${escape(words.members)}</h2>${memberRows}</section>${invitations}${leave}`;
1372
+ const invitations = manages ? panel({
1373
+ title: words.invitations,
1374
+ section: "invitations",
1375
+ problem: problemIn(["invite", "cancel"]),
1376
+ rows: pending.map((one) => row(String(one.email), roles[one.role ?? "member"] ?? String(one.role), rowButton("cancel", words.cancel, { invitation: String(one.id) }))).join("") + `<form method="post" id="msa-invite">${fieldRow({
1377
+ label: WORDS.fields.inviteEmail,
1378
+ name: "email",
1379
+ type: "email",
1380
+ placeholder: WORDS.placeholders.email
1381
+ })}${row(WORDS.fields.role, "", select("role", WORDS.fields.role, roleOptions("member")))}</form>`,
1382
+ foot: `<button class="msa-button msa-secondary msa-small" form="msa-invite" name="action" value="invite">${escape(words.invite)}</button>`
1383
+ }) : "";
1384
+ const rename = manages ? `<form method="post">${panel({
1385
+ title: words.settings,
1386
+ section: "organization",
1387
+ problem: problemIn(["rename"]),
1388
+ rows: fieldRow({
1389
+ label: WORDS.fields.organization,
1390
+ name: "name",
1391
+ value: String(full.name ?? "")
1392
+ }),
1393
+ foot: `<button class="msa-button msa-secondary msa-small" name="action" value="rename">${escape(words.save)}</button>`
1394
+ })}</form>` : "";
1395
+ const leave = me && me.role !== "owner" ? panel({
1396
+ title: words.leave,
1397
+ section: "leave",
1398
+ problem: problemIn(["leave"]),
1399
+ tone: "danger",
1400
+ action: rowButton("leave", words.leave, {}, words.leaveForGood)
1401
+ }) : "";
1402
+ return `${identity}${rename}${panel({
1403
+ title: words.members,
1404
+ section: "members",
1405
+ problem: problemIn(["role", "remove"]),
1406
+ rows: memberRows
1407
+ })}${invitations}${leave}${switcher}`;
1119
1408
  }
1120
1409
  /** The few lines passkeys need: the browser's own prompt, between two calls to sign-in. */
1121
1410
  function passkeyScript(kind, then) {