@jsb188/graphql 1.1.11 → 1.1.13

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 (174) hide show
  1. package/LICENSE +21 -0
  2. package/audience.d.ts +205 -0
  3. package/cache/config.ts +65 -28
  4. package/cache/index.helpers.ts +96 -0
  5. package/cache/index.ts +364 -808
  6. package/cache/mounted-queries.ts +33 -0
  7. package/cache/optimistic-ui-runtime.ts +46 -0
  8. package/cache/optimistic-ui.ts +401 -0
  9. package/cache/persist.ts +107 -22
  10. package/cache/realtime-fence.ts +47 -0
  11. package/cache/realtime-live.ts +17 -0
  12. package/cache/store.ts +22 -64
  13. package/cache/value.helpers.ts +17 -0
  14. package/{drafts/store.ts → client/draft-persistence-indexed-db.ts} +19 -3
  15. package/{drafts/index.ts → client/draft-persistence.ts} +13 -39
  16. package/client/index.ts +4 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +122 -232
  19. package/client/storage-asset.ts +58 -0
  20. package/gql/fragments/accountAuthFragments.ts +0 -4
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +156 -0
  23. package/gql/fragments/aiChatFragments.ts +35 -11
  24. package/gql/fragments/aiChatLinkFragments.ts +8 -0
  25. package/gql/fragments/audienceFragments.ts +76 -0
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +49 -21
  28. package/gql/fragments/emailOutreachFragments.ts +281 -0
  29. package/gql/fragments/fieldDocFragments.ts +222 -40
  30. package/gql/fragments/inboundContactFragments.ts +2 -0
  31. package/gql/fragments/libraryFragments.ts +120 -0
  32. package/gql/fragments/logFragments.ts +93 -2
  33. package/gql/fragments/organizationFragments.ts +12 -0
  34. package/gql/fragments/qrCodeFragments.ts +29 -0
  35. package/gql/fragments/scheduleFragments.ts +574 -145
  36. package/gql/fragments/sheetFragments.ts +86 -424
  37. package/gql/fragments/storageFragments.ts +25 -1
  38. package/gql/fragments/workWaitFragments.ts +13 -0
  39. package/gql/fragments/workflowFragments.ts +32 -4
  40. package/gql/mutations/agentMemoryMutations.ts +32 -0
  41. package/gql/mutations/agentNoteMutations.ts +64 -0
  42. package/gql/mutations/aiChatLinkMutations.ts +13 -0
  43. package/gql/mutations/aiChatMutations.ts +34 -4
  44. package/gql/mutations/audienceMutations.ts +58 -0
  45. package/gql/mutations/authMutations.ts +24 -28
  46. package/gql/mutations/billingMutations.ts +24 -0
  47. package/gql/mutations/contactMutations.ts +23 -0
  48. package/gql/mutations/dataTableMutations.ts +18 -75
  49. package/gql/mutations/emailMutations.ts +22 -0
  50. package/gql/mutations/emailOutreachMutations.ts +139 -0
  51. package/gql/mutations/fieldDocMutations.ts +162 -13
  52. package/gql/mutations/index.ts +10 -5
  53. package/gql/mutations/organizationMutations.ts +6 -0
  54. package/gql/mutations/qrCodeMutations.ts +20 -0
  55. package/gql/mutations/scheduleMutations.ts +389 -417
  56. package/gql/mutations/sheetMutations.ts +62 -118
  57. package/gql/mutations/storageMutations.ts +1 -1
  58. package/gql/mutations/workflowMutations.ts +94 -0
  59. package/gql/queries/agentMemoryQueries.ts +12 -2
  60. package/gql/queries/agentNoteQueries.ts +86 -0
  61. package/gql/queries/aiChatQueries.ts +63 -12
  62. package/gql/queries/audienceQueries.ts +104 -0
  63. package/gql/queries/authQueries.ts +20 -4
  64. package/gql/queries/billingQueries.ts +114 -9
  65. package/gql/queries/dataTableQueries.ts +43 -75
  66. package/gql/queries/emailOutreachQueries.ts +282 -0
  67. package/gql/queries/emailQueries.ts +48 -64
  68. package/gql/queries/emailReplyReportQueries.ts +127 -0
  69. package/gql/queries/fieldDocQueries.ts +128 -98
  70. package/gql/queries/inboundContactQueries.ts +15 -4
  71. package/gql/queries/index.ts +5 -3
  72. package/gql/queries/libraryQueries.ts +112 -0
  73. package/gql/queries/logQueries.ts +86 -12
  74. package/gql/queries/organizationQueries.ts +44 -12
  75. package/gql/queries/qrCodeQueries.ts +27 -0
  76. package/gql/queries/scheduleQueries.ts +401 -278
  77. package/gql/queries/sheetQueries.ts +94 -165
  78. package/gql/queries/storageQueries.ts +11 -4
  79. package/gql/queries/workflowQueries.ts +61 -12
  80. package/gql/reactivity.ts +98 -0
  81. package/gql/recordReads.ts +171 -0
  82. package/hooks/index.helpers.ts +52 -0
  83. package/hooks/index.ts +920 -715
  84. package/hooks/use-agentMemory-mtn.ts +29 -31
  85. package/hooks/use-agentMemory-qry.ts +15 -3
  86. package/hooks/use-agentNote-mtn.ts +89 -0
  87. package/hooks/use-agentNote-qry.ts +162 -0
  88. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  89. package/hooks/use-agentNote-recovery.ts +57 -0
  90. package/hooks/use-aiChat-mtn.ts +104 -115
  91. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  92. package/hooks/use-aiChat-qry.ts +254 -387
  93. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  94. package/hooks/use-audience-mtn.ts +170 -0
  95. package/hooks/use-audience-qry.helpers.ts +39 -0
  96. package/hooks/use-audience-qry.ts +245 -0
  97. package/hooks/use-auth-mtn.ts +30 -1
  98. package/hooks/use-billing-mtn.ts +31 -0
  99. package/hooks/use-billing-qry.ts +76 -0
  100. package/hooks/use-dataTable-mtn.ts +23 -115
  101. package/hooks/use-dataTable-qry.ts +69 -914
  102. package/hooks/use-email-mtn.ts +26 -0
  103. package/hooks/use-email-qry.helpers.ts +37 -0
  104. package/hooks/use-email-qry.ts +44 -174
  105. package/hooks/use-emailOutreach-mtn.ts +211 -0
  106. package/hooks/use-emailOutreach-qry.helpers.ts +25 -0
  107. package/hooks/use-emailOutreach-qry.ts +367 -0
  108. package/hooks/use-emailOutreachReplyReport-qry.ts +46 -0
  109. package/hooks/use-fieldDoc-mtn.ts +244 -32
  110. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  111. package/hooks/use-fieldDoc-qry.ts +134 -102
  112. package/hooks/use-inboundContact-qry.ts +7 -9
  113. package/hooks/use-library-qry.ts +233 -0
  114. package/hooks/use-log-mtn.ts +25 -12
  115. package/hooks/use-log-qry.ts +99 -46
  116. package/hooks/use-organization-qry.ts +16 -60
  117. package/hooks/use-qrCode-mtn.ts +40 -0
  118. package/hooks/use-qrCode-qry.ts +78 -0
  119. package/hooks/use-schedule-mtn.ts +231 -348
  120. package/hooks/use-schedule-qry.ts +208 -139
  121. package/hooks/use-schedule-reactive.ts +218 -0
  122. package/hooks/use-sheet-mtn.ts +91 -199
  123. package/hooks/use-sheet-qry.ts +88 -237
  124. package/hooks/use-storage-qry.ts +84 -61
  125. package/hooks/use-workflow-mtn.ts +84 -23
  126. package/hooks/use-workflow-qry.ts +60 -61
  127. package/libs/ai-chat-link-events.ts +78 -0
  128. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  129. package/libs/ai-chat-outgoing.ts +11 -0
  130. package/libs/ai-chat-outgoing.types.ts +25 -0
  131. package/libs/ai-chat-run-realtime.ts +20 -0
  132. package/libs/ai-chat-submission-realtime.ts +150 -0
  133. package/libs/data-changes.helpers.ts +161 -0
  134. package/libs/data-changes.ts +382 -0
  135. package/libs/fragment-realtime-sequence.ts +55 -0
  136. package/libs/open-sheet.ts +138 -0
  137. package/libs/record-read.ts +327 -0
  138. package/libs/sheet-command-batch.ts +45 -0
  139. package/libs/sheet-realtime-packet.ts +53 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/emailPreference.ts +69 -0
  142. package/loaders/rest.ts +12 -0
  143. package/package.json +77 -25
  144. package/schedule.d.ts +1183 -0
  145. package/sse.helpers.ts +19 -0
  146. package/sse.ts +26 -115
  147. package/types.d.ts +48 -25
  148. package/cache/index.test.ts +0 -881
  149. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  150. package/client/data-table-realtime-subscriptions.ts +0 -955
  151. package/client/data-table-realtime.test.ts +0 -792
  152. package/client/data-table-realtime.ts +0 -1218
  153. package/client/fragment-realtime-sequence.ts +0 -52
  154. package/client/open-sheet.ts +0 -137
  155. package/client/request-managed-session.test.ts +0 -574
  156. package/client/request-no-store.test.ts +0 -157
  157. package/client/sse-ticket.test.ts +0 -26
  158. package/deno.lock +0 -170
  159. package/deno.test.json +0 -10
  160. package/gql/fragments/agentDocFragments.ts +0 -46
  161. package/gql/fragments/billingFragments.ts +0 -14
  162. package/gql/fragments/campaignFragments.ts +0 -277
  163. package/gql/mutations/agentDocMutations.ts +0 -177
  164. package/gql/mutations/campaignMutations.ts +0 -215
  165. package/gql/queries/agentDocQueries.ts +0 -120
  166. package/gql/queries/appQueries.ts +0 -14
  167. package/gql/queries/campaignQueries.ts +0 -127
  168. package/hooks/use-agentDoc-mtn.ts +0 -285
  169. package/hooks/use-agentDoc-qry.ts +0 -208
  170. package/hooks/use-app-qry.ts +0 -22
  171. package/hooks/use-campaign-mtn.ts +0 -377
  172. package/hooks/use-campaign-qry.ts +0 -257
  173. package/loaders/campaign.ts +0 -137
  174. package/tsconfig.json +0 -13
@@ -1,574 +0,0 @@
1
- import { registerENV } from '@jsb188/app';
2
- import { setAuthToken } from '@jsb188/app/utils/api.ts';
3
- import {
4
- graphqlRequestNoStore,
5
- setGraphQLAccessTokenRefreshHandler,
6
- setGraphQLManagedSessionVersion,
7
- } from './request.ts';
8
-
9
- /**
10
- * Build the smallest GraphQL document needed to test request authorization.
11
- */
12
- function buildManagedSessionTestQuery() {
13
- return {
14
- definitions: [
15
- {
16
- kind: 'OperationDefinition',
17
- name: { value: 'managedSessionTest' },
18
- },
19
- ],
20
- loc: { source: { body: 'query managedSessionTest { viewer { id } }' } },
21
- };
22
- }
23
-
24
- /**
25
- * Build an unsigned JWT-shaped value whose expiry can drive proactive refresh.
26
- */
27
- function buildAccessToken(
28
- expiresAtSeconds: number,
29
- name: string,
30
- managed = true,
31
- binding: { accountId: string; sessionId: string } = {
32
- accountId: '1',
33
- sessionId: '101',
34
- },
35
- ) {
36
- const encode = (value: object) =>
37
- btoa(JSON.stringify(value))
38
- .replace(/=/g, '')
39
- .replace(/\+/g, '-')
40
- .replace(/\//g, '_');
41
-
42
- return `${encode({ alg: 'none' })}.${encode({
43
- exp: expiresAtSeconds,
44
- name,
45
- accountId: binding.accountId,
46
- ...(managed
47
- ? {
48
- __name: 'type:AccountAuth',
49
- sessionVersion: 1,
50
- sid: binding.sessionId,
51
- }
52
- : null),
53
- })}.signature`;
54
- }
55
-
56
- /**
57
- * Create one manually resolved promise for cross-session refresh race tests.
58
- */
59
- function createDeferred<T>() {
60
- let resolve!: (value: T) => void;
61
- const promise = new Promise<T>((resolvePromise) => {
62
- resolve = resolvePromise;
63
- });
64
- return { promise, resolve };
65
- }
66
-
67
- Deno.test('managed-session capability is explicit and absent by default', async () => {
68
- registerENV({
69
- GQL_SERVER: 'https://graphql.test/managed-session-capability',
70
- IS_BROWSER: '1',
71
- });
72
- const originalFetch = globalThis.fetch;
73
- const advertisedVersions: Array<string | null> = [];
74
- const bffProofs: Array<string | null> = [];
75
- globalThis.fetch = (async (_input: URL | RequestInfo, init?: RequestInit) => {
76
- const headers = new Headers(init?.headers);
77
- advertisedVersions.push(headers.get('x-managed-session-version'));
78
- bffProofs.push(headers.get('x-managed-session-bff-proof'));
79
- return new Response(JSON.stringify({ data: { viewer: null } }), {
80
- status: 200,
81
- headers: { 'content-type': 'application/json' },
82
- });
83
- }) as typeof fetch;
84
-
85
- try {
86
- setGraphQLManagedSessionVersion(null);
87
- await graphqlRequestNoStore(buildManagedSessionTestQuery());
88
- setGraphQLManagedSessionVersion(1);
89
- await graphqlRequestNoStore(buildManagedSessionTestQuery());
90
- await graphqlRequestNoStore(buildManagedSessionTestQuery(), undefined, {
91
- managedSessionVersion: null,
92
- });
93
- await graphqlRequestNoStore(buildManagedSessionTestQuery(), undefined, {
94
- managedSessionBffProof: 'signed-bff-proof',
95
- });
96
-
97
- if (
98
- advertisedVersions.length !== 4 ||
99
- advertisedVersions[0] !== null ||
100
- advertisedVersions[1] !== '1' ||
101
- advertisedVersions[2] !== null ||
102
- bffProofs[3] !== 'signed-bff-proof'
103
- ) {
104
- throw new Error(
105
- `Managed-session capability headers were not opt-in: ${advertisedVersions.join(',')}`,
106
- );
107
- }
108
- } finally {
109
- setGraphQLManagedSessionVersion(null);
110
- globalThis.fetch = originalFetch;
111
- }
112
- });
113
-
114
- Deno.test('graphql requests share one proactive managed-session refresh', async () => {
115
- registerENV({
116
- GQL_SERVER: 'https://graphql.test/managed-session',
117
- IS_BROWSER: '1',
118
- });
119
- const originalFetch = globalThis.fetch;
120
- const currentTimeSeconds = Math.floor(Date.now() / 1000);
121
- const expiringAccessToken = buildAccessToken(currentTimeSeconds + 30, 'old');
122
- const refreshedAccessToken = buildAccessToken(
123
- currentTimeSeconds + 900,
124
- 'new',
125
- );
126
- const authorizationHeaders: Array<string | null> = [];
127
- let refreshCount = 0;
128
-
129
- setAuthToken(expiringAccessToken);
130
- setGraphQLAccessTokenRefreshHandler(async () => {
131
- refreshCount += 1;
132
- await Promise.resolve();
133
- setAuthToken(refreshedAccessToken);
134
- return { status: 'REFRESHED', accessToken: refreshedAccessToken };
135
- });
136
- globalThis.fetch = (async (_input: URL | RequestInfo, init?: RequestInit) => {
137
- authorizationHeaders.push(new Headers(init?.headers).get('authorization'));
138
- return new Response(
139
- JSON.stringify({ data: { viewer: { id: 'account-1' } } }),
140
- {
141
- status: 200,
142
- headers: { 'content-type': 'application/json' },
143
- },
144
- );
145
- }) as typeof fetch;
146
-
147
- try {
148
- const query = buildManagedSessionTestQuery();
149
- await Promise.all([
150
- graphqlRequestNoStore(query),
151
- graphqlRequestNoStore(query),
152
- ]);
153
-
154
- if (refreshCount !== 1) {
155
- throw new Error(`Expected one shared refresh, received ${refreshCount}.`);
156
- }
157
- if (
158
- authorizationHeaders.some((header) => header !== refreshedAccessToken)
159
- ) {
160
- throw new Error(
161
- 'A request was sent before the shared refresh completed.',
162
- );
163
- }
164
- } finally {
165
- globalThis.fetch = originalFetch;
166
- setGraphQLAccessTokenRefreshHandler(null);
167
- setAuthToken(null);
168
- }
169
- });
170
-
171
- Deno.test('legacy access tokens remain valid until their original expiry', async () => {
172
- registerENV({
173
- GQL_SERVER: 'https://graphql.test/legacy-session',
174
- IS_BROWSER: '1',
175
- });
176
- const originalFetch = globalThis.fetch;
177
- const legacyAccessToken = buildAccessToken(
178
- Math.floor(Date.now() / 1000) + 30,
179
- 'legacy',
180
- false,
181
- );
182
- let refreshCount = 0;
183
- let authorizationHeader: string | null = null;
184
-
185
- setAuthToken(legacyAccessToken);
186
- setGraphQLAccessTokenRefreshHandler(async () => {
187
- refreshCount += 1;
188
- return { status: 'UNAVAILABLE' };
189
- });
190
- globalThis.fetch = (async (_input: URL | RequestInfo, init?: RequestInit) => {
191
- authorizationHeader = new Headers(init?.headers).get('authorization');
192
- return new Response(
193
- JSON.stringify({ data: { viewer: { id: 'legacy-account' } } }),
194
- {
195
- status: 200,
196
- headers: { 'content-type': 'application/json' },
197
- },
198
- );
199
- }) as typeof fetch;
200
-
201
- try {
202
- await graphqlRequestNoStore(buildManagedSessionTestQuery());
203
- if (refreshCount !== 0 || authorizationHeader !== legacyAccessToken) {
204
- throw new Error(
205
- 'The legacy token was refreshed before its original expiry.',
206
- );
207
- }
208
- } finally {
209
- globalThis.fetch = originalFetch;
210
- setGraphQLAccessTokenRefreshHandler(null);
211
- setAuthToken(null);
212
- }
213
- });
214
-
215
- Deno.test('graphql request refreshes and retries one confirmed auth failure', async () => {
216
- registerENV({
217
- GQL_SERVER: 'https://graphql.test/managed-session',
218
- IS_BROWSER: '1',
219
- });
220
- const originalFetch = globalThis.fetch;
221
- const currentTimeSeconds = Math.floor(Date.now() / 1000);
222
- const accessToken = buildAccessToken(currentTimeSeconds + 900, 'old');
223
- const refreshedAccessToken = buildAccessToken(
224
- currentTimeSeconds + 1800,
225
- 'new',
226
- );
227
- const authorizationHeaders: Array<string | null> = [];
228
- let refreshCount = 0;
229
- let errorCallbackCount = 0;
230
-
231
- setAuthToken(accessToken);
232
- setGraphQLAccessTokenRefreshHandler(async ({ reason }) => {
233
- if (reason !== 'AUTH_FAILURE') {
234
- throw new Error(`Unexpected refresh reason: ${reason}`);
235
- }
236
- refreshCount += 1;
237
- setAuthToken(refreshedAccessToken);
238
- return { status: 'REFRESHED', accessToken: refreshedAccessToken };
239
- });
240
- globalThis.fetch = (async (_input: URL | RequestInfo, init?: RequestInit) => {
241
- authorizationHeaders.push(new Headers(init?.headers).get('authorization'));
242
- if (authorizationHeaders.length === 1) {
243
- return new Response(
244
- JSON.stringify({
245
- errors: [{ errorCode: '20019', statusCode: 401 }],
246
- }),
247
- {
248
- status: 200,
249
- headers: { 'content-type': 'application/json' },
250
- },
251
- );
252
- }
253
-
254
- return new Response(
255
- JSON.stringify({ data: { viewer: { id: 'account-1' } } }),
256
- {
257
- status: 200,
258
- headers: { 'content-type': 'application/json' },
259
- },
260
- );
261
- }) as typeof fetch;
262
-
263
- try {
264
- const result = await graphqlRequestNoStore(
265
- buildManagedSessionTestQuery(),
266
- undefined,
267
- {
268
- onError: () => {
269
- errorCallbackCount += 1;
270
- },
271
- },
272
- );
273
-
274
- if (result?.viewer?.id !== 'account-1') {
275
- throw new Error(
276
- 'The original operation did not return its retried result.',
277
- );
278
- }
279
- if (refreshCount !== 1 || authorizationHeaders.length !== 2) {
280
- throw new Error(
281
- 'The authentication failure was not refreshed exactly once.',
282
- );
283
- }
284
- if (
285
- authorizationHeaders[0] !== accessToken ||
286
- authorizationHeaders[1] !== refreshedAccessToken
287
- ) {
288
- throw new Error('The retry did not replace the rejected access token.');
289
- }
290
- if (errorCallbackCount !== 0) {
291
- throw new Error(
292
- 'The recovered authentication failure leaked to the caller.',
293
- );
294
- }
295
- } finally {
296
- globalThis.fetch = originalFetch;
297
- setGraphQLAccessTokenRefreshHandler(null);
298
- setAuthToken(null);
299
- }
300
- });
301
-
302
- Deno.test('proactive refresh unavailability preserves a still-usable access token', async () => {
303
- registerENV({
304
- GQL_SERVER: 'https://graphql.test/managed-session-proactive-outage',
305
- IS_BROWSER: '1',
306
- });
307
- const originalFetch = globalThis.fetch;
308
- const accessToken = buildAccessToken(
309
- Math.floor(Date.now() / 1000) + 30,
310
- 'proactive-outage',
311
- );
312
- let authorizationHeader: string | null = null;
313
-
314
- setAuthToken(accessToken);
315
- setGraphQLAccessTokenRefreshHandler(async () => ({ status: 'UNAVAILABLE' }));
316
- globalThis.fetch = (async (_input: URL | RequestInfo, init?: RequestInit) => {
317
- authorizationHeader = new Headers(init?.headers).get('authorization');
318
- return new Response(
319
- JSON.stringify({ data: { viewer: { id: 'account-1' } } }),
320
- {
321
- status: 200,
322
- headers: { 'content-type': 'application/json' },
323
- },
324
- );
325
- }) as typeof fetch;
326
-
327
- try {
328
- const result = await graphqlRequestNoStore(buildManagedSessionTestQuery());
329
- if (
330
- result?.viewer?.id !== 'account-1' ||
331
- authorizationHeader !== accessToken
332
- ) {
333
- throw new Error(
334
- 'Proactive refresh unavailability prevented use of the current token.',
335
- );
336
- }
337
- } finally {
338
- globalThis.fetch = originalFetch;
339
- setGraphQLAccessTokenRefreshHandler(null);
340
- setAuthToken(null);
341
- }
342
- });
343
-
344
- Deno.test('proactive refresh unavailability masks a resulting expired-token error', async () => {
345
- registerENV({
346
- GQL_SERVER: 'https://graphql.test/managed-session-proactive-auth-outage',
347
- IS_BROWSER: '1',
348
- });
349
- const originalFetch = globalThis.fetch;
350
- const accessToken = buildAccessToken(
351
- Math.floor(Date.now() / 1000) + 30,
352
- 'proactive-auth-outage',
353
- );
354
-
355
- setAuthToken(accessToken);
356
- setGraphQLAccessTokenRefreshHandler(async () => ({ status: 'UNAVAILABLE' }));
357
- globalThis.fetch = (async () =>
358
- new Response(
359
- JSON.stringify({
360
- errors: [{ errorCode: '20019', statusCode: 401 }],
361
- }),
362
- {
363
- status: 200,
364
- headers: { 'content-type': 'application/json' },
365
- },
366
- )) as typeof fetch;
367
-
368
- try {
369
- const result = await graphqlRequestNoStore(buildManagedSessionTestQuery());
370
- if (
371
- result?.error?.errorCode !== 'network_error' ||
372
- result?.error?.statusCode !== 503
373
- ) {
374
- throw new Error(
375
- 'Proactive refresh unavailability leaked an expired-token error.',
376
- );
377
- }
378
- } finally {
379
- globalThis.fetch = originalFetch;
380
- setGraphQLAccessTokenRefreshHandler(null);
381
- setAuthToken(null);
382
- }
383
- });
384
-
385
- Deno.test('auth failure refresh unavailability becomes a retryable network error', async () => {
386
- registerENV({
387
- GQL_SERVER: 'https://graphql.test/managed-session-auth-outage',
388
- IS_BROWSER: '1',
389
- });
390
- const originalFetch = globalThis.fetch;
391
- const accessToken = buildAccessToken(
392
- Math.floor(Date.now() / 1000) + 900,
393
- 'auth-outage',
394
- );
395
- let fetchCount = 0;
396
-
397
- setAuthToken(accessToken);
398
- setGraphQLAccessTokenRefreshHandler(async () => ({ status: 'UNAVAILABLE' }));
399
- globalThis.fetch = (async () => {
400
- fetchCount += 1;
401
- return new Response(
402
- JSON.stringify({
403
- errors: [{ errorCode: '20019', statusCode: 401 }],
404
- }),
405
- {
406
- status: 200,
407
- headers: { 'content-type': 'application/json' },
408
- },
409
- );
410
- }) as typeof fetch;
411
-
412
- try {
413
- const result = await graphqlRequestNoStore(buildManagedSessionTestQuery());
414
- if (
415
- result?.error?.errorCode !== 'network_error' ||
416
- result?.error?.statusCode !== 503 ||
417
- fetchCount !== 1
418
- ) {
419
- throw new Error(
420
- 'An unavailable refresh leaked the original authentication rejection.',
421
- );
422
- }
423
- } finally {
424
- globalThis.fetch = originalFetch;
425
- setGraphQLAccessTokenRefreshHandler(null);
426
- setAuthToken(null);
427
- }
428
- });
429
-
430
- Deno.test('managed refresh rejects a replacement token from another account session', async () => {
431
- registerENV({
432
- GQL_SERVER: 'https://graphql.test/managed-session-binding',
433
- IS_BROWSER: '1',
434
- });
435
- const originalFetch = globalThis.fetch;
436
- const currentTimeSeconds = Math.floor(Date.now() / 1000);
437
- const accessToken = buildAccessToken(currentTimeSeconds + 30, 'account-a');
438
- const mismatchedAccessToken = buildAccessToken(
439
- currentTimeSeconds + 900,
440
- 'account-b',
441
- true,
442
- { accountId: '2', sessionId: '202' },
443
- );
444
- let authorizationHeader: string | null = null;
445
-
446
- setAuthToken(accessToken);
447
- setGraphQLAccessTokenRefreshHandler(async () => ({
448
- status: 'REFRESHED',
449
- accessToken: mismatchedAccessToken,
450
- }));
451
- globalThis.fetch = (async (_input: URL | RequestInfo, init?: RequestInit) => {
452
- authorizationHeader = new Headers(init?.headers).get('authorization');
453
- return new Response(
454
- JSON.stringify({ data: { viewer: { id: 'account-1' } } }),
455
- {
456
- status: 200,
457
- headers: { 'content-type': 'application/json' },
458
- },
459
- );
460
- }) as typeof fetch;
461
-
462
- try {
463
- await graphqlRequestNoStore(buildManagedSessionTestQuery());
464
- if (authorizationHeader !== accessToken) {
465
- throw new Error(
466
- 'A mismatched account/session refresh token was used for the request.',
467
- );
468
- }
469
- } finally {
470
- globalThis.fetch = originalFetch;
471
- setGraphQLAccessTokenRefreshHandler(null);
472
- setAuthToken(null);
473
- }
474
- });
475
-
476
- Deno.test('refresh work is scoped by token and cancels a request after an account switch', async () => {
477
- registerENV({
478
- GQL_SERVER: 'https://graphql.test/managed-session-switch',
479
- IS_BROWSER: '1',
480
- });
481
- const originalFetch = globalThis.fetch;
482
- const currentTimeSeconds = Math.floor(Date.now() / 1000);
483
- const accountAToken = buildAccessToken(
484
- currentTimeSeconds + 30,
485
- 'account-a-old',
486
- true,
487
- { accountId: '1', sessionId: '101' },
488
- );
489
- const accountARefreshedToken = buildAccessToken(
490
- currentTimeSeconds + 900,
491
- 'account-a-new',
492
- true,
493
- { accountId: '1', sessionId: '101' },
494
- );
495
- const accountBToken = buildAccessToken(
496
- currentTimeSeconds + 30,
497
- 'account-b-old',
498
- true,
499
- { accountId: '2', sessionId: '202' },
500
- );
501
- const accountBRefreshedToken = buildAccessToken(
502
- currentTimeSeconds + 900,
503
- 'account-b-new',
504
- true,
505
- { accountId: '2', sessionId: '202' },
506
- );
507
- const accountARefresh = createDeferred<{
508
- status: 'REFRESHED';
509
- accessToken: string;
510
- }>();
511
- const refreshedTokens: string[] = [];
512
- const authorizationHeaders: Array<string | null> = [];
513
-
514
- setGraphQLAccessTokenRefreshHandler(async ({ accessToken }) => {
515
- refreshedTokens.push(accessToken);
516
- return accessToken === accountAToken
517
- ? accountARefresh.promise
518
- : { status: 'REFRESHED', accessToken: accountBRefreshedToken };
519
- });
520
- globalThis.fetch = (async (_input: URL | RequestInfo, init?: RequestInit) => {
521
- authorizationHeaders.push(new Headers(init?.headers).get('authorization'));
522
- return new Response(
523
- JSON.stringify({ data: { viewer: { id: 'account-2' } } }),
524
- {
525
- status: 200,
526
- headers: { 'content-type': 'application/json' },
527
- },
528
- );
529
- }) as typeof fetch;
530
-
531
- try {
532
- setAuthToken(accountAToken);
533
- const accountARequest = graphqlRequestNoStore(
534
- buildManagedSessionTestQuery(),
535
- );
536
- await Promise.resolve();
537
-
538
- setAuthToken(accountBToken);
539
- const accountBRequest = graphqlRequestNoStore(
540
- buildManagedSessionTestQuery(),
541
- );
542
- await accountBRequest;
543
- accountARefresh.resolve({
544
- status: 'REFRESHED',
545
- accessToken: accountARefreshedToken,
546
- });
547
- const accountAResult = await accountARequest;
548
-
549
- if (
550
- refreshedTokens.length !== 2 ||
551
- !refreshedTokens.includes(accountAToken) ||
552
- !refreshedTokens.includes(accountBToken)
553
- ) {
554
- throw new Error(
555
- 'Different account sessions incorrectly shared one refresh operation.',
556
- );
557
- }
558
- if (
559
- authorizationHeaders.length !== 1 ||
560
- authorizationHeaders[0] !== accountBRefreshedToken
561
- ) {
562
- throw new Error(
563
- 'The switched-away account request was sent after refresh.',
564
- );
565
- }
566
- if (!accountAResult?.aborted) {
567
- throw new Error('The switched-away account request was not cancelled.');
568
- }
569
- } finally {
570
- globalThis.fetch = originalFetch;
571
- setGraphQLAccessTokenRefreshHandler(null);
572
- setAuthToken(null);
573
- }
574
- });