@oxyhq/core 3.10.0 → 3.11.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/AuthManager.js +9 -2
- package/dist/cjs/HttpService.js +27 -9
- package/dist/cjs/OxyServices.base.js +3 -2
- package/dist/cjs/crypto/canonicalJson.js +107 -0
- package/dist/cjs/crypto/keyManager.js +67 -8
- package/dist/cjs/crypto/signatureService.js +103 -0
- package/dist/cjs/i18n/locales/en-US.json +9 -0
- package/dist/cjs/i18n/locales/es-ES.json +9 -0
- package/dist/cjs/i18n/locales/locales/en-US.json +9 -0
- package/dist/cjs/i18n/locales/locales/es-ES.json +9 -0
- package/dist/cjs/index.js +15 -5
- package/dist/cjs/mixins/OxyServices.assets.js +45 -7
- package/dist/cjs/mixins/OxyServices.auth.js +190 -1
- package/dist/cjs/mixins/OxyServices.identity.js +291 -0
- package/dist/cjs/mixins/OxyServices.sso.js +28 -1
- package/dist/cjs/mixins/OxyServices.user.js +1 -0
- package/dist/cjs/mixins/OxyServices.utility.js +52 -23
- package/dist/cjs/mixins/index.js +3 -0
- package/dist/cjs/server/cors.js +20 -21
- package/dist/cjs/server/rateLimit.js +32 -8
- package/dist/cjs/utils/fapiAutoDetect.js +12 -42
- package/dist/cjs/utils/ssoReturn.js +1 -1
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/AuthManager.js +9 -2
- package/dist/esm/HttpService.js +27 -9
- package/dist/esm/OxyServices.base.js +3 -2
- package/dist/esm/crypto/canonicalJson.js +104 -0
- package/dist/esm/crypto/keyManager.js +67 -8
- package/dist/esm/crypto/signatureService.js +102 -0
- package/dist/esm/i18n/locales/en-US.json +9 -0
- package/dist/esm/i18n/locales/es-ES.json +9 -0
- package/dist/esm/i18n/locales/locales/en-US.json +9 -0
- package/dist/esm/i18n/locales/locales/es-ES.json +9 -0
- package/dist/esm/index.js +10 -2
- package/dist/esm/mixins/OxyServices.assets.js +45 -7
- package/dist/esm/mixins/OxyServices.auth.js +190 -1
- package/dist/esm/mixins/OxyServices.identity.js +287 -0
- package/dist/esm/mixins/OxyServices.sso.js +28 -1
- package/dist/esm/mixins/OxyServices.user.js +1 -0
- package/dist/esm/mixins/OxyServices.utility.js +52 -23
- package/dist/esm/mixins/index.js +3 -0
- package/dist/esm/server/cors.js +20 -21
- package/dist/esm/server/rateLimit.js +32 -8
- package/dist/esm/utils/fapiAutoDetect.js +12 -41
- package/dist/esm/utils/ssoReturn.js +1 -1
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/HttpService.d.ts +3 -0
- package/dist/types/OxyServices.d.ts +2 -2
- package/dist/types/crypto/canonicalJson.d.ts +44 -0
- package/dist/types/crypto/keyManager.d.ts +7 -0
- package/dist/types/crypto/signatureService.d.ts +61 -0
- package/dist/types/index.d.ts +7 -3
- package/dist/types/mixins/OxyServices.assets.d.ts +6 -1
- package/dist/types/mixins/OxyServices.auth.d.ts +136 -0
- package/dist/types/mixins/OxyServices.identity.d.ts +249 -0
- package/dist/types/mixins/OxyServices.sso.d.ts +4 -1
- package/dist/types/mixins/OxyServices.utility.d.ts +3 -3
- package/dist/types/mixins/index.d.ts +2 -1
- package/dist/types/models/interfaces.d.ts +3 -0
- package/dist/types/server/cors.d.ts +5 -5
- package/dist/types/utils/fapiAutoDetect.d.ts +6 -23
- package/dist/types/utils/ssoReturn.d.ts +1 -1
- package/package.json +3 -2
- package/src/AuthManager.ts +8 -2
- package/src/HttpService.ts +36 -8
- package/src/OxyServices.base.ts +3 -2
- package/src/OxyServices.ts +1 -1
- package/src/__tests__/authManager.security.test.ts +31 -0
- package/src/__tests__/authSocket.test.ts +96 -0
- package/src/__tests__/httpServiceCsrf.test.ts +75 -0
- package/src/crypto/__tests__/canonicalJson.test.ts +116 -0
- package/src/crypto/__tests__/keyManager.atomicity.test.ts +41 -2
- package/src/crypto/__tests__/signChallengeShared.test.ts +64 -0
- package/src/crypto/__tests__/signedRecord.test.ts +125 -0
- package/src/crypto/canonicalJson.ts +120 -0
- package/src/crypto/keyManager.ts +62 -12
- package/src/crypto/signatureService.ts +126 -0
- package/src/i18n/locales/en-US.json +9 -0
- package/src/i18n/locales/es-ES.json +9 -0
- package/src/index.ts +28 -3
- package/src/mixins/OxyServices.assets.ts +56 -7
- package/src/mixins/OxyServices.auth.ts +309 -1
- package/src/mixins/OxyServices.identity.ts +445 -0
- package/src/mixins/OxyServices.sso.ts +30 -1
- package/src/mixins/OxyServices.user.ts +1 -0
- package/src/mixins/OxyServices.utility.ts +57 -23
- package/src/mixins/__tests__/OxyServices.identity.test.ts +364 -0
- package/src/mixins/__tests__/assetCredentials.test.ts +47 -0
- package/src/mixins/__tests__/assetUpload.test.ts +191 -0
- package/src/mixins/__tests__/commonsSignIn.test.ts +277 -0
- package/src/mixins/__tests__/getFileDownloadUrl.test.ts +13 -0
- package/src/mixins/__tests__/serviceAuth.test.ts +49 -2
- package/src/mixins/__tests__/sso.test.ts +31 -0
- package/src/mixins/index.ts +4 -0
- package/src/models/interfaces.ts +3 -0
- package/src/server/__tests__/cors.test.ts +5 -1
- package/src/server/__tests__/rateLimit.test.ts +116 -0
- package/src/server/cors.ts +25 -20
- package/src/server/rateLimit.ts +39 -8
- package/src/utils/__tests__/consumeSsoReturn.test.ts +1 -1
- package/src/utils/__tests__/fapiAutoDetect.test.ts +40 -11
- package/src/utils/__tests__/ssoReturn.test.ts +1 -1
- package/src/utils/fapiAutoDetect.ts +12 -39
- 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).
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { KeyManager } from '../crypto/keyManager.js';
|
|
2
|
+
import { SignatureService } from '../crypto/signatureService.js';
|
|
3
|
+
import { CACHE_TIMES } from './mixinHelpers.js';
|
|
4
|
+
/**
|
|
5
|
+
* Registrable apex the Oxy DID method is anchored on. A user's DID is
|
|
6
|
+
* `did:web:<OXY_IDENTITY_APEX>:u:<userId>`, anchored on the stable account id
|
|
7
|
+
* (NOT the keypair).
|
|
8
|
+
*/
|
|
9
|
+
const OXY_IDENTITY_APEX = 'oxy.so';
|
|
10
|
+
/**
|
|
11
|
+
* Derive a user's Oxy DID from their stable account id.
|
|
12
|
+
* `did:web:oxy.so:u:<userId>`.
|
|
13
|
+
*/
|
|
14
|
+
export function buildUserDid(userId) {
|
|
15
|
+
return `did:web:${OXY_IDENTITY_APEX}:u:${userId}`;
|
|
16
|
+
}
|
|
17
|
+
export function OxyServicesIdentityMixin(Base) {
|
|
18
|
+
return class extends Base {
|
|
19
|
+
constructor(...args) {
|
|
20
|
+
super(...args);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Resolve the W3C DID document for any user. The API derives it on demand
|
|
24
|
+
* from the account's `authMethods` + `publicKey` — there is no stored
|
|
25
|
+
* document. Public (no auth required); short-TTL cached.
|
|
26
|
+
*
|
|
27
|
+
* @param userId - The account's Mongo `_id`. URL-encoded into the path.
|
|
28
|
+
*/
|
|
29
|
+
async resolveDid(userId) {
|
|
30
|
+
try {
|
|
31
|
+
return await this.makeRequest('GET', `/u/${encodeURIComponent(userId)}/did.json`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
throw this.handleError(error);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The current user's DID (`did:web:oxy.so:u:<userId>`), derived locally from
|
|
39
|
+
* the access token's user id. Throws if no user is authenticated.
|
|
40
|
+
*/
|
|
41
|
+
getMyDid() {
|
|
42
|
+
const userId = this.getCurrentUserId();
|
|
43
|
+
if (!userId) {
|
|
44
|
+
throw new Error('No authenticated user — cannot derive DID.');
|
|
45
|
+
}
|
|
46
|
+
return buildUserDid(userId);
|
|
47
|
+
}
|
|
48
|
+
/** Resolve the current user's DID document. Requires an authenticated session. */
|
|
49
|
+
async getMyDidDocument() {
|
|
50
|
+
const userId = this.getCurrentUserId();
|
|
51
|
+
if (!userId) {
|
|
52
|
+
throw new Error('No authenticated user — cannot resolve DID document.');
|
|
53
|
+
}
|
|
54
|
+
return this.resolveDid(userId);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* List the current user's linked authentication methods plus their DID.
|
|
58
|
+
* Each `identity` method carries a `verificationMethodId` linking it to its
|
|
59
|
+
* DID verification-method fragment.
|
|
60
|
+
*/
|
|
61
|
+
async listAuthMethods() {
|
|
62
|
+
try {
|
|
63
|
+
return await this.makeRequest('GET', '/auth/methods', undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
throw this.handleError(error);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Link the on-device cryptographic identity to the current account,
|
|
71
|
+
* upgrading it from custodial to self-sovereign. Signs a proof of private
|
|
72
|
+
* key ownership and posts it to `POST /auth/link`.
|
|
73
|
+
*
|
|
74
|
+
* NATIVE-ONLY: requires a stored identity (throws if `KeyManager` has no key
|
|
75
|
+
* or no user is authenticated). The signed payload is
|
|
76
|
+
* `JSON.stringify({ action: 'link_identity', userId, timestamp })` — the
|
|
77
|
+
* exact bytes the server reconstructs and verifies.
|
|
78
|
+
*/
|
|
79
|
+
async linkIdentityKey() {
|
|
80
|
+
try {
|
|
81
|
+
const userId = this.getCurrentUserId();
|
|
82
|
+
if (!userId) {
|
|
83
|
+
throw new Error('No authenticated user — sign in before linking an identity key.');
|
|
84
|
+
}
|
|
85
|
+
const publicKey = await KeyManager.getPublicKey();
|
|
86
|
+
if (!publicKey) {
|
|
87
|
+
throw new Error('No identity found on this device. Create or import an identity first.');
|
|
88
|
+
}
|
|
89
|
+
const timestamp = Date.now();
|
|
90
|
+
// The signed message MUST match the server's reconstruction byte-for-byte:
|
|
91
|
+
// JSON.stringify with this exact key order (action, userId, timestamp).
|
|
92
|
+
const message = JSON.stringify({ action: 'link_identity', userId, timestamp });
|
|
93
|
+
const signature = await SignatureService.sign(message);
|
|
94
|
+
const result = await this.makeRequest('POST', '/auth/link', { type: 'identity', publicKey, signature, timestamp }, { cache: false });
|
|
95
|
+
this._invalidateIdentityCaches(userId);
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
throw this.handleError(error);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Link password authentication to the current account. Adds a `password`
|
|
104
|
+
* auth method (does not remove existing methods).
|
|
105
|
+
*
|
|
106
|
+
* @param email - The email to associate with password auth.
|
|
107
|
+
* @param password - The new password (server enforces strength rules).
|
|
108
|
+
*/
|
|
109
|
+
async linkPassword(email, password) {
|
|
110
|
+
try {
|
|
111
|
+
const result = await this.makeRequest('POST', '/auth/link', { type: 'password', email, password }, { cache: false });
|
|
112
|
+
this._invalidateIdentityCaches(this.getCurrentUserId());
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
throw this.handleError(error);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Unlink an authentication method from the current account. The server
|
|
121
|
+
* refuses to remove the last remaining method (the account would become
|
|
122
|
+
* inaccessible). Unlinking `identity` downgrades the account to custodial.
|
|
123
|
+
*
|
|
124
|
+
* @param type - The auth-method type to remove.
|
|
125
|
+
*/
|
|
126
|
+
async unlinkAuthMethod(type) {
|
|
127
|
+
try {
|
|
128
|
+
const result = await this.makeRequest('DELETE', `/auth/link/${encodeURIComponent(type)}`, undefined, { cache: false });
|
|
129
|
+
this._invalidateIdentityCaches(this.getCurrentUserId());
|
|
130
|
+
return result;
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
throw this.handleError(error);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Sign a record with the on-device identity key, WITHOUT publishing it.
|
|
138
|
+
* The subject is the current user's DID. NATIVE-ONLY (requires a stored
|
|
139
|
+
* key). Use {@link publishRecord} to sign and store in one step.
|
|
140
|
+
*
|
|
141
|
+
* @param type - The record category.
|
|
142
|
+
* @param record - The arbitrary record payload to attest to.
|
|
143
|
+
*/
|
|
144
|
+
async signRecord(type, record) {
|
|
145
|
+
const subject = this.getMyDid();
|
|
146
|
+
return SignatureService.signRecord(type, subject, record);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Sign a record and publish it to the append-only record store
|
|
150
|
+
* (`POST /identity/records`). NATIVE-ONLY (requires a stored key).
|
|
151
|
+
*
|
|
152
|
+
* @param type - The record category.
|
|
153
|
+
* @param record - The arbitrary record payload to attest to.
|
|
154
|
+
*/
|
|
155
|
+
async publishRecord(type, record) {
|
|
156
|
+
try {
|
|
157
|
+
const envelope = await this.signRecord(type, record);
|
|
158
|
+
return await this.makeRequest('POST', '/identity/records', envelope, { cache: false });
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
throw this.handleError(error);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Fetch a user's most recent signed record of a given type. Public (no auth
|
|
166
|
+
* required); short-TTL cached.
|
|
167
|
+
*
|
|
168
|
+
* @param userId - The subject account's Mongo `_id`.
|
|
169
|
+
* @param type - The record category to fetch.
|
|
170
|
+
*/
|
|
171
|
+
async getRecord(userId, type) {
|
|
172
|
+
try {
|
|
173
|
+
const res = await this.makeRequest('GET', `/identity/records/${encodeURIComponent(userId)}/${encodeURIComponent(type)}`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
|
|
174
|
+
return res.record;
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
throw this.handleError(error);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Ask the server to verify a user's stored record: it recomputes the
|
|
182
|
+
* canonical signing input, checks the signature, and asserts the signing key
|
|
183
|
+
* is a current verification method on the subject's DID.
|
|
184
|
+
*
|
|
185
|
+
* @param userId - The subject account's Mongo `_id`.
|
|
186
|
+
* @param type - The record category to verify.
|
|
187
|
+
*/
|
|
188
|
+
async verifyRecord(userId, type) {
|
|
189
|
+
try {
|
|
190
|
+
return await this.makeRequest('GET', `/identity/records/${encodeURIComponent(userId)}/${encodeURIComponent(type)}/verify`, undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
throw this.handleError(error);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Download the current user's signed, open-format data-export bundle
|
|
198
|
+
* (`GET /users/me/export`) — the "credible exit" snapshot. Always carries an
|
|
199
|
+
* Oxy provenance `attestation`; carries an optional client `proof` when the
|
|
200
|
+
* account holds its own key.
|
|
201
|
+
*/
|
|
202
|
+
async exportMyData() {
|
|
203
|
+
try {
|
|
204
|
+
return await this.makeRequest('GET', '/users/me/export', undefined, { cache: false });
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
throw this.handleError(error);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Start verifying ownership of a domain. Returns the instructions: publish
|
|
212
|
+
* EITHER the DNS-TXT record OR the `/.well-known/oxy-domain` file, then call
|
|
213
|
+
* {@link verifyDomain}.
|
|
214
|
+
*
|
|
215
|
+
* @param domain - The domain to claim (e.g. `nate.com`).
|
|
216
|
+
*/
|
|
217
|
+
async requestDomainVerification(domain) {
|
|
218
|
+
try {
|
|
219
|
+
return await this.makeRequest('POST', '/identity/domains', { domain }, { cache: false });
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
throw this.handleError(error);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Complete domain verification: the server checks the DNS-TXT record or
|
|
227
|
+
* well-known file and, on success, attaches the domain to the account
|
|
228
|
+
* (surfaced in the DID's `alsoKnownAs` and the user's `verifiedDomains`).
|
|
229
|
+
*
|
|
230
|
+
* @param domain - The domain previously requested via
|
|
231
|
+
* {@link requestDomainVerification}.
|
|
232
|
+
*/
|
|
233
|
+
async verifyDomain(domain) {
|
|
234
|
+
try {
|
|
235
|
+
const result = await this.makeRequest('POST', `/identity/domains/${encodeURIComponent(domain)}/verify`, undefined, { cache: false });
|
|
236
|
+
this._invalidateIdentityCaches(this.getCurrentUserId());
|
|
237
|
+
return result;
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
throw this.handleError(error);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/** List the current user's verified domains. */
|
|
244
|
+
async listDomains() {
|
|
245
|
+
try {
|
|
246
|
+
const res = await this.makeRequest('GET', '/identity/domains', undefined, { cache: true, cacheTTL: CACHE_TIMES.SHORT });
|
|
247
|
+
return res.domains ?? [];
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
throw this.handleError(error);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Remove a verified domain from the current account.
|
|
255
|
+
* @param domain - The verified domain to remove.
|
|
256
|
+
*/
|
|
257
|
+
async removeDomain(domain) {
|
|
258
|
+
try {
|
|
259
|
+
const result = await this.makeRequest('DELETE', `/identity/domains/${encodeURIComponent(domain)}`, undefined, { cache: false });
|
|
260
|
+
this._invalidateIdentityCaches(this.getCurrentUserId());
|
|
261
|
+
return result;
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
throw this.handleError(error);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Bust the cached reads that an identity mutation invalidates: the current
|
|
269
|
+
* user (`/users/me*`), the linked auth-methods list, the verified-domains
|
|
270
|
+
* list, and the user's derived DID document (which embeds auth methods +
|
|
271
|
+
* verified domains, so it goes stale on link/unlink/domain changes).
|
|
272
|
+
*
|
|
273
|
+
* Internal helper (leading underscore); not part of the supported public
|
|
274
|
+
* surface. Public rather than `private` because mixins compose into an
|
|
275
|
+
* exported anonymous class, where TypeScript cannot represent a private
|
|
276
|
+
* member in the emitted declaration file (TS4094).
|
|
277
|
+
*/
|
|
278
|
+
_invalidateIdentityCaches(userId) {
|
|
279
|
+
this.clearCacheByPrefix('GET:/users/me');
|
|
280
|
+
this.clearCacheEntry('GET:/auth/methods');
|
|
281
|
+
this.clearCacheEntry('GET:/identity/domains');
|
|
282
|
+
if (userId) {
|
|
283
|
+
this.clearCacheEntry(`GET:/u/${encodeURIComponent(userId)}/did.json`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
}
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* `verifyChallenge` — so callers do NOT need to plant tokens manually.
|
|
24
24
|
*/
|
|
25
25
|
import { createDebugLogger } from '../shared/utils/debugUtils.js';
|
|
26
|
+
import { ssoStateKey } from '../utils/ssoBounce.js';
|
|
26
27
|
const debug = createDebugLogger('SSO');
|
|
27
28
|
/**
|
|
28
29
|
* Generate a cryptographically secure state value for the SSO bounce.
|
|
@@ -42,6 +43,25 @@ export function generateSsoState() {
|
|
|
42
43
|
}
|
|
43
44
|
throw new Error('No secure random source available for SSO state generation');
|
|
44
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* Read the SSO bounce state stored for the current browser origin, if any.
|
|
48
|
+
*
|
|
49
|
+
* Returns `null` outside a browser (no `window`/`sessionStorage`) or when no
|
|
50
|
+
* state is stored — in which case the caller cannot (and must not) enforce a
|
|
51
|
+
* state match, e.g. native flows or pre-hydration callbacks that already
|
|
52
|
+
* validated the state before this exchange.
|
|
53
|
+
*/
|
|
54
|
+
function getStoredSsoStateForCurrentOrigin() {
|
|
55
|
+
if (typeof window === 'undefined' || !window.location || !window.sessionStorage) {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
return window.sessionStorage.getItem(ssoStateKey(window.location.origin));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
45
65
|
export function OxyServicesSsoMixin(Base) {
|
|
46
66
|
return class extends Base {
|
|
47
67
|
constructor(...args) {
|
|
@@ -68,12 +88,19 @@ export function OxyServicesSsoMixin(Base) {
|
|
|
68
88
|
* @param code - The opaque single-use code delivered in the SSO return
|
|
69
89
|
* fragment (see {@link parseSsoReturnFragment}). The central store burns
|
|
70
90
|
* it atomically on exchange.
|
|
91
|
+
* @param state - The state value returned alongside the code. In browsers,
|
|
92
|
+
* when an SSO bounce state is still stored for the current origin, this
|
|
93
|
+
* must match before any token-committing exchange is attempted.
|
|
71
94
|
* @returns The resolved {@link SessionLoginResponse}.
|
|
72
95
|
*/
|
|
73
|
-
async exchangeSsoCode(code) {
|
|
96
|
+
async exchangeSsoCode(code, state) {
|
|
74
97
|
if (typeof code !== 'string' || code.length === 0) {
|
|
75
98
|
throw this.handleError(new Error('exchangeSsoCode requires a non-empty code'));
|
|
76
99
|
}
|
|
100
|
+
const expectedState = getStoredSsoStateForCurrentOrigin();
|
|
101
|
+
if (expectedState !== null && (typeof state !== 'string' || state.length === 0 || state !== expectedState)) {
|
|
102
|
+
throw this.handleError(new Error('SSO exchange state mismatch'));
|
|
103
|
+
}
|
|
77
104
|
const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/sso/exchange`;
|
|
78
105
|
debug.log('Exchanging SSO code for session...');
|
|
79
106
|
let response;
|