@tenminuteschool/auth-react 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,30 +9,61 @@ Add "Login with 10MinuteSchool" to any React app in minutes.
9
9
  Copy and paste this into your AI assistant to get a full working implementation:
10
10
 
11
11
  ```
12
- Implement "Login with 10MinuteSchool" in this project using @tenminuteschool/auth-react.
12
+ Implement "Login with 10MinuteSchool" in this project using the latest version of @tenminuteschool/auth-react.
13
+ It must support two ways of logging in:
14
+ a) the user clicks the "Login with 10MinuteSchool" button, and
15
+ b) automatic login when the 10MinuteSchool app or website opens any page of this
16
+ project with the user's token in the URL (?token=... or ?tenms_token=...).
13
17
 
14
18
  Steps:
15
- 1. Install: npm install @tenminuteschool/auth-react
19
+ 1. Install the latest version: npm install @tenminuteschool/auth-react@latest
16
20
 
17
- 2. Add to .env.local:
18
- NEXT_PUBLIC_TENMS_CLIENT_ID=YOUR_CLIENT_ID
21
+ 2. Add the client ID to the env file. The variable must use this framework's public
22
+ (browser-exposed) prefix, otherwise it is undefined in the browser:
23
+ - Next.js: NEXT_PUBLIC_TENMS_CLIENT_ID=YOUR_CLIENT_ID
24
+ - Vite: VITE_TENMS_CLIENT_ID=YOUR_CLIENT_ID
25
+ - Other: use that framework's equivalent public prefix
19
26
 
20
- 3. Create lib/auth.ts:
27
+ 3. Create lib/auth.ts (a client-only module):
21
28
  import { TenMSAuth } from '@tenminuteschool/auth-react';
22
- export const CLIENT_ID = process.env.NEXT_PUBLIC_TENMS_CLIENT_ID!;
29
+ export const CLIENT_ID = <the public env var from step 2>;
23
30
  export const auth = new TenMSAuth({ clientId: CLIENT_ID, storage: 'localStorage' });
24
31
 
25
- 4. Create a login page that:
26
- - Imports LoginButton and CLIENT_ID from the files above
27
- - Shows the button with clientId={CLIENT_ID} and onSuccess handler
28
- - In onSuccess, calls auth.handleLoginSuccess(response) then redirects to /dashboard
29
- - If auth.isLoggedIn() on mount, immediately redirects to /dashboard
30
-
31
- 5. On the dashboard page:
32
- - Get the user with auth.getUser() — it returns { sub, name, email, picture }
33
- - Add a logout button that calls auth.logout() then redirects back to the login page
32
+ 4. Wrap the whole app ONCE at the root with the provider:
33
+ import { TenMSAuthProvider } from '@tenminuteschool/auth-react';
34
+ <TenMSAuthProvider auth={auth}>{children}</TenMSAuthProvider>
35
+ - The provider reads ?token= / ?tenms_token= on load, logs the user in, and removes the token from the URL.
36
+ - In Next.js App Router, put the provider in a 'use client' component and render it from the root layout.
37
+
38
+ 5. Everywhere you need the user, use the hook instead of reading storage directly:
39
+ const { user, loading, refresh } = useTenMSAuth();
40
+ - user is { sub, name, email, phone, picture } or null.
41
+ - IMPORTANT: while loading is true, render a loader and do NOT redirect anywhere.
42
+ Redirecting before loading is false drops the ?token= from the URL and breaks auto-login.
43
+
44
+ 6. Create a login page (client component) that:
45
+ - If !loading && user, redirects to /dashboard.
46
+ - Otherwise shows <LoginButton clientId={CLIENT_ID} onSuccess={...} onError={...} />.
47
+ - In onSuccess: await auth.handleLoginSuccess(response); refresh(); then redirect to /dashboard.
48
+
49
+ 7. On the dashboard page (client component):
50
+ - If !loading && !user, redirect to the login page.
51
+ - Show the user's name/email/picture from useTenMSAuth().
52
+ - For API calls, get the token with await auth.getAccessToken() (it refreshes automatically).
53
+ - Add a logout button: await auth.logout(); refresh(); then redirect to the login page.
54
+
55
+ 8. The login popup returns to this site's root URL (/) with ?code=...&state=...
56
+ Make sure / loads the app (with the provider) in the browser and is NOT redirected
57
+ on the server (no middleware or server-side redirect on /), otherwise the code is
58
+ lost and the popup never finishes. Client-side redirects after loading are fine.
34
59
 
35
60
  Do not hardcode the client ID anywhere. Do not change the storage value.
61
+ Do not add any other code that reads or strips ?token= / ?tenms_token= — the provider handles it.
62
+
63
+ When you are done, tell me: "Ask the 10MinuteSchool team to register this site's exact
64
+ origin as a redirect URI for the client ID — no trailing slash, e.g. https://yourapp.com,
65
+ plus http://localhost:3000 for local dev — otherwise login fails with
66
+ 'redirect_uri is not registered'."
36
67
  ```
37
68
 
38
69
  ---
@@ -111,9 +142,43 @@ import { auth } from '@/lib/auth';
111
142
  auth.isLoggedIn() // true/false — no network call
112
143
  auth.getUser() // { sub, name, email, picture, ... } or null
113
144
  await auth.getAccessToken() // valid token string, auto-refreshes if expired
114
- await auth.logout() // revokes token + clears session
145
+ await auth.logout() // clears session (+ revokes it if it came from the login button)
146
+ ```
147
+
148
+ Button logins stay signed in for up to 30 days: the access token (1 hour) is refreshed automatically by `getAccessToken()`.
149
+
150
+ ---
151
+
152
+ ## Auto-login from the 10MS app / site (token handoff)
153
+
154
+ When the 10MS app or site opens your page with the user's token in the URL (`?token=` from the app, or `?tenms_token=`), the SDK can log them in without a click. No extra config is needed — just run the handoff on page load, either way below.
155
+
156
+ **With the React provider** — wrap the app root once:
157
+
158
+ ```tsx
159
+ import { TenMSAuthProvider, useTenMSAuth } from '@tenminuteschool/auth-react';
160
+
161
+ <TenMSAuthProvider auth={auth} onTokenHandoff={(session) => saveMyUser(session.user)}>
162
+ <App />
163
+ </TenMSAuthProvider>
164
+
165
+ const { user, loading, error, refresh } = useTenMSAuth();
115
166
  ```
116
167
 
168
+ **Without the provider** — call it once on page load:
169
+
170
+ ```ts
171
+ try {
172
+ const session = await auth.handleTokenHandoff(); // null when the URL has no token
173
+ if (session) saveMyUser(session.user);
174
+ } catch (err) {
175
+ // token invalid/expired (code: 'token_handoff_failed') — show the login button
176
+ }
177
+ ```
178
+
179
+ - The token is removed from the URL before it is validated, even if validation fails.- `logout()` does **not** revoke a handoff token, since it is the user's 10MS session and revoking it would log them out of the 10MS app too.
180
+ - Handoff sessions last as long as the 10MS token and have no refresh token.
181
+
117
182
  ---
118
183
 
119
184
  ## TenMSAuth options
@@ -124,4 +189,7 @@ await auth.logout() // revokes token + clears session
124
189
  | `storage` | `'cookie' \| 'localStorage'` | `'cookie'` | Use `localStorage` for SPAs, `cookie` for SSR |
125
190
  | `redirectUri` | `string` | `window.location.origin` | Override only if needed |
126
191
  | `scopes` | `string[]` | `['profile', 'email', 'phone']` | OAuth scopes |
192
+ | `handoffParams` | `string[]` | `['tenms_token', 'token']` | URL params read by `handleTokenHandoff()` |
193
+ | `baseUrl` | `string` | production auth API | Override for staging |
194
+ | `authorizeUrl` | `string` | production login page | Override for staging |
127
195
  | `debug` | `boolean` | `false` | Logs every OAuth step to the console |
package/dist/browser.d.ts CHANGED
@@ -5,9 +5,9 @@
5
5
  * React consumers should use the npm package instead:
6
6
  * import { LoginButton } from '@10minuteschool/auth';
7
7
  */
8
- export declare const VERSION = "0.1.0";
8
+ export declare const VERSION = "1.2.0";
9
9
  export { TenMSAuth } from './core/TenMSAuth';
10
- export type { AuthResponse, LoginButtonOptions, PopupOptions, TenMSAuthConfig, TokenResponse, UserInfo, } from './core/types';
10
+ export type { AuthResponse, LoginButtonOptions, PopupOptions, Session, SessionSource, TenMSAuthConfig, TokenResponse, UserInfo, } from './core/types';
11
11
  export { TenMSAuthError } from './core/types';
12
12
  export { generateCodeChallenge, generateCodeVerifier, generateState, } from './core/pkce';
13
13
  export { createLogger, truncate } from './utils/debug';
@@ -17,4 +17,6 @@ export { openPopup, waitForPopupRedirect } from './core/popup';
17
17
  export { TenMSLoginButtonElement, registerLoginButton, renderLoginButton, } from './ui/LoginButton';
18
18
  export { LoginButton } from './react/LoginButton';
19
19
  export type { LoginButtonProps } from './react/LoginButton';
20
+ export { TenMSAuthProvider, useTenMSAuth } from './react/TenMSAuthProvider';
21
+ export type { TenMSAuthContextValue, TenMSAuthProviderProps, } from './react/TenMSAuthProvider';
20
22
  //# sourceMappingURL=browser.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,eAAO,MAAM,OAAO,UAAU,CAAC;AAE/B,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,YAAY,EACV,YAAY,E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AACrE,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAE/D,OAAO,EACL,uBAAuB,EACvB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAI1B,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,YAAY,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC5E,YAAY,EACV,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,2BAA2B,CAAC"}
@@ -13,6 +13,7 @@ export declare class TenMSAuth {
13
13
  private readonly config;
14
14
  private readonly log;
15
15
  private readonly storage;
16
+ private refreshInFlight;
16
17
  constructor(config: TenMSAuthConfig);
17
18
  /**
18
19
  * Starts OAuth login in a popup window and returns the authorization code plus
@@ -60,6 +61,12 @@ export declare class TenMSAuth {
60
61
  * Fetches the current user's profile from the OAuth userinfo endpoint.
61
62
  */
62
63
  getUserInfo(accessToken: string): Promise<UserInfo>;
64
+ /**
65
+ * Handoff tokens come from the main-site login, not OAuth, so userinfo
66
+ * rejects them ("token is not associated with an OAuth session");
67
+ * `/v1/user/me` validates the signature server-side instead.
68
+ */
69
+ private getHandoffUser;
63
70
  /**
64
71
  * Requests token revocation for a previously issued OAuth token.
65
72
  *
@@ -79,22 +86,41 @@ export declare class TenMSAuth {
79
86
  */
80
87
  handleLoginSuccess(response: AuthResponse): Promise<Session>;
81
88
  /**
82
- * Returns a valid access token from storage, automatically refreshing it if
83
- * it has expired and a refresh token is available. Returns `null` when the
84
- * user is not logged in or the session cannot be recovered.
89
+ * Auto-login for links carrying a 10MS main-site access token, e.g.
90
+ * `?tenms_token=<token>` (param names come from `handoffParams`). Validates
91
+ * the token via `/v1/user/me` and stores it as the session. Returns `null`
92
+ * when the URL has no handoff param.
93
+ *
94
+ * Any prior session is replaced without revoking its token, since another
95
+ * app may still use it. Throws `TenMSAuthError` if the token is invalid or
96
+ * expired; the existing session is kept in that case.
97
+ */
98
+ handleTokenHandoff(): Promise<Session | null>;
99
+ /**
100
+ * Returns a valid access token from storage, refreshing it first when it is
101
+ * expired (or about to be) and a refresh token is available. Returns `null`
102
+ * when the user is not logged in or the session cannot be recovered.
85
103
  */
86
104
  getAccessToken(): Promise<string | null>;
105
+ private refreshSession;
106
+ /**
107
+ * Persists an OAuth session. With a refresh token, every key lives as long
108
+ * as it does: if the access-token cookie expired with the token,
109
+ * `getAccessToken` would see no session and never refresh.
110
+ */
111
+ private saveOAuthSession;
87
112
  /**
88
113
  * Returns the stored user profile, or `null` if no session exists.
89
114
  */
90
115
  getUser(): UserInfo | null;
91
116
  /**
92
- * Returns `true` when a non-expired access token exists in storage.
93
- * Does not make any network requests.
117
+ * Returns `true` when storage holds a non-expired access token or a refresh
118
+ * token that `getAccessToken()` can use. Does not make any network requests.
94
119
  */
95
120
  isLoggedIn(): boolean;
96
121
  /**
97
- * Revokes the current access token and clears the session from storage.
122
+ * Clears the session from storage. OAuth sessions are also revoked
123
+ * server-side; handoff sessions are not (see below).
98
124
  */
99
125
  logout(): Promise<void>;
100
126
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"TenMSAuth.d.ts","sourceRoot":"","sources":["../../src/core/TenMSAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,OAAO,EACZ,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,QAAQ,EAEd,MAAM,SAAS,CAAC;AAgCjB;;;;;;;;;GASG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA4B;IACnD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAiB;gBAE7B,MAAM,EAAE,eAAe;IAwCnC;;;;;;;OAOG;IACG,cAAc,CAAC,OAAO,GAAE,YAAiB,GAAG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ACG,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAoB7B;;OAEG;IACH,UAAU,IAAI,MAAM;IAIpB;;OAEG;IACH,WAAW,IAAI,MAAM;IAIrB,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,kBAAkB;IAS1B;;;;;OAKG;IACH,OAAO,CAAC,iBAAiB;CAW1B"}
@@ -12,6 +12,15 @@ export interface TenMSAuthConfig {
12
12
  */
13
13
  redirectUri?: string;
14
14
  scopes?: string[];
15
+ /** Auth API base URL. Defaults to production (`https://api.10minuteschool.com/auth`). */
16
+ baseUrl?: string;
17
+ /** 10MS login page the popup/redirect flow opens. Defaults to production. */
18
+ authorizeUrl?: string;
19
+ /**
20
+ * URL query params checked, in order, for a token handoff (see
21
+ * `handleTokenHandoff`). Defaults to `['tenms_token', 'token']`.
22
+ */
23
+ handoffParams?: string[];
15
24
  /**
16
25
  * Where to persist the session (access token, refresh token, user profile).
17
26
  * Defaults to `'cookie'`, which works in both browser and SSR environments.
@@ -26,10 +35,16 @@ export interface TenMSAuthConfig {
26
35
  */
27
36
  debug?: boolean;
28
37
  }
38
+ /**
39
+ * How the session was obtained: `'oauth'` from the popup/redirect flow,
40
+ * `'handoff'` from a 10MS main-site token passed in the URL.
41
+ */
42
+ export type SessionSource = 'oauth' | 'handoff';
29
43
  /** Session data persisted after a successful login. */
30
44
  export interface Session {
31
45
  user: UserInfo;
32
46
  accessToken: string;
47
+ source: SessionSource;
33
48
  }
34
49
  /** Result returned after authorization completes. */
35
50
  export interface AuthResponse {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/core/types.ts"],"names":[],"mappings":"AAAA,iDAAiD;AACjD,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,MAAM,CAAC;IAEjB;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAElB;;;;OAIG;IACH,OAAO,CAAC,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C,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,oDAAoD;AACpD,MAAM,WAAW,aAAa;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,QAAQ,CAAC;CACjB;AAED,iDAAiD;AACjD,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,4EAA4E;AAC5E,MAAM,WAAW,kBAAkB;IACjC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,IAAI,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,OAAO,CAAC;IACpC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,KAAK,IAAI,CAAC;IAC7C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAED;;;GAGG;AACH,qBAAa,cAAe,SAAQ,KAAK;IACvC,SAAgB,IAAI,EAAE,MAAM,CAAC;gBAEjB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;CAQ1C"}
package/dist/index.d.ts CHANGED
@@ -3,10 +3,10 @@
3
3
  * Public entrypoint for the @10minuteschool/auth browser SDK.
4
4
  */
5
5
  /** Current SDK version. */
6
- export declare const VERSION = "1.0.0";
6
+ export declare const VERSION = "1.2.0";
7
7
  export { TenMSAuth } from './core/TenMSAuth';
8
8
  /** Public types and error contract. */
9
- export type { AuthResponse, LoginButtonOptions, PopupOptions, Session, TenMSAuthConfig, TokenResponse, UserInfo, } from './core/types';
9
+ export type { AuthResponse, LoginButtonOptions, PopupOptions, Session, SessionSource, TenMSAuthConfig, TokenResponse, UserInfo, } from './core/types';
10
10
  export { TenMSAuthError } from './core/types';
11
11
  /** Low-level PKCE helpers. */
12
12
  export { generateCodeChallenge, generateCodeVerifier, generateState, } from './core/pkce';
@@ -20,4 +20,6 @@ export { openPopup, waitForPopupRedirect } from './core/popup';
20
20
  export { TenMSLoginButtonElement, registerLoginButton, renderLoginButton, } from './ui/LoginButton';
21
21
  export { LoginButton } from './react/LoginButton';
22
22
  export type { LoginButtonProps } from './react/LoginButton';
23
+ export { TenMSAuthProvider, useTenMSAuth } from './react/TenMSAuthProvider';
24
+ export type { TenMSAuthContextValue, TenMSAuthProviderProps, } from './react/TenMSAuthProvider';
23
25
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,2BAA2B;AAC3B,eAAO,MAAM,OAAO,UAAU,CAAC;AAE/B,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,uCAAuC;AACvC,YAAY,EACV,YAAY,EACZ,kBAAkB,EAClB,YAAY,EACZ,OAAO,EACP,eAAe,EACf,aAAa,EACb,QAAQ,GACT,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAE9C,8BAA8B;AAC9B,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,aAAa,GACd,MAAM,aAAa,CAAC;AAErB,8BAA8B;AAC9B,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACvD,YAAY,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAE5C,+BAA+B;AAC/B,YAAY,EAAE,WAAW,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,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC5E,YAAY,EACV,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,2BAA2B,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"LoginButton.d.ts","sourceRoot":"","sources":["../../src/react/LoginButton.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,uBAAuB,CAAC;AAG/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAWzE,MAAM,WAAW,gBAAiB,SAAQ,eAAe,EAAE,kBAAkB;IAC3E,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,qBAsElD"}
1
+ {"version":3,"file":"LoginButton.d.ts","sourceRoot":"","sources":["../../src/react/LoginButton.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,uBAAuB,CAAC;AAG/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAWzE,MAAM,WAAW,gBAAiB,SAAQ,eAAe,EAAE,kBAAkB;IAC3E,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,qBAwElD"}
@@ -0,0 +1,23 @@
1
+ import * as React from 'react';
2
+ import type { TenMSAuth } from '../core/TenMSAuth';
3
+ import type { Session, UserInfo } from '../core/types';
4
+ export interface TenMSAuthContextValue {
5
+ auth: TenMSAuth;
6
+ user: UserInfo | null;
7
+ /** `true` until the initial session check (including any `tenms_token` handoff) resolves. */
8
+ loading: boolean;
9
+ /** Set when a `tenms_token` handoff was present but failed. */
10
+ error: Error | null;
11
+ /** Re-reads the session from storage; call after `handleLoginSuccess()` or `logout()`. */
12
+ refresh: () => void;
13
+ }
14
+ export interface TenMSAuthProviderProps {
15
+ auth: TenMSAuth;
16
+ children: React.ReactNode;
17
+ /** Called after a URL token handoff logs the user in, e.g. to sync an app-owned user store. */
18
+ onTokenHandoff?: (session: Session) => void | Promise<void>;
19
+ }
20
+ /** Wrap the app root once; auto-logs in when the URL carries a handoff token (see `handoffParams`). */
21
+ export declare function TenMSAuthProvider({ auth, children, onTokenHandoff, }: TenMSAuthProviderProps): React.JSX.Element;
22
+ export declare function useTenMSAuth(): TenMSAuthContextValue;
23
+ //# sourceMappingURL=TenMSAuthProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TenMSAuthProvider.d.ts","sourceRoot":"","sources":["../../src/react/TenMSAuthProvider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGvD,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,SAAS,CAAC;IAChB,IAAI,EAAE,QAAQ,GAAG,IAAI,CAAC;IACtB,6FAA6F;IAC7F,OAAO,EAAE,OAAO,CAAC;IACjB,+DAA+D;IAC/D,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IACpB,0FAA0F;IAC1F,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAID,MAAM,WAAW,sBAAsB;IACrC,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B,+FAA+F;IAC/F,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7D;AAED,uGAAuG;AACvG,wBAAgB,iBAAiB,CAAC,EAChC,IAAI,EACJ,QAAQ,EACR,cAAc,GACf,EAAE,sBAAsB,qBA+CxB;AAED,wBAAgB,YAAY,IAAI,qBAAqB,CASpD"}
@@ -1,2 +1,2 @@
1
- "use strict";function e(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var t=e(require("react"));class n extends Error{constructor(e,t){super(e),this.name="TenMSAuthError",this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}const o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function i(e=64){a(e,43,128,"code_verifier length");const t=[];for(;t.length<e;){const n=new Uint8Array(e+16);crypto.getRandomValues(n);for(const i of n){if(t.length>=e)break;i<198&&t.push(o[i%66])}}return t.join("")}async function r(e){if(!e)throw new Error("codeVerifier is required to generate a code challenge");const t=(new TextEncoder).encode(e);return function(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.digest("SHA-256",t))}function s(e=32){a(e,1,1024,"state byte length");const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function a(e,t,n,o){if(!Number.isInteger(e)||e<t||e>n)throw new RangeError(`${o} must be an integer between ${t} and ${n}`)}const c="tenms_auth_popup_callback";function l(e){h(e.width,"popup width"),h(e.height,"popup height");const t="number"==typeof window.screenX?window.screenX:window.screenLeft,n="number"==typeof window.screenY?window.screenY:window.screenTop,o=Math.round(t+Math.max(0,(window.innerWidth-e.width)/2)),i=Math.round(n+Math.max(0,(window.innerHeight-e.height)/2)),r=[`width=${e.width}`,`height=${e.height}`,`left=${o}`,`top=${i}`,"toolbar=no","menubar=no","scrollbars=yes","resizable=yes","status=no"].join(",");return window.open(e.url,"tenms_auth_popup",r)}function d(e,t,o,i=3e5){if(!t)throw new Error("redirectUri is required to monitor popup redirects");if(!o)throw new Error("expectedState is required to validate the popup callback");let r;h(i,"popup timeout");try{r=new URL(t)}catch(e){throw new n(`redirectUri is not a valid URL: "${t}"`,"invalid_redirect_uri")}return new Promise((t,s)=>{const a=Date.now();let l,d=!1,h=null;const u=t=>{d||(d=!0,window.clearInterval(l),null==h||h.close(),e.closed||e.close(),t())},g=(e,i,r,a)=>{u(r?()=>s(new n(a||r,"oauth_error")):e?i===o?()=>t({code:e,state:i}):()=>s(new n("State mismatch — possible CSRF attack","state_mismatch")):()=>s(new n("No authorization code was returned to the redirect URI","missing_authorization_code")))};try{h=new BroadcastChannel(c),h.onmessage=e=>{var t,n,o,i;g(null!==(t=e.data.code)&&void 0!==t?t:null,null!==(n=e.data.state)&&void 0!==n?n:null,null!==(o=e.data.error)&&void 0!==o?o:null,null!==(i=e.data.errorDescription)&&void 0!==i?i:null)}}catch(e){h=null}l=window.setInterval(()=>{try{if(!e||e.closed)return void u(()=>s(new n("Login popup was closed","popup_closed")));if(Date.now()-a>i)return void u(()=>s(new n("Login timed out while waiting for the redirect URI","popup_timeout")));const t=e.location.href;if(!t)return;let o;try{o=new URL(t)}catch(e){return}if(o.origin!==r.origin||o.pathname!==r.pathname)return;g(o.searchParams.get("code"),o.searchParams.get("state"),o.searchParams.get("error"),o.searchParams.get("error_description"))}catch(e){e instanceof DOMException||u(()=>s(e instanceof Error?e:new Error(String(e))))}},500)})}function h(e,t){if(!Number.isInteger(e)||e<=0)throw new RangeError(`${t} must be a positive integer`)}const u="[TenMSAuth]",g="color:#22c55e;font-weight:700",f="color:inherit;font-weight:normal";function p(e){return e?w:m}const m={info:()=>{},warn:()=>{},error:()=>{}},w={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${u}%c ${e}`,g,f),console.table(t),console.groupEnd()):console.log(`%c${u}%c ${e}`,g,f)},warn(e,t){console.warn(`%c${u}%c ⚠ ${e}`,g,f,null!=t?t:"")},error(e,t){console.error(`%c${u}%c ✕ ${e}`,g,f,null!=t?t:"")}};function b(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}class _{get(e){const t=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return t?decodeURIComponent(t[1]):null}set(e,t,n){let o=`${e}=${encodeURIComponent(t)}; path=/; SameSite=Lax`;n&&(o+=`; expires=${new Date(1e3*n).toUTCString()}`),document.cookie=o}remove(e){document.cookie=`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`}clear(e){e.forEach(e=>this.remove(e))}}class v{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}clear(e){e.forEach(e=>this.remove(e))}}const k="https://api.10minuteschool.com/auth",y="https://10minuteschool.com/auth/login",S=["profile","email","phone"],x={ACCESS_TOKEN:"_tenms_access_token",REFRESH_TOKEN:"_tenms_refresh_token",EXPIRES_AT:"_tenms_expires_at",USER:"_tenms_user"};class E{constructor(e){var t,o;if(this.config=function(e){var t,o;const i=null===(t=e.clientId)||void 0===t?void 0:t.trim();if(!i)throw new n("clientId is required","missing_client_id");const r=(null===(o=e.redirectUri)||void 0===o?void 0:o.trim())||void 0,s=C(k,"baseUrl","invalid_base_url"),a=C(y,"authorizeUrl","invalid_authorize_url"),c=function(e){if(!Array.isArray(e)||0===e.length)return S;const t=e.map(e=>e.trim()).filter(Boolean);return t.length>0?t:S}(e.scopes);return{clientId:i,redirectUri:r,scopes:c,baseUrl:s,authorizeUrl:a}}(e),this.log=p(!0===e.debug),this.storage="localStorage"===(null!==(t=e.storage)&&void 0!==t?t:"cookie")?new v:new _,this.log.info("init",{clientId:this.config.clientId,redirectUri:this.config.redirectUri,baseUrl:this.config.baseUrl,authorizeUrl:this.config.authorizeUrl,scopes:this.config.scopes.join(" "),storage:null!==(o=e.storage)&&void 0!==o?o:"cookie",debug:!0===e.debug}),"undefined"!=typeof window&&window.opener){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),o=e.get("error");if(t||o)try{const i=new BroadcastChannel(c);i.postMessage({code:t,state:n,error:o,errorDescription:e.get("error_description")}),i.close()}catch(e){}}}async loginWithPopup(e={}){var t,o;const a=null!==(t=e.width)&&void 0!==t?t:500,c=null!==(o=e.height)&&void 0!==o?o:600;this.log.info("loginWithPopup:start",{width:a,height:c});const h=s(),u=i();this.log.info("loginWithPopup:pkce-generated",{state:b(h),codeVerifier:b(u)});const g=l({url:"about:blank",width:a,height:c});if(!g){const e=new n("Failed to open login popup. Please allow popups for this site.","popup_blocked");throw this.log.error("loginWithPopup:popup-blocked",e),e}if(g===window){const e=new n("The browser reused the current tab instead of opening a popup window.","popup_reused_opener");throw this.log.error("loginWithPopup:popup-reused-opener",e),e}this.log.info("loginWithPopup:popup-opened"),function(e){try{e.document.title="Signing in…",e.document.body.style.cssText="font-family:system-ui,sans-serif;padding:2rem;text-align:center",e.document.body.textContent="Signing in…"}catch(e){}}(g);try{const e=await r(u),t=this.buildAuthorizeUrl(h,e);this.log.info("loginWithPopup:navigating",{authorizeUrl:t,codeChallenge:b(e)}),g.location.href=t;const n=await d(g,this.requireRedirectUri(),h);return this.log.info("loginWithPopup:success",{code:b(n.code),state:b(n.state)}),{code:n.code,state:n.state,codeVerifier:u}}catch(e){throw g.closed||g.close(),this.log.error("loginWithPopup:error",e),e}}async loginWithRedirect(){this.log.info("loginWithRedirect:start");const e=s(),t=i(),n=await r(t);this.log.info("loginWithRedirect:pkce-generated",{state:b(e),codeVerifier:b(t),codeChallenge:b(n)}),function(e,t){sessionStorage.setItem(U("state"),e),sessionStorage.setItem(U("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[U("state"),U("code_verifier")]});const o=this.buildAuthorizeUrl(e,n);this.log.info("loginWithRedirect:navigating",{authorizeUrl:o}),window.location.href=o}handleRedirectCallback(){const e=new URLSearchParams(window.location.search),t=e.get("code"),o=e.get("state"),i=e.get("error"),r=e.get("error_description");if(!t&&!o&&!i)return this.log.info("handleRedirectCallback:not-a-callback"),null;this.log.info("handleRedirectCallback:callback-detected",{hasCode:Boolean(t),hasState:Boolean(o),error:null!=i?i:"(none)",errorDescription:null!=r?r:"(none)"});const s=sessionStorage.getItem(U("state")),a=sessionStorage.getItem(U("code_verifier"));if(!o||!s||o!==s){T();const e=new n("State mismatch — possible CSRF attack","state_mismatch");throw this.log.warn("handleRedirectCallback:state-mismatch",{receivedState:o?b(o):"(missing)",storedStatePresent:Boolean(s)}),e}if(T(),function(){const e=window.location.origin+window.location.pathname;window.history.replaceState({},document.title,e)}(),i)throw this.log.error("handleRedirectCallback:oauth-error",{error:i,errorDescription:r}),new n(r||i,i);if(!t){const e=new n("No authorization code was returned to the redirect URI","missing_authorization_code");throw this.log.error("handleRedirectCallback:missing-code",e),e}if(!a){const e=new n("No PKCE code verifier was found for the redirect callback","missing_code_verifier");throw this.log.error("handleRedirectCallback:missing-verifier",e),e}return this.log.info("handleRedirectCallback:success",{code:b(t),state:b(o)}),{code:t,state:o,codeVerifier:a}}async exchangeCode(e,t){if(!e||e.length>2048)throw new n("code is required and must be under 2048 characters","invalid_authorization_code");if(!t||t.length<43||t.length>128)throw new n("codeVerifier must be 43–128 characters (RFC 7636)","invalid_code_verifier");const o=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("exchangeCode:start",{endpoint:o,code:b(e),codeVerifier:b(t),clientId:this.config.clientId,redirectUri:this.config.redirectUri});const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:this.requireRedirectUri(),client_id:this.config.clientId,code_verifier:t})});if(!i.ok){const e=await R(i),t=new n(I(e,"Token exchange failed"),"token_exchange_failed");throw this.log.error("exchangeCode:error",{status:i.status,message:t.message}),t}const r=A(await i.json());return this.log.info("exchangeCode:success",{token_type:r.token_type,expires_in:r.expires_in,scope:r.scope,access_token:b(r.access_token),has_refresh_token:Boolean(r.refresh_token)}),r}async refreshToken(e){if(!e)throw new n("refreshToken is required","missing_refresh_token");const t=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("refreshToken:start",{endpoint:t,refreshToken:b(e),clientId:this.config.clientId});const o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId})});if(!o.ok){const e=await R(o),t=new n(I(e,"Token refresh failed"),"token_refresh_failed");throw this.log.error("refreshToken:error",{status:o.status,message:t.message}),t}const i=A(await o.json());return this.log.info("refreshToken:success",{token_type:i.token_type,expires_in:i.expires_in,access_token:b(i.access_token)}),i}async getUserInfo(e){var t,o;if(!e)throw new n("accessToken is required to fetch user info","missing_access_token");const i=`${this.config.baseUrl}/v1/oauth/userinfo`;this.log.info("getUserInfo:start",{endpoint:i,accessToken:b(e)});const r=await fetch(i,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){const e=await R(r),t=new n(I(e,"Failed to fetch user info"),"userinfo_failed");throw this.log.error("getUserInfo:error",{status:r.status,message:t.message}),t}const s=function(e){if(!e||"object"!=typeof e||"string"!=typeof e.sub||!e.sub)throw new n("Server returned an invalid userinfo response (missing sub)","invalid_userinfo_response");return e}(await r.json());return this.log.info("getUserInfo:success",{sub:s.sub,name:null!==(t=s.name)&&void 0!==t?t:"(not returned)",email:null!==(o=s.email)&&void 0!==o?o:"(not returned)"}),s}async revokeToken(e){if(!e)throw new n("token is required to revoke an OAuth token","missing_token");const t=`${this.config.baseUrl}/v1/oauth/revoke`;this.log.info("revokeToken:start",{endpoint:t,token:b(e),clientId:this.config.clientId});const o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,client_id:this.config.clientId})});if(!o.ok){const e=await R(o),t=new n(I(e,"Failed to revoke token"),"revoke_failed");throw this.log.error("revokeToken:error",{status:o.status,message:t.message}),t}this.log.info("revokeToken:success")}async handleLoginSuccess(e){this.log.info("handleLoginSuccess:start",{code:b(e.code)});const t=await this.exchangeCode(e.code,e.codeVerifier),n=await this.getUserInfo(t.access_token),o=Math.floor(Date.now()/1e3)+t.expires_in;return this.storage.set(x.ACCESS_TOKEN,t.access_token,o),this.storage.set(x.EXPIRES_AT,String(o),o),t.refresh_token&&this.storage.set(x.REFRESH_TOKEN,t.refresh_token),this.storage.set(x.USER,JSON.stringify(n)),this.log.info("handleLoginSuccess:session-saved",{sub:n.sub,expiresAt:o,hasRefreshToken:Boolean(t.refresh_token)}),{user:n,accessToken:t.access_token}}async getAccessToken(){var e;const t=this.storage.get(x.ACCESS_TOKEN),n=Number(null!==(e=this.storage.get(x.EXPIRES_AT))&&void 0!==e?e:"0");if(!t)return null;if(!(n>0&&Math.floor(Date.now()/1e3)>=n))return t;this.log.info("getAccessToken:expired, attempting refresh");const o=this.storage.get(x.REFRESH_TOKEN);if(!o)return this.log.info("getAccessToken:no-refresh-token, clearing session"),this.clearSession(),null;try{const e=await this.refreshToken(o),t=Math.floor(Date.now()/1e3)+e.expires_in;return this.storage.set(x.ACCESS_TOKEN,e.access_token,t),this.storage.set(x.EXPIRES_AT,String(t),t),e.refresh_token&&this.storage.set(x.REFRESH_TOKEN,e.refresh_token),this.log.info("getAccessToken:refreshed",{newExpiresAt:t}),e.access_token}catch(e){return this.log.error("getAccessToken:refresh-failed",e),this.clearSession(),null}}getUser(){const e=this.storage.get(x.USER);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}}isLoggedIn(){var e;if(!this.storage.get(x.ACCESS_TOKEN))return!1;const t=Number(null!==(e=this.storage.get(x.EXPIRES_AT))&&void 0!==e?e:"0");return 0===t||Math.floor(Date.now()/1e3)<t}async logout(){const e=this.storage.get(x.ACCESS_TOKEN);if(e)try{await this.revokeToken(e)}catch(e){this.log.error("logout:revoke-failed",e)}this.clearSession(),this.log.info("logout:done")}getBaseUrl(){return this.config.baseUrl}getClientId(){return this.config.clientId}clearSession(){this.storage.clear(Object.values(x))}requireRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if("undefined"!=typeof window)return window.location.origin;throw new n("redirectUri is required — pass it in the TenMSAuth constructor or call from a browser context","missing_redirect_uri")}buildAuthorizeUrl(e,t){const n=new URL(this.config.authorizeUrl);return n.searchParams.set("client_id",this.config.clientId),n.searchParams.set("redirect_uri",this.requireRedirectUri()),n.searchParams.set("response_type","code"),n.searchParams.set("scope",this.config.scopes.join(" ")),n.searchParams.set("state",e),n.searchParams.set("code_challenge",t),n.searchParams.set("code_challenge_method","S256"),n.toString()}}function C(e,t,o){const i=e.trim();if(!i)throw new n(`${t} must not be empty`,o);const r=i.replace(/\/+$/,"");try{new URL(r)}catch(e){throw new n(`${t} is not a valid URL: "${r}"`,o)}return r}function U(e){return`tenms_auth_${e}`}function T(){sessionStorage.removeItem(U("state")),sessionStorage.removeItem(U("code_verifier"))}async function R(e){try{const t=await e.text();return t?JSON.parse(t):{}}catch(e){return{}}}function I(e,t){var n,o,i;return null!==(i=null!==(o=null!==(n=e.error_description)&&void 0!==n?n:e.message)&&void 0!==o?o:e.error)&&void 0!==i?i:t}function A(e){if(!e||"object"!=typeof e||"string"!=typeof e.access_token||!e.access_token)throw new n("Server returned an invalid token response (missing access_token)","invalid_token_response");return e}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}(".tenms-login-btn{-webkit-font-smoothing:antialiased;align-items:center;border:1px solid transparent;border-radius:6px;cursor:pointer;display:inline-flex;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif;font-size:14px;font-weight:500;gap:6px;height:36px;justify-content:center;line-height:1;padding:0 12px;text-decoration:none;transition:background .15s ease,border-color .15s ease,color .15s ease,opacity .15s ease;user-select:none;-webkit-user-select:none;white-space:nowrap;width:fit-content}.tenms-login-btn:focus-visible{outline:2px solid #0070f3;outline-offset:2px}.tenms-login-btn:disabled{cursor:not-allowed}.tenms-login-btn--dark.tenms-login-btn--fill{background:#000;border-color:#000;color:#fff}.tenms-login-btn--dark.tenms-login-btn--fill:hover:not(:disabled){background:#333;border-color:#333}.tenms-login-btn--dark.tenms-login-btn--outline{background:transparent;border-color:#000;color:#000}.tenms-login-btn--dark.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--fill{background:#fff;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--fill:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--outline{background:transparent;border-color:hsla(0,0%,100%,.4);color:#fff}.tenms-login-btn--light.tenms-login-btn--outline:hover:not(:disabled){background:hsla(0,0%,100%,.12);border-color:hsla(0,0%,100%,.6)}.tenms-login-btn--small{font-size:13px;gap:5px;height:32px;padding:0 10px}.tenms-login-btn--medium{font-size:14px;height:36px;padding:0 12px}.tenms-login-btn--large{font-size:14px;height:40px;padding:0 14px}.tenms-login-btn__logo{align-items:center;display:inline-flex;flex-shrink:0}.tenms-login-btn__logo svg{display:block;height:18px;width:18px}.tenms-login-btn--loading{opacity:.6;pointer-events:none}.tenms-login-btn__spinner{animation:tenms-spin .6s linear infinite;border:1.5px solid;border-radius:50%;border-top:1.5px solid transparent;height:14px;width:14px}@keyframes tenms-spin{to{transform:rotate(1turn)}}");function L(e,t){return"dark"===e&&"fill"===t||"light"===e&&"outline"===t?'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#F9FAFB"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#F9FAFB"/>\n</svg>':'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#111827"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#111827"/>\n</svg>'}function $(e="dark",t="fill"){return`<span class="tenms-login-btn__logo">${L(e,t)}</span>`}var P;const z="Login with 10MinuteSchool",N=null!==(P=globalThis.HTMLElement)&&void 0!==P?P:class{};class O extends N{constructor(){super(...arguments),this.auth=null,this.loading=!1}static get observedAttributes(){return["client-id","redirect-uri","scope","theme","variant","size","text"]}connectedCallback(){this.render()}attributeChangedCallback(){this.loading||this.render()}render(){var e;const t=j(this.getAttribute("theme")),n=q(this.getAttribute("variant")),o=F(this.getAttribute("size")),i=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||z;var r;this.innerHTML=`\n <button class="${B((r={loading:this.loading,text:i,theme:t,variant:n,size:o}).theme,r.variant,r.size,r.loading)}" type="button" ${r.loading?'disabled aria-busy="true"':""}>\n ${r.loading?'<span class="tenms-login-btn__spinner" aria-hidden="true"></span>':$(r.theme)}\n <span class="tenms-login-btn__label">${W(r.text)}</span>\n </button>\n `;const s=this.querySelector("button");s&&s.addEventListener("click",()=>{this.handleClick()})}async handleClick(){if(this.loading)return;const e=this.getConfig();if(e.clientId&&e.redirectUri){this.auth||(this.auth=new E(e)),this.loading=!0,this.render();try{const e=await this.auth.loginWithPopup();this.dispatchEvent(new CustomEvent("tenms-success",{detail:e,bubbles:!0,composed:!0}))}catch(e){this.dispatchError(H(e))}finally{this.loading=!1,this.render()}}else this.dispatchError(new n("client-id and redirect-uri attributes are required","invalid_login_button_config"))}getConfig(){const e=this.getAttribute("scope")||"profile";return{clientId:this.getAttribute("client-id")||"",redirectUri:this.getAttribute("redirect-uri")||"",scopes:e.split(" ").map(e=>e.trim()).filter(Boolean)}}dispatchError(e){this.dispatchEvent(new CustomEvent("tenms-error",{detail:e,bubbles:!0,composed:!0}))}}function M(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",O)}function V(e,t){e.className=B(t.theme,t.variant,t.size,t.loading),e.type="button",e.disabled=t.loading,e.setAttribute("aria-busy",String(t.loading)),e.innerHTML=t.loading?`<span class="tenms-login-btn__spinner" aria-hidden="true"></span><span class="tenms-login-btn__label">${W(t.text)}</span>`:`${$(t.theme)}<span class="tenms-login-btn__label">${W(t.text)}</span>`}function B(e,t,n,o){return["tenms-login-btn",`tenms-login-btn--${e}`,`tenms-login-btn--${t}`,`tenms-login-btn--${n}`,o?"tenms-login-btn--loading":""].filter(Boolean).join(" ")}function j(e){return"light"===e?e:"dark"}function q(e){return"outline"===e?e:"fill"}function F(e){return"small"===e||"medium"===e?e:"large"}function W(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function H(e){return e instanceof Error?e:new Error(String(e))}const D="Login with 10MinuteSchool",K="dark",J="fill",X="large";function Z(e){return"light"===e?e:K}function Y(e){return"outline"===e?e:J}M(),exports.LoginButton=function(e){const{clientId:n,redirectUri:o,scopes:i,theme:r=K,variant:s=J,size:a=X,text:c=D,onSuccess:l,onError:d,className:h=""}=e,[u,g]=t.useState(!1),f=t.useRef(l),p=t.useRef(d);t.useEffect(()=>{f.current=l},[l]),t.useEffect(()=>{p.current=d},[d]);const m=Array.isArray(i)?i.join("\0"):"",w=t.useMemo(()=>new E({clientId:n,redirectUri:o,scopes:i}),[n,o,m]),b=t.useCallback(async()=>{var e,t;g(!0);try{const t=await w.loginWithPopup();null===(e=f.current)||void 0===e||e.call(f,t)}catch(e){null===(t=p.current)||void 0===t||t.call(p,function(e){return e instanceof Error?e:new Error(String(e))}(e))}finally{g(!1)}},[w]),_=["tenms-login-btn",`tenms-login-btn--${Z(r)}`,`tenms-login-btn--${Y(s)}`,`tenms-login-btn--${v=a,"small"===v||"medium"===v?v:X}`,u?"tenms-login-btn--loading":"",h].filter(Boolean).join(" ");var v;return t.createElement("button",{className:_,type:"button",onClick:()=>{b()},disabled:u,"aria-busy":u},u?t.createElement("span",{className:"tenms-login-btn__spinner","aria-hidden":"true"}):t.createElement("span",{className:"tenms-login-btn__logo",dangerouslySetInnerHTML:{__html:L(Z(r),Y(s))}}),t.createElement("span",{className:"tenms-login-btn__label"},c))},exports.TenMSAuth=E,exports.TenMSAuthError=n,exports.TenMSLoginButtonElement=O,exports.VERSION="1.0.0",exports.createLogger=p,exports.generateCodeChallenge=r,exports.generateCodeVerifier=i,exports.generateState=s,exports.openPopup=l,exports.registerLoginButton=M,exports.renderLoginButton=function(e,t){var o;const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new n(`Container element not found: ${e}`,"container_not_found");const r=new E({clientId:t.clientId,redirectUri:t.redirectUri,scopes:t.scopes}),s=j(t.theme),a=q(t.variant),c=F(t.size),l=(null===(o=t.text)||void 0===o?void 0:o.trim())||z,d=document.createElement("button");V(d,{loading:!1,size:c,text:l,theme:s,variant:a}),d.addEventListener("click",async()=>{var e,n;if(!d.classList.contains("tenms-login-btn--loading")){V(d,{loading:!0,size:c,text:l,theme:s,variant:a});try{const n=await r.loginWithPopup();null===(e=t.onSuccess)||void 0===e||e.call(t,n)}catch(e){null===(n=t.onError)||void 0===n||n.call(t,H(e))}finally{V(d,{loading:!1,size:c,text:l,theme:s,variant:a})}}}),i.replaceChildren(d)},exports.truncate=b,exports.waitForPopupRedirect=d;
1
+ "use strict";function e(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var t=e(require("react"));class n extends Error{constructor(e,t){super(e),this.name="TenMSAuthError",this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}const o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function r(e=64){a(e,43,128,"code_verifier length");const t=[];for(;t.length<e;){const n=new Uint8Array(e+16);crypto.getRandomValues(n);for(const r of n){if(t.length>=e)break;r<198&&t.push(o[r%66])}}return t.join("")}async function i(e){if(!e)throw new Error("codeVerifier is required to generate a code challenge");const t=(new TextEncoder).encode(e);return function(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await crypto.subtle.digest("SHA-256",t))}function s(e=32){a(e,1,1024,"state byte length");const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function a(e,t,n,o){if(!Number.isInteger(e)||e<t||e>n)throw new RangeError(`${o} must be an integer between ${t} and ${n}`)}const l="tenms_auth_popup_callback";function c(e){d(e.width,"popup width"),d(e.height,"popup height");const t="number"==typeof window.screenX?window.screenX:window.screenLeft,n="number"==typeof window.screenY?window.screenY:window.screenTop,o=Math.round(t+Math.max(0,(window.innerWidth-e.width)/2)),r=Math.round(n+Math.max(0,(window.innerHeight-e.height)/2)),i=[`width=${e.width}`,`height=${e.height}`,`left=${o}`,`top=${r}`,"toolbar=no","menubar=no","scrollbars=yes","resizable=yes","status=no"].join(",");return window.open(e.url,"tenms_auth_popup",i)}function h(e,t,o,r=3e5){if(!t)throw new Error("redirectUri is required to monitor popup redirects");if(!o)throw new Error("expectedState is required to validate the popup callback");let i;d(r,"popup timeout");try{i=new URL(t)}catch(e){throw new n(`redirectUri is not a valid URL: "${t}"`,"invalid_redirect_uri")}return new Promise((t,s)=>{const a=Date.now();let c,h=!1,d=null;const u=t=>{h||(h=!0,window.clearInterval(c),null==d||d.close(),e.closed||e.close(),t())},g=(e,r,i,a)=>{u(i?()=>s(new n(a||i,"oauth_error")):e?r===o?()=>t({code:e,state:r}):()=>s(new n("State mismatch — possible CSRF attack","state_mismatch")):()=>s(new n("No authorization code was returned to the redirect URI","missing_authorization_code")))};try{d=new BroadcastChannel(l),d.onmessage=e=>{var t,n,o,r;g(null!==(t=e.data.code)&&void 0!==t?t:null,null!==(n=e.data.state)&&void 0!==n?n:null,null!==(o=e.data.error)&&void 0!==o?o:null,null!==(r=e.data.errorDescription)&&void 0!==r?r:null)}}catch(e){d=null}c=window.setInterval(()=>{try{if(!e||e.closed)return void u(()=>s(new n("Login popup was closed","popup_closed")));if(Date.now()-a>r)return void u(()=>s(new n("Login timed out while waiting for the redirect URI","popup_timeout")));const t=e.location.href;if(!t)return;let o;try{o=new URL(t)}catch(e){return}if(o.origin!==i.origin||o.pathname!==i.pathname)return;g(o.searchParams.get("code"),o.searchParams.get("state"),o.searchParams.get("error"),o.searchParams.get("error_description"))}catch(e){e instanceof DOMException||u(()=>s(e instanceof Error?e:new Error(String(e))))}},500)})}function d(e,t){if(!Number.isInteger(e)||e<=0)throw new RangeError(`${t} must be a positive integer`)}const u="[TenMSAuth]",g="color:#22c55e;font-weight:700",f="color:inherit;font-weight:normal";function p(e){return e?w:m}const m={info:()=>{},warn:()=>{},error:()=>{}},w={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${u}%c ${e}`,g,f),console.table(t),console.groupEnd()):console.log(`%c${u}%c ${e}`,g,f)},warn(e,t){console.warn(`%c${u}%c ⚠ ${e}`,g,f,null!=t?t:"")},error(e,t){console.error(`%c${u}%c ✕ ${e}`,g,f,null!=t?t:"")}};function b(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}class _{get(e){const t=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return t?decodeURIComponent(t[1]):null}set(e,t,n){let o=`${e}=${encodeURIComponent(t)}; path=/; SameSite=Lax`;n&&(o+=`; expires=${new Date(1e3*n).toUTCString()}`),document.cookie=o}remove(e){document.cookie=`${e}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`}clear(e){e.forEach(e=>this.remove(e))}}class v{get(e){return localStorage.getItem(e)}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}clear(e){e.forEach(e=>this.remove(e))}}const k="https://api.10minuteschool.com/auth",S="https://10minuteschool.com/auth/login",y=["profile","email","phone"],E=["tenms_token","token"],x={ACCESS_TOKEN:"_tenms_access_token",REFRESH_TOKEN:"_tenms_refresh_token",EXPIRES_AT:"_tenms_expires_at",USER:"_tenms_user",SOURCE:"_tenms_session_source"};class C{constructor(e){var t,o;if(this.refreshInFlight=null,this.config=function(e){var t,o,r,i;const s=null===(t=e.clientId)||void 0===t?void 0:t.trim();if(!s)throw new n("clientId is required","missing_client_id");const a=(null===(o=e.redirectUri)||void 0===o?void 0:o.trim())||void 0,l=U(null!==(r=e.baseUrl)&&void 0!==r?r:k,"baseUrl","invalid_base_url"),c=U(null!==(i=e.authorizeUrl)&&void 0!==i?i:S,"authorizeUrl","invalid_authorize_url"),h=function(e){if(!Array.isArray(e)||0===e.length)return y;const t=e.map(e=>e.trim()).filter(Boolean);return t.length>0?t:y}(e.scopes),d=function(e){if(!Array.isArray(e))return E;const t=[...new Set(e.map(e=>e.trim()).filter(Boolean))];return t.length>0?t:E}(e.handoffParams);return{clientId:s,redirectUri:a,scopes:h,baseUrl:l,authorizeUrl:c,handoffParams:d}}(e),this.log=p(!0===e.debug),this.storage="localStorage"===(null!==(t=e.storage)&&void 0!==t?t:"cookie")?new v:new _,this.log.info("init",{clientId:this.config.clientId,redirectUri:this.config.redirectUri,baseUrl:this.config.baseUrl,authorizeUrl:this.config.authorizeUrl,scopes:this.config.scopes.join(" "),handoffParams:this.config.handoffParams.join(", "),storage:null!==(o=e.storage)&&void 0!==o?o:"cookie",debug:!0===e.debug}),"undefined"!=typeof window&&window.opener){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),o=e.get("error");if(t||o)try{const r=new BroadcastChannel(l);r.postMessage({code:t,state:n,error:o,errorDescription:e.get("error_description")}),r.close()}catch(e){}}}async loginWithPopup(e={}){var t,o;const a=null!==(t=e.width)&&void 0!==t?t:500,l=null!==(o=e.height)&&void 0!==o?o:600;this.log.info("loginWithPopup:start",{width:a,height:l});const d=s(),u=r();this.log.info("loginWithPopup:pkce-generated",{state:b(d),codeVerifier:b(u)});const g=c({url:"about:blank",width:a,height:l});if(!g){const e=new n("Failed to open login popup. Please allow popups for this site.","popup_blocked");throw this.log.error("loginWithPopup:popup-blocked",e),e}if(g===window){const e=new n("The browser reused the current tab instead of opening a popup window.","popup_reused_opener");throw this.log.error("loginWithPopup:popup-reused-opener",e),e}this.log.info("loginWithPopup:popup-opened"),function(e){try{e.document.title="Signing in…",e.document.body.style.cssText="font-family:system-ui,sans-serif;padding:2rem;text-align:center",e.document.body.textContent="Signing in…"}catch(e){}}(g);try{const e=await i(u),t=this.buildAuthorizeUrl(d,e);this.log.info("loginWithPopup:navigating",{authorizeUrl:t,codeChallenge:b(e)}),g.location.href=t;const n=await h(g,this.requireRedirectUri(),d);return this.log.info("loginWithPopup:success",{code:b(n.code),state:b(n.state)}),{code:n.code,state:n.state,codeVerifier:u}}catch(e){throw g.closed||g.close(),this.log.error("loginWithPopup:error",e),e}}async loginWithRedirect(){this.log.info("loginWithRedirect:start");const e=s(),t=r(),n=await i(t);this.log.info("loginWithRedirect:pkce-generated",{state:b(e),codeVerifier:b(t),codeChallenge:b(n)}),function(e,t){sessionStorage.setItem(T("state"),e),sessionStorage.setItem(T("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[T("state"),T("code_verifier")]});const o=this.buildAuthorizeUrl(e,n);this.log.info("loginWithRedirect:navigating",{authorizeUrl:o}),window.location.href=o}handleRedirectCallback(){const e=new URLSearchParams(window.location.search),t=e.get("code"),o=e.get("state"),r=e.get("error"),i=e.get("error_description");if(!t&&!o&&!r)return this.log.info("handleRedirectCallback:not-a-callback"),null;this.log.info("handleRedirectCallback:callback-detected",{hasCode:Boolean(t),hasState:Boolean(o),error:null!=r?r:"(none)",errorDescription:null!=i?i:"(none)"});const s=sessionStorage.getItem(T("state")),a=sessionStorage.getItem(T("code_verifier"));if(!o||!s||o!==s){R();const e=new n("State mismatch — possible CSRF attack","state_mismatch");throw this.log.warn("handleRedirectCallback:state-mismatch",{receivedState:o?b(o):"(missing)",storedStatePresent:Boolean(s)}),e}if(R(),function(){const e=window.location.origin+window.location.pathname;window.history.replaceState({},document.title,e)}(),r)throw this.log.error("handleRedirectCallback:oauth-error",{error:r,errorDescription:i}),new n(i||r,r);if(!t){const e=new n("No authorization code was returned to the redirect URI","missing_authorization_code");throw this.log.error("handleRedirectCallback:missing-code",e),e}if(!a){const e=new n("No PKCE code verifier was found for the redirect callback","missing_code_verifier");throw this.log.error("handleRedirectCallback:missing-verifier",e),e}return this.log.info("handleRedirectCallback:success",{code:b(t),state:b(o)}),{code:t,state:o,codeVerifier:a}}async exchangeCode(e,t){if(!e||e.length>2048)throw new n("code is required and must be under 2048 characters","invalid_authorization_code");if(!t||t.length<43||t.length>128)throw new n("codeVerifier must be 43–128 characters (RFC 7636)","invalid_code_verifier");const o=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("exchangeCode:start",{endpoint:o,code:b(e),codeVerifier:b(t),clientId:this.config.clientId,redirectUri:this.config.redirectUri});const r=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:this.requireRedirectUri(),client_id:this.config.clientId,code_verifier:t})});if(!r.ok){const e=await A(r),t=new n(I(e,"Token exchange failed"),"token_exchange_failed");throw this.log.error("exchangeCode:error",{status:r.status,message:t.message}),t}const i=$(await r.json());return this.log.info("exchangeCode:success",{token_type:i.token_type,expires_in:i.expires_in,scope:i.scope,access_token:b(i.access_token),has_refresh_token:Boolean(i.refresh_token)}),i}async refreshToken(e){if(!e)throw new n("refreshToken is required","missing_refresh_token");const t=`${this.config.baseUrl}/v1/oauth/token`;this.log.info("refreshToken:start",{endpoint:t,refreshToken:b(e),clientId:this.config.clientId});const o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId})});if(!o.ok){const e=await A(o),t=new n(I(e,"Token refresh failed"),"token_refresh_failed");throw this.log.error("refreshToken:error",{status:o.status,message:t.message}),t}const r=$(await o.json());return this.log.info("refreshToken:success",{token_type:r.token_type,expires_in:r.expires_in,access_token:b(r.access_token)}),r}async getUserInfo(e){var t,o;if(!e)throw new n("accessToken is required to fetch user info","missing_access_token");const r=`${this.config.baseUrl}/v1/oauth/userinfo`;this.log.info("getUserInfo:start",{endpoint:r,accessToken:b(e)});const i=await fetch(r,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){const e=await A(i),t=new n(I(e,"Failed to fetch user info"),"userinfo_failed");throw this.log.error("getUserInfo:error",{status:i.status,message:t.message}),t}const s=function(e){if(!e||"object"!=typeof e||"string"!=typeof e.sub||!e.sub)throw new n("Server returned an invalid userinfo response (missing sub)","invalid_userinfo_response");return e}(await i.json());return this.log.info("getUserInfo:success",{sub:s.sub,name:null!==(t=s.name)&&void 0!==t?t:"(not returned)",email:null!==(o=s.email)&&void 0!==o?o:"(not returned)"}),s}async getHandoffUser(e){var t,o;const r=`${this.config.baseUrl}/v1/user/me`;this.log.info("getHandoffUser:start",{endpoint:r,accessToken:b(e)});const i=await fetch(r,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){const e=await A(i);throw new n(I(e,"Failed to validate the handoff token"),"token_handoff_failed")}const s=null===(o=null===(t=await i.json())||void 0===t?void 0:t.data)||void 0===o?void 0:o.user_info;if(!(null==s?void 0:s.id))throw new n("Handoff profile response is missing user id","token_handoff_failed");return{sub:s.id,name:s.name||void 0,email:s.email||void 0,phone:s.contact||void 0,picture:s.profile_img_url||void 0}}async revokeToken(e){if(!e)throw new n("token is required to revoke an OAuth token","missing_token");const t=`${this.config.baseUrl}/v1/oauth/revoke`;this.log.info("revokeToken:start",{endpoint:t,token:b(e),clientId:this.config.clientId});const o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,client_id:this.config.clientId})});if(!o.ok){const e=await A(o),t=new n(I(e,"Failed to revoke token"),"revoke_failed");throw this.log.error("revokeToken:error",{status:o.status,message:t.message}),t}this.log.info("revokeToken:success")}async handleLoginSuccess(e){this.log.info("handleLoginSuccess:start",{code:b(e.code)});const t=await this.exchangeCode(e.code,e.codeVerifier),n=await this.getUserInfo(t.access_token);return this.clearSession(),this.saveOAuthSession(t,JSON.stringify(n)),this.log.info("handleLoginSuccess:session-saved",{sub:n.sub,hasRefreshToken:Boolean(t.refresh_token)}),{user:n,accessToken:t.access_token,source:"oauth"}}async handleTokenHandoff(){const e=new URLSearchParams(window.location.search),t=this.config.handoffParams.filter(t=>e.has(t));if(0===t.length)return null;const o=t[0],r=function(e){let t=e.trim();t.length>=2&&t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1).trim());return t.replace(/^Bearer\s+/i,"")}(e.get(o));t.forEach(t=>e.delete(t));const i=e.toString();if(window.history.replaceState(window.history.state,document.title,window.location.pathname+(i?`?${i}`:"")+window.location.hash),this.log.info("handleTokenHandoff:detected",{param:o,token:b(r)}),!r)throw new n(`The "${o}" handoff param is empty`,"token_handoff_failed");const s=await this.getHandoffUser(r),a=function(e){try{const t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t)).exp;return"number"==typeof n?n:void 0}catch(e){return}}(r);return this.clearSession(),this.storage.set(x.ACCESS_TOKEN,r,a),a&&this.storage.set(x.EXPIRES_AT,String(a),a),this.storage.set(x.USER,JSON.stringify(s),a),this.storage.set(x.SOURCE,"handoff",a),this.log.info("handleTokenHandoff:success",{sub:s.sub,exp:a}),{user:s,accessToken:r,source:"handoff"}}async getAccessToken(){var e,t;const n=this.storage.get(x.ACCESS_TOKEN),o=this.storage.get(x.REFRESH_TOKEN),r=Number(null!==(e=this.storage.get(x.EXPIRES_AT))&&void 0!==e?e:"0"),i=Math.floor(Date.now()/1e3);return o?n&&r>0&&i<r-30?n:(null!==(t=this.refreshInFlight)&&void 0!==t||(this.refreshInFlight=this.refreshSession(o).finally(()=>{this.refreshInFlight=null})),this.refreshInFlight):n?0===r||i<r?n:(this.log.info("getAccessToken:expired-without-refresh-token"),this.clearSession(),null):null}async refreshSession(e){this.log.info("getAccessToken:refreshing");try{const t=await this.refreshToken(e);return this.storage.get(x.REFRESH_TOKEN)!==e?(this.log.info("getAccessToken:session-changed-during-refresh"),this.storage.get(x.ACCESS_TOKEN)):(this.saveOAuthSession(t,this.storage.get(x.USER),e),this.log.info("getAccessToken:refreshed"),t.access_token)}catch(t){return this.log.error("getAccessToken:refresh-failed",t),this.storage.get(x.REFRESH_TOKEN)===e&&this.clearSession(),null}}saveOAuthSession(e,t,n){const o=Math.floor(Date.now()/1e3),r=o+e.expires_in,i=e.refresh_token||n,s=i?o+2592e3:r;this.storage.set(x.ACCESS_TOKEN,e.access_token,s),this.storage.set(x.EXPIRES_AT,String(r),s),this.storage.set(x.SOURCE,"oauth",s),i&&this.storage.set(x.REFRESH_TOKEN,i,s),t&&this.storage.set(x.USER,t,s)}getUser(){const e=this.storage.get(x.USER);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}}isLoggedIn(){var e;if(this.storage.get(x.REFRESH_TOKEN))return!0;if(!this.storage.get(x.ACCESS_TOKEN))return!1;const t=Number(null!==(e=this.storage.get(x.EXPIRES_AT))&&void 0!==e?e:"0");return 0===t||Math.floor(Date.now()/1e3)<t}async logout(){const e=this.storage.get(x.ACCESS_TOKEN),t=this.storage.get(x.SOURCE);if(this.clearSession(),e&&"oauth"===t)try{await this.revokeToken(e)}catch(e){this.log.error("logout:revoke-failed",e)}this.log.info("logout:done",{revoked:Boolean(e&&"oauth"===t)})}getBaseUrl(){return this.config.baseUrl}getClientId(){return this.config.clientId}clearSession(){this.storage.clear(Object.values(x))}requireRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if("undefined"!=typeof window)return window.location.origin;throw new n("redirectUri is required — pass it in the TenMSAuth constructor or call from a browser context","missing_redirect_uri")}buildAuthorizeUrl(e,t){const n=new URL(this.config.authorizeUrl);return n.searchParams.set("client_id",this.config.clientId),n.searchParams.set("redirect_uri",this.requireRedirectUri()),n.searchParams.set("response_type","code"),n.searchParams.set("scope",this.config.scopes.join(" ")),n.searchParams.set("state",e),n.searchParams.set("code_challenge",t),n.searchParams.set("code_challenge_method","S256"),n.toString()}}function U(e,t,o){const r=e.trim();if(!r)throw new n(`${t} must not be empty`,o);const i=r.replace(/\/+$/,"");try{new URL(i)}catch(e){throw new n(`${t} is not a valid URL: "${i}"`,o)}return i}function T(e){return`tenms_auth_${e}`}function R(){sessionStorage.removeItem(T("state")),sessionStorage.removeItem(T("code_verifier"))}async function A(e){try{const t=await e.text();return t?JSON.parse(t):{}}catch(e){return{}}}function I(e,t){var n,o,r;return null!==(r=null!==(o=null!==(n=e.error_description)&&void 0!==n?n:e.message)&&void 0!==o?o:e.error)&&void 0!==r?r:t}function $(e){if(!e||"object"!=typeof e||"string"!=typeof e.access_token||!e.access_token)throw new n("Server returned an invalid token response (missing access_token)","invalid_token_response");return e}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===n&&o.firstChild?o.insertBefore(r,o.firstChild):o.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".tenms-login-btn{-webkit-font-smoothing:antialiased;align-items:center;border:1px solid transparent;border-radius:6px;cursor:pointer;display:inline-flex;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif;font-size:14px;font-weight:500;gap:6px;height:36px;justify-content:center;line-height:1;padding:0 12px;text-decoration:none;transition:background .15s ease,border-color .15s ease,color .15s ease,opacity .15s ease;user-select:none;-webkit-user-select:none;white-space:nowrap;width:fit-content}.tenms-login-btn:focus-visible{outline:2px solid #0070f3;outline-offset:2px}.tenms-login-btn:disabled{cursor:not-allowed}.tenms-login-btn--dark.tenms-login-btn--fill{background:#000;border-color:#000;color:#fff}.tenms-login-btn--dark.tenms-login-btn--fill:hover:not(:disabled){background:#333;border-color:#333}.tenms-login-btn--dark.tenms-login-btn--outline{background:transparent;border-color:#000;color:#000}.tenms-login-btn--dark.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--fill{background:#fff;border-color:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--fill:hover:not(:disabled){background:#f5f5f5}.tenms-login-btn--light.tenms-login-btn--outline{background:transparent;border-color:hsla(0,0%,100%,.4);color:#fff}.tenms-login-btn--light.tenms-login-btn--outline:hover:not(:disabled){background:hsla(0,0%,100%,.12);border-color:hsla(0,0%,100%,.6)}.tenms-login-btn--small{font-size:13px;gap:5px;height:32px;padding:0 10px}.tenms-login-btn--medium{font-size:14px;height:36px;padding:0 12px}.tenms-login-btn--large{font-size:14px;height:40px;padding:0 14px}.tenms-login-btn__logo{align-items:center;display:inline-flex;flex-shrink:0}.tenms-login-btn__logo svg{display:block;height:18px;width:18px}.tenms-login-btn--loading{opacity:.6;pointer-events:none}.tenms-login-btn__spinner{animation:tenms-spin .6s linear infinite;border:1.5px solid;border-radius:50%;border-top:1.5px solid transparent;height:14px;width:14px}@keyframes tenms-spin{to{transform:rotate(1turn)}}");function P(e,t){return"dark"===e&&"fill"===t||"light"===e&&"outline"===t?'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#F9FAFB"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#F9FAFB"/>\n</svg>':'<svg width="20" height="20" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <path d="M21.9012 17.9947L28.8098 11.085C28.0544 7.39598 25.1207 4.50016 21.4039 4.03514C21.3338 4.02624 21.2626 4.01845 21.1925 4.01178V7.43714C22.8023 7.7097 24.1373 8.751 24.916 10.1839L19.5049 15.5939L21.9012 17.9947Z" fill="#EB2026"/>\n <path d="M9.47025 27.9927H6.0727V7.40489H3V4.00734H9.47025V27.9927Z" fill="#111827"/>\n <path d="M25.5835 16.7187L25.569 18.9771V18.9882C25.569 22.0776 23.2172 24.5907 20.3269 24.5907C17.4367 24.5907 15.0871 22.0798 15.0849 18.9938L15.126 12.9807V12.9696C15.126 10.224 16.9906 7.88999 19.4992 7.44388V4.01518L19.2767 4.04076C14.9703 4.60591 11.7263 8.44178 11.7229 12.9641L11.684 18.9771V18.9882C11.684 23.951 15.5599 27.9883 20.3236 27.9883C25.0873 27.9883 28.9599 23.9544 28.9621 18.9938L28.9999 13.2989L25.5835 16.7187Z" fill="#111827"/>\n</svg>'}function L(e="dark",t="fill"){return`<span class="tenms-login-btn__logo">${P(e,t)}</span>`}var O;const z="Login with 10MinuteSchool",N=null!==(O=globalThis.HTMLElement)&&void 0!==O?O:class{};class M extends N{constructor(){super(...arguments),this.auth=null,this.loading=!1}static get observedAttributes(){return["client-id","redirect-uri","scope","authorize-url","theme","variant","size","text"]}connectedCallback(){this.render()}attributeChangedCallback(){this.loading||this.render()}render(){var e;const t=j(this.getAttribute("theme")),n=F(this.getAttribute("variant")),o=W(this.getAttribute("size")),r=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||z;var i;this.innerHTML=`\n <button class="${V((i={loading:this.loading,text:r,theme:t,variant:n,size:o}).theme,i.variant,i.size,i.loading)}" type="button" ${i.loading?'disabled aria-busy="true"':""}>\n ${i.loading?'<span class="tenms-login-btn__spinner" aria-hidden="true"></span>':L(i.theme)}\n <span class="tenms-login-btn__label">${q(i.text)}</span>\n </button>\n `;const s=this.querySelector("button");s&&s.addEventListener("click",()=>{this.handleClick()})}async handleClick(){if(this.loading)return;const e=this.getConfig();if(e.clientId&&e.redirectUri){this.auth||(this.auth=new C(e)),this.loading=!0,this.render();try{const e=await this.auth.loginWithPopup();this.dispatchEvent(new CustomEvent("tenms-success",{detail:e,bubbles:!0,composed:!0}))}catch(e){this.dispatchError(K(e))}finally{this.loading=!1,this.render()}}else this.dispatchError(new n("client-id and redirect-uri attributes are required","invalid_login_button_config"))}getConfig(){const e=this.getAttribute("scope")||"profile";return{clientId:this.getAttribute("client-id")||"",redirectUri:this.getAttribute("redirect-uri")||"",authorizeUrl:this.getAttribute("authorize-url")||void 0,scopes:e.split(" ").map(e=>e.trim()).filter(Boolean)}}dispatchError(e){this.dispatchEvent(new CustomEvent("tenms-error",{detail:e,bubbles:!0,composed:!0}))}}function B(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",M)}function H(e,t){e.className=V(t.theme,t.variant,t.size,t.loading),e.type="button",e.disabled=t.loading,e.setAttribute("aria-busy",String(t.loading)),e.innerHTML=t.loading?`<span class="tenms-login-btn__spinner" aria-hidden="true"></span><span class="tenms-login-btn__label">${q(t.text)}</span>`:`${L(t.theme)}<span class="tenms-login-btn__label">${q(t.text)}</span>`}function V(e,t,n,o){return["tenms-login-btn",`tenms-login-btn--${e}`,`tenms-login-btn--${t}`,`tenms-login-btn--${n}`,o?"tenms-login-btn--loading":""].filter(Boolean).join(" ")}function j(e){return"light"===e?e:"dark"}function F(e){return"outline"===e?e:"fill"}function W(e){return"small"===e||"medium"===e?e:"large"}function q(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function K(e){return e instanceof Error?e:new Error(String(e))}const D="Login with 10MinuteSchool",J="dark",X="fill",Z="large";function Y(e){return"light"===e?e:J}function G(e){return"outline"===e?e:X}const Q=t.createContext(null);B(),exports.LoginButton=function(e){const{clientId:n,redirectUri:o,scopes:r,baseUrl:i,authorizeUrl:s,theme:a=J,variant:l=X,size:c=Z,text:h=D,onSuccess:d,onError:u,className:g=""}=e,[f,p]=t.useState(!1),m=t.useRef(d),w=t.useRef(u);t.useEffect(()=>{m.current=d},[d]),t.useEffect(()=>{w.current=u},[u]);const b=Array.isArray(r)?r.join("\0"):"",_=t.useMemo(()=>new C({clientId:n,redirectUri:o,scopes:r,baseUrl:i,authorizeUrl:s}),[n,o,b,i,s]),v=t.useCallback(async()=>{var e,t;p(!0);try{const t=await _.loginWithPopup();null===(e=m.current)||void 0===e||e.call(m,t)}catch(e){null===(t=w.current)||void 0===t||t.call(w,function(e){return e instanceof Error?e:new Error(String(e))}(e))}finally{p(!1)}},[_]),k=["tenms-login-btn",`tenms-login-btn--${Y(a)}`,`tenms-login-btn--${G(l)}`,`tenms-login-btn--${S=c,"small"===S||"medium"===S?S:Z}`,f?"tenms-login-btn--loading":"",g].filter(Boolean).join(" ");var S;return t.createElement("button",{className:k,type:"button",onClick:()=>{v()},disabled:f,"aria-busy":f},f?t.createElement("span",{className:"tenms-login-btn__spinner","aria-hidden":"true"}):t.createElement("span",{className:"tenms-login-btn__logo",dangerouslySetInnerHTML:{__html:P(Y(a),G(l))}}),t.createElement("span",{className:"tenms-login-btn__label"},h))},exports.TenMSAuth=C,exports.TenMSAuthError=n,exports.TenMSAuthProvider=function({auth:e,children:n,onTokenHandoff:o}){const[r,i]=t.useState(null),[s,a]=t.useState(!0),[l,c]=t.useState(null),h=t.useRef(null),d=t.useRef(o);d.current=o;const u=t.useCallback(()=>{i(e.getUser()),c(null)},[e]);t.useEffect(()=>{h.current!==e&&(h.current=e,(async()=>{var t,n;let o=null,r=null;const s=async()=>await e.getAccessToken()?e.getUser():null;try{const o=await e.handleTokenHandoff();o&&await(null===(t=d.current)||void 0===t?void 0:t.call(d,o)),r=null!==(n=null==o?void 0:o.user)&&void 0!==n?n:await s()}catch(e){o=e instanceof Error?e:new Error(String(e)),r=await s()}i(r),c(o),a(!1)})())},[e]);const g=t.useMemo(()=>({auth:e,user:r,loading:s,error:l,refresh:u}),[e,r,s,l,u]);return t.createElement(Q.Provider,{value:g},n)},exports.TenMSLoginButtonElement=M,exports.VERSION="1.2.0",exports.createLogger=p,exports.generateCodeChallenge=i,exports.generateCodeVerifier=r,exports.generateState=s,exports.openPopup=c,exports.registerLoginButton=B,exports.renderLoginButton=function(e,t){var o;const r="string"==typeof e?document.querySelector(e):e;if(!r)throw new n(`Container element not found: ${e}`,"container_not_found");const i=new C({clientId:t.clientId,redirectUri:t.redirectUri,scopes:t.scopes,baseUrl:t.baseUrl,authorizeUrl:t.authorizeUrl}),s=j(t.theme),a=F(t.variant),l=W(t.size),c=(null===(o=t.text)||void 0===o?void 0:o.trim())||z,h=document.createElement("button");H(h,{loading:!1,size:l,text:c,theme:s,variant:a}),h.addEventListener("click",async()=>{var e,n;if(!h.classList.contains("tenms-login-btn--loading")){H(h,{loading:!0,size:l,text:c,theme:s,variant:a});try{const n=await i.loginWithPopup();null===(e=t.onSuccess)||void 0===e||e.call(t,n)}catch(e){null===(n=t.onError)||void 0===n||n.call(t,K(e))}finally{H(h,{loading:!1,size:l,text:c,theme:s,variant:a})}}}),r.replaceChildren(h)},exports.truncate=b,exports.useTenMSAuth=function(){const e=t.useContext(Q);if(!e)throw new n("useTenMSAuth must be used within a TenMSAuthProvider","missing_provider");return e},exports.waitForPopupRedirect=h;
2
2
  //# sourceMappingURL=tenms-auth.cjs.js.map