@tenminuteschool/auth-react 0.5.0 → 1.0.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 +77 -248
- package/dist/core/TenMSAuth.d.ts.map +1 -1
- package/dist/core/popup.d.ts +1 -0
- package/dist/core/popup.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/tenms-auth.cjs.js +1 -1
- package/dist/tenms-auth.cjs.js.map +1 -1
- package/dist/tenms-auth.esm.js +1 -1
- package/dist/tenms-auth.esm.js.map +1 -1
- package/dist/tenms-auth.umd.js +1 -1
- package/dist/tenms-auth.umd.js.map +1 -1
- package/dist/ui/logo.d.ts +11 -1
- package/dist/ui/logo.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,298 +1,127 @@
|
|
|
1
1
|
# @tenminuteschool/auth-react
|
|
2
2
|
|
|
3
|
-
"Login with 10MinuteSchool"
|
|
4
|
-
Drop in a login button, get back a user session. No auth system required.
|
|
3
|
+
Add "Login with 10MinuteSchool" to any React app in minutes.
|
|
5
4
|
|
|
6
5
|
---
|
|
7
6
|
|
|
8
|
-
##
|
|
7
|
+
## AI Prompt
|
|
9
8
|
|
|
10
|
-
|
|
11
|
-
- React ≥ 16.8 (hooks required)
|
|
12
|
-
- Your app's domain must be registered as an allowed origin for your Client ID
|
|
9
|
+
Copy and paste this into your AI assistant to get a full working implementation:
|
|
13
10
|
|
|
14
|
-
---
|
|
15
|
-
|
|
16
|
-
## Installation
|
|
17
|
-
|
|
18
|
-
```bash
|
|
19
|
-
npm install @tenminuteschool/auth-react
|
|
20
|
-
# or
|
|
21
|
-
pnpm add @tenminuteschool/auth-react
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
---
|
|
25
|
-
|
|
26
|
-
## Quick Start
|
|
27
|
-
|
|
28
|
-
### 1. Create the auth instance (once, at app level)
|
|
29
|
-
|
|
30
|
-
```ts
|
|
31
|
-
// lib/auth.ts
|
|
32
|
-
import { TenMSAuth } from '@tenminuteschool/auth-react';
|
|
33
|
-
|
|
34
|
-
export const auth = new TenMSAuth({ clientId: 'YOUR_CLIENT_ID' });
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
### 2. Add the login button
|
|
38
|
-
|
|
39
|
-
```tsx
|
|
40
|
-
'use client'; // Next.js only
|
|
41
|
-
import { LoginButton } from '@tenminuteschool/auth-react';
|
|
42
|
-
import type { AuthResponse } from '@tenminuteschool/auth-react';
|
|
43
|
-
import { auth } from '@/lib/auth';
|
|
44
|
-
|
|
45
|
-
export function LoginSection() {
|
|
46
|
-
async function handleLoginSuccess(response: AuthResponse) {
|
|
47
|
-
const session = await auth.handleLoginSuccess(response);
|
|
48
|
-
console.log(session.user); // { sub, name, email, ... }
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
return (
|
|
52
|
-
<LoginButton
|
|
53
|
-
clientId="YOUR_CLIENT_ID"
|
|
54
|
-
onSuccess={handleLoginSuccess}
|
|
55
|
-
onError={(err) => console.error(err)}
|
|
56
|
-
/>
|
|
57
|
-
);
|
|
58
|
-
}
|
|
59
11
|
```
|
|
12
|
+
Implement "Login with 10MinuteSchool" in this project using @tenminuteschool/auth-react.
|
|
60
13
|
|
|
61
|
-
|
|
14
|
+
Steps:
|
|
15
|
+
1. Install: npm install @tenminuteschool/auth-react
|
|
62
16
|
|
|
63
|
-
|
|
64
|
-
|
|
17
|
+
2. Add to .env.local:
|
|
18
|
+
NEXT_PUBLIC_TENMS_CLIENT_ID=YOUR_CLIENT_ID
|
|
65
19
|
|
|
66
|
-
|
|
67
|
-
|
|
20
|
+
3. Create lib/auth.ts:
|
|
21
|
+
import { TenMSAuth } from '@tenminuteschool/auth-react';
|
|
22
|
+
export const CLIENT_ID = process.env.NEXT_PUBLIC_TENMS_CLIENT_ID!;
|
|
23
|
+
export const auth = new TenMSAuth({ clientId: CLIENT_ID, storage: 'localStorage' });
|
|
68
24
|
|
|
69
|
-
|
|
70
|
-
|
|
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
|
|
71
30
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
// Logout (revokes token + clears storage)
|
|
76
|
-
await auth.logout();
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
### 4. Make authenticated API calls
|
|
80
|
-
|
|
81
|
-
```ts
|
|
82
|
-
const token = await auth.getAccessToken();
|
|
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
|
|
83
34
|
|
|
84
|
-
|
|
85
|
-
headers: { Authorization: `Bearer ${token}` },
|
|
86
|
-
});
|
|
35
|
+
Do not hardcode the client ID anywhere. Do not change the storage value.
|
|
87
36
|
```
|
|
88
37
|
|
|
89
38
|
---
|
|
90
39
|
|
|
91
|
-
##
|
|
92
|
-
|
|
93
|
-
### `new TenMSAuth(config)`
|
|
94
|
-
|
|
95
|
-
| Option | Type | Default | Description |
|
|
96
|
-
|--------|------|---------|-------------|
|
|
97
|
-
| `clientId` | `string` | **required** | Your registered client ID |
|
|
98
|
-
| `redirectUri` | `string` | `window.location.origin` | OAuth callback URL. Only needed if you want a custom path |
|
|
99
|
-
| `storage` | `'cookie' \| 'localStorage'` | `'cookie'` | Where to persist the session. Use `cookie` for SSR/Next.js, `localStorage` for pure SPAs |
|
|
100
|
-
| `scopes` | `string[]` | `['profile']` | OAuth scopes to request |
|
|
101
|
-
| `debug` | `boolean` | `false` | Logs each OAuth step to the console |
|
|
102
|
-
|
|
103
|
-
### `<LoginButton />` props
|
|
104
|
-
|
|
105
|
-
| Prop | Type | Default | Description |
|
|
106
|
-
|------|------|---------|-------------|
|
|
107
|
-
| `clientId` | `string` | **required** | Your registered client ID |
|
|
108
|
-
| `onSuccess` | `(response: AuthResponse) => void` | — | Called after the user logs in. Pass the response to `auth.handleLoginSuccess()` |
|
|
109
|
-
| `onError` | `(error: Error) => void` | — | Called on failure |
|
|
110
|
-
| `theme` | `'dark' \| 'light'` | `'dark'` | Button color scheme |
|
|
111
|
-
| `variant` | `'fill' \| 'outline'` | `'fill'` | Button style |
|
|
112
|
-
| `size` | `'small' \| 'medium' \| 'large'` | `'large'` | Button size |
|
|
113
|
-
| `text` | `string` | `'Login with 10MinuteSchool'` | Button label |
|
|
114
|
-
| `redirectUri` | `string` | `window.location.origin` | Override the redirect URI |
|
|
115
|
-
| `className` | `string` | `''` | Extra CSS class for layout |
|
|
116
|
-
|
|
117
|
-
---
|
|
118
|
-
|
|
119
|
-
## Session Methods
|
|
120
|
-
|
|
121
|
-
All session data is persisted to the configured storage (`cookie` by default) and survives page refresh.
|
|
122
|
-
|
|
123
|
-
### `auth.handleLoginSuccess(response)`
|
|
124
|
-
Exchanges the authorization code for tokens, fetches the user profile, and saves everything to storage. Returns `{ user, accessToken }`.
|
|
125
|
-
|
|
126
|
-
```ts
|
|
127
|
-
const session = await auth.handleLoginSuccess(response);
|
|
128
|
-
// session.user → UserInfo
|
|
129
|
-
// session.accessToken → string
|
|
130
|
-
```
|
|
131
|
-
|
|
132
|
-
### `auth.getAccessToken()`
|
|
133
|
-
Returns a valid access token. **Automatically refreshes** if the current token is expired and a refresh token is available. Returns `null` if the user is not logged in.
|
|
40
|
+
## Installation
|
|
134
41
|
|
|
135
|
-
```
|
|
136
|
-
|
|
42
|
+
```bash
|
|
43
|
+
npm install @tenminuteschool/auth-react
|
|
44
|
+
# or
|
|
45
|
+
pnpm add @tenminuteschool/auth-react
|
|
137
46
|
```
|
|
138
47
|
|
|
139
|
-
|
|
140
|
-
Returns the stored user profile synchronously. Returns `null` if not logged in.
|
|
48
|
+
---
|
|
141
49
|
|
|
142
|
-
|
|
143
|
-
const user = auth.getUser();
|
|
144
|
-
// { sub, name, email, phone, picture, email_verified, phone_verified }
|
|
145
|
-
```
|
|
50
|
+
## Setup
|
|
146
51
|
|
|
147
|
-
|
|
148
|
-
Returns `true` if a non-expired access token exists in storage. Synchronous, no network call.
|
|
52
|
+
Add your client ID to `.env.local`:
|
|
149
53
|
|
|
150
|
-
```
|
|
151
|
-
|
|
54
|
+
```bash
|
|
55
|
+
NEXT_PUBLIC_TENMS_CLIENT_ID=your_client_id_here
|
|
152
56
|
```
|
|
153
57
|
|
|
154
|
-
|
|
155
|
-
Revokes the access token on the server and clears all session data from storage.
|
|
58
|
+
Then create this file once at the root of your project:
|
|
156
59
|
|
|
157
60
|
```ts
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
---
|
|
61
|
+
// lib/auth.ts
|
|
62
|
+
import { TenMSAuth } from '@tenminuteschool/auth-react';
|
|
162
63
|
|
|
163
|
-
|
|
64
|
+
export const CLIENT_ID = process.env.NEXT_PUBLIC_TENMS_CLIENT_ID!;
|
|
164
65
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
email?: string;
|
|
170
|
-
phone?: string;
|
|
171
|
-
picture?: string;
|
|
172
|
-
email_verified?: boolean;
|
|
173
|
-
phone_verified?: boolean;
|
|
174
|
-
}
|
|
66
|
+
export const auth = new TenMSAuth({
|
|
67
|
+
clientId: CLIENT_ID,
|
|
68
|
+
storage: 'localStorage',
|
|
69
|
+
});
|
|
175
70
|
```
|
|
176
71
|
|
|
177
72
|
---
|
|
178
73
|
|
|
179
|
-
##
|
|
74
|
+
## Login Button
|
|
180
75
|
|
|
181
|
-
|
|
76
|
+
```tsx
|
|
77
|
+
import { LoginButton } from '@tenminuteschool/auth-react';
|
|
78
|
+
import { auth, CLIENT_ID } from '@/lib/auth';
|
|
182
79
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
case 'token_exchange_failed': // server rejected the code
|
|
193
|
-
case 'userinfo_failed': // couldn't fetch profile
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
}
|
|
80
|
+
<LoginButton
|
|
81
|
+
clientId={CLIENT_ID}
|
|
82
|
+
onSuccess={async (response) => {
|
|
83
|
+
const session = await auth.handleLoginSuccess(response);
|
|
84
|
+
// session.user → { sub, name, email, picture, ... }
|
|
85
|
+
window.location.href = '/dashboard';
|
|
86
|
+
}}
|
|
87
|
+
onError={(err) => console.error(err)}
|
|
88
|
+
/>
|
|
197
89
|
```
|
|
198
90
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
| Code | When |
|
|
202
|
-
|------|------|
|
|
203
|
-
| `popup_blocked` | Browser blocked the login popup |
|
|
204
|
-
| `token_exchange_failed` | Server rejected the authorization code |
|
|
205
|
-
| `userinfo_failed` | Failed to fetch user profile |
|
|
206
|
-
| `missing_client_id` | `clientId` not provided |
|
|
207
|
-
| `missing_redirect_uri` | `redirectUri` needed but not set and `window` unavailable |
|
|
208
|
-
| `state_mismatch` | Possible CSRF — state param didn't match |
|
|
209
|
-
|
|
210
|
-
---
|
|
211
|
-
|
|
212
|
-
## Full Next.js Example
|
|
91
|
+
### Button appearance
|
|
213
92
|
|
|
214
93
|
```tsx
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
export default function LoginPage() {
|
|
224
|
-
const [user, setUser] = useState<UserInfo | null>(null);
|
|
225
|
-
|
|
226
|
-
useEffect(() => {
|
|
227
|
-
setUser(auth.getUser());
|
|
228
|
-
}, []);
|
|
229
|
-
|
|
230
|
-
async function handleLoginSuccess(response: AuthResponse) {
|
|
231
|
-
const session = await auth.handleLoginSuccess(response);
|
|
232
|
-
setUser(session.user);
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
async function handleLogout() {
|
|
236
|
-
await auth.logout();
|
|
237
|
-
setUser(null);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
if (user) {
|
|
241
|
-
return (
|
|
242
|
-
<div>
|
|
243
|
-
<p>Logged in as {user.name ?? user.email}</p>
|
|
244
|
-
<button onClick={handleLogout}>Log out</button>
|
|
245
|
-
</div>
|
|
246
|
-
);
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
return (
|
|
250
|
-
<LoginButton
|
|
251
|
-
clientId="YOUR_CLIENT_ID"
|
|
252
|
-
theme="dark"
|
|
253
|
-
onSuccess={handleLoginSuccess}
|
|
254
|
-
onError={(err) => console.error(err)}
|
|
255
|
-
/>
|
|
256
|
-
);
|
|
257
|
-
}
|
|
94
|
+
<LoginButton
|
|
95
|
+
clientId={CLIENT_ID}
|
|
96
|
+
onSuccess={...}
|
|
97
|
+
theme="dark" // 'dark' (default) | 'light'
|
|
98
|
+
variant="fill" // 'fill' (default) | 'outline'
|
|
99
|
+
size="large" // 'large' (default) | 'medium' | 'small'
|
|
100
|
+
text="Sign in" // custom label
|
|
101
|
+
/>
|
|
258
102
|
```
|
|
259
103
|
|
|
260
104
|
---
|
|
261
105
|
|
|
262
|
-
##
|
|
263
|
-
|
|
264
|
-
| Storage | Survives refresh | SSR readable | Recommended for |
|
|
265
|
-
|---------|-----------------|--------------|-----------------|
|
|
266
|
-
| `cookie` (default) | Yes | Yes | Next.js, SSR apps |
|
|
267
|
-
| `localStorage` | Yes | No | Pure client-side SPAs |
|
|
106
|
+
## Reading the session
|
|
268
107
|
|
|
269
|
-
|
|
108
|
+
```ts
|
|
109
|
+
import { auth } from '@/lib/auth';
|
|
270
110
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
| `_tenms_user` | JSON-serialized user profile |
|
|
111
|
+
auth.isLoggedIn() // true/false — no network call
|
|
112
|
+
auth.getUser() // { sub, name, email, picture, ... } or null
|
|
113
|
+
await auth.getAccessToken() // valid token string, auto-refreshes if expired
|
|
114
|
+
await auth.logout() // revokes token + clears session
|
|
115
|
+
```
|
|
277
116
|
|
|
278
117
|
---
|
|
279
118
|
|
|
280
|
-
##
|
|
119
|
+
## TenMSAuth options
|
|
281
120
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
<script>
|
|
291
|
-
document.querySelector('tenms-login-button')
|
|
292
|
-
.addEventListener('tenms-success', async (e) => {
|
|
293
|
-
const auth = new TenMSAuth.TenMSAuth({ clientId: 'YOUR_CLIENT_ID' });
|
|
294
|
-
const session = await auth.handleLoginSuccess(e.detail);
|
|
295
|
-
console.log(session.user);
|
|
296
|
-
});
|
|
297
|
-
</script>
|
|
298
|
-
```
|
|
121
|
+
| Option | Type | Default | Description |
|
|
122
|
+
|--------|------|---------|-------------|
|
|
123
|
+
| `clientId` | `string` | required | Your registered client ID |
|
|
124
|
+
| `storage` | `'cookie' \| 'localStorage'` | `'cookie'` | Use `localStorage` for SPAs, `cookie` for SSR |
|
|
125
|
+
| `redirectUri` | `string` | `window.location.origin` | Override only if needed |
|
|
126
|
+
| `scopes` | `string[]` | `['profile', 'email', 'phone']` | OAuth scopes |
|
|
127
|
+
| `debug` | `boolean` | `false` | Logs every OAuth step to the console |
|
|
@@ -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;
|
|
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,OAAO,CAAC,YAAY,CAAC;IAyEvE;;;;;;OAMG;IACG,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC;IAuBxC;;;;;;;OAOG;IACH,sBAAsB,IAAI,YAAY,GAAG,IAAI;IA8E7C;;;;;;OAMG;IACG,YAAY,CAChB,IAAI,EAAE,MAAM,EACZ,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,aAAa,CAAC;IAkEzB;;;;;;OAMG;IACG,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IAgDhE;;OAEG;IACG,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;IAyCzD;;;;;;OAMG;IACG,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAqC/C;;;;;;;;OAQG;IACG,kBAAkB,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;IA6BlE;;;;OAIG;IACG,cAAc,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IA+C9C;;OAEG;IACH,OAAO,IAAI,QAAQ,GAAG,IAAI;IAU1B;;;OAGG;IACH,UAAU,IAAI,OAAO;IAQrB;;OAEG;IACG,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAa7B;;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"}
|
package/dist/core/popup.d.ts
CHANGED
package/dist/core/popup.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"popup.d.ts","sourceRoot":"","sources":["../../src/core/popup.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,wCAAwC;IACxC,GAAG,EAAE,MAAM,CAAC;IAEZ,6BAA6B;IAC7B,KAAK,EAAE,MAAM,CAAC;IAEd,8BAA8B;IAC9B,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;IAEb,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAC;CACf;
|
|
1
|
+
{"version":3,"file":"popup.d.ts","sourceRoot":"","sources":["../../src/core/popup.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,wCAAwC;IACxC,GAAG,EAAE,MAAM,CAAC;IAEZ,6BAA6B;IAC7B,KAAK,EAAE,MAAM,CAAC;IAEd,8BAA8B;IAC9B,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;IAEb,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAC;CACf;AAOD,eAAO,MAAM,sBAAsB,8BAA8B,CAAC;AAElE;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,GAAG,IAAI,CA6B5D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,MAAM,EACnB,aAAa,EAAE,MAAM,EACrB,SAAS,SAAqB,GAC7B,OAAO,CAAC,mBAAmB,CAAC,CA4J9B"}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Public entrypoint for the @10minuteschool/auth browser SDK.
|
|
4
4
|
*/
|
|
5
5
|
/** Current SDK version. */
|
|
6
|
-
export declare const VERSION = "0.
|
|
6
|
+
export declare const VERSION = "1.0.0";
|
|
7
7
|
export { TenMSAuth } from './core/TenMSAuth';
|
|
8
8
|
/** Public types and error contract. */
|
|
9
9
|
export type { AuthResponse, LoginButtonOptions, PopupOptions, Session, TenMSAuthConfig, TokenResponse, UserInfo, } from './core/types';
|
package/dist/tenms-auth.cjs.js
CHANGED
|
@@ -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}`)}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)),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 l(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;d(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(),c=window.setInterval(()=>{try{if(!e||e.closed)return window.clearInterval(c),void s(new n("Login popup was closed","popup_closed"));if(Date.now()-a>i)return window.clearInterval(c),e.close(),void s(new n("Login timed out while waiting for the redirect URI","popup_timeout"));const l=e.location.href;if(!l)return;let d;try{d=new URL(l)}catch(e){return}if(d.origin!==r.origin||d.pathname!==r.pathname)return;window.clearInterval(c),e.close();const h=d.searchParams.get("code"),u=d.searchParams.get("state"),g=d.searchParams.get("error"),f=d.searchParams.get("error_description");if(g)return void s(new n(f||g,"oauth_error"));if(!h)return void s(new n("No authorization code was returned to the redirect URI","missing_authorization_code"));if(u!==o)return void s(new n("State mismatch — possible CSRF attack","state_mismatch"));t({code:h,state:u})}catch(e){e instanceof DOMException||(window.clearInterval(c),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 h="[TenMSAuth]",u="color:#22c55e;font-weight:700",g="color:inherit;font-weight:normal";function f(e){return e?m:p}const p={info:()=>{},warn:()=>{},error:()=>{}},m={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${h}%c ${e}`,u,g),console.table(t),console.groupEnd()):console.log(`%c${h}%c ${e}`,u,g)},warn(e,t){console.warn(`%c${h}%c ⚠ ${e}`,u,g,null!=t?t:"")},error(e,t){console.error(`%c${h}%c ✕ ${e}`,u,g,null!=t?t:"")}};function w(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}class b{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 _{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 v="https://api.10minuteschool.com/auth",k="https://10minuteschool.com/auth/login",y=["profile","email","phone"],S={ACCESS_TOKEN:"_tenms_access_token",REFRESH_TOKEN:"_tenms_refresh_token",EXPIRES_AT:"_tenms_expires_at",USER:"_tenms_user"};class x{constructor(e){var t,o;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=E(v,"baseUrl","invalid_base_url"),a=E(k,"authorizeUrl","invalid_authorize_url"),c=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);return{clientId:i,redirectUri:r,scopes:c,baseUrl:s,authorizeUrl:a}}(e),this.log=f(!0===e.debug),this.storage="localStorage"===(null!==(t=e.storage)&&void 0!==t?t:"cookie")?new _:new b,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})}async loginWithPopup(e={}){var t,o;const a=null!==(t=e.width)&&void 0!==t?t:500,d=null!==(o=e.height)&&void 0!==o?o:600;this.log.info("loginWithPopup:start",{width:a,height:d});const h=s(),u=i();this.log.info("loginWithPopup:pkce-generated",{state:w(h),codeVerifier:w(u)});const g=c({url:"about:blank",width:a,height:d});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:w(e)}),g.location.href=t;const n=await l(g,this.requireRedirectUri(),h);return this.log.info("loginWithPopup:success",{code:w(n.code),state:w(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:w(e),codeVerifier:w(t),codeChallenge:w(n)}),function(e,t){sessionStorage.setItem(C("state"),e),sessionStorage.setItem(C("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[C("state"),C("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(C("state")),a=sessionStorage.getItem(C("code_verifier"));if(!o||!s||o!==s){U();const e=new n("State mismatch — possible CSRF attack","state_mismatch");throw this.log.warn("handleRedirectCallback:state-mismatch",{receivedState:o?w(o):"(missing)",storedStatePresent:Boolean(s)}),e}if(U(),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:w(t),state:w(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:w(e),codeVerifier:w(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 T(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=R(await i.json());return this.log.info("exchangeCode:success",{token_type:r.token_type,expires_in:r.expires_in,scope:r.scope,access_token:w(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:w(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 T(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=R(await o.json());return this.log.info("refreshToken:success",{token_type:i.token_type,expires_in:i.expires_in,access_token:w(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:w(e)});const r=await fetch(i,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){const e=await T(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:w(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 T(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:w(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(S.ACCESS_TOKEN,t.access_token,o),this.storage.set(S.EXPIRES_AT,String(o),o),t.refresh_token&&this.storage.set(S.REFRESH_TOKEN,t.refresh_token),this.storage.set(S.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(S.ACCESS_TOKEN),n=Number(null!==(e=this.storage.get(S.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(S.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(S.ACCESS_TOKEN,e.access_token,t),this.storage.set(S.EXPIRES_AT,String(t),t),e.refresh_token&&this.storage.set(S.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(S.USER);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}}isLoggedIn(){var e;if(!this.storage.get(S.ACCESS_TOKEN))return!1;const t=Number(null!==(e=this.storage.get(S.EXPIRES_AT))&&void 0!==e?e:"0");return 0===t||Math.floor(Date.now()/1e3)<t}async logout(){const e=this.storage.get(S.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(S))}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 E(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 C(e){return`tenms_auth_${e}`}function U(){sessionStorage.removeItem(C("state")),sessionStorage.removeItem(C("code_verifier"))}async function T(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 R(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:#e5e7eb;color:#111}.tenms-login-btn--light.tenms-login-btn--outline:hover:not(:disabled){background:#f5f5f5;border-color:#d1d5db}.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 A(e){return"light"===e?'<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>':'<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>'}function $(e="dark"){return`<span class="tenms-login-btn__logo">${A(e)}</span>`}var L;const P="Login with 10MinuteSchool",z=null!==(L=globalThis.HTMLElement)&&void 0!==L?L:class{};class N extends z{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=B(this.getAttribute("variant")),o=q(this.getAttribute("size")),i=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||P;var r;this.innerHTML=`\n <button class="${V((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">${F(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 x(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(W(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 O(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",N)}function M(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">${F(t.text)}</span>`:`${$(t.theme)}<span class="tenms-login-btn__label">${F(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 B(e){return"outline"===e?e:"fill"}function q(e){return"small"===e||"medium"===e?e:"large"}function F(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function W(e){return e instanceof Error?e:new Error(String(e))}const H="Login with 10MinuteSchool",K="dark",D="fill",J="large";function X(e){return"light"===e?e:K}function Z(e){return"small"===e||"medium"===e?e:J}O(),exports.LoginButton=function(e){const{clientId:n,redirectUri:o,scopes:i,theme:r=K,variant:s=D,size:a=J,text:c=H,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 x({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--${X(r)}`,`tenms-login-btn--${v=s,"outline"===v?v:D}`,`tenms-login-btn--${Z(a)}`,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:A(X(r))}}),t.createElement("span",{className:"tenms-login-btn__label"},c))},exports.TenMSAuth=x,exports.TenMSAuthError=n,exports.TenMSLoginButtonElement=N,exports.VERSION="0.5.0",exports.createLogger=f,exports.generateCodeChallenge=r,exports.generateCodeVerifier=i,exports.generateState=s,exports.openPopup=c,exports.registerLoginButton=O,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 x({clientId:t.clientId,redirectUri:t.redirectUri,scopes:t.scopes}),s=j(t.theme),a=B(t.variant),c=q(t.size),l=(null===(o=t.text)||void 0===o?void 0:o.trim())||P,d=document.createElement("button");M(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")){M(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,W(e))}finally{M(d,{loading:!1,size:c,text:l,theme:s,variant:a})}}}),i.replaceChildren(d)},exports.truncate=w,exports.waitForPopupRedirect=l;
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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;
|
|
2
2
|
//# sourceMappingURL=tenms-auth.cjs.js.map
|