@eloxiv/client 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Account.d.ts +131 -0
  4. package/dist/Account.d.ts.map +1 -0
  5. package/dist/Account.js +169 -0
  6. package/dist/Account.js.map +1 -0
  7. package/dist/Agent.d.ts +496 -0
  8. package/dist/Agent.d.ts.map +1 -0
  9. package/dist/Agent.js +228 -0
  10. package/dist/Agent.js.map +1 -0
  11. package/dist/AgentSync.d.ts +990 -0
  12. package/dist/AgentSync.d.ts.map +1 -0
  13. package/dist/AgentSync.js +46 -0
  14. package/dist/AgentSync.js.map +1 -0
  15. package/dist/AppState.d.ts +127 -0
  16. package/dist/AppState.d.ts.map +1 -0
  17. package/dist/AppState.js +145 -0
  18. package/dist/AppState.js.map +1 -0
  19. package/dist/AppStateSync.d.ts +193 -0
  20. package/dist/AppStateSync.d.ts.map +1 -0
  21. package/dist/AppStateSync.js +23 -0
  22. package/dist/AppStateSync.js.map +1 -0
  23. package/dist/Auth.d.ts +95 -0
  24. package/dist/Auth.d.ts.map +1 -0
  25. package/dist/Auth.js +139 -0
  26. package/dist/Auth.js.map +1 -0
  27. package/dist/Avatars.d.ts +53 -0
  28. package/dist/Avatars.d.ts.map +1 -0
  29. package/dist/Avatars.js +121 -0
  30. package/dist/Avatars.js.map +1 -0
  31. package/dist/BrowserAnalytics.d.ts +56 -0
  32. package/dist/BrowserAnalytics.d.ts.map +1 -0
  33. package/dist/BrowserAnalytics.js +94 -0
  34. package/dist/BrowserAnalytics.js.map +1 -0
  35. package/dist/Chat.d.ts +712 -0
  36. package/dist/Chat.d.ts.map +1 -0
  37. package/dist/Chat.js +883 -0
  38. package/dist/Chat.js.map +1 -0
  39. package/dist/ChatIntegrity.d.ts +63 -0
  40. package/dist/ChatIntegrity.d.ts.map +1 -0
  41. package/dist/ChatIntegrity.js +89 -0
  42. package/dist/ChatIntegrity.js.map +1 -0
  43. package/dist/ChatSends.d.ts +103 -0
  44. package/dist/ChatSends.d.ts.map +1 -0
  45. package/dist/ChatSends.js +157 -0
  46. package/dist/ChatSends.js.map +1 -0
  47. package/dist/Client.d.ts +113 -0
  48. package/dist/Client.d.ts.map +1 -0
  49. package/dist/Client.js +189 -0
  50. package/dist/Client.js.map +1 -0
  51. package/dist/Collab.d.ts +138 -0
  52. package/dist/Collab.d.ts.map +1 -0
  53. package/dist/Collab.js +454 -0
  54. package/dist/Collab.js.map +1 -0
  55. package/dist/CollabTools.d.ts +129 -0
  56. package/dist/CollabTools.d.ts.map +1 -0
  57. package/dist/CollabTools.js +277 -0
  58. package/dist/CollabTools.js.map +1 -0
  59. package/dist/Connections.d.ts +288 -0
  60. package/dist/Connections.d.ts.map +1 -0
  61. package/dist/Connections.js +316 -0
  62. package/dist/Connections.js.map +1 -0
  63. package/dist/Consent.d.ts +338 -0
  64. package/dist/Consent.d.ts.map +1 -0
  65. package/dist/Consent.js +142 -0
  66. package/dist/Consent.js.map +1 -0
  67. package/dist/Desktop.d.ts +61 -0
  68. package/dist/Desktop.d.ts.map +1 -0
  69. package/dist/Desktop.js +101 -0
  70. package/dist/Desktop.js.map +1 -0
  71. package/dist/Directory.d.ts +36 -0
  72. package/dist/Directory.d.ts.map +1 -0
  73. package/dist/Directory.js +42 -0
  74. package/dist/Directory.js.map +1 -0
  75. package/dist/ErrorReporter.d.ts +48 -0
  76. package/dist/ErrorReporter.d.ts.map +1 -0
  77. package/dist/ErrorReporter.js +70 -0
  78. package/dist/ErrorReporter.js.map +1 -0
  79. package/dist/ExpoSqlite.d.ts +7 -0
  80. package/dist/ExpoSqlite.d.ts.map +1 -0
  81. package/dist/ExpoSqlite.js +7 -0
  82. package/dist/ExpoSqlite.js.map +1 -0
  83. package/dist/FileSync.d.ts +265 -0
  84. package/dist/FileSync.d.ts.map +1 -0
  85. package/dist/FileSync.js +29 -0
  86. package/dist/FileSync.js.map +1 -0
  87. package/dist/FileTables.gen.d.ts +109 -0
  88. package/dist/FileTables.gen.d.ts.map +1 -0
  89. package/dist/FileTables.gen.js +23 -0
  90. package/dist/FileTables.gen.js.map +1 -0
  91. package/dist/Foldkit.d.ts +487 -0
  92. package/dist/Foldkit.d.ts.map +1 -0
  93. package/dist/Foldkit.js +617 -0
  94. package/dist/Foldkit.js.map +1 -0
  95. package/dist/History.d.ts +133 -0
  96. package/dist/History.d.ts.map +1 -0
  97. package/dist/History.js +210 -0
  98. package/dist/History.js.map +1 -0
  99. package/dist/InboxSync.d.ts +428 -0
  100. package/dist/InboxSync.d.ts.map +1 -0
  101. package/dist/InboxSync.js +37 -0
  102. package/dist/InboxSync.js.map +1 -0
  103. package/dist/KernelTables.gen.d.ts +1522 -0
  104. package/dist/KernelTables.gen.d.ts.map +1 -0
  105. package/dist/KernelTables.gen.js +307 -0
  106. package/dist/KernelTables.gen.js.map +1 -0
  107. package/dist/Make.d.ts +75 -0
  108. package/dist/Make.d.ts.map +1 -0
  109. package/dist/Make.js +70 -0
  110. package/dist/Make.js.map +1 -0
  111. package/dist/Models.d.ts +88 -0
  112. package/dist/Models.d.ts.map +1 -0
  113. package/dist/Models.js +80 -0
  114. package/dist/Models.js.map +1 -0
  115. package/dist/Optimistic.d.ts +120 -0
  116. package/dist/Optimistic.d.ts.map +1 -0
  117. package/dist/Optimistic.js +231 -0
  118. package/dist/Optimistic.js.map +1 -0
  119. package/dist/PlatformSync.d.ts +273 -0
  120. package/dist/PlatformSync.d.ts.map +1 -0
  121. package/dist/PlatformSync.js +92 -0
  122. package/dist/PlatformSync.js.map +1 -0
  123. package/dist/Poll.d.ts +113 -0
  124. package/dist/Poll.d.ts.map +1 -0
  125. package/dist/Poll.js +179 -0
  126. package/dist/Poll.js.map +1 -0
  127. package/dist/Preferences.d.ts +18 -0
  128. package/dist/Preferences.d.ts.map +1 -0
  129. package/dist/Preferences.js +22 -0
  130. package/dist/Preferences.js.map +1 -0
  131. package/dist/Proposals.d.ts +29 -0
  132. package/dist/Proposals.d.ts.map +1 -0
  133. package/dist/Proposals.js +41 -0
  134. package/dist/Proposals.js.map +1 -0
  135. package/dist/React.d.ts +17 -0
  136. package/dist/React.d.ts.map +1 -0
  137. package/dist/React.js +17 -0
  138. package/dist/React.js.map +1 -0
  139. package/dist/Reader.d.ts +35 -0
  140. package/dist/Reader.d.ts.map +1 -0
  141. package/dist/Reader.js +136 -0
  142. package/dist/Reader.js.map +1 -0
  143. package/dist/Resources.d.ts +98 -0
  144. package/dist/Resources.d.ts.map +1 -0
  145. package/dist/Resources.js +161 -0
  146. package/dist/Resources.js.map +1 -0
  147. package/dist/Rows.d.ts +4 -0
  148. package/dist/Rows.d.ts.map +1 -0
  149. package/dist/Rows.js +16 -0
  150. package/dist/Rows.js.map +1 -0
  151. package/dist/Runtime.d.ts +254 -0
  152. package/dist/Runtime.d.ts.map +1 -0
  153. package/dist/Runtime.js +1283 -0
  154. package/dist/Runtime.js.map +1 -0
  155. package/dist/RuntimeRuns.d.ts +74 -0
  156. package/dist/RuntimeRuns.d.ts.map +1 -0
  157. package/dist/RuntimeRuns.js +118 -0
  158. package/dist/RuntimeRuns.js.map +1 -0
  159. package/dist/ServicesSync.d.ts +286 -0
  160. package/dist/ServicesSync.d.ts.map +1 -0
  161. package/dist/ServicesSync.js +40 -0
  162. package/dist/ServicesSync.js.map +1 -0
  163. package/dist/Session.d.ts +228 -0
  164. package/dist/Session.d.ts.map +1 -0
  165. package/dist/Session.js +792 -0
  166. package/dist/Session.js.map +1 -0
  167. package/dist/ShareGrant.d.ts +47 -0
  168. package/dist/ShareGrant.d.ts.map +1 -0
  169. package/dist/ShareGrant.js +20 -0
  170. package/dist/ShareGrant.js.map +1 -0
  171. package/dist/Sharing.d.ts +203 -0
  172. package/dist/Sharing.d.ts.map +1 -0
  173. package/dist/Sharing.js +520 -0
  174. package/dist/Sharing.js.map +1 -0
  175. package/dist/Skew.d.ts +52 -0
  176. package/dist/Skew.d.ts.map +1 -0
  177. package/dist/Skew.js +77 -0
  178. package/dist/Skew.js.map +1 -0
  179. package/dist/SpacesSync.d.ts +247 -0
  180. package/dist/SpacesSync.d.ts.map +1 -0
  181. package/dist/SpacesSync.js +30 -0
  182. package/dist/SpacesSync.js.map +1 -0
  183. package/dist/Storage.d.ts +51 -0
  184. package/dist/Storage.d.ts.map +1 -0
  185. package/dist/Storage.js +107 -0
  186. package/dist/Storage.js.map +1 -0
  187. package/dist/Sync.d.ts +48 -0
  188. package/dist/Sync.d.ts.map +1 -0
  189. package/dist/Sync.js +48 -0
  190. package/dist/Sync.js.map +1 -0
  191. package/dist/SyncTables.d.ts +13 -0
  192. package/dist/SyncTables.d.ts.map +1 -0
  193. package/dist/SyncTables.js +13 -0
  194. package/dist/SyncTables.js.map +1 -0
  195. package/dist/Tab.d.ts +36 -0
  196. package/dist/Tab.d.ts.map +1 -0
  197. package/dist/Tab.js +44 -0
  198. package/dist/Tab.js.map +1 -0
  199. package/dist/Transport.d.ts +139 -0
  200. package/dist/Transport.d.ts.map +1 -0
  201. package/dist/Transport.js +232 -0
  202. package/dist/Transport.js.map +1 -0
  203. package/dist/Upload.d.ts +41 -0
  204. package/dist/Upload.d.ts.map +1 -0
  205. package/dist/Upload.js +93 -0
  206. package/dist/Upload.js.map +1 -0
  207. package/dist/WebMcp.d.ts +78 -0
  208. package/dist/WebMcp.d.ts.map +1 -0
  209. package/dist/WebMcp.js +204 -0
  210. package/dist/WebMcp.js.map +1 -0
  211. package/dist/index.d.ts +27 -0
  212. package/dist/index.d.ts.map +1 -0
  213. package/dist/index.js +27 -0
  214. package/dist/index.js.map +1 -0
  215. package/package.json +97 -3
  216. package/src/Account.ts +249 -0
  217. package/src/Agent.ts +387 -0
  218. package/src/AgentSync.ts +59 -0
  219. package/src/AppState.ts +222 -0
  220. package/src/AppStateSync.ts +26 -0
  221. package/src/Auth.ts +225 -0
  222. package/src/Avatars.ts +144 -0
  223. package/src/BrowserAnalytics.ts +133 -0
  224. package/src/Chat.ts +1150 -0
  225. package/src/ChatIntegrity.ts +130 -0
  226. package/src/ChatSends.ts +209 -0
  227. package/src/Client.ts +319 -0
  228. package/src/Collab.ts +524 -0
  229. package/src/CollabTools.ts +381 -0
  230. package/src/Connections.ts +517 -0
  231. package/src/Consent.ts +176 -0
  232. package/src/Desktop.ts +139 -0
  233. package/src/Directory.ts +71 -0
  234. package/src/ErrorReporter.ts +112 -0
  235. package/src/ExpoSqlite.ts +6 -0
  236. package/src/FileSync.ts +34 -0
  237. package/src/FileTables.gen.ts +23 -0
  238. package/src/Foldkit.ts +960 -0
  239. package/src/History.ts +337 -0
  240. package/src/InboxSync.ts +47 -0
  241. package/src/KernelTables.gen.ts +329 -0
  242. package/src/Make.ts +120 -0
  243. package/src/Models.ts +134 -0
  244. package/src/Optimistic.ts +364 -0
  245. package/src/PlatformSync.ts +156 -0
  246. package/src/Poll.ts +227 -0
  247. package/src/Preferences.ts +42 -0
  248. package/src/Proposals.ts +57 -0
  249. package/src/React.ts +26 -0
  250. package/src/Reader.ts +180 -0
  251. package/src/Resources.ts +257 -0
  252. package/src/Rows.ts +16 -0
  253. package/src/Runtime.ts +1442 -0
  254. package/src/RuntimeRuns.ts +180 -0
  255. package/src/ServicesSync.ts +58 -0
  256. package/src/Session.ts +844 -0
  257. package/src/ShareGrant.ts +20 -0
  258. package/src/Sharing.ts +696 -0
  259. package/src/Skew.ts +97 -0
  260. package/src/SpacesSync.ts +61 -0
  261. package/src/Storage.ts +167 -0
  262. package/src/Sync.ts +125 -0
  263. package/src/SyncTables.ts +12 -0
  264. package/src/Tab.ts +59 -0
  265. package/src/Transport.ts +321 -0
  266. package/src/Upload.ts +125 -0
  267. package/src/WebMcp.ts +279 -0
  268. package/src/index.ts +26 -0
  269. package/src/web-globals.d.ts +103 -0
@@ -0,0 +1,792 @@
1
+ /**
2
+ * The signed-in session, headless: one controller per app (or per window) that every view shares, so the page has
3
+ * one verified read of who is signed in, one sign-out, and one place that hears a session ended. Framework-free: a
4
+ * Foldkit program subscribes to it with a Subscription, any other UI with `subscribe`.
5
+ *
6
+ * States: `loading` (the stored session not checked yet), `authenticated` (checked with the kernel, `token` and
7
+ * `account`), `unauthenticated`, `unavailable` (the kernel could not be reached to check it: the stored session is
8
+ * kept, and `refresh` checks again; the client core may open the replica its store remembers for it meanwhile,
9
+ * `SessionStore.recall`), `signing-out`.
10
+ *
11
+ * Guarantees:
12
+ * - **One verified read.** `start`, `refresh` and `invalidate` share one check in flight; a stored token is never
13
+ * reported `authenticated` before the kernel accepted it.
14
+ * - **A session is stored only once adopted.** `adopt` (and the sign-ins through it) checks the account before it
15
+ * stores the token; an adoption overtaken by a sign-out or another adoption, or whose check fails, stores
16
+ * nothing and revokes the session it was given, unless something else holds that token: the current or the
17
+ * stored session, or another adoption of it still running or accepted.
18
+ * - **One writer at a time.** A check's answer, an adoption's acceptance or cleanup and a sign-out's end change
19
+ * the store and the state one at a time, in order; a check that began before a session was adopted or a
20
+ * sign-out began changes neither (it cannot restore the previous session or forget the new one), and a session
21
+ * is forgotten only while the store still holds it (`SessionStore.clearIf`).
22
+ * - **A session the kernel refuses is forgotten.** A 401 (on the check, or one the client core heard elsewhere:
23
+ * `refuse`) reports `unauthenticated` first, so the views close before any storage is touched, and then clears
24
+ * the store in the background, retried until it succeeds (its remembered context forgotten meanwhile). The refused
25
+ * token is remembered in memory for the store it came from, so no later check in this process reports it or lets
26
+ * it be reopened offline, even while the store still holds it. A network failure or a 5xx retries with backoff
27
+ * and then reports `unavailable`, keeping it. The first check of a token with a remembered context makes one
28
+ * attempt within `offlineProbeMs`, so an offline start is not held up by a stalled connection; a late refusal is
29
+ * applied at once (a newer check still in flight cannot replace it), a late acceptance is checked again.
30
+ * - **Sign-out stops reads first.** `signOut` reports `signing-out` and `token()` returns nothing before the
31
+ * revocation is sent, so no view issues another authenticated read; the stored session is kept until the kernel
32
+ * confirms the revocation (retried with backoff), then cleared. The token it revokes is refused to an adoption
33
+ * from before the revocation is sent (a changed password's unrotated token), so no revoked session is reported.
34
+ * - **A durable sign-out survives the page** (with `revocations`, a browser's storage). The revocation is kept in
35
+ * that store (read back) and the stored session forgotten before the person is reported `unauthenticated`, so an
36
+ * interruption at any instant after the signed-out state shows (a reload, a closed tab) finds the revocation, never
37
+ * the session. When the store will not keep it, the token stays in memory, the stored session stays (a reload finds
38
+ * a session the kernel still accepts, never a token nobody holds) with its remembered context forgotten, so an
39
+ * offline restart reopens nothing (`SignOutNotSaved` when that cannot be saved either), and a sign-in or adoption
40
+ * is refused
41
+ * (`UnsavedSignOut`) until the revocation is stored or confirmed. Pending revocations are retried
42
+ * (`retryRevocations`, each attempt with a timeout) and leave the store only when the kernel confirms them (revoked
43
+ * now, or refused already: 401) and the session's slot or its remembered context is gone (cleared first, retried
44
+ * while it fails); `revocationStatus` says where the last sign-out stands. A stored session whose token is pending
45
+ * there (its slot survived the sign-out) is never checked or reported, and its slot is forgotten. A slot that
46
+ * cannot be read at sign-out is a failure (`SignOutNotSaved`), never "nobody signed in", unless the caller knows
47
+ * the token (an offline start's); a sign-out that failed keeps its token, so trying again revokes the same one.
48
+ */
49
+ import { getAccount, verifyTwoFactor } from "./Account.js";
50
+ import { AuthError, signIn, signOut } from "./Auth.js";
51
+ /** A store in memory only (nothing survives a reload). */
52
+ export const memorySessionStore = () => {
53
+ let token;
54
+ let remembered;
55
+ const forget = () => {
56
+ token = undefined;
57
+ remembered = undefined;
58
+ };
59
+ return {
60
+ load: async () => token,
61
+ save: async (next) => {
62
+ if (next !== token)
63
+ remembered = undefined;
64
+ token = next;
65
+ },
66
+ clear: async () => forget(),
67
+ clearIf: async (expected) => {
68
+ if (token === expected)
69
+ forget();
70
+ },
71
+ recall: async (expected) => (remembered?.token === expected && token === expected ? remembered.context : undefined),
72
+ remember: async (next, context) => {
73
+ if (next === token)
74
+ remembered = { token: next, context };
75
+ },
76
+ forgetContext: async (expected) => {
77
+ if (remembered?.token === expected)
78
+ remembered = undefined;
79
+ },
80
+ };
81
+ };
82
+ /** A sign-in refused while a sign-out's revocation exists only in memory (the revocation store would not keep it). */
83
+ export class UnsavedSignOut extends Error {
84
+ name = "UnsavedSignOut";
85
+ constructor() {
86
+ super("Your last sign-out has not reached the server, and this browser could not save it to retry later. " +
87
+ "It is being retried: sign in again once it has gone through.");
88
+ }
89
+ }
90
+ /**
91
+ * A sign-out that could not be saved on this device (a durable sign-out whose revocation the store would not keep, and
92
+ * whose remembered context could not be forgotten either): the session stays signed out of in memory and its
93
+ * revocation is retried, but a restart could find it. The person should try signing out again.
94
+ */
95
+ export class SignOutNotSaved extends Error {
96
+ name = "SignOutNotSaved";
97
+ constructor() {
98
+ super("Sign-out could not be saved on this device. Try signing out again.");
99
+ }
100
+ }
101
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
102
+ /**
103
+ * Tokens the kernel refused, by the store they came from: kept for the life of the process, so a store that could not
104
+ * forget one (its keystore failing) never has it reported or reopened again by any controller over that store.
105
+ */
106
+ const refusedByStore = new WeakMap();
107
+ /** A failure worth trying again: no answer at all, a timeout, or the server's own failure. */
108
+ const transient = (error) => !(error instanceof AuthError) || error.status === 0 || error.status === 408 || error.status >= 500;
109
+ export const sessionController = (options) => {
110
+ const attempts = Math.max(1, options.retry?.attempts ?? 4);
111
+ const baseMs = options.retry?.baseMs ?? 250;
112
+ let state = { status: "loading" };
113
+ const listeners = new Set();
114
+ let checking;
115
+ let signingOut;
116
+ /** The token a sign-out that failed was revoking: trying again revokes it, even when the slot cannot be read. */
117
+ let retryToken;
118
+ /** Stopped (`dispose`): background cleanup ends. */
119
+ let disposed = false;
120
+ const refused = refusedByStore.get(options.store) ?? new Set();
121
+ refusedByStore.set(options.store, refused);
122
+ const set = (next) => {
123
+ state = next;
124
+ for (const listener of listeners) {
125
+ try {
126
+ listener(next);
127
+ }
128
+ catch {
129
+ // A listener's failure is its own.
130
+ }
131
+ }
132
+ };
133
+ const withRetry = async (work) => {
134
+ for (let attempt = 1;; attempt++) {
135
+ try {
136
+ return await work();
137
+ }
138
+ catch (error) {
139
+ if (!transient(error) || attempt >= attempts)
140
+ throw error;
141
+ await sleep(baseMs * 2 ** (attempt - 1));
142
+ }
143
+ }
144
+ };
145
+ /**
146
+ * The session's generation: advanced by every sign-out, every adoption when it starts and again when it is
147
+ * accepted. A check or an adoption that began in an earlier generation changes neither the state nor the store
148
+ * when it finishes: an answer that arrives after a sign-out (or after another session was adopted) is stale.
149
+ */
150
+ let generation = 0;
151
+ /**
152
+ * Store changes and the state they publish run one at a time, in order: a check's answer, an adoption's acceptance
153
+ * or cleanup, the ownership of a discarded token, a sign-out's end. Never one inside another, and never across a
154
+ * kernel call (a sign-out's retried revocation must not hold up an adoption).
155
+ */
156
+ let queue = Promise.resolve();
157
+ const exclusive = (work) => {
158
+ const run = queue.then(work, work);
159
+ queue = run.catch(() => undefined);
160
+ return run;
161
+ };
162
+ /** Forget `token` from the store unless another took its place (inside `exclusive`). */
163
+ const forget = async (token) => {
164
+ if (options.store.clearIf !== undefined)
165
+ return options.store.clearIf(token);
166
+ if ((await options.store.load()) === token)
167
+ await options.store.clear();
168
+ };
169
+ /** Disable the offline recall of `token`'s remembered context: whether nothing can be recalled for it now. */
170
+ const forgetContextOf = async (token) => {
171
+ if (options.store.recall === undefined)
172
+ return true;
173
+ if (options.store.forgetContext === undefined)
174
+ return false;
175
+ return options.store.forgetContext(token).then(() => true, () => false);
176
+ };
177
+ /**
178
+ * Forget a session the kernel refused, in the background, after the refusal was published: the slot cleared (only
179
+ * while it still holds that token), retried with backoff until it succeeds or the controller is disposed; while it
180
+ * fails, the remembered context is forgotten at least. The in-memory marker (`refused`) covers what is left.
181
+ */
182
+ const cleaning = new Set();
183
+ const cleanupRefused = (token) => {
184
+ if (cleaning.has(token))
185
+ return;
186
+ cleaning.add(token);
187
+ void (async () => {
188
+ try {
189
+ for (let attempt = 0;; attempt++) {
190
+ if (disposed)
191
+ return;
192
+ const done = await exclusive(async () => {
193
+ // A session stored since (a new sign-in) is not this one: `forget` keeps it.
194
+ await forget(token);
195
+ return true;
196
+ }).catch(() => false);
197
+ if (done)
198
+ return;
199
+ if (attempt === 0)
200
+ await exclusive(() => forgetContextOf(token)).catch(() => false);
201
+ await sleep(Math.min(baseMs * 2 ** attempt, 30_000));
202
+ }
203
+ }
204
+ finally {
205
+ cleaning.delete(token);
206
+ }
207
+ })();
208
+ };
209
+ /**
210
+ * The kernel refused `token` (inside `exclusive`): marked, a new generation (a check still in flight cannot
211
+ * replace the answer), `unauthenticated` published, and then its storage cleaned up in the background.
212
+ */
213
+ const publishRefusal = (token) => {
214
+ refused.add(token);
215
+ advance();
216
+ set({ status: "unauthenticated" });
217
+ cleanupRefused(token);
218
+ };
219
+ /** Adoptions running, by token: a token one of them holds is not revoked by another that is discarded. */
220
+ const adopting = new Map();
221
+ /**
222
+ * Tokens revoked here (by a sign-out from before its request is sent, or by a discard): an adoption whose check
223
+ * passed before the revocation took effect is overtaken, not accepted. Kept only while that can happen: until the
224
+ * revocation has settled and no adoption of the token is still running (a later adoption is checked by the kernel
225
+ * after the revocation), so a long-lived controller does not keep every token it ever revoked.
226
+ */
227
+ const retired = new Map();
228
+ /** Drop `token`'s tombstone once its revocation settled and no adoption of it can still be accepted. */
229
+ const prune = (token) => {
230
+ if (retired.get(token) === "settled" && !adopting.has(token))
231
+ retired.delete(token);
232
+ };
233
+ // -- A durable sign-out (with `revocations`) ------------------------------------------------------------------
234
+ //
235
+ // A sign-out's token stays pending until the kernel confirms its revocation, and only that removes it: in the
236
+ // revocation store (appended to, never rewritten by a sign-in or a session write) and in memory, which holds every
237
+ // one this controller made. One the store would not keep exists only in memory, so nothing may replace the stored
238
+ // session that still holds it: a sign-in waits until it is stored or confirmed.
239
+ const revocations = options.revocations;
240
+ const revocationTimeoutMs = options.revocationTimeoutMs ?? 10_000;
241
+ /** This controller's pending revocations (the store's are read each time: another window may change them). */
242
+ const unconfirmed = new Set();
243
+ let revocation = "none";
244
+ const revocationListeners = new Set();
245
+ const setRevocation = (next) => {
246
+ if (next === revocation)
247
+ return;
248
+ revocation = next;
249
+ for (const listener of revocationListeners) {
250
+ try {
251
+ listener(next);
252
+ }
253
+ catch {
254
+ // A listener's failure is its own.
255
+ }
256
+ }
257
+ };
258
+ const storedRevocations = async () => revocations === undefined ? [] : revocations.load().catch(() => []);
259
+ const pendingRevocations = async () => [...new Set([...(await storedRevocations()), ...unconfirmed])];
260
+ /** This controller's pending revocations the store does not hold: a reload would lose them. */
261
+ const unsavedRevocations = async () => {
262
+ const stored = await storedRevocations();
263
+ return [...unconfirmed].filter((token) => !stored.includes(token));
264
+ };
265
+ /**
266
+ * Keep `token` pending (inside `exclusive`): in memory, reserved as revoked (no adoption accepts it), and in the
267
+ * store. Once the store holds it, the stored session that was its only other copy is forgotten; until then it stays.
268
+ */
269
+ const keepPending = async (token) => {
270
+ unconfirmed.add(token);
271
+ retired.set(token, "revoking");
272
+ const kept = revocations === undefined ? false : await revocations.keep(token).catch(() => false);
273
+ // Kept: the revocation store holds it, so the session is never reported or reopened again even if this fails.
274
+ if (kept)
275
+ await forget(token).catch(() => forgetContextOf(token));
276
+ return kept;
277
+ };
278
+ /**
279
+ * The kernel confirmed `token`'s revocation (inside `exclusive`): the session slot is cleared first (or, failing that,
280
+ * its remembered context forgotten), and only then does the revocation leave the store and memory. Whether it did:
281
+ * while neither cleanup succeeds the revocation stays pending, the last thing keeping an offline restart from
282
+ * reopening it, and is retried. A failed sign-out waiting on this token ends signed out once it did.
283
+ */
284
+ const confirmRevoked = async (token) => {
285
+ retired.set(token, "settled");
286
+ prune(token);
287
+ const safe = await forget(token).then(() => true, () => forgetContextOf(token));
288
+ if (!safe)
289
+ return false;
290
+ unconfirmed.delete(token);
291
+ await revocations?.drop(token).catch(() => undefined);
292
+ if (retryToken === token) {
293
+ retryToken = undefined;
294
+ if (state.status === "signing-out")
295
+ set({ status: "unauthenticated" });
296
+ }
297
+ return true;
298
+ };
299
+ /**
300
+ * One attempt to revoke `token`: whether the kernel no longer accepts it (revoked now, or refused already: 401). An
301
+ * attempt it does not answer in time counts as unconfirmed, so the revocation stays pending and is retried.
302
+ */
303
+ const revokeOnce = async (token) => {
304
+ let timer;
305
+ const unanswered = new Promise((resolve) => {
306
+ timer = setTimeout(() => resolve(false), revocationTimeoutMs);
307
+ });
308
+ const attempt = signOut(options.baseUrl, token).then(() => true, (error) => error instanceof AuthError && error.status === 401);
309
+ try {
310
+ return await Promise.race([attempt, unanswered]);
311
+ }
312
+ finally {
313
+ clearTimeout(timer);
314
+ }
315
+ };
316
+ /** Store, and failing that revoke, each revocation only memory holds: whether none is left. */
317
+ const settleUnsaved = async () => {
318
+ if (revocations === undefined)
319
+ return true;
320
+ let revoked = false;
321
+ for (const token of await unsavedRevocations()) {
322
+ if (!(await exclusive(() => keepPending(token))) &&
323
+ (await revokeOnce(token)) &&
324
+ (await exclusive(() => confirmRevoked(token)).catch(() => false))) {
325
+ revoked = true;
326
+ }
327
+ }
328
+ if (revoked && (await pendingRevocations()).length === 0)
329
+ setRevocation("confirmed");
330
+ return (await unsavedRevocations()).length === 0;
331
+ };
332
+ let retrying;
333
+ /** Every pending revocation tried once more (those only memory holds stored first, if the store takes them now). */
334
+ const retryRevocations = () => {
335
+ retrying ??= (async () => {
336
+ for (const token of await unsavedRevocations())
337
+ await exclusive(() => keepPending(token));
338
+ const pending = await pendingRevocations();
339
+ if (pending.length > 0 && revocation === "none")
340
+ setRevocation("pending");
341
+ let revoked = false;
342
+ for (const token of pending) {
343
+ if ((await revokeOnce(token)) && (await exclusive(() => confirmRevoked(token)).catch(() => false))) {
344
+ revoked = true;
345
+ }
346
+ }
347
+ const stillPending = (await pendingRevocations()).length > 0;
348
+ if (stillPending)
349
+ setRevocation("pending");
350
+ else if (revoked)
351
+ setRevocation("confirmed");
352
+ else if (revocation === "pending")
353
+ setRevocation("none");
354
+ return { revoked, stillPending };
355
+ })().finally(() => {
356
+ retrying = undefined;
357
+ });
358
+ return retrying;
359
+ };
360
+ /**
361
+ * A durable sign-out (`signOut` with `revocations`): the revocation kept first, then `unauthenticated`; the
362
+ * kernel's confirmation is awaited in the background (`revocationStatus`), never by the person.
363
+ */
364
+ const durableSignOut = async (token) => {
365
+ const notSaved = async (revoking) => {
366
+ const error = new SignOutNotSaved();
367
+ retryToken = revoking;
368
+ await exclusive(async () => {
369
+ if (state.status === "signing-out")
370
+ set({ status: "signing-out", error: error.message });
371
+ });
372
+ return error;
373
+ };
374
+ let revoking = token;
375
+ if (revoking === undefined) {
376
+ // A slot that cannot be read is not an empty one: nothing was saved, and the person is told.
377
+ const read = await exclusive(() => options.store.load()).then((stored) => ({ stored }), () => undefined);
378
+ if (read === undefined)
379
+ throw await notSaved(undefined);
380
+ revoking = read.stored;
381
+ }
382
+ const target = revoking;
383
+ // Saved: the revocation kept, or at least the session's remembered context forgotten (it stays stored for the
384
+ // revocation, but an offline restart reopens nothing for it). Neither: the sign-out is not reported done.
385
+ const saved = target === undefined ||
386
+ (await exclusive(async () => (await keepPending(target)) || (await forgetContextOf(target))));
387
+ const background = () => {
388
+ if (target === undefined)
389
+ return;
390
+ setRevocation("revoking");
391
+ void (async () => {
392
+ const revoked = await revokeOnce(target);
393
+ // Confirmed only once the slot (or its context) is gone too; a failed sign-out waiting on it then ends.
394
+ const confirmed = revoked && (await exclusive(() => confirmRevoked(target)).catch(() => false));
395
+ const stillPending = (await pendingRevocations()).length > 0;
396
+ setRevocation(stillPending ? "pending" : confirmed ? "confirmed" : "none");
397
+ })();
398
+ };
399
+ if (!saved) {
400
+ const error = await notSaved(target);
401
+ // The kernel's confirmation still ends it, once the slot or its context is gone: safe to report signed out.
402
+ background();
403
+ throw error;
404
+ }
405
+ retryToken = undefined;
406
+ await exclusive(async () => {
407
+ if (state.status === "signing-out")
408
+ set({ status: "unauthenticated" });
409
+ });
410
+ background();
411
+ };
412
+ /** Whether the store remembers a context for `token` (an offline start could open it). */
413
+ const remembers = async (token) => options.store.recall !== undefined && (await options.store.recall(token).catch(() => undefined)) !== undefined;
414
+ const offlineProbeMs = options.offlineProbeMs ?? 3_000;
415
+ /** Whether no check has run yet: only the first is bounded by `offlineProbeMs`. */
416
+ let firstCheck = true;
417
+ /**
418
+ * The first check of a session with a remembered context: one attempt, given `offlineProbeMs`. Unanswered by then it
419
+ * counts as a network failure (`unavailable`: the offline start opens); its answer, when it comes, is checked again
420
+ * at once, so a refusal tears the offline context down without waiting for the next retry.
421
+ */
422
+ const probe = (token, of) => {
423
+ let timer;
424
+ let timedOut = false;
425
+ const attempt = getAccount(options.baseUrl, token);
426
+ const deadline = new Promise((_, reject) => {
427
+ timer = setTimeout(() => {
428
+ timedOut = true;
429
+ reject(new AuthError("The server did not answer in time", 0));
430
+ }, offlineProbeMs);
431
+ });
432
+ // Answered after the deadline: a refusal is applied at once, for this token and generation only (a check begun
433
+ // since, perhaps stalled, cannot replace it); an acceptance is checked again.
434
+ void attempt.then(() => {
435
+ if (timedOut && generation === of)
436
+ void check();
437
+ return undefined;
438
+ }, (error) => {
439
+ if (!timedOut || transient(error))
440
+ return;
441
+ void exclusive(async () => {
442
+ if (generation === of && signingOut === undefined)
443
+ publishRefusal(token);
444
+ });
445
+ });
446
+ return Promise.race([attempt, deadline]).finally(() => clearTimeout(timer));
447
+ };
448
+ /** The one check: the stored token, accepted by the kernel or not. */
449
+ const check = () => {
450
+ // A sign-out is revoking the session: nothing reads it again until it ends.
451
+ if (signingOut !== undefined)
452
+ return Promise.resolve(state);
453
+ if (checking !== undefined)
454
+ return checking;
455
+ const mine = generation;
456
+ const verify = async () => {
457
+ const first = firstCheck;
458
+ firstCheck = false;
459
+ const token = await exclusive(() => options.store.load());
460
+ if (generation !== mine)
461
+ return undefined;
462
+ if (token === undefined)
463
+ return { next: { status: "unauthenticated" } };
464
+ // A session signed out here whose revocation is still pending: never reported again (its slot stays only
465
+ // because the revocation store would not keep it).
466
+ if (unconfirmed.has(token))
467
+ return { next: { status: "unauthenticated" } };
468
+ // One a durable sign-out kept pending (before a reload, or in another window) whose slot survived (its removal
469
+ // failed, or was interrupted): never reported either, and its slot forgotten (the revocation store holds it).
470
+ if ((await storedRevocations()).includes(token))
471
+ return { next: { status: "unauthenticated" }, refused: token };
472
+ // Refused by the kernel before, in this process: never checked or reported again (its slot is being cleared).
473
+ if (refused.has(token))
474
+ return { next: { status: "unauthenticated" }, refused: token };
475
+ try {
476
+ const account = await (first && (await remembers(token))
477
+ ? probe(token, mine)
478
+ : withRetry(() => getAccount(options.baseUrl, token)));
479
+ return { next: { status: "authenticated", token, account } };
480
+ }
481
+ catch (error) {
482
+ if (!transient(error))
483
+ return { next: { status: "unauthenticated" }, refused: token };
484
+ return { next: { status: "unavailable", reason: error instanceof Error ? error.message : String(error) } };
485
+ }
486
+ };
487
+ const running = (async () => {
488
+ try {
489
+ const answer = await verify();
490
+ if (answer !== undefined) {
491
+ await exclusive(async () => {
492
+ // Stale (a sign-out or an adoption since): it neither publishes nor forgets anything.
493
+ if (generation !== mine)
494
+ return;
495
+ // Published first, the store cleaned up afterwards: a stalled or failing store never keeps it signed in.
496
+ if (answer.refused !== undefined)
497
+ publishRefusal(answer.refused);
498
+ else
499
+ set(answer.next);
500
+ });
501
+ }
502
+ return state;
503
+ }
504
+ finally {
505
+ // Only this check's own slot: a newer generation's check may have taken it.
506
+ if (generation === mine)
507
+ checking = undefined;
508
+ }
509
+ })();
510
+ checking = running;
511
+ return running;
512
+ };
513
+ /** A new generation: checks in flight become stale, and the next check starts afresh. */
514
+ const advance = () => {
515
+ generation++;
516
+ checking = undefined;
517
+ return generation;
518
+ };
519
+ /**
520
+ * A session that was not adopted must not stay live, unless something else holds its token: the current session,
521
+ * the stored one, or another adoption of it still running. Then revoked once, best effort (it was never reported).
522
+ */
523
+ const discard = async (token) => {
524
+ const revoke = await exclusive(async () => {
525
+ const stored = await options.store.load();
526
+ // Every holder is judged after the read, with no await before the tombstone: an adoption of the token that
527
+ // started while the store was read holds it too.
528
+ if (retired.has(token) || adopting.has(token))
529
+ return false;
530
+ if (state.status === "authenticated" && state.token === token)
531
+ return false;
532
+ if (stored === token)
533
+ return false;
534
+ retired.set(token, "revoking");
535
+ return true;
536
+ });
537
+ if (!revoke)
538
+ return;
539
+ await signOut(options.baseUrl, token).catch(() => undefined);
540
+ retired.set(token, "settled");
541
+ prune(token);
542
+ };
543
+ /**
544
+ * Adopt a session: its account is checked first, and only then is it stored and reported `authenticated`. One that
545
+ * is overtaken while it runs (a sign-out, another adoption, or the caller's `current` turning false) or whose check
546
+ * fails stores nothing and is revoked (unless something else holds its token): it resolves `false` when overtaken
547
+ * and rejects when the check failed. One whose `current` is already false when it is called overtakes nothing.
548
+ */
549
+ const adopt = async (session, guard) => {
550
+ const token = session.token;
551
+ // Abandoned before it began (its caller's attempt was overtaken): it must not overtake a live adoption, so it
552
+ // leaves the generation alone, and its session goes the way of any discarded one.
553
+ if (guard !== undefined && !guard.current()) {
554
+ await discard(token);
555
+ return false;
556
+ }
557
+ const mine = advance();
558
+ const live = () => generation === mine && !retired.has(token) && (guard?.current() ?? true);
559
+ adopting.set(token, (adopting.get(token) ?? 0) + 1);
560
+ let adopted = false;
561
+ try {
562
+ // A sign-out's revocation only memory holds: the stored session it may still occupy is not replaced.
563
+ if (!(await settleUnsaved()))
564
+ throw new UnsavedSignOut();
565
+ const account = await getAccount(options.baseUrl, token);
566
+ adopted = await exclusive(async () => {
567
+ if (!live())
568
+ return false;
569
+ const before = await options.store.load();
570
+ if (!live())
571
+ return false;
572
+ if (before !== token)
573
+ await options.store.save(token, account);
574
+ if (live()) {
575
+ // Accepted: a check that began before (of the previous session) is stale now.
576
+ refused.delete(token);
577
+ advance();
578
+ set({ status: "authenticated", token, account });
579
+ return true;
580
+ }
581
+ // Overtaken while it was stored: forgotten again (a token stored before it is kept).
582
+ if (before !== token)
583
+ await forget(token);
584
+ return false;
585
+ });
586
+ return adopted;
587
+ }
588
+ finally {
589
+ const left = (adopting.get(token) ?? 1) - 1;
590
+ if (left > 0)
591
+ adopting.set(token, left);
592
+ else
593
+ adopting.delete(token);
594
+ if (!adopted)
595
+ await discard(token);
596
+ prune(token);
597
+ }
598
+ };
599
+ return {
600
+ state: () => state,
601
+ /** The token to make authenticated calls with: only while `authenticated`. */
602
+ token: () => (state.status === "authenticated" ? state.token : undefined),
603
+ subscribe: (listener) => {
604
+ listeners.add(listener);
605
+ return () => void listeners.delete(listener);
606
+ },
607
+ /** Check the stored session (once at launch). */
608
+ start: check,
609
+ /** Check it again (after `unavailable`, or when the app regains focus). */
610
+ refresh: check,
611
+ /** A call was refused with 401: check the session again (calls made together share the check). */
612
+ invalidate: check,
613
+ /**
614
+ * Sign in with a password; rejects with `TwoFactorRequired` when a second factor is needed, and (a durable
615
+ * sign-out) with `UnsavedSignOut`, before asking the kernel, while a revocation only memory holds is left.
616
+ */
617
+ signIn: async (credentials, guard) => {
618
+ if (!(await settleUnsaved()))
619
+ throw new UnsavedSignOut();
620
+ return adopt(await signIn(options.baseUrl, credentials), guard);
621
+ },
622
+ /** Finish a sign-in `TwoFactorRequired` interrupted. */
623
+ completeTwoFactor: async (input, guard) => {
624
+ if (!(await settleUnsaved()))
625
+ throw new UnsavedSignOut();
626
+ return adopt(await verifyTwoFactor(options.baseUrl, input), guard);
627
+ },
628
+ /**
629
+ * Adopt a session obtained otherwise (a sign-up, a changed password's new token, a desktop sign-in): `false` when
630
+ * it was overtaken (then revoked, nothing stored); `guard.current` lets the caller abandon it while it is checked.
631
+ */
632
+ adopt,
633
+ /**
634
+ * Sign out: reads stop at once (`signing-out`; checks answer the state without reading until it ends), then the
635
+ * revocation is sent and retried; the revoked session is forgotten from the store only once the kernel confirms
636
+ * it. Rejects (staying `signing-out`, the session kept) when it could not be confirmed; call it again. A session
637
+ * adopted after it began is kept, unless it is the session being revoked: that adoption resolves `false`.
638
+ * `known`: the token of a session the caller holds without a check (an offline start), so a slot that cannot be
639
+ * read does not lose it.
640
+ */
641
+ signOut: (known) => {
642
+ if (signingOut !== undefined)
643
+ return signingOut;
644
+ // The checked session's token; else the one the caller knows (an offline start's), or a failed sign-out's.
645
+ const token = state.status === "authenticated" ? state.token : (known ?? retryToken);
646
+ advance();
647
+ set({ status: "signing-out" });
648
+ if (revocations !== undefined) {
649
+ // Durable: resolves once the revocation is kept and `unauthenticated` reported (`revocationStatus` follows).
650
+ signingOut = durableSignOut(token).finally(() => {
651
+ signingOut = undefined;
652
+ });
653
+ return signingOut;
654
+ }
655
+ signingOut = (async () => {
656
+ // The token is reserved as revoked before the request is sent: an adoption of it (a changed password's
657
+ // unrotated token) is not accepted while the revocation is pending. Released if it is not confirmed.
658
+ let reserved = false;
659
+ const reserve = (revoking) => {
660
+ if (revoking !== undefined && !retired.has(revoking)) {
661
+ retired.set(revoking, "revoking");
662
+ reserved = true;
663
+ }
664
+ return revoking;
665
+ };
666
+ let revoking;
667
+ /** Whether nothing could be recalled for it from before the revocation was sent (its context forgotten). */
668
+ let contextForgotten = false;
669
+ try {
670
+ // A slot that cannot be read fails the sign-out (reported, tried again), never counts as nobody's.
671
+ revoking = reserve(token) ?? (await exclusive(async () => reserve(await options.store.load())));
672
+ // Its remembered context goes before the revocation is sent: whatever the kernel answers (or not), an offline
673
+ // restart reopens nothing for a session being signed out of (it stays stored until the kernel confirms).
674
+ if (revoking !== undefined)
675
+ contextForgotten = await exclusive(() => forgetContextOf(revoking));
676
+ // Refused already (401: revoked by an earlier attempt whose local cleanup failed) counts as revoked.
677
+ if (revoking !== undefined) {
678
+ await withRetry(() => signOut(options.baseUrl, revoking)).catch((error) => {
679
+ if (!(error instanceof AuthError && error.status === 401))
680
+ throw error;
681
+ });
682
+ }
683
+ retryToken = undefined;
684
+ }
685
+ catch (error) {
686
+ if (revoking !== undefined)
687
+ retryToken = revoking;
688
+ if (reserved && revoking !== undefined)
689
+ retired.delete(revoking);
690
+ if (state.status === "signing-out") {
691
+ set({ status: "signing-out", error: error instanceof Error ? error.message : String(error) });
692
+ }
693
+ throw error;
694
+ }
695
+ await exclusive(async () => {
696
+ if (revoking !== undefined) {
697
+ retired.set(revoking, "settled");
698
+ prune(revoking);
699
+ // Revoked: the slot goes now. Where it cannot, the context forgotten (before the revocation, or now) still
700
+ // leaves nothing to reopen offline, and the kernel refuses the slot's token at the next check; only when
701
+ // neither protection holds is the sign-out not saved on this device (tried again with the same token).
702
+ const safe = (await forget(revoking).then(() => true, () => false)) ||
703
+ contextForgotten ||
704
+ (await forgetContextOf(revoking));
705
+ if (!safe) {
706
+ retryToken = revoking;
707
+ const error = new SignOutNotSaved();
708
+ if (state.status === "signing-out")
709
+ set({ status: "signing-out", error: error.message });
710
+ throw error;
711
+ }
712
+ }
713
+ // A session adopted after the sign-out began (a new sign-in) stays; the session just revoked does not.
714
+ const revoked = state.status === "authenticated" && state.token === revoking;
715
+ if (state.status === "signing-out" || revoked)
716
+ set({ status: "unauthenticated" });
717
+ });
718
+ })().finally(() => {
719
+ signingOut = undefined;
720
+ });
721
+ return signingOut;
722
+ },
723
+ /**
724
+ * The kernel refused `token` with 401 on another call (the client core's organisation listing): while it is the
725
+ * checked session, it is torn down as a refused check's would be (published first, the store cleaned up after).
726
+ * `owns`: the caller still holds `token` without a check (an offline start whose check went `unavailable` again
727
+ * while its listing was in flight): the refusal is recorded for it too, judged in turn with the store's writes.
728
+ */
729
+ refuse: (token, owns) => exclusive(async () => {
730
+ if (signingOut !== undefined)
731
+ return false;
732
+ const checked = state.status === "authenticated" && state.token === token;
733
+ const unchecked = state.status === "unavailable" && owns !== undefined && owns();
734
+ if (!checked && !unchecked)
735
+ return false;
736
+ publishRefusal(token);
737
+ return true;
738
+ }),
739
+ /** Whether the kernel refused `token` in this process (it is never reopened, even offline). */
740
+ isRefused: (token) => refused.has(token),
741
+ /** Stop the background cleanup's retries (the client stopped). */
742
+ dispose: () => {
743
+ disposed = true;
744
+ },
745
+ /** Where the last durable sign-out's revocation stands (always `none` without `revocations`). */
746
+ revocationStatus: () => revocation,
747
+ subscribeRevocation: (listener) => {
748
+ revocationListeners.add(listener);
749
+ return () => void revocationListeners.delete(listener);
750
+ },
751
+ /**
752
+ * Try every pending revocation once more (at start, on a timer, when the network returns): `revoked` when the
753
+ * kernel confirmed one, `stillPending` while any is left. Calls made together share one round.
754
+ */
755
+ retryRevocations,
756
+ };
757
+ };
758
+ /**
759
+ * A return path that is safe to send a person to after sign-in: a path on `origin` itself (`/inbox?x=1#y`), or
760
+ * `fallback` (default `/`) for anything else: another origin, a scheme (`javascript:`), a protocol-relative or
761
+ * backslashed path (`//evil.example`, `/\evil.example`), or what does not parse.
762
+ */
763
+ export const safeReturnPath = (candidate, origin, fallback = "/") => {
764
+ if (candidate === null || candidate === undefined || candidate === "")
765
+ return fallback;
766
+ if (!candidate.startsWith("/") || candidate.startsWith("//") || candidate.includes("\\"))
767
+ return fallback;
768
+ for (let i = 0; i < candidate.length; i++) {
769
+ const code = candidate.charCodeAt(i);
770
+ if (code < 0x20 || code === 0x7f)
771
+ return fallback;
772
+ }
773
+ try {
774
+ const base = new URL(origin);
775
+ const resolved = new URL(candidate, base);
776
+ if (resolved.origin !== base.origin)
777
+ return fallback;
778
+ // Normalised (`/.//x`, `/a/..//x`, `/%2e//x`), a path starting `//` would be read as another host.
779
+ if (resolved.pathname.startsWith("//"))
780
+ return fallback;
781
+ return `${resolved.pathname}${resolved.search}${resolved.hash}`;
782
+ }
783
+ catch {
784
+ return fallback;
785
+ }
786
+ };
787
+ /** The sign-in page's path with where to return afterwards (`?returnTo=`), only when that is safe. */
788
+ export const signInPath = (signIn, returnTo, origin) => {
789
+ const safe = safeReturnPath(returnTo, origin, "");
790
+ return safe === "" || safe === "/" ? signIn : `${signIn}?returnTo=${encodeURIComponent(safe)}`;
791
+ };
792
+ //# sourceMappingURL=Session.js.map