@jsb188/app 1.1.9 → 1.1.11

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 (63) hide show
  1. package/package.json +54 -45
  2. package/src/constants/agent.ts +58 -25
  3. package/src/constants/app.ts +18 -14
  4. package/src/constants/billing.ts +92 -92
  5. package/src/constants/emoji.ts +9144 -8936
  6. package/src/constants/other.ts +1 -5
  7. package/src/constants/user.ts +16 -25
  8. package/src/constants/wsActions.ts +35 -0
  9. package/src/i18n/account.ts +129 -107
  10. package/src/i18n/agent.ts +63 -43
  11. package/src/i18n/agentDoc.ts +110 -0
  12. package/src/i18n/app.ts +101 -91
  13. package/src/i18n/auth.ts +119 -102
  14. package/src/i18n/billing.ts +73 -78
  15. package/src/i18n/campaign.ts +217 -0
  16. package/src/i18n/country.ts +248 -248
  17. package/src/i18n/datetime.ts +26 -26
  18. package/src/i18n/error.ts +428 -182
  19. package/src/i18n/field_docs.ts +28 -0
  20. package/src/i18n/form.ts +464 -344
  21. package/src/i18n/index.ts +25 -18
  22. package/src/i18n/log.ts +53 -213
  23. package/src/i18n/memory.ts +39 -0
  24. package/src/i18n/message.ts +3 -4
  25. package/src/i18n/note.ts +17 -0
  26. package/src/i18n/org.ts +115 -109
  27. package/src/i18n/sheet.ts +376 -4
  28. package/src/i18n/workflow.ts +70 -23
  29. package/src/main.ts +66 -62
  30. package/src/platform.ts +25 -24
  31. package/src/types/ai.d.ts +33 -23
  32. package/src/types/app.d.ts +95 -37
  33. package/src/types/auth.d.ts +66 -40
  34. package/src/types/console.d.ts +3 -0
  35. package/src/types/form.d.ts +65 -61
  36. package/src/types/other.d.ts +6 -6
  37. package/src/types.d.ts +12 -14
  38. package/src/utils/account.ts +64 -58
  39. package/src/utils/api.ts +280 -77
  40. package/src/utils/authSession.ts +24 -0
  41. package/src/utils/billing.ts +110 -103
  42. package/src/utils/color.ts +202 -0
  43. package/src/utils/cron.ts +49 -18
  44. package/src/utils/datetime.ts +255 -103
  45. package/src/utils/emoji.ts +107 -84
  46. package/src/utils/expression.ts +867 -0
  47. package/src/utils/interval.ts +80 -0
  48. package/src/utils/logic.ts +209 -36
  49. package/src/utils/managedSession.ts +34 -0
  50. package/src/utils/managedSessionBff.test.ts +60 -0
  51. package/src/utils/managedSessionBff.ts +117 -0
  52. package/src/utils/number.ts +60 -32
  53. package/src/utils/object.ts +198 -30
  54. package/src/utils/promise.ts +27 -0
  55. package/src/utils/queryReset.ts +179 -0
  56. package/src/utils/recurringTask.ts +60 -0
  57. package/src/utils/schema.ts +293 -0
  58. package/src/utils/string.test.ts +220 -208
  59. package/src/utils/string.ts +471 -438
  60. package/src/utils/timeZone.ts +309 -851
  61. package/src/utils/url_client.ts +73 -69
  62. package/tsconfig.json +10 -10
  63. package/src/i18n/product.ts +0 -76
@@ -0,0 +1,80 @@
1
+ export type IntervalStabIndex<T> = {
2
+ /* Items sorted by ascending interval start */
3
+ items: T[];
4
+ /* Interval starts, parallel to items */
5
+ starts: number[];
6
+ /* Interval ends, parallel to items */
7
+ ends: number[];
8
+ /* Running prefix maximum of ends, parallel to items */
9
+ prefixMaxEnds: number[];
10
+ };
11
+
12
+ /*
13
+ * Build a stabbing-query index over closed integer intervals: items sorted
14
+ * by start with a running prefix max of end, so queryIntervalStabIndex can
15
+ * binary-search the last candidate and walk left, stopping as soon as the
16
+ * prefix max falls below the probe.
17
+ */
18
+ export function buildIntervalStabIndex<T>(
19
+ items: T[],
20
+ getStart: (item: T) => number,
21
+ getEnd: (item: T) => number,
22
+ ): IntervalStabIndex<T> {
23
+ const sortedItems = [...items].sort((a, b) => getStart(a) - getStart(b));
24
+ const starts: number[] = [];
25
+ const ends: number[] = [];
26
+ const prefixMaxEnds: number[] = [];
27
+
28
+ sortedItems.forEach((item, index) => {
29
+ const end = getEnd(item);
30
+ starts.push(getStart(item));
31
+ ends.push(end);
32
+ prefixMaxEnds.push(
33
+ index === 0 ? end : Math.max(prefixMaxEnds[index - 1], end),
34
+ );
35
+ });
36
+
37
+ return {
38
+ items: sortedItems,
39
+ starts,
40
+ ends,
41
+ prefixMaxEnds,
42
+ };
43
+ }
44
+
45
+ /*
46
+ * Return every indexed interval containing one point (closed bounds). Binary
47
+ * search finds the last interval whose start <= point; the leftward walk
48
+ * stops once the prefix max of ends drops below the point, so no interval
49
+ * left of that position can contain it.
50
+ */
51
+ export function queryIntervalStabIndex<T>(
52
+ index: IntervalStabIndex<T>,
53
+ point: number,
54
+ ): T[] {
55
+ // Binary search: last position with start <= point
56
+ let low = 0;
57
+ let high = index.starts.length - 1;
58
+ let last = -1;
59
+ while (low <= high) {
60
+ const mid = (low + high) >> 1;
61
+ if (index.starts[mid] <= point) {
62
+ last = mid;
63
+ low = mid + 1;
64
+ } else {
65
+ high = mid - 1;
66
+ }
67
+ }
68
+
69
+ const results: T[] = [];
70
+ for (let position = last; position >= 0; position--) {
71
+ if (index.prefixMaxEnds[position] < point) {
72
+ break;
73
+ }
74
+ if (index.ends[position] >= point) {
75
+ results.push(index.items[position]);
76
+ }
77
+ }
78
+
79
+ return results;
80
+ }
@@ -13,11 +13,16 @@ type DatabaseActionResult = {
13
13
  documentData: any;
14
14
  };
15
15
 
16
+ const COMPACT_CACHE_KEY_SEGMENT_BYTE_LIMIT = 1800;
17
+ const UTF8_ENCODER = new TextEncoder();
18
+
16
19
  export interface GetFiltersFromURLResult {
17
20
  filter: Omit<Partial<FilterLogEntriesArgs>, 'operation'> | null;
18
21
  sort: string | null;
19
22
  }
20
23
 
24
+ export type FilterOptionURLMode = 'INDEXED' | 'KEYS';
25
+
21
26
  /**
22
27
  * Check if database document needs an update, insert, or do nothing based on the user API arguments
23
28
  * NOTE: There is a copy paste of this function in @jsb188/react/utils/hooks.ts
@@ -40,7 +45,10 @@ export function getDatabaseAction(
40
45
 
41
46
  let hasChanges = false;
42
47
  for (const key in data) {
43
- if (Object.prototype.hasOwnProperty.call(data, key) && data[key] !== undefined) {
48
+ if (
49
+ Object.prototype.hasOwnProperty.call(data, key) &&
50
+ data[key] !== undefined
51
+ ) {
44
52
  // trim() on all string databse fields should be OK;
45
53
  // But if not, add an extra param.
46
54
  let value = typeof data[key] === 'string' ? data[key].trim() : data[key];
@@ -74,7 +82,10 @@ export function getDatabaseAction(
74
82
 
75
83
  if (mergeCurrentData) {
76
84
  for (const key in currentData) {
77
- if (Object.prototype.hasOwnProperty.call(currentData, key) && documentData[key] === undefined) {
85
+ if (
86
+ Object.prototype.hasOwnProperty.call(currentData, key) &&
87
+ documentData[key] === undefined
88
+ ) {
78
89
  documentData[key] = currentData[key];
79
90
  }
80
91
  }
@@ -99,7 +110,7 @@ export function checkLastSetTime(time?: number, minsThreshold: number = 5) {
99
110
 
100
111
  const now = Date.now();
101
112
  const diff = now - time;
102
- return diff > (minsThreshold * 60 * 1000);
113
+ return diff > minsThreshold * 60 * 1000;
103
114
  }
104
115
 
105
116
  /**
@@ -110,30 +121,123 @@ export function delay(ms: number) {
110
121
  return new Promise((resolve) => setTimeout(resolve, ms));
111
122
  }
112
123
 
124
+ /**
125
+ * Create a leading + trailing edge throttled wrapper for one function. Calls
126
+ * during the wait window collapse into one trailing invocation with the
127
+ * latest arguments; cancel() drops any pending trailing call.
128
+ */
129
+
130
+ export function createThrottledInvoke<T extends any[]>(
131
+ fn: (...args: T) => void,
132
+ waitMs: number,
133
+ ): { invoke: (...args: T) => void; cancel: () => void } {
134
+ let lastInvokeAt = 0;
135
+ let pendingArgs: T | null = null;
136
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
137
+
138
+ // Run immediately and stamp the throttle window
139
+ const invokeNow = (args: T) => {
140
+ lastInvokeAt = Date.now();
141
+ fn(...args);
142
+ };
143
+
144
+ const invoke = (...args: T) => {
145
+ const remaining = waitMs - (Date.now() - lastInvokeAt);
146
+
147
+ if (remaining <= 0 && !timeoutId) {
148
+ invokeNow(args);
149
+ return;
150
+ }
151
+
152
+ pendingArgs = args;
153
+ if (!timeoutId) {
154
+ timeoutId = setTimeout(
155
+ () => {
156
+ timeoutId = null;
157
+ if (pendingArgs) {
158
+ const pending = pendingArgs;
159
+ pendingArgs = null;
160
+ invokeNow(pending);
161
+ }
162
+ },
163
+ Math.max(remaining, 0),
164
+ );
165
+ }
166
+ };
167
+
168
+ const cancel = () => {
169
+ if (timeoutId) {
170
+ clearTimeout(timeoutId);
171
+ timeoutId = null;
172
+ }
173
+ pendingArgs = null;
174
+ };
175
+
176
+ return { invoke, cancel };
177
+ }
178
+
113
179
  /**
114
180
  * Convert an indexed bit-string into a list of selected values.
115
181
  */
116
182
 
117
- function getIndexedValues(
118
- value: string | null,
119
- options?: string[],
120
- ) {
183
+ function getIndexedValues(value: string | null, options?: string[]) {
184
+ if (!value || !options?.length) {
185
+ return null;
186
+ }
187
+
188
+ const selectedValues = options
189
+ .map((option, i) => {
190
+ return value.charAt(i) === '1' ? option : null;
191
+ })
192
+ .filter(Boolean) as string[];
193
+
194
+ return selectedValues.length ? selectedValues : null;
195
+ }
196
+
197
+ /**
198
+ * Convert a comma-separated filter value into validated stable option keys.
199
+ */
200
+
201
+ function getKeyValues(value: string | null, options?: string[]) {
121
202
  if (!value || !options?.length) {
122
203
  return null;
123
204
  }
124
205
 
125
- const selectedValues = options.map((option, i) => {
126
- return value.charAt(i) === '1' ? option : null;
127
- }).filter(Boolean) as string[];
206
+ const optionSet = new Set(options);
207
+ const selectedValues = Array.from(
208
+ new Set(
209
+ value
210
+ .split(',')
211
+ .map((option) => option.trim())
212
+ .filter((option) => optionSet.has(option)),
213
+ ),
214
+ ).sort();
128
215
 
129
216
  return selectedValues.length ? selectedValues : null;
130
217
  }
131
218
 
219
+ /**
220
+ * Parse one filter search-param using either the legacy indexed encoding or
221
+ * stable literal registry keys.
222
+ */
223
+
224
+ function getFilterOptionValues(
225
+ value: string | null,
226
+ options?: string[],
227
+ optionURLMode: FilterOptionURLMode = 'INDEXED',
228
+ ) {
229
+ return optionURLMode === 'KEYS'
230
+ ? getKeyValues(value, options)
231
+ : getIndexedValues(value, options);
232
+ }
233
+
132
234
  /**
133
235
  * Check whether a URL search-param value is a serialized generic ID.
134
236
  */
135
237
 
136
- export function isValidGenericIdSearchParam(value?: string | number | bigint | null) {
238
+ export function isValidGenericIdSearchParam(
239
+ value?: string | number | bigint | null,
240
+ ) {
137
241
  if (!value) {
138
242
  return true;
139
243
  }
@@ -146,7 +250,9 @@ export function isValidGenericIdSearchParam(value?: string | number | bigint | n
146
250
  * Validate parsed URL filters using the same date and timezone rules as the logs filter schema.
147
251
  */
148
252
 
149
- function parsedFilterIsValid(filter: Omit<Partial<FilterLogEntriesArgs>, 'operation'>) {
253
+ function parsedFilterIsValid(
254
+ filter: Omit<Partial<FilterLogEntriesArgs>, 'operation'>,
255
+ ) {
150
256
  if (!isValidGenericIdSearchParam(filter.siteId)) {
151
257
  return false;
152
258
  }
@@ -169,7 +275,8 @@ function parsedFilterIsValid(filter: Omit<Partial<FilterLogEntriesArgs>, 'operat
169
275
  }
170
276
 
171
277
  /**
172
- * Parse indexed filters and sort values from URL search params without including operation in the output.
278
+ * Parse legacy indexed or registry-key filters and sort values from URL
279
+ * search params without including operation in the output.
173
280
  */
174
281
 
175
282
  export function getFiltersFromURL(
@@ -177,6 +284,7 @@ export function getFiltersFromURL(
177
284
  sortOptions?: string[],
178
285
  types?: string[],
179
286
  activities?: string[],
287
+ optionURLMode: FilterOptionURLMode = 'INDEXED',
180
288
  ): GetFiltersFromURLResult {
181
289
  const urlParams = new URLSearchParams(searchQuery);
182
290
 
@@ -190,8 +298,16 @@ export function getFiltersFromURL(
190
298
 
191
299
  const filter: Omit<Partial<FilterLogEntriesArgs>, 'operation'> = {
192
300
  siteId: urlParams.get('sid') || null,
193
- types: getIndexedValues(urlParams.get('t'), types) as FilterLogEntriesArgs['types'],
194
- activities: getIndexedValues(urlParams.get('a'), activities) as FilterLogEntriesArgs['activities'],
301
+ types: getFilterOptionValues(
302
+ urlParams.get('t'),
303
+ types,
304
+ optionURLMode,
305
+ ) as FilterLogEntriesArgs['types'],
306
+ activities: getFilterOptionValues(
307
+ urlParams.get('a'),
308
+ activities,
309
+ optionURLMode,
310
+ ) as FilterLogEntriesArgs['activities'],
195
311
  startDate,
196
312
  endDate,
197
313
  query: urlParams.get('q') || '',
@@ -232,15 +348,71 @@ export function timeoutPromise<T>(
232
348
  p.then((result: any) => {
233
349
  clearTimeout(timeout);
234
350
  resolve(result);
235
- })
236
- .catch((err: any) => {
237
- clearTimeout(timeout);
238
- reject(err);
239
- });
351
+ }).catch((err: any) => {
352
+ clearTimeout(timeout);
353
+ reject(err);
354
+ });
240
355
  }
241
356
  });
242
357
  }
243
358
 
359
+ /**
360
+ * Return a JSON-safe value with stable object key order for cache keys.
361
+ */
362
+ function getStableVariablesKeyValue(value: any): any {
363
+ if (Array.isArray(value)) {
364
+ return value.map(getStableVariablesKeyValue);
365
+ }
366
+
367
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
368
+ return Object.keys(value)
369
+ .sort()
370
+ .reduce(
371
+ (acc, key) => {
372
+ acc[key] = getStableVariablesKeyValue(value[key]);
373
+ return acc;
374
+ },
375
+ {} as Record<string, any>,
376
+ );
377
+ }
378
+
379
+ return value;
380
+ }
381
+
382
+ /*
383
+ * Return a compact deterministic hash for a cache key segment.
384
+ */
385
+ function hashCacheKeySegment(value: string, seed: number) {
386
+ let hash = 0x811c9dc5 ^ seed;
387
+
388
+ for (let i = 0; i < value.length; i++) {
389
+ hash ^= value.charCodeAt(i);
390
+ hash = Math.imul(hash, 0x01000193);
391
+ }
392
+
393
+ return (hash >>> 0).toString(36);
394
+ }
395
+
396
+ /*
397
+ * Shorten oversized KV/cache key string segments while preserving deterministic identity.
398
+ */
399
+ export function compactCacheKeySegment(
400
+ value: string,
401
+ byteLimit: number = COMPACT_CACHE_KEY_SEGMENT_BYTE_LIMIT,
402
+ ) {
403
+ const byteLength = UTF8_ENCODER.encode(value).byteLength;
404
+ if (byteLength <= byteLimit) {
405
+ return value;
406
+ }
407
+
408
+ return [
409
+ '*hash',
410
+ byteLength.toString(36),
411
+ hashCacheKeySegment(value, 0),
412
+ hashCacheKeySegment(value, 0x9e3779b9),
413
+ ].join(':');
414
+ }
415
+
244
416
  /**
245
417
  * Make String based key from variables Object
246
418
  * @param variables - any variables or arguments object
@@ -251,24 +423,25 @@ export function timeoutPromise<T>(
251
423
  export function makeVariablesKey(
252
424
  variables: Record<string, any> | null | undefined,
253
425
  doNotLowerCaseCacheKey?: boolean,
254
- // gqlDefinitions?: any[],
426
+ // gqlDefinitions?: any[],
255
427
  ): string {
256
428
  if (variables) {
257
-
258
- // const gqlOperation = gqlDefinitions?.find((def: any) => def.kind === 'OperationDefinition');
259
- const key = Object.keys(variables).sort().reduce((acc, key) => {
260
- // I *could* loop and make sure the variables match those defined in the GQL operation,
261
- // But instead of wasting compute, I rather make sure the variables are passed in identical manner from the app.
262
- // if (gqlOperation) {
263
- // console.log(key);
264
- // ..
265
- // }
266
- const value = variables[key];
267
- if (value || value === 0 || value === false) {
268
- return `${acc}$${key}:${typeof value === 'object' ? stringifyJSON(value) : value}`;
269
- }
270
- return acc;
271
- }, '');
429
+ // const gqlOperation = gqlDefinitions?.find((def: any) => def.kind === 'OperationDefinition');
430
+ const key = Object.keys(variables)
431
+ .sort()
432
+ .reduce((acc, key) => {
433
+ // I *could* loop and make sure the variables match those defined in the GQL operation,
434
+ // But instead of wasting compute, I rather make sure the variables are passed in identical manner from the app.
435
+ // if (gqlOperation) {
436
+ // console.log(key);
437
+ // ..
438
+ // }
439
+ const value = variables[key];
440
+ if (value || value === 0 || value === false) {
441
+ return `${acc}$${key}:${typeof value === 'object' ? stringifyJSON(getStableVariablesKeyValue(value)) : value}`;
442
+ }
443
+ return acc;
444
+ }, '');
272
445
 
273
446
  if (!doNotLowerCaseCacheKey) {
274
447
  return key.toLowerCase();
@@ -0,0 +1,34 @@
1
+ const FILE_CONSTANTS = {
2
+ refreshAttemptDomain: 'marketday:managed-session-refresh:',
3
+ };
4
+
5
+ /*
6
+ * Derive one UUID-shaped refresh attempt identifier from an access token so
7
+ * browser, SSR, concurrent-tab, and retry paths recover the same rotation.
8
+ */
9
+ export async function getManagedSessionRefreshAttemptId(
10
+ accessToken: string,
11
+ ): Promise<string> {
12
+ const digest = new Uint8Array(
13
+ await globalThis.crypto.subtle.digest(
14
+ 'SHA-256',
15
+ new TextEncoder().encode(
16
+ `${FILE_CONSTANTS.refreshAttemptDomain}${accessToken}`,
17
+ ),
18
+ ),
19
+ );
20
+ const uuidBytes = digest.slice(0, 16);
21
+ uuidBytes[6] = (uuidBytes[6] & 0x0f) | 0x40;
22
+ uuidBytes[8] = (uuidBytes[8] & 0x3f) | 0x80;
23
+ const hex = Array.from(uuidBytes, (value) =>
24
+ value.toString(16).padStart(2, '0'),
25
+ );
26
+
27
+ return [
28
+ hex.slice(0, 4).join(''),
29
+ hex.slice(4, 6).join(''),
30
+ hex.slice(6, 8).join(''),
31
+ hex.slice(8, 10).join(''),
32
+ hex.slice(10, 16).join(''),
33
+ ].join('-');
34
+ }
@@ -0,0 +1,60 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import {
4
+ createManagedSessionBffProof,
5
+ verifyManagedSessionBffProof,
6
+ } from './managedSessionBff.ts';
7
+
8
+ const TEST_TIMESTAMP = 1_720_000_000_000;
9
+ const TEST_NONCE = '8c7535fc-1b8c-4ac6-b7f5-60b47ec83c3f';
10
+
11
+ describe('managed session BFF proof', () => {
12
+ it('accepts an authentic proof only inside its short validity window', async () => {
13
+ const proof = await createManagedSessionBffProof(
14
+ 'deployment-secret',
15
+ TEST_TIMESTAMP,
16
+ TEST_NONCE,
17
+ );
18
+
19
+ expect(
20
+ await verifyManagedSessionBffProof(
21
+ proof,
22
+ 'deployment-secret',
23
+ TEST_TIMESTAMP + 30_000,
24
+ ),
25
+ ).toBe(true);
26
+ expect(
27
+ await verifyManagedSessionBffProof(
28
+ proof,
29
+ 'deployment-secret',
30
+ TEST_TIMESTAMP + 30_001,
31
+ ),
32
+ ).toBe(false);
33
+ });
34
+
35
+ it('rejects missing, forged, and differently scoped proofs', async () => {
36
+ const proof = await createManagedSessionBffProof(
37
+ 'deployment-secret',
38
+ TEST_TIMESTAMP,
39
+ TEST_NONCE,
40
+ );
41
+
42
+ expect(await verifyManagedSessionBffProof(null, 'deployment-secret')).toBe(
43
+ false,
44
+ );
45
+ expect(
46
+ await verifyManagedSessionBffProof(
47
+ proof,
48
+ 'different-secret',
49
+ TEST_TIMESTAMP,
50
+ ),
51
+ ).toBe(false);
52
+ expect(
53
+ await verifyManagedSessionBffProof(
54
+ `${proof?.slice(0, -1)}${proof?.endsWith('0') ? '1' : '0'}`,
55
+ 'deployment-secret',
56
+ TEST_TIMESTAMP,
57
+ ),
58
+ ).toBe(false);
59
+ });
60
+ });
@@ -0,0 +1,117 @@
1
+ const MANAGED_SESSION_BFF_PROOF = {
2
+ maxAgeMs: 30_000,
3
+ noncePattern:
4
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
5
+ purpose: 'managed-session-bff',
6
+ version: '1',
7
+ };
8
+
9
+ /*
10
+ * Convert bytes into the lowercase hexadecimal representation used by BFF proofs.
11
+ */
12
+ function bytesToHex(bytes: Uint8Array): string {
13
+ return Array.from(bytes)
14
+ .map((byte) => byte.toString(16).padStart(2, '0'))
15
+ .join('');
16
+ }
17
+
18
+ /*
19
+ * Compare equal-length proof signatures without data-dependent early exits.
20
+ */
21
+ function signaturesMatch(left: string, right: string): boolean {
22
+ if (left.length !== right.length) {
23
+ return false;
24
+ }
25
+
26
+ let difference = 0;
27
+ for (let index = 0; index < left.length; index++) {
28
+ difference |= left.charCodeAt(index) ^ right.charCodeAt(index);
29
+ }
30
+ return difference === 0;
31
+ }
32
+
33
+ /*
34
+ * Import the deployment secret under the managed-session BFF domain.
35
+ */
36
+ async function importManagedSessionBffKey(secret: string): Promise<CryptoKey> {
37
+ return await crypto.subtle.importKey(
38
+ 'raw',
39
+ new TextEncoder().encode(`${MANAGED_SESSION_BFF_PROOF.purpose}:${secret}`),
40
+ { name: 'HMAC', hash: 'SHA-256' },
41
+ false,
42
+ ['sign'],
43
+ );
44
+ }
45
+
46
+ /*
47
+ * Sign one proof timestamp and nonce without including credentials or request data.
48
+ */
49
+ async function signManagedSessionBffProof(
50
+ secret: string,
51
+ timestamp: number,
52
+ nonce: string,
53
+ ): Promise<string> {
54
+ const signature = await crypto.subtle.sign(
55
+ 'HMAC',
56
+ await importManagedSessionBffKey(secret),
57
+ new TextEncoder().encode(
58
+ `${MANAGED_SESSION_BFF_PROOF.version}:${timestamp}:${nonce}`,
59
+ ),
60
+ );
61
+ return bytesToHex(new Uint8Array(signature));
62
+ }
63
+
64
+ /*
65
+ * Create a short-lived proof that authorizes direct credential delivery to the BFF.
66
+ */
67
+ export async function createManagedSessionBffProof(
68
+ secret: string,
69
+ now: number = Date.now(),
70
+ nonce: string = crypto.randomUUID(),
71
+ ): Promise<string | null> {
72
+ if (
73
+ !secret ||
74
+ !Number.isSafeInteger(now) ||
75
+ now <= 0 ||
76
+ !MANAGED_SESSION_BFF_PROOF.noncePattern.test(nonce)
77
+ ) {
78
+ return null;
79
+ }
80
+
81
+ const signature = await signManagedSessionBffProof(secret, now, nonce);
82
+ return `${MANAGED_SESSION_BFF_PROOF.version}.${now}.${nonce}.${signature}`;
83
+ }
84
+
85
+ /*
86
+ * Verify one unexpired BFF proof against the shared deployment secret.
87
+ */
88
+ export async function verifyManagedSessionBffProof(
89
+ proof: string | null | undefined,
90
+ secret: string,
91
+ now: number = Date.now(),
92
+ ): Promise<boolean> {
93
+ if (!proof || !secret || !Number.isSafeInteger(now) || now <= 0) {
94
+ return false;
95
+ }
96
+
97
+ const [version, timestampText, nonce, signature, ...extra] = proof.split('.');
98
+ const timestamp = Number(timestampText);
99
+ if (
100
+ extra.length ||
101
+ version !== MANAGED_SESSION_BFF_PROOF.version ||
102
+ !Number.isSafeInteger(timestamp) ||
103
+ timestamp <= 0 ||
104
+ Math.abs(now - timestamp) > MANAGED_SESSION_BFF_PROOF.maxAgeMs ||
105
+ !MANAGED_SESSION_BFF_PROOF.noncePattern.test(nonce || '') ||
106
+ !/^[0-9a-f]{64}$/.test(signature || '')
107
+ ) {
108
+ return false;
109
+ }
110
+
111
+ const expectedSignature = await signManagedSessionBffProof(
112
+ secret,
113
+ timestamp,
114
+ nonce,
115
+ );
116
+ return signaturesMatch(signature, expectedSignature);
117
+ }