@photonhealth/client 0.0.0-stage → 2.0.0-rc.2

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 (218) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +234 -2
  3. package/dist/analytics/lifecycleEvents.d.ts +29 -0
  4. package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
  5. package/dist/analytics/lifecycleEvents.js +72 -0
  6. package/dist/analytics/lifecycleEvents.js.map +1 -0
  7. package/dist/api/changes/applyOption.d.ts +41 -0
  8. package/dist/api/changes/applyOption.d.ts.map +1 -0
  9. package/dist/api/changes/applyOption.js +76 -0
  10. package/dist/api/changes/applyOption.js.map +1 -0
  11. package/dist/api/changes/classifyChanges.d.ts +9 -0
  12. package/dist/api/changes/classifyChanges.d.ts.map +1 -0
  13. package/dist/api/changes/classifyChanges.js +2 -0
  14. package/dist/api/changes/classifyChanges.js.map +1 -0
  15. package/dist/api/changes/index.d.ts +3 -0
  16. package/dist/api/changes/index.d.ts.map +1 -0
  17. package/dist/api/changes/index.js +3 -0
  18. package/dist/api/changes/index.js.map +1 -0
  19. package/dist/api/client.d.ts +48 -0
  20. package/dist/api/client.d.ts.map +1 -0
  21. package/dist/api/client.js +91 -0
  22. package/dist/api/client.js.map +1 -0
  23. package/dist/api/health.d.ts +4 -0
  24. package/dist/api/health.d.ts.map +1 -0
  25. package/dist/api/health.js +6 -0
  26. package/dist/api/health.js.map +1 -0
  27. package/dist/api/index.d.ts +24 -0
  28. package/dist/api/index.d.ts.map +1 -0
  29. package/dist/api/index.js +23 -0
  30. package/dist/api/index.js.map +1 -0
  31. package/dist/api/me.d.ts +37 -0
  32. package/dist/api/me.d.ts.map +1 -0
  33. package/dist/api/me.js +6 -0
  34. package/dist/api/me.js.map +1 -0
  35. package/dist/api/order.d.ts +33 -0
  36. package/dist/api/order.d.ts.map +1 -0
  37. package/dist/api/order.js +33 -0
  38. package/dist/api/order.js.map +1 -0
  39. package/dist/api/orders.d.ts +1047 -0
  40. package/dist/api/orders.d.ts.map +1 -0
  41. package/dist/api/orders.js +7 -0
  42. package/dist/api/orders.js.map +1 -0
  43. package/dist/api/patient.d.ts +36 -0
  44. package/dist/api/patient.d.ts.map +1 -0
  45. package/dist/api/patient.js +33 -0
  46. package/dist/api/patient.js.map +1 -0
  47. package/dist/api/prescription.d.ts +37 -0
  48. package/dist/api/prescription.d.ts.map +1 -0
  49. package/dist/api/prescription.js +39 -0
  50. package/dist/api/prescription.js.map +1 -0
  51. package/dist/api/results.d.ts +30 -0
  52. package/dist/api/results.d.ts.map +1 -0
  53. package/dist/api/results.js +26 -0
  54. package/dist/api/results.js.map +1 -0
  55. package/dist/gql/gql.d.ts +29 -0
  56. package/dist/gql/gql.d.ts.map +1 -0
  57. package/dist/gql/gql.js +15 -0
  58. package/dist/gql/gql.js.map +1 -0
  59. package/dist/gql/graphql.d.ts +18618 -0
  60. package/dist/gql/graphql.d.ts.map +1 -0
  61. package/dist/gql/graphql.js +6579 -0
  62. package/dist/gql/graphql.js.map +1 -0
  63. package/dist/gql/index.d.ts +2 -0
  64. package/dist/gql/index.d.ts.map +1 -0
  65. package/dist/gql/index.js +3 -0
  66. package/dist/gql/index.js.map +1 -0
  67. package/dist/index.d.ts +15 -0
  68. package/dist/index.d.ts.map +1 -0
  69. package/dist/index.js +15 -0
  70. package/dist/index.js.map +1 -0
  71. package/dist/meta/version.d.ts +2 -0
  72. package/dist/meta/version.d.ts.map +1 -0
  73. package/dist/meta/version.js +2 -0
  74. package/dist/meta/version.js.map +1 -0
  75. package/dist/photon/analytics.d.ts +39 -0
  76. package/dist/photon/analytics.d.ts.map +1 -0
  77. package/dist/photon/analytics.js +91 -0
  78. package/dist/photon/analytics.js.map +1 -0
  79. package/dist/photon/auth.d.ts +52 -0
  80. package/dist/photon/auth.d.ts.map +1 -0
  81. package/dist/photon/auth.js +30 -0
  82. package/dist/photon/auth.js.map +1 -0
  83. package/dist/photon/choices.d.ts +44 -0
  84. package/dist/photon/choices.d.ts.map +1 -0
  85. package/dist/photon/choices.js +58 -0
  86. package/dist/photon/choices.js.map +1 -0
  87. package/dist/photon/context.d.ts +29 -0
  88. package/dist/photon/context.d.ts.map +1 -0
  89. package/dist/photon/context.js +2 -0
  90. package/dist/photon/context.js.map +1 -0
  91. package/dist/photon/environments.d.ts +27 -0
  92. package/dist/photon/environments.d.ts.map +1 -0
  93. package/dist/photon/environments.js +27 -0
  94. package/dist/photon/environments.js.map +1 -0
  95. package/dist/photon/errors.d.ts +26 -0
  96. package/dist/photon/errors.d.ts.map +1 -0
  97. package/dist/photon/errors.js +42 -0
  98. package/dist/photon/errors.js.map +1 -0
  99. package/dist/photon/index.d.ts +26 -0
  100. package/dist/photon/index.d.ts.map +1 -0
  101. package/dist/photon/index.js +12 -0
  102. package/dist/photon/index.js.map +1 -0
  103. package/dist/photon/inputs.d.ts +7 -0
  104. package/dist/photon/inputs.d.ts.map +1 -0
  105. package/dist/photon/inputs.js +25 -0
  106. package/dist/photon/inputs.js.map +1 -0
  107. package/dist/photon/links.d.ts +68 -0
  108. package/dist/photon/links.d.ts.map +1 -0
  109. package/dist/photon/links.js +187 -0
  110. package/dist/photon/links.js.map +1 -0
  111. package/dist/photon/live.d.ts +62 -0
  112. package/dist/photon/live.d.ts.map +1 -0
  113. package/dist/photon/live.js +107 -0
  114. package/dist/photon/live.js.map +1 -0
  115. package/dist/photon/machine.d.ts +28 -0
  116. package/dist/photon/machine.d.ts.map +1 -0
  117. package/dist/photon/machine.js +53 -0
  118. package/dist/photon/machine.js.map +1 -0
  119. package/dist/photon/map.d.ts +14 -0
  120. package/dist/photon/map.d.ts.map +1 -0
  121. package/dist/photon/map.js +311 -0
  122. package/dist/photon/map.js.map +1 -0
  123. package/dist/photon/order.d.ts +168 -0
  124. package/dist/photon/order.d.ts.map +1 -0
  125. package/dist/photon/order.js +558 -0
  126. package/dist/photon/order.js.map +1 -0
  127. package/dist/photon/orders.d.ts +5 -0
  128. package/dist/photon/orders.d.ts.map +1 -0
  129. package/dist/photon/orders.js +39 -0
  130. package/dist/photon/orders.js.map +1 -0
  131. package/dist/photon/patient.d.ts +80 -0
  132. package/dist/photon/patient.d.ts.map +1 -0
  133. package/dist/photon/patient.js +347 -0
  134. package/dist/photon/patient.js.map +1 -0
  135. package/dist/photon/photon.d.ts +188 -0
  136. package/dist/photon/photon.d.ts.map +1 -0
  137. package/dist/photon/photon.js +395 -0
  138. package/dist/photon/photon.js.map +1 -0
  139. package/dist/photon/prescription.d.ts +145 -0
  140. package/dist/photon/prescription.d.ts.map +1 -0
  141. package/dist/photon/prescription.js +418 -0
  142. package/dist/photon/prescription.js.map +1 -0
  143. package/dist/photon/session.d.ts +89 -0
  144. package/dist/photon/session.d.ts.map +1 -0
  145. package/dist/photon/session.js +352 -0
  146. package/dist/photon/session.js.map +1 -0
  147. package/dist/photon/types.d.ts +643 -0
  148. package/dist/photon/types.d.ts.map +1 -0
  149. package/dist/photon/types.js +7 -0
  150. package/dist/photon/types.js.map +1 -0
  151. package/dist/test-utils/msw.d.ts +23 -0
  152. package/dist/test-utils/msw.d.ts.map +1 -0
  153. package/dist/test-utils/msw.js +51 -0
  154. package/dist/test-utils/msw.js.map +1 -0
  155. package/dist/testing/fakeNetworkApiClient.d.ts +39 -0
  156. package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
  157. package/dist/testing/fakeNetworkApiClient.js +56 -0
  158. package/dist/testing/fakeNetworkApiClient.js.map +1 -0
  159. package/dist/testing/fixtures.d.ts +1098 -0
  160. package/dist/testing/fixtures.d.ts.map +1 -0
  161. package/dist/testing/fixtures.js +200 -0
  162. package/dist/testing/fixtures.js.map +1 -0
  163. package/dist/testing.d.ts +11 -0
  164. package/dist/testing.d.ts.map +1 -0
  165. package/dist/testing.js +10 -0
  166. package/dist/testing.js.map +1 -0
  167. package/package.json +67 -4
  168. package/src/analytics/lifecycleEvents.test.ts +417 -0
  169. package/src/analytics/lifecycleEvents.ts +155 -0
  170. package/src/api/changes/applyOption.ts +103 -0
  171. package/src/api/changes/classifyChanges.ts +10 -0
  172. package/src/api/changes/index.ts +2 -0
  173. package/src/api/client.ts +149 -0
  174. package/src/api/health.ts +7 -0
  175. package/src/api/index.ts +24 -0
  176. package/src/api/me.ts +7 -0
  177. package/src/api/order.ts +64 -0
  178. package/src/api/orders.ts +8 -0
  179. package/src/api/patient.ts +67 -0
  180. package/src/api/prescription.ts +86 -0
  181. package/src/api/results.ts +45 -0
  182. package/src/gql/gql.ts +68 -0
  183. package/src/gql/graphql.ts +9027 -0
  184. package/src/gql/index.ts +2 -0
  185. package/src/index.ts +14 -0
  186. package/src/meta/version.test.ts +10 -0
  187. package/src/meta/version.ts +1 -0
  188. package/src/operations/fragments.graphql +497 -0
  189. package/src/operations/health.graphql +4 -0
  190. package/src/operations/me.graphql +38 -0
  191. package/src/operations/order.graphql +42 -0
  192. package/src/operations/orders.graphql +35 -0
  193. package/src/operations/patient.graphql +62 -0
  194. package/src/operations/prescription.graphql +90 -0
  195. package/src/photon/analytics.ts +129 -0
  196. package/src/photon/auth.ts +69 -0
  197. package/src/photon/choices.ts +79 -0
  198. package/src/photon/context.ts +30 -0
  199. package/src/photon/environments.ts +49 -0
  200. package/src/photon/errors.ts +56 -0
  201. package/src/photon/index.ts +49 -0
  202. package/src/photon/inputs.ts +24 -0
  203. package/src/photon/links.ts +197 -0
  204. package/src/photon/live.ts +135 -0
  205. package/src/photon/machine.ts +90 -0
  206. package/src/photon/map.ts +371 -0
  207. package/src/photon/order.test.ts +142 -0
  208. package/src/photon/order.ts +661 -0
  209. package/src/photon/orders.ts +42 -0
  210. package/src/photon/patient.ts +386 -0
  211. package/src/photon/photon.ts +646 -0
  212. package/src/photon/prescription.ts +506 -0
  213. package/src/photon/session.ts +454 -0
  214. package/src/photon/types.ts +583 -0
  215. package/src/test-utils/msw.ts +72 -0
  216. package/src/testing/fakeNetworkApiClient.ts +56 -0
  217. package/src/testing/fixtures.ts +233 -0
  218. package/src/testing.ts +25 -0
@@ -0,0 +1,454 @@
1
+ import { PhotonError } from "./errors.ts";
2
+
3
+ /**
4
+ * The prescriber's sign-in, run by core in the browser: OAuth 2 authorization code with PKCE against the
5
+ * environment's Auth0 tenant — no SDK, no dependency (the browser's own crypto, fetch and storage).
6
+ *
7
+ * start() once, on load: finishes a sign-in coming back from Auth0 (only one this session started — a host's
8
+ * own `?code` is left alone), else renews a stored session, else signed out. Never redirects.
9
+ * signIn() from a click: redirects to Auth0 (its organization picker, or straight into `?organization=`).
10
+ * Inside an iframe, where Auth0's page won't load, it's a popup. `signInUrl()`: that page, to go to.
11
+ * signOut() forgets the session and ends Auth0's (`signOutUrl()`). The cards never offer it; an app may.
12
+ * token() the access token, renewed shortly before it expires — one renewal at a time.
13
+ *
14
+ * One session per Auth0 tenant and client per page (`sessionFor`): providers anywhere in the tree share it, and
15
+ * the code from a redirect is exchanged once. A live object: `subscribe` + `snapshot`.
16
+ *
17
+ * Where it's kept: the access token only in this page's memory. Across page loads, `localStorage` keeps the
18
+ * refresh token and who it's for — never the access token — so each load starts with a refresh. Auth0 rotates
19
+ * refresh tokens with reuse detection: a stolen one is revoked, with the whole chain, the first time either side
20
+ * uses a token the other already has. So the tabs of a site take turns (Web Locks) and each uses the newest one
21
+ * stored. No refresh token from Auth0: nothing is kept, and the session lasts as long as the page.
22
+ *
23
+ * Known risks: a script on the page can still read the refresh token (the posture chosen, Auth0's own for SPAs);
24
+ * a session ending mid-work swaps the cards for Sign in.
25
+ */
26
+ export type SessionStatus = "starting" | "signed-out" | "signing-in" | "signed-in" | "error";
27
+
28
+ export interface SessionUser {
29
+ name: string | null;
30
+ email: string | null;
31
+ /** The Photon organization the token is scoped to (`org_id`); null if the sign-in didn't pick one. */
32
+ organization: string | null;
33
+ }
34
+
35
+ export interface SessionSnapshot {
36
+ readonly status: SessionStatus;
37
+ readonly user: SessionUser | null;
38
+ readonly error: PhotonError | null;
39
+ }
40
+
41
+ /** Where `signIn` goes at Auth0. */
42
+ export interface SignInOptions {
43
+ /** The Photon organization to sign in to, past Auth0's picker. */
44
+ organization?: string;
45
+ /** An Auth0 connection (e.g. `"google-oauth2"`): straight to that identity provider, past Auth0's own page. */
46
+ connection?: string;
47
+ }
48
+
49
+ export interface SessionConfig {
50
+ /** The Auth0 tenant (`auth.<env>.health`). */
51
+ domain: string;
52
+ clientId: string;
53
+ /** The token audience network-api accepts. */
54
+ audience: string;
55
+ /** For tests: fetch, and how to leave the page. */
56
+ fetch?: typeof fetch;
57
+ navigate?: (url: string) => void;
58
+ openPopup?: (url: string) => Window | null;
59
+ }
60
+
61
+ /** What's kept across page loads: the refresh token and who it's for. Never the access token. */
62
+ interface Stored {
63
+ refreshToken: string;
64
+ user: SessionUser;
65
+ }
66
+
67
+ /** The access token: this page's memory only. */
68
+ interface Access {
69
+ token: string;
70
+ expiresAt: number;
71
+ }
72
+
73
+ interface Pending {
74
+ verifier: string;
75
+ returnTo: string;
76
+ redirectUri: string;
77
+ }
78
+
79
+ /** Renew this long before the token expires. */
80
+ const EARLY_MS = 60_000;
81
+ /** Auth0's own params on a callback — taken off the URL once handled. */
82
+ const CALLBACK_PARAMS = [
83
+ "code",
84
+ "state",
85
+ "error",
86
+ "error_description",
87
+ "organization",
88
+ "organization_name",
89
+ "invitation",
90
+ ];
91
+
92
+ export class Session {
93
+ #snapshot: SessionSnapshot = { status: "starting", user: null, error: null };
94
+ #listeners = new Set<() => void>();
95
+ #access: Access | null = null;
96
+ #user: SessionUser | null = null;
97
+ /** The refresh token, for when storage can't keep it (`#kept` false): then it lasts as long as the page. */
98
+ #refreshToken: string | null = null;
99
+ /** Whether storage holds the refresh token — then the newest one is read from there (another tab may rotate it). */
100
+ #kept = false;
101
+ #renewing: Promise<string> | null = null;
102
+ #started: Promise<void> | null = null;
103
+ readonly #config: SessionConfig;
104
+
105
+ constructor(config: SessionConfig) {
106
+ this.#config = config;
107
+ }
108
+
109
+ get snapshot(): SessionSnapshot {
110
+ return this.#snapshot;
111
+ }
112
+ get status(): SessionStatus {
113
+ return this.#snapshot.status;
114
+ }
115
+ get user(): SessionUser | null {
116
+ return this.#snapshot.user;
117
+ }
118
+ subscribe = (listener: () => void): (() => void) => {
119
+ this.#listeners.add(listener);
120
+ return () => this.#listeners.delete(listener);
121
+ };
122
+
123
+ /** Once per session: finish a sign-in that's coming back, else renew a stored one, else signed out. */
124
+ start(): Promise<void> {
125
+ return (this.#started ??= this.#start());
126
+ }
127
+
128
+ /**
129
+ * Sign in — from a click. Leaves the page for Auth0 (its organization picker; `organization`, or the page's
130
+ * `?organization=`, goes straight in; `connection`, e.g. `"google-oauth2"`, goes straight to that identity provider,
131
+ * past Auth0's page) and comes back here. Inside an iframe: a popup, then signed in here.
132
+ */
133
+ async signIn(options: SignInOptions = {}): Promise<void> {
134
+ this.#set({ status: "signing-in", error: null });
135
+ if (window.top !== window) {
136
+ const { params, state, pending } = await this.#authorize(options);
137
+ return this.#popup(params, state, pending);
138
+ }
139
+ this.#navigate(await this.signInUrl(options));
140
+ }
141
+
142
+ /**
143
+ * Auth0's sign-in page for this session — to link to, or go to yourself. It's ready to come back to: the next
144
+ * `start()` on this page finishes the sign-in (PKCE: the verifier is kept for it, in this tab).
145
+ */
146
+ async signInUrl(options: SignInOptions = {}): Promise<string> {
147
+ const { params, state, pending } = await this.#authorize(options);
148
+ write(sessionStorage, pendingKey(state), pending);
149
+ return this.#authorizeUrl(params);
150
+ }
151
+
152
+ /** Auth0's sign-out page, coming back to `returnTo` (this site, unless said; Auth0 must allow it). */
153
+ signOutUrl(options: { returnTo?: string } = {}): string {
154
+ const returnTo = options.returnTo ?? window.location.origin;
155
+ return `https://${this.#config.domain}/v2/logout?${new URLSearchParams({ client_id: this.#config.clientId, returnTo })}`;
156
+ }
157
+
158
+ /** Sign out: forget the session here, and end Auth0's (`signOutUrl`). Not something the cards offer. */
159
+ signOut(options: { returnTo?: string } = {}): void {
160
+ this.#forget();
161
+ this.#set({ status: "signed-out", user: null, error: null });
162
+ this.#navigate(this.signOutUrl(options));
163
+ }
164
+
165
+ /** The access token for network-api, renewed when it's about to expire. Signed out: `unauthorized`. */
166
+ async token(): Promise<string> {
167
+ await this.start();
168
+ const access = this.#access;
169
+ if (access && access.expiresAt - EARLY_MS > Date.now()) return access.token;
170
+ return (this.#renewing ??= this.#renew().finally(() => (this.#renewing = null)));
171
+ }
172
+
173
+ // ---- inside ----
174
+
175
+ /** A sign-in request: Auth0's parameters (PKCE), and what coming back needs. */
176
+ async #authorize(options: SignInOptions) {
177
+ const state = randomString(16);
178
+ const verifier = randomString(32);
179
+ const redirectUri = window.location.origin;
180
+ const organization = options.organization ?? new URLSearchParams(window.location.search).get("organization");
181
+ const params = new URLSearchParams({
182
+ response_type: "code",
183
+ client_id: this.#config.clientId,
184
+ redirect_uri: redirectUri,
185
+ audience: this.#config.audience,
186
+ scope: "openid profile email offline_access",
187
+ state,
188
+ code_challenge: await challengeOf(verifier),
189
+ code_challenge_method: "S256",
190
+ ...(organization ? { organization } : {}),
191
+ ...(options.connection ? { connection: options.connection } : {}),
192
+ });
193
+ const pending: Pending = { verifier, returnTo: returnTo(), redirectUri };
194
+ return { params, state, pending };
195
+ }
196
+
197
+ #navigate(url: string) {
198
+ (this.#config.navigate ?? ((to) => window.location.assign(to)))(url);
199
+ }
200
+
201
+ async #start(): Promise<void> {
202
+ const params = new URLSearchParams(window.location.search);
203
+ const state = params.get("state");
204
+ const pending = state ? read<Pending>(sessionStorage, pendingKey(state)) : null;
205
+ try {
206
+ if (pending && state) {
207
+ sessionStorage.removeItem(pendingKey(state));
208
+ window.history.replaceState(window.history.state, "", pending.returnTo);
209
+ if (params.get("error")) throw signInError(params.get("error_description") ?? params.get("error")!);
210
+ await this.#exchange(params.get("code")!, pending);
211
+ return;
212
+ }
213
+ const stored = this.#readStored();
214
+ if (!stored) return this.#set({ status: "signed-out" });
215
+ this.#user = stored.user;
216
+ await this.#renew(); // the access token was never kept: every load starts with a refresh
217
+ } catch (e) {
218
+ // A stored session that couldn't be renewed is just signed out (#signedOut); anything else is an error.
219
+ if (this.#snapshot.status !== "signed-out") this.#set({ status: "error", user: null, error: asError(e) });
220
+ }
221
+ }
222
+
223
+ /**
224
+ * A new access token from the refresh token. Auth0 rotates it, and the new one is kept. One tab at a time, each
225
+ * using the newest stored: two tabs using the same refresh token looks like theft to Auth0, which revokes it.
226
+ */
227
+ #renew(): Promise<string> {
228
+ return this.#oneTabAtATime(async () => {
229
+ const refreshToken = this.#kept ? (this.#readStored()?.refreshToken ?? null) : this.#refreshToken;
230
+ if (!refreshToken) return this.#signedOut(); // signed out here, or in another tab
231
+ try {
232
+ const tokens = await this.#tokenRequest({ grant_type: "refresh_token", refresh_token: refreshToken });
233
+ this.#keep(tokens, refreshToken);
234
+ return this.#access!.token;
235
+ } catch (e) {
236
+ // A refresh token Auth0 won't take (expired, revoked, rotated away): signed out — not an error.
237
+ if (e instanceof PhotonError && e.kind === "unauthorized") return this.#signedOut();
238
+ throw e;
239
+ }
240
+ });
241
+ }
242
+
243
+ /** Runs `renew` holding this site's lock for the session (Web Locks); where there are none, just this tab's. */
244
+ #oneTabAtATime<T>(renew: () => Promise<T>): Promise<T> {
245
+ const locks = globalThis.navigator?.locks;
246
+ return locks ? locks.request(`${this.#storeKey()}:refresh`, renew) : renew();
247
+ }
248
+
249
+ /** The stored refresh token and user. An older record (with an access token) is trimmed to them, or dropped. */
250
+ #readStored(): Stored | null {
251
+ const raw = read<Partial<Stored> & { accessToken?: unknown }>(localStorage, this.#storeKey());
252
+ if (!raw) return null;
253
+ if (typeof raw.refreshToken !== "string" || !raw.user) {
254
+ remove(localStorage, this.#storeKey());
255
+ return null;
256
+ }
257
+ const stored = { refreshToken: raw.refreshToken, user: raw.user };
258
+ if ("accessToken" in raw) write(localStorage, this.#storeKey(), stored);
259
+ this.#kept = true;
260
+ return stored;
261
+ }
262
+
263
+ async #exchange(code: string, pending: Pending) {
264
+ const tokens = await this.#tokenRequest({
265
+ grant_type: "authorization_code",
266
+ code,
267
+ code_verifier: pending.verifier,
268
+ redirect_uri: pending.redirectUri,
269
+ });
270
+ this.#keep(tokens, null);
271
+ }
272
+
273
+ async #popup(params: URLSearchParams, state: string, pending: Pending) {
274
+ params.set("response_mode", "web_message");
275
+ const url = this.#authorizeUrl(params);
276
+ const popup = (this.#config.openPopup ?? ((u) => window.open(u, "photon-sign-in", "width=480,height=720")))(url);
277
+ if (!popup) return this.#set({ status: "error", error: signInError("The sign-in window was blocked.") });
278
+ const origin = `https://${this.#config.domain}`;
279
+ const code = await new Promise<string | null>((resolve) => {
280
+ const done = (value: string | null) => {
281
+ window.removeEventListener("message", hear);
282
+ clearInterval(closed);
283
+ resolve(value);
284
+ };
285
+ // Auth0 posts the result to this window (response_mode=web_message).
286
+ const hear = (e: MessageEvent) => {
287
+ const response = e.data?.type === "authorization_response" ? e.data.response : null;
288
+ if (e.origin !== origin || !response || response.state !== state) return;
289
+ popup.close();
290
+ done(response.error ? null : response.code);
291
+ };
292
+ window.addEventListener("message", hear);
293
+ const closed = setInterval(() => popup.closed && done(null), 500);
294
+ });
295
+ if (!code) return this.#set({ status: this.#access ? "signed-in" : "signed-out" });
296
+ try {
297
+ await this.#exchange(code, pending);
298
+ } catch (e) {
299
+ this.#set({ status: "error", error: asError(e) });
300
+ }
301
+ }
302
+
303
+ async #tokenRequest(body: Record<string, string>): Promise<TokenResponse> {
304
+ const response = await (this.#config.fetch ?? fetch)(`https://${this.#config.domain}/oauth/token`, {
305
+ method: "POST",
306
+ headers: { "Content-Type": "application/json" },
307
+ body: JSON.stringify({ client_id: this.#config.clientId, ...body }),
308
+ }).catch((e: unknown) => {
309
+ throw new PhotonError("network", "Couldn't reach sign-in.", true, { cause: e });
310
+ });
311
+ const json = (await response.json().catch(() => ({}))) as Partial<TokenResponse> & {
312
+ error?: string;
313
+ error_description?: string;
314
+ };
315
+ if (!response.ok || !json.access_token)
316
+ throw new PhotonError(
317
+ response.status >= 500 ? "network" : "unauthorized",
318
+ json.error_description ?? json.error ?? `Sign-in failed (${response.status}).`,
319
+ response.status >= 500,
320
+ );
321
+ return json as TokenResponse;
322
+ }
323
+
324
+ #keep(tokens: TokenResponse, previousRefresh: string | null) {
325
+ const claims = { ...claimsOf(tokens.id_token), ...claimsOf(tokens.access_token) };
326
+ this.#access = { token: tokens.access_token, expiresAt: Date.now() + (tokens.expires_in ?? 3600) * 1000 };
327
+ // The access token has the org; a refresh's id token may not come back, so the user carries over.
328
+ this.#user = {
329
+ name: str(claims.name) ?? this.#user?.name ?? null,
330
+ email: str(claims.email) ?? this.#user?.email ?? null,
331
+ organization: str(claims.org_id),
332
+ };
333
+ this.#refreshToken = tokens.refresh_token ?? previousRefresh;
334
+ // Only the refresh token and the user are kept. None from Auth0: nothing is — the session lasts the page.
335
+ if (this.#refreshToken)
336
+ this.#kept = write(localStorage, this.#storeKey(), { refreshToken: this.#refreshToken, user: this.#user });
337
+ else this.#forgetStored();
338
+ this.#set({ status: "signed-in", user: this.#user, error: null });
339
+ }
340
+
341
+ #signedOut(): never {
342
+ this.#forget();
343
+ this.#set({ status: "signed-out", user: null, error: null });
344
+ throw new PhotonError("unauthorized", "Sign in to Photon first.");
345
+ }
346
+
347
+ #forget() {
348
+ this.#access = null;
349
+ this.#user = null;
350
+ this.#refreshToken = null;
351
+ this.#forgetStored();
352
+ }
353
+
354
+ #forgetStored() {
355
+ remove(localStorage, this.#storeKey());
356
+ this.#kept = false;
357
+ }
358
+
359
+ #authorizeUrl(params: URLSearchParams) {
360
+ return `https://${this.#config.domain}/authorize?${params.toString()}`;
361
+ }
362
+
363
+ #storeKey() {
364
+ return `photon-rx:session:${this.#config.domain}:${this.#config.clientId}`;
365
+ }
366
+
367
+ #set(next: Partial<SessionSnapshot>) {
368
+ this.#snapshot = { ...this.#snapshot, ...next };
369
+ for (const listener of this.#listeners) listener();
370
+ }
371
+ }
372
+
373
+ interface TokenResponse {
374
+ access_token: string;
375
+ id_token?: string;
376
+ refresh_token?: string;
377
+ expires_in?: number;
378
+ }
379
+
380
+ /** One session per Auth0 tenant and client per page: every provider (and instance) for it shares one. */
381
+ const sessions = new Map<string, Session>();
382
+ export function sessionFor(config: SessionConfig): Session {
383
+ const key = `${config.domain}:${config.clientId}:${config.audience}`;
384
+ let session = sessions.get(key);
385
+ if (!session) sessions.set(key, (session = new Session(config)));
386
+ return session;
387
+ }
388
+
389
+ // ---- helpers ----
390
+
391
+ const pendingKey = (state: string) => `photon-rx:sign-in:${state}`;
392
+
393
+ /** Where to come back to: this page, minus Auth0's params. */
394
+ function returnTo(): string {
395
+ const url = new URL(window.location.href);
396
+ for (const key of CALLBACK_PARAMS) url.searchParams.delete(key);
397
+ return url.pathname + url.search + url.hash;
398
+ }
399
+
400
+ function randomString(bytes: number): string {
401
+ return base64Url(crypto.getRandomValues(new Uint8Array(bytes)));
402
+ }
403
+
404
+ async function challengeOf(verifier: string): Promise<string> {
405
+ return base64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
406
+ }
407
+
408
+ function base64Url(bytes: Uint8Array): string {
409
+ let binary = "";
410
+ for (const b of bytes) binary += String.fromCharCode(b);
411
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
412
+ }
413
+
414
+ /** A JWT's claims (not verified — read only for display and the org; network-api checks the token). */
415
+ export function claimsOf(jwt: string | undefined): Record<string, unknown> {
416
+ const payload = jwt?.split(".")[1];
417
+ if (!payload) return {};
418
+ try {
419
+ const binary = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
420
+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
421
+ return JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>;
422
+ } catch {
423
+ return {};
424
+ }
425
+ }
426
+
427
+ const str = (value: unknown) => (typeof value === "string" ? value : null);
428
+ const signInError = (message: string) => new PhotonError("unauthorized", message);
429
+ const asError = (e: unknown) => (e instanceof PhotonError ? e : new PhotonError("network", String(e), true));
430
+
431
+ function read<T>(storage: Storage, key: string): T | null {
432
+ try {
433
+ const raw = storage.getItem(key);
434
+ return raw ? (JSON.parse(raw) as T) : null;
435
+ } catch {
436
+ return null;
437
+ }
438
+ }
439
+ /** Whether it was written: storage can be unavailable (then the session lasts as long as the page). */
440
+ function write(storage: Storage, key: string, value: unknown): boolean {
441
+ try {
442
+ storage.setItem(key, JSON.stringify(value));
443
+ return true;
444
+ } catch {
445
+ return false;
446
+ }
447
+ }
448
+ function remove(storage: Storage, key: string) {
449
+ try {
450
+ storage.removeItem(key);
451
+ } catch {
452
+ // nothing stored
453
+ }
454
+ }