@jsb188/app 1.1.10 → 1.1.12
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 -45
- package/src/constants/agent.ts +51 -41
- package/src/constants/app.ts +34 -13
- package/src/constants/emoji.ts +9144 -8936
- package/src/constants/other.ts +1 -5
- package/src/constants/user.ts +16 -25
- package/src/constants/wsActions.ts +27 -0
- package/src/i18n/account.ts +129 -107
- package/src/i18n/agent.ts +331 -73
- 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 +107 -91
- package/src/i18n/auth.ts +117 -102
- package/src/i18n/billing.ts +5 -92
- package/src/i18n/c.ts +907 -0
- package/src/i18n/campaign.ts +919 -0
- package/src/i18n/country.ts +248 -248
- package/src/i18n/datetime.ts +32 -26
- package/src/i18n/editor.ts +58 -0
- package/src/i18n/error.ts +577 -192
- 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 +42 -19
- package/src/i18n/log.ts +272 -238
- package/src/i18n/memory.ts +53 -0
- package/src/i18n/message.ts +3 -4
- package/src/i18n/note.ts +19 -0
- package/src/i18n/org.ts +164 -109
- package/src/i18n/schedule.ts +209 -0
- package/src/i18n/sheet.ts +333 -4
- package/src/i18n/sheet_formula.ts +165 -0
- package/src/i18n/workflow.ts +109 -23
- package/src/main.ts +68 -64
- package/src/platform.ts +90 -49
- package/src/types/ai.d.ts +52 -23
- package/src/types/app.d.ts +95 -44
- package/src/types/auth.d.ts +66 -40
- package/src/types/console.d.ts +3 -0
- package/src/types/other.d.ts +13 -6
- package/src/types.d.ts +12 -14
- package/src/utils/account.ts +64 -58
- package/src/utils/api.ts +326 -77
- 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 +49 -18
- package/src/utils/csv.ts +19 -0
- package/src/utils/datetime.ts +445 -117
- package/src/utils/deferredSave.ts +89 -0
- package/src/utils/email.ts +50 -0
- package/src/utils/emoji.ts +107 -84
- 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 +141 -121
- 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 +85 -38
- package/src/utils/object.ts +227 -30
- 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 +205 -208
- package/src/utils/string.ts +426 -463
- package/src/utils/timeZone.ts +309 -851
- package/src/utils/url_client.ts +145 -72
- package/tsconfig.json +10 -10
- package/src/constants/billing.ts +0 -146
- package/src/i18n/form.ts +0 -376
- package/src/i18n/product.ts +0 -76
- package/src/types/form.d.ts +0 -97
- package/src/utils/billing.ts +0 -134
package/src/utils/api.ts
CHANGED
|
@@ -4,15 +4,259 @@ import type { ServerErrorObj } from '../types/app.d.ts';
|
|
|
4
4
|
|
|
5
5
|
let AUTH_TOKEN: string | null = null;
|
|
6
6
|
|
|
7
|
+
export type ManagedAccessTokenBinding = {
|
|
8
|
+
accountId: string;
|
|
9
|
+
sessionId: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export type RealtimeCapabilityResource = 'DATA_TABLE' | 'SHEET';
|
|
13
|
+
|
|
14
|
+
export type RealtimeCapabilityBinding = ManagedAccessTokenBinding & {
|
|
15
|
+
resource: RealtimeCapabilityResource;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Decode an unverified JWT payload for client-side scheduling and request
|
|
20
|
+
* coordination only.
|
|
21
|
+
*/
|
|
22
|
+
function getUnverifiedJWTPayload(token: string): Record<string, any> | null {
|
|
23
|
+
try {
|
|
24
|
+
const rawToken = token.startsWith('Bearer ')
|
|
25
|
+
? token.slice('Bearer '.length)
|
|
26
|
+
: token;
|
|
27
|
+
const encodedPayload = rawToken.split('.')[1];
|
|
28
|
+
if (!encodedPayload) {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const normalizedPayload = encodedPayload
|
|
33
|
+
.replace(/-/g, '+')
|
|
34
|
+
.replace(/_/g, '/')
|
|
35
|
+
.padEnd(Math.ceil(encodedPayload.length / 4) * 4, '=');
|
|
36
|
+
const payload = JSON.parse(atob(normalizedPayload));
|
|
37
|
+
return payload && typeof payload === 'object' ? payload : null;
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Read one JWT expiration as an unverified millisecond scheduling hint. This
|
|
45
|
+
* must never be used as authorization; the receiving server still verifies
|
|
46
|
+
* the signature, resource, principal, and exact expiry.
|
|
47
|
+
*/
|
|
48
|
+
export function getUnverifiedJWTExpirationMs(token: string): number | null {
|
|
49
|
+
const expirationSeconds = getUnverifiedJWTPayload(token)?.exp;
|
|
50
|
+
if (
|
|
51
|
+
typeof expirationSeconds !== 'number' ||
|
|
52
|
+
!Number.isSafeInteger(expirationSeconds) ||
|
|
53
|
+
expirationSeconds <= 0
|
|
54
|
+
) {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const expirationMs = expirationSeconds * 1_000;
|
|
59
|
+
return Number.isSafeInteger(expirationMs) ? expirationMs : null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Read one JWT issued-at as an unverified millisecond scheduling hint. Paired
|
|
64
|
+
* with the expiry claim it yields the token's server-clock lifetime, which
|
|
65
|
+
* stays correct on clients whose local clock is skewed.
|
|
66
|
+
*/
|
|
67
|
+
export function getUnverifiedJWTIssuedAtMs(token: string): number | null {
|
|
68
|
+
const issuedAtSeconds = getUnverifiedJWTPayload(token)?.iat;
|
|
69
|
+
if (
|
|
70
|
+
typeof issuedAtSeconds !== 'number' ||
|
|
71
|
+
!Number.isSafeInteger(issuedAtSeconds) ||
|
|
72
|
+
issuedAtSeconds <= 0
|
|
73
|
+
) {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const issuedAtMs = issuedAtSeconds * 1_000;
|
|
78
|
+
return Number.isSafeInteger(issuedAtMs) ? issuedAtMs : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Normalize one positive integer JWT hint to a bounded decimal string.
|
|
83
|
+
*/
|
|
84
|
+
function normalizeAccessTokenIntegerHint(value: unknown): string | null {
|
|
85
|
+
if (typeof value !== 'string' && typeof value !== 'number') {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
if (typeof value === 'number' && !Number.isSafeInteger(value)) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const normalizedValue = String(value).trim();
|
|
93
|
+
return normalizedValue.length <= 19 && /^[1-9][0-9]*$/.test(normalizedValue)
|
|
94
|
+
? normalizedValue
|
|
95
|
+
: null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Read an account hint from an access JWT for client-side coordination only.
|
|
100
|
+
*/
|
|
101
|
+
export function getAccessTokenAccountIdHint(token: string): string | null {
|
|
102
|
+
const payload = getUnverifiedJWTPayload(token);
|
|
103
|
+
return normalizeAccessTokenIntegerHint(payload?.accountId);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Read the account/session hint from a managed access JWT without treating it
|
|
108
|
+
* as authentication; the server still verifies every credential.
|
|
109
|
+
*/
|
|
110
|
+
export function getManagedAccessTokenBinding(
|
|
111
|
+
token: string,
|
|
112
|
+
): ManagedAccessTokenBinding | null {
|
|
113
|
+
const payload = getUnverifiedJWTPayload(token);
|
|
114
|
+
if (
|
|
115
|
+
payload?.__name !== 'type:AccountAuth' ||
|
|
116
|
+
Number(payload?.sessionVersion || 0) !== 1
|
|
117
|
+
) {
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
const accountId = normalizeAccessTokenIntegerHint(payload?.accountId);
|
|
121
|
+
const canonicalSessionId = normalizeAccessTokenIntegerHint(
|
|
122
|
+
payload?.sessionId,
|
|
123
|
+
);
|
|
124
|
+
const aliasSessionId = normalizeAccessTokenIntegerHint(payload?.sid);
|
|
125
|
+
if (
|
|
126
|
+
canonicalSessionId &&
|
|
127
|
+
aliasSessionId &&
|
|
128
|
+
canonicalSessionId !== aliasSessionId
|
|
129
|
+
) {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
const sessionId = canonicalSessionId || aliasSessionId;
|
|
133
|
+
if (!accountId || !sessionId) {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
accountId,
|
|
139
|
+
sessionId,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Check whether two access JWTs identify the same managed account session.
|
|
145
|
+
*/
|
|
146
|
+
export function managedAccessTokensShareBinding(
|
|
147
|
+
left: string,
|
|
148
|
+
right: string,
|
|
149
|
+
): boolean {
|
|
150
|
+
const leftBinding = getManagedAccessTokenBinding(left);
|
|
151
|
+
const rightBinding = getManagedAccessTokenBinding(right);
|
|
152
|
+
return Boolean(
|
|
153
|
+
leftBinding &&
|
|
154
|
+
rightBinding &&
|
|
155
|
+
leftBinding.accountId === rightBinding.accountId &&
|
|
156
|
+
leftBinding.sessionId === rightBinding.sessionId,
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Read the stable managed-session owner from a signed realtime capability as
|
|
162
|
+
* an unverified client-side lifecycle hint. The websocket server remains the
|
|
163
|
+
* only authority for the capability itself.
|
|
164
|
+
*/
|
|
165
|
+
export function getRealtimeCapabilityBinding(
|
|
166
|
+
token: string,
|
|
167
|
+
expectedResource: RealtimeCapabilityResource,
|
|
168
|
+
): RealtimeCapabilityBinding | null {
|
|
169
|
+
const payload = getUnverifiedJWTPayload(token);
|
|
170
|
+
if (
|
|
171
|
+
payload?.__name !== 'type:RealtimeCapability' ||
|
|
172
|
+
Number(payload?.realtimeCapabilityVersion || 0) !== 2 ||
|
|
173
|
+
payload?.resource !== expectedResource
|
|
174
|
+
) {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const accountId = normalizeAccessTokenIntegerHint(payload.accountId);
|
|
179
|
+
const sessionId = normalizeAccessTokenIntegerHint(payload.sessionId);
|
|
180
|
+
if (!accountId || !sessionId) {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
accountId,
|
|
186
|
+
resource: expectedResource,
|
|
187
|
+
sessionId,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Return one exact account/session ownership key for client-retained realtime
|
|
193
|
+
* state. Token renewal within the same managed session intentionally keeps it.
|
|
194
|
+
*/
|
|
195
|
+
export function getRealtimeCapabilityOwnerKey(
|
|
196
|
+
token: string | null | undefined,
|
|
197
|
+
expectedResource: RealtimeCapabilityResource,
|
|
198
|
+
) {
|
|
199
|
+
const binding = token
|
|
200
|
+
? getRealtimeCapabilityBinding(token, expectedResource)
|
|
201
|
+
: null;
|
|
202
|
+
return binding ? JSON.stringify([binding.accountId, binding.sessionId]) : '';
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Return the candidate realtime capability only when it provably renews the
|
|
207
|
+
* current one: same resource instance, organization, and owner, with a strictly
|
|
208
|
+
* later server issue time. Otherwise the current token stays. This only picks
|
|
209
|
+
* which signed token to present; the server still verifies everything.
|
|
210
|
+
*/
|
|
211
|
+
export function getNewerRealtimeCapability(
|
|
212
|
+
current: string | null | undefined,
|
|
213
|
+
candidate: string | null | undefined,
|
|
214
|
+
expectedResource: RealtimeCapabilityResource,
|
|
215
|
+
): string | null {
|
|
216
|
+
const currentToken = current || null;
|
|
217
|
+
if (!currentToken || !candidate || candidate === currentToken) {
|
|
218
|
+
return currentToken;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const resourceIdKey = {
|
|
222
|
+
DATA_TABLE: 'dataTableId',
|
|
223
|
+
SHEET: 'sheetId',
|
|
224
|
+
}[expectedResource];
|
|
225
|
+
const [currentPayload, candidatePayload] = [currentToken, candidate].map(
|
|
226
|
+
(token) => {
|
|
227
|
+
const payload = getUnverifiedJWTPayload(token);
|
|
228
|
+
return payload?.__name === 'type:RealtimeCapability' &&
|
|
229
|
+
Number(payload.realtimeCapabilityVersion || 0) === 2 &&
|
|
230
|
+
payload.resource === expectedResource &&
|
|
231
|
+
Number.isSafeInteger(payload.issuedAtMs)
|
|
232
|
+
? payload
|
|
233
|
+
: null;
|
|
234
|
+
},
|
|
235
|
+
);
|
|
236
|
+
const sameIdentity = Boolean(
|
|
237
|
+
currentPayload &&
|
|
238
|
+
candidatePayload &&
|
|
239
|
+
['organizationId', resourceIdKey, 'accountId', 'sessionId'].every(
|
|
240
|
+
(key) =>
|
|
241
|
+
String(currentPayload[key] ?? '') ===
|
|
242
|
+
String(candidatePayload[key] ?? ''),
|
|
243
|
+
),
|
|
244
|
+
);
|
|
245
|
+
return sameIdentity &&
|
|
246
|
+
candidatePayload!.issuedAtMs > currentPayload!.issuedAtMs
|
|
247
|
+
? candidate
|
|
248
|
+
: currentToken;
|
|
249
|
+
}
|
|
250
|
+
|
|
7
251
|
/**
|
|
8
252
|
* Global; save auth token to memory
|
|
9
253
|
*/
|
|
10
254
|
|
|
11
255
|
export function setAuthToken(token: string | null) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
256
|
+
if (getENVVariable('IS_BROWSER')) {
|
|
257
|
+
// Only set auth token if it's browser; we don't want to share it across users
|
|
258
|
+
AUTH_TOKEN = token || null;
|
|
259
|
+
}
|
|
16
260
|
}
|
|
17
261
|
|
|
18
262
|
/**
|
|
@@ -20,7 +264,7 @@ export function setAuthToken(token: string | null) {
|
|
|
20
264
|
*/
|
|
21
265
|
|
|
22
266
|
export function getAuthToken(): string | null {
|
|
23
|
-
|
|
267
|
+
return getENVVariable('IS_BROWSER') ? AUTH_TOKEN : null;
|
|
24
268
|
}
|
|
25
269
|
|
|
26
270
|
/**
|
|
@@ -28,7 +272,7 @@ export function getAuthToken(): string | null {
|
|
|
28
272
|
*/
|
|
29
273
|
|
|
30
274
|
function i18nErrCodeExists(errorCode: string): boolean {
|
|
31
|
-
|
|
275
|
+
return i18n.has(`error.${errorCode}`) || i18n.has(`error.${errorCode}_other`);
|
|
32
276
|
}
|
|
33
277
|
|
|
34
278
|
/**
|
|
@@ -36,74 +280,79 @@ function i18nErrCodeExists(errorCode: string): boolean {
|
|
|
36
280
|
*/
|
|
37
281
|
|
|
38
282
|
export function normalizeServerError(error?: any): ServerErrorObj {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
283
|
+
let statusCode = 500;
|
|
284
|
+
let errorCode: string | undefined;
|
|
285
|
+
let errorValue: string | undefined;
|
|
286
|
+
let iconName: string | undefined;
|
|
287
|
+
let message = '';
|
|
288
|
+
|
|
289
|
+
if (!error || error instanceof Error) {
|
|
290
|
+
if (error?.message === 'Failed to fetch') {
|
|
291
|
+
errorCode = 'network_error';
|
|
292
|
+
iconName = 'wifi-off';
|
|
293
|
+
message = i18n.t('error.network_error');
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (!errorCode && error?.errors?.length) {
|
|
298
|
+
const loggedError = error.errors.find(
|
|
299
|
+
(gErr: ServerErrorObj) =>
|
|
300
|
+
gErr.errorCode && i18nErrCodeExists(gErr.errorCode),
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
if (loggedError) {
|
|
304
|
+
statusCode = loggedError.statusCode;
|
|
305
|
+
errorCode = loggedError.errorCode;
|
|
306
|
+
errorValue = loggedError.variableWord;
|
|
307
|
+
} else {
|
|
308
|
+
statusCode = error.errors[0].statusCode;
|
|
309
|
+
errorCode = error.errors[0].errorCode;
|
|
310
|
+
errorValue = error.errors[0].variableWord;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Keep the returned error contract total even for malformed server payloads.
|
|
315
|
+
errorCode ||= 'unknown_error';
|
|
316
|
+
if (!message) {
|
|
317
|
+
if (i18nErrCodeExists(errorCode)) {
|
|
318
|
+
message = i18n.t(`error.${errorCode}`, {
|
|
319
|
+
value: errorValue,
|
|
320
|
+
smart_count: Number(errorValue),
|
|
321
|
+
});
|
|
322
|
+
} else {
|
|
323
|
+
message = i18n.t('error.unknown_error_msg');
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (
|
|
328
|
+
getENVVariable('NODE_ENV') === 'development' &&
|
|
329
|
+
message === i18n.t('error.unknown_error_msg')
|
|
330
|
+
) {
|
|
331
|
+
// Log for development so I can see what went wrong
|
|
332
|
+
console.warn(error);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
let title: string;
|
|
336
|
+
if (i18n.has(`error.${errorCode}_title`)) {
|
|
337
|
+
title = i18n.t(`error.${errorCode}_title`);
|
|
338
|
+
} else if (i18n.has(`error.${statusCode}_title`)) {
|
|
339
|
+
title = i18n.t(`error.${statusCode}_title`);
|
|
340
|
+
} else {
|
|
341
|
+
title = i18n.t('error.error');
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (i18n.has(`error.${errorCode}_icon`)) {
|
|
345
|
+
iconName = i18n.t(`error.${errorCode}_icon`);
|
|
346
|
+
} else if (statusCode == 404) {
|
|
347
|
+
iconName = 'folder-question';
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
return {
|
|
351
|
+
statusCode,
|
|
352
|
+
errorCode,
|
|
353
|
+
errorValue,
|
|
354
|
+
iconName,
|
|
355
|
+
title,
|
|
356
|
+
message,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const FILE_CONSTANTS = {
|
|
2
|
+
browserLockName: 'marketday:auth-session',
|
|
3
|
+
};
|
|
4
|
+
|
|
5
|
+
/*
|
|
6
|
+
* Serialize participating authentication-cookie writers across same-origin
|
|
7
|
+
* tabs while retaining a compatibility fallback without the Web Locks API.
|
|
8
|
+
*/
|
|
9
|
+
export async function runWithAuthSessionBrowserLock<T>(
|
|
10
|
+
callback: () => Promise<T>,
|
|
11
|
+
): Promise<T> {
|
|
12
|
+
const lockManager = globalThis.navigator?.locks;
|
|
13
|
+
if (!lockManager) {
|
|
14
|
+
return callback();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
return lockManager.request(
|
|
18
|
+
FILE_CONSTANTS.browserLockName,
|
|
19
|
+
{ mode: 'exclusive' },
|
|
20
|
+
callback,
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export { getManagedSessionRefreshAttemptId } from './managedSession.ts';
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The visitor's IP address behind our proxies, and the proof the app server
|
|
3
|
+
* sends with the visitor IP it forwards to the API.
|
|
4
|
+
*
|
|
5
|
+
* Production traffic reaches the servers through a Google Cloud external
|
|
6
|
+
* Application Load Balancer, then nginx on each instance. The load balancer
|
|
7
|
+
* appends two addresses to `X-Forwarded-For`: the client it accepted the
|
|
8
|
+
* connection from, then its own; nginx may append the Google front end it
|
|
9
|
+
* heard from. Everything left of the client's entry is whatever the client
|
|
10
|
+
* sent, so only the entries our own proxies appended can be trusted.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const CLIENT_IP = {
|
|
14
|
+
/** Addresses of our own hops: Google front ends (the load balancer's proxies), private networks and loopback. */
|
|
15
|
+
proxyRanges: [
|
|
16
|
+
['35.191.0.0', 16],
|
|
17
|
+
['130.211.0.0', 22],
|
|
18
|
+
['10.0.0.0', 8],
|
|
19
|
+
['172.16.0.0', 12],
|
|
20
|
+
['192.168.0.0', 16],
|
|
21
|
+
['169.254.0.0', 16],
|
|
22
|
+
['127.0.0.0', 8],
|
|
23
|
+
] as const,
|
|
24
|
+
proof: {
|
|
25
|
+
version: '1',
|
|
26
|
+
purpose: 'ssr-client-ip',
|
|
27
|
+
// App server and API clocks are both NTP-synced; this only has to cover the request's flight
|
|
28
|
+
maxAgeMs: 30_000,
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/*
|
|
33
|
+
* An IPv4 address as a 32-bit number, or null when the text is not one.
|
|
34
|
+
*/
|
|
35
|
+
function parseIPv4(value: string): number | null {
|
|
36
|
+
const parts = value.split('.');
|
|
37
|
+
if (parts.length !== 4) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
let address = 0;
|
|
42
|
+
for (const part of parts) {
|
|
43
|
+
if (!/^\d{1,3}$/.test(part) || Number(part) > 255) {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
address = address * 256 + Number(part);
|
|
47
|
+
}
|
|
48
|
+
return address;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/*
|
|
52
|
+
* Whether the text is an IPv6 address, as the URL parser reads a bracketed host.
|
|
53
|
+
*/
|
|
54
|
+
function isIPv6(value: string): boolean {
|
|
55
|
+
if (!value.includes(':') || !/^[0-9a-f:.]+$/i.test(value)) {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
new URL(`http://[${value}]/`);
|
|
61
|
+
return true;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/*
|
|
68
|
+
* Whether the text is an IPv4 or IPv6 address.
|
|
69
|
+
*/
|
|
70
|
+
export function isIPAddress(value: string): boolean {
|
|
71
|
+
return parseIPv4(value) !== null || isIPv6(value);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/*
|
|
75
|
+
* Whether an address belongs to one of our own hops (a Google front end, a
|
|
76
|
+
* private network, loopback) rather than to a client on the internet.
|
|
77
|
+
*/
|
|
78
|
+
function isProxyAddress(value: string): boolean {
|
|
79
|
+
const lower = value.toLowerCase();
|
|
80
|
+
// IPv4-mapped IPv6 (::ffff:10.0.0.1) is judged by the IPv4 address inside it
|
|
81
|
+
const ipv4 = parseIPv4(lower.startsWith('::ffff:') ? lower.slice(7) : lower);
|
|
82
|
+
if (ipv4 !== null) {
|
|
83
|
+
return CLIENT_IP.proxyRanges.some(([base, bits]) => {
|
|
84
|
+
const size = 2 ** (32 - bits);
|
|
85
|
+
return Math.floor(ipv4 / size) === Math.floor((parseIPv4(base) as number) / size);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Loopback, unique local (fc00::/7) and link-local (fe80::/10) IPv6
|
|
90
|
+
return lower === '::1' || /^f[cd][0-9a-f]{0,2}:/.test(lower) || /^fe[89ab][0-9a-f]?:/.test(lower);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/*
|
|
94
|
+
* The client address our load balancer saw connect, read from the right of an
|
|
95
|
+
* `X-Forwarded-For` chain: past our own trailing hops (nginx's Google front
|
|
96
|
+
* end, private networks), past the load balancer's own address (once, or
|
|
97
|
+
* repeated if a hop copied it), to the address the load balancer appended for
|
|
98
|
+
* the connection. Null when the chain cannot have come through our load
|
|
99
|
+
* balancer (fewer than two addresses, or nothing valid where the client should
|
|
100
|
+
* be), so the caller decides what an unproxied request means.
|
|
101
|
+
*/
|
|
102
|
+
export function getForwardedClientIP(forwardedFor: string | null | undefined): string | null {
|
|
103
|
+
const hops = (forwardedFor || '')
|
|
104
|
+
.split(',')
|
|
105
|
+
.map((hop) => hop.trim())
|
|
106
|
+
.filter(Boolean);
|
|
107
|
+
let index = hops.length - 1;
|
|
108
|
+
|
|
109
|
+
while (index >= 0 && isProxyAddress(hops[index])) {
|
|
110
|
+
index--;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const balancer = hops[index];
|
|
114
|
+
while (index >= 0 && hops[index] === balancer) {
|
|
115
|
+
index--;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const client = hops[index];
|
|
119
|
+
return client && isIPAddress(client) && !isProxyAddress(client) ? client : null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/*
|
|
123
|
+
* Convert bytes into lowercase hexadecimal.
|
|
124
|
+
*/
|
|
125
|
+
function bytesToHex(bytes: Uint8Array): string {
|
|
126
|
+
return Array.from(bytes)
|
|
127
|
+
.map((byte) => byte.toString(16).padStart(2, '0'))
|
|
128
|
+
.join('');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/*
|
|
132
|
+
* Compare two equal-length signatures without data-dependent early exits.
|
|
133
|
+
*/
|
|
134
|
+
function signaturesMatch(left: string, right: string): boolean {
|
|
135
|
+
if (left.length !== right.length) {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
let difference = 0;
|
|
140
|
+
for (let index = 0; index < left.length; index++) {
|
|
141
|
+
difference |= left.charCodeAt(index) ^ right.charCodeAt(index);
|
|
142
|
+
}
|
|
143
|
+
return difference === 0;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/*
|
|
147
|
+
* Sign one forwarded client IP and its timestamp under the SSR client IP key domain.
|
|
148
|
+
*/
|
|
149
|
+
async function signClientIPProof(secret: string, timestamp: number, ipAddress: string): Promise<string> {
|
|
150
|
+
const { purpose, version } = CLIENT_IP.proof;
|
|
151
|
+
const key = await crypto.subtle.importKey(
|
|
152
|
+
'raw',
|
|
153
|
+
new TextEncoder().encode(`${purpose}:${secret}`),
|
|
154
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
155
|
+
false,
|
|
156
|
+
['sign'],
|
|
157
|
+
);
|
|
158
|
+
const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${version}:${timestamp}:${ipAddress}`));
|
|
159
|
+
return bytesToHex(new Uint8Array(signature));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/*
|
|
163
|
+
* Create the short-lived proof the app server sends with the visitor IP it
|
|
164
|
+
* forwards to the API (`x-ssr-ip-proof` beside `x-ssr-ip`), signed with the
|
|
165
|
+
* deployment secret the two share. Null without a secret or a valid address.
|
|
166
|
+
*/
|
|
167
|
+
export async function createClientIPProof(secret: string, ipAddress: string, now: number = Date.now()): Promise<string | null> {
|
|
168
|
+
if (!secret || !isIPAddress(ipAddress) || !Number.isSafeInteger(now) || now <= 0) {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return `${CLIENT_IP.proof.version}.${now}.${await signClientIPProof(secret, now, ipAddress)}`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/*
|
|
176
|
+
* When a client IP proof claims it was signed, or null when it is not shaped
|
|
177
|
+
* like one; read without checking the signature, to diagnose a rejected proof
|
|
178
|
+
* (a stale one points to clock drift, a fresh one to a secret mismatch).
|
|
179
|
+
*/
|
|
180
|
+
export function getClientIPProofTimestamp(proof: string | null | undefined): number | null {
|
|
181
|
+
const timestamp = Number(proof?.split('.')[1]);
|
|
182
|
+
return Number.isSafeInteger(timestamp) && timestamp > 0 ? timestamp : null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/*
|
|
186
|
+
* Verify that a forwarded client IP was signed by the app server within the
|
|
187
|
+
* last `maxAgeMs`, for exactly this address.
|
|
188
|
+
*/
|
|
189
|
+
export async function verifyClientIPProof(
|
|
190
|
+
proof: string | null | undefined,
|
|
191
|
+
ipAddress: string | null | undefined,
|
|
192
|
+
secret: string,
|
|
193
|
+
now: number = Date.now(),
|
|
194
|
+
): Promise<boolean> {
|
|
195
|
+
if (!proof || !ipAddress || !secret || !isIPAddress(ipAddress)) {
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const [version, timestampText, signature, ...extra] = proof.split('.');
|
|
200
|
+
const timestamp = Number(timestampText);
|
|
201
|
+
if (
|
|
202
|
+
extra.length ||
|
|
203
|
+
version !== CLIENT_IP.proof.version ||
|
|
204
|
+
!Number.isSafeInteger(timestamp) ||
|
|
205
|
+
timestamp <= 0 ||
|
|
206
|
+
Math.abs(now - timestamp) > CLIENT_IP.proof.maxAgeMs ||
|
|
207
|
+
!/^[0-9a-f]{64}$/.test(signature || '')
|
|
208
|
+
) {
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return signaturesMatch(signature, await signClientIPProof(secret, timestamp, ipAddress));
|
|
213
|
+
}
|