@haakco/custd-sdk 0.0.0-stage → 3.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/README.md +958 -2
  2. package/dist/admin-accounting-evidence.d.ts +48 -0
  3. package/dist/admin-accounting-evidence.js +24 -0
  4. package/dist/admin-app-releases.d.ts +116 -0
  5. package/dist/admin-app-releases.js +8 -0
  6. package/dist/admin-apps.d.ts +120 -0
  7. package/dist/admin-apps.js +47 -0
  8. package/dist/admin-auth-project-domain.d.ts +125 -0
  9. package/dist/admin-auth-project-domain.js +37 -0
  10. package/dist/admin-auth-projects.d.ts +989 -0
  11. package/dist/admin-auth-projects.js +527 -0
  12. package/dist/admin-campaign-email.d.ts +120 -0
  13. package/dist/admin-campaign-email.js +64 -0
  14. package/dist/admin-client-setup.d.ts +122 -0
  15. package/dist/admin-client-setup.js +408 -0
  16. package/dist/admin-data-labels.d.ts +124 -0
  17. package/dist/admin-data-labels.js +51 -0
  18. package/dist/admin-data-scopes.d.ts +93 -0
  19. package/dist/admin-data-scopes.js +154 -0
  20. package/dist/admin-email-relay.d.ts +66 -0
  21. package/dist/admin-email-relay.js +25 -0
  22. package/dist/admin-environment-policy.d.ts +32 -0
  23. package/dist/admin-environment-policy.js +26 -0
  24. package/dist/admin-error-issues.d.ts +91 -0
  25. package/dist/admin-error-issues.js +52 -0
  26. package/dist/admin-event-types.d.ts +57 -0
  27. package/dist/admin-event-types.js +28 -0
  28. package/dist/admin-impersonation.d.ts +48 -0
  29. package/dist/admin-impersonation.js +27 -0
  30. package/dist/admin-ingest-claims.d.ts +35 -0
  31. package/dist/admin-ingest-claims.js +26 -0
  32. package/dist/admin-managed-audit.d.ts +13 -0
  33. package/dist/admin-managed-audit.js +13 -0
  34. package/dist/admin-measurement-projects.d.ts +166 -0
  35. package/dist/admin-measurement-projects.js +120 -0
  36. package/dist/admin-notification-destinations.d.ts +31 -0
  37. package/dist/admin-notification-destinations.js +19 -0
  38. package/dist/admin-notification-webhooks.d.ts +64 -0
  39. package/dist/admin-notification-webhooks.js +42 -0
  40. package/dist/admin-oauth-client-admissions.d.ts +65 -0
  41. package/dist/admin-oauth-client-admissions.js +46 -0
  42. package/dist/admin-offboarding.d.ts +123 -0
  43. package/dist/admin-offboarding.js +129 -0
  44. package/dist/admin-predictions.d.ts +266 -0
  45. package/dist/admin-predictions.js +93 -0
  46. package/dist/admin-privacy-erasures.d.ts +74 -0
  47. package/dist/admin-privacy-erasures.js +73 -0
  48. package/dist/admin-retention.d.ts +99 -0
  49. package/dist/admin-retention.js +60 -0
  50. package/dist/admin-rls.d.ts +94 -0
  51. package/dist/admin-rls.js +33 -0
  52. package/dist/admin-sdk-usage.d.ts +41 -0
  53. package/dist/admin-sdk-usage.js +23 -0
  54. package/dist/admin-site-ai.d.ts +72 -0
  55. package/dist/admin-site-ai.js +1 -0
  56. package/dist/admin-site-analytics.d.ts +52 -0
  57. package/dist/admin-site-analytics.js +14 -0
  58. package/dist/admin-site-audit-pages.d.ts +76 -0
  59. package/dist/admin-site-audit-pages.js +27 -0
  60. package/dist/admin-site-campaign-links.d.ts +40 -0
  61. package/dist/admin-site-campaign-links.js +9 -0
  62. package/dist/admin-site-domains.d.ts +733 -0
  63. package/dist/admin-site-domains.js +768 -0
  64. package/dist/admin-site-export.d.ts +76 -0
  65. package/dist/admin-site-export.js +15 -0
  66. package/dist/admin-site-insights-tasks.d.ts +44 -0
  67. package/dist/admin-site-insights-tasks.js +28 -0
  68. package/dist/admin-site-insights.d.ts +527 -0
  69. package/dist/admin-site-insights.js +61 -0
  70. package/dist/admin-site-links.d.ts +87 -0
  71. package/dist/admin-site-links.js +16 -0
  72. package/dist/admin-site-monitors.d.ts +110 -0
  73. package/dist/admin-site-monitors.js +25 -0
  74. package/dist/admin-site-next-actions.d.ts +93 -0
  75. package/dist/admin-site-next-actions.js +36 -0
  76. package/dist/admin-site-page-queries.d.ts +63 -0
  77. package/dist/admin-site-page-queries.js +20 -0
  78. package/dist/admin-site-rankings.d.ts +98 -0
  79. package/dist/admin-site-rankings.js +46 -0
  80. package/dist/admin-site-regional-trends.d.ts +30 -0
  81. package/dist/admin-site-regional-trends.js +1 -0
  82. package/dist/admin-site-saved-reports.d.ts +45 -0
  83. package/dist/admin-site-saved-reports.js +13 -0
  84. package/dist/admin-site-search-pool.d.ts +77 -0
  85. package/dist/admin-site-search-pool.js +41 -0
  86. package/dist/admin-site-search-value.d.ts +97 -0
  87. package/dist/admin-site-search-value.js +29 -0
  88. package/dist/admin-site-status-page.d.ts +57 -0
  89. package/dist/admin-site-status-page.js +10 -0
  90. package/dist/admin-site-traffic.d.ts +145 -0
  91. package/dist/admin-site-traffic.js +32 -0
  92. package/dist/admin-site-web-data.d.ts +258 -0
  93. package/dist/admin-site-web-data.js +60 -0
  94. package/dist/admin-subject-exports.d.ts +79 -0
  95. package/dist/admin-subject-exports.js +44 -0
  96. package/dist/admin-support-access.d.ts +32 -0
  97. package/dist/admin-support-access.js +21 -0
  98. package/dist/admin-system.d.ts +283 -0
  99. package/dist/admin-system.js +65 -0
  100. package/dist/admin-tenant-storage.d.ts +35 -0
  101. package/dist/admin-tenant-storage.js +24 -0
  102. package/dist/admin-timeplans.d.ts +512 -0
  103. package/dist/admin-timeplans.js +200 -0
  104. package/dist/admin-uncertainty-models.d.ts +42 -0
  105. package/dist/admin-uncertainty-models.js +53 -0
  106. package/dist/admin-usage.d.ts +124 -0
  107. package/dist/admin-usage.js +169 -0
  108. package/dist/admin-users.d.ts +124 -0
  109. package/dist/admin-users.js +82 -0
  110. package/dist/admin-workflow-timings.d.ts +367 -0
  111. package/dist/admin-workflow-timings.js +117 -0
  112. package/dist/analytics-events.d.ts +167 -0
  113. package/dist/analytics-events.js +197 -0
  114. package/dist/analytics-reads.d.ts +81 -0
  115. package/dist/analytics-reads.js +5 -0
  116. package/dist/app-account.d.ts +84 -0
  117. package/dist/app-account.js +177 -0
  118. package/dist/app-alerts.d.ts +120 -0
  119. package/dist/app-alerts.js +44 -0
  120. package/dist/app-items.d.ts +786 -0
  121. package/dist/app-items.js +524 -0
  122. package/dist/app-live.d.ts +84 -0
  123. package/dist/app-live.js +228 -0
  124. package/dist/app-meetings.d.ts +95 -0
  125. package/dist/app-meetings.js +26 -0
  126. package/dist/app-models.d.ts +271 -0
  127. package/dist/app-models.js +83 -0
  128. package/dist/app-push.d.ts +64 -0
  129. package/dist/app-push.js +178 -0
  130. package/dist/backend-lifecycle.d.ts +85 -0
  131. package/dist/backend-lifecycle.js +212 -0
  132. package/dist/browser-manifest.json +7 -0
  133. package/dist/browser-script-BWnwDjAC.js +711 -0
  134. package/dist/browser-script.d.ts +1 -0
  135. package/dist/browser-script.js +5 -0
  136. package/dist/browser-sign-in.d.ts +153 -0
  137. package/dist/browser-sign-in.js +410 -0
  138. package/dist/browser-tracker.d.ts +142 -0
  139. package/dist/browser-tracker.js +775 -0
  140. package/dist/browser-web-vitals.d.ts +22 -0
  141. package/dist/browser-web-vitals.js +116 -0
  142. package/dist/browser.d.ts +10 -0
  143. package/dist/browser.js +10 -0
  144. package/dist/download-stream.d.ts +16 -0
  145. package/dist/download-stream.js +55 -0
  146. package/dist/error-capture.d.ts +62 -0
  147. package/dist/error-capture.js +168 -0
  148. package/dist/hosted-app.d.ts +115 -0
  149. package/dist/hosted-app.js +275 -0
  150. package/dist/index.d.ts +2324 -0
  151. package/dist/index.js +2226 -0
  152. package/dist/ingest-operations.d.ts +483 -0
  153. package/dist/ingest-operations.js +154 -0
  154. package/dist/measurement.d.ts +164 -0
  155. package/dist/measurement.js +104 -0
  156. package/dist/mobile-adapter.d.ts +25 -0
  157. package/dist/mobile-adapter.js +57 -0
  158. package/dist/mobile-context.d.ts +32 -0
  159. package/dist/mobile-context.js +156 -0
  160. package/dist/mobile-queue.d.ts +22 -0
  161. package/dist/mobile-queue.js +73 -0
  162. package/dist/oauth.d.ts +1 -0
  163. package/dist/oauth.js +8 -0
  164. package/dist/parsers.d.ts +149 -0
  165. package/dist/parsers.js +115 -0
  166. package/dist/public-reads.d.ts +79 -0
  167. package/dist/public-reads.js +57 -0
  168. package/dist/reporting-catalogue.d.ts +264 -0
  169. package/dist/reporting-catalogue.js +5 -0
  170. package/dist/reporting-state.d.ts +46 -0
  171. package/dist/reporting-state.js +76 -0
  172. package/dist/response-lists.d.ts +16 -0
  173. package/dist/response-lists.generated.d.ts +7 -0
  174. package/dist/response-lists.generated.js +1927 -0
  175. package/dist/response-lists.js +70 -0
  176. package/dist/response-validation.d.ts +30 -0
  177. package/dist/response-validation.js +94 -0
  178. package/dist/runtime-readiness.d.ts +30 -0
  179. package/dist/runtime-readiness.js +150 -0
  180. package/dist/schema-registry.d.ts +45 -0
  181. package/dist/schema-registry.js +9 -0
  182. package/dist/secure-url.d.ts +4 -0
  183. package/dist/secure-url.js +23 -0
  184. package/dist/site-ai-owner.d.ts +34 -0
  185. package/dist/site-ai-owner.js +99 -0
  186. package/dist/site-monitor-reports.d.ts +15 -0
  187. package/dist/site-monitor-reports.js +87 -0
  188. package/dist/testing/fake-custd.d.ts +150 -0
  189. package/dist/testing/fake-custd.js +842 -0
  190. package/dist/testing/fake-results.d.ts +30 -0
  191. package/dist/testing/fake-results.js +293 -0
  192. package/dist/testing.d.ts +2 -0
  193. package/dist/testing.js +3 -0
  194. package/dist/version.d.ts +10 -0
  195. package/dist/version.js +10 -0
  196. package/package.json +57 -4
@@ -0,0 +1,5 @@
1
+ import { installBrowserTrackerFromScript } from "./browser-tracker.js";
2
+ const script = Array.from(document.scripts).find((candidate) => candidate.src === import.meta.url);
3
+ void installBrowserTrackerFromScript(script)
4
+ .then((tracker) => tracker.installSpaTracking())
5
+ .catch(() => undefined);
@@ -0,0 +1,153 @@
1
+ /** Sign-in block of the hosted app discovery file `/.well-known/custd.json`. */
2
+ export type CustdDiscoverySignIn = {
3
+ issuer: string;
4
+ authorizationEndpoint: string;
5
+ tokenEndpoint: string;
6
+ endSessionEndpoint?: string;
7
+ /** Where the provider returns the browser after sign-out; `signOut` uses it by default. */
8
+ postLogoutRedirectUri?: string;
9
+ clientId: string;
10
+ /** The API audience the access token is issued for; sent as the authorize `audience` parameter. */
11
+ audience?: string;
12
+ };
13
+ /** The parts of `/.well-known/custd.json` that sign-in reads. */
14
+ export type CustdDiscoveryDocument = {
15
+ signIn?: CustdDiscoverySignIn;
16
+ };
17
+ /** Minimal storage contract; `sessionStorage` satisfies it. */
18
+ export type SignInStorage = Pick<Storage, "getItem" | "setItem" | "removeItem">;
19
+ export type BrowserSignInEndpoints = CustdDiscoverySignIn & {
20
+ redirectUri: string;
21
+ scopes?: string[];
22
+ };
23
+ export type BrowserSignInConfig = BrowserSignInEndpoints & {
24
+ storage?: SignInStorage;
25
+ fetch?: typeof fetch;
26
+ now?: () => number;
27
+ navigate?: (url: string) => void;
28
+ };
29
+ export type SignInDiscoveryOptions = {
30
+ redirectUri: string;
31
+ scopes?: string[];
32
+ };
33
+ /** Tokens returned by the token endpoint, with an absolute expiry. */
34
+ export type SignInSession = {
35
+ accessToken: string;
36
+ tokenType: string;
37
+ expiresAtMs: number;
38
+ refreshToken?: string;
39
+ idToken?: string;
40
+ scopes: string[];
41
+ };
42
+ export type SignInStartOptions = {
43
+ /** Same-origin path to return to after sign-in. Defaults to the current page. */
44
+ returnTo?: string;
45
+ };
46
+ export type SignInStart = {
47
+ authorizationUrl: string;
48
+ };
49
+ export type SignInCompletion = {
50
+ session: SignInSession;
51
+ returnTo: string;
52
+ };
53
+ export type SignOutOptions = {
54
+ postLogoutRedirectUri?: string;
55
+ };
56
+ export type SignOutResult = {
57
+ endSessionUrl?: string;
58
+ };
59
+ export declare const SIGN_IN_STATUSES: {
60
+ readonly signedOut: "signed_out";
61
+ readonly signingIn: "signing_in";
62
+ readonly signedIn: "signed_in";
63
+ readonly error: "error";
64
+ };
65
+ export type SignInStatus = (typeof SIGN_IN_STATUSES)[keyof typeof SIGN_IN_STATUSES];
66
+ export type SignInState = {
67
+ status: typeof SIGN_IN_STATUSES.signedOut;
68
+ } | {
69
+ status: typeof SIGN_IN_STATUSES.signingIn;
70
+ } | {
71
+ status: typeof SIGN_IN_STATUSES.signedIn;
72
+ session: SignInSession;
73
+ } | {
74
+ status: typeof SIGN_IN_STATUSES.error;
75
+ error: SignInError;
76
+ };
77
+ export type SignInRestoreResult = {
78
+ state: SignInState;
79
+ /** Set when this page load completed a sign-in redirect. */
80
+ returnTo?: string;
81
+ };
82
+ export declare const SIGN_IN_ERROR_CODES: {
83
+ readonly invalidDiscovery: "invalid_discovery";
84
+ readonly missingPendingSignIn: "missing_pending_sign_in";
85
+ readonly stateMismatch: "state_mismatch";
86
+ readonly issuerMismatch: "issuer_mismatch";
87
+ readonly authorizationDenied: "authorization_denied";
88
+ readonly missingCode: "missing_code";
89
+ readonly tokenRequestFailed: "token_request_failed";
90
+ readonly invalidTokenResponse: "invalid_token_response";
91
+ readonly noRefreshToken: "no_refresh_token";
92
+ };
93
+ export type SignInErrorCode = (typeof SIGN_IN_ERROR_CODES)[keyof typeof SIGN_IN_ERROR_CODES];
94
+ export declare class SignInError extends Error {
95
+ readonly code: SignInErrorCode;
96
+ readonly oauthError?: string | undefined;
97
+ readonly status?: number | undefined;
98
+ /** @param oauthError OAuth `error` value from the authorization server, when it sent one. */
99
+ constructor(code: SignInErrorCode, message: string, oauthError?: string | undefined, status?: number | undefined);
100
+ }
101
+ export declare const DEFAULT_SIGN_IN_SCOPES: readonly string[];
102
+ /** Reads and validates the sign-in endpoints from a discovery document. */
103
+ export declare function signInConfigFromDiscovery(document: CustdDiscoveryDocument, options: SignInDiscoveryOptions): BrowserSignInEndpoints;
104
+ /** RFC 7636 S256 challenge: base64url(SHA-256(verifier)) without padding. */
105
+ export declare function createSignInCodeChallenge(codeVerifier: string): Promise<string>;
106
+ export declare class BrowserSignIn {
107
+ private readonly config;
108
+ private readonly storage;
109
+ private readonly fetchImpl;
110
+ private readonly now;
111
+ private readonly navigate;
112
+ private readonly listeners;
113
+ private state;
114
+ private completion;
115
+ private refresh;
116
+ constructor(config: BrowserSignInConfig);
117
+ /** Current state for UI bindings; replaced (never mutated) on each change. */
118
+ getState(): SignInState;
119
+ subscribe(listener: () => void): () => void;
120
+ /** Stored session, or null. It may be expired; use `restore` to refresh it. */
121
+ currentSession(): SignInSession | null;
122
+ /** Creates and stores PKCE state, and returns the authorize URL. */
123
+ startSignIn(options?: SignInStartOptions): Promise<SignInStart>;
124
+ /** Starts sign-in and sends the browser to the authorization endpoint. */
125
+ signIn(options?: SignInStartOptions): Promise<void>;
126
+ /** Validates the redirect and exchanges its code. Pending state is single-use. */
127
+ completeSignIn(callbackUrl: string): Promise<SignInCompletion>;
128
+ /** Exchanges the stored refresh token. Concurrent calls share one request. */
129
+ refreshSession(): Promise<SignInSession>;
130
+ /**
131
+ * Settles state on page load: completes a sign-in redirect when `url` is the
132
+ * redirect URI, otherwise reads the stored session and refreshes it if expired.
133
+ */
134
+ restore(url?: string): Promise<SignInRestoreResult>;
135
+ /**
136
+ * Clears local sign-in state. When the provider has an end-session endpoint,
137
+ * sends the browser there and returns its URL.
138
+ */
139
+ signOut(options?: SignOutOptions): SignOutResult;
140
+ private initialState;
141
+ private exchangeCallback;
142
+ private exchangeRefreshToken;
143
+ private requestTokens;
144
+ private sessionFromTokenResponse;
145
+ /** A redirect back to the app while this tab has a sign-in in progress. */
146
+ private isPendingCallback;
147
+ private takePending;
148
+ private saveSession;
149
+ private clearSession;
150
+ private setState;
151
+ private scopes;
152
+ private storageKey;
153
+ }
@@ -0,0 +1,410 @@
1
+ // Browser sign-in for app users: OAuth 2.0 authorization code with PKCE (RFC 7636).
2
+ //
3
+ // The app is a public client, so no client secret is involved. Pending sign-in
4
+ // state and the token set live in sessionStorage by default. Tokens are never
5
+ // placed in error messages.
6
+ export const SIGN_IN_STATUSES = {
7
+ signedOut: "signed_out",
8
+ signingIn: "signing_in",
9
+ signedIn: "signed_in",
10
+ error: "error",
11
+ };
12
+ export const SIGN_IN_ERROR_CODES = {
13
+ invalidDiscovery: "invalid_discovery",
14
+ missingPendingSignIn: "missing_pending_sign_in",
15
+ stateMismatch: "state_mismatch",
16
+ issuerMismatch: "issuer_mismatch",
17
+ authorizationDenied: "authorization_denied",
18
+ missingCode: "missing_code",
19
+ tokenRequestFailed: "token_request_failed",
20
+ invalidTokenResponse: "invalid_token_response",
21
+ noRefreshToken: "no_refresh_token",
22
+ };
23
+ export class SignInError extends Error {
24
+ /** @param oauthError OAuth `error` value from the authorization server, when it sent one. */
25
+ constructor(code, message, oauthError, status) {
26
+ super(`custd: ${message}`);
27
+ this.code = code;
28
+ this.oauthError = oauthError;
29
+ this.status = status;
30
+ this.name = "SignInError";
31
+ }
32
+ }
33
+ export const DEFAULT_SIGN_IN_SCOPES = ["openid", "profile", "offline_access"];
34
+ const STORAGE_PREFIX = "custd:sign-in";
35
+ const EXPIRY_SKEW_MS = 30000;
36
+ const RANDOM_BYTES = 32;
37
+ /** Reads and validates the sign-in endpoints from a discovery document. */
38
+ export function signInConfigFromDiscovery(document, options) {
39
+ const signIn = document.signIn;
40
+ if (!signIn) {
41
+ throw new SignInError(SIGN_IN_ERROR_CODES.invalidDiscovery, "discovery document has no signIn section");
42
+ }
43
+ const config = {
44
+ issuer: signIn.issuer,
45
+ authorizationEndpoint: signIn.authorizationEndpoint,
46
+ tokenEndpoint: signIn.tokenEndpoint,
47
+ clientId: signIn.clientId,
48
+ redirectUri: options.redirectUri,
49
+ };
50
+ if (signIn.endSessionEndpoint)
51
+ config.endSessionEndpoint = signIn.endSessionEndpoint;
52
+ if (signIn.postLogoutRedirectUri)
53
+ config.postLogoutRedirectUri = signIn.postLogoutRedirectUri;
54
+ if (signIn.audience)
55
+ config.audience = signIn.audience;
56
+ if (options.scopes)
57
+ config.scopes = options.scopes;
58
+ validateEndpoints(config);
59
+ return config;
60
+ }
61
+ /** RFC 7636 S256 challenge: base64url(SHA-256(verifier)) without padding. */
62
+ export async function createSignInCodeChallenge(codeVerifier) {
63
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
64
+ return base64Url(new Uint8Array(digest));
65
+ }
66
+ export class BrowserSignIn {
67
+ constructor(config) {
68
+ this.listeners = new Set();
69
+ this.completion = null;
70
+ this.refresh = null;
71
+ validateEndpoints(config);
72
+ const { storage, fetch: fetchImpl, now, navigate, ...endpoints } = config;
73
+ this.config = endpoints;
74
+ this.storage = storage ?? defaultStorage();
75
+ this.fetchImpl = fetchImpl ?? ((input, init) => globalThis.fetch(input, init));
76
+ this.now = now ?? Date.now;
77
+ this.navigate = navigate ?? ((url) => window.location.assign(url));
78
+ this.state = this.initialState();
79
+ }
80
+ /** Current state for UI bindings; replaced (never mutated) on each change. */
81
+ getState() {
82
+ return this.state;
83
+ }
84
+ subscribe(listener) {
85
+ this.listeners.add(listener);
86
+ return () => this.listeners.delete(listener);
87
+ }
88
+ /** Stored session, or null. It may be expired; use `restore` to refresh it. */
89
+ currentSession() {
90
+ const stored = readJson(this.storage, this.storageKey("session"));
91
+ return isSession(stored) ? stored : null;
92
+ }
93
+ /** Creates and stores PKCE state, and returns the authorize URL. */
94
+ async startSignIn(options = {}) {
95
+ const pending = {
96
+ state: randomToken(),
97
+ codeVerifier: randomToken(),
98
+ returnTo: safeReturnTo(options.returnTo ?? currentPath()),
99
+ };
100
+ this.storage.setItem(this.storageKey("pending"), JSON.stringify(pending));
101
+ const url = new URL(this.config.authorizationEndpoint);
102
+ url.searchParams.set("response_type", "code");
103
+ url.searchParams.set("client_id", this.config.clientId);
104
+ url.searchParams.set("redirect_uri", this.config.redirectUri);
105
+ url.searchParams.set("scope", this.scopes().join(" "));
106
+ url.searchParams.set("state", pending.state);
107
+ url.searchParams.set("code_challenge", await createSignInCodeChallenge(pending.codeVerifier));
108
+ url.searchParams.set("code_challenge_method", "S256");
109
+ if (this.config.audience)
110
+ url.searchParams.set("audience", this.config.audience);
111
+ return { authorizationUrl: url.toString() };
112
+ }
113
+ /** Starts sign-in and sends the browser to the authorization endpoint. */
114
+ async signIn(options = {}) {
115
+ this.setState({ status: SIGN_IN_STATUSES.signingIn });
116
+ try {
117
+ const start = await this.startSignIn(options);
118
+ this.navigate(start.authorizationUrl);
119
+ }
120
+ catch (error) {
121
+ this.setState({ status: SIGN_IN_STATUSES.error, error: toSignInError(error) });
122
+ throw error;
123
+ }
124
+ }
125
+ /** Validates the redirect and exchanges its code. Pending state is single-use. */
126
+ completeSignIn(callbackUrl) {
127
+ this.completion ?? (this.completion = this.exchangeCallback(callbackUrl).finally(() => {
128
+ this.completion = null;
129
+ }));
130
+ return this.completion;
131
+ }
132
+ /** Exchanges the stored refresh token. Concurrent calls share one request. */
133
+ refreshSession() {
134
+ this.refresh ?? (this.refresh = this.exchangeRefreshToken().finally(() => {
135
+ this.refresh = null;
136
+ }));
137
+ return this.refresh;
138
+ }
139
+ /**
140
+ * Settles state on page load: completes a sign-in redirect when `url` is the
141
+ * redirect URI, otherwise reads the stored session and refreshes it if expired.
142
+ */
143
+ async restore(url = currentHref()) {
144
+ if (this.isPendingCallback(url)) {
145
+ this.setState({ status: SIGN_IN_STATUSES.signingIn });
146
+ try {
147
+ const completion = await this.completeSignIn(url);
148
+ return { state: this.state, returnTo: completion.returnTo };
149
+ }
150
+ catch (error) {
151
+ this.setState({ status: SIGN_IN_STATUSES.error, error: toSignInError(error) });
152
+ return { state: this.state };
153
+ }
154
+ }
155
+ const session = this.currentSession();
156
+ if (session && session.expiresAtMs - EXPIRY_SKEW_MS <= this.now() && session.refreshToken) {
157
+ try {
158
+ await this.refreshSession();
159
+ }
160
+ catch (error) {
161
+ this.storage.removeItem(this.storageKey("session"));
162
+ this.setState({ status: SIGN_IN_STATUSES.error, error: toSignInError(error) });
163
+ }
164
+ }
165
+ else if (!session || session.expiresAtMs <= this.now()) {
166
+ this.clearSession();
167
+ }
168
+ return { state: this.state };
169
+ }
170
+ /**
171
+ * Clears local sign-in state. When the provider has an end-session endpoint,
172
+ * sends the browser there and returns its URL.
173
+ */
174
+ signOut(options = {}) {
175
+ const idToken = this.currentSession()?.idToken;
176
+ this.storage.removeItem(this.storageKey("pending"));
177
+ this.clearSession();
178
+ if (!this.config.endSessionEndpoint)
179
+ return {};
180
+ const url = new URL(this.config.endSessionEndpoint);
181
+ url.searchParams.set("client_id", this.config.clientId);
182
+ if (idToken)
183
+ url.searchParams.set("id_token_hint", idToken);
184
+ const postLogoutRedirectUri = options.postLogoutRedirectUri ?? this.config.postLogoutRedirectUri;
185
+ if (postLogoutRedirectUri)
186
+ url.searchParams.set("post_logout_redirect_uri", postLogoutRedirectUri);
187
+ const endSessionUrl = url.toString();
188
+ this.navigate(endSessionUrl);
189
+ return { endSessionUrl };
190
+ }
191
+ initialState() {
192
+ if (this.isPendingCallback(currentHref()))
193
+ return { status: SIGN_IN_STATUSES.signingIn };
194
+ const session = this.currentSession();
195
+ return session ? { status: SIGN_IN_STATUSES.signedIn, session } : { status: SIGN_IN_STATUSES.signedOut };
196
+ }
197
+ async exchangeCallback(callbackUrl) {
198
+ const params = new URL(callbackUrl).searchParams;
199
+ const pending = this.takePending();
200
+ if (!pending) {
201
+ throw new SignInError(SIGN_IN_ERROR_CODES.missingPendingSignIn, "no sign-in is in progress in this tab");
202
+ }
203
+ if (params.get("state") !== pending.state) {
204
+ throw new SignInError(SIGN_IN_ERROR_CODES.stateMismatch, "sign-in state does not match; the redirect was refused");
205
+ }
206
+ const issuer = params.get("iss");
207
+ if (issuer !== null && issuer !== this.config.issuer) {
208
+ throw new SignInError(SIGN_IN_ERROR_CODES.issuerMismatch, "sign-in redirect came from an unexpected issuer");
209
+ }
210
+ const oauthError = params.get("error");
211
+ if (oauthError !== null) {
212
+ throw new SignInError(SIGN_IN_ERROR_CODES.authorizationDenied, "sign-in was not completed", oauthError);
213
+ }
214
+ const code = params.get("code");
215
+ if (!code)
216
+ throw new SignInError(SIGN_IN_ERROR_CODES.missingCode, "sign-in redirect has no code");
217
+ const session = await this.requestTokens({
218
+ grant_type: "authorization_code",
219
+ code,
220
+ redirect_uri: this.config.redirectUri,
221
+ client_id: this.config.clientId,
222
+ code_verifier: pending.codeVerifier,
223
+ });
224
+ this.saveSession(session);
225
+ return { session, returnTo: pending.returnTo };
226
+ }
227
+ async exchangeRefreshToken() {
228
+ const refreshToken = this.currentSession()?.refreshToken;
229
+ if (!refreshToken)
230
+ throw new SignInError(SIGN_IN_ERROR_CODES.noRefreshToken, "session has no refresh token");
231
+ const session = await this.requestTokens({ grant_type: "refresh_token", refresh_token: refreshToken, client_id: this.config.clientId }, refreshToken);
232
+ this.saveSession(session);
233
+ return session;
234
+ }
235
+ async requestTokens(form, previousRefreshToken) {
236
+ const response = await this.fetchImpl(this.config.tokenEndpoint, {
237
+ method: "POST",
238
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
239
+ body: new URLSearchParams(form).toString(),
240
+ });
241
+ const body = (await response.json().catch(() => ({})));
242
+ if (!response.ok) {
243
+ const oauthError = typeof body.error === "string" ? body.error : undefined;
244
+ throw new SignInError(SIGN_IN_ERROR_CODES.tokenRequestFailed, `token endpoint returned ${response.status}${oauthError ? ` (${oauthError})` : ""}`, oauthError, response.status);
245
+ }
246
+ return this.sessionFromTokenResponse(body, previousRefreshToken);
247
+ }
248
+ sessionFromTokenResponse(body, previousRefreshToken) {
249
+ if (typeof body.access_token !== "string" ||
250
+ typeof body.token_type !== "string" ||
251
+ typeof body.expires_in !== "number") {
252
+ throw new SignInError(SIGN_IN_ERROR_CODES.invalidTokenResponse, "token response needs access_token, token_type and expires_in");
253
+ }
254
+ const session = {
255
+ accessToken: body.access_token,
256
+ tokenType: body.token_type,
257
+ expiresAtMs: this.now() + body.expires_in * 1000,
258
+ scopes: typeof body.scope === "string" ? body.scope.split(" ").filter(Boolean) : this.scopes(),
259
+ };
260
+ const refreshToken = typeof body.refresh_token === "string" ? body.refresh_token : previousRefreshToken;
261
+ if (refreshToken)
262
+ session.refreshToken = refreshToken;
263
+ const idToken = sessionIdToken(body.id_token, this.currentSession()?.idToken);
264
+ if (idToken)
265
+ session.idToken = idToken;
266
+ return session;
267
+ }
268
+ /** A redirect back to the app while this tab has a sign-in in progress. */
269
+ isPendingCallback(url) {
270
+ if (this.completion === null && this.storage.getItem(this.storageKey("pending")) === null)
271
+ return false;
272
+ const current = new URL(url);
273
+ const redirect = new URL(this.config.redirectUri);
274
+ return (current.origin === redirect.origin &&
275
+ current.pathname === redirect.pathname &&
276
+ (current.searchParams.has("code") || current.searchParams.has("error")));
277
+ }
278
+ takePending() {
279
+ const key = this.storageKey("pending");
280
+ const stored = readJson(this.storage, key);
281
+ this.storage.removeItem(key);
282
+ return isPending(stored) ? stored : null;
283
+ }
284
+ saveSession(session) {
285
+ this.storage.setItem(this.storageKey("session"), JSON.stringify(session));
286
+ this.setState({ status: SIGN_IN_STATUSES.signedIn, session });
287
+ }
288
+ clearSession() {
289
+ this.storage.removeItem(this.storageKey("session"));
290
+ this.setState({ status: SIGN_IN_STATUSES.signedOut });
291
+ }
292
+ setState(state) {
293
+ this.state = state;
294
+ for (const listener of this.listeners)
295
+ listener();
296
+ }
297
+ scopes() {
298
+ return this.config.scopes ? [...this.config.scopes] : [...DEFAULT_SIGN_IN_SCOPES];
299
+ }
300
+ storageKey(kind) {
301
+ return `${STORAGE_PREFIX}:${this.config.clientId}:${kind}`;
302
+ }
303
+ }
304
+ function validateEndpoints(config) {
305
+ for (const field of ["issuer", "authorizationEndpoint", "tokenEndpoint", "clientId", "redirectUri"]) {
306
+ if (typeof config[field] !== "string" || config[field] === "") {
307
+ throw new SignInError(SIGN_IN_ERROR_CODES.invalidDiscovery, `sign-in ${field} is required`);
308
+ }
309
+ }
310
+ for (const field of ["authorizationEndpoint", "tokenEndpoint", "redirectUri"]) {
311
+ assertSecureOrLocalHTTP(config[field], field);
312
+ }
313
+ if (config.endSessionEndpoint)
314
+ assertSecureOrLocalHTTP(config.endSessionEndpoint, "endSessionEndpoint");
315
+ if (config.postLogoutRedirectUri)
316
+ assertSecureOrLocalHTTP(config.postLogoutRedirectUri, "postLogoutRedirectUri");
317
+ }
318
+ function assertSecureOrLocalHTTP(rawUrl, field) {
319
+ const parsed = new URL(rawUrl);
320
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(parsed.hostname);
321
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && local)) {
322
+ throw new SignInError(SIGN_IN_ERROR_CODES.invalidDiscovery, `sign-in ${field} must use https unless it targets localhost`);
323
+ }
324
+ }
325
+ function randomToken() {
326
+ return base64Url(crypto.getRandomValues(new Uint8Array(RANDOM_BYTES)));
327
+ }
328
+ function base64Url(bytes) {
329
+ let binary = "";
330
+ for (const byte of bytes)
331
+ binary += String.fromCharCode(byte);
332
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
333
+ }
334
+ function safeReturnTo(path) {
335
+ return path.startsWith("/") && !path.startsWith("//") ? path : "/";
336
+ }
337
+ function currentPath() {
338
+ if (typeof window === "undefined")
339
+ return "/";
340
+ const { pathname, search, hash } = window.location;
341
+ return `${pathname}${search}${hash}`;
342
+ }
343
+ function currentHref() {
344
+ return typeof window === "undefined" ? "http://localhost/" : window.location.href;
345
+ }
346
+ function readJson(storage, key) {
347
+ const raw = storage.getItem(key);
348
+ if (raw === null)
349
+ return null;
350
+ try {
351
+ return JSON.parse(raw);
352
+ }
353
+ catch {
354
+ storage.removeItem(key);
355
+ return null;
356
+ }
357
+ }
358
+ function isPending(value) {
359
+ const record = value;
360
+ return (typeof record?.state === "string" && typeof record.codeVerifier === "string" && typeof record.returnTo === "string");
361
+ }
362
+ function isSession(value) {
363
+ const record = value;
364
+ return (typeof record?.accessToken === "string" &&
365
+ typeof record.tokenType === "string" &&
366
+ typeof record.expiresAtMs === "number" &&
367
+ Array.isArray(record.scopes));
368
+ }
369
+ function toSignInError(error) {
370
+ if (error instanceof SignInError)
371
+ return error;
372
+ return new SignInError(SIGN_IN_ERROR_CODES.tokenRequestFailed, "sign-in request failed");
373
+ }
374
+ function defaultStorage() {
375
+ if (typeof sessionStorage !== "undefined")
376
+ return sessionStorage;
377
+ const items = new Map();
378
+ return {
379
+ getItem: (key) => items.get(key) ?? null,
380
+ setItem: (key, value) => {
381
+ items.set(key, value);
382
+ },
383
+ removeItem: (key) => {
384
+ items.delete(key);
385
+ },
386
+ };
387
+ }
388
+ /**
389
+ * The ID token kept for sign-out. A refreshed ID token carries no `sid`, and the provider refuses an
390
+ * end-session request whose hint has none, so the sign-in token stays until a new one names a session.
391
+ */
392
+ function sessionIdToken(issued, previous) {
393
+ if (typeof issued !== "string")
394
+ return previous;
395
+ if (previous && !idTokenHasSessionId(issued) && idTokenHasSessionId(previous))
396
+ return previous;
397
+ return issued;
398
+ }
399
+ function idTokenHasSessionId(token) {
400
+ const payload = token.split(".")[1];
401
+ if (!payload)
402
+ return false;
403
+ try {
404
+ const claims = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
405
+ return typeof claims === "object" && claims !== null && typeof claims.sid === "string";
406
+ }
407
+ catch {
408
+ return false;
409
+ }
410
+ }