@oxyhq/core 3.10.1 → 3.12.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 (92) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/AuthManager.js +9 -2
  3. package/dist/cjs/HttpService.js +27 -9
  4. package/dist/cjs/OxyServices.base.js +3 -2
  5. package/dist/cjs/crypto/canonicalJson.js +107 -0
  6. package/dist/cjs/crypto/keyManager.js +67 -8
  7. package/dist/cjs/crypto/signatureService.js +189 -0
  8. package/dist/cjs/index.js +30 -4
  9. package/dist/cjs/mixins/OxyServices.assets.js +16 -1
  10. package/dist/cjs/mixins/OxyServices.auth.js +190 -1
  11. package/dist/cjs/mixins/OxyServices.civic.js +611 -0
  12. package/dist/cjs/mixins/OxyServices.identity.js +291 -0
  13. package/dist/cjs/mixins/OxyServices.sso.js +28 -1
  14. package/dist/cjs/mixins/OxyServices.user.js +1 -0
  15. package/dist/cjs/mixins/index.js +6 -0
  16. package/dist/cjs/server/cors.js +20 -21
  17. package/dist/cjs/server/rateLimit.js +32 -8
  18. package/dist/cjs/utils/profileLinks.js +52 -0
  19. package/dist/cjs/utils/ssoReturn.js +1 -1
  20. package/dist/esm/.tsbuildinfo +1 -1
  21. package/dist/esm/AuthManager.js +9 -2
  22. package/dist/esm/HttpService.js +27 -9
  23. package/dist/esm/OxyServices.base.js +3 -2
  24. package/dist/esm/crypto/canonicalJson.js +104 -0
  25. package/dist/esm/crypto/keyManager.js +67 -8
  26. package/dist/esm/crypto/signatureService.js +187 -0
  27. package/dist/esm/index.js +19 -1
  28. package/dist/esm/mixins/OxyServices.assets.js +16 -1
  29. package/dist/esm/mixins/OxyServices.auth.js +190 -1
  30. package/dist/esm/mixins/OxyServices.civic.js +605 -0
  31. package/dist/esm/mixins/OxyServices.identity.js +287 -0
  32. package/dist/esm/mixins/OxyServices.sso.js +28 -1
  33. package/dist/esm/mixins/OxyServices.user.js +1 -0
  34. package/dist/esm/mixins/index.js +6 -0
  35. package/dist/esm/server/cors.js +20 -21
  36. package/dist/esm/server/rateLimit.js +32 -8
  37. package/dist/esm/utils/profileLinks.js +49 -0
  38. package/dist/esm/utils/ssoReturn.js +1 -1
  39. package/dist/types/.tsbuildinfo +1 -1
  40. package/dist/types/HttpService.d.ts +3 -0
  41. package/dist/types/OxyServices.d.ts +2 -2
  42. package/dist/types/crypto/canonicalJson.d.ts +44 -0
  43. package/dist/types/crypto/keyManager.d.ts +7 -0
  44. package/dist/types/crypto/signatureService.d.ts +112 -0
  45. package/dist/types/index.d.ts +10 -2
  46. package/dist/types/mixins/OxyServices.auth.d.ts +136 -0
  47. package/dist/types/mixins/OxyServices.civic.d.ts +512 -0
  48. package/dist/types/mixins/OxyServices.identity.d.ts +249 -0
  49. package/dist/types/mixins/OxyServices.sso.d.ts +4 -1
  50. package/dist/types/mixins/index.d.ts +3 -1
  51. package/dist/types/models/interfaces.d.ts +3 -0
  52. package/dist/types/server/cors.d.ts +5 -5
  53. package/dist/types/utils/profileLinks.d.ts +36 -0
  54. package/dist/types/utils/ssoReturn.d.ts +1 -1
  55. package/package.json +2 -2
  56. package/src/AuthManager.ts +8 -2
  57. package/src/HttpService.ts +36 -8
  58. package/src/OxyServices.base.ts +3 -2
  59. package/src/OxyServices.ts +1 -1
  60. package/src/__tests__/authManager.security.test.ts +31 -0
  61. package/src/__tests__/httpServiceCsrf.test.ts +75 -0
  62. package/src/crypto/__tests__/canonicalJson.test.ts +116 -0
  63. package/src/crypto/__tests__/keyManager.atomicity.test.ts +41 -2
  64. package/src/crypto/__tests__/signChallengeShared.test.ts +64 -0
  65. package/src/crypto/__tests__/signedRecord.test.ts +345 -0
  66. package/src/crypto/canonicalJson.ts +120 -0
  67. package/src/crypto/keyManager.ts +62 -12
  68. package/src/crypto/signatureService.ts +225 -0
  69. package/src/index.ts +55 -2
  70. package/src/mixins/OxyServices.assets.ts +16 -1
  71. package/src/mixins/OxyServices.auth.ts +309 -1
  72. package/src/mixins/OxyServices.civic.ts +956 -0
  73. package/src/mixins/OxyServices.identity.ts +445 -0
  74. package/src/mixins/OxyServices.sso.ts +30 -1
  75. package/src/mixins/OxyServices.user.ts +1 -0
  76. package/src/mixins/__tests__/OxyServices.civic.test.ts +1097 -0
  77. package/src/mixins/__tests__/OxyServices.identity.test.ts +364 -0
  78. package/src/mixins/__tests__/assetCredentials.test.ts +47 -0
  79. package/src/mixins/__tests__/commonsSignIn.test.ts +277 -0
  80. package/src/mixins/__tests__/serviceAuth.test.ts +19 -0
  81. package/src/mixins/__tests__/sso.test.ts +31 -0
  82. package/src/mixins/index.ts +8 -0
  83. package/src/models/interfaces.ts +3 -0
  84. package/src/server/__tests__/cors.test.ts +5 -1
  85. package/src/server/__tests__/rateLimit.test.ts +116 -0
  86. package/src/server/cors.ts +25 -20
  87. package/src/server/rateLimit.ts +39 -8
  88. package/src/utils/__tests__/consumeSsoReturn.test.ts +1 -1
  89. package/src/utils/__tests__/profileLinks.test.ts +126 -0
  90. package/src/utils/__tests__/ssoReturn.test.ts +1 -1
  91. package/src/utils/profileLinks.ts +74 -0
  92. package/src/utils/ssoReturn.ts +2 -2
@@ -1,7 +1,15 @@
1
1
  import { OxyAuthenticationError } from '../OxyServices.errors.js';
2
+ import { KeyManager } from '../crypto/keyManager.js';
3
+ import { SignatureService } from '../crypto/signatureService.js';
2
4
  import { loadNodeCrypto } from '../utils/platformCrypto.js';
3
5
  import { logger } from '../utils/loggerUtils.js';
4
6
  import { normalizeUserIdentity, normalizeUserIdentityOrNull } from '../utils/userIdentity.js';
7
+ /**
8
+ * Default lifetime of a "Sign in with Oxy" device-flow session / authorize code.
9
+ * Matches the authorize-code TTL the server enforces (5 minutes). The server's
10
+ * returned `expiresAt` is authoritative; this is only the client-proposed value.
11
+ */
12
+ const COMMONS_SIGN_IN_EXPIRY_MS = 5 * 60 * 1000;
5
13
  /**
6
14
  * Sentinel error raised when getServiceToken() is called with a known apiKey
7
15
  * but a non-matching secret. Indicates either credential drift in the caller
@@ -143,11 +151,25 @@ export function OxyServicesAuthMixin(Base) {
143
151
  try {
144
152
  return await pending;
145
153
  }
154
+ catch (error) {
155
+ // Do not retain unauthenticated cache entries. If the initial
156
+ // /auth/service-token request fails (for example, wrong apiSecret),
157
+ // leaving the pre-seeded empty entry would cause later calls with the
158
+ // real secret for the same apiKey to fail locally as a credential
159
+ // mismatch without ever contacting the server. Keep previously-issued
160
+ // stale tokens on refresh failures, but remove never-authenticated
161
+ // entries.
162
+ const failed = this._serviceTokenCache.get(cacheKey);
163
+ if (failed?.pending === pending && !failed.token) {
164
+ this._serviceTokenCache.delete(cacheKey);
165
+ }
166
+ throw error;
167
+ }
146
168
  finally {
147
169
  // Clear the in-flight slot; the entry itself (with fresh token / expiry)
148
170
  // is updated inside _doFetchServiceToken before we land here.
149
171
  const settled = this._serviceTokenCache.get(cacheKey);
150
- if (settled) {
172
+ if (settled?.pending === pending) {
151
173
  settled.pending = null;
152
174
  }
153
175
  }
@@ -413,6 +435,173 @@ export function OxyServicesAuthMixin(Base) {
413
435
  throw this.handleError(error);
414
436
  }
415
437
  }
438
+ // =======================================================================
439
+ // "Sign in with Oxy" — handoff (Workstream C)
440
+ //
441
+ // Two mechanisms share the same challenge/verify + device-flow primitives:
442
+ // A. Same-device shared-keychain SSO (`signInWithSharedIdentity`): a
443
+ // sibling native app silently mints its own session from the shared
444
+ // identity key. No user interaction.
445
+ // B. QR / app-to-app handoff: a relying party (`startCommonsSignIn` +
446
+ // `pollCommonsSignIn` + the existing `claimSessionByToken`) and the
447
+ // approver / Commons (`getCommonsApprovalInfo` + `approveCommonsSignIn`
448
+ // / `denyCommonsSignIn`). The approver signs with its PRIMARY local
449
+ // key; the RP never sees the private key.
450
+ // =======================================================================
451
+ /**
452
+ * MECHANISM A — same-device shared-keychain SSO.
453
+ *
454
+ * Native-only. If this device holds a shared identity (the cross-app
455
+ * `group.so.oxy.shared` keychain key), prove control of it and mint a
456
+ * session: `requestChallenge(sharedPublicKey)` → `signChallengeWithSharedKey`
457
+ * → `verifyChallenge` (which plants the tokens). Returns `null` on web or
458
+ * when no shared identity is present — never throws for the absent-identity
459
+ * case, so a cold-boot caller can fall through to the next step.
460
+ *
461
+ * The cold-boot wiring that CALLS this lives in `OxyContext`
462
+ * (`@oxyhq/services`); this method just performs the exchange.
463
+ */
464
+ async signInWithSharedIdentity(opts = {}) {
465
+ try {
466
+ // `hasSharedIdentity()` already returns false on web (the shared
467
+ // keychain is native-only), so this short-circuits the web case without
468
+ // a wasted challenge round-trip.
469
+ if (!(await KeyManager.hasSharedIdentity())) {
470
+ return null;
471
+ }
472
+ const sharedPublicKey = await KeyManager.getSharedPublicKey();
473
+ if (!sharedPublicKey) {
474
+ return null;
475
+ }
476
+ const { challenge } = await this.requestChallenge(sharedPublicKey);
477
+ const signed = await SignatureService.signChallengeWithSharedKey(challenge);
478
+ // `signed.challenge` carries the SIGNATURE (mirrors `signChallenge`).
479
+ return await this.verifyChallenge(signed.publicKey, challenge, signed.challenge, signed.timestamp, opts.deviceName, opts.deviceFingerprint);
480
+ }
481
+ catch (error) {
482
+ throw this.handleError(error);
483
+ }
484
+ }
485
+ /**
486
+ * MECHANISM B (relying party) — begin a "Sign in with Oxy" handoff.
487
+ *
488
+ * Generates a secret device-flow `sessionToken` client-side (it never
489
+ * appears in the QR), registers it with `POST /auth/session/create`, and
490
+ * returns the server-issued public `authorizeCode` + ready-to-render
491
+ * `qrPayload`. Render the QR (web) / open the deep-link (same-device); the
492
+ * approver resolves the code and authorizes. Then poll with
493
+ * {@link pollCommonsSignIn} and, on `authorized`, exchange the
494
+ * `sessionToken` via the existing `claimSessionByToken`.
495
+ *
496
+ * @param params.clientId - The RP's registered OAuth client id
497
+ * (ApplicationCredential publicKey); required so the server can resolve the
498
+ * requesting application's identity.
499
+ */
500
+ async startCommonsSignIn(params) {
501
+ try {
502
+ // High-entropy opaque secret token (256-bit hex). Generated client-side
503
+ // and held only here; the server stores it but never returns it in the
504
+ // QR. Reuses the platform-safe random generator.
505
+ const sessionToken = await SignatureService.generateChallenge();
506
+ const expiresAt = Date.now() + COMMONS_SIGN_IN_EXPIRY_MS;
507
+ const res = await this.makeRequest('POST', '/auth/session/create', { sessionToken, expiresAt, clientId: params.clientId }, { cache: false });
508
+ return {
509
+ sessionToken,
510
+ authorizeCode: res.authorizeCode,
511
+ qrPayload: res.qrPayload,
512
+ expiresAt: res.expiresAt ?? expiresAt,
513
+ status: res.status,
514
+ };
515
+ }
516
+ catch (error) {
517
+ throw this.handleError(error);
518
+ }
519
+ }
520
+ /**
521
+ * MECHANISM B (relying party) — poll a device-flow session for approval.
522
+ *
523
+ * Backstop for the auth socket. On `authorized` (with a `sessionId`), the
524
+ * caller exchanges the secret `sessionToken` via the existing
525
+ * `claimSessionByToken` to mint the first access token.
526
+ *
527
+ * @param sessionToken - The secret token from {@link startCommonsSignIn}.
528
+ */
529
+ async pollCommonsSignIn(sessionToken) {
530
+ try {
531
+ return await this.makeRequest('GET', `/auth/session/status/${encodeURIComponent(sessionToken)}`, undefined, { cache: false, retry: false });
532
+ }
533
+ catch (error) {
534
+ throw this.handleError(error);
535
+ }
536
+ }
537
+ /**
538
+ * MECHANISM B (approver / Commons) — resolve the TRUSTED identity of a
539
+ * sign-in request from its public `authorizeCode`.
540
+ *
541
+ * The returned `application` is resolved server-side and is the only safe
542
+ * thing to display in the approval UI — NEVER trust the app/name/origin
543
+ * strings carried in the QR payload. Public (no auth required).
544
+ *
545
+ * @param authorizeCode - The public code scanned from the QR / deep-link.
546
+ */
547
+ async getCommonsApprovalInfo(authorizeCode) {
548
+ try {
549
+ return await this.makeRequest('GET', `/auth/session/approve-info/${encodeURIComponent(authorizeCode)}`, undefined, { cache: false });
550
+ }
551
+ catch (error) {
552
+ throw this.handleError(error);
553
+ }
554
+ }
555
+ /**
556
+ * MECHANISM B (approver / Commons) — approve a sign-in request by signing a
557
+ * fresh challenge with the PRIMARY local identity key.
558
+ *
559
+ * Commons holds the user's identity as its primary key (not the shared
560
+ * key), so this uses `signChallenge`. The signed-but-cookieless authorize
561
+ * endpoint resolves the user from the verified signer — the RP that started
562
+ * the flow then claims its session. Native-only (requires a local identity).
563
+ *
564
+ * @param params.authorizeCode - The public code being approved.
565
+ * @param params.deviceName - Optional human-readable device label.
566
+ * @param params.deviceFingerprint - Optional device fingerprint.
567
+ */
568
+ async approveCommonsSignIn(params) {
569
+ try {
570
+ const publicKey = await KeyManager.getPublicKey();
571
+ if (!publicKey) {
572
+ throw new Error('No identity found on this device. Create or import an identity first.');
573
+ }
574
+ const { challenge } = await this.requestChallenge(publicKey);
575
+ const signed = await SignatureService.signChallenge(challenge);
576
+ return await this.makeRequest('POST', `/auth/session/authorize-signed/${encodeURIComponent(params.authorizeCode)}`, {
577
+ // `signed.challenge` carries the SIGNATURE; `challenge` is the
578
+ // original server-issued challenge string.
579
+ publicKey: signed.publicKey,
580
+ challenge,
581
+ signature: signed.challenge,
582
+ timestamp: signed.timestamp,
583
+ ...(params.deviceName ? { deviceName: params.deviceName } : {}),
584
+ ...(params.deviceFingerprint ? { deviceFingerprint: params.deviceFingerprint } : {}),
585
+ }, { cache: false });
586
+ }
587
+ catch (error) {
588
+ throw this.handleError(error);
589
+ }
590
+ }
591
+ /**
592
+ * MECHANISM B (approver / Commons) — deny a sign-in request, cancelling the
593
+ * device-flow session so the RP stops waiting.
594
+ *
595
+ * @param authorizeCode - The public code being denied.
596
+ */
597
+ async denyCommonsSignIn(authorizeCode) {
598
+ try {
599
+ return await this.makeRequest('POST', `/auth/session/deny/${encodeURIComponent(authorizeCode)}`, undefined, { cache: false });
600
+ }
601
+ catch (error) {
602
+ throw this.handleError(error);
603
+ }
604
+ }
416
605
  /**
417
606
  * Refresh every device-local refresh-cookie slot in a single round trip
418
607
  * (Google-style multi-account rebuild).