@eloxiv/client 0.0.0-stage → 0.1.0

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