@oxyhq/core 1.11.13 → 1.11.15

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/esm/index.js CHANGED
@@ -21,6 +21,7 @@ export { OXY_CLOUD_URL, oxyClient } from './OxyServices.js';
21
21
  // --- Authentication ---
22
22
  export { AuthManager, createAuthManager } from './AuthManager.js';
23
23
  export { CrossDomainAuth, createCrossDomainAuth } from './CrossDomainAuth.js';
24
+ export { ServiceCredentialMismatchError } from './mixins/OxyServices.auth.js';
24
25
  // --- Crypto / Identity ---
25
26
  export { KeyManager, SignatureService, RecoveryPhraseService, IdentityAlreadyExistsError, IdentityPersistError, } from './crypto/index.js';
26
27
  // --- Models & Types ---
@@ -30,7 +31,7 @@ export { TopicType, TopicSource } from './models/Topic.js';
30
31
  // --- Device Management ---
31
32
  export { DeviceManager } from './utils/deviceManager.js';
32
33
  // --- Language Utilities ---
33
- export { SUPPORTED_LANGUAGES, getLanguageMetadata, getLanguageName, getNativeLanguageName, normalizeLanguageCode, } from './utils/languageUtils.js';
34
+ export { SUPPORTED_LANGUAGES, getLanguageMetadata, getLanguageName, getNativeLanguageName, normalizeLanguageCode, isRTLLocale, } from './utils/languageUtils.js';
34
35
  // --- Platform Detection ---
35
36
  export { getPlatformOS, setPlatformOS, isWeb, isNative, isIOS, isAndroid, } from './utils/platform.js';
36
37
  // --- Shared Utilities ---
@@ -1,40 +1,87 @@
1
1
  import { OxyAuthenticationError } from '../OxyServices.errors.js';
2
+ import { loadNodeCrypto } from '../utils/platformCrypto.js';
3
+ import { logger } from '../utils/loggerUtils.js';
4
+ /**
5
+ * Sentinel error raised when getServiceToken() is called with a known apiKey
6
+ * but a non-matching secret. Indicates either credential drift in the caller
7
+ * or a cross-tenant cache lookup attempt. Surface as a 401-equivalent.
8
+ */
9
+ export class ServiceCredentialMismatchError extends Error {
10
+ constructor() {
11
+ super('Service credential mismatch: provided secret does not match the secret stored for this apiKey');
12
+ this.name = 'ServiceCredentialMismatchError';
13
+ }
14
+ }
2
15
  export function OxyServicesAuthMixin(Base) {
3
16
  return class extends Base {
4
17
  constructor(...args) {
5
18
  super(...args);
6
- /** @internal */ this._serviceToken = null;
7
- /** @internal */ this._serviceTokenExp = 0;
8
- /** @internal */ this._serviceApiKey = null;
9
- /** @internal */ this._serviceApiSecret = null;
10
19
  /**
11
- * In-flight promise for service token fetch. Used to deduplicate concurrent
12
- * calls to getServiceToken() — pattern mirrors AuthManager.refreshToken().
20
+ * Per-credential token cache.
21
+ *
22
+ * Keyed by SHA-256(apiKey). Each entry carries:
23
+ * - the issued service JWT
24
+ * - its expiry timestamp
25
+ * - the secret that produced it (Buffer for constant-time compare)
26
+ * - an optional in-flight promise to deduplicate concurrent refreshes
27
+ *
28
+ * The previous implementation kept ONE token/exp pair per OxyServices
29
+ * instance. That meant calling `getServiceToken(keyA, secretA)` populated
30
+ * the cache, and a subsequent `getServiceToken(keyB, secretB)` (different
31
+ * tenant) would receive tenant A's token. This is fixed by routing every
32
+ * lookup through the Map.
33
+ *
13
34
  * @internal
14
35
  */
15
- this._serviceTokenPromise = null;
36
+ this._serviceTokenCache = new Map();
37
+ /** @internal Raw apiKey stored by configureServiceAuth() for use by getServiceToken() */
38
+ this._serviceApiKey = null;
39
+ /** @internal Raw apiSecret stored by configureServiceAuth() for use by getServiceToken() */
40
+ this._serviceApiSecret = null;
41
+ }
42
+ /**
43
+ * Hash an apiKey into a stable Map cache key. Uses Node's SHA-256 — service
44
+ * tokens are only ever issued by a Node host (the SDK on web/RN never has
45
+ * the apiSecret in the first place), so we can rely on Node crypto here.
46
+ *
47
+ * @internal
48
+ */
49
+ async _hashApiKey(apiKey) {
50
+ const nodeCrypto = await loadNodeCrypto();
51
+ return nodeCrypto.createHash('sha256').update(apiKey).digest('hex');
16
52
  }
17
53
  /**
18
54
  * Configure service credentials for internal service-to-service communication.
19
55
  * Call this once at startup so that getServiceToken() and makeServiceRequest()
20
56
  * can automatically obtain and refresh tokens.
21
57
  *
58
+ * Calling this with credentials that differ from a previously-configured pair
59
+ * is allowed — each `(apiKey, apiSecret)` pair is cached independently, so
60
+ * legitimate multi-tenant hosts that need to switch credentials cannot leak
61
+ * one tenant's token to another tenant on the same instance.
62
+ *
22
63
  * @param apiKey - DeveloperApp API key (oxy_dk_*)
23
64
  * @param apiSecret - DeveloperApp API secret
24
65
  */
25
66
  configureServiceAuth(apiKey, apiSecret) {
26
67
  this._serviceApiKey = apiKey;
27
68
  this._serviceApiSecret = apiSecret;
28
- // Invalidate any cached token
29
- this._serviceToken = null;
30
- this._serviceTokenExp = 0;
31
69
  }
32
70
  /**
33
71
  * Get a service token for internal service-to-service communication.
34
- * Tokens are short-lived (1h) and automatically cached/refreshed.
72
+ * Tokens are short-lived (1h) and automatically cached/refreshed per
73
+ * `(apiKey, apiSecret)` pair.
74
+ *
75
+ * Concurrent callers for the same credential pair share a single in-flight
76
+ * request to avoid hammering `/auth/service-token` when the cache is empty
77
+ * or expired.
35
78
  *
36
- * Concurrent callers share a single in-flight request to avoid hammering
37
- * `/auth/service-token` when the cache is empty or expired.
79
+ * **Security guarantee:** if the cache already holds a token for this
80
+ * apiKey but the supplied apiSecret does not constant-time match the
81
+ * secret that originally produced that token, this method throws
82
+ * `ServiceCredentialMismatchError` instead of returning the cached token.
83
+ * This prevents an attacker who learned a peer's apiKey from extracting
84
+ * their service token by polling with a wrong secret.
38
85
  *
39
86
  * @param apiKey - DeveloperApp API key (optional if configureServiceAuth was called)
40
87
  * @param apiSecret - DeveloperApp API secret (optional if configureServiceAuth was called)
@@ -45,20 +92,62 @@ export function OxyServicesAuthMixin(Base) {
45
92
  if (!key || !secret) {
46
93
  throw new Error('Service credentials not provided. Call configureServiceAuth() or pass apiKey and apiSecret.');
47
94
  }
48
- // Return cached token if still valid (with 60s buffer)
49
- if (this._serviceToken && this._serviceTokenExp > Date.now() + 60000) {
50
- return this._serviceToken;
51
- }
52
- // If a fetch is already in-flight, share the same promise
53
- if (this._serviceTokenPromise) {
54
- return this._serviceTokenPromise;
95
+ const cacheKey = await this._hashApiKey(key);
96
+ const now = Date.now();
97
+ const providedSecretBuf = Buffer.from(secret, 'utf8');
98
+ let entry = this._serviceTokenCache.get(cacheKey);
99
+ // Verify the secret on every cache hit, regardless of token freshness.
100
+ // Constant-time compare prevents timing oracles on the stored secret.
101
+ if (entry) {
102
+ const nodeCrypto = await loadNodeCrypto();
103
+ const storedSecretBuf = entry.secretBuf;
104
+ const lengthMatch = storedSecretBuf.length === providedSecretBuf.length;
105
+ // Always run timingSafeEqual on equal-length inputs to keep timing flat.
106
+ // When lengths differ, run against a zero-padded copy of the same length
107
+ // to avoid an early-return timing signal.
108
+ const compareBuf = lengthMatch
109
+ ? providedSecretBuf
110
+ : Buffer.alloc(storedSecretBuf.length);
111
+ const compareResult = nodeCrypto.timingSafeEqual(storedSecretBuf, compareBuf);
112
+ if (!lengthMatch || !compareResult) {
113
+ logger.warn('[oxy.auth] Service token cache hit with mismatched secret', {
114
+ component: 'auth',
115
+ method: 'getServiceToken',
116
+ });
117
+ throw new ServiceCredentialMismatchError();
118
+ }
119
+ // Return cached token if still valid (with 60s buffer for clock drift)
120
+ if (entry.token && entry.expiresAt > now + 60000) {
121
+ return entry.token;
122
+ }
123
+ // If a fetch is already in-flight for this credential, share its result
124
+ if (entry.pending) {
125
+ return entry.pending;
126
+ }
55
127
  }
56
- this._serviceTokenPromise = this._doFetchServiceToken(key, secret);
128
+ else {
129
+ // First time seeing this apiKey on this instance — seed an empty entry
130
+ // so concurrent callers serialize on the same promise.
131
+ entry = {
132
+ token: '',
133
+ expiresAt: 0,
134
+ secretBuf: providedSecretBuf,
135
+ pending: null,
136
+ };
137
+ this._serviceTokenCache.set(cacheKey, entry);
138
+ }
139
+ const pending = this._doFetchServiceToken(key, secret, cacheKey, providedSecretBuf);
140
+ entry.pending = pending;
57
141
  try {
58
- return await this._serviceTokenPromise;
142
+ return await pending;
59
143
  }
60
144
  finally {
61
- this._serviceTokenPromise = null;
145
+ // Clear the in-flight slot; the entry itself (with fresh token / expiry)
146
+ // is updated inside _doFetchServiceToken before we land here.
147
+ const settled = this._serviceTokenCache.get(cacheKey);
148
+ if (settled) {
149
+ settled.pending = null;
150
+ }
62
151
  }
63
152
  }
64
153
  /**
@@ -66,11 +155,26 @@ export function OxyServicesAuthMixin(Base) {
66
155
  * Separated so getServiceToken() can deduplicate concurrent calls.
67
156
  * @internal
68
157
  */
69
- async _doFetchServiceToken(key, secret) {
158
+ async _doFetchServiceToken(key, secret, cacheKey, secretBuf) {
70
159
  const response = await this.makeRequest('POST', '/auth/service-token', { apiKey: key, apiSecret: secret }, { cache: false, retry: false });
71
- this._serviceToken = response.token;
72
- this._serviceTokenExp = Date.now() + response.expiresIn * 1000;
73
- return this._serviceToken;
160
+ const expiresAt = Date.now() + response.expiresIn * 1000;
161
+ // Update the entry in-place so any caller that already grabbed a reference
162
+ // (via `_serviceTokenCache.get(...)`) sees the fresh state.
163
+ const entry = this._serviceTokenCache.get(cacheKey);
164
+ if (entry) {
165
+ entry.token = response.token;
166
+ entry.expiresAt = expiresAt;
167
+ entry.secretBuf = secretBuf;
168
+ }
169
+ else {
170
+ this._serviceTokenCache.set(cacheKey, {
171
+ token: response.token,
172
+ expiresAt,
173
+ secretBuf,
174
+ pending: null,
175
+ });
176
+ }
177
+ return response.token;
74
178
  }
75
179
  /**
76
180
  * Make an authenticated request on behalf of a user using a service token.
@@ -168,8 +168,48 @@ export function OxyServicesPopupAuthMixin(Base) {
168
168
  document.body.appendChild(iframe);
169
169
  try {
170
170
  const session = await this.waitForIframeAuth(iframe, timeout, clientId);
171
- if (session && session.accessToken) {
172
- this.httpService.setTokens(session.accessToken);
171
+ // Bail early on incomplete responses. The iframe contract requires
172
+ // both an access token and a session id; anything less is unusable.
173
+ // Returning `null` here (without installing the token) prevents a
174
+ // stale credential from being committed to HttpService when the
175
+ // user is actually signed out — that pattern caused a `getCurrentUser`
176
+ // -> 401 -> token-clear loop in consumer apps because callers gated
177
+ // on `session?.user` and never installed the user via
178
+ // `handleAuthSuccess`, while HttpService quietly held the token.
179
+ const accessToken = session ? session.accessToken : undefined;
180
+ if (!session || !accessToken || !session.sessionId) {
181
+ return null;
182
+ }
183
+ // Snapshot the previous token so we can roll back if the user
184
+ // lookup below fails — this avoids leaving a half-committed session
185
+ // (token installed, user missing) which would let the next
186
+ // authenticated request 401 with no way to recover.
187
+ const previousAccessToken = this.httpService.getAccessToken();
188
+ this.httpService.setTokens(accessToken);
189
+ // The iframe typically returns `{ sessionId, accessToken }` without
190
+ // user data. Fetch the user explicitly so callers receive a
191
+ // fully-formed session and never need a second `/users/me` round
192
+ // trip. If this fails the session is unusable — revert the token
193
+ // and return null so the caller treats this exactly like a
194
+ // missing-session response.
195
+ if (!session.user) {
196
+ try {
197
+ const userData = await this.makeRequest('GET', `/session/user/${session.sessionId}`, undefined, { cache: false, retry: false });
198
+ if (!userData) {
199
+ throw new Error('Empty user response');
200
+ }
201
+ session.user = userData;
202
+ }
203
+ catch (userError) {
204
+ debug.warn('silentSignIn: failed to fetch user data, rolling back token', userError);
205
+ if (previousAccessToken) {
206
+ this.httpService.setTokens(previousAccessToken);
207
+ }
208
+ else {
209
+ this.httpService.clearTokens();
210
+ }
211
+ return null;
212
+ }
173
213
  }
174
214
  return session;
175
215
  }