@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
package/src/Consent.ts ADDED
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Consent before and after sign-in, headless (the Privacy contract's visitor routes): a visitor's region (their time
3
+ * zone, or a country an edge stated), their category choices (kept by the kernel on their visit, which an HttpOnly
4
+ * cookie names, so a banner shows the same choices on every page), the touch that brought them (recorded only with
5
+ * their marketing consent), the scripts an app loads per category (loaded once granted, unloaded once refused), and
6
+ * the visit claimed at sign-in so the choices become the person's. The cookie banner itself is the app's.
7
+ *
8
+ * In a browser on another origin than the kernel, the kernel must trust the app's origin (`ELOXIV_TRUSTED_ORIGINS`)
9
+ * for its cookie to travel; `fetch` can be replaced (a server-side render, a test).
10
+ */
11
+ import type { ConsentCategory, RegionHint, VisitClaimed, VisitRequest, VisitState, VisitTouch } from "@eloxiv/contracts"
12
+ import { CLICK_IDS, VISIT_PATHS } from "@eloxiv/contracts"
13
+
14
+ /** A script an app loads only with consent for its category (analytics, a chat widget, an ad pixel). */
15
+ export interface ConsentScript {
16
+ readonly category: Exclude<ConsentCategory, "necessary">
17
+ /** Load it (insert the tag, start the SDK); called once each time consent is granted. */
18
+ readonly load: () => void | Promise<void>
19
+ /** Stop it and remove what it set; called once each time consent is withdrawn after it loaded. */
20
+ readonly unload?: (() => void | Promise<void>) | undefined
21
+ }
22
+
23
+ export interface ConsentControllerOptions {
24
+ /** The kernel's base URL. */
25
+ readonly baseUrl: string
26
+ /** Where the visitor is (default: their time zone). */
27
+ readonly region?: RegionHint | undefined
28
+ /** Replace `fetch` (it must send and keep the visit cookie: `credentials: "include"` in a browser). */
29
+ readonly fetch?: typeof fetch | undefined
30
+ }
31
+
32
+ /** The touch a page's address and referrer describe: UTM parameters, ad-click ids present, the path, the referrer. */
33
+ export const touchFromLocation = (href: string, referrer?: string): VisitTouch => {
34
+ const query = href.includes("?") ? href.slice(href.indexOf("?") + 1).split("#")[0]! : ""
35
+ const params = new Map<string, string>()
36
+ for (const pair of query.split("&")) {
37
+ if (pair === "") continue
38
+ const at = pair.indexOf("=")
39
+ const key = decodeURIComponent((at < 0 ? pair : pair.slice(0, at)).replaceAll("+", " "))
40
+ params.set(key, at < 0 ? "" : decodeURIComponent(pair.slice(at + 1).replaceAll("+", " ")))
41
+ }
42
+ const utm = (name: string) => {
43
+ const value = params.get(`utm_${name}`)?.slice(0, 200)
44
+ return value === undefined || value === "" ? {} : { [name]: value }
45
+ }
46
+ const afterOrigin = href.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/iu, "")
47
+ const path = (afterOrigin === "" ? "/" : afterOrigin).split(/[?#]/u)[0]!.slice(0, 500)
48
+ const clickIds = CLICK_IDS.filter((id) => params.has(id))
49
+ return {
50
+ ...utm("source"),
51
+ ...utm("medium"),
52
+ ...utm("campaign"),
53
+ ...utm("term"),
54
+ ...utm("content"),
55
+ ...(referrer === undefined || referrer === "" ? {} : { referrer: referrer.slice(0, 2_000) }),
56
+ landingPath: path,
57
+ ...(clickIds.length === 0 ? {} : { clickIds }),
58
+ }
59
+ }
60
+
61
+ const timeZone = (): RegionHint => {
62
+ try {
63
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
64
+ return typeof zone === "string" && zone !== "" ? { timeZone: zone } : {}
65
+ } catch {
66
+ return {}
67
+ }
68
+ }
69
+
70
+ /** A refused visitor request: the HTTP status and the kernel's error. */
71
+ export class ConsentRequestError extends Error {
72
+ readonly status: number
73
+ readonly error: { readonly _tag: string; readonly message?: string }
74
+ constructor(status: number, error: { readonly _tag: string; readonly message?: string }) {
75
+ super(error.message ?? error._tag)
76
+ this.status = status
77
+ this.error = error
78
+ }
79
+ }
80
+
81
+ export const consentController = (options: ConsentControllerOptions) => {
82
+ const base = options.baseUrl.replace(/\/+$/u, "")
83
+ const send = options.fetch ?? fetch
84
+ const region = options.region ?? timeZone()
85
+ const scripts: Array<{ readonly script: ConsentScript; loaded: boolean }> = []
86
+ const listeners = new Set<(state: VisitState) => void>()
87
+ let current: VisitState | undefined
88
+ // Once the visit is claimed: the person's consent in the organisation, which every later state follows.
89
+ let account: VisitState["consent"] | undefined
90
+ // Script loads and unloads run one at a time, in the order states arrive.
91
+ let applying: Promise<void> = Promise.resolve()
92
+
93
+ const apply = (received: VisitState) => {
94
+ const state = account === undefined ? received : { ...received, consent: account }
95
+ current = state
96
+ applying = applying.then(async () => {
97
+ for (const entry of scripts) {
98
+ const granted = state.consent.categories[entry.script.category].granted
99
+ // A script that fails to load or unload is the app's to report; the others still follow the state.
100
+ try {
101
+ if (granted && !entry.loaded) {
102
+ entry.loaded = true
103
+ await entry.script.load()
104
+ } else if (!granted && entry.loaded) {
105
+ entry.loaded = false
106
+ await entry.script.unload?.()
107
+ }
108
+ } catch {
109
+ // (ignored: see above)
110
+ }
111
+ }
112
+ return undefined
113
+ })
114
+ for (const listener of listeners) listener(state)
115
+ return applying.then(() => state)
116
+ }
117
+
118
+ const request = async <A>(method: string, path: string, body?: unknown, token?: string): Promise<A> => {
119
+ const headers: Record<string, string> = { "content-type": "application/json" }
120
+ if (token !== undefined) headers["authorization"] = `Bearer ${token}`
121
+ const response = await send(`${base}${path}`, {
122
+ method,
123
+ headers,
124
+ credentials: "include",
125
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
126
+ })
127
+ const parsed = (await response.json().catch(() => ({}))) as A & {
128
+ readonly _tag?: string
129
+ readonly message?: string
130
+ }
131
+ if (!response.ok)
132
+ throw new ConsentRequestError(response.status, { _tag: parsed._tag ?? `HTTP ${response.status}`, ...parsed })
133
+ return parsed
134
+ }
135
+ const post = (body: VisitRequest) => request<VisitState>("POST", VISIT_PATHS.visit, { region, ...body }).then(apply)
136
+
137
+ return {
138
+ /** The visitor's consent and attribution, as the kernel holds them (scripts follow it). */
139
+ load: () => request<VisitState>("GET", VISIT_PATHS.visit).then(apply),
140
+ /** Record choices (a banner's answer): categories left out keep their choice, or their region's default. */
141
+ choose: (choices: NonNullable<VisitRequest["choices"]>) => post({ choices }),
142
+ /** Record the touch that brought the visitor (kept only with their marketing consent). */
143
+ touch: (touch: VisitTouch) => post({ touch }),
144
+ /** The last state seen, if any. */
145
+ get state(): VisitState | undefined {
146
+ return current
147
+ },
148
+ /** Is the category granted in the last state seen? (`necessary` always is; anything else is not before `load`.) */
149
+ granted: (category: ConsentCategory) =>
150
+ category === "necessary" || current?.consent.categories[category].granted === true,
151
+ /** A script loaded while its category is granted and unloaded when it is withdrawn. */
152
+ register: (script: ConsentScript) => {
153
+ scripts.push({ script, loaded: false })
154
+ return current === undefined ? Promise.resolve(undefined) : apply(current)
155
+ },
156
+ /** Every state from now on (a consent mode adapter, a banner). Returns the unsubscribe. */
157
+ subscribe: (listener: (state: VisitState) => void) => {
158
+ listeners.add(listener)
159
+ return () => void listeners.delete(listener)
160
+ },
161
+ /** Once signed in: the visit becomes the person's, its choices theirs where they made none (after `load`). */
162
+ claim: async (token: string) => {
163
+ const claim = current?.claim ?? (await request<VisitState>("GET", VISIT_PATHS.visit).then(apply)).claim
164
+ if (claim === null) throw new ConsentRequestError(400, { _tag: "InvalidInput", message: "No visit to claim" })
165
+ const claimed = await request<VisitClaimed>("POST", VISIT_PATHS.claim, { claim }, token)
166
+ // From here on the person's own consent decides: a category they refused unloads its scripts.
167
+ account = claimed.consent
168
+ await apply({ claim, consent: claimed.consent, attribution: claimed.attribution })
169
+ return claimed
170
+ },
171
+ /** Wait for script loads and unloads in progress. */
172
+ settled: () => applying,
173
+ }
174
+ }
175
+
176
+ export type ConsentController = ReturnType<typeof consentController>
package/src/Desktop.ts ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Desktop sign-in, headless (the kernel's `DesktopSignIn.ts`): a desktop or native app gets a session of its own
3
+ * through the system browser, never by copying the browser's cookie. The app keeps a PKCE verifier; the browser,
4
+ * signed in, approves its challenge and is sent to the app's redirect with a one-time code; the app redeems the code
5
+ * with its verifier. Only the instance holding the verifier can redeem it, once, within a minute, while the session
6
+ * that approved it lasts.
7
+ *
8
+ * const login = await beginDesktopSignIn({ redirectUri: "http://127.0.0.1:43123/done" })
9
+ * open(`${signInPage}?${login.query}`) // the app's web sign-in page, which calls approveDesktopSignIn
10
+ * const { code, state } = await receive() // the loopback server (or deep link) the browser lands on
11
+ * const session = await completeDesktopSignIn(baseUrl, login, { code, state })
12
+ *
13
+ * `desktopSignIn(controller, ...)` runs the whole journey into the shared session controller (the desktop identity
14
+ * bootstrap).
15
+ */
16
+ import { AuthError, originOf, type Session } from "./Auth.ts"
17
+ import type { SessionController } from "./Session.ts"
18
+
19
+ /** What the app keeps between opening the browser and receiving its code. */
20
+ export interface DesktopSignIn {
21
+ readonly verifier: string
22
+ readonly challenge: string
23
+ readonly state: string
24
+ readonly redirectUri: string
25
+ /** The query to append to the app's sign-in page: `challenge`, `redirect_uri`, `state`. */
26
+ readonly query: string
27
+ }
28
+
29
+ /**
30
+ * The web globals this file needs, read from `globalThis`: a runtime without one (React Native without its polyfills)
31
+ * has no such global at all, and naming it would throw a ReferenceError instead of this file's own error; React
32
+ * Native's typecheck declares none of them either.
33
+ */
34
+ const web = globalThis as {
35
+ readonly btoa?: (data: string) => string
36
+ readonly crypto?: {
37
+ getRandomValues(array: Uint8Array): Uint8Array
38
+ readonly subtle?: { digest(algorithm: string, data: Uint8Array): Promise<ArrayBuffer> }
39
+ }
40
+ readonly TextEncoder?: new () => { encode(input: string): Uint8Array }
41
+ }
42
+
43
+ const base64url = (bytes: Uint8Array) => {
44
+ if (web.btoa === undefined) throw new AuthError("This runtime has no btoa", 0)
45
+ let binary = ""
46
+ for (const byte of bytes) binary += String.fromCharCode(byte)
47
+ return web.btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "")
48
+ }
49
+
50
+ const random = (length: number) => {
51
+ if (web.crypto === undefined) throw new AuthError("This runtime has no Web Crypto", 0)
52
+ return base64url(web.crypto.getRandomValues(new Uint8Array(length)))
53
+ }
54
+
55
+ /** Start a desktop sign-in: a fresh verifier (kept by the app), its S256 challenge and a state. */
56
+ export const beginDesktopSignIn = async (input: { readonly redirectUri: string }): Promise<DesktopSignIn> => {
57
+ const subtle = web.crypto?.subtle
58
+ if (subtle === undefined || web.TextEncoder === undefined) {
59
+ throw new AuthError("This runtime has no Web Crypto digest", 0)
60
+ }
61
+ const verifier = random(32)
62
+ const challenge = base64url(new Uint8Array(await subtle.digest("SHA-256", new web.TextEncoder().encode(verifier))))
63
+ const state = random(16)
64
+ const query = [
65
+ `challenge=${encodeURIComponent(challenge)}`,
66
+ `redirect_uri=${encodeURIComponent(input.redirectUri)}`,
67
+ `state=${encodeURIComponent(state)}`,
68
+ ].join("&")
69
+ return { verifier, challenge, state, redirectUri: input.redirectUri, query }
70
+ }
71
+
72
+ const post = async (baseUrl: string, path: string, body: unknown, token?: string) => {
73
+ const response = await fetch(`${baseUrl}${path}`, {
74
+ method: "POST",
75
+ headers: {
76
+ "content-type": "application/json",
77
+ origin: originOf(baseUrl),
78
+ ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
79
+ },
80
+ body: JSON.stringify(body),
81
+ })
82
+ const text = await response.text()
83
+ let json: unknown
84
+ try {
85
+ json = text.length === 0 ? {} : JSON.parse(text)
86
+ } catch {
87
+ json = undefined
88
+ }
89
+ if (!response.ok) {
90
+ const message = (json as { message?: unknown } | undefined)?.message
91
+ throw new AuthError(`${path} failed: ${typeof message === "string" ? message : text}`, response.status)
92
+ }
93
+ return json
94
+ }
95
+
96
+ /**
97
+ * The browser's step, on the app's own web sign-in page, signed in (`token`, or the session cookie when omitted):
98
+ * approve the desktop's challenge. Answers where to send the browser next (the app's redirect, with the code).
99
+ */
100
+ export const approveDesktopSignIn = async (
101
+ baseUrl: string,
102
+ token: string | undefined,
103
+ input: { readonly challenge: string; readonly redirectUri: string; readonly state: string },
104
+ ): Promise<{ readonly redirect: string }> =>
105
+ (await post(baseUrl, "/api/desktop/approve", input, token)) as { readonly redirect: string }
106
+
107
+ /** The app's step: redeem the code its redirect received, with its verifier. Refuses a state it did not send. */
108
+ export const completeDesktopSignIn = async (
109
+ baseUrl: string,
110
+ login: DesktopSignIn,
111
+ received: { readonly code: string; readonly state: string },
112
+ ): Promise<Session> => {
113
+ if (received.state !== login.state) throw new AuthError("The sign-in returned a state this app did not send", 400)
114
+ const answer = (await post(baseUrl, "/api/desktop/token", {
115
+ code: received.code,
116
+ verifier: login.verifier,
117
+ redirectUri: login.redirectUri,
118
+ })) as { token: string; user: Session["user"] }
119
+ return { token: answer.token, user: answer.user }
120
+ }
121
+
122
+ /**
123
+ * The desktop identity bootstrap: the whole sign-in journey into the shared session controller. `open` shows the
124
+ * app's web sign-in page (with the query); `receive` resolves with what the redirect received.
125
+ */
126
+ export const desktopSignIn = async (
127
+ controller: SessionController,
128
+ input: {
129
+ readonly baseUrl: string
130
+ readonly redirectUri: string
131
+ readonly signInPage: string
132
+ readonly open: (url: string) => Promise<void>
133
+ readonly receive: () => Promise<{ readonly code: string; readonly state: string }>
134
+ },
135
+ ): Promise<void> => {
136
+ const login = await beginDesktopSignIn({ redirectUri: input.redirectUri })
137
+ await input.open(`${input.signInPage}${input.signInPage.includes("?") ? "&" : "?"}${login.query}`)
138
+ await controller.adopt(await completeDesktopSignIn(input.baseUrl, login, await input.receive()))
139
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The Directory's operations, headless (`POST /kernel/directory/<operation>`): an organisation's members, roles,
3
+ * groups, invitations and domains for an administrator, and a person's own (their organisations, accepting an
4
+ * invitation, joining through their address's domain). Inputs and outputs are typed from the Directory contract, so
5
+ * nothing is declared twice. Every call is made with a person's own session; administration needs
6
+ * `eloxiv.directory.manage` in the organisation `orgId` names, and is audited by the kernel.
7
+ */
8
+ import type { DirectoryContract } from "@eloxiv/contracts"
9
+
10
+ type Operations = Omit<(typeof DirectoryContract)["operations"], "createOrganization">
11
+
12
+ /** A Directory operation the kernel serves over HTTP. */
13
+ export type DirectoryOperation = keyof Operations
14
+ export type DirectoryInput<K extends DirectoryOperation> = Operations[K]["input"]["Encoded"]
15
+ export type DirectoryOutput<K extends DirectoryOperation> = Operations[K]["output"]["Type"]
16
+
17
+ /**
18
+ * A refused Directory call: the kernel's typed error (`Unauthenticated`, `Forbidden`: not permitted, not the invited
19
+ * or a verified address; `InvalidInput`: a request the directory cannot apply), its message and HTTP status.
20
+ */
21
+ export class DirectoryError extends Error {
22
+ readonly tag: string
23
+ readonly status: number
24
+ constructor(tag: string, message: string, status: number) {
25
+ super(message)
26
+ this.tag = tag
27
+ this.status = status
28
+ }
29
+ }
30
+
31
+ export interface DirectoryClientOptions {
32
+ readonly baseUrl: string
33
+ /** The person's session token, read for every call. */
34
+ readonly token: () => string
35
+ /** The organisation administration acts in (`x-eloxiv-org`); a person's own operations ignore it. */
36
+ readonly orgId?: (() => string | undefined) | undefined
37
+ }
38
+
39
+ export const directoryClient = (options: DirectoryClientOptions) => ({
40
+ /** One Directory operation; rejects with `DirectoryError`. */
41
+ call: async <K extends DirectoryOperation>(operation: K, input: DirectoryInput<K>): Promise<DirectoryOutput<K>> => {
42
+ const orgId = options.orgId?.()
43
+ const response = await fetch(`${options.baseUrl}/kernel/directory/${operation}`, {
44
+ method: "POST",
45
+ headers: {
46
+ authorization: `Bearer ${options.token()}`,
47
+ "content-type": "application/json",
48
+ ...(orgId === undefined ? {} : { "x-eloxiv-org": orgId }),
49
+ },
50
+ body: JSON.stringify(input),
51
+ })
52
+ const text = await response.text()
53
+ let parsed: unknown
54
+ try {
55
+ parsed = text.length === 0 ? {} : JSON.parse(text)
56
+ } catch {
57
+ parsed = undefined
58
+ }
59
+ if (!response.ok) {
60
+ const error = (parsed ?? {}) as { _tag?: unknown; message?: unknown }
61
+ throw new DirectoryError(
62
+ typeof error._tag === "string" ? error._tag : "Unknown",
63
+ typeof error.message === "string" ? error.message : `${operation} failed (${response.status})`,
64
+ response.status,
65
+ )
66
+ }
67
+ return parsed as DirectoryOutput<K>
68
+ },
69
+ })
70
+
71
+ export type DirectoryClient = ReturnType<typeof directoryClient>
@@ -0,0 +1,112 @@
1
+ /**
2
+ * A client's unexpected errors, reported to the kernel's error capture (the Telemetry contract's `telemetry.captureError`):
3
+ * global exceptions and unhandled rejections (or any error the app passes), with the route they happened on as the
4
+ * router's registered template (never a path: a path's segments can be names or diagnoses, and no rule tells them from
5
+ * static ones), the invocation they followed, and the last breadcrumbs (navigations, actions, requests, UI events by a
6
+ * label the app chooses: a route template, an action's name). **Only labels leave**: never an error's message or
7
+ * stack, a URL or any input.
8
+ * Reports are sent one at a time; one that fails to send is dropped (error reporting never throws into the app).
9
+ */
10
+ import type { ClientErrorReport } from "@eloxiv/contracts"
11
+
12
+ type Breadcrumb = ClientErrorReport["breadcrumbs"][number]
13
+
14
+ const LABEL = /^[A-Za-z0-9_.:/-]{1,64}$/u
15
+
16
+ /** A label as the kernel takes it: anything else replaced by `_`, at most 64 characters (`other` when empty). */
17
+ export const labelOf = (text: string): string => {
18
+ const label = text.replaceAll(/[^A-Za-z0-9_.:/-]/gu, "_").slice(0, 64)
19
+ return label === "" ? "other" : label
20
+ }
21
+
22
+ /** The route reported when the router names none (an unknown route) or names something that is not a template. */
23
+ export const UNKNOWN_ROUTE = "/unknown"
24
+
25
+ const TEMPLATE = /^\/[A-Za-z0-9_.:\-/*]{0,199}$/u
26
+
27
+ /** A router's registered template (`/orders/:id`) as reported: anything else is `UNKNOWN_ROUTE`. */
28
+ export const routeTemplateOf = (template: string | undefined): string =>
29
+ template !== undefined && TEMPLATE.test(template) ? template : UNKNOWN_ROUTE
30
+
31
+ /** Where global errors come from: a browser's `window` (or `globalThis`), anything with these listeners. */
32
+ export interface ErrorSource {
33
+ readonly addEventListener: (type: "error" | "unhandledrejection", listener: (event: unknown) => void) => void
34
+ readonly removeEventListener: (type: "error" | "unhandledrejection", listener: (event: unknown) => void) => void
35
+ }
36
+
37
+ export interface ErrorReporterOptions {
38
+ /** Send a report (`client.call("telemetry.captureError", report)` of the typed client, say). */
39
+ readonly send: (report: ClientErrorReport) => Promise<unknown>
40
+ /**
41
+ * The registered template of the route being shown (`/patients/:id/diagnosis/:code`), from the app's router, or
42
+ * undefined for a route it does not know; the URL itself is never read.
43
+ */
44
+ readonly route?: (() => string | undefined) | undefined
45
+ /** How many breadcrumbs are kept (at most 20). */
46
+ readonly breadcrumbs?: number | undefined
47
+ }
48
+
49
+ const nameOf = (error: unknown) => {
50
+ const name = (error as { readonly name?: unknown } | null)?.name
51
+ return typeof name === "string" && LABEL.test(name) ? name : "Error"
52
+ }
53
+
54
+ export const errorReporter = (options: ErrorReporterOptions) => {
55
+ const keep = Math.min(Math.max(options.breadcrumbs ?? 20, 0), 20)
56
+ const trail: Array<Breadcrumb> = []
57
+ let lastInvocation: string | undefined
58
+ let sending: Promise<void> = Promise.resolve()
59
+
60
+ const breadcrumb = (kind: Breadcrumb["kind"], name: string) => {
61
+ trail.push({ kind, name: labelOf(name), at: Date.now() })
62
+ while (trail.length > keep) trail.shift()
63
+ }
64
+
65
+ const report = (error: unknown, kind: ClientErrorReport["kind"] = "exception") => {
66
+ const invocation = (error as { readonly invocationId?: unknown } | null)?.invocationId
67
+ const invocationId = typeof invocation === "string" ? invocation : lastInvocation
68
+ const payload: ClientErrorReport = {
69
+ kind,
70
+ errorName: nameOf(error),
71
+ route: routeTemplateOf(options.route?.()),
72
+ ...(invocationId !== undefined && /^[0-9a-f-]{8,64}$/u.test(invocationId) ? { invocationId } : {}),
73
+ breadcrumbs: [...trail],
74
+ }
75
+ const previous = sending
76
+ sending = (async () => {
77
+ await previous
78
+ try {
79
+ await options.send(payload)
80
+ } catch {
81
+ // Dropped: reporting an error never throws into the app.
82
+ }
83
+ })()
84
+ return sending
85
+ }
86
+
87
+ const onError = (event: unknown) => void report((event as { readonly error?: unknown } | null)?.error ?? event)
88
+ const onRejection = (event: unknown) =>
89
+ void report((event as { readonly reason?: unknown } | null)?.reason ?? event, "rejection")
90
+
91
+ return {
92
+ /** Remember what the person just did (a navigation, an action, a request, a UI event), by a label. */
93
+ breadcrumb,
94
+ /** The invocation the next report follows (the kernel's id of the last call that failed, say). */
95
+ correlate: (invocationId: string) => void (lastInvocation = invocationId),
96
+ /** Report an error the app caught. */
97
+ report,
98
+ /** Report every uncaught exception and unhandled rejection of `source`; returns the uninstall. */
99
+ install: (source: ErrorSource) => {
100
+ source.addEventListener("error", onError)
101
+ source.addEventListener("unhandledrejection", onRejection)
102
+ return () => {
103
+ source.removeEventListener("error", onError)
104
+ source.removeEventListener("unhandledrejection", onRejection)
105
+ }
106
+ },
107
+ /** Wait for reports being sent. */
108
+ settled: () => sending,
109
+ }
110
+ }
111
+
112
+ export type ErrorReporter = ReturnType<typeof errorReporter>
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The replica's SQLite storage on React Native (decision 7), through `expo-sqlite`:
3
+ * `connectSync({ ..., storage: expoSQLiteStoreProvider() })`. The app installs `expo-sqlite` itself, so this is a
4
+ * separate entry (`@eloxiv/client/expo-sqlite`) that nothing else in the SDK imports.
5
+ */
6
+ export { expoSQLiteStoreProvider } from "@rocicorp/zero/expo-sqlite"
@@ -0,0 +1,34 @@
1
+ /**
2
+ * File metadata in each person's replica (the Files contract): the kernel's `eloxiv.file` table, generated from
3
+ * the kernel's Drizzle declaration of it (`FileTables.gen.ts`), and its named queries. An app that installs the
4
+ * kernel's `filesModule` adds `fileTables` and `fileQueries` to its sync schema (and, for files attached to its
5
+ * records, keeps those entities' tables in the schema too).
6
+ *
7
+ * The kernel filters every query that reads the table: a replica holds a file's metadata (never its bytes)
8
+ * exactly while its actor may read the record the file is attached to (that entity's read policy, evaluated
9
+ * live), or while it is a file the actor uploaded and has not attached yet; deleted files leave the replica.
10
+ */
11
+ import { createBuilder, createSchema, defineQueryWithType } from "@rocicorp/zero"
12
+ import { eloxivFileTable } from "./FileTables.gen.ts"
13
+
14
+ export { eloxivFileTable }
15
+ /** The file metadata table (the generated `eloxivFileTable`). */
16
+ export const fileTable = eloxivFileTable
17
+
18
+ export const fileTables = [eloxivFileTable] as const
19
+
20
+ const localSchema = createSchema({ tables: [eloxivFileTable] })
21
+ const zql = createBuilder(localSchema)
22
+ const defineQuery = defineQueryWithType<typeof localSchema>()
23
+
24
+ /** Named queries (`files.ofRecord`, `files.staged`). */
25
+ export const fileQueries = {
26
+ files: {
27
+ /** The files attached to one record (the kernel keeps only those you may read). */
28
+ ofRecord: defineQuery(({ args }: { args: { readonly entity: string; readonly id: string } }) =>
29
+ zql.eloxivFile.where("ownerType", args.entity).where("ownerId", args.id).orderBy("createdAt", "asc"),
30
+ ),
31
+ /** Files you uploaded and have not attached to a record yet. */
32
+ staged: defineQuery(() => zql.eloxivFile.where("ownerType", "IS", null).orderBy("createdAt", "desc")),
33
+ },
34
+ }
@@ -0,0 +1,23 @@
1
+ // Generated from the kernel's file metadata Drizzle tables and entities by packages/testing/scripts/sync-tables.ts (the CLI's
2
+ // sync generator, through drizzle-zero 0.21.0). Do not edit: run `pnpm --filter @eloxiv/testing generate`.
3
+ import { enumeration, number, string, table } from "@rocicorp/zero"
4
+
5
+ export const eloxivFileTable = table("eloxivFile")
6
+ .from("eloxiv.file")
7
+ .columns({
8
+ id: string(),
9
+ orgId: string().from("org_id"),
10
+ ownerType: string().from("owner_type").optional(),
11
+ ownerId: string().from("owner_id").optional(),
12
+ name: string(),
13
+ declaredType: string().from("declared_type"),
14
+ contentType: string().from("content_type").optional(),
15
+ size: number(),
16
+ sha256: string().optional(),
17
+ state: enumeration<"uploading" | "processing" | "available" | "quarantined" | "rejected" | "deleted">(),
18
+ stateReason: string().from("state_reason").optional(),
19
+ uploadedBy: string().from("uploaded_by"),
20
+ createdAt: number().from("created_at"),
21
+ completedAt: number().from("completed_at").optional(),
22
+ })
23
+ .primaryKey("id")