@oxyhq/core 17.1.0 → 19.0.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/boot/sessionColdBoot.js +4 -5
- package/dist/cjs/i18n/locales/en-US.json +48 -5
- package/dist/cjs/i18n/locales/es-ES.json +48 -5
- package/dist/cjs/i18n/locales/locales/en-US.json +48 -5
- package/dist/cjs/i18n/locales/locales/es-ES.json +48 -5
- package/dist/cjs/index.js +10 -6
- package/dist/cjs/mixins/OxyServices.accounts.js +27 -2
- package/dist/cjs/mixins/OxyServices.deviceBoot.js +3 -2
- package/dist/cjs/mixins/OxyServices.user.js +14 -20
- package/dist/cjs/server/index.js +8 -2
- package/dist/cjs/server/userInvalidation.js +6 -28
- package/dist/cjs/session/refresh.js +9 -14
- package/dist/cjs/utils/identityCacheSweep.js +97 -0
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/boot/sessionColdBoot.js +4 -5
- package/dist/esm/i18n/locales/en-US.json +48 -5
- package/dist/esm/i18n/locales/es-ES.json +48 -5
- package/dist/esm/i18n/locales/locales/en-US.json +48 -5
- package/dist/esm/i18n/locales/locales/es-ES.json +48 -5
- package/dist/esm/index.js +1 -1
- package/dist/esm/mixins/OxyServices.accounts.js +22 -1
- package/dist/esm/mixins/OxyServices.deviceBoot.js +3 -2
- package/dist/esm/mixins/OxyServices.user.js +14 -20
- package/dist/esm/server/index.js +5 -1
- package/dist/esm/server/userInvalidation.js +5 -26
- package/dist/esm/session/refresh.js +9 -14
- package/dist/esm/utils/identityCacheSweep.js +92 -0
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/mixins/OxyServices.accounts.d.ts +54 -11
- package/dist/types/mixins/OxyServices.deviceBoot.d.ts +3 -2
- package/dist/types/mixins/OxyServices.user.d.ts +9 -7
- package/dist/types/models/interfaces.d.ts +11 -3
- package/dist/types/server/index.d.ts +4 -2
- package/dist/types/server/userInvalidation.d.ts +5 -24
- package/dist/types/session/refresh.d.ts +13 -18
- package/dist/types/utils/identityCacheSweep.d.ts +80 -0
- package/package.json +2 -2
- package/src/boot/sessionColdBoot.ts +4 -5
- package/src/i18n/locales/en-US.json +48 -5
- package/src/i18n/locales/es-ES.json +48 -5
- package/src/index.ts +8 -3
- package/src/mixins/OxyServices.accounts.ts +73 -12
- package/src/mixins/OxyServices.deviceBoot.ts +3 -2
- package/src/mixins/OxyServices.user.ts +14 -20
- package/src/mixins/__tests__/identityWriteCacheInvalidation.test.ts +370 -0
- package/src/models/interfaces.ts +11 -3
- package/src/server/__tests__/userInvalidation.test.ts +3 -20
- package/src/server/index.ts +5 -2
- package/src/server/userInvalidation.ts +8 -36
- package/src/session/refresh.ts +15 -20
- package/src/utils/__tests__/identityCacheSweep.test.ts +151 -0
- package/src/utils/identityCacheSweep.ts +104 -0
|
@@ -33,10 +33,11 @@
|
|
|
33
33
|
* registers the switched session into the operator's device-set directly).
|
|
34
34
|
*/
|
|
35
35
|
import type { User } from '../models/interfaces';
|
|
36
|
-
import type { AccountKind,
|
|
36
|
+
import type { AccountCategoryId, AccountKind, ChildAccountKind } from '@oxyhq/contracts';
|
|
37
37
|
import type { SessionLoginResponse } from '../models/session';
|
|
38
38
|
import type { OxyServicesBase } from '../OxyServices.base';
|
|
39
39
|
import { normalizeUserIdentity } from '../utils/userIdentity';
|
|
40
|
+
import { evictOxyIdentityCache } from '../utils/identityCacheSweep';
|
|
40
41
|
import { CACHE_TIMES } from './mixinHelpers';
|
|
41
42
|
|
|
42
43
|
// ---------------------------------------------------------------------------
|
|
@@ -52,8 +53,16 @@ import { CACHE_TIMES } from './mixinHelpers';
|
|
|
52
53
|
*
|
|
53
54
|
* Single source of truth is `@oxyhq/contracts`.
|
|
54
55
|
*/
|
|
55
|
-
export type {
|
|
56
|
-
export {
|
|
56
|
+
export type { AccountCategoryId, AccountKind } from '@oxyhq/contracts';
|
|
57
|
+
export {
|
|
58
|
+
ACCOUNT_CATEGORY_IDS,
|
|
59
|
+
ACCOUNT_KINDS,
|
|
60
|
+
MAX_ACCOUNT_CATEGORIES,
|
|
61
|
+
SELECTABLE_ACCOUNT_CATEGORY_IDS,
|
|
62
|
+
isActAsEligibleKind,
|
|
63
|
+
isSelectableAccountCategoryId,
|
|
64
|
+
kindAcceptsAccountCategories,
|
|
65
|
+
} from '@oxyhq/contracts';
|
|
57
66
|
|
|
58
67
|
/**
|
|
59
68
|
* The calling user's relationship to an account node, as resolved by the API:
|
|
@@ -146,13 +155,23 @@ export interface ListAccountsOptions {
|
|
|
146
155
|
tree?: boolean;
|
|
147
156
|
}
|
|
148
157
|
|
|
149
|
-
/** Kinds a signed-in user may create via `POST /accounts`. Channels are service-provisioned only. */
|
|
150
|
-
export type UserCreatableAccountKind = 'organization' | 'project' | 'bot';
|
|
151
|
-
|
|
152
158
|
/** Input accepted by `createAccount`. */
|
|
153
159
|
export interface CreateAccountInput {
|
|
154
|
-
/**
|
|
155
|
-
|
|
160
|
+
/**
|
|
161
|
+
* Classification of the new account. Every CHILD kind is creatable here with
|
|
162
|
+
* the caller's own bearer, `channel` included: a signed-in person has already
|
|
163
|
+
* proven who they are, and minting a child under their own tree is the same
|
|
164
|
+
* operation whichever kind it is.
|
|
165
|
+
*
|
|
166
|
+
* `channel` used to be excluded, on the reasoning that channels are
|
|
167
|
+
* service-provisioned only. What actually makes a channel safe does not depend
|
|
168
|
+
* on who creates it: `createChildAccount` writes no auth method, so it is born
|
|
169
|
+
* with no login, and `POST /accounts/:id/switch` refuses it via
|
|
170
|
+
* `isActAsEligibleKind`, so no session can ever have a channel as its subject
|
|
171
|
+
* and therefore no bearer exists that could add one. `personal` is excluded
|
|
172
|
+
* because it is a human login, minted at signup.
|
|
173
|
+
*/
|
|
174
|
+
kind: ChildAccountKind;
|
|
156
175
|
/**
|
|
157
176
|
* Parent account `_id` to nest the new account under. Omitted → the API roots
|
|
158
177
|
* it under the caller's personal account.
|
|
@@ -169,8 +188,17 @@ export interface CreateAccountInput {
|
|
|
169
188
|
name?: { first?: string; last?: string; displayName?: string };
|
|
170
189
|
bio?: string;
|
|
171
190
|
avatar?: string;
|
|
172
|
-
/**
|
|
173
|
-
|
|
191
|
+
/**
|
|
192
|
+
* What the account is about. ORDERED — the FIRST element is the primary
|
|
193
|
+
* category, so a picker must submit them in the order the user arranged them
|
|
194
|
+
* and must not sort. Stable ids, never labels: render each one through the
|
|
195
|
+
* `accounts.accountCategory.<id>` translation key.
|
|
196
|
+
*
|
|
197
|
+
* Offer `SELECTABLE_ACCOUNT_CATEGORY_IDS`, not `ACCOUNT_CATEGORY_IDS` — the
|
|
198
|
+
* latter still contains withdrawn ids so that accounts already carrying one
|
|
199
|
+
* keep working. At most `MAX_ACCOUNT_CATEGORIES`, no duplicates.
|
|
200
|
+
*/
|
|
201
|
+
accountCategories?: AccountCategoryId[];
|
|
174
202
|
}
|
|
175
203
|
|
|
176
204
|
/** Input accepted by `updateAccount`. Tree placement changes go through `/move`. */
|
|
@@ -185,8 +213,19 @@ export interface UpdateAccountInput {
|
|
|
185
213
|
name?: { first?: string; last?: string; displayName?: string };
|
|
186
214
|
bio?: string | null;
|
|
187
215
|
avatar?: string | null;
|
|
188
|
-
/**
|
|
189
|
-
|
|
216
|
+
/**
|
|
217
|
+
* Replaces the WHOLE list, in the order given — there is no add/remove verb,
|
|
218
|
+
* because a partial edit cannot express a re-ordering and the order is what
|
|
219
|
+
* names the primary category. `[]` clears it.
|
|
220
|
+
*
|
|
221
|
+
* Not nullable, unlike `bio` and `avatar`: the empty case already has a
|
|
222
|
+
* spelling of its own, so a second one could only ever disagree with it.
|
|
223
|
+
*
|
|
224
|
+
* Rejected for a `personal` account, and rejected when it ADDS a withdrawn
|
|
225
|
+
* id the account did not already carry — keeping or re-ordering one it has is
|
|
226
|
+
* always allowed.
|
|
227
|
+
*/
|
|
228
|
+
accountCategories?: AccountCategoryId[];
|
|
190
229
|
}
|
|
191
230
|
|
|
192
231
|
/** Input accepted by `provisionChannelAccount` (service token + `accounts:provision`). */
|
|
@@ -726,6 +765,18 @@ export function OxyServicesAccountsMixin<T extends typeof OxyServicesBase>(Base:
|
|
|
726
765
|
/**
|
|
727
766
|
* Update an account's mutable profile fields. Tree placement changes
|
|
728
767
|
* (reparenting) go through the dedicated move endpoint, not here.
|
|
768
|
+
*
|
|
769
|
+
* An account IS a user, so this write changes identity — and a profile
|
|
770
|
+
* screen never reads `/accounts/<id>`. It reads `GET /users/<id>` and
|
|
771
|
+
* `GET /profiles/username/<handle>`, both cached for 5 minutes in the
|
|
772
|
+
* CALLER'S OWN process, so busting only the account-graph keys left every
|
|
773
|
+
* profile surface serving the pre-edit avatar and name for the full TTL
|
|
774
|
+
* with a perfectly healthy server (the cross-service `oxy:user:invalidate`
|
|
775
|
+
* signal does not help: it evicts BACKEND caches, and cannot reach a cache
|
|
776
|
+
* living in a browser tab). {@link evictOxyIdentityCache} owns that key
|
|
777
|
+
* list — see its docs for why the handle-keyed entries are prefix-swept
|
|
778
|
+
* (a RENAME leaves the old handle's entry unreachable by any targeted key).
|
|
779
|
+
*
|
|
729
780
|
* @param accountId - The account's Mongo `_id`.
|
|
730
781
|
* @param data - Subset of updatable profile fields.
|
|
731
782
|
*/
|
|
@@ -744,6 +795,16 @@ export function OxyServicesAccountsMixin<T extends typeof OxyServicesBase>(Base:
|
|
|
744
795
|
// data) so neither serves the pre-update snapshot.
|
|
745
796
|
this.clearCacheEntry(`GET:/accounts/${encodeURIComponent(accountId)}`);
|
|
746
797
|
this._invalidateAccountLists();
|
|
798
|
+
// The parent's children list embeds this account's profile and is keyed
|
|
799
|
+
// by the PARENT id, so it is reachable only from the response node.
|
|
800
|
+
const parentAccountId = res.account?.parentAccountId;
|
|
801
|
+
if (parentAccountId) {
|
|
802
|
+
this.clearCacheEntry(
|
|
803
|
+
`GET:/accounts/${encodeURIComponent(parentAccountId)}/children`,
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
// Every identity read of this account, whichever key it lands under.
|
|
807
|
+
evictOxyIdentityCache(this, accountId);
|
|
747
808
|
return res.account;
|
|
748
809
|
} catch (error) {
|
|
749
810
|
throw this.handleError(error);
|
|
@@ -70,8 +70,9 @@ export function OxyServicesDeviceBootMixin<T extends typeof OxyServicesBase>(Bas
|
|
|
70
70
|
* Zero-cookie mint. Present the first-party `deviceId` + `deviceSecret` to
|
|
71
71
|
* `POST /session/device/token` — NO bearer, NO cookies: possession of the
|
|
72
72
|
* secret IS the device-ownership proof. Returns a fresh short access token
|
|
73
|
-
* for the device's active account plus `nextDeviceSecret` (
|
|
74
|
-
*
|
|
73
|
+
* for the device's active account plus `nextDeviceSecret` (on mint, the same
|
|
74
|
+
* proven secret echoed back — rotation happens on sign-in, not mint) and
|
|
75
|
+
* the projected device-session `state`.
|
|
75
76
|
*
|
|
76
77
|
* `skipAuth`: this call carries no bearer, so a 401 must surface DIRECTLY —
|
|
77
78
|
* never trigger `HttpService`'s 401→refresh→retry dance. The cold boot / re-
|
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
import { KeyManager } from '../crypto/keyManager';
|
|
29
29
|
import { SignatureService } from '../crypto/signatureService';
|
|
30
30
|
import { normalizeUserIdentity, normalizeUserIdentityOrNull } from '../utils/userIdentity';
|
|
31
|
+
import { evictOxyIdentityCache } from '../utils/identityCacheSweep';
|
|
31
32
|
import { logger } from '../logger';
|
|
32
33
|
import { extractErrorStatus } from '../utils/errorUtils';
|
|
33
34
|
|
|
@@ -534,13 +535,15 @@ export function OxyServicesUserMixin<T extends typeof OxyServicesBase>(Base: T)
|
|
|
534
535
|
/**
|
|
535
536
|
* Update user profile.
|
|
536
537
|
*
|
|
537
|
-
* Invalidates the SDK-side response cache for every endpoint that
|
|
538
|
-
*
|
|
539
|
-
*
|
|
540
|
-
*
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
*
|
|
538
|
+
* Invalidates the SDK-side response cache for every endpoint that can
|
|
539
|
+
* return this user — the list is owned by {@link evictOxyIdentityCache}, so
|
|
540
|
+
* a new identity read is added in one place instead of to each writer
|
|
541
|
+
* separately (this method's own hand-written copy had already drifted from
|
|
542
|
+
* the server-side one, missing `GET /auth/lookup/*` and
|
|
543
|
+
* `GET /profiles/resolve`). Without the sweep a follow-up
|
|
544
|
+
* `getUserBySession` inside the cache window returns the pre-update user —
|
|
545
|
+
* most visibly during onboarding, where the username step flickers back as
|
|
546
|
+
* if nothing was saved.
|
|
544
547
|
*
|
|
545
548
|
* TanStack Query handles offline queuing automatically.
|
|
546
549
|
*/
|
|
@@ -550,15 +553,7 @@ export function OxyServicesUserMixin<T extends typeof OxyServicesBase>(Base: T)
|
|
|
550
553
|
await this.makeRequest<User>('PUT', '/users/me', updates, { cache: false }),
|
|
551
554
|
);
|
|
552
555
|
|
|
553
|
-
|
|
554
|
-
// prefix sweep rather than an enumeration because the SDK never
|
|
555
|
-
// tracks the set of active session IDs centrally.
|
|
556
|
-
this.clearCacheByPrefix('GET:/session/user/');
|
|
557
|
-
this.clearCacheByPrefix('GET:/users/me');
|
|
558
|
-
this.clearCacheByPrefix('GET:/profiles/username/');
|
|
559
|
-
if (result?.id) {
|
|
560
|
-
this.clearCacheEntry(`GET:/users/${result.id}`);
|
|
561
|
-
}
|
|
556
|
+
evictOxyIdentityCache(this, result?.id);
|
|
562
557
|
|
|
563
558
|
return result;
|
|
564
559
|
} catch (error) {
|
|
@@ -615,10 +610,9 @@ export function OxyServicesUserMixin<T extends typeof OxyServicesBase>(Base: T)
|
|
|
615
610
|
const result = await this.makeRequest<PrivacySettings>('PATCH', `/privacy/${id}/privacy`, settings, {
|
|
616
611
|
cache: false,
|
|
617
612
|
});
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
this
|
|
621
|
-
this.clearCacheEntry(`GET:/users/${id}`);
|
|
613
|
+
// Privacy settings ride the user DTO, so every identity read goes stale
|
|
614
|
+
// too — same key list as any other profile write.
|
|
615
|
+
evictOxyIdentityCache(this, id);
|
|
622
616
|
this.clearCacheEntry(`GET:/privacy/${id}/privacy`);
|
|
623
617
|
return result;
|
|
624
618
|
} catch (error) {
|
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identity-cache invalidation for the profile WRITERS, against the REAL
|
|
3
|
+
* response cache.
|
|
4
|
+
*
|
|
5
|
+
* An account IS a user, and a profile screen never reads `/accounts/<id>` — it
|
|
6
|
+
* reads `GET /users/<id>` and `GET /profiles/username/<handle>`, both cached for
|
|
7
|
+
* five minutes in the caller's own process. `updateAccount` used to bust only
|
|
8
|
+
* the account-graph keys, so for up to five minutes after an edit a refetch
|
|
9
|
+
* handed back the PRE-EDIT profile from the client's own cache, with a
|
|
10
|
+
* perfectly healthy server ("I changed my channel's picture and it doesn't
|
|
11
|
+
* update until I reload the page").
|
|
12
|
+
*
|
|
13
|
+
* These tests drive the real `HttpService` cache over a mocked `fetch` rather
|
|
14
|
+
* than spying on `clearCacheEntry` / `clearCacheByPrefix`, because a spy proves
|
|
15
|
+
* only that SOME string was passed — not that the entry a read actually lands
|
|
16
|
+
* under was evicted. The load-bearing case is the RENAME: an implementation
|
|
17
|
+
* that busts the exact key for the handle in the write RESPONSE passes every
|
|
18
|
+
* assertion about the new handle while leaving the OLD handle's entry serving
|
|
19
|
+
* the pre-rename profile until its TTL. Both handles are warmed here so the two
|
|
20
|
+
* implementations disagree.
|
|
21
|
+
*
|
|
22
|
+
* `updateProfile` is covered here too, because it carried a SECOND, drifted
|
|
23
|
+
* hand-written copy of the same key list — it swept four of the six keys,
|
|
24
|
+
* missing `GET:/auth/lookup/` and `GET:/profiles/resolve`. Both writers now
|
|
25
|
+
* share one enumeration (`utils/identityCacheSweep`), and this is where that is
|
|
26
|
+
* asserted from the outside.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { OxyServices } from '../../OxyServices';
|
|
30
|
+
import type { AccountNode } from '../OxyServices.accounts';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A non-verified JWT whose payload decodes to the given claims — enough for the
|
|
34
|
+
* cache's identity tag and the bearer preflight (`jwtDecode` never checks a
|
|
35
|
+
* signature).
|
|
36
|
+
*/
|
|
37
|
+
function makeJwt(payload: Record<string, unknown>): string {
|
|
38
|
+
const b64url = (obj: Record<string, unknown>): string =>
|
|
39
|
+
Buffer.from(JSON.stringify(obj)).toString('base64url');
|
|
40
|
+
return `${b64url({ alg: 'none', typ: 'JWT' })}.${b64url({
|
|
41
|
+
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
42
|
+
...payload,
|
|
43
|
+
})}.sig`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A JSON `Response` in the API's `{ data: ... }` success envelope. */
|
|
47
|
+
function jsonResponse(data: unknown): Response {
|
|
48
|
+
return new Response(JSON.stringify({ data }), {
|
|
49
|
+
status: 200,
|
|
50
|
+
headers: { 'content-type': 'application/json' },
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const ACCOUNT_ID = 'acc1';
|
|
55
|
+
const PARENT_ID = 'root1';
|
|
56
|
+
const OLD_USERNAME = 'oldhandle';
|
|
57
|
+
const NEW_USERNAME = 'newhandle';
|
|
58
|
+
|
|
59
|
+
/** The write response: the account after a rename + a new picture. */
|
|
60
|
+
const renamedNode: AccountNode = {
|
|
61
|
+
accountId: ACCOUNT_ID,
|
|
62
|
+
kind: 'channel',
|
|
63
|
+
parentAccountId: PARENT_ID,
|
|
64
|
+
account: {
|
|
65
|
+
id: ACCOUNT_ID,
|
|
66
|
+
publicKey: 'pk-acc1',
|
|
67
|
+
username: NEW_USERNAME,
|
|
68
|
+
name: { displayName: 'Renamed Channel' },
|
|
69
|
+
avatar: 'file_new',
|
|
70
|
+
},
|
|
71
|
+
relationship: 'owner',
|
|
72
|
+
callerMembership: null,
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
describe('updateAccount identity-cache invalidation (real cache)', () => {
|
|
76
|
+
let originalFetch: typeof globalThis.fetch;
|
|
77
|
+
let fetchMock: jest.Mock<Promise<Response>, [RequestInfo | URL, RequestInit?]>;
|
|
78
|
+
let oxy: OxyServices;
|
|
79
|
+
|
|
80
|
+
beforeEach(() => {
|
|
81
|
+
originalFetch = globalThis.fetch;
|
|
82
|
+
fetchMock = jest.fn();
|
|
83
|
+
globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch;
|
|
84
|
+
|
|
85
|
+
oxy = new OxyServices({
|
|
86
|
+
baseURL: 'http://test.invalid',
|
|
87
|
+
enableRetry: false,
|
|
88
|
+
requestTimeout: 1000,
|
|
89
|
+
});
|
|
90
|
+
oxy.httpService.setTokens(makeJwt({ userId: 'operator-1' }));
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
afterEach(() => {
|
|
94
|
+
globalThis.fetch = originalFetch;
|
|
95
|
+
jest.clearAllMocks();
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Warm every cache entry an account can be served under, plus one unrelated
|
|
100
|
+
* entry that must SURVIVE. Returns the number of network calls made, so each
|
|
101
|
+
* assertion below can be expressed as "did this read hit the network again".
|
|
102
|
+
*/
|
|
103
|
+
async function warmCaches(): Promise<number> {
|
|
104
|
+
// The profile screen's two reads, under the handle it had BEFORE the edit
|
|
105
|
+
// and under the id.
|
|
106
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: OLD_USERNAME }));
|
|
107
|
+
await oxy.getProfileByUsername(OLD_USERNAME);
|
|
108
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: OLD_USERNAME }));
|
|
109
|
+
await oxy.getUserById(ACCOUNT_ID);
|
|
110
|
+
|
|
111
|
+
// The handle the account is ABOUT to be renamed to may already be warm (a
|
|
112
|
+
// 404-shaped read, a previous holder, a same-session preview). Warming it
|
|
113
|
+
// is what makes the old-handle assertion below non-vacuous: an
|
|
114
|
+
// implementation that busts only the response's handle passes for this one.
|
|
115
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: NEW_USERNAME }));
|
|
116
|
+
await oxy.getProfileByUsername(NEW_USERNAME);
|
|
117
|
+
|
|
118
|
+
// The pre-session login lookup (carries avatar + display name) and handle
|
|
119
|
+
// resolution — two keys the SDK's own profile-write sweep had drifted away
|
|
120
|
+
// from, and which no test previously covered from a write.
|
|
121
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ exists: true, username: OLD_USERNAME }));
|
|
122
|
+
await oxy.lookupUsername(OLD_USERNAME);
|
|
123
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: OLD_USERNAME }));
|
|
124
|
+
await oxy.resolveProfile(`@${OLD_USERNAME}@test.invalid`);
|
|
125
|
+
|
|
126
|
+
// The account-graph reads.
|
|
127
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ account: renamedNode }));
|
|
128
|
+
await oxy.getAccount(ACCOUNT_ID);
|
|
129
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [renamedNode] }));
|
|
130
|
+
await oxy.listAccounts();
|
|
131
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [renamedNode] }));
|
|
132
|
+
await oxy.listChildAccounts(PARENT_ID);
|
|
133
|
+
|
|
134
|
+
// An unrelated cached read. It must survive — the vacuity floor that tells
|
|
135
|
+
// a targeted sweep from a blanket `clearCache()`.
|
|
136
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ count: 3 }));
|
|
137
|
+
await oxy.httpService.get('/notifications/unread-count', { cache: true });
|
|
138
|
+
|
|
139
|
+
return fetchMock.mock.calls.length;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Perform the rename + picture change. */
|
|
143
|
+
async function performUpdate(): Promise<void> {
|
|
144
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ account: renamedNode }));
|
|
145
|
+
await oxy.updateAccount(ACCOUNT_ID, {
|
|
146
|
+
username: NEW_USERNAME,
|
|
147
|
+
avatar: 'file_new',
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
it('warms every read it later asserts on (control: all are cache hits before the write)', async () => {
|
|
152
|
+
const warmed = await warmCaches();
|
|
153
|
+
|
|
154
|
+
// Re-issue every read with no queued response. A cache MISS would call
|
|
155
|
+
// `fetch`, which now resolves `undefined` and throws — so a green run here
|
|
156
|
+
// is proof that each entry really is resident, and that the assertions
|
|
157
|
+
// below are measuring eviction rather than a cache that was never warm.
|
|
158
|
+
await oxy.getProfileByUsername(OLD_USERNAME);
|
|
159
|
+
await oxy.getProfileByUsername(NEW_USERNAME);
|
|
160
|
+
await oxy.getUserById(ACCOUNT_ID);
|
|
161
|
+
await oxy.lookupUsername(OLD_USERNAME);
|
|
162
|
+
await oxy.resolveProfile(`@${OLD_USERNAME}@test.invalid`);
|
|
163
|
+
await oxy.getAccount(ACCOUNT_ID);
|
|
164
|
+
await oxy.listAccounts();
|
|
165
|
+
await oxy.listChildAccounts(PARENT_ID);
|
|
166
|
+
await oxy.httpService.get('/notifications/unread-count', { cache: true });
|
|
167
|
+
|
|
168
|
+
expect(fetchMock).toHaveBeenCalledTimes(warmed);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it('evicts the OLD handle, not just the handle in the write response', async () => {
|
|
172
|
+
await warmCaches();
|
|
173
|
+
await performUpdate();
|
|
174
|
+
const afterWrite = fetchMock.mock.calls.length;
|
|
175
|
+
|
|
176
|
+
// THE assertion. `updateAccount` cannot know the pre-rename handle — it is
|
|
177
|
+
// in neither the request nor the response — so only a PREFIX sweep of
|
|
178
|
+
// `GET:/profiles/username/` reaches it. A targeted `clearCacheEntry` for
|
|
179
|
+
// the response's handle leaves this entry serving the pre-rename profile.
|
|
180
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: NEW_USERNAME }));
|
|
181
|
+
const refetched = await oxy.getProfileByUsername(OLD_USERNAME);
|
|
182
|
+
|
|
183
|
+
expect(fetchMock).toHaveBeenCalledTimes(afterWrite + 1);
|
|
184
|
+
expect(refetched.username).toBe(NEW_USERNAME);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it('evicts the by-id profile read the account detail page uses', async () => {
|
|
188
|
+
await warmCaches();
|
|
189
|
+
await performUpdate();
|
|
190
|
+
const afterWrite = fetchMock.mock.calls.length;
|
|
191
|
+
|
|
192
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, avatar: 'file_new' }));
|
|
193
|
+
const refetched = await oxy.getUserById(ACCOUNT_ID);
|
|
194
|
+
|
|
195
|
+
expect(fetchMock).toHaveBeenCalledTimes(afterWrite + 1);
|
|
196
|
+
expect(refetched.avatar).toBe('file_new');
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it('evicts the new handle, the login lookup, and handle resolution', async () => {
|
|
200
|
+
await warmCaches();
|
|
201
|
+
await performUpdate();
|
|
202
|
+
let calls = fetchMock.mock.calls.length;
|
|
203
|
+
|
|
204
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: NEW_USERNAME }));
|
|
205
|
+
await oxy.getProfileByUsername(NEW_USERNAME);
|
|
206
|
+
expect(fetchMock).toHaveBeenCalledTimes(++calls);
|
|
207
|
+
|
|
208
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ exists: false, username: OLD_USERNAME }));
|
|
209
|
+
await oxy.lookupUsername(OLD_USERNAME);
|
|
210
|
+
expect(fetchMock).toHaveBeenCalledTimes(++calls);
|
|
211
|
+
|
|
212
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: NEW_USERNAME }));
|
|
213
|
+
await oxy.resolveProfile(`@${OLD_USERNAME}@test.invalid`);
|
|
214
|
+
expect(fetchMock).toHaveBeenCalledTimes(++calls);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it('evicts the account detail, the account lists, and the PARENT children list', async () => {
|
|
218
|
+
await warmCaches();
|
|
219
|
+
await performUpdate();
|
|
220
|
+
let calls = fetchMock.mock.calls.length;
|
|
221
|
+
|
|
222
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ account: renamedNode }));
|
|
223
|
+
await oxy.getAccount(ACCOUNT_ID);
|
|
224
|
+
expect(fetchMock).toHaveBeenCalledTimes(++calls);
|
|
225
|
+
|
|
226
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [renamedNode] }));
|
|
227
|
+
await oxy.listAccounts();
|
|
228
|
+
expect(fetchMock).toHaveBeenCalledTimes(++calls);
|
|
229
|
+
|
|
230
|
+
// Keyed by the PARENT id, which is reachable only from the response node —
|
|
231
|
+
// the child's own id does not build this key.
|
|
232
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [renamedNode] }));
|
|
233
|
+
await oxy.listChildAccounts(PARENT_ID);
|
|
234
|
+
expect(fetchMock).toHaveBeenCalledTimes(++calls);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it('leaves unrelated cached reads alone (it is a sweep, not a cache wipe)', async () => {
|
|
238
|
+
await warmCaches();
|
|
239
|
+
await performUpdate();
|
|
240
|
+
const afterWrite = fetchMock.mock.calls.length;
|
|
241
|
+
|
|
242
|
+
// No queued response: a miss would call `fetch` and throw.
|
|
243
|
+
const cached = await oxy.httpService.get<{ count: number }>(
|
|
244
|
+
'/notifications/unread-count',
|
|
245
|
+
{ cache: true },
|
|
246
|
+
);
|
|
247
|
+
|
|
248
|
+
expect(fetchMock).toHaveBeenCalledTimes(afterWrite);
|
|
249
|
+
expect(cached.count).toBe(3);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it('does not sweep when the write fails', async () => {
|
|
253
|
+
await warmCaches();
|
|
254
|
+
const warmed = fetchMock.mock.calls.length;
|
|
255
|
+
|
|
256
|
+
fetchMock.mockResolvedValueOnce(
|
|
257
|
+
new Response(JSON.stringify({ message: 'forbidden' }), {
|
|
258
|
+
status: 403,
|
|
259
|
+
headers: { 'content-type': 'application/json' },
|
|
260
|
+
}),
|
|
261
|
+
);
|
|
262
|
+
await expect(
|
|
263
|
+
oxy.updateAccount(ACCOUNT_ID, { avatar: 'file_new' }),
|
|
264
|
+
).rejects.toThrow();
|
|
265
|
+
|
|
266
|
+
// The failed PATCH is one call; every read below must still be a cache hit.
|
|
267
|
+
await oxy.getProfileByUsername(OLD_USERNAME);
|
|
268
|
+
await oxy.getUserById(ACCOUNT_ID);
|
|
269
|
+
await oxy.getAccount(ACCOUNT_ID);
|
|
270
|
+
|
|
271
|
+
expect(fetchMock).toHaveBeenCalledTimes(warmed + 1);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
it('still sweeps the identity keys when the response carries no parent', async () => {
|
|
275
|
+
await warmCaches();
|
|
276
|
+
const rootNode: AccountNode = { ...renamedNode, parentAccountId: null };
|
|
277
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ account: rootNode }));
|
|
278
|
+
await oxy.updateAccount(ACCOUNT_ID, { avatar: 'file_new' });
|
|
279
|
+
const afterWrite = fetchMock.mock.calls.length;
|
|
280
|
+
|
|
281
|
+
// A root account has no children list to bust, but its identity keys go
|
|
282
|
+
// stale exactly the same way — the `parentAccountId` guard must not gate
|
|
283
|
+
// the identity sweep.
|
|
284
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, avatar: 'file_new' }));
|
|
285
|
+
await oxy.getUserById(ACCOUNT_ID);
|
|
286
|
+
|
|
287
|
+
expect(fetchMock).toHaveBeenCalledTimes(afterWrite + 1);
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
describe('updateProfile identity-cache invalidation (real cache)', () => {
|
|
292
|
+
let originalFetch: typeof globalThis.fetch;
|
|
293
|
+
let fetchMock: jest.Mock<Promise<Response>, [RequestInfo | URL, RequestInit?]>;
|
|
294
|
+
let oxy: OxyServices;
|
|
295
|
+
|
|
296
|
+
const SELF_ID = 'me-1';
|
|
297
|
+
|
|
298
|
+
beforeEach(() => {
|
|
299
|
+
originalFetch = globalThis.fetch;
|
|
300
|
+
fetchMock = jest.fn();
|
|
301
|
+
globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch;
|
|
302
|
+
oxy = new OxyServices({
|
|
303
|
+
baseURL: 'http://test.invalid',
|
|
304
|
+
enableRetry: false,
|
|
305
|
+
requestTimeout: 1000,
|
|
306
|
+
});
|
|
307
|
+
oxy.httpService.setTokens(makeJwt({ userId: SELF_ID }));
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
afterEach(() => {
|
|
311
|
+
globalThis.fetch = originalFetch;
|
|
312
|
+
jest.clearAllMocks();
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* The two keys `updateProfile`'s own hand-written sweep MISSED. They are the
|
|
317
|
+
* whole point of this block — a test that only re-checked `GET:/users/me` and
|
|
318
|
+
* `GET:/profiles/username/` would have passed against the drifted version.
|
|
319
|
+
*/
|
|
320
|
+
it('evicts the login lookup and handle resolution, not just the keys it used to know', async () => {
|
|
321
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ exists: true, username: 'alice', avatar: 'old' }));
|
|
322
|
+
await oxy.lookupUsername('alice');
|
|
323
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
|
|
324
|
+
await oxy.resolveProfile('@alice@test.invalid');
|
|
325
|
+
|
|
326
|
+
// Control: both are warm (a miss would call the un-queued mock and throw).
|
|
327
|
+
await oxy.lookupUsername('alice');
|
|
328
|
+
await oxy.resolveProfile('@alice@test.invalid');
|
|
329
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
330
|
+
|
|
331
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'new' }));
|
|
332
|
+
await oxy.updateProfile({ avatar: 'new' });
|
|
333
|
+
expect(fetchMock).toHaveBeenCalledTimes(3);
|
|
334
|
+
|
|
335
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ exists: true, username: 'alice', avatar: 'new' }));
|
|
336
|
+
await oxy.lookupUsername('alice');
|
|
337
|
+
expect(fetchMock).toHaveBeenCalledTimes(4);
|
|
338
|
+
|
|
339
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'new' }));
|
|
340
|
+
await oxy.resolveProfile('@alice@test.invalid');
|
|
341
|
+
expect(fetchMock).toHaveBeenCalledTimes(5);
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
it('still evicts the self, by-id and handle reads it always did', async () => {
|
|
345
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
|
|
346
|
+
await oxy.getCurrentUser();
|
|
347
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
|
|
348
|
+
await oxy.getUserById(SELF_ID);
|
|
349
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
|
|
350
|
+
await oxy.getProfileByUsername('alice');
|
|
351
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
|
|
352
|
+
await oxy.getUserBySession('sess-1');
|
|
353
|
+
expect(fetchMock).toHaveBeenCalledTimes(4);
|
|
354
|
+
|
|
355
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'new' }));
|
|
356
|
+
await oxy.updateProfile({ avatar: 'new' });
|
|
357
|
+
|
|
358
|
+
let calls = 5;
|
|
359
|
+
for (const read of [
|
|
360
|
+
() => oxy.getCurrentUser(),
|
|
361
|
+
() => oxy.getUserById(SELF_ID),
|
|
362
|
+
() => oxy.getProfileByUsername('alice'),
|
|
363
|
+
() => oxy.getUserBySession('sess-1'),
|
|
364
|
+
]) {
|
|
365
|
+
fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'new' }));
|
|
366
|
+
await read();
|
|
367
|
+
expect(fetchMock).toHaveBeenCalledTimes(++calls);
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
});
|
package/src/models/interfaces.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
AccountKind,
|
|
3
|
-
|
|
3
|
+
AccountCategoryId,
|
|
4
4
|
UserNameResponse,
|
|
5
5
|
UserRelationship,
|
|
6
6
|
ThemePreference,
|
|
@@ -170,8 +170,16 @@ export interface User {
|
|
|
170
170
|
// Managed account fields
|
|
171
171
|
isManagedAccount?: boolean;
|
|
172
172
|
managedBy?: string;
|
|
173
|
-
/**
|
|
174
|
-
|
|
173
|
+
/**
|
|
174
|
+
* What this account is about, for any NON-personal account. ORDERED — the
|
|
175
|
+
* first element is the primary category, and nothing may reorder it.
|
|
176
|
+
*
|
|
177
|
+
* Stable ids, not labels: render each through the
|
|
178
|
+
* `accounts.accountCategory.<id>` translation key so the reader sees their own
|
|
179
|
+
* language rather than the language of whoever chose it. Absent when the
|
|
180
|
+
* account has none.
|
|
181
|
+
*/
|
|
182
|
+
accountCategories?: AccountCategoryId[];
|
|
175
183
|
/**
|
|
176
184
|
* The account's languages as full BCP-47 locales (`language-REGION`, e.g.
|
|
177
185
|
* `en-US`, `es-MX`, `pt-BR`), ordered with the PRIMARY (UI) locale first.
|
|
@@ -2,10 +2,11 @@ import { OXY_USER_INVALIDATION_CHANNEL } from '@oxyhq/contracts';
|
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
4
|
createOxyUserInvalidationHandler,
|
|
5
|
-
evictOxyIdentityCache,
|
|
6
5
|
publishOxyUserInvalidation,
|
|
7
|
-
type OxyIdentityCacheEvictor,
|
|
8
6
|
} from '../userInvalidation';
|
|
7
|
+
// The key enumeration this subscriber sweeps is platform-neutral and shared
|
|
8
|
+
// with the client mixins — see `utils/identityCacheSweep` and its own suite.
|
|
9
|
+
import type { OxyIdentityCacheEvictor } from '../../utils/identityCacheSweep';
|
|
9
10
|
|
|
10
11
|
function makePublisher() {
|
|
11
12
|
const calls: Array<{ channel: string; message: string }> = [];
|
|
@@ -200,21 +201,3 @@ describe('@oxyhq/core/server createOxyUserInvalidationHandler', () => {
|
|
|
200
201
|
expect(() => createOxyUserInvalidationHandler()(validMessage)).not.toThrow();
|
|
201
202
|
});
|
|
202
203
|
});
|
|
203
|
-
|
|
204
|
-
describe('@oxyhq/core/server evictOxyIdentityCache', () => {
|
|
205
|
-
it('clears the exact by-id entry and the handle-keyed prefixes', () => {
|
|
206
|
-
// The by-id key is exact. The handle-keyed ones cannot be derived from an
|
|
207
|
-
// id without the lookup being invalidated, so they are swept by prefix.
|
|
208
|
-
const { evictor, entries, prefixes } = makeEvictor();
|
|
209
|
-
evictOxyIdentityCache(evictor, 'abc123');
|
|
210
|
-
|
|
211
|
-
expect(entries).toEqual(['GET:/users/abc123']);
|
|
212
|
-
expect(prefixes).toEqual([
|
|
213
|
-
'GET:/session/user/',
|
|
214
|
-
'GET:/users/me',
|
|
215
|
-
'GET:/auth/lookup/',
|
|
216
|
-
'GET:/profiles/username/',
|
|
217
|
-
'GET:/profiles/resolve',
|
|
218
|
-
]);
|
|
219
|
-
});
|
|
220
|
-
});
|
package/src/server/index.ts
CHANGED
|
@@ -86,14 +86,17 @@ export { verifySecret } from './verifySecret';
|
|
|
86
86
|
// changes, every consuming backend sweeps its caches instead of waiting out a TTL.
|
|
87
87
|
export {
|
|
88
88
|
createOxyUserInvalidationHandler,
|
|
89
|
-
evictOxyIdentityCache,
|
|
90
89
|
publishOxyUserInvalidation,
|
|
91
90
|
} from './userInvalidation';
|
|
92
91
|
export type {
|
|
93
|
-
OxyIdentityCacheEvictor,
|
|
94
92
|
OxyInvalidationPublisher,
|
|
95
93
|
OxyUserInvalidationHandlerOptions,
|
|
96
94
|
} from './userInvalidation';
|
|
95
|
+
// The identity-key enumeration itself is platform-neutral (`src/utils/`) so the
|
|
96
|
+
// client mixins and this Node-only subscriber sweep the SAME list — a second
|
|
97
|
+
// copy is what let `updateAccount` and `updateProfile` drift apart.
|
|
98
|
+
export { evictOxyIdentityCache, oxyUserByIdCacheKey, OXY_IDENTITY_CACHE_PREFIXES } from '../utils/identityCacheSweep';
|
|
99
|
+
export type { OxyIdentityCacheEvictor } from '../utils/identityCacheSweep';
|
|
97
100
|
|
|
98
101
|
// Registrable-apex (eTLD+1) derivation via the Public Suffix List — the SINGLE
|
|
99
102
|
// SOURCE OF TRUTH shared with the IdP worker and the client FAPI auto-detect.
|