@jsb188/app 1.0.4 → 1.1.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.
- package/package.json +57 -37
- package/src/constants/agent.ts +74 -0
- package/src/constants/app.ts +389 -0
- package/src/constants/emoji.ts +9153 -0
- package/src/constants/other.ts +13 -0
- package/src/constants/user.ts +27 -0
- package/src/constants/wsActions.ts +49 -0
- package/src/i18n/account.ts +139 -0
- package/src/i18n/agent.ts +397 -0
- package/src/i18n/agentToolBusiness.ts +196 -0
- package/src/i18n/agentToolGrid.ts +137 -0
- package/src/i18n/agentToolWorkflow.ts +101 -0
- package/src/i18n/agent_note.ts +109 -0
- package/src/i18n/app.ts +124 -0
- package/src/i18n/auth.ts +128 -0
- package/src/i18n/billing.ts +7 -0
- package/src/i18n/c.ts +907 -0
- package/src/i18n/campaign.ts +919 -0
- package/src/i18n/country.ts +249 -0
- package/src/i18n/datetime.ts +66 -0
- package/src/i18n/editor.ts +58 -0
- package/src/i18n/error.ts +579 -0
- package/src/i18n/field_doc_editor.ts +21 -0
- package/src/i18n/field_doc_programs.ts +52 -0
- package/src/i18n/field_docs.ts +190 -0
- package/src/i18n/index.ts +64 -0
- package/src/i18n/log.ts +566 -0
- package/src/i18n/memory.ts +59 -0
- package/src/i18n/message.ts +13 -0
- package/src/i18n/note.ts +19 -0
- package/src/i18n/org.ts +306 -0
- package/src/i18n/schedule.ts +209 -0
- package/src/i18n/sheet.ts +339 -0
- package/src/i18n/sheet_formula.ts +165 -0
- package/src/i18n/workflow.ts +111 -0
- package/src/main.ts +89 -0
- package/src/platform.ts +166 -0
- package/src/types/ai.d.ts +63 -0
- package/src/types/app.d.ts +127 -0
- package/src/types/auth.d.ts +94 -0
- package/src/types/console.d.ts +3 -0
- package/src/types/node-polyglot.d.ts +23 -0
- package/src/types/other.d.ts +66 -0
- package/src/types.d.ts +29 -0
- package/src/utils/account.ts +97 -0
- package/src/utils/api.ts +358 -0
- package/src/utils/authSession.ts +24 -0
- package/src/utils/clientIP.ts +213 -0
- package/src/utils/color.ts +279 -0
- package/src/utils/cron.ts +310 -0
- package/src/utils/csv.ts +19 -0
- package/src/utils/datetime.ts +1394 -0
- package/src/utils/deferredSave.ts +89 -0
- package/src/utils/email.ts +39 -0
- package/src/utils/emoji.ts +174 -0
- package/src/utils/expression.helpers.ts +470 -0
- package/src/utils/expression.test.ts +793 -0
- package/src/utils/expression.ts +2261 -0
- package/src/utils/interval.ts +80 -0
- package/src/utils/language.ts +9 -0
- package/src/utils/logic.ts +299 -0
- package/src/utils/managedSession.ts +34 -0
- package/src/utils/managedSessionBff.test.ts +60 -0
- package/src/utils/managedSessionBff.ts +117 -0
- package/src/utils/number.ts +338 -0
- package/src/utils/object.ts +916 -0
- package/src/utils/promise.ts +98 -0
- package/src/utils/queryReset.ts +266 -0
- package/src/utils/recurringTask.ts +60 -0
- package/src/utils/schema.ts +293 -0
- package/src/utils/string.test.ts +278 -0
- package/src/utils/string.ts +709 -0
- package/src/utils/timeZone.ts +2048 -0
- package/src/utils/url_client.ts +206 -0
- package/tsconfig.json +12 -0
- package/constants/app.ts +0 -47
- package/constants/billing.ts +0 -146
- package/constants/emoji.ts +0 -8945
- package/constants/user.ts +0 -36
- package/constants/ws.ts +0 -47
- package/i18n/app.ts +0 -99
- package/i18n/auth.ts +0 -57
- package/i18n/billing.ts +0 -94
- package/i18n/datetime.ts +0 -22
- package/i18n/error.ts +0 -138
- package/i18n/form.ts +0 -73
- package/i18n/index.ts +0 -6
- package/i18n/user.ts +0 -98
- package/main.ts +0 -62
- package/types/app.d.ts +0 -46
- package/types/datetime.d.ts +0 -10
- package/types/form.d.ts +0 -56
- package/types/user.d.ts +0 -52
- package/types.d.ts +0 -23
- package/utils/api.ts +0 -99
- package/utils/billing.ts +0 -134
- package/utils/datetime.ts +0 -358
- package/utils/emoji.ts +0 -151
- package/utils/logic.ts +0 -115
- package/utils/number.ts +0 -115
- package/utils/object.ts +0 -367
- package/utils/string.ts +0 -211
- package/utils/url_client.ts +0 -138
- package/utils/user.ts +0 -273
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { SUPPORTED_LOG_LANGUAGES, type SupportedLogLanguage } from '../constants/app.ts';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Resolve a supported log language to its canonical locale key without losing script subtags.
|
|
5
|
+
*/
|
|
6
|
+
export function normalizeLogLanguage(value: unknown): SupportedLogLanguage | null {
|
|
7
|
+
const normalized = typeof value === 'string' ? value.trim().toLowerCase() : '';
|
|
8
|
+
return SUPPORTED_LOG_LANGUAGES.find((language) => language.toLowerCase() === normalized) ?? null;
|
|
9
|
+
}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { sortObjectByKeys, stringifyJSON } from './object.ts';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Types
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
type DatabaseAction = 'INSERT' | 'UPDATE' | 'NONE';
|
|
8
|
+
|
|
9
|
+
type DatabaseActionResult = {
|
|
10
|
+
action: DatabaseAction;
|
|
11
|
+
documentData: any;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const COMPACT_CACHE_KEY_SEGMENT_BYTE_LIMIT = 1800;
|
|
15
|
+
const UTF8_ENCODER = new TextEncoder();
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Check if database document needs an update, insert, or do nothing based on the user API arguments
|
|
19
|
+
* NOTE: There is a copy paste of this function in @jsb188/react/utils/hooks.ts
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export function getDatabaseAction(
|
|
23
|
+
currentData: any,
|
|
24
|
+
data: any,
|
|
25
|
+
allowNull?: boolean,
|
|
26
|
+
mergeCurrentData?: boolean,
|
|
27
|
+
): DatabaseActionResult {
|
|
28
|
+
if (!currentData) {
|
|
29
|
+
return {
|
|
30
|
+
action: 'INSERT',
|
|
31
|
+
documentData: data,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const documentData: Record<string, any> = {};
|
|
36
|
+
|
|
37
|
+
let hasChanges = false;
|
|
38
|
+
for (const key in data) {
|
|
39
|
+
if (
|
|
40
|
+
Object.prototype.hasOwnProperty.call(data, key) &&
|
|
41
|
+
data[key] !== undefined
|
|
42
|
+
) {
|
|
43
|
+
// trim() on all string databse fields should be OK;
|
|
44
|
+
// But if not, add an extra param.
|
|
45
|
+
let value = typeof data[key] === 'string' ? data[key].trim() : data[key];
|
|
46
|
+
if (value instanceof Date) {
|
|
47
|
+
value = value.toISOString();
|
|
48
|
+
} else if (value && typeof value === 'object') {
|
|
49
|
+
value = stringifyJSON(sortObjectByKeys(value));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const isNullValue = value !== null || allowNull;
|
|
53
|
+
if (isNullValue) {
|
|
54
|
+
documentData[key] = value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let currentValue = currentData[key];
|
|
58
|
+
if (currentValue instanceof Date) {
|
|
59
|
+
currentValue = currentValue.toISOString();
|
|
60
|
+
} else if (currentValue && typeof currentValue === 'object') {
|
|
61
|
+
currentValue = stringifyJSON(sortObjectByKeys(currentValue));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (
|
|
65
|
+
// Doing loose != check instead of !== type check
|
|
66
|
+
currentValue != value &&
|
|
67
|
+
isNullValue
|
|
68
|
+
) {
|
|
69
|
+
hasChanges = true;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (mergeCurrentData) {
|
|
75
|
+
for (const key in currentData) {
|
|
76
|
+
if (
|
|
77
|
+
Object.prototype.hasOwnProperty.call(currentData, key) &&
|
|
78
|
+
documentData[key] === undefined
|
|
79
|
+
) {
|
|
80
|
+
documentData[key] = currentData[key];
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const action = hasChanges ? 'UPDATE' : 'NONE';
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
action,
|
|
89
|
+
documentData,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Check if enough time has passed and whether an action should take place (such as websocket events)
|
|
95
|
+
*/
|
|
96
|
+
|
|
97
|
+
export function checkLastSetTime(time?: number, minsThreshold: number = 5) {
|
|
98
|
+
if (!time) {
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const now = Date.now();
|
|
103
|
+
const diff = now - time;
|
|
104
|
+
return diff > minsThreshold * 60 * 1000;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Promised delay, using setTimeout
|
|
109
|
+
*/
|
|
110
|
+
|
|
111
|
+
export function delay(ms: number) {
|
|
112
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Create a leading + trailing edge throttled wrapper for one function. Calls
|
|
117
|
+
* during the wait window collapse into one trailing invocation with the
|
|
118
|
+
* latest arguments; cancel() drops any pending trailing call.
|
|
119
|
+
*/
|
|
120
|
+
|
|
121
|
+
export function createThrottledInvoke<T extends any[]>(
|
|
122
|
+
fn: (...args: T) => void,
|
|
123
|
+
waitMs: number,
|
|
124
|
+
): { invoke: (...args: T) => void; cancel: () => void } {
|
|
125
|
+
let lastInvokeAt = 0;
|
|
126
|
+
let pendingArgs: T | null = null;
|
|
127
|
+
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
|
128
|
+
|
|
129
|
+
// Run immediately and stamp the throttle window
|
|
130
|
+
const invokeNow = (args: T) => {
|
|
131
|
+
lastInvokeAt = Date.now();
|
|
132
|
+
fn(...args);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const invoke = (...args: T) => {
|
|
136
|
+
const remaining = waitMs - (Date.now() - lastInvokeAt);
|
|
137
|
+
|
|
138
|
+
if (remaining <= 0 && !timeoutId) {
|
|
139
|
+
invokeNow(args);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
pendingArgs = args;
|
|
144
|
+
if (!timeoutId) {
|
|
145
|
+
timeoutId = setTimeout(
|
|
146
|
+
() => {
|
|
147
|
+
timeoutId = null;
|
|
148
|
+
if (pendingArgs) {
|
|
149
|
+
const pending = pendingArgs;
|
|
150
|
+
pendingArgs = null;
|
|
151
|
+
invokeNow(pending);
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
Math.max(remaining, 0),
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
const cancel = () => {
|
|
160
|
+
if (timeoutId) {
|
|
161
|
+
clearTimeout(timeoutId);
|
|
162
|
+
timeoutId = null;
|
|
163
|
+
}
|
|
164
|
+
pendingArgs = null;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
return { invoke, cancel };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Promise with timeout
|
|
172
|
+
*/
|
|
173
|
+
|
|
174
|
+
export function timeoutPromise<T>(
|
|
175
|
+
mainPromise: () => any,
|
|
176
|
+
onTimeout: () => any,
|
|
177
|
+
timeoutMs: number,
|
|
178
|
+
): Promise<T> {
|
|
179
|
+
return new Promise<T>((resolve, reject) => {
|
|
180
|
+
const timeout = setTimeout(() => {
|
|
181
|
+
resolve(onTimeout());
|
|
182
|
+
}, timeoutMs);
|
|
183
|
+
|
|
184
|
+
const p = mainPromise();
|
|
185
|
+
if (typeof p?.then === 'function') {
|
|
186
|
+
p.then((result: any) => {
|
|
187
|
+
clearTimeout(timeout);
|
|
188
|
+
resolve(result);
|
|
189
|
+
}).catch((err: any) => {
|
|
190
|
+
clearTimeout(timeout);
|
|
191
|
+
reject(err);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Return a JSON-safe value with stable object key order for cache keys.
|
|
199
|
+
*/
|
|
200
|
+
function getStableVariablesKeyValue(value: any): any {
|
|
201
|
+
if (Array.isArray(value)) {
|
|
202
|
+
return value.map(getStableVariablesKeyValue);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (value && typeof value === 'object' && !(value instanceof Date)) {
|
|
206
|
+
return Object.keys(value)
|
|
207
|
+
.sort()
|
|
208
|
+
.reduce(
|
|
209
|
+
(acc, key) => {
|
|
210
|
+
acc[key] = getStableVariablesKeyValue(value[key]);
|
|
211
|
+
return acc;
|
|
212
|
+
},
|
|
213
|
+
{} as Record<string, any>,
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return value;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/*
|
|
221
|
+
* Key GraphQL variables exactly as JSON sends them: preserve case, scalar
|
|
222
|
+
* types, null and empty strings, omit undefined, and sort object keys. The
|
|
223
|
+
* prefix distinguishes this format from legacy delimiter-based cache keys.
|
|
224
|
+
*/
|
|
225
|
+
export function makeGraphQLVariablesKey(variables?: Record<string, any> | null): string {
|
|
226
|
+
return '@' + JSON.stringify(getStableVariablesKeyValue(variables || {}));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/*
|
|
230
|
+
* Return a compact deterministic hash for a cache key segment.
|
|
231
|
+
*/
|
|
232
|
+
function hashCacheKeySegment(value: string, seed: number) {
|
|
233
|
+
let hash = 0x811c9dc5 ^ seed;
|
|
234
|
+
|
|
235
|
+
for (let i = 0; i < value.length; i++) {
|
|
236
|
+
hash ^= value.charCodeAt(i);
|
|
237
|
+
hash = Math.imul(hash, 0x01000193);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return (hash >>> 0).toString(36);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/*
|
|
244
|
+
* Shorten oversized KV/cache key string segments while preserving deterministic identity.
|
|
245
|
+
*/
|
|
246
|
+
export function compactCacheKeySegment(
|
|
247
|
+
value: string,
|
|
248
|
+
byteLimit: number = COMPACT_CACHE_KEY_SEGMENT_BYTE_LIMIT,
|
|
249
|
+
) {
|
|
250
|
+
const byteLength = UTF8_ENCODER.encode(value).byteLength;
|
|
251
|
+
if (byteLength <= byteLimit) {
|
|
252
|
+
return value;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return [
|
|
256
|
+
'*hash',
|
|
257
|
+
byteLength.toString(36),
|
|
258
|
+
hashCacheKeySegment(value, 0),
|
|
259
|
+
hashCacheKeySegment(value, 0x9e3779b9),
|
|
260
|
+
].join(':');
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Make String based key from variables Object
|
|
265
|
+
* @param variables - any variables or arguments object
|
|
266
|
+
* @param doNotLowerCaseCacheKey - If true, the returned key will maintain original casing
|
|
267
|
+
* @return string key
|
|
268
|
+
*/
|
|
269
|
+
|
|
270
|
+
export function makeVariablesKey(
|
|
271
|
+
variables: Record<string, any> | null | undefined,
|
|
272
|
+
doNotLowerCaseCacheKey?: boolean,
|
|
273
|
+
// gqlDefinitions?: any[],
|
|
274
|
+
): string {
|
|
275
|
+
if (variables) {
|
|
276
|
+
// const gqlOperation = gqlDefinitions?.find((def: any) => def.kind === 'OperationDefinition');
|
|
277
|
+
const key = Object.keys(variables)
|
|
278
|
+
.sort()
|
|
279
|
+
.reduce((acc, key) => {
|
|
280
|
+
// I *could* loop and make sure the variables match those defined in the GQL operation,
|
|
281
|
+
// But instead of wasting compute, I rather make sure the variables are passed in identical manner from the app.
|
|
282
|
+
// if (gqlOperation) {
|
|
283
|
+
// console.log(key);
|
|
284
|
+
// ..
|
|
285
|
+
// }
|
|
286
|
+
const value = variables[key];
|
|
287
|
+
if (value || value === 0 || value === false) {
|
|
288
|
+
return `${acc}$${key}:${typeof value === 'object' ? stringifyJSON(getStableVariablesKeyValue(value)) : value}`;
|
|
289
|
+
}
|
|
290
|
+
return acc;
|
|
291
|
+
}, '');
|
|
292
|
+
|
|
293
|
+
if (!doNotLowerCaseCacheKey) {
|
|
294
|
+
return key.toLowerCase();
|
|
295
|
+
}
|
|
296
|
+
return key;
|
|
297
|
+
}
|
|
298
|
+
return 'none';
|
|
299
|
+
}
|
|
@@ -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
|
+
}
|