@oxyhq/core 2.4.1 → 3.1.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.
@@ -0,0 +1,531 @@
1
+ /**
2
+ * Applications Methods Mixin
3
+ *
4
+ * Provides methods for managing Oxy applications, their members, and their
5
+ * credentials via the `/applications` API. An application is a multi-user
6
+ * entity: membership (with a role) grants permissions; credentials
7
+ * (public/confidential/service) carry OAuth client identifiers and the
8
+ * service-token API key material.
9
+ *
10
+ * Reference applications by their Mongo `_id` (`applicationId`) and credentials
11
+ * by their `credentialId`. Never by name.
12
+ */
13
+ import type { OxyServicesBase } from '../OxyServices.base';
14
+ import { CACHE_TIMES } from './mixinHelpers';
15
+
16
+ /**
17
+ * Application classification. Set only by Oxy platform staff — never editable
18
+ * through the normal member-facing update path.
19
+ */
20
+ export type ApplicationType = 'first_party' | 'third_party' | 'internal' | 'system';
21
+
22
+ /** Lifecycle status of an application. */
23
+ export type ApplicationStatus = 'active' | 'suspended' | 'deleted' | 'pending_review';
24
+
25
+ /** Role a member holds within an application. */
26
+ export type ApplicationRole = 'owner' | 'admin' | 'developer' | 'viewer' | 'billing';
27
+
28
+ /** Membership lifecycle status. */
29
+ export type ApplicationMemberStatus = 'active' | 'invited' | 'removed';
30
+
31
+ /** Credential kind. `service` credentials mint service tokens. */
32
+ export type ApplicationCredentialType = 'public' | 'confidential' | 'service';
33
+
34
+ /** Deployment environment a credential is scoped to. */
35
+ export type ApplicationEnvironment = 'development' | 'staging' | 'production';
36
+
37
+ /** Credential lifecycle status. */
38
+ export type ApplicationCredentialStatus = 'active' | 'deprecated' | 'revoked';
39
+
40
+ /**
41
+ * Client-facing Application shape returned by the `/applications` API.
42
+ * Mirrors the server `Application` model with `_id` as a string and dates
43
+ * serialized to ISO strings.
44
+ */
45
+ export interface Application {
46
+ _id: string;
47
+ name: string;
48
+ description?: string;
49
+ websiteUrl?: string;
50
+ icon?: string;
51
+ type: ApplicationType;
52
+ status: ApplicationStatus;
53
+ isOfficial: boolean;
54
+ isInternal: boolean;
55
+ capabilities: string[];
56
+ redirectUris: string[];
57
+ scopes: string[];
58
+ webhookUrl?: string;
59
+ devWebhookUrl?: string;
60
+ createdByUserId: string;
61
+ createdAt: string;
62
+ updatedAt: string;
63
+ /**
64
+ * The calling user's own membership in this application, embedded by the API
65
+ * on list (`GET /applications`) and detail (`GET /applications/:appId`)
66
+ * responses. Use `callerMembership.permissions` to gate UI affordances.
67
+ */
68
+ callerMembership?: ApplicationMember;
69
+ }
70
+
71
+ /**
72
+ * Client-facing ApplicationMember shape. `permissions` is derived from `role`
73
+ * on the server at write time.
74
+ */
75
+ export interface ApplicationMember {
76
+ _id: string;
77
+ applicationId: string;
78
+ userId: string;
79
+ role: ApplicationRole;
80
+ permissions: string[];
81
+ invitedByUserId?: string;
82
+ joinedAt?: string;
83
+ status: ApplicationMemberStatus;
84
+ createdAt: string;
85
+ updatedAt: string;
86
+ }
87
+
88
+ /**
89
+ * Client-facing ApplicationCredential shape. The raw secret is NEVER part of
90
+ * this shape — it is returned exactly once, separately, at creation/rotation.
91
+ */
92
+ export interface ApplicationCredential {
93
+ _id: string;
94
+ applicationId: string;
95
+ name: string;
96
+ publicKey: string;
97
+ type: ApplicationCredentialType;
98
+ environment: ApplicationEnvironment;
99
+ scopes: string[];
100
+ status: ApplicationCredentialStatus;
101
+ lastUsedAt?: string;
102
+ expiresAt?: string;
103
+ /**
104
+ * Audit link to the credential this one was rotated FROM. Populated by the
105
+ * API on credentials created via rotation; absent on original credentials.
106
+ */
107
+ rotatedFromCredentialId?: string;
108
+ createdByUserId: string;
109
+ createdAt: string;
110
+ updatedAt: string;
111
+ }
112
+
113
+ /** Input accepted by `createApplication`. Staff-only fields are not settable here. */
114
+ export interface CreateApplicationInput {
115
+ name: string;
116
+ description?: string;
117
+ websiteUrl?: string;
118
+ icon?: string;
119
+ redirectUris?: string[];
120
+ scopes?: string[];
121
+ }
122
+
123
+ /** Input accepted by `updateApplication`. Staff-only fields are not settable here. */
124
+ export interface UpdateApplicationInput {
125
+ name?: string;
126
+ description?: string;
127
+ websiteUrl?: string;
128
+ icon?: string;
129
+ redirectUris?: string[];
130
+ scopes?: string[];
131
+ webhookUrl?: string;
132
+ devWebhookUrl?: string;
133
+ status?: ApplicationStatus;
134
+ }
135
+
136
+ /** Input accepted by `inviteApplicationMember`. The owner role cannot be invited. */
137
+ export interface InviteApplicationMemberInput {
138
+ userId: string;
139
+ role: Exclude<ApplicationRole, 'owner'>;
140
+ }
141
+
142
+ /** Input accepted by `updateApplicationMember`. */
143
+ export interface UpdateApplicationMemberInput {
144
+ role: ApplicationRole;
145
+ }
146
+
147
+ /** Input accepted by `transferApplicationOwnership`. */
148
+ export interface TransferApplicationOwnershipInput {
149
+ userId: string;
150
+ }
151
+
152
+ /** Input accepted by `createApplicationCredential`. */
153
+ export interface CreateApplicationCredentialInput {
154
+ name: string;
155
+ type: ApplicationCredentialType;
156
+ environment: ApplicationEnvironment;
157
+ scopes?: string[];
158
+ }
159
+
160
+ /** Result of creating a credential — `secret` is returned ONCE. */
161
+ export interface ApplicationCredentialWithSecret {
162
+ credential: ApplicationCredential;
163
+ secret: string;
164
+ }
165
+
166
+ /**
167
+ * Result of rotating a credential. Extends the create result with audit fields:
168
+ * the new plaintext `secret` is returned ONCE, plus `rotatedFrom` (the previous
169
+ * credential's `credentialId`) and `graceExpiresAt` (ISO string marking when the
170
+ * old credential stops being honoured during the rotation grace window).
171
+ */
172
+ export interface RotateApplicationCredentialResult extends ApplicationCredentialWithSecret {
173
+ /** The previous credential's `credentialId` that this rotation supersedes. */
174
+ rotatedFrom: string;
175
+ /** ISO timestamp at which the rotated-from credential's grace window ends. */
176
+ graceExpiresAt: string;
177
+ }
178
+
179
+ /** Time window for application usage statistics. */
180
+ export type ApplicationUsagePeriod = '24h' | '7d' | '30d' | '90d';
181
+
182
+ /** Aggregate totals for an application over the requested period. */
183
+ export interface ApplicationUsageSummary {
184
+ totalRequests: number;
185
+ totalTokens: number;
186
+ totalCredits: number;
187
+ avgResponseTime: number;
188
+ successfulRequests: number;
189
+ errorRequests: number;
190
+ }
191
+
192
+ /** Per-day usage bucket. `_id` is the day key (e.g. `YYYY-MM-DD`). */
193
+ export interface ApplicationUsageByDay {
194
+ _id: string;
195
+ requests: number;
196
+ tokens: number;
197
+ credits: number;
198
+ }
199
+
200
+ /** Per-endpoint usage bucket. `_id` is the endpoint identifier. */
201
+ export interface ApplicationUsageByEndpoint {
202
+ _id: string;
203
+ requests: number;
204
+ tokens: number;
205
+ }
206
+
207
+ /** Usage statistics for an application over a period. */
208
+ export interface ApplicationUsageStats {
209
+ summary: ApplicationUsageSummary;
210
+ byDay: ApplicationUsageByDay[];
211
+ byEndpoint: ApplicationUsageByEndpoint[];
212
+ }
213
+
214
+ /** Result of a delete/remove/revoke/transfer operation. */
215
+ export interface ApplicationSuccessResult {
216
+ success: boolean;
217
+ }
218
+
219
+ export function OxyServicesApplicationsMixin<T extends typeof OxyServicesBase>(Base: T) {
220
+ return class extends Base {
221
+ constructor(...args: any[]) {
222
+ super(...(args as [any]));
223
+ }
224
+
225
+ /**
226
+ * List applications the current user is an active member of.
227
+ */
228
+ async getApplications(): Promise<Application[]> {
229
+ try {
230
+ const res = await this.makeRequest<{ applications?: Application[] }>(
231
+ 'GET',
232
+ '/applications',
233
+ undefined,
234
+ { cache: true, cacheTTL: CACHE_TIMES.MEDIUM },
235
+ );
236
+ return res.applications ?? [];
237
+ } catch (error) {
238
+ throw this.handleError(error);
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Create a new application. The caller becomes its `owner`.
244
+ * @param data - Application configuration. Staff-only fields are ignored.
245
+ */
246
+ async createApplication(data: CreateApplicationInput): Promise<Application> {
247
+ try {
248
+ const res = await this.makeRequest<{ application: Application }>(
249
+ 'POST',
250
+ '/applications',
251
+ data,
252
+ { cache: false },
253
+ );
254
+ return res.application;
255
+ } catch (error) {
256
+ throw this.handleError(error);
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Fetch a single application by id.
262
+ * @param applicationId - The application's Mongo `_id`.
263
+ */
264
+ async getApplication(applicationId: string): Promise<Application> {
265
+ try {
266
+ const res = await this.makeRequest<{ application: Application }>(
267
+ 'GET',
268
+ `/applications/${applicationId}`,
269
+ undefined,
270
+ { cache: true, cacheTTL: CACHE_TIMES.LONG },
271
+ );
272
+ return res.application;
273
+ } catch (error) {
274
+ throw this.handleError(error);
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Update an application's mutable fields.
280
+ * @param applicationId - The application's Mongo `_id`.
281
+ * @param data - Subset of updatable fields. Staff-only fields are ignored.
282
+ */
283
+ async updateApplication(
284
+ applicationId: string,
285
+ data: UpdateApplicationInput,
286
+ ): Promise<Application> {
287
+ try {
288
+ const res = await this.makeRequest<{ application: Application }>(
289
+ 'PATCH',
290
+ `/applications/${applicationId}`,
291
+ data,
292
+ { cache: false },
293
+ );
294
+ return res.application;
295
+ } catch (error) {
296
+ throw this.handleError(error);
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Soft-delete an application (owner only).
302
+ * @param applicationId - The application's Mongo `_id`.
303
+ */
304
+ async deleteApplication(applicationId: string): Promise<ApplicationSuccessResult> {
305
+ try {
306
+ return await this.makeRequest<ApplicationSuccessResult>(
307
+ 'DELETE',
308
+ `/applications/${applicationId}`,
309
+ undefined,
310
+ { cache: false },
311
+ );
312
+ } catch (error) {
313
+ throw this.handleError(error);
314
+ }
315
+ }
316
+
317
+ /**
318
+ * List members of an application.
319
+ * @param applicationId - The application's Mongo `_id`.
320
+ */
321
+ async getApplicationMembers(applicationId: string): Promise<ApplicationMember[]> {
322
+ try {
323
+ const res = await this.makeRequest<{ members?: ApplicationMember[] }>(
324
+ 'GET',
325
+ `/applications/${applicationId}/members`,
326
+ undefined,
327
+ { cache: true, cacheTTL: CACHE_TIMES.MEDIUM },
328
+ );
329
+ return res.members ?? [];
330
+ } catch (error) {
331
+ throw this.handleError(error);
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Add a member to an application.
337
+ * @param applicationId - The application's Mongo `_id`.
338
+ * @param data - Target user id and role (never `owner`).
339
+ */
340
+ async inviteApplicationMember(
341
+ applicationId: string,
342
+ data: InviteApplicationMemberInput,
343
+ ): Promise<ApplicationMember> {
344
+ try {
345
+ const res = await this.makeRequest<{ member: ApplicationMember }>(
346
+ 'POST',
347
+ `/applications/${applicationId}/members`,
348
+ data,
349
+ { cache: false },
350
+ );
351
+ return res.member;
352
+ } catch (error) {
353
+ throw this.handleError(error);
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Change a member's role.
359
+ * @param applicationId - The application's Mongo `_id`.
360
+ * @param memberId - The member's Mongo `_id`.
361
+ * @param data - New role.
362
+ */
363
+ async updateApplicationMember(
364
+ applicationId: string,
365
+ memberId: string,
366
+ data: UpdateApplicationMemberInput,
367
+ ): Promise<ApplicationMember> {
368
+ try {
369
+ const res = await this.makeRequest<{ member: ApplicationMember }>(
370
+ 'PATCH',
371
+ `/applications/${applicationId}/members/${memberId}`,
372
+ data,
373
+ { cache: false },
374
+ );
375
+ return res.member;
376
+ } catch (error) {
377
+ throw this.handleError(error);
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Remove a member from an application.
383
+ * @param applicationId - The application's Mongo `_id`.
384
+ * @param memberId - The member's Mongo `_id`.
385
+ */
386
+ async removeApplicationMember(
387
+ applicationId: string,
388
+ memberId: string,
389
+ ): Promise<ApplicationSuccessResult> {
390
+ try {
391
+ return await this.makeRequest<ApplicationSuccessResult>(
392
+ 'DELETE',
393
+ `/applications/${applicationId}/members/${memberId}`,
394
+ undefined,
395
+ { cache: false },
396
+ );
397
+ } catch (error) {
398
+ throw this.handleError(error);
399
+ }
400
+ }
401
+
402
+ /**
403
+ * Transfer ownership of an application to another member (owner only).
404
+ * Demotes the current owner to `admin` and promotes the target to `owner`.
405
+ * @param applicationId - The application's Mongo `_id`.
406
+ * @param data - Target user id.
407
+ */
408
+ async transferApplicationOwnership(
409
+ applicationId: string,
410
+ data: TransferApplicationOwnershipInput,
411
+ ): Promise<ApplicationSuccessResult> {
412
+ try {
413
+ return await this.makeRequest<ApplicationSuccessResult>(
414
+ 'POST',
415
+ `/applications/${applicationId}/transfer-ownership`,
416
+ data,
417
+ { cache: false },
418
+ );
419
+ } catch (error) {
420
+ throw this.handleError(error);
421
+ }
422
+ }
423
+
424
+ /**
425
+ * List an application's credentials. The response NEVER includes secrets.
426
+ * @param applicationId - The application's Mongo `_id`.
427
+ */
428
+ async getApplicationCredentials(applicationId: string): Promise<ApplicationCredential[]> {
429
+ try {
430
+ const res = await this.makeRequest<{ credentials?: ApplicationCredential[] }>(
431
+ 'GET',
432
+ `/applications/${applicationId}/credentials`,
433
+ undefined,
434
+ { cache: true, cacheTTL: CACHE_TIMES.MEDIUM },
435
+ );
436
+ return res.credentials ?? [];
437
+ } catch (error) {
438
+ throw this.handleError(error);
439
+ }
440
+ }
441
+
442
+ /**
443
+ * Create a credential. The plaintext `secret` is returned exactly ONCE;
444
+ * the server stores only a hash and will never return it again.
445
+ * @param applicationId - The application's Mongo `_id`.
446
+ * @param data - Credential configuration.
447
+ */
448
+ async createApplicationCredential(
449
+ applicationId: string,
450
+ data: CreateApplicationCredentialInput,
451
+ ): Promise<ApplicationCredentialWithSecret> {
452
+ try {
453
+ return await this.makeRequest<ApplicationCredentialWithSecret>(
454
+ 'POST',
455
+ `/applications/${applicationId}/credentials`,
456
+ data,
457
+ { cache: false },
458
+ );
459
+ } catch (error) {
460
+ throw this.handleError(error);
461
+ }
462
+ }
463
+
464
+ /**
465
+ * Rotate a credential's secret. The new plaintext `secret` is returned
466
+ * exactly ONCE, along with audit fields: `rotatedFrom` (the previous
467
+ * credentialId) and `graceExpiresAt` (ISO string for the grace window during
468
+ * which the old credential is still honoured).
469
+ * @param applicationId - The application's Mongo `_id`.
470
+ * @param credentialId - The credential's Mongo `_id`.
471
+ */
472
+ async rotateApplicationCredential(
473
+ applicationId: string,
474
+ credentialId: string,
475
+ ): Promise<RotateApplicationCredentialResult> {
476
+ try {
477
+ return await this.makeRequest<RotateApplicationCredentialResult>(
478
+ 'POST',
479
+ `/applications/${applicationId}/credentials/${credentialId}/rotate`,
480
+ undefined,
481
+ { cache: false },
482
+ );
483
+ } catch (error) {
484
+ throw this.handleError(error);
485
+ }
486
+ }
487
+
488
+ /**
489
+ * Revoke a credential (`status='revoked'`). Revoked credentials can no
490
+ * longer authenticate.
491
+ * @param applicationId - The application's Mongo `_id`.
492
+ * @param credentialId - The credential's Mongo `_id`.
493
+ */
494
+ async revokeApplicationCredential(
495
+ applicationId: string,
496
+ credentialId: string,
497
+ ): Promise<ApplicationSuccessResult> {
498
+ try {
499
+ return await this.makeRequest<ApplicationSuccessResult>(
500
+ 'DELETE',
501
+ `/applications/${applicationId}/credentials/${credentialId}`,
502
+ undefined,
503
+ { cache: false },
504
+ );
505
+ } catch (error) {
506
+ throw this.handleError(error);
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Fetch usage statistics for an application.
512
+ * @param applicationId - The application's Mongo `_id`.
513
+ * @param period - Time window (defaults to the server default).
514
+ */
515
+ async getApplicationUsage(
516
+ applicationId: string,
517
+ period?: ApplicationUsagePeriod,
518
+ ): Promise<ApplicationUsageStats> {
519
+ try {
520
+ return await this.makeRequest<ApplicationUsageStats>(
521
+ 'GET',
522
+ `/applications/${applicationId}/usage`,
523
+ period ? { period } : undefined,
524
+ { cache: true, cacheTTL: CACHE_TIMES.SHORT },
525
+ );
526
+ } catch (error) {
527
+ throw this.handleError(error);
528
+ }
529
+ }
530
+ };
531
+ }
@@ -157,8 +157,8 @@ export function OxyServicesAuthMixin<T extends typeof OxyServicesBase>(Base: T)
157
157
  * legitimate multi-tenant hosts that need to switch credentials cannot leak
158
158
  * one tenant's token to another tenant on the same instance.
159
159
  *
160
- * @param apiKey - DeveloperApp API key (oxy_dk_*)
161
- * @param apiSecret - DeveloperApp API secret
160
+ * @param apiKey - Application credential public key (oxy_dk_*)
161
+ * @param apiSecret - Application credential secret
162
162
  */
163
163
  configureServiceAuth(apiKey: string, apiSecret: string): void {
164
164
  this._serviceApiKey = apiKey;
@@ -181,8 +181,8 @@ export function OxyServicesAuthMixin<T extends typeof OxyServicesBase>(Base: T)
181
181
  * This prevents an attacker who learned a peer's apiKey from extracting
182
182
  * their service token by polling with a wrong secret.
183
183
  *
184
- * @param apiKey - DeveloperApp API key (optional if configureServiceAuth was called)
185
- * @param apiSecret - DeveloperApp API secret (optional if configureServiceAuth was called)
184
+ * @param apiKey - Application credential public key (optional if configureServiceAuth was called)
185
+ * @param apiSecret - Application credential secret (optional if configureServiceAuth was called)
186
186
  */
187
187
  async getServiceToken(apiKey?: string, apiSecret?: string): Promise<string> {
188
188
  const key = apiKey || this._serviceApiKey;
@@ -18,6 +18,7 @@ interface JwtPayload {
18
18
  sessionId?: string;
19
19
  type?: string;
20
20
  appId?: string;
21
+ credentialId?: string;
21
22
  appName?: string;
22
23
  scopes?: string[];
23
24
  aud?: string | string[];
@@ -54,13 +55,20 @@ export interface ServiceActingAsVerification {
54
55
  /**
55
56
  * Service app metadata attached to requests authenticated with service tokens.
56
57
  * `scopes` reflects the scopes granted to the app at signup time (from the
57
- * `DeveloperApp.scopes` field); route-level checks can require additional
58
+ * `Application.scopes` field); route-level checks can require additional
58
59
  * scope-narrowing via `requireScope()`.
59
60
  */
60
61
  export interface ServiceApp {
61
62
  appId: string;
62
63
  appName: string;
63
64
  scopes: string[];
65
+ /**
66
+ * The credentialId of the specific service credential that minted this token.
67
+ * Carried by newer service-token JWTs alongside `appId`; absent on tokens
68
+ * issued before credential-level audit linking. Use for per-credential audit
69
+ * trails and rotation alignment (GitHub #215).
70
+ */
71
+ credentialId?: string;
64
72
  }
65
73
 
66
74
  /**
@@ -618,6 +626,9 @@ export function OxyServicesUtilityMixin<T extends typeof OxyServicesBase>(Base:
618
626
  appId,
619
627
  appName: decoded.appName || 'unknown',
620
628
  scopes: Array.isArray(decoded.scopes) ? decoded.scopes : [],
629
+ ...(typeof decoded.credentialId === 'string' && decoded.credentialId.length > 0
630
+ ? { credentialId: decoded.credentialId }
631
+ : {}),
621
632
  };
622
633
 
623
634
  if (debug) {
@@ -17,7 +17,7 @@ import { OxyServicesLanguageMixin } from './OxyServices.language';
17
17
  import { OxyServicesPaymentMixin } from './OxyServices.payment';
18
18
  import { OxyServicesKarmaMixin } from './OxyServices.karma';
19
19
  import { OxyServicesAssetsMixin } from './OxyServices.assets';
20
- import { OxyServicesDeveloperMixin } from './OxyServices.developer';
20
+ import { OxyServicesApplicationsMixin } from './OxyServices.applications';
21
21
  import { OxyServicesLocationMixin } from './OxyServices.location';
22
22
  import { OxyServicesAnalyticsMixin } from './OxyServices.analytics';
23
23
  import { OxyServicesDevicesMixin } from './OxyServices.devices';
@@ -50,7 +50,7 @@ type AllMixinInstances =
50
50
  & InstanceType<ReturnType<typeof OxyServicesPaymentMixin<typeof OxyServicesBase>>>
51
51
  & InstanceType<ReturnType<typeof OxyServicesKarmaMixin<typeof OxyServicesBase>>>
52
52
  & InstanceType<ReturnType<typeof OxyServicesAssetsMixin<typeof OxyServicesBase>>>
53
- & InstanceType<ReturnType<typeof OxyServicesDeveloperMixin<typeof OxyServicesBase>>>
53
+ & InstanceType<ReturnType<typeof OxyServicesApplicationsMixin<typeof OxyServicesBase>>>
54
54
  & InstanceType<ReturnType<typeof OxyServicesLocationMixin<typeof OxyServicesBase>>>
55
55
  & InstanceType<ReturnType<typeof OxyServicesAnalyticsMixin<typeof OxyServicesBase>>>
56
56
  & InstanceType<ReturnType<typeof OxyServicesDevicesMixin<typeof OxyServicesBase>>>
@@ -114,7 +114,7 @@ const MIXIN_PIPELINE: MixinFunction[] = [
114
114
  OxyServicesPaymentMixin,
115
115
  OxyServicesKarmaMixin,
116
116
  OxyServicesAssetsMixin,
117
- OxyServicesDeveloperMixin,
117
+ OxyServicesApplicationsMixin,
118
118
  OxyServicesLocationMixin,
119
119
  OxyServicesAnalyticsMixin,
120
120
  OxyServicesDevicesMixin,