@smartcrab/browser 0.3.2 → 0.4.0-next-20261016193833
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/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/package.json +2 -2
- 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/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ClientId, EmailChallengeResponse, EmailResendRequest, EmailStartRequest, EmailVerifyRequest, EmailVerifyResponse, MeDeleteResponse, MeEmailChangeStartRequest, MeEmailChangeStartResponse, MeEmailChangeVerifyNewRequest, MeEmailChangeVerifyNewResponse, MeEmailChangeVerifyOldRequest, MeEmailChangeVerifyOldResponse, MeIdentitiesListResponse,
|
|
1
|
+
import type { ClientId, EmailChallengeResponse, EmailResendRequest, EmailStartRequest, EmailVerifyRequest, EmailVerifyResponse, MeDeleteResponse, MeEmailChangeStartRequest, MeEmailChangeStartResponse, MeEmailChangeVerifyNewRequest, MeEmailChangeVerifyNewResponse, MeEmailChangeVerifyOldRequest, MeEmailChangeVerifyOldResponse, MeIdentitiesListResponse, MeIdentityLinkCompleteResponse, MeIdentityUnlinkResponse, MePasskeyRegistrationOptionsResponse, MeRecoveryCompleteResponse, MePasskeyRegistrationVerifyRequest, MePasskeyRegistrationVerifyResponse, MePasskeyDeleteResponse, MePasskeysListResponse, MeSessionRevokeResponse, MeSessionsListResponse, MeSessionsRevokeAllResponse, MeUpdateRequest, MeUpdateResponse, MeUser, PasskeyAuthenticationOptionsRequest, PasskeyAuthenticationOptionsResponse, PasskeyAuthenticationVerifyRequest, PasskeyAuthenticationVerifyResponse, PasskeyRegistrationOptionsResponse, PasskeyRegistrationVerifyRequest, PublicConfigResponse, SocialProvider, SocialStartResponse, TransactionCancelResponse, TransactionCompleteResponse, TransactionCreateResponse, TransactionGetResponse, TransactionPasskeyRegistrationVerifyResponse } from "@smartcrab/contracts-public";
|
|
2
2
|
import type { Outcome } from "@smartcrab/contracts-public";
|
|
3
3
|
import type { BrowserAuthError } from "./errors.js";
|
|
4
4
|
import type { FetchPort } from "./http.js";
|
|
@@ -132,7 +132,9 @@ export interface BrowserAuthClient {
|
|
|
132
132
|
* provider callback eventually lands on `redirectUri`; resume with
|
|
133
133
|
* `handleHostedAuthorizationCallback`.
|
|
134
134
|
*/
|
|
135
|
-
startSocialSignIn(transactionId: string, provider: SocialProvider
|
|
135
|
+
startSocialSignIn(transactionId: string, provider: SocialProvider, input?: {
|
|
136
|
+
readonly challenge_token?: string;
|
|
137
|
+
}): Promise<Outcome<SocialStartResponse, BrowserAuthError>>;
|
|
136
138
|
completeTransaction(transactionId: string): Promise<Outcome<TransactionCompleteResponse, BrowserAuthError>>;
|
|
137
139
|
/**
|
|
138
140
|
* Exchanges a one-time authorization code at the token endpoint using the
|
|
@@ -181,7 +183,16 @@ export interface BrowserAuthClient {
|
|
|
181
183
|
}): Promise<Outcome<MePasskeyRegistrationVerifyResponse, BrowserAuthError>>;
|
|
182
184
|
deleteMyPasskey(passkeyId: string): Promise<Outcome<MePasskeyDeleteResponse, BrowserAuthError>>;
|
|
183
185
|
listMyIdentities(): Promise<Outcome<MeIdentitiesListResponse, BrowserAuthError>>;
|
|
184
|
-
|
|
186
|
+
/** Starts app-held PKCE identity linking and navigates to the provider. */
|
|
187
|
+
linkMyIdentity(provider: SocialProvider): Promise<Outcome<{
|
|
188
|
+
readonly state: string;
|
|
189
|
+
}, BrowserAuthError>>;
|
|
190
|
+
/** Validates the registered callback state, then completes the identity link. */
|
|
191
|
+
completeMyIdentityLink(provider: SocialProvider, callbackUrl: string): Promise<Outcome<MeIdentityLinkCompleteResponse, BrowserAuthError>>;
|
|
192
|
+
/** Confirms self-service recovery and clears local tokens only after success. */
|
|
193
|
+
completeMyRecovery(input: {
|
|
194
|
+
readonly idempotencyKey: string;
|
|
195
|
+
}): Promise<Outcome<MeRecoveryCompleteResponse, BrowserAuthError>>;
|
|
185
196
|
unlinkMyIdentity(identityId: string): Promise<Outcome<MeIdentityUnlinkResponse, BrowserAuthError>>;
|
|
186
197
|
listMySessions(): Promise<Outcome<MeSessionsListResponse, BrowserAuthError>>;
|
|
187
198
|
revokeMySession(sessionId: string): Promise<Outcome<MeSessionRevokeResponse, BrowserAuthError>>;
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { clientIdSchema, emailChallengeResponseSchema, emailVerifyResponseSchema, meDeleteResponseSchema, meEmailChangeStartResponseSchema, meEmailChangeVerifyNewResponseSchema, meEmailChangeVerifyOldResponseSchema, meIdentitiesListResponseSchema, meIdentityLinkResponseSchema, meIdentityUnlinkResponseSchema, mePasskeyDeleteResponseSchema, mePasskeyRegistrationOptionsResponseSchema, mePasskeyRegistrationVerifyResponseSchema, mePasskeysListResponseSchema, meSessionRevokeResponseSchema, meSessionsListResponseSchema, meSessionsRevokeAllResponseSchema, meUpdateResponseSchema, meUserSchema, passkeyAuthenticationOptionsResponseSchema, passkeyAuthenticationVerifyResponseSchema, passkeyRegistrationOptionsResponseSchema, publicConfigResponseSchema, scopeStringSchema, socialStartResponseSchema, tokenResponseSchema, transactionCancelResponseSchema, transactionCompleteResponseSchema, transactionCreateResponseSchema, transactionGetResponseSchema, transactionPasskeyRegistrationVerifyResponseSchema, } from "@smartcrab/contracts-public";
|
|
1
|
+
import { clientIdSchema, emailChallengeResponseSchema, emailVerifyResponseSchema, meDeleteResponseSchema, meEmailChangeStartResponseSchema, meEmailChangeVerifyNewResponseSchema, meEmailChangeVerifyOldResponseSchema, meIdentitiesListResponseSchema, meIdentityLinkResponseSchema, meIdentityUnlinkResponseSchema, mePasskeyDeleteResponseSchema, mePasskeyRegistrationOptionsResponseSchema, mePasskeyRegistrationVerifyResponseSchema, mePasskeysListResponseSchema, meSessionRevokeResponseSchema, meSessionsListResponseSchema, meSessionsRevokeAllResponseSchema, meUpdateResponseSchema, meUserSchema, passkeyAuthenticationOptionsResponseSchema, passkeyAuthenticationVerifyResponseSchema, passkeyRegistrationOptionsResponseSchema, publicConfigResponseSchema, scopeStringSchema, socialStartResponseSchema, tokenResponseSchema, transactionCancelResponseSchema, transactionCompleteResponseSchema, transactionCreateResponseSchema, transactionGetResponseSchema, transactionPasskeyRegistrationVerifyResponseSchema, meIdentityLinkCompleteResponseSchema, meRecoveryCompleteResponseSchema, socialProviderSchema, } from "@smartcrab/contracts-public";
|
|
2
2
|
import { err, ok } from "@smartcrab/contracts-public";
|
|
3
3
|
import { buildUrl, isOAuthErrorCode, requestJson } from "./http.js";
|
|
4
4
|
import { generateNonce, generatePkcePair, generateState } from "./pkce.js";
|
|
@@ -9,6 +9,8 @@ import { navigatorWebAuthnPort } from "./webauthn.js";
|
|
|
9
9
|
const EXPIRY_SKEW_MS = 30_000;
|
|
10
10
|
/** Matches the transaction lifetime implied by design.md §16.1's example (10 minutes). */
|
|
11
11
|
const PENDING_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;
|
|
12
|
+
/** App-held identity-link state may span the 10-minute begin and 5-minute callback windows. */
|
|
13
|
+
const PENDING_IDENTITY_LINK_TTL_MS = 15 * 60 * 1000;
|
|
12
14
|
const defaultFetchPort = (url, init) => fetch(url, init);
|
|
13
15
|
const defaultRedirectPort = {
|
|
14
16
|
assign: (url) => {
|
|
@@ -19,6 +21,7 @@ const defaultRedirectPort = {
|
|
|
19
21
|
};
|
|
20
22
|
const PENDING_AUTHORIZATION_STORAGE_PREFIX = "@smartcrab/browser:pending:";
|
|
21
23
|
const TRANSACTION_SECRET_STORAGE_PREFIX = "@smartcrab/browser:transaction-secret:";
|
|
24
|
+
const PENDING_IDENTITY_LINK_STORAGE_PREFIX = "@smartcrab/browser:identity-link:";
|
|
22
25
|
const isPendingAuthorization = (value) => {
|
|
23
26
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
24
27
|
return false;
|
|
@@ -30,6 +33,19 @@ const isPendingAuthorization = (value) => {
|
|
|
30
33
|
typeof record["createdAt"] === "number" &&
|
|
31
34
|
Number.isFinite(record["createdAt"]));
|
|
32
35
|
};
|
|
36
|
+
const isPendingIdentityLink = (value) => {
|
|
37
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
38
|
+
return false;
|
|
39
|
+
const record = value;
|
|
40
|
+
return (typeof record["state"] === "string" &&
|
|
41
|
+
socialProviderSchema.safeParse(record["provider"]).success &&
|
|
42
|
+
typeof record["codeVerifier"] === "string" &&
|
|
43
|
+
typeof record["redirectUri"] === "string" &&
|
|
44
|
+
typeof record["clientId"] === "string" &&
|
|
45
|
+
typeof record["userId"] === "string" &&
|
|
46
|
+
typeof record["createdAt"] === "number" &&
|
|
47
|
+
Number.isFinite(record["createdAt"]));
|
|
48
|
+
};
|
|
33
49
|
const isPersistedTransactionSecret = (value) => {
|
|
34
50
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
35
51
|
return false;
|
|
@@ -66,7 +82,10 @@ export const createBrowserAuthClient = (config) => {
|
|
|
66
82
|
let tokenSet = null;
|
|
67
83
|
let cachedIssuer = config.issuer ?? null;
|
|
68
84
|
let inflightRefresh = null;
|
|
85
|
+
let sessionGeneration = 0;
|
|
86
|
+
let refreshStorageOperation = Promise.resolve();
|
|
69
87
|
const pendingByState = new Map();
|
|
88
|
+
const pendingIdentityLinks = new Map();
|
|
70
89
|
const transactionSecrets = new Map();
|
|
71
90
|
const listeners = new Set();
|
|
72
91
|
let snapshot = { status: "signed_out", hasRefreshToken: false };
|
|
@@ -121,6 +140,43 @@ export const createBrowserAuthClient = (config) => {
|
|
|
121
140
|
}
|
|
122
141
|
return pending;
|
|
123
142
|
};
|
|
143
|
+
const registerPendingIdentityLink = async (pending) => {
|
|
144
|
+
pendingIdentityLinks.set(pending.state, pending);
|
|
145
|
+
return Promise.resolve()
|
|
146
|
+
.then(() => sessionStorage.setItem(`${PENDING_IDENTITY_LINK_STORAGE_PREFIX}${pending.state}`, JSON.stringify(pending)))
|
|
147
|
+
.then(() => true, () => {
|
|
148
|
+
pendingIdentityLinks.delete(pending.state);
|
|
149
|
+
return false;
|
|
150
|
+
});
|
|
151
|
+
};
|
|
152
|
+
const getPendingIdentityLink = async (state) => {
|
|
153
|
+
const inMemory = pendingIdentityLinks.get(state) ?? null;
|
|
154
|
+
const stored = await Promise.resolve()
|
|
155
|
+
.then(() => {
|
|
156
|
+
const serialized = sessionStorage.getItem(`${PENDING_IDENTITY_LINK_STORAGE_PREFIX}${state}`);
|
|
157
|
+
if (serialized === null)
|
|
158
|
+
return null;
|
|
159
|
+
const parsed = JSON.parse(serialized);
|
|
160
|
+
return isPendingIdentityLink(parsed) && parsed.state === state ? parsed : null;
|
|
161
|
+
})
|
|
162
|
+
.then(undefined, () => null);
|
|
163
|
+
const pending = inMemory ?? stored;
|
|
164
|
+
if (pending === null ||
|
|
165
|
+
now() - pending.createdAt > PENDING_IDENTITY_LINK_TTL_MS ||
|
|
166
|
+
pending.clientId !== config.clientId) {
|
|
167
|
+
if (pending !== null)
|
|
168
|
+
await clearPendingIdentityLink(state);
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
pendingIdentityLinks.set(state, pending);
|
|
172
|
+
return pending;
|
|
173
|
+
};
|
|
174
|
+
const clearPendingIdentityLink = async (state) => {
|
|
175
|
+
pendingIdentityLinks.delete(state);
|
|
176
|
+
await Promise.resolve()
|
|
177
|
+
.then(() => sessionStorage.removeItem(`${PENDING_IDENTITY_LINK_STORAGE_PREFIX}${state}`))
|
|
178
|
+
.then(undefined, () => undefined);
|
|
179
|
+
};
|
|
124
180
|
const registerTransactionSecret = async (transactionId, secret) => {
|
|
125
181
|
const persisted = { transactionId, secret, createdAt: now() };
|
|
126
182
|
transactionSecrets.set(transactionId, persisted);
|
|
@@ -164,7 +220,14 @@ export const createBrowserAuthClient = (config) => {
|
|
|
164
220
|
.then(() => sessionStorage.removeItem(`${TRANSACTION_SECRET_STORAGE_PREFIX}${transactionId}`))
|
|
165
221
|
.then(undefined, () => undefined);
|
|
166
222
|
};
|
|
167
|
-
const
|
|
223
|
+
const enqueueRefreshStorageOperation = (operation) => {
|
|
224
|
+
const pending = refreshStorageOperation.then(operation);
|
|
225
|
+
refreshStorageOperation = pending.then(() => undefined, () => undefined);
|
|
226
|
+
return pending;
|
|
227
|
+
};
|
|
228
|
+
const applyTokenResponse = async (tokenResponse, expectedGeneration = sessionGeneration) => {
|
|
229
|
+
if (expectedGeneration !== sessionGeneration)
|
|
230
|
+
return err({ type: "not_authenticated" });
|
|
168
231
|
const refreshToken = tokenResponse.refresh_token ?? tokenSet?.refreshToken ?? null;
|
|
169
232
|
tokenSet = {
|
|
170
233
|
accessToken: tokenResponse.access_token,
|
|
@@ -175,25 +238,33 @@ export const createBrowserAuthClient = (config) => {
|
|
|
175
238
|
const persistToken = tokenResponse.refresh_token;
|
|
176
239
|
if (persistToken !== undefined && storage !== undefined) {
|
|
177
240
|
// Best-effort: a failing storage port must not break authentication.
|
|
178
|
-
await
|
|
179
|
-
|
|
180
|
-
|
|
241
|
+
await enqueueRefreshStorageOperation(() => storage.save(persistToken)).then(undefined, () => undefined);
|
|
242
|
+
}
|
|
243
|
+
if (expectedGeneration !== sessionGeneration || tokenSet === null) {
|
|
244
|
+
return err({ type: "not_authenticated" });
|
|
181
245
|
}
|
|
182
246
|
notify();
|
|
183
|
-
return {
|
|
247
|
+
return ok({
|
|
184
248
|
accessTokenExpiresAt: tokenSet.accessTokenExpiresAt,
|
|
185
249
|
scope: tokenSet.scope,
|
|
186
250
|
hasRefreshToken: refreshToken !== null,
|
|
187
|
-
};
|
|
251
|
+
});
|
|
188
252
|
};
|
|
189
|
-
const clearSession = () => {
|
|
253
|
+
const clearSession = async () => {
|
|
254
|
+
sessionGeneration += 1;
|
|
190
255
|
tokenSet = null;
|
|
256
|
+
notify();
|
|
191
257
|
if (storage !== undefined) {
|
|
192
|
-
|
|
193
|
-
.then(() => storage.clear())
|
|
194
|
-
.then(undefined, () => undefined);
|
|
258
|
+
await enqueueRefreshStorageOperation(() => storage.clear()).then(undefined, () => undefined);
|
|
195
259
|
}
|
|
260
|
+
};
|
|
261
|
+
const clearSessionAfterRecovery = async () => {
|
|
262
|
+
sessionGeneration += 1;
|
|
263
|
+
tokenSet = null;
|
|
196
264
|
notify();
|
|
265
|
+
if (storage === undefined)
|
|
266
|
+
return true;
|
|
267
|
+
return enqueueRefreshStorageOperation(() => storage.clear()).then(() => true, () => false);
|
|
197
268
|
};
|
|
198
269
|
const request = async (method, path, schema, options) => {
|
|
199
270
|
const transactionSecret = options?.transactionId === undefined
|
|
@@ -205,6 +276,9 @@ export const createBrowserAuthClient = (config) => {
|
|
|
205
276
|
...(options?.body !== undefined ? { body: options.body } : {}),
|
|
206
277
|
...(options?.accessToken !== undefined ? { accessToken: options.accessToken } : {}),
|
|
207
278
|
...(transactionSecret !== null ? { transactionSecret } : {}),
|
|
279
|
+
...(options?.idempotencyKey !== undefined
|
|
280
|
+
? { idempotencyKey: options.idempotencyKey }
|
|
281
|
+
: {}),
|
|
208
282
|
}, schema);
|
|
209
283
|
};
|
|
210
284
|
const getPublicConfig = () => request("GET", "/v1/config", publicConfigResponseSchema, {
|
|
@@ -318,8 +392,11 @@ export const createBrowserAuthClient = (config) => {
|
|
|
318
392
|
return verifyPasskeyAuthentication(transactionId, { credential: credential.value });
|
|
319
393
|
};
|
|
320
394
|
// --- social -----------------------------------------------------------------------
|
|
321
|
-
const startSocialSignIn = async (transactionId, provider) => {
|
|
322
|
-
const outcome = await request("POST", `${transactionPath(transactionId)}/social/${encodeSegment(provider)}/start`, socialStartResponseSchema, {
|
|
395
|
+
const startSocialSignIn = async (transactionId, provider, input) => {
|
|
396
|
+
const outcome = await request("POST", `${transactionPath(transactionId)}/social/${encodeSegment(provider)}/start`, socialStartResponseSchema, {
|
|
397
|
+
body: input?.challenge_token === undefined ? {} : { challenge_token: input.challenge_token },
|
|
398
|
+
transactionId,
|
|
399
|
+
});
|
|
323
400
|
if (!outcome.ok)
|
|
324
401
|
return outcome;
|
|
325
402
|
// design.md §22.3/§20.6: top-level navigation only; the SPA resumes via
|
|
@@ -366,7 +443,7 @@ export const createBrowserAuthClient = (config) => {
|
|
|
366
443
|
const outcome = await requestJson(fetchPort, { method: "POST", url: `${issuerOutcome.value}/oauth2/token`, body }, tokenResponseSchema);
|
|
367
444
|
if (!outcome.ok)
|
|
368
445
|
return outcome;
|
|
369
|
-
return
|
|
446
|
+
return applyTokenResponse(outcome.value);
|
|
370
447
|
};
|
|
371
448
|
// --- hosted (redirect) authorization ------------------------------------------------------
|
|
372
449
|
const createHostedAuthorizationUrl = async () => {
|
|
@@ -441,6 +518,7 @@ export const createBrowserAuthClient = (config) => {
|
|
|
441
518
|
const refreshSession = () => {
|
|
442
519
|
if (inflightRefresh !== null)
|
|
443
520
|
return inflightRefresh;
|
|
521
|
+
const generation = sessionGeneration;
|
|
444
522
|
const pending = (async () => {
|
|
445
523
|
const refreshToken = tokenSet?.refreshToken ?? null;
|
|
446
524
|
if (refreshToken === null) {
|
|
@@ -449,6 +527,8 @@ export const createBrowserAuthClient = (config) => {
|
|
|
449
527
|
const issuerOutcome = await resolveIssuer();
|
|
450
528
|
if (!issuerOutcome.ok)
|
|
451
529
|
return issuerOutcome;
|
|
530
|
+
if (generation !== sessionGeneration)
|
|
531
|
+
return err({ type: "not_authenticated" });
|
|
452
532
|
const body = {
|
|
453
533
|
grant_type: "refresh_token",
|
|
454
534
|
refresh_token: refreshToken,
|
|
@@ -456,15 +536,17 @@ export const createBrowserAuthClient = (config) => {
|
|
|
456
536
|
...(config.resource !== undefined ? { resource: [...config.resource] } : {}),
|
|
457
537
|
};
|
|
458
538
|
const outcome = await requestJson(fetchPort, { method: "POST", url: `${issuerOutcome.value}/oauth2/token`, body }, tokenResponseSchema);
|
|
539
|
+
if (generation !== sessionGeneration)
|
|
540
|
+
return err({ type: "not_authenticated" });
|
|
459
541
|
if (!outcome.ok) {
|
|
460
542
|
// design.md §21.7: invalid_grant kills the local session entirely;
|
|
461
543
|
// transient failures (network/5xx/429) must not.
|
|
462
544
|
if (outcome.error.type === "oauth_error" && outcome.error.code === "invalid_grant") {
|
|
463
|
-
clearSession();
|
|
545
|
+
await clearSession();
|
|
464
546
|
}
|
|
465
547
|
return outcome;
|
|
466
548
|
}
|
|
467
|
-
return
|
|
549
|
+
return applyTokenResponse(outcome.value, generation);
|
|
468
550
|
})();
|
|
469
551
|
inflightRefresh = pending;
|
|
470
552
|
const clearInflight = () => {
|
|
@@ -521,7 +603,7 @@ export const createBrowserAuthClient = (config) => {
|
|
|
521
603
|
safeParse: () => ({ success: true, data: {} }),
|
|
522
604
|
});
|
|
523
605
|
}
|
|
524
|
-
clearSession();
|
|
606
|
+
await clearSession();
|
|
525
607
|
return ok({ signedOut: true });
|
|
526
608
|
};
|
|
527
609
|
// --- /v1/me -------------------------------------------------------------------------
|
|
@@ -560,7 +642,156 @@ export const createBrowserAuthClient = (config) => {
|
|
|
560
642
|
};
|
|
561
643
|
const deleteMyPasskey = (passkeyId) => authed("DELETE", `/v1/me/passkeys/${encodeSegment(passkeyId)}`, mePasskeyDeleteResponseSchema);
|
|
562
644
|
const listMyIdentities = () => authed("GET", "/v1/me/identities", meIdentitiesListResponseSchema);
|
|
563
|
-
const linkMyIdentity = (provider
|
|
645
|
+
const linkMyIdentity = async (provider) => {
|
|
646
|
+
if (!URL.canParse(config.redirectUri)) {
|
|
647
|
+
return err({ type: "invalid_response", message: "redirectUri is not a valid URL" });
|
|
648
|
+
}
|
|
649
|
+
const accessToken = await getAccessToken();
|
|
650
|
+
if (!accessToken.ok)
|
|
651
|
+
return accessToken;
|
|
652
|
+
const currentUser = await request("GET", "/v1/me", meUserSchema, {
|
|
653
|
+
accessToken: accessToken.value,
|
|
654
|
+
});
|
|
655
|
+
if (!currentUser.ok)
|
|
656
|
+
return currentUser;
|
|
657
|
+
const pkce = await generatePkcePair();
|
|
658
|
+
const state = generateState();
|
|
659
|
+
const pending = {
|
|
660
|
+
state,
|
|
661
|
+
provider,
|
|
662
|
+
codeVerifier: pkce.verifier,
|
|
663
|
+
redirectUri: config.redirectUri,
|
|
664
|
+
clientId: config.clientId,
|
|
665
|
+
userId: currentUser.value.user_id,
|
|
666
|
+
createdAt: now(),
|
|
667
|
+
};
|
|
668
|
+
if (!(await registerPendingIdentityLink(pending))) {
|
|
669
|
+
return err({
|
|
670
|
+
type: "invalid_response",
|
|
671
|
+
message: "sessionStorage is required to persist identity-link PKCE state",
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
const body = {
|
|
675
|
+
redirect_uri: config.redirectUri,
|
|
676
|
+
code_challenge: pkce.challenge,
|
|
677
|
+
code_challenge_method: "S256",
|
|
678
|
+
state,
|
|
679
|
+
};
|
|
680
|
+
const started = await request("POST", `/v1/me/identities/${encodeSegment(provider)}/link`, meIdentityLinkResponseSchema, { body, accessToken: accessToken.value });
|
|
681
|
+
if (!started.ok) {
|
|
682
|
+
await clearPendingIdentityLink(state);
|
|
683
|
+
return started;
|
|
684
|
+
}
|
|
685
|
+
const redirected = await Promise.resolve()
|
|
686
|
+
.then(() => {
|
|
687
|
+
redirectPort.assign(started.value.authorization_url);
|
|
688
|
+
return ok({ state });
|
|
689
|
+
})
|
|
690
|
+
.then((result) => result, (cause) => err({
|
|
691
|
+
type: "network_error",
|
|
692
|
+
message: cause instanceof Error ? cause.message : "Failed to open the system browser",
|
|
693
|
+
retryable: true,
|
|
694
|
+
}));
|
|
695
|
+
if (!redirected.ok) {
|
|
696
|
+
await clearPendingIdentityLink(state);
|
|
697
|
+
return redirected;
|
|
698
|
+
}
|
|
699
|
+
return redirected;
|
|
700
|
+
};
|
|
701
|
+
const isRetryableCallbackError = (error) => error.type === "network_error" ||
|
|
702
|
+
error.type === "rate_limited" ||
|
|
703
|
+
(error.type === "problem_details" && (error.status === 408 || error.status >= 500)) ||
|
|
704
|
+
(error.type === "oauth_error" &&
|
|
705
|
+
((error.status ?? 0) === 408 ||
|
|
706
|
+
(error.status ?? 0) >= 500 ||
|
|
707
|
+
error.code === "server_error" ||
|
|
708
|
+
error.code === "temporarily_unavailable"));
|
|
709
|
+
const completeMyIdentityLink = async (provider, callbackUrl) => {
|
|
710
|
+
if (!URL.canParse(callbackUrl) || !URL.canParse(config.redirectUri)) {
|
|
711
|
+
return err({ type: "invalid_response", message: "identity-link callback URL is invalid" });
|
|
712
|
+
}
|
|
713
|
+
const callback = new URL(callbackUrl);
|
|
714
|
+
const registeredRedirect = new URL(config.redirectUri);
|
|
715
|
+
if (callback.origin !== registeredRedirect.origin ||
|
|
716
|
+
callback.pathname !== registeredRedirect.pathname) {
|
|
717
|
+
return err({
|
|
718
|
+
type: "invalid_response",
|
|
719
|
+
message: "callback is not on the registered redirect URI",
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
const states = callback.searchParams.getAll("state");
|
|
723
|
+
if (states.length !== 1 || states[0] === undefined || states[0].length === 0) {
|
|
724
|
+
return err({ type: "state_mismatch" });
|
|
725
|
+
}
|
|
726
|
+
const state = states[0];
|
|
727
|
+
const pending = await getPendingIdentityLink(state);
|
|
728
|
+
if (pending === null)
|
|
729
|
+
return err({ type: "state_mismatch" });
|
|
730
|
+
if (pending.provider !== provider) {
|
|
731
|
+
return err({
|
|
732
|
+
type: "invalid_response",
|
|
733
|
+
message: "callback provider does not match pending link",
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
const reasons = callback.searchParams.getAll("reason");
|
|
737
|
+
if (reasons.length > 0) {
|
|
738
|
+
await clearPendingIdentityLink(state);
|
|
739
|
+
return err({
|
|
740
|
+
type: "invalid_response",
|
|
741
|
+
message: `identity-link callback failed: ${reasons[0] ?? "unknown reason"}`,
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
const codes = callback.searchParams.getAll("link_code");
|
|
745
|
+
if (codes.length !== 1 || codes[0] === undefined || codes[0].length === 0) {
|
|
746
|
+
await clearPendingIdentityLink(state);
|
|
747
|
+
return err({
|
|
748
|
+
type: "invalid_response",
|
|
749
|
+
message: "callback is missing exactly one link_code",
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
if (tokenSet === null) {
|
|
753
|
+
const restored = await restoreSession();
|
|
754
|
+
if (!restored.ok) {
|
|
755
|
+
if (!isRetryableCallbackError(restored.error))
|
|
756
|
+
await clearPendingIdentityLink(state);
|
|
757
|
+
return restored;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
const accessToken = await getAccessToken();
|
|
761
|
+
if (!accessToken.ok) {
|
|
762
|
+
if (!isRetryableCallbackError(accessToken.error))
|
|
763
|
+
await clearPendingIdentityLink(state);
|
|
764
|
+
return accessToken;
|
|
765
|
+
}
|
|
766
|
+
const currentUser = await request("GET", "/v1/me", meUserSchema, {
|
|
767
|
+
accessToken: accessToken.value,
|
|
768
|
+
});
|
|
769
|
+
if (!currentUser.ok) {
|
|
770
|
+
if (!isRetryableCallbackError(currentUser.error))
|
|
771
|
+
await clearPendingIdentityLink(state);
|
|
772
|
+
return currentUser;
|
|
773
|
+
}
|
|
774
|
+
if (pending.userId !== currentUser.value.user_id || pending.clientId !== config.clientId) {
|
|
775
|
+
await clearPendingIdentityLink(state);
|
|
776
|
+
return err({ type: "state_mismatch" });
|
|
777
|
+
}
|
|
778
|
+
const body = {
|
|
779
|
+
code: codes[0],
|
|
780
|
+
code_verifier: pending.codeVerifier,
|
|
781
|
+
};
|
|
782
|
+
const completed = await request("POST", `/v1/me/identities/${encodeSegment(provider)}/link/complete`, meIdentityLinkCompleteResponseSchema, { body, accessToken: accessToken.value });
|
|
783
|
+
if (completed.ok) {
|
|
784
|
+
await clearPendingIdentityLink(state);
|
|
785
|
+
return completed;
|
|
786
|
+
}
|
|
787
|
+
if (!isRetryableCallbackError(completed.error) &&
|
|
788
|
+
!(completed.error.type === "problem_details" &&
|
|
789
|
+
completed.error.status === 503 &&
|
|
790
|
+
completed.error.code === "identity_link_code_unavailable")) {
|
|
791
|
+
await clearPendingIdentityLink(state);
|
|
792
|
+
}
|
|
793
|
+
return completed;
|
|
794
|
+
};
|
|
564
795
|
const unlinkMyIdentity = (identityId) => authed("DELETE", `/v1/me/identities/${encodeSegment(identityId)}`, meIdentityUnlinkResponseSchema);
|
|
565
796
|
const listMySessions = () => authed("GET", "/v1/me/sessions", meSessionsListResponseSchema);
|
|
566
797
|
const revokeMySession = (sessionId) => authed("DELETE", `/v1/me/sessions/${encodeSegment(sessionId)}`, meSessionRevokeResponseSchema);
|
|
@@ -569,6 +800,27 @@ export const createBrowserAuthClient = (config) => {
|
|
|
569
800
|
const verifyMyEmailChangeOld = (input) => authed("POST", "/v1/me/email/change/verify-old", meEmailChangeVerifyOldResponseSchema, input);
|
|
570
801
|
const verifyMyEmailChangeNew = (input) => authed("POST", "/v1/me/email/change/verify-new", meEmailChangeVerifyNewResponseSchema, input);
|
|
571
802
|
const deleteMyAccount = () => authed("DELETE", "/v1/me", meDeleteResponseSchema);
|
|
803
|
+
const completeMyRecovery = async (input) => {
|
|
804
|
+
const accessToken = await getAccessToken();
|
|
805
|
+
if (!accessToken.ok)
|
|
806
|
+
return accessToken;
|
|
807
|
+
const body = { confirmed: true };
|
|
808
|
+
const completed = await request("POST", "/v1/me/recovery/complete", meRecoveryCompleteResponseSchema, {
|
|
809
|
+
body,
|
|
810
|
+
accessToken: accessToken.value,
|
|
811
|
+
idempotencyKey: input.idempotencyKey,
|
|
812
|
+
});
|
|
813
|
+
if (!completed.ok)
|
|
814
|
+
return completed;
|
|
815
|
+
const cleared = await clearSessionAfterRecovery();
|
|
816
|
+
if (!cleared) {
|
|
817
|
+
return err({
|
|
818
|
+
type: "storage_error",
|
|
819
|
+
message: "The recovery succeeded but the refresh-token store could not be cleared",
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
return completed;
|
|
823
|
+
};
|
|
572
824
|
return {
|
|
573
825
|
getPublicConfig,
|
|
574
826
|
createTransaction,
|
|
@@ -608,6 +860,7 @@ export const createBrowserAuthClient = (config) => {
|
|
|
608
860
|
deleteMyPasskey,
|
|
609
861
|
listMyIdentities,
|
|
610
862
|
linkMyIdentity,
|
|
863
|
+
completeMyIdentityLink,
|
|
611
864
|
unlinkMyIdentity,
|
|
612
865
|
listMySessions,
|
|
613
866
|
revokeMySession,
|
|
@@ -616,5 +869,6 @@ export const createBrowserAuthClient = (config) => {
|
|
|
616
869
|
verifyMyEmailChangeOld,
|
|
617
870
|
verifyMyEmailChangeNew,
|
|
618
871
|
deleteMyAccount,
|
|
872
|
+
completeMyRecovery,
|
|
619
873
|
};
|
|
620
874
|
};
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { AdaptiveChallengeAction } from "@smartcrab/contracts-public";
|
|
1
2
|
import type { OAuthErrorCode } from "@smartcrab/contracts-public";
|
|
2
3
|
/**
|
|
3
4
|
* Error model for `@smartcrab/browser` (design.md §26.3, §32).
|
|
@@ -52,6 +53,14 @@ export interface ProblemDetailsError {
|
|
|
52
53
|
readonly detail?: string;
|
|
53
54
|
readonly requestId?: string;
|
|
54
55
|
}
|
|
56
|
+
export interface AdaptiveChallengeRequiredError {
|
|
57
|
+
readonly type: "adaptive_challenge_required";
|
|
58
|
+
readonly challengeId: string;
|
|
59
|
+
readonly siteKey: string;
|
|
60
|
+
readonly action: AdaptiveChallengeAction;
|
|
61
|
+
readonly transactionId: string;
|
|
62
|
+
readonly requestId?: string;
|
|
63
|
+
}
|
|
55
64
|
export interface OAuthFailureError {
|
|
56
65
|
readonly type: "oauth_error";
|
|
57
66
|
readonly code: OAuthErrorCode;
|
|
@@ -65,13 +74,17 @@ export interface StateMismatchError {
|
|
|
65
74
|
export interface NotAuthenticatedError {
|
|
66
75
|
readonly type: "not_authenticated";
|
|
67
76
|
}
|
|
77
|
+
export interface StorageFailureError {
|
|
78
|
+
readonly type: "storage_error";
|
|
79
|
+
readonly message: string;
|
|
80
|
+
}
|
|
68
81
|
export type WebAuthnFailureReason = "not_supported" | "cancelled" | "failed";
|
|
69
82
|
export interface WebAuthnFailureError {
|
|
70
83
|
readonly type: "webauthn_error";
|
|
71
84
|
readonly reason: WebAuthnFailureReason;
|
|
72
85
|
readonly message: string;
|
|
73
86
|
}
|
|
74
|
-
export type BrowserAuthError = NetworkFailureError | InvalidResponseError | RateLimitedError | ProblemDetailsError | OAuthFailureError | StateMismatchError | NotAuthenticatedError | WebAuthnFailureError;
|
|
87
|
+
export type BrowserAuthError = NetworkFailureError | InvalidResponseError | RateLimitedError | ProblemDetailsError | AdaptiveChallengeRequiredError | OAuthFailureError | StateMismatchError | NotAuthenticatedError | WebAuthnFailureError | StorageFailureError;
|
|
75
88
|
/** Validated RFC 9457 Problem Details body as sent by the platform (design.md §26.3). */
|
|
76
89
|
export interface ProblemDetailsWire {
|
|
77
90
|
readonly type: string;
|
package/dist/http.d.ts
CHANGED
|
@@ -36,6 +36,7 @@ export interface JsonRequest {
|
|
|
36
36
|
readonly body?: unknown;
|
|
37
37
|
readonly accessToken?: string;
|
|
38
38
|
readonly transactionSecret?: string;
|
|
39
|
+
readonly idempotencyKey?: string;
|
|
39
40
|
}
|
|
40
41
|
export declare const isOAuthErrorCode: (value: string) => value is OAuthErrorCode;
|
|
41
42
|
/**
|
package/dist/http.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { adaptiveChallengeRequiredResponseSchema } from "@smartcrab/contracts-public";
|
|
1
2
|
import { err, ok } from "@smartcrab/contracts-public";
|
|
2
3
|
import { OAUTH_ERROR_CODES } from "@smartcrab/contracts-public";
|
|
3
4
|
import { parseOAuthErrorWire, parseProblemDetailsWire } from "./errors.js";
|
|
@@ -44,6 +45,7 @@ export const requestJson = async (fetchPort, request, schema) => {
|
|
|
44
45
|
...(request.transactionSecret !== undefined
|
|
45
46
|
? { "x-transaction-secret": request.transactionSecret }
|
|
46
47
|
: {}),
|
|
48
|
+
...(request.idempotencyKey !== undefined ? { "Idempotency-Key": request.idempotencyKey } : {}),
|
|
47
49
|
};
|
|
48
50
|
const responseOutcome = await fetchPort(request.url, {
|
|
49
51
|
method: request.method,
|
|
@@ -77,6 +79,19 @@ export const requestJson = async (fetchPort, request, schema) => {
|
|
|
77
79
|
});
|
|
78
80
|
}
|
|
79
81
|
if (!response.ok) {
|
|
82
|
+
const adaptiveChallenge = adaptiveChallengeRequiredResponseSchema.safeParse(json);
|
|
83
|
+
if (adaptiveChallenge.success) {
|
|
84
|
+
return err({
|
|
85
|
+
type: "adaptive_challenge_required",
|
|
86
|
+
challengeId: adaptiveChallenge.data.challenge_id,
|
|
87
|
+
siteKey: adaptiveChallenge.data.site_key,
|
|
88
|
+
action: adaptiveChallenge.data.action,
|
|
89
|
+
transactionId: adaptiveChallenge.data.transaction_id,
|
|
90
|
+
...(adaptiveChallenge.data.request_id !== undefined
|
|
91
|
+
? { requestId: adaptiveChallenge.data.request_id }
|
|
92
|
+
: {}),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
80
95
|
const problem = parseProblemDetailsWire(json);
|
|
81
96
|
if (problem !== null) {
|
|
82
97
|
return err({
|
package/dist/index.d.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
export { createBrowserAuthClient } from "./client.js";
|
|
17
17
|
export type { AuthenticatedSession, BrowserAuthClient, BrowserAuthClientConfig, BrowserAuthListener, BrowserAuthSnapshot, BrowserTransaction, CreateTransactionInput, HostedAuthorization, RedirectPort, RefreshTokenStoragePort, } from "./client.js";
|
|
18
18
|
export { parseOAuthErrorWire, parseProblemDetailsWire } from "./errors.js";
|
|
19
|
-
export type { BrowserAuthError, InvalidResponseError, NetworkFailureError, NotAuthenticatedError, OAuthErrorWire, OAuthFailureError, ProblemDetailsError, ProblemDetailsWire, RateLimitedError, StateMismatchError, WebAuthnFailureError, WebAuthnFailureReason, } from "./errors.js";
|
|
19
|
+
export type { BrowserAuthError, InvalidResponseError, NetworkFailureError, NotAuthenticatedError, StorageFailureError, OAuthErrorWire, OAuthFailureError, ProblemDetailsError, ProblemDetailsWire, RateLimitedError, StateMismatchError, AdaptiveChallengeRequiredError, WebAuthnFailureError, WebAuthnFailureReason, } from "./errors.js";
|
|
20
20
|
export { buildUrl, requestJson } from "./http.js";
|
|
21
21
|
export type { FetchPort, HttpMethod, JsonRequest, WireSchema } from "./http.js";
|
|
22
22
|
export { generateNonce, generatePkcePair, generateState } from "./pkce.js";
|
|
@@ -25,4 +25,4 @@ export { base64UrlDecodeToBytes, base64UrlEncodeBytes, bufferToBase64Url } from
|
|
|
25
25
|
export { navigatorWebAuthnPort } from "./webauthn.js";
|
|
26
26
|
export type { WebAuthnBrowserPort } from "./webauthn.js";
|
|
27
27
|
export { err, ok } from "@smartcrab/contracts-public";
|
|
28
|
-
export type { EmailChallengeResponse, MeIdentitySummary, MeSessionSummary, MeUpdateRequest, MeUser, Outcome, PasskeySummary, PublicConfigResponse, SocialProvider, TransactionStatus, } from "@smartcrab/contracts-public";
|
|
28
|
+
export type { EmailChallengeResponse, MeIdentitySummary, MeSessionSummary, MeUpdateRequest, MeUser, Outcome, PasskeySummary, PublicConfigResponse, AdaptiveChallengeAction, MeIdentityLinkCompleteResponse, MeRecoveryCompleteResponse, SocialProvider, TransactionStatus, } from "@smartcrab/contracts-public";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@smartcrab/browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0-next-20261016193833",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"access": "public"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@smartcrab/contracts-public": "0.
|
|
30
|
+
"@smartcrab/contracts-public": "0.4.0-next-20261016193833"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"typescript": "5.9.3",
|