@oxyhq/core 2.4.0 → 3.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.
Files changed (35) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/OxyServices.js +1 -1
  3. package/dist/cjs/mixins/OxyServices.applications.js +212 -0
  4. package/dist/cjs/mixins/OxyServices.auth.js +4 -4
  5. package/dist/cjs/mixins/OxyServices.fedcm.js +52 -2
  6. package/dist/cjs/mixins/index.js +2 -2
  7. package/dist/cjs/utils/coldBoot.js +66 -17
  8. package/dist/esm/.tsbuildinfo +1 -1
  9. package/dist/esm/OxyServices.js +1 -1
  10. package/dist/esm/mixins/OxyServices.applications.js +209 -0
  11. package/dist/esm/mixins/OxyServices.auth.js +4 -4
  12. package/dist/esm/mixins/OxyServices.fedcm.js +52 -2
  13. package/dist/esm/mixins/index.js +2 -2
  14. package/dist/esm/utils/coldBoot.js +66 -17
  15. package/dist/types/.tsbuildinfo +1 -1
  16. package/dist/types/OxyServices.d.ts +1 -1
  17. package/dist/types/index.d.ts +1 -0
  18. package/dist/types/mixins/OxyServices.applications.d.ts +317 -0
  19. package/dist/types/mixins/OxyServices.auth.d.ts +4 -4
  20. package/dist/types/mixins/OxyServices.fedcm.d.ts +1 -0
  21. package/dist/types/mixins/OxyServices.utility.d.ts +1 -1
  22. package/dist/types/mixins/index.d.ts +2 -2
  23. package/dist/types/utils/coldBoot.d.ts +26 -0
  24. package/package.json +1 -1
  25. package/src/OxyServices.ts +1 -1
  26. package/src/index.ts +29 -0
  27. package/src/mixins/OxyServices.applications.ts +511 -0
  28. package/src/mixins/OxyServices.auth.ts +4 -4
  29. package/src/mixins/OxyServices.fedcm.ts +56 -2
  30. package/src/mixins/OxyServices.utility.ts +1 -1
  31. package/src/mixins/__tests__/fedcm.test.ts +52 -0
  32. package/src/mixins/index.ts +3 -3
  33. package/src/utils/__tests__/coldBoot.test.ts +150 -0
  34. package/src/utils/coldBoot.ts +96 -17
  35. package/src/mixins/OxyServices.developer.ts +0 -114
@@ -20,7 +20,7 @@ import { composeOxyServices } from './mixins/index.js';
20
20
  * - **Payment**: Payment processing
21
21
  * - **Karma**: Karma system
22
22
  * - **Assets**: File upload and asset management
23
- * - **Developer**: Developer API management
23
+ * - **Applications**: Application, membership, and credential management
24
24
  * - **Location**: Location-based features
25
25
  * - **Analytics**: Analytics tracking
26
26
  * - **Devices**: Device management
@@ -0,0 +1,209 @@
1
+ import { CACHE_TIMES } from './mixinHelpers.js';
2
+ export function OxyServicesApplicationsMixin(Base) {
3
+ return class extends Base {
4
+ constructor(...args) {
5
+ super(...args);
6
+ }
7
+ /**
8
+ * List applications the current user is an active member of.
9
+ */
10
+ async getApplications() {
11
+ try {
12
+ const res = await this.makeRequest('GET', '/applications', undefined, { cache: true, cacheTTL: CACHE_TIMES.MEDIUM });
13
+ return res.applications ?? [];
14
+ }
15
+ catch (error) {
16
+ throw this.handleError(error);
17
+ }
18
+ }
19
+ /**
20
+ * Create a new application. The caller becomes its `owner`.
21
+ * @param data - Application configuration. Staff-only fields are ignored.
22
+ */
23
+ async createApplication(data) {
24
+ try {
25
+ const res = await this.makeRequest('POST', '/applications', data, { cache: false });
26
+ return res.application;
27
+ }
28
+ catch (error) {
29
+ throw this.handleError(error);
30
+ }
31
+ }
32
+ /**
33
+ * Fetch a single application by id.
34
+ * @param applicationId - The application's Mongo `_id`.
35
+ */
36
+ async getApplication(applicationId) {
37
+ try {
38
+ const res = await this.makeRequest('GET', `/applications/${applicationId}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.LONG });
39
+ return res.application;
40
+ }
41
+ catch (error) {
42
+ throw this.handleError(error);
43
+ }
44
+ }
45
+ /**
46
+ * Update an application's mutable fields.
47
+ * @param applicationId - The application's Mongo `_id`.
48
+ * @param data - Subset of updatable fields. Staff-only fields are ignored.
49
+ */
50
+ async updateApplication(applicationId, data) {
51
+ try {
52
+ const res = await this.makeRequest('PATCH', `/applications/${applicationId}`, data, { cache: false });
53
+ return res.application;
54
+ }
55
+ catch (error) {
56
+ throw this.handleError(error);
57
+ }
58
+ }
59
+ /**
60
+ * Soft-delete an application (owner only).
61
+ * @param applicationId - The application's Mongo `_id`.
62
+ */
63
+ async deleteApplication(applicationId) {
64
+ try {
65
+ return await this.makeRequest('DELETE', `/applications/${applicationId}`, undefined, { cache: false });
66
+ }
67
+ catch (error) {
68
+ throw this.handleError(error);
69
+ }
70
+ }
71
+ /**
72
+ * List members of an application.
73
+ * @param applicationId - The application's Mongo `_id`.
74
+ */
75
+ async getApplicationMembers(applicationId) {
76
+ try {
77
+ const res = await this.makeRequest('GET', `/applications/${applicationId}/members`, undefined, { cache: true, cacheTTL: CACHE_TIMES.MEDIUM });
78
+ return res.members ?? [];
79
+ }
80
+ catch (error) {
81
+ throw this.handleError(error);
82
+ }
83
+ }
84
+ /**
85
+ * Add a member to an application.
86
+ * @param applicationId - The application's Mongo `_id`.
87
+ * @param data - Target user id and role (never `owner`).
88
+ */
89
+ async inviteApplicationMember(applicationId, data) {
90
+ try {
91
+ const res = await this.makeRequest('POST', `/applications/${applicationId}/members`, data, { cache: false });
92
+ return res.member;
93
+ }
94
+ catch (error) {
95
+ throw this.handleError(error);
96
+ }
97
+ }
98
+ /**
99
+ * Change a member's role.
100
+ * @param applicationId - The application's Mongo `_id`.
101
+ * @param memberId - The member's Mongo `_id`.
102
+ * @param data - New role.
103
+ */
104
+ async updateApplicationMember(applicationId, memberId, data) {
105
+ try {
106
+ const res = await this.makeRequest('PATCH', `/applications/${applicationId}/members/${memberId}`, data, { cache: false });
107
+ return res.member;
108
+ }
109
+ catch (error) {
110
+ throw this.handleError(error);
111
+ }
112
+ }
113
+ /**
114
+ * Remove a member from an application.
115
+ * @param applicationId - The application's Mongo `_id`.
116
+ * @param memberId - The member's Mongo `_id`.
117
+ */
118
+ async removeApplicationMember(applicationId, memberId) {
119
+ try {
120
+ return await this.makeRequest('DELETE', `/applications/${applicationId}/members/${memberId}`, undefined, { cache: false });
121
+ }
122
+ catch (error) {
123
+ throw this.handleError(error);
124
+ }
125
+ }
126
+ /**
127
+ * Transfer ownership of an application to another member (owner only).
128
+ * Demotes the current owner to `admin` and promotes the target to `owner`.
129
+ * @param applicationId - The application's Mongo `_id`.
130
+ * @param data - Target user id.
131
+ */
132
+ async transferApplicationOwnership(applicationId, data) {
133
+ try {
134
+ return await this.makeRequest('POST', `/applications/${applicationId}/transfer-ownership`, data, { cache: false });
135
+ }
136
+ catch (error) {
137
+ throw this.handleError(error);
138
+ }
139
+ }
140
+ /**
141
+ * List an application's credentials. The response NEVER includes secrets.
142
+ * @param applicationId - The application's Mongo `_id`.
143
+ */
144
+ async getApplicationCredentials(applicationId) {
145
+ try {
146
+ const res = await this.makeRequest('GET', `/applications/${applicationId}/credentials`, undefined, { cache: true, cacheTTL: CACHE_TIMES.MEDIUM });
147
+ return res.credentials ?? [];
148
+ }
149
+ catch (error) {
150
+ throw this.handleError(error);
151
+ }
152
+ }
153
+ /**
154
+ * Create a credential. The plaintext `secret` is returned exactly ONCE;
155
+ * the server stores only a hash and will never return it again.
156
+ * @param applicationId - The application's Mongo `_id`.
157
+ * @param data - Credential configuration.
158
+ */
159
+ async createApplicationCredential(applicationId, data) {
160
+ try {
161
+ return await this.makeRequest('POST', `/applications/${applicationId}/credentials`, data, { cache: false });
162
+ }
163
+ catch (error) {
164
+ throw this.handleError(error);
165
+ }
166
+ }
167
+ /**
168
+ * Rotate a credential's secret. The new plaintext `secret` is returned
169
+ * exactly ONCE.
170
+ * @param applicationId - The application's Mongo `_id`.
171
+ * @param credentialId - The credential's Mongo `_id`.
172
+ */
173
+ async rotateApplicationCredential(applicationId, credentialId) {
174
+ try {
175
+ return await this.makeRequest('POST', `/applications/${applicationId}/credentials/${credentialId}/rotate`, undefined, { cache: false });
176
+ }
177
+ catch (error) {
178
+ throw this.handleError(error);
179
+ }
180
+ }
181
+ /**
182
+ * Revoke a credential (`status='revoked'`). Revoked credentials can no
183
+ * longer authenticate.
184
+ * @param applicationId - The application's Mongo `_id`.
185
+ * @param credentialId - The credential's Mongo `_id`.
186
+ */
187
+ async revokeApplicationCredential(applicationId, credentialId) {
188
+ try {
189
+ return await this.makeRequest('DELETE', `/applications/${applicationId}/credentials/${credentialId}`, undefined, { cache: false });
190
+ }
191
+ catch (error) {
192
+ throw this.handleError(error);
193
+ }
194
+ }
195
+ /**
196
+ * Fetch usage statistics for an application.
197
+ * @param applicationId - The application's Mongo `_id`.
198
+ * @param period - Time window (defaults to the server default).
199
+ */
200
+ async getApplicationUsage(applicationId, period) {
201
+ try {
202
+ return await this.makeRequest('GET', `/applications/${applicationId}/usage`, period ? { period } : undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
203
+ }
204
+ catch (error) {
205
+ throw this.handleError(error);
206
+ }
207
+ }
208
+ };
209
+ }
@@ -60,8 +60,8 @@ export function OxyServicesAuthMixin(Base) {
60
60
  * legitimate multi-tenant hosts that need to switch credentials cannot leak
61
61
  * one tenant's token to another tenant on the same instance.
62
62
  *
63
- * @param apiKey - DeveloperApp API key (oxy_dk_*)
64
- * @param apiSecret - DeveloperApp API secret
63
+ * @param apiKey - Application credential public key (oxy_dk_*)
64
+ * @param apiSecret - Application credential secret
65
65
  */
66
66
  configureServiceAuth(apiKey, apiSecret) {
67
67
  this._serviceApiKey = apiKey;
@@ -83,8 +83,8 @@ export function OxyServicesAuthMixin(Base) {
83
83
  * This prevents an attacker who learned a peer's apiKey from extracting
84
84
  * their service token by polling with a wrong secret.
85
85
  *
86
- * @param apiKey - DeveloperApp API key (optional if configureServiceAuth was called)
87
- * @param apiSecret - DeveloperApp API secret (optional if configureServiceAuth was called)
86
+ * @param apiKey - Application credential public key (optional if configureServiceAuth was called)
87
+ * @param apiSecret - Application credential secret (optional if configureServiceAuth was called)
88
88
  */
89
89
  async getServiceToken(apiKey, apiSecret) {
90
90
  const key = apiKey || this._serviceApiKey;
@@ -441,6 +441,34 @@ export function OxyServicesFedCMMixin(Base) {
441
441
  debug.log('Request timed out after', timeoutMs, 'ms (mediation:', requestedMediation + ')');
442
442
  controller.abort();
443
443
  }, timeoutMs);
444
+ // Hard settle guarantee for the timeout path.
445
+ //
446
+ // The `setTimeout` above aborts the request's `AbortController`, which is
447
+ // the COOPERATIVE cancel signal. For a regular `fetch` an abort deterministically
448
+ // rejects the awaited promise — but `navigator.credentials.get()` is a
449
+ // browser-internal FedCM primitive whose abort behaviour is NOT guaranteed
450
+ // to settle the awaited promise in every Chrome version / internal state
451
+ // (the credential request can sit "pending" while the browser-side flow is
452
+ // stuck, ignoring the signal). If that happens, `await credentials.get(...)`
453
+ // never resolves OR rejects, this IIFE hangs forever, and — because this is
454
+ // ONE step of the ordered cold-boot sequence — the whole cold boot hangs and
455
+ // the terminal `/sso` bounce never fires. That was the production hang.
456
+ //
457
+ // `settlePromise` races the credential lookup against a timer that ALWAYS
458
+ // resolves to `null` shortly after the abort deadline. The abort still fires
459
+ // first (so the browser is asked to cancel), but even if `credentials.get`
460
+ // never settles, the race resolves and the step falls through cleanly to the
461
+ // next cold-boot step. The small `FEDCM_ABORT_SETTLE_GRACE_MS` margin gives a
462
+ // well-behaved browser the chance to surface its own AbortError (preserving
463
+ // the existing error path) before we force a clean `null`.
464
+ let settleTimer;
465
+ const settlePromise = new Promise((resolve) => {
466
+ const ctor = this.constructor;
467
+ settleTimer = setTimeout(() => {
468
+ debug.log('Request hard-settled to null', timeoutMs + ctor.FEDCM_ABORT_SETTLE_GRACE_MS, 'ms (credentials.get never settled after abort)');
469
+ resolve(null);
470
+ }, timeoutMs + ctor.FEDCM_ABORT_SETTLE_GRACE_MS);
471
+ });
444
472
  // Normalise the caller's mode to the modern W3C value first. A modern
445
473
  // browser accepts it; an older one (Chrome 125–131) rejects it with a
446
474
  // synchronous TypeError, in which case we retry with the legacy value.
@@ -477,7 +505,13 @@ export function OxyServicesFedCMMixin(Base) {
477
505
  debug.log('Calling navigator.credentials.get with mediation:', requestedMediation, modernMode ? `mode: ${modernMode}` : '');
478
506
  let credential;
479
507
  try {
480
- credential = await credentials.get(buildCredentialOptions(modernMode));
508
+ // Race the browser FedCM lookup against the hard settle guarantee so
509
+ // a `credentials.get` that ignores the abort signal can never hang
510
+ // the cold boot (see `settlePromise`).
511
+ credential = await Promise.race([
512
+ credentials.get(buildCredentialOptions(modernMode)),
513
+ settlePromise,
514
+ ]);
481
515
  }
482
516
  catch (modeError) {
483
517
  // Chrome 125–131 only knows the legacy 'button'/'widget' enum and
@@ -486,7 +520,10 @@ export function OxyServicesFedCMMixin(Base) {
486
520
  if (modernMode && isUnknownModeEnumError(modeError)) {
487
521
  const legacyMode = MODERN_TO_LEGACY_MODE[modernMode];
488
522
  debug.log(`Browser rejected modern mode '${modernMode}'; retrying with legacy mode '${legacyMode}'`);
489
- credential = await credentials.get(buildCredentialOptions(legacyMode));
523
+ credential = await Promise.race([
524
+ credentials.get(buildCredentialOptions(legacyMode)),
525
+ settlePromise,
526
+ ]);
490
527
  }
491
528
  else {
492
529
  throw modeError;
@@ -513,6 +550,9 @@ export function OxyServicesFedCMMixin(Base) {
513
550
  }
514
551
  finally {
515
552
  clearTimeout(timeout);
553
+ if (settleTimer !== undefined) {
554
+ clearTimeout(settleTimer);
555
+ }
516
556
  // Only reset the shared lock if it still belongs to THIS request. When an
517
557
  // interactive request aborts a slow silent one, the silent settles (and
518
558
  // runs this `finally`) AFTER the interactive has already taken over the
@@ -763,6 +803,16 @@ export function OxyServicesFedCMMixin(Base) {
763
803
  // 20-30s cold-boot stall. Do NOT lower below 4s (it would clip live success).
764
804
  _a.FEDCM_SILENT_TIMEOUT = 4000 // 4 seconds for silent mediation
765
805
  ,
806
+ // Grace margin between the cooperative abort deadline (`FEDCM_SILENT_TIMEOUT`
807
+ // / `FEDCM_TIMEOUT`) and the HARD settle of `requestIdentityCredential`. The
808
+ // abort fires first; a well-behaved browser surfaces its own `AbortError`
809
+ // within this window (keeping the existing error path intact). If — as seen
810
+ // in production — `navigator.credentials.get()` ignores the abort and the
811
+ // awaited promise never settles, the hard settle resolves the request to
812
+ // `null` this many ms later, guaranteeing the cold-boot step always settles.
813
+ // 500ms is ample for a browser to deliver an abort rejection while keeping the
814
+ // worst-case dead wait tight (silent: 4.5s, interactive: 15.5s).
815
+ _a.FEDCM_ABORT_SETTLE_GRACE_MS = 500,
766
816
  _a;
767
817
  }
768
818
  // Export the mixin function as both named and default
@@ -16,7 +16,7 @@ import { OxyServicesLanguageMixin } from './OxyServices.language.js';
16
16
  import { OxyServicesPaymentMixin } from './OxyServices.payment.js';
17
17
  import { OxyServicesKarmaMixin } from './OxyServices.karma.js';
18
18
  import { OxyServicesAssetsMixin } from './OxyServices.assets.js';
19
- import { OxyServicesDeveloperMixin } from './OxyServices.developer.js';
19
+ import { OxyServicesApplicationsMixin } from './OxyServices.applications.js';
20
20
  import { OxyServicesLocationMixin } from './OxyServices.location.js';
21
21
  import { OxyServicesAnalyticsMixin } from './OxyServices.analytics.js';
22
22
  import { OxyServicesDevicesMixin } from './OxyServices.devices.js';
@@ -60,7 +60,7 @@ const MIXIN_PIPELINE = [
60
60
  OxyServicesPaymentMixin,
61
61
  OxyServicesKarmaMixin,
62
62
  OxyServicesAssetsMixin,
63
- OxyServicesDeveloperMixin,
63
+ OxyServicesApplicationsMixin,
64
64
  OxyServicesLocationMixin,
65
65
  OxyServicesAnalyticsMixin,
66
66
  OxyServicesDevicesMixin,
@@ -22,6 +22,15 @@
22
22
  * `onStepError` and treated as a non-fatal skip, so one broken recovery path
23
23
  * can never prevent a later, healthy one from succeeding.
24
24
  */
25
+ /**
26
+ * The unique sentinel a step's `run()` resolves to (via the internal race)
27
+ * when the overall cold-boot deadline expires before that step settled. It is
28
+ * NOT a {@link ColdBootStepResult} — the runner detects it by identity and
29
+ * treats it as "this step did not settle in time; move on".
30
+ *
31
+ * @internal
32
+ */
33
+ const DEADLINE_EXPIRED = Symbol('coldBoot.deadlineExpired');
25
34
  /**
26
35
  * Run the ordered cold-boot steps and resolve to the first recovered session,
27
36
  * or `unauthenticated` if none recovers one.
@@ -38,31 +47,71 @@
38
47
  * 4. After the loop with no winner → `{ kind: 'unauthenticated' }`.
39
48
  */
40
49
  export async function runColdBoot(options) {
41
- const { steps, onStepError } = options;
42
- for (const step of steps) {
43
- if (step.enabled) {
44
- let isEnabled;
50
+ const { steps, onStepError, overallDeadlineMs, onStepDeadline } = options;
51
+ // Arm the optional overall deadline. The budget is SHARED across the whole
52
+ // loop (not reset per step): a single timer resolves a reusable
53
+ // `DEADLINE_EXPIRED` sentinel that every per-step race can observe. Once it
54
+ // fires, later steps race against an already-resolved promise and so never
55
+ // block, yet the loop keeps iterating so the terminal step still fires.
56
+ const deadlineMs = typeof overallDeadlineMs === 'number' &&
57
+ Number.isFinite(overallDeadlineMs) &&
58
+ overallDeadlineMs > 0
59
+ ? overallDeadlineMs
60
+ : null;
61
+ let deadlineTimer;
62
+ let deadlinePromise;
63
+ if (deadlineMs !== null) {
64
+ deadlinePromise = new Promise((resolve) => {
65
+ deadlineTimer = setTimeout(() => resolve(DEADLINE_EXPIRED), deadlineMs);
66
+ });
67
+ }
68
+ try {
69
+ for (const step of steps) {
70
+ if (step.enabled) {
71
+ let isEnabled;
72
+ try {
73
+ isEnabled = step.enabled();
74
+ }
75
+ catch (error) {
76
+ onStepError?.(step.id, error);
77
+ continue;
78
+ }
79
+ if (!isEnabled)
80
+ continue;
81
+ }
82
+ let result;
45
83
  try {
46
- isEnabled = step.enabled();
84
+ // Without a deadline: legacy behaviour — await the step directly.
85
+ // With a deadline: race the step against the shared deadline. The
86
+ // step's `run()` still STARTS synchronously up to its first `await`
87
+ // (so a terminal step's synchronous navigation side effect always
88
+ // executes), but a non-settling step can no longer block the loop —
89
+ // the race resolves with the sentinel and we move on.
90
+ result = deadlinePromise
91
+ ? await Promise.race([step.run(), deadlinePromise])
92
+ : await step.run();
47
93
  }
48
94
  catch (error) {
49
95
  onStepError?.(step.id, error);
50
96
  continue;
51
97
  }
52
- if (!isEnabled)
98
+ if (result === DEADLINE_EXPIRED) {
99
+ // The deadline tripped before this step settled. Abandon the await and
100
+ // continue: subsequent steps race against the already-resolved deadline
101
+ // (so they cannot block), which lets a terminal side-effect step still
102
+ // run while guaranteeing the loop terminates promptly.
103
+ onStepDeadline?.(step.id);
53
104
  continue;
105
+ }
106
+ if (result.kind === 'session') {
107
+ return { kind: 'session', via: step.id, session: result.session };
108
+ }
54
109
  }
55
- let result;
56
- try {
57
- result = await step.run();
58
- }
59
- catch (error) {
60
- onStepError?.(step.id, error);
61
- continue;
62
- }
63
- if (result.kind === 'session') {
64
- return { kind: 'session', via: step.id, session: result.session };
110
+ return { kind: 'unauthenticated' };
111
+ }
112
+ finally {
113
+ if (deadlineTimer !== undefined) {
114
+ clearTimeout(deadlineTimer);
65
115
  }
66
116
  }
67
- return { kind: 'unauthenticated' };
68
117
  }