@tenminuteschool/auth-react 0.1.0 → 0.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 +298 -0
- package/dist/core/TenMSAuth.d.ts +33 -1
- package/dist/core/TenMSAuth.d.ts.map +1 -1
- package/dist/core/storage.d.ts +20 -0
- package/dist/core/storage.d.ts.map +1 -0
- package/dist/core/types.d.ts +17 -2
- package/dist/core/types.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/react/LoginButton.d.ts +0 -13
- package/dist/react/LoginButton.d.ts.map +1 -1
- package/dist/tenms-auth.cjs.js +1 -1
- package/dist/tenms-auth.cjs.js.map +1 -1
- package/dist/tenms-auth.css +1 -0
- 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/LoginButton.d.ts.map +1 -1
- package/dist/ui/logo.d.ts +8 -11
- package/dist/ui/logo.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
# @tenminuteschool/auth-react
|
|
2
|
+
|
|
3
|
+
"Login with 10MinuteSchool" for React and Next.js apps.
|
|
4
|
+
Drop in a login button, get back a user session. No auth system required.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Requirements
|
|
9
|
+
|
|
10
|
+
- A **Client ID** — get one by registering your app with 10MinuteSchool
|
|
11
|
+
- React ≥ 16.8 (hooks required)
|
|
12
|
+
- Your app's domain must be registered as an allowed origin for your Client ID
|
|
13
|
+
|
|
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
|
+
```
|
|
60
|
+
|
|
61
|
+
### 3. Use the session anywhere
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { auth } from '@/lib/auth';
|
|
65
|
+
|
|
66
|
+
// Get the current user (sync, reads from storage)
|
|
67
|
+
const user = auth.getUser();
|
|
68
|
+
|
|
69
|
+
// Get a valid access token for API calls (async, auto-refreshes if expired)
|
|
70
|
+
const token = await auth.getAccessToken();
|
|
71
|
+
|
|
72
|
+
// Check login status (sync)
|
|
73
|
+
const loggedIn = auth.isLoggedIn();
|
|
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();
|
|
83
|
+
|
|
84
|
+
const res = await fetch('https://api.example.com/data', {
|
|
85
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## Configuration
|
|
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.
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
const token = await auth.getAccessToken(); // string | null
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### `auth.getUser()`
|
|
140
|
+
Returns the stored user profile synchronously. Returns `null` if not logged in.
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
const user = auth.getUser();
|
|
144
|
+
// { sub, name, email, phone, picture, email_verified, phone_verified }
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### `auth.isLoggedIn()`
|
|
148
|
+
Returns `true` if a non-expired access token exists in storage. Synchronous, no network call.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
if (auth.isLoggedIn()) { ... }
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### `auth.logout()`
|
|
155
|
+
Revokes the access token on the server and clears all session data from storage.
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
await auth.logout();
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## User Profile Shape
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
interface UserInfo {
|
|
167
|
+
sub: string; // unique user ID — always present
|
|
168
|
+
name?: string;
|
|
169
|
+
email?: string;
|
|
170
|
+
phone?: string;
|
|
171
|
+
picture?: string;
|
|
172
|
+
email_verified?: boolean;
|
|
173
|
+
phone_verified?: boolean;
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
## Error Handling
|
|
180
|
+
|
|
181
|
+
All SDK errors are instances of `TenMSAuthError` with a stable `code` field:
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
import { TenMSAuthError } from '@tenminuteschool/auth-react';
|
|
185
|
+
|
|
186
|
+
try {
|
|
187
|
+
await auth.handleLoginSuccess(response);
|
|
188
|
+
} catch (err) {
|
|
189
|
+
if (err instanceof TenMSAuthError) {
|
|
190
|
+
switch (err.code) {
|
|
191
|
+
case 'popup_blocked': // user needs to allow popups
|
|
192
|
+
case 'token_exchange_failed': // server rejected the code
|
|
193
|
+
case 'userinfo_failed': // couldn't fetch profile
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Common error codes:
|
|
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
|
|
213
|
+
|
|
214
|
+
```tsx
|
|
215
|
+
// app/login/page.tsx
|
|
216
|
+
'use client';
|
|
217
|
+
import { useEffect, useState } from 'react';
|
|
218
|
+
import { LoginButton, TenMSAuth } from '@tenminuteschool/auth-react';
|
|
219
|
+
import type { AuthResponse, UserInfo } from '@tenminuteschool/auth-react';
|
|
220
|
+
|
|
221
|
+
const auth = new TenMSAuth({ clientId: 'YOUR_CLIENT_ID' });
|
|
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
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
---
|
|
261
|
+
|
|
262
|
+
## Storage
|
|
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 |
|
|
268
|
+
|
|
269
|
+
What gets stored:
|
|
270
|
+
|
|
271
|
+
| Key | Value |
|
|
272
|
+
|-----|-------|
|
|
273
|
+
| `_tenms_access_token` | OAuth access token |
|
|
274
|
+
| `_tenms_refresh_token` | OAuth refresh token (if issued) |
|
|
275
|
+
| `_tenms_expires_at` | Token expiry as Unix timestamp |
|
|
276
|
+
| `_tenms_user` | JSON-serialized user profile |
|
|
277
|
+
|
|
278
|
+
---
|
|
279
|
+
|
|
280
|
+
## Plain HTML / No Bundler
|
|
281
|
+
|
|
282
|
+
```html
|
|
283
|
+
<script src="https://cdn.10minuteschool.com/sdk/tenms-auth.umd.js"></script>
|
|
284
|
+
|
|
285
|
+
<tenms-login-button
|
|
286
|
+
client-id="YOUR_CLIENT_ID"
|
|
287
|
+
theme="dark"
|
|
288
|
+
></tenms-login-button>
|
|
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
|
+
```
|
package/dist/core/TenMSAuth.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AuthResponse, type PopupOptions, type TenMSAuthConfig, type TokenResponse, type UserInfo } from './types';
|
|
1
|
+
import { type AuthResponse, type PopupOptions, type Session, type TenMSAuthConfig, type TokenResponse, type UserInfo } from './types';
|
|
2
2
|
/**
|
|
3
3
|
* Main browser client for "Login with 10MinuteSchool".
|
|
4
4
|
*
|
|
@@ -12,6 +12,7 @@ import { type AuthResponse, type PopupOptions, type TenMSAuthConfig, type TokenR
|
|
|
12
12
|
export declare class TenMSAuth {
|
|
13
13
|
private readonly config;
|
|
14
14
|
private readonly log;
|
|
15
|
+
private readonly storage;
|
|
15
16
|
constructor(config: TenMSAuthConfig);
|
|
16
17
|
/**
|
|
17
18
|
* Starts OAuth login in a popup window and returns the authorization code plus
|
|
@@ -67,6 +68,35 @@ export declare class TenMSAuth {
|
|
|
67
68
|
* surface as structured SDK errors.
|
|
68
69
|
*/
|
|
69
70
|
revokeToken(token: string): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* Completes login after the popup flow: exchanges the authorization code for
|
|
73
|
+
* tokens, fetches the user profile, and persists everything to the configured
|
|
74
|
+
* storage. Returns the session so the caller can update UI immediately.
|
|
75
|
+
*
|
|
76
|
+
* Pass `redirectUri` here if the instance was created without one (e.g. a
|
|
77
|
+
* singleton used only for session reads where the URI is only known at login
|
|
78
|
+
* time, such as when it is derived from `window.location.href`).
|
|
79
|
+
*/
|
|
80
|
+
handleLoginSuccess(response: AuthResponse): Promise<Session>;
|
|
81
|
+
/**
|
|
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.
|
|
85
|
+
*/
|
|
86
|
+
getAccessToken(): Promise<string | null>;
|
|
87
|
+
/**
|
|
88
|
+
* Returns the stored user profile, or `null` if no session exists.
|
|
89
|
+
*/
|
|
90
|
+
getUser(): UserInfo | null;
|
|
91
|
+
/**
|
|
92
|
+
* Returns `true` when a non-expired access token exists in storage.
|
|
93
|
+
* Does not make any network requests.
|
|
94
|
+
*/
|
|
95
|
+
isLoggedIn(): boolean;
|
|
96
|
+
/**
|
|
97
|
+
* Revokes the current access token and clears the session from storage.
|
|
98
|
+
*/
|
|
99
|
+
logout(): Promise<void>;
|
|
70
100
|
/**
|
|
71
101
|
* Returns the API base URL the client was configured with.
|
|
72
102
|
*/
|
|
@@ -75,6 +105,8 @@ export declare class TenMSAuth {
|
|
|
75
105
|
* Returns the client identifier configured for this SDK instance.
|
|
76
106
|
*/
|
|
77
107
|
getClientId(): string;
|
|
108
|
+
private clearSession;
|
|
109
|
+
private requireRedirectUri;
|
|
78
110
|
/**
|
|
79
111
|
* Builds the OAuth authorize URL for the current client configuration.
|
|
80
112
|
*
|
|
@@ -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,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,QAAQ,EAEd,MAAM,SAAS,CAAC;
|
|
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;IAgBnC;;;;;;;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"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface StorageAdapter {
|
|
2
|
+
get(key: string): string | null;
|
|
3
|
+
set(key: string, value: string, expiresAt?: number): void;
|
|
4
|
+
remove(key: string): void;
|
|
5
|
+
clear(keys: string[]): void;
|
|
6
|
+
}
|
|
7
|
+
export declare class CookieStorageAdapter implements StorageAdapter {
|
|
8
|
+
get(key: string): string | null;
|
|
9
|
+
set(key: string, value: string, expiresAt?: number): void;
|
|
10
|
+
remove(key: string): void;
|
|
11
|
+
clear(keys: string[]): void;
|
|
12
|
+
}
|
|
13
|
+
export declare class LocalStorageAdapter implements StorageAdapter {
|
|
14
|
+
get(key: string): string | null;
|
|
15
|
+
set(key: string, value: string): void;
|
|
16
|
+
remove(key: string): void;
|
|
17
|
+
clear(keys: string[]): void;
|
|
18
|
+
}
|
|
19
|
+
export declare function createStorageAdapter(type: 'cookie' | 'localStorage'): StorageAdapter;
|
|
20
|
+
//# sourceMappingURL=storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../src/core/storage.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,cAAc;IAC7B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IAChC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1D,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;CAC7B;AAED,qBAAa,oBAAqB,YAAW,cAAc;IACzD,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAO/B,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI;IAQzD,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIzB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;CAG5B;AAED,qBAAa,mBAAoB,YAAW,cAAc;IACxD,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAI/B,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAIrC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIzB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;CAG5B;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,QAAQ,GAAG,cAAc,GAAG,cAAc,CAEpF"}
|
package/dist/core/types.d.ts
CHANGED
|
@@ -4,11 +4,20 @@ export interface TenMSAuthConfig {
|
|
|
4
4
|
/**
|
|
5
5
|
* Redirect URI registered for the client.
|
|
6
6
|
*
|
|
7
|
+
* Required for login flows (popup/redirect) and token exchange. Can be
|
|
8
|
+
* omitted when only using session methods (getAccessToken, getUser, logout).
|
|
9
|
+
*
|
|
7
10
|
* For popup flows, it must be same-origin as the opener so the SDK can read
|
|
8
11
|
* `popup.location` after the provider redirects back with `code` and `state`.
|
|
9
12
|
*/
|
|
10
|
-
redirectUri
|
|
13
|
+
redirectUri?: string;
|
|
11
14
|
scopes?: string[];
|
|
15
|
+
/**
|
|
16
|
+
* Where to persist the session (access token, refresh token, user profile).
|
|
17
|
+
* Defaults to `'cookie'`, which works in both browser and SSR environments.
|
|
18
|
+
* Use `'localStorage'` for pure client-side apps that don't need SSR.
|
|
19
|
+
*/
|
|
20
|
+
storage?: 'cookie' | 'localStorage';
|
|
12
21
|
/**
|
|
13
22
|
* Enable verbose debug logging to the browser console.
|
|
14
23
|
*
|
|
@@ -17,6 +26,11 @@ export interface TenMSAuthConfig {
|
|
|
17
26
|
*/
|
|
18
27
|
debug?: boolean;
|
|
19
28
|
}
|
|
29
|
+
/** Session data persisted after a successful login. */
|
|
30
|
+
export interface Session {
|
|
31
|
+
user: UserInfo;
|
|
32
|
+
accessToken: string;
|
|
33
|
+
}
|
|
20
34
|
/** Result returned after authorization completes. */
|
|
21
35
|
export interface AuthResponse {
|
|
22
36
|
code: string;
|
|
@@ -49,7 +63,8 @@ export interface PopupOptions {
|
|
|
49
63
|
}
|
|
50
64
|
/** Customization hooks shared by the packaged login button integrations. */
|
|
51
65
|
export interface LoginButtonOptions {
|
|
52
|
-
theme?: 'dark' | 'light'
|
|
66
|
+
theme?: 'dark' | 'light';
|
|
67
|
+
variant?: 'fill' | 'outline';
|
|
53
68
|
size?: 'small' | 'medium' | 'large';
|
|
54
69
|
text?: string;
|
|
55
70
|
onSuccess?: (response: AuthResponse) => void;
|
package/dist/core/types.d.ts.map
CHANGED
|
@@ -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
|
|
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,EAAE,QAAQ,GAAG,cAAc,CAAC;IAEpC;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,uDAAuD;AACvD,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,QAAQ,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,qDAAqD;AACrD,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,0DAA0D;AAC1D,MAAM,WAAW,QAAQ;IACvB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,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 = "0.
|
|
6
|
+
export declare const VERSION = "0.2.0";
|
|
7
7
|
export { TenMSAuth } from './core/TenMSAuth';
|
|
8
8
|
/** Public types and error contract. */
|
|
9
|
-
export type { AuthResponse, LoginButtonOptions, PopupOptions, TenMSAuthConfig, TokenResponse, UserInfo, } from './core/types';
|
|
9
|
+
export type { AuthResponse, LoginButtonOptions, PopupOptions, Session, 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';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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,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,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAE/D,gCAAgC;AAChC,OAAO,EACL,uBAAuB,EACvB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,YAAY,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC"}
|
|
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,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAE/D,gCAAgC;AAChC,OAAO,EACL,uBAAuB,EACvB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,YAAY,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC"}
|
|
@@ -1,21 +1,8 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
2
|
import '../ui/LoginButton.css';
|
|
3
3
|
import type { LoginButtonOptions, TenMSAuthConfig } from '../core/types';
|
|
4
|
-
/**
|
|
5
|
-
* Props for the optional React button wrapper.
|
|
6
|
-
*
|
|
7
|
-
* This composes the core auth configuration with the shared button styling and
|
|
8
|
-
* callback options, while allowing an extra `className` for app-specific layout.
|
|
9
|
-
*/
|
|
10
4
|
export interface LoginButtonProps extends TenMSAuthConfig, LoginButtonOptions {
|
|
11
5
|
className?: string;
|
|
12
6
|
}
|
|
13
|
-
/**
|
|
14
|
-
* Optional React wrapper around the popup login flow.
|
|
15
|
-
*
|
|
16
|
-
* Requires React ≥ 16.8. Import from `@10minuteschool/auth` only in React
|
|
17
|
-
* projects — non-React consumers should use `renderLoginButton` or the
|
|
18
|
-
* `<tenms-login-button>` web component instead.
|
|
19
|
-
*/
|
|
20
7
|
export declare function LoginButton(props: LoginButtonProps): React.JSX.Element;
|
|
21
8
|
//# sourceMappingURL=LoginButton.d.ts.map
|
|
@@ -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;
|
|
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"}
|
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 l(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 c(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(),l=window.setInterval(()=>{try{if(!e||e.closed)return window.clearInterval(l),void s(new n("Login popup was closed","popup_closed"));if(Date.now()-a>i)return window.clearInterval(l),e.close(),void s(new n("Login timed out while waiting for the redirect URI","popup_timeout"));const c=e.location.href;if(!c)return;let d;try{d=new URL(c)}catch(e){return}if(d.origin!==r.origin||d.pathname!==r.pathname)return;window.clearInterval(l),e.close();const h=d.searchParams.get("code"),g=d.searchParams.get("state"),u=d.searchParams.get("error"),p=d.searchParams.get("error_description");if(u)return void s(new n(p||u,"oauth_error"));if(!h)return void s(new n("No authorization code was returned to the redirect URI","missing_authorization_code"));if(g!==o)return void s(new n("State mismatch — possible CSRF attack","state_mismatch"));t({code:h,state:g})}catch(e){e instanceof DOMException||(window.clearInterval(l),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]",g="color:#22c55e;font-weight:700",u="color:inherit;font-weight:normal";function p(e){return e?m:f}const f={info:()=>{},warn:()=>{},error:()=>{}},m={info(e,t){t&&Object.keys(t).length>0?(console.groupCollapsed(`%c${h}%c ${e}`,g,u),console.table(t),console.groupEnd()):console.log(`%c${h}%c ${e}`,g,u)},warn(e,t){console.warn(`%c${h}%c ⚠ ${e}`,g,u,null!=t?t:"")},error(e,t){console.error(`%c${h}%c ✕ ${e}`,g,u,null!=t?t:"")}};function b(e){return e?e.length>8?`${e.slice(0,8)}…`:e:"(empty)"}const w="https://local-api.10minuteschool.net/auth",v="http://local.10minuteschool.net/auth/login",_=["profile"];class x{constructor(e){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();if(!r)throw new n("redirectUri is required","missing_redirect_uri");const s=k(w,"baseUrl","invalid_base_url"),a=k(v,"authorizeUrl","invalid_authorize_url"),l=function(e){if(!Array.isArray(e)||0===e.length)return _;const t=e.map(e=>e.trim()).filter(Boolean);return t.length>0?t:_}(e.scopes);return{clientId:i,redirectUri:r,scopes:l,baseUrl:s,authorizeUrl:a}}(e),this.log=p(!0===e.debug),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(" "),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(),g=i();this.log.info("loginWithPopup:pkce-generated",{state:b(h),codeVerifier:b(g)});const u=l({url:"about:blank",width:a,height:d});if(!u){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(u===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){}}(u);try{const e=await r(g),t=this.buildAuthorizeUrl(h,e);this.log.info("loginWithPopup:navigating",{authorizeUrl:t,codeChallenge:b(e)}),u.location.href=t;const n=await c(u,this.config.redirectUri,h);return this.log.info("loginWithPopup:success",{code:b(n.code),state:b(n.state)}),{code:n.code,state:n.state,codeVerifier:g}}catch(e){throw u.closed||u.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(y("state"),e),sessionStorage.setItem(y("code_verifier"),t)}(e,t),this.log.info("loginWithRedirect:session-persisted",{storageKeys:[y("state"),y("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(y("state")),a=sessionStorage.getItem(y("code_verifier"));if(!o||!s||o!==s){C();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(C(),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.config.redirectUri,client_id:this.config.clientId,code_verifier:t})});if(!i.ok){const e=await S(i),t=new n(U(e,"Token exchange failed"),"token_exchange_failed");throw this.log.error("exchangeCode:error",{status:i.status,message:t.message}),t}const r=I(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 S(o),t=new n(U(e,"Token refresh failed"),"token_refresh_failed");throw this.log.error("refreshToken:error",{status:o.status,message:t.message}),t}const i=I(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 S(r),t=new n(U(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 S(o),t=new n(U(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")}getBaseUrl(){return this.config.baseUrl}getClientId(){return this.config.clientId}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.config.redirectUri),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 k(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 y(e){return`tenms_auth_${e}`}function C(){sessionStorage.removeItem(y("state")),sessionStorage.removeItem(y("code_verifier"))}async function S(e){try{const t=await e.text();return t?JSON.parse(t):{}}catch(e){return{}}}function U(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 I(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))}}(':root{--tenms-ink-950:#0f172a;--tenms-border-soft:rgba(148,163,184,.2);--tenms-border-strong:rgba(148,163,184,.34);--tenms-surface-glass:hsla(0,0%,100%,.72);--tenms-shadow:0 12px 28px rgba(15,23,42,.12),0 2px 8px rgba(15,23,42,.08);--tenms-shadow-hover:0 18px 38px rgba(15,23,42,.16),0 8px 16px rgba(15,23,42,.1);--tenms-shadow-active:0 8px 18px rgba(15,23,42,.12);--tenms-radius:16px;--tenms-focus-ring:0 0 0 4px rgba(34,197,94,.18);--tenms-transition:transform 0.18s ease,box-shadow 0.18s ease,background-color 0.18s ease,border-color 0.18s ease,color 0.18s ease,opacity 0.18s ease}.tenms-login-btn{--tenms-logo-h:14px;-webkit-font-smoothing:antialiased;align-items:center;border:1px solid transparent;border-radius:var(--tenms-radius);box-shadow:var(--tenms-shadow);cursor:pointer;display:inline-flex;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;font-weight:600;gap:12px;isolation:isolate;justify-content:center;letter-spacing:-.01em;overflow:hidden;position:relative;text-decoration:none;transition:var(--tenms-transition);user-select:none;-webkit-user-select:none;white-space:nowrap}.tenms-login-btn:before{background:linear-gradient(135deg,hsla(0,0%,100%,.24),hsla(0,0%,100%,0) 56%);content:"";inset:0;opacity:.72;pointer-events:none;position:absolute;transition:opacity .18s ease;z-index:0}.tenms-login-btn>span{position:relative;z-index:1}.tenms-login-btn:hover{box-shadow:var(--tenms-shadow-hover);transform:translateY(-1px)}.tenms-login-btn:hover:before{opacity:.95}.tenms-login-btn:active{box-shadow:var(--tenms-shadow-active);transform:translateY(0) scale(.985)}.tenms-login-btn:focus-visible{box-shadow:var(--tenms-shadow-hover),var(--tenms-focus-ring);outline:none}.tenms-login-btn:disabled{cursor:not-allowed}.tenms-login-btn--small{--tenms-logo-h:12px;font-size:13px;gap:10px;line-height:1;min-height:40px;padding:10px 16px}.tenms-login-btn--medium{font-size:14px;gap:11px;line-height:1.1;min-height:46px;padding:12px 18px}.tenms-login-btn--large{--tenms-logo-h:15px;font-size:15px;gap:12px;line-height:1.1;min-height:52px;padding:14px 22px}.tenms-login-btn--dark.tenms-login-btn--large{--tenms-logo-h:16px}.tenms-login-btn--dark{background:linear-gradient(180deg,#172033,#0f172a);border-color:hsla(0,0%,100%,.08);color:#fff}.tenms-login-btn--dark:hover{background:linear-gradient(180deg,#1f2937,#0f172a)}.tenms-login-btn--light{background:linear-gradient(180deg,hsla(0,0%,100%,.98),rgba(248,250,252,.96));border-color:var(--tenms-border-soft);color:var(--tenms-ink-950)}.tenms-login-btn--light:hover{background:linear-gradient(180deg,#fff,rgba(241,245,249,.98));border-color:rgba(148,163,184,.28)}.tenms-login-btn--outline{backdrop-filter:blur(12px);background:var(--tenms-surface-glass);border-color:var(--tenms-border-strong);color:var(--tenms-ink-950)}.tenms-login-btn--outline:hover{background:rgba(240,253,244,.86);border-color:rgba(34,197,94,.42);color:#0f172a}.tenms-login-btn__logo{align-items:center;display:inline-flex;flex-shrink:0;justify-content:center}.tenms-login-btn:not(.tenms-login-btn--dark) .tenms-login-btn__logo{background:linear-gradient(180deg,rgba(23,32,51,.98),rgba(15,23,42,.94));border:1px solid hsla(0,0%,100%,.08);border-radius:8px;box-shadow:inset 0 1px 0 hsla(0,0%,100%,.08),0 4px 10px rgba(15,23,42,.12);padding:3px 4px}.tenms-login-btn--small:not(.tenms-login-btn--dark) .tenms-login-btn__logo{border-radius:6px;padding:2px 3px}.tenms-login-btn--large:not(.tenms-login-btn--dark) .tenms-login-btn__logo{padding:3px 5px}.tenms-login-btn--dark .tenms-login-btn__logo{background:transparent;border:none;box-shadow:none;padding:0 2px 0 0}.tenms-login-btn__label{align-items:center;display:inline-flex}.tenms-login-btn__logo svg{display:block;height:var(--tenms-logo-h);width:auto}.tenms-login-btn--loading{opacity:.76;pointer-events:none}.tenms-login-btn__spinner{animation:tenms-spin .72s linear infinite;border:2px solid;border-radius:999px;border-top:2px solid transparent;height:18px;width:18px}@keyframes tenms-spin{to{transform:rotate(1turn)}}');const E='<svg viewBox="0 0 35 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">\n <g clip-path="url(#tenms-logo-clip)">\n <path d="M25.2166 18.6611L34.4336 9.44259C33.4258 4.52089 29.5119 0.657436 24.5531 0.0370282C24.4596 0.0251544 24.3646 0.0147648 24.2711 0.00585938V4.5758C26.4188 4.93944 28.1999 6.32868 29.2388 8.24037L22.0195 15.4582L25.2166 18.6611Z" fill="#EB2026"/>\n <path d="M8.63228 32H4.09944V4.53284H0V0H8.63228V32Z" fill="white"/>\n <path d="M30.1299 16.9588L30.1106 19.9718V19.9866C30.1106 24.1083 26.9729 27.4612 23.1169 27.4612C19.2609 27.4612 16.1262 24.1113 16.1232 19.994L16.1781 11.9718V11.9569C16.1781 8.29385 18.6657 5.17994 22.0126 4.58476V0.0103635L21.7158 0.0445008C15.9703 0.79849 11.6423 5.91611 11.6379 11.9495L11.5859 19.9718V19.9866C11.5859 26.6078 16.757 31.994 23.1124 31.994C29.4679 31.994 34.6345 26.6122 34.6375 19.994L34.688 12.3963L30.1299 16.9588Z" fill="white"/>\n </g>\n <defs>\n <clipPath id="tenms-logo-clip">\n <rect width="35" height="32" fill="white"/>\n </clipPath>\n </defs>\n</svg>';function $(){return`<span class="tenms-login-btn__logo">${E}</span>`}var P;const T="Login with 10MinuteSchool",z=null!==(P=globalThis.HTMLElement)&&void 0!==P?P:class{};class R extends z{constructor(){super(...arguments),this.auth=null,this.loading=!1}static get observedAttributes(){return["client-id","redirect-uri","scope","theme","size","text"]}connectedCallback(){this.render()}attributeChangedCallback(){this.loading||this.render()}render(){var e;const t=M(this.getAttribute("theme")),n=B(this.getAttribute("size")),o=(null===(e=this.getAttribute("text"))||void 0===e?void 0:e.trim())||T;var i;this.innerHTML=`\n <button class="${j((i={loading:this.loading,text:o,theme:t,size:n}).theme,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>':$()}\n <span class="tenms-login-btn__label">${N(i.text)}</span>\n </button>\n `;const r=this.querySelector("button");r&&r.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(O(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 L(){"undefined"==typeof window||"undefined"==typeof customElements||customElements.get("tenms-login-button")||customElements.define("tenms-login-button",R)}function A(e,t){e.className=j(t.theme,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">${N(t.text)}</span>`:`${$()}<span class="tenms-login-btn__label">${N(t.text)}</span>`}function j(e,t,n){return["tenms-login-btn",`tenms-login-btn--${e}`,`tenms-login-btn--${t}`,n?"tenms-login-btn--loading":""].filter(Boolean).join(" ")}function M(e){return"light"===e||"outline"===e?e:"dark"}function B(e){return"small"===e||"medium"===e?e:"large"}function N(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function O(e){return e instanceof Error?e:new Error(String(e))}const V="Login with 10MinuteSchool",W="dark",q="large";function H(e){return"light"===e||"outline"===e?e:W}function F(e){return"small"===e||"medium"===e?e:q}L(),exports.LoginButton=function(e){const{clientId:n,redirectUri:o,scopes:i,theme:r=W,size:s=q,text:a=V,onSuccess:l,onError:c,className:d=""}=e,[h,g]=t.useState(!1),u=t.useRef(l),p=t.useRef(c);t.useEffect(()=>{u.current=l},[l]),t.useEffect(()=>{p.current=c},[c]);const f=Array.isArray(i)?i.join("\0"):"",m=t.useMemo(()=>new x({clientId:n,redirectUri:o,scopes:i}),[n,o,f]),b=t.useCallback(async()=>{var e,t;g(!0);try{const t=await m.loginWithPopup();null===(e=u.current)||void 0===e||e.call(u,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)}},[m]),w=["tenms-login-btn",`tenms-login-btn--${H(r)}`,`tenms-login-btn--${F(s)}`,h?"tenms-login-btn--loading":"",d].filter(Boolean).join(" ");return t.createElement("button",{className:w,type:"button",onClick:()=>{b()},disabled:h,"aria-busy":h},h?t.createElement("span",{className:"tenms-login-btn__spinner","aria-hidden":"true"}):t.createElement("span",{className:"tenms-login-btn__logo",dangerouslySetInnerHTML:{__html:E}}),t.createElement("span",{className:"tenms-login-btn__label"},a))},exports.TenMSAuth=x,exports.TenMSAuthError=n,exports.TenMSLoginButtonElement=R,exports.VERSION="0.1.0",exports.createLogger=p,exports.generateCodeChallenge=r,exports.generateCodeVerifier=i,exports.generateState=s,exports.openPopup=l,exports.registerLoginButton=L,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=M(t.theme),a=B(t.size),l=(null===(o=t.text)||void 0===o?void 0:o.trim())||T,c=document.createElement("button");A(c,{loading:!1,size:a,text:l,theme:s}),c.addEventListener("click",async()=>{var e,n;if(!c.classList.contains("tenms-login-btn--loading")){A(c,{loading:!0,size:a,text:l,theme:s});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,O(e))}finally{A(c,{loading:!1,size:a,text:l,theme:s})}}}),i.replaceChildren(c)},exports.truncate=b,exports.waitForPopupRedirect=c;
|
|
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://local-api.10minuteschool.net/auth",k="http://local.10minuteschool.net/auth/login",y=["profile"],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.2.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;
|
|
2
2
|
//# sourceMappingURL=tenms-auth.cjs.js.map
|