@powerhousedao/reactor-browser 6.4.0-next.2 → 6.4.0-next.4

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/dist/{attachment-service-0E5S0hZ6.d.ts → attachment-service-DdLM0Yf5.d.ts} +40 -9
  2. package/dist/attachment-service-DdLM0Yf5.d.ts.map +1 -0
  3. package/dist/auth-Ryem1MiX.d.ts +53 -0
  4. package/dist/auth-Ryem1MiX.d.ts.map +1 -0
  5. package/dist/{client-BFnMV-EO.js → client-DMCO2IaR.js} +3 -2
  6. package/dist/client-DMCO2IaR.js.map +1 -0
  7. package/dist/{document-model-modules-DCC6DjOP.js → document-model-modules-CHo9NZhj.js} +37 -5
  8. package/dist/document-model-modules-CHo9NZhj.js.map +1 -0
  9. package/dist/{document-operations-BUbpyfSf.js → document-operations-Dj0fTOHE.js} +113 -14
  10. package/dist/document-operations-Dj0fTOHE.js.map +1 -0
  11. package/dist/{global-DfeQC3Fg.d.ts → global-DMTXzdRf.d.ts} +28 -2
  12. package/dist/{global-DfeQC3Fg.d.ts.map → global-DMTXzdRf.d.ts.map} +1 -1
  13. package/dist/{index-BlCYgfht.d.ts → index-C5bsy9EC.d.ts} +127 -4
  14. package/dist/index-C5bsy9EC.d.ts.map +1 -0
  15. package/dist/index.d.ts +13 -5
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +7 -6
  18. package/dist/index.js.map +1 -1
  19. package/dist/local-sign-in-D2zVzXgm.js +12 -0
  20. package/dist/local-sign-in-D2zVzXgm.js.map +1 -0
  21. package/dist/{renown-BlvHEYjM.js → renown-BwJ9oWxt.js} +414 -64
  22. package/dist/renown-BwJ9oWxt.js.map +1 -0
  23. package/dist/src/ai/index.d.ts +1 -1
  24. package/dist/src/ai/index.js +2 -2
  25. package/dist/src/graphql-client/entry.d.ts +4 -4
  26. package/dist/src/graphql-client/entry.js +3 -3
  27. package/dist/src/renown/index.d.ts +2 -2
  28. package/dist/src/renown/index.js +2 -2
  29. package/dist/src/rpc/index.d.ts +17 -11
  30. package/dist/src/rpc/index.d.ts.map +1 -1
  31. package/dist/src/rpc/index.js +4 -3
  32. package/dist/src/rpc/index.js.map +1 -1
  33. package/dist/{switchboard-directory-CwT34q4g.js → switchboard-directory-7KPHB5Tz.js} +2 -2
  34. package/dist/{switchboard-directory-CwT34q4g.js.map → switchboard-directory-7KPHB5Tz.js.map} +1 -1
  35. package/package.json +11 -11
  36. package/dist/attachment-service-0E5S0hZ6.d.ts.map +0 -1
  37. package/dist/auth-DRbzRdeC.d.ts +0 -32
  38. package/dist/auth-DRbzRdeC.d.ts.map +0 -1
  39. package/dist/client-BFnMV-EO.js.map +0 -1
  40. package/dist/document-model-modules-DCC6DjOP.js.map +0 -1
  41. package/dist/document-operations-BUbpyfSf.js.map +0 -1
  42. package/dist/index-BlCYgfht.d.ts.map +0 -1
  43. package/dist/renown-BlvHEYjM.js.map +0 -1
@@ -0,0 +1,12 @@
1
+ import { t as makePHEventFunctions } from "./make-ph-event-functions-B5GU5xcR.js";
2
+ //#region src/hooks/local-sign-in.ts
3
+ const localSignInEventFunctions = makePHEventFunctions("localSignIn");
4
+ /** What sign-in by link needs of the person, if anything. */
5
+ const useLocalSignIn = localSignInEventFunctions.useValue;
6
+ /** Sets (or clears, with `undefined`) what sign-in by link needs. */
7
+ const setLocalSignIn = localSignInEventFunctions.setValue;
8
+ const addLocalSignInEventHandler = localSignInEventFunctions.addEventHandler;
9
+ //#endregion
10
+ export { setLocalSignIn as n, useLocalSignIn as r, addLocalSignInEventHandler as t };
11
+
12
+ //# sourceMappingURL=local-sign-in-D2zVzXgm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local-sign-in-D2zVzXgm.js","names":[],"sources":["../src/hooks/local-sign-in.ts"],"sourcesContent":["import type {\n LocalSignInState,\n SetPHGlobalValue,\n UsePHGlobalValue,\n} from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst localSignInEventFunctions = makePHEventFunctions(\"localSignIn\");\n\n/** What sign-in by link needs of the person, if anything. */\nexport const useLocalSignIn: UsePHGlobalValue<LocalSignInState> =\n localSignInEventFunctions.useValue;\n\n/** Sets (or clears, with `undefined`) what sign-in by link needs. */\nexport const setLocalSignIn: SetPHGlobalValue<LocalSignInState> =\n localSignInEventFunctions.setValue;\n\nexport const addLocalSignInEventHandler =\n localSignInEventFunctions.addEventHandler;\n"],"mappings":";;AAOA,MAAM,4BAA4B,qBAAqB,aAAa;;AAGpE,MAAa,iBACX,0BAA0B;;AAG5B,MAAa,iBACX,0BAA0B;AAE5B,MAAa,6BACX,0BAA0B"}
@@ -1,9 +1,10 @@
1
1
  import { c as getPHStore } from "./make-ph-event-functions-B5GU5xcR.js";
2
2
  import { R as setSearchParams, a as useRenown, c as RENOWN_INITIAL_UNKNOWN, i as useLoginStatus, l as RenownInitialUserProvider, n as setRenown, o as useUser, s as RENOWN_INITIAL_ANONYMOUS, t as addRenownEventHandler, u as useRenownInitialAuth, w as getPHNavigation } from "./renown-BXiV_I-t.js";
3
+ import { n as setLocalSignIn } from "./local-sign-in-D2zVzXgm.js";
3
4
  import { Children, cloneElement, createContext, forwardRef, isValidElement, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
5
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
6
  import { logger } from "document-model";
6
- import { BrowserKeyStorage, CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, DOMAIN_TYPE, ISSUER_TYPE, MissingSwitchboardError, RenownBuilder, RenownCryptoBuilder, VERIFIABLE_CREDENTIAL_EIP712_TYPE, consoleLogin, createDelegation, decodeDelegation, readPersistedUser } from "@renown/sdk";
7
+ import { BrowserKeyStorage, CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, DOMAIN_TYPE, ISSUER_TYPE, MissingSwitchboardError, RenownBuilder, RenownCryptoBuilder, VERIFIABLE_CREDENTIAL_EIP712_TYPE, anonymousLabel, consoleLogin, createDelegation, decodeDelegation, enrolBrowserCredential, ensureBrowserPseudonym, issueBrowserCredential, readBrowserPseudonym, readPersistedUser } from "@renown/sdk";
7
8
  import { LoginMethod, isWalletRedirectReturn, resolveAdapters } from "@renown/sdk/wallet";
8
9
  //#region src/renown/wallet-registry.ts
9
10
  let activeWalletController;
@@ -241,15 +242,23 @@ async function login(userDid, renown) {
241
242
  }
242
243
  }
243
244
  async function logout() {
245
+ const renown = getPHStore()?.renown;
244
246
  try {
245
- await (getActiveWalletController() ?? await getWalletActivator()?.())?.disconnect();
247
+ await (getActiveWalletController() ?? (renown?.user?.local ? void 0 : await getWalletActivator()?.()))?.disconnect();
246
248
  } catch (error) {
247
249
  logger.error(error instanceof Error ? error.message : String(error));
248
250
  }
249
- await (getPHStore()?.renown)?.logout();
251
+ await endSession(renown);
252
+ clearUserParamFromUrl();
253
+ }
254
+ /**
255
+ * Ends `renown`'s session without a wallet: what dropping a refused or
256
+ * expired credential does, also before the instance is in the store.
257
+ */
258
+ async function endSession(renown) {
259
+ await renown?.logout();
250
260
  resetSignInGuard();
251
261
  notifyReactorClientCredentialsChanged();
252
- clearUserParamFromUrl();
253
262
  }
254
263
  //#endregion
255
264
  //#region src/renown/use-renown-auth.ts
@@ -773,6 +782,12 @@ const styles = {
773
782
  },
774
783
  menuItemHover: { backgroundColor: "var(--accent, #f3f4f6)" },
775
784
  disconnectItem: { color: "var(--destructive, #dc2626)" },
785
+ note: {
786
+ margin: "8px 0 0",
787
+ fontSize: "12px",
788
+ lineHeight: 1.4,
789
+ color: "var(--muted-foreground, #6b7280)"
790
+ },
776
791
  separator: {
777
792
  height: "1px",
778
793
  backgroundColor: "var(--border, #e5e7eb)",
@@ -787,12 +802,13 @@ function truncateAddress(address) {
787
802
  function RenownUserButton({ address: addressProp, username: usernameProp, avatarUrl: avatarUrlProp, userId: userIdProp, onDisconnect: onDisconnectProp, style, className, asChild = false, children, menuItems }) {
788
803
  const user = useUser();
789
804
  const address = addressProp ?? user?.address ?? "";
790
- const username = usernameProp ?? user?.profile?.username ?? user?.ens?.name;
805
+ const localIdentity = addressProp ? void 0 : user?.localIdentity;
806
+ const username = usernameProp ?? user?.profile?.username ?? user?.ens?.name ?? (localIdentity && address ? anonymousLabel(address) : void 0);
791
807
  const avatarUrl = avatarUrlProp ?? user?.profile?.userImage ?? user?.ens?.avatarUrl;
792
808
  const userId = userIdProp ?? user?.profile?.documentId;
793
809
  const onDisconnect = onDisconnectProp ?? (() => void logout());
794
810
  const displayName = username ?? (address ? truncateAddress(address) : "Account");
795
- const profileId = userId ?? address;
811
+ const profileId = localIdentity ? void 0 : userId ?? address;
796
812
  const [isOpen, setIsOpen] = useState(false);
797
813
  const [isHovered, setIsHovered] = useState(false);
798
814
  const [isCopied, setIsCopied] = useState(false);
@@ -886,70 +902,95 @@ function RenownUserButton({ address: addressProp, username: usernameProp, avatar
886
902
  children: [
887
903
  /* @__PURE__ */ jsxs("div", {
888
904
  style: styles.header,
889
- children: [username && /* @__PURE__ */ jsx("div", {
890
- style: styles.headerUsername,
891
- children: username
892
- }), address && /* @__PURE__ */ jsx("div", {
893
- style: styles.addressRow,
894
- children: /* @__PURE__ */ jsx("button", {
895
- type: "button",
896
- onClick: () => void copyToClipboard(),
897
- style: styles.addressButton,
898
- children: /* @__PURE__ */ jsxs("div", {
899
- style: {
900
- position: "relative",
901
- display: "flex",
902
- alignItems: "center",
903
- gap: "4px",
904
- width: "100%"
905
- },
906
- children: [/* @__PURE__ */ jsxs("div", {
905
+ children: [
906
+ username && /* @__PURE__ */ jsx("div", {
907
+ style: styles.headerUsername,
908
+ children: username
909
+ }),
910
+ address && /* @__PURE__ */ jsx("div", {
911
+ style: styles.addressRow,
912
+ children: /* @__PURE__ */ jsx("button", {
913
+ type: "button",
914
+ onClick: () => void copyToClipboard(),
915
+ style: styles.addressButton,
916
+ children: /* @__PURE__ */ jsxs("div", {
907
917
  style: {
908
- ...styles.addressText,
909
- opacity: isCopied ? 0 : 1
918
+ position: "relative",
919
+ display: "flex",
920
+ alignItems: "center",
921
+ gap: "4px",
922
+ width: "100%"
910
923
  },
911
- children: [/* @__PURE__ */ jsx("span", { children: truncateAddress(address) }), /* @__PURE__ */ jsx(CopyIcon, {
912
- size: 12,
913
- color: "var(--muted-foreground, #9ca3af)"
924
+ children: [/* @__PURE__ */ jsxs("div", {
925
+ style: {
926
+ ...styles.addressText,
927
+ opacity: isCopied ? 0 : 1
928
+ },
929
+ children: [/* @__PURE__ */ jsx("span", { children: truncateAddress(address) }), /* @__PURE__ */ jsx(CopyIcon, {
930
+ size: 12,
931
+ color: "var(--muted-foreground, #9ca3af)"
932
+ })]
933
+ }), /* @__PURE__ */ jsx("div", {
934
+ style: {
935
+ ...styles.copiedText,
936
+ opacity: isCopied ? 1 : 0
937
+ },
938
+ children: "Copied!"
914
939
  })]
915
- }), /* @__PURE__ */ jsx("div", {
916
- style: {
917
- ...styles.copiedText,
918
- opacity: isCopied ? 1 : 0
919
- },
920
- children: "Copied!"
921
- })]
940
+ })
922
941
  })
942
+ }),
943
+ localIdentity === "browser" && /* @__PURE__ */ jsx("p", {
944
+ style: styles.note,
945
+ "data-testid": "browser-pseudonym-note",
946
+ children: "Kept in this browser only. Clearing this site's data loses it: your documents stay, but you can no longer sign as their author."
923
947
  })
924
- })]
948
+ ]
925
949
  }),
926
950
  /* @__PURE__ */ jsxs("div", {
927
951
  style: styles.menuSection,
928
- children: [profileId && /* @__PURE__ */ jsxs("button", {
929
- type: "button",
930
- onClick: () => openRenown(profileId),
931
- onMouseEnter: () => setHoveredItem("profile"),
932
- onMouseLeave: () => setHoveredItem(null),
933
- style: {
934
- ...styles.menuItem,
935
- ...hoveredItem === "profile" ? styles.menuItemHover : {}
936
- },
937
- children: [/* @__PURE__ */ jsx(UserIcon, {
938
- size: 14,
939
- color: "var(--muted-foreground, #6b7280)"
940
- }), "View Profile"]
941
- }), menuItems?.map((item) => /* @__PURE__ */ jsxs("button", {
942
- type: "button",
943
- onClick: item.onClick,
944
- onMouseEnter: () => setHoveredItem(item.label),
945
- onMouseLeave: () => setHoveredItem(null),
946
- style: {
947
- ...styles.menuItem,
948
- ...hoveredItem === item.label ? styles.menuItemHover : {},
949
- ...item.style
950
- },
951
- children: [item.icon, item.label]
952
- }, item.label))]
952
+ children: [
953
+ localIdentity === "browser" && /* @__PURE__ */ jsxs("button", {
954
+ type: "button",
955
+ onClick: () => openRenown(),
956
+ onMouseEnter: () => setHoveredItem("renown"),
957
+ onMouseLeave: () => setHoveredItem(null),
958
+ style: {
959
+ ...styles.menuItem,
960
+ ...hoveredItem === "renown" ? styles.menuItemHover : {}
961
+ },
962
+ children: [/* @__PURE__ */ jsx(UserIcon, {
963
+ size: 14,
964
+ color: "var(--muted-foreground, #6b7280)"
965
+ }), "Sign in with Renown"]
966
+ }),
967
+ profileId && /* @__PURE__ */ jsxs("button", {
968
+ type: "button",
969
+ onClick: () => openRenown(profileId),
970
+ onMouseEnter: () => setHoveredItem("profile"),
971
+ onMouseLeave: () => setHoveredItem(null),
972
+ style: {
973
+ ...styles.menuItem,
974
+ ...hoveredItem === "profile" ? styles.menuItemHover : {}
975
+ },
976
+ children: [/* @__PURE__ */ jsx(UserIcon, {
977
+ size: 14,
978
+ color: "var(--muted-foreground, #6b7280)"
979
+ }), "View Profile"]
980
+ }),
981
+ menuItems?.map((item) => /* @__PURE__ */ jsxs("button", {
982
+ type: "button",
983
+ onClick: item.onClick,
984
+ onMouseEnter: () => setHoveredItem(item.label),
985
+ onMouseLeave: () => setHoveredItem(null),
986
+ style: {
987
+ ...styles.menuItem,
988
+ ...hoveredItem === item.label ? styles.menuItemHover : {},
989
+ ...item.style
990
+ },
991
+ children: [item.icon, item.label]
992
+ }, item.label))
993
+ ]
953
994
  }),
954
995
  /* @__PURE__ */ jsx("hr", { style: styles.separator }),
955
996
  /* @__PURE__ */ jsx("div", {
@@ -1410,6 +1451,315 @@ function useRenownWalletAdapter(id) {
1410
1451
  return controller;
1411
1452
  }
1412
1453
  //#endregion
1413
- export { DOMAIN_TYPE as A, desktopShell as C, CREDENTIAL_SCHEMA_EIP712_TYPE as D, openRenown as E, RENOWN_URL as F, VERIFIABLE_CREDENTIAL_EIP712_TYPE as I, RENOWN_CHAIN_ID as M, RENOWN_NETWORK_ID as N, CREDENTIAL_SUBJECT_TYPE as O, RENOWN_RETURN_URL_STRIPPED_PARAMS as P, useRenownAuthAsync as S, logout as T, DisconnectIcon as _, RenownProvider as a, UserIcon as b, useRenownInit as c, initRenownCrypto as d, RenownAuthButton as f, CopyIcon as g, ChevronDownIcon as h, useRenownLoginMethods as i, ISSUER_TYPE as j, CREDENTIAL_TYPES as k, useRenownSessionCookie as l, RenownLoginButton as m, decodeDelegation as n, RenownWalletProvider as o, RenownUserButton as p, useRenownWalletAdapter as r, Renown as s, createDelegation as t, useRenownSessionSynced as u, RenownLogo as v, login as w, useRenownAuth as x, SpinnerIcon as y };
1454
+ //#region src/renown/local-sign-in.ts
1455
+ /**
1456
+ * Sign-in by link, the page's side (F3d): `ph dev` and `ph vetra` open the
1457
+ * page with `#ph-sign-in=<code>`, and the page exchanges the code once, at the
1458
+ * loopback endpoint of the process that serves it, for a credential that names
1459
+ * its session key, signed by the person's identity on this computer. The page
1460
+ * adopts it as a local user (`localIdentity: "machine"`) and renews it there
1461
+ * while the server runs. A credential a switchboard refuses for good is
1462
+ * dropped, and the page says how to get a fresh link.
1463
+ */
1464
+ /** As `LOCAL_SIGN_IN_ROUTES` of `@powerhousedao/shared/clis/local-sign-in`. */
1465
+ const ROUTES = {
1466
+ signIn: "__ph/sign-in",
1467
+ renew: "__ph/renew"
1468
+ };
1469
+ /** How long before its end a credential is renewed. */
1470
+ const LOCAL_SIGN_IN_RENEW_DAYS = 7;
1471
+ /** Refusals no retry with the same credential can change: it is dropped. */
1472
+ const DROPPED_CREDENTIAL_REASONS = /* @__PURE__ */ new Set([
1473
+ "expired",
1474
+ "withdrawn-here",
1475
+ "withdrawn-at-renown",
1476
+ "bad-credential"
1477
+ ]);
1478
+ const DAY_MS = 864e5;
1479
+ const RENEW_EVERY_MS$1 = 216e5;
1480
+ const PROBE_TIMEOUT_MS = 2e3;
1481
+ const REQUEST_TIMEOUT_MS = 15e3;
1482
+ const BOOT_RENEW_WAIT_MS = 3e3;
1483
+ function routeUrl(endpoint, route) {
1484
+ const base = endpoint.base.endsWith("/") ? endpoint.base : `${endpoint.base}/`;
1485
+ const page = endpoint.origin ? `${endpoint.origin}/` : globalThis.location.href;
1486
+ return new URL(`${base}${route}`, page).href;
1487
+ }
1488
+ async function post(endpoint, route, body, bearer) {
1489
+ try {
1490
+ const response = await (endpoint.fetch ?? globalThis.fetch)(routeUrl(endpoint, route), {
1491
+ method: "POST",
1492
+ headers: {
1493
+ "content-type": "application/json",
1494
+ ...bearer ? { authorization: `Bearer ${bearer}` } : {}
1495
+ },
1496
+ body: JSON.stringify(body),
1497
+ cache: "no-store",
1498
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1499
+ });
1500
+ const answer = await response.json().catch(() => void 0);
1501
+ if (!answer || typeof answer !== "object") return void 0;
1502
+ if (response.ok) return answer.credential ? {
1503
+ ...answer,
1504
+ ok: true
1505
+ } : void 0;
1506
+ return {
1507
+ ok: false,
1508
+ status: response.status,
1509
+ reason: typeof answer.reason === "string" ? answer.reason : "failed",
1510
+ ...typeof answer.triesLeft === "number" ? { triesLeft: answer.triesLeft } : {},
1511
+ ...typeof answer.label === "string" ? { label: answer.label } : {}
1512
+ };
1513
+ } catch {
1514
+ return;
1515
+ }
1516
+ }
1517
+ /** Whether the server that serves this page signs pages in by link. */
1518
+ async function localSignInAvailable(endpoint) {
1519
+ try {
1520
+ const response = await (endpoint.fetch ?? globalThis.fetch)(routeUrl(endpoint, ROUTES.signIn), {
1521
+ cache: "no-store",
1522
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)
1523
+ });
1524
+ if (!response.ok) return false;
1525
+ return (await response.json().catch(() => void 0))?.available === true;
1526
+ } catch {
1527
+ return false;
1528
+ }
1529
+ }
1530
+ /** Exchanges a link's one-time code for a credential for `sessionDid`. */
1531
+ function exchangeLocalSignIn(endpoint, o) {
1532
+ return post(endpoint, ROUTES.signIn, o);
1533
+ }
1534
+ /** A new credential for the session whose `bearer` carries one issued here. */
1535
+ function renewLocalSignIn(endpoint, o) {
1536
+ return post(endpoint, ROUTES.renew, o.password === void 0 ? {} : { password: o.password }, o.bearer);
1537
+ }
1538
+ /** Whether `credential` ends within `days` of `now` (or has ended). */
1539
+ function credentialEndsWithin(credential, days, now) {
1540
+ const ends = Date.parse(credential?.expirationDate ?? "");
1541
+ return !Number.isNaN(ends) && ends - now < days * DAY_MS;
1542
+ }
1543
+ /**
1544
+ * The tab's answer to a credential a switchboard refused (for
1545
+ * `setCredentialRefusalHandler`): a refusal for good drops it and the request
1546
+ * goes again anonymously; `not-registered` enrols the browser's pseudonym at
1547
+ * that switchboard and the request goes again with it.
1548
+ */
1549
+ function credentialRefusalHandler(o) {
1550
+ return async ({ reason, url }) => {
1551
+ if (DROPPED_CREDENTIAL_REASONS.has(reason)) {
1552
+ await o.localSignIn.drop(reason);
1553
+ return "anonymous";
1554
+ }
1555
+ if (reason === "not-registered" && url && o.browserIdentity && o.renown.user?.localIdentity === "browser") return await o.browserIdentity.enrolAt(url) ? "again" : void 0;
1556
+ };
1557
+ }
1558
+ function createLocalSignIn(o) {
1559
+ const { renown } = o;
1560
+ const now = o.now ?? Date.now;
1561
+ let timer;
1562
+ const dismiss = () => setLocalSignIn(void 0);
1563
+ async function adopt(answer) {
1564
+ if (renown.user && renown.user.localIdentity !== "machine") await endSession(renown);
1565
+ await renown.adoptCredential(answer.credential, {
1566
+ local: true,
1567
+ localIdentity: "machine"
1568
+ });
1569
+ setLocalSignIn(void 0);
1570
+ notifyReactorClientCredentialsChanged();
1571
+ }
1572
+ /** Asks the password while the server keeps the code (or the bearer). */
1573
+ function askPassword(triesLeft, retry) {
1574
+ setLocalSignIn({
1575
+ status: "password",
1576
+ ...triesLeft === void 0 ? {} : { triesLeft },
1577
+ submit: retry,
1578
+ dismiss
1579
+ });
1580
+ }
1581
+ async function signIn(code, password) {
1582
+ const answer = await exchangeLocalSignIn(o, {
1583
+ code,
1584
+ sessionDid: renown.did,
1585
+ ...password === void 0 ? {} : { password }
1586
+ });
1587
+ if (!answer) {
1588
+ setLocalSignIn({
1589
+ status: "failed",
1590
+ reason: "unreachable",
1591
+ dismiss
1592
+ });
1593
+ return;
1594
+ }
1595
+ if (answer.ok) return adopt(answer);
1596
+ if (answer.status === 423 || answer.reason === "wrong-password" && (answer.triesLeft ?? 0) > 0) {
1597
+ askPassword(answer.triesLeft, (next) => signIn(code, next));
1598
+ return;
1599
+ }
1600
+ setLocalSignIn({
1601
+ status: "failed",
1602
+ reason: answer.reason,
1603
+ ...answer.label ? { label: answer.label } : {},
1604
+ dismiss
1605
+ });
1606
+ }
1607
+ async function drop(reason) {
1608
+ const user = renown.user;
1609
+ if (!user) return;
1610
+ logger.warn("Dropping the sign-in of @address: @reason", user.address, reason);
1611
+ await endSession(renown);
1612
+ if (user.localIdentity === "machine") setLocalSignIn({
1613
+ status: "ended",
1614
+ reason
1615
+ });
1616
+ }
1617
+ async function renew(password) {
1618
+ const user = renown.user;
1619
+ if (user?.localIdentity !== "machine") return;
1620
+ if (!credentialEndsWithin(user.credential, 7, now())) return;
1621
+ if (credentialEndsWithin(user.credential, 0, now())) {
1622
+ await drop("expired");
1623
+ return;
1624
+ }
1625
+ const answer = await renewLocalSignIn(o, {
1626
+ bearer: await renown.getBearerToken({ expiresIn: 60 }),
1627
+ ...password === void 0 ? {} : { password }
1628
+ });
1629
+ if (!answer) return;
1630
+ if (answer.ok) return adopt(answer);
1631
+ if (answer.status === 423 || answer.reason === "wrong-password") {
1632
+ askPassword(answer.triesLeft, (next) => renew(next));
1633
+ return;
1634
+ }
1635
+ if (answer.status === 401) await drop(answer.reason);
1636
+ }
1637
+ return {
1638
+ async start(fragment) {
1639
+ if (fragment?.kind === "sign-out") {
1640
+ await endSession(renown);
1641
+ setLocalSignIn(void 0);
1642
+ } else if (fragment?.kind === "sign-in") await signIn(fragment.code);
1643
+ const user = renown.user;
1644
+ if (user && credentialEndsWithin(user.credential, 0, now())) await drop("expired");
1645
+ const renewing = renew().catch((error) => logger.warn("Could not renew the sign-in: @error", error));
1646
+ await Promise.race([renewing, new Promise((resolve) => setTimeout(resolve, BOOT_RENEW_WAIT_MS))]);
1647
+ timer ??= setInterval(() => {
1648
+ renew().catch((error) => logger.warn("Could not renew the sign-in: @error", error));
1649
+ }, o.renewEveryMs ?? RENEW_EVERY_MS$1);
1650
+ },
1651
+ renew: () => renew(),
1652
+ drop,
1653
+ stop() {
1654
+ clearInterval(timer);
1655
+ timer = void 0;
1656
+ }
1657
+ };
1658
+ }
1659
+ //#endregion
1660
+ //#region src/renown/browser-identity.ts
1661
+ /**
1662
+ * Hosted Connect without a login (F3d): at the first signature with nobody
1663
+ * logged in, this browser's pseudonym (made when it has none, kept in
1664
+ * IndexedDB) signs a credential for the tab's session key, the tab signs in
1665
+ * with it (`localIdentity: "browser"`), and the switchboards it writes to are
1666
+ * asked to keep its record. A page a local server signs in by link is left to
1667
+ * its link, so one person does not get two pseudonyms.
1668
+ */
1669
+ const RENEW_EVERY_MS = 216e5;
1670
+ const ENROL_TIMEOUT_MS = 5e3;
1671
+ /** A switchboard's base URL from its GraphQL endpoint (or base). */
1672
+ function switchboardBaseOf(url) {
1673
+ return url.replace(/\/graphql(?:\/.*)?$/, "").replace(/\/+$/, "");
1674
+ }
1675
+ function createBrowserIdentity(o) {
1676
+ const { renown } = o;
1677
+ const now = o.now ?? Date.now;
1678
+ const baseFetch = o.fetch ?? ((input, init) => globalThis.fetch(input, init));
1679
+ const fetch = (input, init) => baseFetch(input, {
1680
+ ...init,
1681
+ signal: init?.signal ?? AbortSignal.timeout(ENROL_TIMEOUT_MS)
1682
+ });
1683
+ let pending;
1684
+ let leftToLink = false;
1685
+ let timer;
1686
+ const enrolling = /* @__PURE__ */ new Map();
1687
+ async function enrol(pseudonym, credential, hosts) {
1688
+ const outcomes = await enrolBrowserCredential({
1689
+ pseudonym,
1690
+ credential,
1691
+ hosts: hosts.map(switchboardBaseOf),
1692
+ fetch
1693
+ });
1694
+ for (const outcome of outcomes) if (!outcome.ok) logger.warn("Could not enrol this browser's pseudonym at @host: @error", outcome.host, outcome.error);
1695
+ return outcomes.every((outcome) => outcome.ok);
1696
+ }
1697
+ async function signIn(pseudonym) {
1698
+ const credential = await issueBrowserCredential(pseudonym, {
1699
+ sessionDid: renown.did,
1700
+ ...o.chainId === void 0 ? {} : { chainId: o.chainId }
1701
+ });
1702
+ await enrol(pseudonym, credential, o.hosts());
1703
+ await renown.adoptCredential(credential, {
1704
+ local: true,
1705
+ localIdentity: "browser"
1706
+ });
1707
+ notifyReactorClientCredentialsChanged();
1708
+ }
1709
+ /** The kept pseudonym, when it is the signed-in browser identity's. */
1710
+ async function currentPseudonym() {
1711
+ const user = renown.user;
1712
+ if (user?.localIdentity !== "browser") return void 0;
1713
+ const pseudonym = await readBrowserPseudonym(await o.store());
1714
+ return pseudonym?.address.toLowerCase() === user.address.toLowerCase() ? pseudonym : void 0;
1715
+ }
1716
+ async function renew() {
1717
+ const user = renown.user;
1718
+ if (user?.localIdentity !== "browser" || !credentialEndsWithin(user.credential, 7, now())) return;
1719
+ const pseudonym = await currentPseudonym();
1720
+ if (pseudonym) await signIn(pseudonym);
1721
+ }
1722
+ return {
1723
+ ensure() {
1724
+ if (renown.user || leftToLink) return Promise.resolve();
1725
+ pending ??= (async () => {
1726
+ if (await o.localSignInAvailable()) {
1727
+ leftToLink = true;
1728
+ return;
1729
+ }
1730
+ await signIn(await ensureBrowserPseudonym(await o.store(), now));
1731
+ })().finally(() => {
1732
+ pending = void 0;
1733
+ });
1734
+ return pending;
1735
+ },
1736
+ renew,
1737
+ enrolAt(url) {
1738
+ const base = switchboardBaseOf(url);
1739
+ let running = enrolling.get(base);
1740
+ if (!running) {
1741
+ running = (async () => {
1742
+ const credential = renown.user?.credential;
1743
+ const pseudonym = await currentPseudonym();
1744
+ if (!pseudonym || !credential) return false;
1745
+ return enrol(pseudonym, credential, [base]);
1746
+ })().finally(() => enrolling.delete(base));
1747
+ enrolling.set(base, running);
1748
+ }
1749
+ return running;
1750
+ },
1751
+ start() {
1752
+ const run = () => void renew().catch((error) => logger.warn("Could not renew this browser's pseudonym: @error", error));
1753
+ run();
1754
+ timer ??= setInterval(run, o.renewEveryMs ?? RENEW_EVERY_MS);
1755
+ },
1756
+ stop() {
1757
+ clearInterval(timer);
1758
+ timer = void 0;
1759
+ }
1760
+ };
1761
+ }
1762
+ //#endregion
1763
+ export { UserIcon as A, DOMAIN_TYPE as B, RenownUserButton as C, DisconnectIcon as D, CopyIcon as E, logout as F, RENOWN_URL as G, RENOWN_CHAIN_ID as H, openRenown as I, VERIFIABLE_CREDENTIAL_EIP712_TYPE as K, CREDENTIAL_SCHEMA_EIP712_TYPE as L, useRenownAuthAsync as M, desktopShell as N, RenownLogo as O, login as P, CREDENTIAL_SUBJECT_TYPE as R, RenownAuthButton as S, ChevronDownIcon as T, RENOWN_NETWORK_ID as U, ISSUER_TYPE as V, RENOWN_RETURN_URL_STRIPPED_PARAMS as W, Renown as _, DROPPED_CREDENTIAL_REASONS as a, useRenownSessionSynced as b, credentialEndsWithin as c, localSignInAvailable as d, renewLocalSignIn as f, RenownWalletProvider as g, RenownProvider as h, switchboardBaseOf as i, useRenownAuth as j, SpinnerIcon as k, credentialRefusalHandler as l, useRenownLoginMethods as m, decodeDelegation as n, LOCAL_SIGN_IN_RENEW_DAYS as o, useRenownWalletAdapter as p, createBrowserIdentity as r, createLocalSignIn as s, createDelegation as t, exchangeLocalSignIn as u, useRenownInit as v, RenownLoginButton as w, initRenownCrypto as x, useRenownSessionCookie as y, CREDENTIAL_TYPES as z };
1414
1764
 
1415
- //# sourceMappingURL=renown-BlvHEYjM.js.map
1765
+ //# sourceMappingURL=renown-BwJ9oWxt.js.map