@smartcrab/browser 0.3.2 → 0.4.0-next-20261017141739
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/base64url.d.ts +1 -9
- package/dist/base64url.js +11 -41
- package/dist/client.d.ts +14 -3
- package/dist/client.js +272 -18
- package/dist/errors.d.ts +14 -1
- package/dist/http.d.ts +1 -0
- package/dist/http.js +15 -0
- package/dist/index.d.ts +2 -2
- package/dist/pkce.js +1 -2
- package/package.json +2 -2
- package/src/base64url.ts +11 -41
- package/src/client-me.test.ts +520 -17
- package/src/client.test.ts +13 -5
- package/src/client.ts +354 -21
- package/src/errors.ts +18 -1
- package/src/http.ts +17 -0
- package/src/index.ts +5 -0
- package/src/pkce.ts +1 -2
package/src/client.test.ts
CHANGED
|
@@ -394,11 +394,17 @@ describe("passkeys (design.md §17)", () => {
|
|
|
394
394
|
expect(webAuthn.get).toHaveBeenCalledWith(AUTHN_OPTIONS);
|
|
395
395
|
});
|
|
396
396
|
|
|
397
|
-
test("authentication options
|
|
397
|
+
test("authentication options transport challenge proof with the original options", async () => {
|
|
398
398
|
const { calls, fetchPort } = createFetchStub(() => jsonResponse(200, AUTHN_OPTIONS));
|
|
399
399
|
const client = makeClient(fetchPort);
|
|
400
|
-
await client.getPasskeyAuthenticationOptions(TXN_ID, {
|
|
401
|
-
|
|
400
|
+
await client.getPasskeyAuthenticationOptions(TXN_ID, {
|
|
401
|
+
email: "user@example.com",
|
|
402
|
+
challenge_token: "turnstile-response",
|
|
403
|
+
});
|
|
404
|
+
expect(calls[0]?.body).toEqual({
|
|
405
|
+
email: "user@example.com",
|
|
406
|
+
challenge_token: "turnstile-response",
|
|
407
|
+
});
|
|
402
408
|
});
|
|
403
409
|
|
|
404
410
|
test("unsupported WebAuthn surfaces webauthn_error without any HTTP call", async () => {
|
|
@@ -453,12 +459,14 @@ describe("social sign-in (design.md §20, §22.3)", () => {
|
|
|
453
459
|
}),
|
|
454
460
|
);
|
|
455
461
|
const client = makeClient(fetchPort, { redirect });
|
|
456
|
-
const outcome = await client.startSocialSignIn(TXN_ID, "google"
|
|
462
|
+
const outcome = await client.startSocialSignIn(TXN_ID, "google", {
|
|
463
|
+
challenge_token: "turnstile-response",
|
|
464
|
+
});
|
|
457
465
|
|
|
458
466
|
expect(outcome.ok).toBe(true);
|
|
459
467
|
expect(calls[0]?.method).toBe("POST");
|
|
460
468
|
expect(calls[0]?.url).toBe(`${BASE_URL}/v1/auth/transactions/${TXN_ID}/social/google/start`);
|
|
461
|
-
expect(calls[0]?.body).toEqual({});
|
|
469
|
+
expect(calls[0]?.body).toEqual({ challenge_token: "turnstile-response" });
|
|
462
470
|
expect(assigned).toEqual(["https://accounts.google.com/o/oauth2/v2/auth?client_id=x"]);
|
|
463
471
|
});
|
|
464
472
|
|
package/src/client.ts
CHANGED
|
@@ -14,10 +14,13 @@ import type {
|
|
|
14
14
|
MeEmailChangeVerifyOldRequest,
|
|
15
15
|
MeEmailChangeVerifyOldResponse,
|
|
16
16
|
MeIdentitiesListResponse,
|
|
17
|
+
MeIdentityLinkCompleteRequest,
|
|
18
|
+
MeIdentityLinkCompleteResponse,
|
|
17
19
|
MeIdentityLinkRequest,
|
|
18
|
-
MeIdentityLinkResponse,
|
|
19
20
|
MeIdentityUnlinkResponse,
|
|
20
21
|
MePasskeyRegistrationOptionsResponse,
|
|
22
|
+
MeRecoveryCompleteResponse,
|
|
23
|
+
MeRecoveryCompleteRequest,
|
|
21
24
|
MePasskeyRegistrationVerifyRequest,
|
|
22
25
|
MePasskeyRegistrationVerifyResponse,
|
|
23
26
|
MePasskeyDeleteResponse,
|
|
@@ -79,6 +82,9 @@ import {
|
|
|
79
82
|
transactionCreateResponseSchema,
|
|
80
83
|
transactionGetResponseSchema,
|
|
81
84
|
transactionPasskeyRegistrationVerifyResponseSchema,
|
|
85
|
+
meIdentityLinkCompleteResponseSchema,
|
|
86
|
+
meRecoveryCompleteResponseSchema,
|
|
87
|
+
socialProviderSchema,
|
|
82
88
|
} from "@smartcrab/contracts-public";
|
|
83
89
|
import { err, ok } from "@smartcrab/contracts-public";
|
|
84
90
|
import type { Outcome } from "@smartcrab/contracts-public";
|
|
@@ -154,6 +160,16 @@ interface PendingAuthorization {
|
|
|
154
160
|
readonly createdAt: number;
|
|
155
161
|
}
|
|
156
162
|
|
|
163
|
+
interface PendingIdentityLink {
|
|
164
|
+
readonly state: string;
|
|
165
|
+
readonly provider: SocialProvider;
|
|
166
|
+
readonly codeVerifier: string;
|
|
167
|
+
readonly redirectUri: string;
|
|
168
|
+
readonly clientId: ClientId;
|
|
169
|
+
readonly userId: string;
|
|
170
|
+
readonly createdAt: number;
|
|
171
|
+
}
|
|
172
|
+
|
|
157
173
|
interface PersistedTransactionSecret {
|
|
158
174
|
readonly transactionId: string;
|
|
159
175
|
readonly secret: string;
|
|
@@ -290,6 +306,7 @@ export interface BrowserAuthClient {
|
|
|
290
306
|
startSocialSignIn(
|
|
291
307
|
transactionId: string,
|
|
292
308
|
provider: SocialProvider,
|
|
309
|
+
input?: { readonly challenge_token?: string },
|
|
293
310
|
): Promise<Outcome<SocialStartResponse, BrowserAuthError>>;
|
|
294
311
|
|
|
295
312
|
// -- Completion / code exchange (design.md §16.3, §15.2) ---------------------
|
|
@@ -351,10 +368,20 @@ export interface BrowserAuthClient {
|
|
|
351
368
|
}): Promise<Outcome<MePasskeyRegistrationVerifyResponse, BrowserAuthError>>;
|
|
352
369
|
deleteMyPasskey(passkeyId: string): Promise<Outcome<MePasskeyDeleteResponse, BrowserAuthError>>;
|
|
353
370
|
listMyIdentities(): Promise<Outcome<MeIdentitiesListResponse, BrowserAuthError>>;
|
|
371
|
+
/** Starts app-held PKCE identity linking and navigates to the provider. */
|
|
354
372
|
linkMyIdentity(
|
|
355
373
|
provider: SocialProvider,
|
|
356
|
-
|
|
357
|
-
|
|
374
|
+
): Promise<Outcome<{ readonly state: string }, BrowserAuthError>>;
|
|
375
|
+
/** Validates the registered callback state, then completes the identity link. */
|
|
376
|
+
completeMyIdentityLink(
|
|
377
|
+
provider: SocialProvider,
|
|
378
|
+
callbackUrl: string,
|
|
379
|
+
): Promise<Outcome<MeIdentityLinkCompleteResponse, BrowserAuthError>>;
|
|
380
|
+
|
|
381
|
+
/** Confirms self-service recovery and clears local tokens only after success. */
|
|
382
|
+
completeMyRecovery(input: {
|
|
383
|
+
readonly idempotencyKey: string;
|
|
384
|
+
}): Promise<Outcome<MeRecoveryCompleteResponse, BrowserAuthError>>;
|
|
358
385
|
unlinkMyIdentity(
|
|
359
386
|
identityId: string,
|
|
360
387
|
): Promise<Outcome<MeIdentityUnlinkResponse, BrowserAuthError>>;
|
|
@@ -380,6 +407,8 @@ export interface BrowserAuthClient {
|
|
|
380
407
|
const EXPIRY_SKEW_MS = 30_000;
|
|
381
408
|
/** Matches the transaction lifetime implied by design.md §16.1's example (10 minutes). */
|
|
382
409
|
const PENDING_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;
|
|
410
|
+
/** App-held identity-link state may span the 10-minute begin and 5-minute callback windows. */
|
|
411
|
+
const PENDING_IDENTITY_LINK_TTL_MS = 15 * 60 * 1000;
|
|
383
412
|
|
|
384
413
|
interface TokenSet {
|
|
385
414
|
accessToken: string;
|
|
@@ -400,6 +429,7 @@ const defaultRedirectPort: RedirectPort = {
|
|
|
400
429
|
};
|
|
401
430
|
const PENDING_AUTHORIZATION_STORAGE_PREFIX = "@smartcrab/browser:pending:";
|
|
402
431
|
const TRANSACTION_SECRET_STORAGE_PREFIX = "@smartcrab/browser:transaction-secret:";
|
|
432
|
+
const PENDING_IDENTITY_LINK_STORAGE_PREFIX = "@smartcrab/browser:identity-link:";
|
|
403
433
|
|
|
404
434
|
const isPendingAuthorization = (value: unknown): value is PendingAuthorization => {
|
|
405
435
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
@@ -414,6 +444,20 @@ const isPendingAuthorization = (value: unknown): value is PendingAuthorization =
|
|
|
414
444
|
);
|
|
415
445
|
};
|
|
416
446
|
|
|
447
|
+
const isPendingIdentityLink = (value: unknown): value is PendingIdentityLink => {
|
|
448
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
449
|
+
const record = value as Record<string, unknown>;
|
|
450
|
+
return (
|
|
451
|
+
typeof record["state"] === "string" &&
|
|
452
|
+
socialProviderSchema.safeParse(record["provider"]).success &&
|
|
453
|
+
typeof record["codeVerifier"] === "string" &&
|
|
454
|
+
typeof record["redirectUri"] === "string" &&
|
|
455
|
+
typeof record["clientId"] === "string" &&
|
|
456
|
+
typeof record["userId"] === "string" &&
|
|
457
|
+
typeof record["createdAt"] === "number" &&
|
|
458
|
+
Number.isFinite(record["createdAt"])
|
|
459
|
+
);
|
|
460
|
+
};
|
|
417
461
|
const isPersistedTransactionSecret = (value: unknown): value is PersistedTransactionSecret => {
|
|
418
462
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
419
463
|
const record = value as Record<string, unknown>;
|
|
@@ -455,7 +499,10 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
455
499
|
let tokenSet: TokenSet | null = null;
|
|
456
500
|
let cachedIssuer: string | null = config.issuer ?? null;
|
|
457
501
|
let inflightRefresh: Promise<Outcome<AuthenticatedSession, BrowserAuthError>> | null = null;
|
|
502
|
+
let sessionGeneration = 0;
|
|
503
|
+
let refreshStorageOperation: Promise<void> = Promise.resolve();
|
|
458
504
|
const pendingByState = new Map<string, PendingAuthorization>();
|
|
505
|
+
const pendingIdentityLinks = new Map<string, PendingIdentityLink>();
|
|
459
506
|
const transactionSecrets = new Map<string, PersistedTransactionSecret>();
|
|
460
507
|
const listeners = new Set<BrowserAuthListener>();
|
|
461
508
|
let snapshot: BrowserAuthSnapshot = { status: "signed_out", hasRefreshToken: false };
|
|
@@ -517,6 +564,55 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
517
564
|
}
|
|
518
565
|
return pending;
|
|
519
566
|
};
|
|
567
|
+
const registerPendingIdentityLink = async (pending: PendingIdentityLink): Promise<boolean> => {
|
|
568
|
+
pendingIdentityLinks.set(pending.state, pending);
|
|
569
|
+
return Promise.resolve()
|
|
570
|
+
.then(() =>
|
|
571
|
+
sessionStorage.setItem(
|
|
572
|
+
`${PENDING_IDENTITY_LINK_STORAGE_PREFIX}${pending.state}`,
|
|
573
|
+
JSON.stringify(pending),
|
|
574
|
+
),
|
|
575
|
+
)
|
|
576
|
+
.then(
|
|
577
|
+
() => true,
|
|
578
|
+
() => {
|
|
579
|
+
pendingIdentityLinks.delete(pending.state);
|
|
580
|
+
return false;
|
|
581
|
+
},
|
|
582
|
+
);
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
const getPendingIdentityLink = async (state: string): Promise<PendingIdentityLink | null> => {
|
|
586
|
+
const inMemory = pendingIdentityLinks.get(state) ?? null;
|
|
587
|
+
const stored = await Promise.resolve()
|
|
588
|
+
.then((): PendingIdentityLink | null => {
|
|
589
|
+
const serialized = sessionStorage.getItem(
|
|
590
|
+
`${PENDING_IDENTITY_LINK_STORAGE_PREFIX}${state}`,
|
|
591
|
+
);
|
|
592
|
+
if (serialized === null) return null;
|
|
593
|
+
const parsed: unknown = JSON.parse(serialized);
|
|
594
|
+
return isPendingIdentityLink(parsed) && parsed.state === state ? parsed : null;
|
|
595
|
+
})
|
|
596
|
+
.then(undefined, () => null);
|
|
597
|
+
const pending = inMemory ?? stored;
|
|
598
|
+
if (
|
|
599
|
+
pending === null ||
|
|
600
|
+
now() - pending.createdAt > PENDING_IDENTITY_LINK_TTL_MS ||
|
|
601
|
+
pending.clientId !== config.clientId
|
|
602
|
+
) {
|
|
603
|
+
if (pending !== null) await clearPendingIdentityLink(state);
|
|
604
|
+
return null;
|
|
605
|
+
}
|
|
606
|
+
pendingIdentityLinks.set(state, pending);
|
|
607
|
+
return pending;
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
const clearPendingIdentityLink = async (state: string): Promise<void> => {
|
|
611
|
+
pendingIdentityLinks.delete(state);
|
|
612
|
+
await Promise.resolve()
|
|
613
|
+
.then(() => sessionStorage.removeItem(`${PENDING_IDENTITY_LINK_STORAGE_PREFIX}${state}`))
|
|
614
|
+
.then(undefined, () => undefined);
|
|
615
|
+
};
|
|
520
616
|
|
|
521
617
|
const registerTransactionSecret = async (
|
|
522
618
|
transactionId: string,
|
|
@@ -569,9 +665,20 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
569
665
|
.then(undefined, () => undefined);
|
|
570
666
|
};
|
|
571
667
|
|
|
668
|
+
const enqueueRefreshStorageOperation = <T>(operation: () => T | PromiseLike<T>): Promise<T> => {
|
|
669
|
+
const pending = refreshStorageOperation.then(operation);
|
|
670
|
+
refreshStorageOperation = pending.then(
|
|
671
|
+
() => undefined,
|
|
672
|
+
() => undefined,
|
|
673
|
+
);
|
|
674
|
+
return pending;
|
|
675
|
+
};
|
|
676
|
+
|
|
572
677
|
const applyTokenResponse = async (
|
|
573
678
|
tokenResponse: TokenResponse,
|
|
574
|
-
|
|
679
|
+
expectedGeneration = sessionGeneration,
|
|
680
|
+
): Promise<Outcome<AuthenticatedSession, BrowserAuthError>> => {
|
|
681
|
+
if (expectedGeneration !== sessionGeneration) return err({ type: "not_authenticated" });
|
|
575
682
|
const refreshToken = tokenResponse.refresh_token ?? tokenSet?.refreshToken ?? null;
|
|
576
683
|
tokenSet = {
|
|
577
684
|
accessToken: tokenResponse.access_token,
|
|
@@ -582,26 +689,40 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
582
689
|
const persistToken = tokenResponse.refresh_token;
|
|
583
690
|
if (persistToken !== undefined && storage !== undefined) {
|
|
584
691
|
// Best-effort: a failing storage port must not break authentication.
|
|
585
|
-
await
|
|
586
|
-
|
|
587
|
-
|
|
692
|
+
await enqueueRefreshStorageOperation(() => storage.save(persistToken)).then(
|
|
693
|
+
undefined,
|
|
694
|
+
() => undefined,
|
|
695
|
+
);
|
|
696
|
+
}
|
|
697
|
+
if (expectedGeneration !== sessionGeneration || tokenSet === null) {
|
|
698
|
+
return err({ type: "not_authenticated" });
|
|
588
699
|
}
|
|
589
700
|
notify();
|
|
590
|
-
return {
|
|
701
|
+
return ok({
|
|
591
702
|
accessTokenExpiresAt: tokenSet.accessTokenExpiresAt,
|
|
592
703
|
scope: tokenSet.scope,
|
|
593
704
|
hasRefreshToken: refreshToken !== null,
|
|
594
|
-
};
|
|
705
|
+
});
|
|
595
706
|
};
|
|
596
707
|
|
|
597
|
-
const clearSession = (): void => {
|
|
708
|
+
const clearSession = async (): Promise<void> => {
|
|
709
|
+
sessionGeneration += 1;
|
|
598
710
|
tokenSet = null;
|
|
711
|
+
notify();
|
|
599
712
|
if (storage !== undefined) {
|
|
600
|
-
|
|
601
|
-
.then(() => storage.clear())
|
|
602
|
-
.then(undefined, () => undefined);
|
|
713
|
+
await enqueueRefreshStorageOperation(() => storage.clear()).then(undefined, () => undefined);
|
|
603
714
|
}
|
|
715
|
+
};
|
|
716
|
+
|
|
717
|
+
const clearSessionAfterRecovery = async (): Promise<boolean> => {
|
|
718
|
+
sessionGeneration += 1;
|
|
719
|
+
tokenSet = null;
|
|
604
720
|
notify();
|
|
721
|
+
if (storage === undefined) return true;
|
|
722
|
+
return enqueueRefreshStorageOperation(() => storage.clear()).then(
|
|
723
|
+
() => true,
|
|
724
|
+
() => false,
|
|
725
|
+
);
|
|
605
726
|
};
|
|
606
727
|
|
|
607
728
|
const request = async <T>(
|
|
@@ -613,6 +734,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
613
734
|
readonly accessToken?: string;
|
|
614
735
|
readonly query?: Record<string, string>;
|
|
615
736
|
readonly transactionId?: string;
|
|
737
|
+
readonly idempotencyKey?: string;
|
|
616
738
|
},
|
|
617
739
|
): Promise<Outcome<T, BrowserAuthError>> => {
|
|
618
740
|
const transactionSecret =
|
|
@@ -627,6 +749,9 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
627
749
|
...(options?.body !== undefined ? { body: options.body } : {}),
|
|
628
750
|
...(options?.accessToken !== undefined ? { accessToken: options.accessToken } : {}),
|
|
629
751
|
...(transactionSecret !== null ? { transactionSecret } : {}),
|
|
752
|
+
...(options?.idempotencyKey !== undefined
|
|
753
|
+
? { idempotencyKey: options.idempotencyKey }
|
|
754
|
+
: {}),
|
|
630
755
|
},
|
|
631
756
|
schema,
|
|
632
757
|
);
|
|
@@ -819,12 +944,17 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
819
944
|
const startSocialSignIn = async (
|
|
820
945
|
transactionId: string,
|
|
821
946
|
provider: SocialProvider,
|
|
947
|
+
input?: { readonly challenge_token?: string },
|
|
822
948
|
): Promise<Outcome<SocialStartResponse, BrowserAuthError>> => {
|
|
823
949
|
const outcome = await request(
|
|
824
950
|
"POST",
|
|
825
951
|
`${transactionPath(transactionId)}/social/${encodeSegment(provider)}/start`,
|
|
826
952
|
socialStartResponseSchema,
|
|
827
|
-
{
|
|
953
|
+
{
|
|
954
|
+
body:
|
|
955
|
+
input?.challenge_token === undefined ? {} : { challenge_token: input.challenge_token },
|
|
956
|
+
transactionId,
|
|
957
|
+
},
|
|
828
958
|
);
|
|
829
959
|
if (!outcome.ok) return outcome;
|
|
830
960
|
// design.md §22.3/§20.6: top-level navigation only; the SPA resumes via
|
|
@@ -885,7 +1015,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
885
1015
|
tokenResponseSchema,
|
|
886
1016
|
);
|
|
887
1017
|
if (!outcome.ok) return outcome;
|
|
888
|
-
return
|
|
1018
|
+
return applyTokenResponse(outcome.value);
|
|
889
1019
|
};
|
|
890
1020
|
|
|
891
1021
|
// --- hosted (redirect) authorization ------------------------------------------------------
|
|
@@ -967,6 +1097,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
967
1097
|
|
|
968
1098
|
const refreshSession = (): Promise<Outcome<AuthenticatedSession, BrowserAuthError>> => {
|
|
969
1099
|
if (inflightRefresh !== null) return inflightRefresh;
|
|
1100
|
+
const generation = sessionGeneration;
|
|
970
1101
|
const pending = (async (): Promise<Outcome<AuthenticatedSession, BrowserAuthError>> => {
|
|
971
1102
|
const refreshToken = tokenSet?.refreshToken ?? null;
|
|
972
1103
|
if (refreshToken === null) {
|
|
@@ -974,6 +1105,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
974
1105
|
}
|
|
975
1106
|
const issuerOutcome = await resolveIssuer();
|
|
976
1107
|
if (!issuerOutcome.ok) return issuerOutcome;
|
|
1108
|
+
if (generation !== sessionGeneration) return err({ type: "not_authenticated" });
|
|
977
1109
|
const body: RefreshTokenGrantRequest = {
|
|
978
1110
|
grant_type: "refresh_token",
|
|
979
1111
|
refresh_token: refreshToken,
|
|
@@ -985,15 +1117,16 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
985
1117
|
{ method: "POST", url: `${issuerOutcome.value}/oauth2/token`, body },
|
|
986
1118
|
tokenResponseSchema,
|
|
987
1119
|
);
|
|
1120
|
+
if (generation !== sessionGeneration) return err({ type: "not_authenticated" });
|
|
988
1121
|
if (!outcome.ok) {
|
|
989
1122
|
// design.md §21.7: invalid_grant kills the local session entirely;
|
|
990
1123
|
// transient failures (network/5xx/429) must not.
|
|
991
1124
|
if (outcome.error.type === "oauth_error" && outcome.error.code === "invalid_grant") {
|
|
992
|
-
clearSession();
|
|
1125
|
+
await clearSession();
|
|
993
1126
|
}
|
|
994
1127
|
return outcome;
|
|
995
1128
|
}
|
|
996
|
-
return
|
|
1129
|
+
return applyTokenResponse(outcome.value, generation);
|
|
997
1130
|
})();
|
|
998
1131
|
inflightRefresh = pending;
|
|
999
1132
|
const clearInflight = (): void => {
|
|
@@ -1055,7 +1188,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
1055
1188
|
},
|
|
1056
1189
|
);
|
|
1057
1190
|
}
|
|
1058
|
-
clearSession();
|
|
1191
|
+
await clearSession();
|
|
1059
1192
|
return ok({ signedOut: true });
|
|
1060
1193
|
};
|
|
1061
1194
|
|
|
@@ -1123,13 +1256,184 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
1123
1256
|
|
|
1124
1257
|
const listMyIdentities = () => authed("GET", "/v1/me/identities", meIdentitiesListResponseSchema);
|
|
1125
1258
|
|
|
1126
|
-
const linkMyIdentity = (
|
|
1127
|
-
|
|
1259
|
+
const linkMyIdentity = async (
|
|
1260
|
+
provider: SocialProvider,
|
|
1261
|
+
): Promise<Outcome<{ readonly state: string }, BrowserAuthError>> => {
|
|
1262
|
+
if (!URL.canParse(config.redirectUri)) {
|
|
1263
|
+
return err({ type: "invalid_response", message: "redirectUri is not a valid URL" });
|
|
1264
|
+
}
|
|
1265
|
+
const accessToken = await getAccessToken();
|
|
1266
|
+
if (!accessToken.ok) return accessToken;
|
|
1267
|
+
const currentUser = await request("GET", "/v1/me", meUserSchema, {
|
|
1268
|
+
accessToken: accessToken.value,
|
|
1269
|
+
});
|
|
1270
|
+
if (!currentUser.ok) return currentUser;
|
|
1271
|
+
|
|
1272
|
+
const pkce = await generatePkcePair();
|
|
1273
|
+
const state = generateState();
|
|
1274
|
+
const pending: PendingIdentityLink = {
|
|
1275
|
+
state,
|
|
1276
|
+
provider,
|
|
1277
|
+
codeVerifier: pkce.verifier,
|
|
1278
|
+
redirectUri: config.redirectUri,
|
|
1279
|
+
clientId: config.clientId,
|
|
1280
|
+
userId: currentUser.value.user_id,
|
|
1281
|
+
createdAt: now(),
|
|
1282
|
+
};
|
|
1283
|
+
if (!(await registerPendingIdentityLink(pending))) {
|
|
1284
|
+
return err({
|
|
1285
|
+
type: "invalid_response",
|
|
1286
|
+
message: "sessionStorage is required to persist identity-link PKCE state",
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
const body: MeIdentityLinkRequest = {
|
|
1291
|
+
redirect_uri: config.redirectUri,
|
|
1292
|
+
code_challenge: pkce.challenge,
|
|
1293
|
+
code_challenge_method: "S256",
|
|
1294
|
+
state,
|
|
1295
|
+
};
|
|
1296
|
+
const started = await request(
|
|
1128
1297
|
"POST",
|
|
1129
1298
|
`/v1/me/identities/${encodeSegment(provider)}/link`,
|
|
1130
1299
|
meIdentityLinkResponseSchema,
|
|
1131
|
-
|
|
1300
|
+
{ body, accessToken: accessToken.value },
|
|
1301
|
+
);
|
|
1302
|
+
if (!started.ok) {
|
|
1303
|
+
await clearPendingIdentityLink(state);
|
|
1304
|
+
return started;
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
const redirected = await Promise.resolve()
|
|
1308
|
+
.then(() => {
|
|
1309
|
+
redirectPort.assign(started.value.authorization_url);
|
|
1310
|
+
return ok<{ readonly state: string }, BrowserAuthError>({ state });
|
|
1311
|
+
})
|
|
1312
|
+
.then(
|
|
1313
|
+
(result) => result,
|
|
1314
|
+
(cause: unknown) =>
|
|
1315
|
+
err<{ readonly state: string }, BrowserAuthError>({
|
|
1316
|
+
type: "network_error",
|
|
1317
|
+
message: cause instanceof Error ? cause.message : "Failed to open the system browser",
|
|
1318
|
+
retryable: true,
|
|
1319
|
+
}),
|
|
1320
|
+
);
|
|
1321
|
+
if (!redirected.ok) {
|
|
1322
|
+
await clearPendingIdentityLink(state);
|
|
1323
|
+
return redirected;
|
|
1324
|
+
}
|
|
1325
|
+
return redirected;
|
|
1326
|
+
};
|
|
1327
|
+
|
|
1328
|
+
const isRetryableCallbackError = (error: BrowserAuthError): boolean =>
|
|
1329
|
+
error.type === "network_error" ||
|
|
1330
|
+
error.type === "rate_limited" ||
|
|
1331
|
+
(error.type === "problem_details" && (error.status === 408 || error.status >= 500)) ||
|
|
1332
|
+
(error.type === "oauth_error" &&
|
|
1333
|
+
((error.status ?? 0) === 408 ||
|
|
1334
|
+
(error.status ?? 0) >= 500 ||
|
|
1335
|
+
error.code === "server_error" ||
|
|
1336
|
+
error.code === "temporarily_unavailable"));
|
|
1337
|
+
|
|
1338
|
+
const completeMyIdentityLink = async (
|
|
1339
|
+
provider: SocialProvider,
|
|
1340
|
+
callbackUrl: string,
|
|
1341
|
+
): Promise<Outcome<MeIdentityLinkCompleteResponse, BrowserAuthError>> => {
|
|
1342
|
+
if (!URL.canParse(callbackUrl) || !URL.canParse(config.redirectUri)) {
|
|
1343
|
+
return err({ type: "invalid_response", message: "identity-link callback URL is invalid" });
|
|
1344
|
+
}
|
|
1345
|
+
const callback = new URL(callbackUrl);
|
|
1346
|
+
const registeredRedirect = new URL(config.redirectUri);
|
|
1347
|
+
if (
|
|
1348
|
+
callback.origin !== registeredRedirect.origin ||
|
|
1349
|
+
callback.pathname !== registeredRedirect.pathname
|
|
1350
|
+
) {
|
|
1351
|
+
return err({
|
|
1352
|
+
type: "invalid_response",
|
|
1353
|
+
message: "callback is not on the registered redirect URI",
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
const states = callback.searchParams.getAll("state");
|
|
1357
|
+
if (states.length !== 1 || states[0] === undefined || states[0].length === 0) {
|
|
1358
|
+
return err({ type: "state_mismatch" });
|
|
1359
|
+
}
|
|
1360
|
+
const state = states[0];
|
|
1361
|
+
const pending = await getPendingIdentityLink(state);
|
|
1362
|
+
if (pending === null) return err({ type: "state_mismatch" });
|
|
1363
|
+
if (pending.provider !== provider) {
|
|
1364
|
+
return err({
|
|
1365
|
+
type: "invalid_response",
|
|
1366
|
+
message: "callback provider does not match pending link",
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
const reasons = callback.searchParams.getAll("reason");
|
|
1371
|
+
if (reasons.length > 0) {
|
|
1372
|
+
await clearPendingIdentityLink(state);
|
|
1373
|
+
return err({
|
|
1374
|
+
type: "invalid_response",
|
|
1375
|
+
message: `identity-link callback failed: ${reasons[0] ?? "unknown reason"}`,
|
|
1376
|
+
});
|
|
1377
|
+
}
|
|
1378
|
+
const codes = callback.searchParams.getAll("link_code");
|
|
1379
|
+
if (codes.length !== 1 || codes[0] === undefined || codes[0].length === 0) {
|
|
1380
|
+
await clearPendingIdentityLink(state);
|
|
1381
|
+
return err({
|
|
1382
|
+
type: "invalid_response",
|
|
1383
|
+
message: "callback is missing exactly one link_code",
|
|
1384
|
+
});
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
if (tokenSet === null) {
|
|
1388
|
+
const restored = await restoreSession();
|
|
1389
|
+
if (!restored.ok) {
|
|
1390
|
+
if (!isRetryableCallbackError(restored.error)) await clearPendingIdentityLink(state);
|
|
1391
|
+
return restored;
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
const accessToken = await getAccessToken();
|
|
1395
|
+
if (!accessToken.ok) {
|
|
1396
|
+
if (!isRetryableCallbackError(accessToken.error)) await clearPendingIdentityLink(state);
|
|
1397
|
+
return accessToken;
|
|
1398
|
+
}
|
|
1399
|
+
const currentUser = await request("GET", "/v1/me", meUserSchema, {
|
|
1400
|
+
accessToken: accessToken.value,
|
|
1401
|
+
});
|
|
1402
|
+
if (!currentUser.ok) {
|
|
1403
|
+
if (!isRetryableCallbackError(currentUser.error)) await clearPendingIdentityLink(state);
|
|
1404
|
+
return currentUser;
|
|
1405
|
+
}
|
|
1406
|
+
if (pending.userId !== currentUser.value.user_id || pending.clientId !== config.clientId) {
|
|
1407
|
+
await clearPendingIdentityLink(state);
|
|
1408
|
+
return err({ type: "state_mismatch" });
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
const body: MeIdentityLinkCompleteRequest = {
|
|
1412
|
+
code: codes[0],
|
|
1413
|
+
code_verifier: pending.codeVerifier,
|
|
1414
|
+
};
|
|
1415
|
+
const completed = await request(
|
|
1416
|
+
"POST",
|
|
1417
|
+
`/v1/me/identities/${encodeSegment(provider)}/link/complete`,
|
|
1418
|
+
meIdentityLinkCompleteResponseSchema,
|
|
1419
|
+
{ body, accessToken: accessToken.value },
|
|
1132
1420
|
);
|
|
1421
|
+
if (completed.ok) {
|
|
1422
|
+
await clearPendingIdentityLink(state);
|
|
1423
|
+
return completed;
|
|
1424
|
+
}
|
|
1425
|
+
if (
|
|
1426
|
+
!isRetryableCallbackError(completed.error) &&
|
|
1427
|
+
!(
|
|
1428
|
+
completed.error.type === "problem_details" &&
|
|
1429
|
+
completed.error.status === 503 &&
|
|
1430
|
+
completed.error.code === "identity_link_code_unavailable"
|
|
1431
|
+
)
|
|
1432
|
+
) {
|
|
1433
|
+
await clearPendingIdentityLink(state);
|
|
1434
|
+
}
|
|
1435
|
+
return completed;
|
|
1436
|
+
};
|
|
1133
1437
|
|
|
1134
1438
|
const unlinkMyIdentity = (identityId: string) =>
|
|
1135
1439
|
authed(
|
|
@@ -1157,6 +1461,33 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
1157
1461
|
|
|
1158
1462
|
const deleteMyAccount = () => authed("DELETE", "/v1/me", meDeleteResponseSchema);
|
|
1159
1463
|
|
|
1464
|
+
const completeMyRecovery = async (input: {
|
|
1465
|
+
readonly idempotencyKey: string;
|
|
1466
|
+
}): Promise<Outcome<MeRecoveryCompleteResponse, BrowserAuthError>> => {
|
|
1467
|
+
const accessToken = await getAccessToken();
|
|
1468
|
+
if (!accessToken.ok) return accessToken;
|
|
1469
|
+
const body: MeRecoveryCompleteRequest = { confirmed: true };
|
|
1470
|
+
const completed = await request(
|
|
1471
|
+
"POST",
|
|
1472
|
+
"/v1/me/recovery/complete",
|
|
1473
|
+
meRecoveryCompleteResponseSchema,
|
|
1474
|
+
{
|
|
1475
|
+
body,
|
|
1476
|
+
accessToken: accessToken.value,
|
|
1477
|
+
idempotencyKey: input.idempotencyKey,
|
|
1478
|
+
},
|
|
1479
|
+
);
|
|
1480
|
+
if (!completed.ok) return completed;
|
|
1481
|
+
const cleared = await clearSessionAfterRecovery();
|
|
1482
|
+
if (!cleared) {
|
|
1483
|
+
return err({
|
|
1484
|
+
type: "storage_error",
|
|
1485
|
+
message: "The recovery succeeded but the refresh-token store could not be cleared",
|
|
1486
|
+
});
|
|
1487
|
+
}
|
|
1488
|
+
return completed;
|
|
1489
|
+
};
|
|
1490
|
+
|
|
1160
1491
|
return {
|
|
1161
1492
|
getPublicConfig,
|
|
1162
1493
|
createTransaction,
|
|
@@ -1196,6 +1527,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
1196
1527
|
deleteMyPasskey,
|
|
1197
1528
|
listMyIdentities,
|
|
1198
1529
|
linkMyIdentity,
|
|
1530
|
+
completeMyIdentityLink,
|
|
1199
1531
|
unlinkMyIdentity,
|
|
1200
1532
|
listMySessions,
|
|
1201
1533
|
revokeMySession,
|
|
@@ -1204,5 +1536,6 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
|
|
|
1204
1536
|
verifyMyEmailChangeOld,
|
|
1205
1537
|
verifyMyEmailChangeNew,
|
|
1206
1538
|
deleteMyAccount,
|
|
1539
|
+
completeMyRecovery,
|
|
1207
1540
|
};
|
|
1208
1541
|
};
|
package/src/errors.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { AdaptiveChallengeAction } from "@smartcrab/contracts-public";
|
|
2
|
+
|
|
1
3
|
import type { OAuthErrorCode } from "@smartcrab/contracts-public";
|
|
2
4
|
|
|
3
5
|
/**
|
|
@@ -57,6 +59,14 @@ export interface ProblemDetailsError {
|
|
|
57
59
|
readonly detail?: string;
|
|
58
60
|
readonly requestId?: string;
|
|
59
61
|
}
|
|
62
|
+
export interface AdaptiveChallengeRequiredError {
|
|
63
|
+
readonly type: "adaptive_challenge_required";
|
|
64
|
+
readonly challengeId: string;
|
|
65
|
+
readonly siteKey: string;
|
|
66
|
+
readonly action: AdaptiveChallengeAction;
|
|
67
|
+
readonly transactionId: string;
|
|
68
|
+
readonly requestId?: string;
|
|
69
|
+
}
|
|
60
70
|
|
|
61
71
|
export interface OAuthFailureError {
|
|
62
72
|
readonly type: "oauth_error";
|
|
@@ -74,6 +84,11 @@ export interface NotAuthenticatedError {
|
|
|
74
84
|
readonly type: "not_authenticated";
|
|
75
85
|
}
|
|
76
86
|
|
|
87
|
+
export interface StorageFailureError {
|
|
88
|
+
readonly type: "storage_error";
|
|
89
|
+
readonly message: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
77
92
|
export type WebAuthnFailureReason = "not_supported" | "cancelled" | "failed";
|
|
78
93
|
|
|
79
94
|
export interface WebAuthnFailureError {
|
|
@@ -87,10 +102,12 @@ export type BrowserAuthError =
|
|
|
87
102
|
| InvalidResponseError
|
|
88
103
|
| RateLimitedError
|
|
89
104
|
| ProblemDetailsError
|
|
105
|
+
| AdaptiveChallengeRequiredError
|
|
90
106
|
| OAuthFailureError
|
|
91
107
|
| StateMismatchError
|
|
92
108
|
| NotAuthenticatedError
|
|
93
|
-
| WebAuthnFailureError
|
|
109
|
+
| WebAuthnFailureError
|
|
110
|
+
| StorageFailureError;
|
|
94
111
|
|
|
95
112
|
// ---------------------------------------------------------------------------
|
|
96
113
|
// Wire guards (this package has no zod dependency — see package.json — so the
|
package/src/http.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { adaptiveChallengeRequiredResponseSchema } from "@smartcrab/contracts-public";
|
|
2
|
+
|
|
1
3
|
import type { Outcome } from "@smartcrab/contracts-public";
|
|
2
4
|
import { err, ok } from "@smartcrab/contracts-public";
|
|
3
5
|
import { OAUTH_ERROR_CODES } from "@smartcrab/contracts-public";
|
|
@@ -38,6 +40,7 @@ export interface JsonRequest {
|
|
|
38
40
|
readonly body?: unknown;
|
|
39
41
|
readonly accessToken?: string;
|
|
40
42
|
readonly transactionSecret?: string;
|
|
43
|
+
readonly idempotencyKey?: string;
|
|
41
44
|
}
|
|
42
45
|
|
|
43
46
|
const OAUTH_ERROR_CODE_SET: ReadonlySet<string> = new Set(OAUTH_ERROR_CODES);
|
|
@@ -98,6 +101,7 @@ export const requestJson = async <T>(
|
|
|
98
101
|
...(request.transactionSecret !== undefined
|
|
99
102
|
? { "x-transaction-secret": request.transactionSecret }
|
|
100
103
|
: {}),
|
|
104
|
+
...(request.idempotencyKey !== undefined ? { "Idempotency-Key": request.idempotencyKey } : {}),
|
|
101
105
|
};
|
|
102
106
|
|
|
103
107
|
const responseOutcome = await fetchPort(request.url, {
|
|
@@ -134,6 +138,19 @@ export const requestJson = async <T>(
|
|
|
134
138
|
}
|
|
135
139
|
|
|
136
140
|
if (!response.ok) {
|
|
141
|
+
const adaptiveChallenge = adaptiveChallengeRequiredResponseSchema.safeParse(json);
|
|
142
|
+
if (adaptiveChallenge.success) {
|
|
143
|
+
return err({
|
|
144
|
+
type: "adaptive_challenge_required",
|
|
145
|
+
challengeId: adaptiveChallenge.data.challenge_id,
|
|
146
|
+
siteKey: adaptiveChallenge.data.site_key,
|
|
147
|
+
action: adaptiveChallenge.data.action,
|
|
148
|
+
transactionId: adaptiveChallenge.data.transaction_id,
|
|
149
|
+
...(adaptiveChallenge.data.request_id !== undefined
|
|
150
|
+
? { requestId: adaptiveChallenge.data.request_id }
|
|
151
|
+
: {}),
|
|
152
|
+
});
|
|
153
|
+
}
|
|
137
154
|
const problem = parseProblemDetailsWire(json);
|
|
138
155
|
if (problem !== null) {
|
|
139
156
|
return err({
|