@oxyhq/core 12.5.2 → 12.6.0
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/dist/cjs/.tsbuildinfo +1 -1
- package/dist/cjs/HttpService.js +4 -1
- package/dist/cjs/OxyServices.errors.js +42 -1
- package/dist/cjs/OxyServices.js +2 -1
- package/dist/cjs/index.js +5 -4
- package/dist/cjs/mixins/OxyServices.assets.js +175 -25
- package/dist/cjs/mixins/OxyServices.user.js +15 -1
- package/dist/cjs/session/SessionClient.js +57 -8
- package/dist/cjs/utils/displayNamePolicyRanges.generated.js +35 -0
- package/dist/cjs/utils/redactUrl.js +29 -0
- package/dist/cjs/utils/textNormalization.js +9 -4
- package/dist/cjs/utils/validationUtils.js +49 -41
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/HttpService.js +4 -1
- package/dist/esm/OxyServices.errors.js +40 -0
- package/dist/esm/OxyServices.js +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/mixins/OxyServices.assets.js +175 -25
- package/dist/esm/mixins/OxyServices.user.js +15 -1
- package/dist/esm/session/SessionClient.js +57 -8
- package/dist/esm/utils/displayNamePolicyRanges.generated.js +32 -0
- package/dist/esm/utils/redactUrl.js +26 -0
- package/dist/esm/utils/textNormalization.js +9 -4
- package/dist/esm/utils/validationUtils.js +50 -42
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/OxyServices.d.ts +2 -2
- package/dist/types/OxyServices.errors.d.ts +40 -0
- package/dist/types/index.d.ts +2 -2
- package/dist/types/mixins/OxyServices.assets.d.ts +103 -13
- package/dist/types/models/interfaces.d.ts +18 -0
- package/dist/types/session/SessionClient.d.ts +19 -2
- package/dist/types/utils/displayNamePolicyRanges.generated.d.ts +32 -0
- package/dist/types/utils/redactUrl.d.ts +17 -0
- package/dist/types/utils/validationUtils.d.ts +48 -34
- package/package.json +5 -3
- package/src/HttpService.ts +4 -1
- package/src/OxyServices.errors.ts +51 -0
- package/src/OxyServices.ts +2 -2
- package/src/index.ts +3 -1
- package/src/mixins/OxyServices.assets.ts +192 -28
- package/src/mixins/OxyServices.user.ts +15 -1
- package/src/mixins/__tests__/followCacheInvalidation.test.ts +5 -0
- package/src/mixins/__tests__/getFileDownloadUrl.test.ts +265 -1
- package/src/mixins/__tests__/userReadCacheBypass.test.ts +8 -0
- package/src/models/interfaces.ts +20 -0
- package/src/session/SessionClient.ts +59 -8
- package/src/session/__tests__/SessionClient.switchTokenOrder.test.ts +170 -0
- package/src/utils/__tests__/redactUrl.test.ts +33 -0
- package/src/utils/__tests__/validationUtils.test.ts +106 -3
- package/src/utils/displayNamePolicyRanges.generated.ts +40 -0
- package/src/utils/redactUrl.ts +28 -0
- package/src/utils/textNormalization.ts +9 -4
- package/src/utils/validationUtils.ts +55 -42
package/src/HttpService.ts
CHANGED
|
@@ -21,6 +21,7 @@ import { jwtDecode } from 'jwt-decode';
|
|
|
21
21
|
import { isNative, getPlatformOS } from './utils/platform';
|
|
22
22
|
import { isReactNative } from '@oxyhq/protocol';
|
|
23
23
|
import { computeIdentityTag, fnv1a32 } from './utils/cacheKey';
|
|
24
|
+
import { redactUrlQuery } from './utils/redactUrl';
|
|
24
25
|
import type { OxyConfig } from './models/interfaces';
|
|
25
26
|
import type { DeviceSecretMintOutcome } from './session/refresh';
|
|
26
27
|
|
|
@@ -405,7 +406,9 @@ export class HttpService {
|
|
|
405
406
|
const cached = this.cache.get(cacheKey) as T | null;
|
|
406
407
|
if (cached !== null) {
|
|
407
408
|
this.requestMetrics.cacheHits++;
|
|
408
|
-
|
|
409
|
+
// Redact the query string: an asset stream URL passed here carries a
|
|
410
|
+
// scoped `mt=` media token that must never reach a log sink.
|
|
411
|
+
this.logger.debug('Cache hit:', redactUrlQuery(url));
|
|
409
412
|
return cached;
|
|
410
413
|
}
|
|
411
414
|
this.requestMetrics.cacheMisses++;
|
|
@@ -13,6 +13,57 @@ export class OxyAuthenticationError extends Error {
|
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Thrown when an asset's authorized download URL cannot be resolved.
|
|
18
|
+
*
|
|
19
|
+
* `getFileDownloadUrlAsync` asks the API for a URL that is valid for the
|
|
20
|
+
* CALLER and the asset's actual visibility. When that resolution fails there is
|
|
21
|
+
* no honest fallback: the public CDN origin only serves `public` assets, so
|
|
22
|
+
* handing back `https://cloud.oxy.so/<id>` for an unresolved asset produces a
|
|
23
|
+
* hard 404 at render time and hides the real failure from the caller. This
|
|
24
|
+
* error surfaces the failure instead.
|
|
25
|
+
*
|
|
26
|
+
* The message and fields deliberately carry only the asset id, the requested
|
|
27
|
+
* variant and the HTTP status — never the resolved URL, which embeds a scoped
|
|
28
|
+
* media token.
|
|
29
|
+
*
|
|
30
|
+
* ## `status` lets a caller decide whether a CDN fallback is safe
|
|
31
|
+
*
|
|
32
|
+
* Core itself never falls back to the public CDN builder, because it has no
|
|
33
|
+
* knowledge of the asset's visibility and that URL is a guaranteed 404 for a
|
|
34
|
+
* private asset. A CALLER that knows an asset is public MAY choose to fall back
|
|
35
|
+
* to `getFileDownloadUrl(id, variant)` — but only for a TRANSIENT failure, not
|
|
36
|
+
* a definitive denial:
|
|
37
|
+
* - `status` 401/403/404 → definitive: the asset is private/denied/missing.
|
|
38
|
+
* Never CDN-fall-back — it will 404.
|
|
39
|
+
* - `status` undefined (network error) or 5xx → transient: resolution itself
|
|
40
|
+
* failed. If the caller independently knows the asset is public, a CDN
|
|
41
|
+
* fallback is defensible best-effort.
|
|
42
|
+
*/
|
|
43
|
+
export class AssetUrlResolutionError extends Error {
|
|
44
|
+
public readonly code = 'ASSET_URL_UNRESOLVED';
|
|
45
|
+
public readonly fileId: string;
|
|
46
|
+
public readonly variant?: string;
|
|
47
|
+
public readonly status?: number;
|
|
48
|
+
/**
|
|
49
|
+
* The underlying transport/API failure, when there was one. Declared on the
|
|
50
|
+
* class rather than relying on `Error.cause` because this package targets
|
|
51
|
+
* ES2020, where `cause` is not part of the `Error` type.
|
|
52
|
+
*/
|
|
53
|
+
public readonly cause?: unknown;
|
|
54
|
+
|
|
55
|
+
constructor(fileId: string, variant: string | undefined, status: number | undefined, cause?: unknown) {
|
|
56
|
+
const variantSuffix = variant ? ` (variant "${variant}")` : '';
|
|
57
|
+
const statusSuffix = typeof status === 'number' ? ` — status ${status}` : '';
|
|
58
|
+
super(`Could not resolve a download URL for asset "${fileId}"${variantSuffix}${statusSuffix}`);
|
|
59
|
+
this.name = 'AssetUrlResolutionError';
|
|
60
|
+
this.fileId = fileId;
|
|
61
|
+
this.variant = variant;
|
|
62
|
+
this.status = status;
|
|
63
|
+
this.cause = cause;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
16
67
|
export class OxyAuthenticationTimeoutError extends OxyAuthenticationError {
|
|
17
68
|
constructor(operationName: string, timeoutMs: number) {
|
|
18
69
|
super(
|
package/src/OxyServices.ts
CHANGED
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
* See method JSDoc for more details and options.
|
|
58
58
|
*/
|
|
59
59
|
import { OxyServicesBase, type LinkedHttpClient, type OxyConfig } from './OxyServices.base';
|
|
60
|
-
import { OxyAuthenticationError, OxyAuthenticationTimeoutError } from './OxyServices.errors';
|
|
60
|
+
import { AssetUrlResolutionError, OxyAuthenticationError, OxyAuthenticationTimeoutError } from './OxyServices.errors';
|
|
61
61
|
|
|
62
62
|
// Import mixin composition helper
|
|
63
63
|
import { composeOxyServices } from './mixins';
|
|
@@ -151,7 +151,7 @@ export interface OxyServices extends InstanceType<ReturnType<typeof composeOxySe
|
|
|
151
151
|
}
|
|
152
152
|
|
|
153
153
|
// Re-export error classes for convenience
|
|
154
|
-
export { OxyAuthenticationError, OxyAuthenticationTimeoutError };
|
|
154
|
+
export { AssetUrlResolutionError, OxyAuthenticationError, OxyAuthenticationTimeoutError };
|
|
155
155
|
|
|
156
156
|
/**
|
|
157
157
|
* Default Oxy Cloud URL — used when no `cloudURL` is provided to OxyServices.
|
package/src/index.ts
CHANGED
|
@@ -23,7 +23,7 @@ import './crypto/polyfill';
|
|
|
23
23
|
// ---------------------------------------------------------------------------
|
|
24
24
|
// API client
|
|
25
25
|
// ---------------------------------------------------------------------------
|
|
26
|
-
export { OxyServices, OxyAuthenticationError, OxyAuthenticationTimeoutError } from './OxyServices';
|
|
26
|
+
export { OxyServices, AssetUrlResolutionError, OxyAuthenticationError, OxyAuthenticationTimeoutError } from './OxyServices';
|
|
27
27
|
export { OXY_CLOUD_URL, oxyClient } from './OxyServices';
|
|
28
28
|
export type { LinkedHttpClient } from './OxyServices.base';
|
|
29
29
|
// Auth-refresh handler surface — consumed by `@oxyhq/services`'s OxyContext to
|
|
@@ -311,6 +311,8 @@ export type {
|
|
|
311
311
|
AssetLinkRequest,
|
|
312
312
|
AssetUnlinkRequest,
|
|
313
313
|
AssetUrlResponse,
|
|
314
|
+
BatchFileAccessEntry,
|
|
315
|
+
BatchFileAccessResponse,
|
|
314
316
|
AssetDeleteSummary,
|
|
315
317
|
AssetUpdateVisibilityRequest,
|
|
316
318
|
AssetUpdateVisibilityResponse,
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import type { AccountStorageUsageResponse, AssetUploadInput, AssetUrlResponse, AssetVariant, RNFileDescriptor, ServiceAssetMetadata, ServiceAssetMetadataBySha } from '../models/interfaces';
|
|
1
|
+
import type { AccountStorageUsageResponse, AssetUploadInput, AssetUrlResponse, AssetVariant, BatchFileAccessResponse, RNFileDescriptor, ServiceAssetMetadata, ServiceAssetMetadataBySha } from '../models/interfaces';
|
|
2
2
|
import type { OxyServicesBase } from '../OxyServices.base';
|
|
3
3
|
import { isReactNative } from '@oxyhq/protocol';
|
|
4
4
|
import { logger } from '../logger';
|
|
5
|
+
import { AssetUrlResolutionError } from '../OxyServices.errors';
|
|
5
6
|
import { extractErrorStatus } from '../utils/errorUtils';
|
|
7
|
+
import { redactUrlQuery } from '../utils/redactUrl';
|
|
6
8
|
|
|
7
9
|
/**
|
|
8
10
|
* Maximum number of ids sent per `POST /assets/service/by-ids` request. Matches
|
|
@@ -27,6 +29,40 @@ const SERVICE_ASSET_METADATA_BY_SHA_CHUNK_SIZE = 100;
|
|
|
27
29
|
*/
|
|
28
30
|
const SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/;
|
|
29
31
|
|
|
32
|
+
/**
|
|
33
|
+
* Conservative lower bound (10 min) the SDK assumes for the lifetime of the
|
|
34
|
+
* scoped media token (`mt`) the API embeds in the stream URL it returns for a
|
|
35
|
+
* private asset. The SDK never mints or inspects that token; this constant
|
|
36
|
+
* exists only so the SDK's own URL cache can be sized safely BELOW the token's
|
|
37
|
+
* real lifetime.
|
|
38
|
+
*
|
|
39
|
+
* The API currently mints tokens for 900s (`MEDIA_TOKEN_TTL_SECONDS` in
|
|
40
|
+
* `packages/api/src/utils/mediaToken.ts`). Core deliberately assumes a shorter
|
|
41
|
+
* 10-min floor rather than copying 15: core and the API are separate packages,
|
|
42
|
+
* so core cannot observe a server-side TTL change at runtime. Under-assuming the
|
|
43
|
+
* lifetime only ever shortens the cache (more refetches, never a dead URL), so
|
|
44
|
+
* it stays correct even if the server lowers its TTL toward this floor. The
|
|
45
|
+
* {@link ASSET_URL_CACHE_LIFETIME_FRACTION} discount is applied on top.
|
|
46
|
+
*/
|
|
47
|
+
const ASSET_MEDIA_TOKEN_TTL_MS = 10 * 60 * 1000;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Fraction of a resolved URL's remaining lifetime the SDK is willing to keep it
|
|
51
|
+
* cached for. A resolved URL stops working the moment its media token expires,
|
|
52
|
+
* so caching it for its full nominal lifetime guarantees a window in which the
|
|
53
|
+
* cache hands out an already-dead URL (clock skew, time spent in the render
|
|
54
|
+
* pipeline, an image request queued behind others). Half the lifetime leaves a
|
|
55
|
+
* margin at least as large as the entry's own age.
|
|
56
|
+
*/
|
|
57
|
+
const ASSET_URL_CACHE_LIFETIME_FRACTION = 0.5;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Fallback URL lifetime, in seconds, assumed when the caller does not request
|
|
61
|
+
* an explicit `expiresIn`. Mirrors the API's default signed-URL expiry; the
|
|
62
|
+
* effective value is still clamped by {@link ASSET_MEDIA_TOKEN_TTL_MS}.
|
|
63
|
+
*/
|
|
64
|
+
const DEFAULT_ASSET_URL_EXPIRES_IN_SECONDS = 3600;
|
|
65
|
+
|
|
30
66
|
export function OxyServicesAssetsMixin<T extends typeof OxyServicesBase>(Base: T) {
|
|
31
67
|
return class extends Base {
|
|
32
68
|
constructor(...args: any[]) {
|
|
@@ -61,14 +97,33 @@ export function OxyServicesAssetsMixin<T extends typeof OxyServicesBase>(Base: T
|
|
|
61
97
|
}
|
|
62
98
|
|
|
63
99
|
/**
|
|
64
|
-
* Build a synchronous, `<img src>`-ready
|
|
100
|
+
* Build a synchronous, `<img src>`-ready URL for a **PUBLIC** Oxy asset.
|
|
101
|
+
*
|
|
102
|
+
* ## Contract — read before calling
|
|
65
103
|
*
|
|
66
|
-
* This
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
104
|
+
* This is a pure string builder. It performs no network call and therefore
|
|
105
|
+
* has **no knowledge of the asset's visibility**. It always produces the
|
|
106
|
+
* public form: `${cloudURL}/<id>[?variant=…]`, which the CDN serves from
|
|
107
|
+
* the public media origin only.
|
|
108
|
+
*
|
|
109
|
+
* Consequently:
|
|
110
|
+
* - Call it ONLY when the asset is known to be `public` — e.g. avatars and
|
|
111
|
+
* profile banners, which {@link uploadAvatar} / {@link uploadProfileBanner}
|
|
112
|
+
* upload with `visibility: 'public'`.
|
|
113
|
+
* - For an asset that may be `private` or `unlisted` — anything uploaded
|
|
114
|
+
* through the generic {@link assetUpload} path, whose server-side default
|
|
115
|
+
* is private — this URL resolves to a hard **404**. Use
|
|
116
|
+
* {@link getFileDownloadUrlAsync}, which asks the API for a URL scoped to
|
|
117
|
+
* the current caller.
|
|
118
|
+
* - It must never guess visibility, and must never embed the caller's
|
|
119
|
+
* bearer token: the returned string is rendered into DOM attributes,
|
|
120
|
+
* browser network panels, HTTP caches, and logs.
|
|
121
|
+
*
|
|
122
|
+
* Passing `expiresIn` switches to the API-origin stream form
|
|
123
|
+
* (`${baseURL}/assets/<id>/stream?…`) WITHOUT any credential. That form
|
|
124
|
+
* still only serves what an unauthenticated request may see — it is not a
|
|
125
|
+
* synchronous private-asset path, and none exists: authorization for a
|
|
126
|
+
* private asset requires the round-trip in {@link getFileDownloadUrlAsync}.
|
|
72
127
|
*/
|
|
73
128
|
getFileDownloadUrl(fileId: string, variant?: string, expiresIn?: number): string {
|
|
74
129
|
// Never embed the in-memory bearer token: this URL is rendered into DOM
|
|
@@ -91,21 +146,46 @@ export function OxyServicesAssetsMixin<T extends typeof OxyServicesBase>(Base: T
|
|
|
91
146
|
}
|
|
92
147
|
|
|
93
148
|
/**
|
|
94
|
-
*
|
|
149
|
+
* Resolve an asset id to a URL that is valid for the CURRENT caller,
|
|
150
|
+
* whatever the asset's visibility.
|
|
151
|
+
*
|
|
152
|
+
* Asks the API (`GET /assets/:id/url`) rather than guessing: a `public`
|
|
153
|
+
* asset resolves to the CDN form, while a `private`/`unlisted` asset the
|
|
154
|
+
* caller may read resolves to an API-origin stream URL carrying a scoped,
|
|
155
|
+
* short-lived media token. The returned URL is passed through **unchanged**
|
|
156
|
+
* — the SDK never rewrites, re-signs, or strips it.
|
|
157
|
+
*
|
|
158
|
+
* ## Failure behaviour — no CDN fallback
|
|
159
|
+
*
|
|
160
|
+
* Throws {@link AssetUrlResolutionError} when the API returns no URL or the
|
|
161
|
+
* request fails (including 401/403/404). It deliberately does NOT fall back
|
|
162
|
+
* to {@link getFileDownloadUrl}: that builder only produces the public CDN
|
|
163
|
+
* form, so falling back would hand the caller a URL that renders as a hard
|
|
164
|
+
* 404 for every private asset and would silently swallow the real failure.
|
|
165
|
+
* A caller that knows an asset is public should call the synchronous
|
|
166
|
+
* builder directly instead of relying on a fallback here.
|
|
167
|
+
*
|
|
168
|
+
* The resolved URL is cached per identity for well under the media token's
|
|
169
|
+
* lifetime — see {@link getAssetUrlCacheTTL}.
|
|
95
170
|
*/
|
|
96
171
|
async getFileDownloadUrlAsync(fileId: string, variant?: string, expiresIn?: number): Promise<string> {
|
|
172
|
+
let url: string | null;
|
|
97
173
|
try {
|
|
98
|
-
|
|
174
|
+
url = await this.fetchAssetDownloadUrl(
|
|
99
175
|
fileId,
|
|
100
176
|
variant,
|
|
101
177
|
this.getAssetUrlCacheTTL(expiresIn),
|
|
102
178
|
expiresIn
|
|
103
179
|
);
|
|
180
|
+
} catch (error: unknown) {
|
|
181
|
+
throw new AssetUrlResolutionError(fileId, variant, extractErrorStatus(error), error);
|
|
182
|
+
}
|
|
104
183
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
return this.getFileDownloadUrl(fileId, variant, expiresIn);
|
|
184
|
+
if (!url) {
|
|
185
|
+
throw new AssetUrlResolutionError(fileId, variant, undefined);
|
|
108
186
|
}
|
|
187
|
+
|
|
188
|
+
return url;
|
|
109
189
|
}
|
|
110
190
|
|
|
111
191
|
/**
|
|
@@ -180,13 +260,39 @@ export function OxyServicesAssetsMixin<T extends typeof OxyServicesBase>(Base: T
|
|
|
180
260
|
}
|
|
181
261
|
|
|
182
262
|
/**
|
|
183
|
-
*
|
|
263
|
+
* Resolve access + a caller-scoped URL for many assets — each with its OWN
|
|
264
|
+
* requested variant — in ONE round trip via `POST /assets/batch-access`.
|
|
265
|
+
*
|
|
266
|
+
* `requests` is a per-file `{ fileId, variant? }` list (a `variant` of
|
|
267
|
+
* `undefined` asks for the original). `options.expiresIn` sets the requested
|
|
268
|
+
* media-token / signed-URL lifetime (seconds); `options.context` is the
|
|
269
|
+
* server-side access-check context. Entries with a blank `fileId` are
|
|
270
|
+
* dropped and exact `(fileId, variant)` duplicates are collapsed before the
|
|
271
|
+
* request; an empty effective list performs no network call.
|
|
272
|
+
*
|
|
273
|
+
* The server caps the batch at 100 entries — callers that page beyond that
|
|
274
|
+
* must chunk. Returns the raw per-file envelope (see
|
|
275
|
+
* {@link BatchFileAccessResponse}); most callers want {@link getFileDownloadUrls},
|
|
276
|
+
* which flattens it to just the usable URLs.
|
|
184
277
|
*/
|
|
185
|
-
async getBatchFileAccess(
|
|
278
|
+
async getBatchFileAccess(
|
|
279
|
+
requests: Array<{ fileId: string; variant?: string }>,
|
|
280
|
+
options?: { expiresIn?: number; context?: string },
|
|
281
|
+
): Promise<BatchFileAccessResponse> {
|
|
282
|
+
const files = dedupeFileAccessRequests(requests);
|
|
283
|
+
if (files.length === 0) {
|
|
284
|
+
return { results: {} };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const body: { files: Array<{ fileId: string; variant?: string }>; expiresIn?: number; context?: string } = {
|
|
288
|
+
files,
|
|
289
|
+
};
|
|
290
|
+
if (typeof options?.expiresIn === 'number') body.expiresIn = options.expiresIn;
|
|
291
|
+
if (typeof options?.context === 'string') body.context = options.context;
|
|
292
|
+
|
|
186
293
|
try {
|
|
187
|
-
return await this.makeRequest('POST', '/assets/batch-access', {
|
|
188
|
-
|
|
189
|
-
context
|
|
294
|
+
return await this.makeRequest<BatchFileAccessResponse>('POST', '/assets/batch-access', body, {
|
|
295
|
+
cache: false,
|
|
190
296
|
});
|
|
191
297
|
} catch (error) {
|
|
192
298
|
throw this.handleError(error);
|
|
@@ -194,13 +300,30 @@ export function OxyServicesAssetsMixin<T extends typeof OxyServicesBase>(Base: T
|
|
|
194
300
|
}
|
|
195
301
|
|
|
196
302
|
/**
|
|
197
|
-
*
|
|
303
|
+
* Resolve many assets — each with its OWN variant — to caller-scoped,
|
|
304
|
+
* `<img src>`-ready URLs in one round trip. The batch counterpart of
|
|
305
|
+
* {@link getFileDownloadUrlAsync}, built to resolve a whole grid page at once.
|
|
306
|
+
*
|
|
307
|
+
* `requests` is a per-file `{ fileId, variant? }` list (e.g. `poster` for a
|
|
308
|
+
* video, `thumb` for an image); the per-file variant RULE lives in the
|
|
309
|
+
* caller — core just forwards what it is given. `options.expiresIn` /
|
|
310
|
+
* `options.context` are passed through to the endpoint.
|
|
311
|
+
*
|
|
312
|
+
* Each returned URL is the API's own scoped form, passed through unchanged:
|
|
313
|
+
* the public CDN URL for a public asset, or an API-origin
|
|
314
|
+
* `/assets/:id/stream?…&mt=<media token>` URL for a private asset the caller
|
|
315
|
+
* may read. Ids the caller cannot access (or that do not exist) are simply
|
|
316
|
+
* OMITTED from the returned map — there is NO public-CDN fallback, so a grid
|
|
317
|
+
* never renders a known-404 URL. Callers detect a miss by the absent key
|
|
318
|
+
* (the map never contains an empty-string value). Keyed by `fileId`.
|
|
198
319
|
*/
|
|
199
|
-
async getFileDownloadUrls(
|
|
200
|
-
|
|
320
|
+
async getFileDownloadUrls(
|
|
321
|
+
requests: Array<{ fileId: string; variant?: string }>,
|
|
322
|
+
options?: { expiresIn?: number; context?: string },
|
|
323
|
+
): Promise<Record<string, string>> {
|
|
324
|
+
const response = await this.getBatchFileAccess(requests, options);
|
|
201
325
|
const urls: Record<string, string> = {};
|
|
202
|
-
const
|
|
203
|
-
for (const [id, result] of Object.entries(results as Record<string, any>)) {
|
|
326
|
+
for (const [id, result] of Object.entries(response.results ?? {})) {
|
|
204
327
|
if (result.allowed && result.url) {
|
|
205
328
|
urls[id] = result.url;
|
|
206
329
|
}
|
|
@@ -526,7 +649,7 @@ export function OxyServicesAssetsMixin<T extends typeof OxyServicesBase>(Base: T
|
|
|
526
649
|
|
|
527
650
|
return await this.makeRequest<AssetUrlResponse>('GET', `/assets/${fileId}/url`, params, {
|
|
528
651
|
cache: true,
|
|
529
|
-
cacheTTL:
|
|
652
|
+
cacheTTL: this.getAssetUrlCacheTTL(expiresIn),
|
|
530
653
|
});
|
|
531
654
|
} catch (error) {
|
|
532
655
|
throw this.handleError(error);
|
|
@@ -614,9 +737,21 @@ export function OxyServicesAssetsMixin<T extends typeof OxyServicesBase>(Base: T
|
|
|
614
737
|
}
|
|
615
738
|
}
|
|
616
739
|
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
740
|
+
/**
|
|
741
|
+
* How long a resolved asset URL may stay in the SDK's GET cache, in ms.
|
|
742
|
+
*
|
|
743
|
+
* A resolved private-asset URL dies the instant its scoped media token
|
|
744
|
+
* expires (~{@link ASSET_MEDIA_TOKEN_TTL_MS}). Caching it for its full
|
|
745
|
+
* nominal lifetime would leave a window where the cache serves an
|
|
746
|
+
* already-dead URL (clock skew, render-pipeline latency, an image request
|
|
747
|
+
* queued behind others). So the TTL is (a) never longer than the token's
|
|
748
|
+
* lifetime and (b) discounted to {@link ASSET_URL_CACHE_LIFETIME_FRACTION}
|
|
749
|
+
* of that bound — comfortably below the token TTL by construction.
|
|
750
|
+
*/
|
|
751
|
+
public getAssetUrlCacheTTL(expiresIn?: number): number {
|
|
752
|
+
const requestedLifetimeMs = (expiresIn ?? DEFAULT_ASSET_URL_EXPIRES_IN_SECONDS) * 1000;
|
|
753
|
+
const boundedLifetimeMs = Math.min(requestedLifetimeMs, ASSET_MEDIA_TOKEN_TTL_MS);
|
|
754
|
+
return Math.floor(boundedLifetimeMs * ASSET_URL_CACHE_LIFETIME_FRACTION);
|
|
620
755
|
}
|
|
621
756
|
|
|
622
757
|
public async fetchAssetDownloadUrl(
|
|
@@ -635,7 +770,10 @@ export function OxyServicesAssetsMixin<T extends typeof OxyServicesBase>(Base: T
|
|
|
635
770
|
Object.keys(params).length ? params : undefined,
|
|
636
771
|
{
|
|
637
772
|
cache: true,
|
|
638
|
-
|
|
773
|
+
// Cap the cached URL well below the media token's lifetime. The
|
|
774
|
+
// response body is a scoped, expiring URL; over-caching it serves a
|
|
775
|
+
// dead URL after the token expires (see getAssetUrlCacheTTL).
|
|
776
|
+
cacheTTL: cacheTTL ?? this.getAssetUrlCacheTTL(expiresIn),
|
|
639
777
|
}
|
|
640
778
|
);
|
|
641
779
|
|
|
@@ -656,6 +794,32 @@ export function OxyServicesAssetsMixin<T extends typeof OxyServicesBase>(Base: T
|
|
|
656
794
|
};
|
|
657
795
|
}
|
|
658
796
|
|
|
797
|
+
/**
|
|
798
|
+
* Normalize the per-file batch-access request list: drop entries with a blank
|
|
799
|
+
* `fileId` and collapse exact `(fileId, variant)` duplicates (first occurrence
|
|
800
|
+
* wins, preserving order). Two entries for the SAME `fileId` with DIFFERENT
|
|
801
|
+
* variants are intentionally kept — but note the response is keyed by `fileId`,
|
|
802
|
+
* so a caller that needs two variants of one file must issue separate calls.
|
|
803
|
+
*/
|
|
804
|
+
function dedupeFileAccessRequests(
|
|
805
|
+
requests: Array<{ fileId: string; variant?: string }>,
|
|
806
|
+
): Array<{ fileId: string; variant?: string }> {
|
|
807
|
+
const seen = new Set<string>();
|
|
808
|
+
const out: Array<{ fileId: string; variant?: string }> = [];
|
|
809
|
+
for (const req of requests) {
|
|
810
|
+
if (typeof req?.fileId !== 'string' || req.fileId.trim().length === 0) {
|
|
811
|
+
continue;
|
|
812
|
+
}
|
|
813
|
+
const key = `${req.fileId}\u0000${req.variant ?? ''}`;
|
|
814
|
+
if (seen.has(key)) {
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
seen.add(key);
|
|
818
|
+
out.push(req.variant === undefined ? { fileId: req.fileId } : { fileId: req.fileId, variant: req.variant });
|
|
819
|
+
}
|
|
820
|
+
return out;
|
|
821
|
+
}
|
|
822
|
+
|
|
659
823
|
/**
|
|
660
824
|
* Only send ambient credentials (cookies) when the asset URL is same-origin with
|
|
661
825
|
* the configured API base. Caller-supplied cross-origin asset URLs must not leak
|
|
@@ -161,7 +161,7 @@ export function OxyServicesUserMixin<T extends typeof OxyServicesBase>(Base: T)
|
|
|
161
161
|
*/
|
|
162
162
|
async getProfileByUsername(username: string, options?: { cache?: boolean }): Promise<User> {
|
|
163
163
|
try {
|
|
164
|
-
const user = await this.makeRequest<User>('GET', `/profiles/username/${username}`, undefined, {
|
|
164
|
+
const user = await this.makeRequest<User>('GET', `/profiles/username/${encodeURIComponent(username)}`, undefined, {
|
|
165
165
|
cache: options?.cache ?? true,
|
|
166
166
|
cacheTTL: 5 * 60 * 1000, // 5 minutes cache for profiles
|
|
167
167
|
});
|
|
@@ -733,6 +733,11 @@ export function OxyServicesUserMixin<T extends typeof OxyServicesBase>(Base: T)
|
|
|
733
733
|
try {
|
|
734
734
|
const result = await this.makeRequest<FollowMutationResult>('POST', `/users/${userId}/follow`, undefined, { cache: false });
|
|
735
735
|
this.clearCacheEntry(`GET:/users/${userId}/follow-status`);
|
|
736
|
+
// Profile fetches embed viewer-relative `relationship` — bust so a
|
|
737
|
+
// remount doesn't serve a stale isFollowing for up to 5 minutes.
|
|
738
|
+
this.clearCacheEntry(`GET:/users/${userId}`);
|
|
739
|
+
this.clearCacheByPrefix('GET:/profiles/username/');
|
|
740
|
+
this.clearCacheByPrefix('GET:/profiles/resolve');
|
|
736
741
|
// The follow changed the viewer's graph — bust the cached consolidated
|
|
737
742
|
// `GET /users/me/graph` so the next read reflects the new following/
|
|
738
743
|
// mutual set instead of the stale pre-write snapshot.
|
|
@@ -760,7 +765,10 @@ export function OxyServicesUserMixin<T extends typeof OxyServicesBase>(Base: T)
|
|
|
760
765
|
// Bust each affected user's cached follow-status (see `followUser`).
|
|
761
766
|
for (const id of userIds) {
|
|
762
767
|
this.clearCacheEntry(`GET:/users/${id}/follow-status`);
|
|
768
|
+
this.clearCacheEntry(`GET:/users/${id}`);
|
|
763
769
|
}
|
|
770
|
+
this.clearCacheByPrefix('GET:/profiles/username/');
|
|
771
|
+
this.clearCacheByPrefix('GET:/profiles/resolve');
|
|
764
772
|
// The batch changed the viewer's graph — bust the consolidated cache.
|
|
765
773
|
this.clearCacheEntry('GET:/users/me/graph');
|
|
766
774
|
return result;
|
|
@@ -786,7 +794,10 @@ export function OxyServicesUserMixin<T extends typeof OxyServicesBase>(Base: T)
|
|
|
786
794
|
// Bust each affected user's cached follow-status (see `followUser`).
|
|
787
795
|
for (const id of userIds) {
|
|
788
796
|
this.clearCacheEntry(`GET:/users/${id}/follow-status`);
|
|
797
|
+
this.clearCacheEntry(`GET:/users/${id}`);
|
|
789
798
|
}
|
|
799
|
+
this.clearCacheByPrefix('GET:/profiles/username/');
|
|
800
|
+
this.clearCacheByPrefix('GET:/profiles/resolve');
|
|
790
801
|
// The batch changed the viewer's graph — bust the consolidated cache.
|
|
791
802
|
this.clearCacheEntry('GET:/users/me/graph');
|
|
792
803
|
return result;
|
|
@@ -803,6 +814,9 @@ export function OxyServicesUserMixin<T extends typeof OxyServicesBase>(Base: T)
|
|
|
803
814
|
const result = await this.makeRequest<FollowMutationResult>('DELETE', `/users/${userId}/follow`, undefined, { cache: false });
|
|
804
815
|
// Bust the cached follow-status so a remount reads fresh truth (see `followUser`).
|
|
805
816
|
this.clearCacheEntry(`GET:/users/${userId}/follow-status`);
|
|
817
|
+
this.clearCacheEntry(`GET:/users/${userId}`);
|
|
818
|
+
this.clearCacheByPrefix('GET:/profiles/username/');
|
|
819
|
+
this.clearCacheByPrefix('GET:/profiles/resolve');
|
|
806
820
|
// The unfollow changed the viewer's graph — bust the consolidated cache.
|
|
807
821
|
this.clearCacheEntry('GET:/users/me/graph');
|
|
808
822
|
return result;
|
|
@@ -147,12 +147,17 @@ describe('follow-status cache invalidation', () => {
|
|
|
147
147
|
|
|
148
148
|
it('invalidates the exact logical follow-status key on a single follow', async () => {
|
|
149
149
|
const clearSpy = jest.spyOn(oxy, 'clearCacheEntry');
|
|
150
|
+
const clearPrefixSpy = jest.spyOn(oxy, 'clearCacheByPrefix');
|
|
150
151
|
fetchMock.mockResolvedValueOnce(jsonResponse({ success: true, message: 'ok' }));
|
|
151
152
|
|
|
152
153
|
await oxy.followUser('target-3');
|
|
153
154
|
|
|
154
155
|
expect(clearSpy).toHaveBeenCalledWith('GET:/users/target-3/follow-status');
|
|
156
|
+
expect(clearSpy).toHaveBeenCalledWith('GET:/users/target-3');
|
|
157
|
+
expect(clearPrefixSpy).toHaveBeenCalledWith('GET:/profiles/username/');
|
|
158
|
+
expect(clearPrefixSpy).toHaveBeenCalledWith('GET:/profiles/resolve');
|
|
155
159
|
clearSpy.mockRestore();
|
|
160
|
+
clearPrefixSpy.mockRestore();
|
|
156
161
|
});
|
|
157
162
|
|
|
158
163
|
it('does not invalidate or call the network when bulk follow gets an empty list', async () => {
|