@namphuongtechnologi/sso-client 0.0.0-stage → 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.
Files changed (43) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE +4 -0
  3. package/README.md +423 -2
  4. package/dist/angular/index.cjs +87 -0
  5. package/dist/angular/index.cjs.map +1 -0
  6. package/dist/angular/index.d.cts +51 -0
  7. package/dist/angular/index.d.ts +51 -0
  8. package/dist/angular/index.js +81 -0
  9. package/dist/angular/index.js.map +1 -0
  10. package/dist/chunk-EIG7HJOU.js +1510 -0
  11. package/dist/chunk-EIG7HJOU.js.map +1 -0
  12. package/dist/chunk-R6N5M4S6.cjs +1549 -0
  13. package/dist/chunk-R6N5M4S6.cjs.map +1 -0
  14. package/dist/iife/sso-client.min.js +135 -0
  15. package/dist/iife/sso-client.min.js.map +1 -0
  16. package/dist/index.cjs +156 -0
  17. package/dist/index.cjs.map +1 -0
  18. package/dist/index.d.cts +264 -0
  19. package/dist/index.d.ts +264 -0
  20. package/dist/index.js +3 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/react/index.cjs +92 -0
  23. package/dist/react/index.cjs.map +1 -0
  24. package/dist/react/index.d.cts +52 -0
  25. package/dist/react/index.d.ts +52 -0
  26. package/dist/react/index.js +86 -0
  27. package/dist/react/index.js.map +1 -0
  28. package/dist/types-BK-kQIAX.d.cts +131 -0
  29. package/dist/types-BK-kQIAX.d.ts +131 -0
  30. package/dist/vanilla/index.cjs +132 -0
  31. package/dist/vanilla/index.cjs.map +1 -0
  32. package/dist/vanilla/index.d.cts +17 -0
  33. package/dist/vanilla/index.d.ts +17 -0
  34. package/dist/vanilla/index.js +129 -0
  35. package/dist/vanilla/index.js.map +1 -0
  36. package/dist/vue/index.cjs +77 -0
  37. package/dist/vue/index.cjs.map +1 -0
  38. package/dist/vue/index.d.cts +43 -0
  39. package/dist/vue/index.d.ts +43 -0
  40. package/dist/vue/index.js +72 -0
  41. package/dist/vue/index.js.map +1 -0
  42. package/docs/PUBLISHING.md +280 -0
  43. package/package.json +108 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,33 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ### Added
6
+
7
+ - Login beacon `/sso-login.html`: Center iframe file này sau khi hub login; xoá logout marker và phát global login key để tab web ngoài thử silent SSO ngay.
8
+ - `GLOBAL_LOGIN_KEY` (`sso:login-at`): cross-tab login listener nghe cả key scoped và global.
9
+ - Config `hubLoginHint`: hiện banner “Đã đăng nhập ở SSO Center — bấm để tiếp tục” khi beacon login tới nhưng silent SSO thất bại.
10
+ - Focus/visibility reconciliation: nếu có logout marker mới hơn login marker, tab tự xoá session khi được focus (không cần F5).
11
+ - Hướng dẫn publish: `docs/PUBLISHING.md`.
12
+
13
+ ### Fixed
14
+
15
+ - Tab mới sau logout không còn silent-login lại khi còn logout marker.
16
+ - Race giữa token refresh và logout: không áp dụng token cũ sau khi có logout marker.
17
+ - Center logout giờ xoá session các tab partner ngay cả khi storage event bị lỡ.
18
+
19
+ ## 1.0.0 — 2026-11-27
20
+
21
+ ### Added
22
+
23
+ - Lõi framework-agnostic `createSso()`: config validate, hub URL builder, safe returnUrl, MSAL engine, silent chain (cache → `acquireTokenSilent` → `ssoSilent` → `prompt=none` một lần/tab), session mapping + refresh, fetch wrapper với 401 single-flight.
24
+ - Adapter React: `SsoProvider`, `useSso`, `RequireSso`.
25
+ - Adapter Vue 3: plugin, composable, router guard.
26
+ - Adapter Angular: `provideSso`, `SsoService`, `ssoGuard`, `ssoInterceptor`, `SsoModule`.
27
+ - Adapter HTML/JS thuần: IIFE `sso-client.min.js`, `data-sso` auto-binding, `window` events.
28
+ - Deep link restore sau `prompt=none`; cross-tab logout broadcast.
29
+ - Lưu email gần nhất làm `login_hint` (localStorage) để tab mới `prompt=none`/`ssoSilent` chọn đúng tài khoản khi browser có nhiều identity; giữ lại sau logout để lần login sau preselect đúng account.
30
+ - `login()` truyền `loginHint` sang Center (`/auth/login?returnUrl=...&loginHint=...`).
31
+ - Cross-origin logout: tab nghe key global `sso:logout-at`; Center iframe `/sso-logout.html` của partner khi logout.
32
+ - `prompt=none` thất bại → quay lại đúng trang đã lưu thay vì kẹt ở `redirectUri`.
33
+ - Unit test cho config, hub, hub-params, prompt-none, session, http, storage.
package/LICENSE ADDED
@@ -0,0 +1,4 @@
1
+ Copyright (c) 2026 VIAGS.
2
+
3
+ Internal, proprietary software. Not for public distribution.
4
+ Unauthorized copying, modification, or distribution is prohibited.
package/README.md CHANGED
@@ -1,3 +1,424 @@
1
- # Temporary Holding Version
1
+ # @namphuongtechnologi/sso-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Thư viện SSO cho **web ngoài** tích hợp với **SSO Center** (Microsoft Entra ID làm identity hub).
4
+
5
+ - Lõi framework-agnostic, adapter cho **React / Vue / Angular**, kèm ví dụ **Svelte** và **HTML thuần**.
6
+ - Không truyền token qua URL. Không cho phép interactive login ngoài SSO Center.
7
+ - Tự xử lý 4 điểm: silent SSO, login hub, logout hub, API 401.
8
+ - Đồng bộ login/logout giữa các tab cùng origin và với hub qua beacon tĩnh.
9
+
10
+ > Publish package: xem [`docs/PUBLISHING.md`](./docs/PUBLISHING.md).
11
+
12
+ ---
13
+
14
+ ## 0. Quick start (5 phút)
15
+
16
+ ```bash
17
+ # Trong app web ngoài
18
+ npm i @namphuongtechnologi/sso-client @azure/msal-browser
19
+ ```
20
+
21
+ ```ts
22
+ // src/sso.ts
23
+ import { createSso } from '@namphuongtechnologi/sso-client';
24
+
25
+ export const sso = createSso({
26
+ clientId: '<app-registration-client-id>',
27
+ authority: 'https://login.microsoftonline.com/<tenant-id>',
28
+ scopes: ['openid', 'profile', 'email', 'offline_access', 'User.Read'],
29
+ centerOrigin: 'https://center.example.com',
30
+ redirectUri: `${window.location.origin}/`,
31
+ });
32
+
33
+ await sso.init();
34
+ ```
35
+
36
+ Sau đó render UI theo trạng thái `sso.getStatus()` / `sso.getSession()`, dùng `sso.login()` và `sso.logout()`.
37
+
38
+ Checklist tối thiểu:
39
+
40
+ 1. App Registration đã có **Redirect URI SPA** đúng `redirectUri`.
41
+ 2. `centerOrigin` là origin của SSO Center (không có path).
42
+ 3. Origin của web ngoài đã được allowlist ở Center / Sys App (`SupportsSso`).
43
+ 4. Có file `/sso-logout.html` và `/sso-login.html` ở origin web ngoài (mục 5).
44
+ 5. Đã admin consent scopes.
45
+
46
+ ---
47
+
48
+ ## 1. Yêu cầu
49
+
50
+ | Thành phần | Ghi chú |
51
+ |---|---|
52
+ | Web ngoài | SPA (React/Vue/Angular/Svelte/HTML thuần…) chạy HTTPS (localhost HTTP được) |
53
+ | SSO Center | Cùng tenant Entra ID, là nơi duy nhất thực hiện login/logout |
54
+ | App Registration | Riêng cho từng web ngoài, nền tảng **Single-page application** |
55
+ | Scopes tối thiểu | `openid profile email offline_access User.Read` |
56
+ | Trình duyệt | Cho phép third-party iframe/cookie tới `login.microsoftonline.com` để silent SSO hoạt động |
57
+
58
+ ---
59
+
60
+ ## 2. Cấu hình App Registration (Azure Portal)
61
+
62
+ 1. **Microsoft Entra admin center → App registrations → New registration**.
63
+ - Name: `SSO — <tên web ngoài>`
64
+ - Supported account types: cùng tenant với SSO Center.
65
+ 2. **Authentication → Add a platform → Single-page application**.
66
+ - Redirect URI: đúng giá trị `redirectUri` sẽ dùng, ví dụ:
67
+ - `https://partner.example.com/`
68
+ - `http://localhost:3005/` (dev)
69
+ - Bật **Access tokens** và **ID tokens** nếu được hỏi.
70
+ 3. **API permissions** → thêm Microsoft Graph delegated:
71
+ - `openid`, `profile`, `email`, `offline_access`, `User.Read`
72
+ - Bấm **Grant admin consent**.
73
+ 4. (Khuyến nghị) **Token configuration** không cần thêm gì cho luồng cơ bản.
74
+ 5. Ở SSO Center:
75
+ - Thêm origin web ngoài vào allowlist (`VITE_SSO_ALLOWED_RETURN_ORIGINS` hoặc Sys App).
76
+ - Bật `SupportsSso` cho Sys App tương ứng để Center iframe được beacon login/logout.
77
+
78
+ > `redirectUri` phải khớp **tuyệt đối**, kể cả dấu `/` cuối. Sai sẽ gặp `AADSTS50011`.
79
+
80
+ ---
81
+
82
+ ## 3. Cài đặt
83
+
84
+ ### 3.1 Từ registry nội bộ / npm
85
+
86
+ ```bash
87
+ npm config set @namphuongtechnologi:registry https://<registry>/npm/registry/
88
+ npm install @namphuongtechnologi/sso-client @azure/msal-browser
89
+ ```
90
+
91
+ `@azure/msal-browser` là dependency bắt buộc của thư viện. Các peer React/Vue/Angular là optional — chỉ cần khi dùng adapter tương ứng.
92
+
93
+ ### 3.2 Từ thư mục local (dev)
94
+
95
+ ```json
96
+ {
97
+ "dependencies": {
98
+ "@namphuongtechnologi/sso-client": "file:../Viags-Web/shared/sso-client"
99
+ }
100
+ }
101
+ ```
102
+
103
+ Sau khi sửa thư viện: `npm run build:sso-client` rồi restart app (Vite có thể cần xoá cache `.vite`).
104
+
105
+ ### 3.3 HTML thuần (IIFE)
106
+
107
+ ```html
108
+ <script src="https://<center>/sso/v1/sso-client.min.js" crossorigin="anonymous"></script>
109
+ <script>
110
+ window.SsoConfig = {
111
+ clientId: '<client-id>',
112
+ authority: 'https://login.microsoftonline.com/<tenant-id>',
113
+ scopes: ['openid', 'profile', 'email', 'offline_access', 'User.Read'],
114
+ centerOrigin: 'https://center.example.com',
115
+ };
116
+ </script>
117
+
118
+ <button data-sso="login">Đăng nhập</button>
119
+ <button data-sso="logout">Đăng xuất</button>
120
+ <span data-sso="user"></span>
121
+ ```
122
+
123
+ Không cần viết JS: `SsoConfig` + `data-sso` tự bind khi DOM ready.
124
+
125
+ ---
126
+
127
+ ## 4. Cấu hình
128
+
129
+ ```ts
130
+ import { createSso } from '@namphuongtechnologi/sso-client';
131
+
132
+ export const sso = createSso({
133
+ clientId: '...',
134
+ authority: 'https://login.microsoftonline.com/<tenant-id>',
135
+ scopes: ['openid', 'profile', 'email', 'offline_access', 'User.Read'],
136
+ centerOrigin: 'https://center.example.com',
137
+ redirectUri: `${window.location.origin}/`,
138
+ cacheLocation: 'localStorage',
139
+ hubLoginHint: true,
140
+ });
141
+ ```
142
+
143
+ | Trường | Bắt buộc | Mặc định | Mô tả |
144
+ |---|---|---|---|
145
+ | `clientId` | ✅ | — | App Registration riêng của web |
146
+ | `authority` | ✅ | — | `https://login.microsoftonline.com/{tenant}` |
147
+ | `scopes` | ✅ | scopes tối thiểu | Không dùng bộ Graph đầy đủ của Center |
148
+ | `centerOrigin` | ✅ | — | Chỉ origin, không path/query/hash |
149
+ | `redirectUri` | | `${origin}/` | Phải khớp Redirect URI SPA |
150
+ | `postLogoutRedirectUri` | | `redirectUri` | |
151
+ | `cacheLocation` | | `sessionStorage` | Dùng `localStorage` nếu muốn chia sẻ phiên giữa các tab cùng origin |
152
+ | `autoSilent` | | `true` | Bật chuỗi silent SSO |
153
+ | `promptNoneOncePerTab` | | `true` | Chống `AADSTS50196` |
154
+ | `promptNoneOnFirstVisit` | | `false` | Chỉ bật khi muốn silent ngay cả khi không từ Center |
155
+ | `allowIframe` | | `false` | Không boot app trong iframe |
156
+ | `autoFallbackToHubLogin` | | `false` | Tự đá sang Center khi silent fail (cooldown 60s) |
157
+ | `treat403AsUnauthorized` | | `false` | Coi 403 là hết phiên |
158
+ | `storagePrefix` | | `sso.<8 ký tự clientId>` | Tránh đụng key nếu 1 origin nhiều app |
159
+ | `hubLoginHint` | | `false` | Hiện banner “Đã đăng nhập ở Center — bấm để tiếp tục” khi beacon login tới nhưng silent fail |
160
+ | `getAccessToken` | | — | Token nghiệp vụ (BE exchange) thay cho MS token |
161
+ | `onUnauthorized` | | — | Tự xử lý 401 thay vì redirect |
162
+ | `onSessionChange` | | — | Đồng bộ session ra store ngoài |
163
+ | `debug` | | `false` | Log chẩn đoán (không log token) |
164
+
165
+ ---
166
+
167
+ ## 5. Beacon tĩnh bắt buộc
168
+
169
+ Thêm 2 file vào thư mục public/static của web ngoài (deploy cùng origin).
170
+
171
+ ### 5.1 `/sso-logout.html`
172
+
173
+ Center iframe file này khi hub logout → tab web ngoài tự xoá phiên.
174
+
175
+ ```html
176
+ <!doctype html>
177
+ <html lang="vi">
178
+ <head><meta charset="UTF-8" /><title>SSO logout</title></head>
179
+ <body>
180
+ <script>
181
+ try {
182
+ localStorage.setItem('sso:logout-at', String(Date.now()));
183
+ } catch (error) {}
184
+ </script>
185
+ </body>
186
+ </html>
187
+ ```
188
+
189
+ ### 5.2 `/sso-login.html`
190
+
191
+ Center iframe file này khi hub login → tab web ngoài xoá marker logout cũ và thử silent SSO ngay.
192
+
193
+ ```html
194
+ <!doctype html>
195
+ <html lang="vi">
196
+ <head><meta charset="UTF-8" /><title>SSO login</title></head>
197
+ <body>
198
+ <script>
199
+ try {
200
+ localStorage.removeItem('sso:logout-at');
201
+ localStorage.setItem('sso:login-at', String(Date.now()));
202
+ } catch (error) {}
203
+ </script>
204
+ </body>
205
+ </html>
206
+ ```
207
+
208
+ > Không có 2 file này: logout/login ở Center sẽ không đồng bộ tức thời sang tab web ngoài (phải F5 hoặc chờ token hết hạn).
209
+
210
+ ---
211
+
212
+ ## 6. Tích hợp theo framework
213
+
214
+ ### 6.1 React
215
+
216
+ ```tsx
217
+ import { SsoProvider, SsoBootGate, RequireSso, useSso } from '@namphuongtechnologi/sso-client/react';
218
+ import { ssoConfig } from './sso-config';
219
+
220
+ <SsoProvider config={ssoConfig}>
221
+ <SsoBootGate loadingFallback={<Spinner />}>
222
+ <RequireSso fallback={<LoginPage />}>
223
+ <App />
224
+ </RequireSso>
225
+ </SsoBootGate>
226
+ </SsoProvider>;
227
+ ```
228
+
229
+ ```tsx
230
+ function Header() {
231
+ const { session, logout, fetch } = useSso();
232
+ return <button onClick={() => logout()}>{session?.account.name}</button>;
233
+ // fetch('/api/orders') tự gắn Bearer + xử lý 401
234
+ }
235
+ ```
236
+
237
+ ### 6.2 Vue 3
238
+
239
+ ```ts
240
+ import { createSso } from '@namphuongtechnologi/sso-client';
241
+ import { createSsoPlugin, createSsoGuard } from '@namphuongtechnologi/sso-client/vue';
242
+
243
+ const sso = createSso(ssoConfig);
244
+ await sso.init(); // trước khi mount để guard thấy session
245
+
246
+ app.use(createSsoPlugin({ config: ssoConfig, client: sso }));
247
+ router.beforeEach(createSsoGuard({ publicRoutes: ['/login'] }));
248
+ ```
249
+
250
+ ```vue
251
+ <script setup lang="ts">
252
+ import { useSso } from '@namphuongtechnologi/sso-client/vue';
253
+ const { session, isAuthenticated, login, logout } = useSso();
254
+ </script>
255
+ ```
256
+
257
+ ### 6.3 Angular (standalone)
258
+
259
+ ```ts
260
+ bootstrapApplication(AppComponent, {
261
+ providers: [
262
+ provideSso(ssoConfig),
263
+ provideHttpClient(withInterceptors([ssoInterceptor])),
264
+ provideRouter(routes),
265
+ ],
266
+ });
267
+ ```
268
+
269
+ ```ts
270
+ // app.routes.ts
271
+ export const routes: Routes = [
272
+ { path: 'home', canActivate: [ssoGuard], component: HomeComponent },
273
+ ];
274
+ ```
275
+
276
+ NgModule cũ: `SsoModule.forRoot(ssoConfig)`.
277
+
278
+ ### 6.4 Svelte (custom store)
279
+
280
+ Thư viện chưa có adapter Svelte; dùng core + `readable`:
281
+
282
+ ```ts
283
+ // lib/sso.ts
284
+ import { createSso } from '@namphuongtechnologi/sso-client';
285
+ export const sso = createSso(ssoConfig);
286
+
287
+ // lib/sso-state.ts
288
+ import { readable } from 'svelte/store';
289
+ export const ssoState = readable(
290
+ { status: sso.getStatus(), session: sso.getSession() },
291
+ (set) => {
292
+ set({ status: sso.getStatus(), session: sso.getSession() });
293
+ return sso.subscribe(set);
294
+ },
295
+ );
296
+ ```
297
+
298
+ ```ts
299
+ // main.ts
300
+ await sso.init();
301
+ mount(App, { target: document.getElementById('app')! });
302
+ ```
303
+
304
+ ### 6.5 HTML / JS thuần
305
+
306
+ Xem mục 3.3. Sự kiện trên `window`: `sso:ready`, `sso:login`, `sso:logout`, `sso:change`, `sso:error`.
307
+
308
+ CSS hook:
309
+
310
+ ```css
311
+ [data-sso='anonymous'] [data-sso='logout'] { display: none; }
312
+ [data-sso='authenticated'] [data-sso='login'] { display: none; }
313
+ ```
314
+
315
+ ---
316
+
317
+ ## 7. Hành vi SSO
318
+
319
+ | Điểm | Thư viện làm gì |
320
+ |---|---|
321
+ | A. App start | `init()` → `handleRedirectPromise` (1 lần) → cache/`acquireTokenSilent` → `ssoSilent` (iframe) → `prompt=none` 1 lần/tab |
322
+ | B. Login | `login()` → `{center}/auth/login?returnUrl=<same-origin>&loginHint=...` |
323
+ | C. Logout | `logout()` → xoá local/MSAL cache → `{center}/auth/logout` |
324
+ | D. 401 | `fetch()` gắn Bearer → 401 → xoá local → Center login kèm URL hiện tại |
325
+
326
+ Bổ sung:
327
+
328
+ - **Cross-tab**: tab cùng origin tự đồng bộ login/logout qua `localStorage` event.
329
+ - **Cross-origin (Center → web ngoài)**: Center iframe `/sso-login.html` / `/sso-logout.html` để tab đang mở tự cập nhật.
330
+ - **Durable logout**: sau logout, tab mới không silent-login lại cho tới khi có login mới/hub entry (`?sso=1`) hoặc beacon login.
331
+ - **Focus reconciliation**: khi tab được focus, nếu có logout marker mới hơn login marker → xoá session ngay (không cần F5).
332
+
333
+ ---
334
+
335
+ ## 8. API
336
+
337
+ ```ts
338
+ client.init(): Promise<void>
339
+ client.getStatus(): 'idle' | 'initializing' | 'authenticated' | 'anonymous' | 'redirecting' | 'error'
340
+ client.getSession(): SsoSession | null
341
+ client.getConfig(): ResolvedSsoConfig
342
+ client.getConfigWarnings(): string[]
343
+ client.subscribe(listener): () => void
344
+ client.syncSession(): Promise<void>
345
+
346
+ client.login(returnUrl?, { loginHint? }): void
347
+ client.logout({ returnUrl?, broadcast? }): Promise<void>
348
+ client.establish(options?): Promise<SsoSession | null>
349
+ client.acquireToken({ forceRefresh?, scopes? }): Promise<string | null>
350
+
351
+ client.fetch(input, init?): Promise<Response>
352
+ client.fetchJson<T>(input, init?): Promise<T>
353
+
354
+ client.requireSession(returnUrl?): boolean
355
+ client.handleUnauthorized(status?): Promise<void>
356
+ client.destroy(): void
357
+ ```
358
+
359
+ `fetch` tự gắn `Authorization: Bearer <token>` (trừ khi `skipAuthHeader: true`) và xử lý 401 single-flight.
360
+
361
+ ---
362
+
363
+ ## 9. Checklist kiểm thử
364
+
365
+ ### 9.1 Hai tab cùng app
366
+
367
+ 1. Mở 2 tab app.
368
+ 2. Login tab A → tab B tự `authenticated`.
369
+ 3. Logout tab B → tab A tự `anonymous`.
370
+ 4. Login lại tab A → tab B tự `authenticated`.
371
+ 5. Logout tab A → tab B tự `anonymous`.
372
+
373
+ ### 9.2 Portal ↔ app
374
+
375
+ 1. Login portal → tab app tự login (silent hoặc banner “Đã đăng nhập ở Center”).
376
+ 2. Logout portal → tab app tự logout (nhờ `/sso-logout.html`).
377
+ 3. Login tab app → portal tự login.
378
+ 4. Logout tab app → portal tự logout.
379
+
380
+ Nếu bước 1 không auto: kiểm tra third-party iframe/cookie; bấm banner hoặc F5 — marker đã được beacon xoá nên không phải nhập lại mật khẩu.
381
+
382
+ ---
383
+
384
+ ## 10. Lỗi thường gặp
385
+
386
+ | Hiện tượng | Nguyên nhân / xử lý |
387
+ |---|---|
388
+ | `AADSTS50011` | `redirectUri` không khớp Redirect URI SPA (kể cả `/` cuối) |
389
+ | `consent_required` | Chưa admin consent scopes |
390
+ | Silent luôn fail | Chrome/Safari chặn third-party iframe/cookie → bật cho `login.microsoftonline.com` |
391
+ | `AADSTS50196` | `prompt=none` bị lặp — không tự gọi `loginRedirect` ngoài thư viện |
392
+ | Hub không bounce | Sys App chưa bật `SupportsSso` hoặc origin chưa allowlist |
393
+ | `centerOrigin` invalid | Phải là origin, không có path/query/hash |
394
+ | Logout portal không logout tab app | Thiếu `/sso-logout.html` hoặc app chưa restart với library mới |
395
+ | Tab mới vẫn authenticated sau logout | Còn `sso:logout-at` / marker scoped cũ; xoá key hoặc kiểm tra durable logout |
396
+ | Vào `/?sso=1&loginHint=...` bị 404 | Router phải so khớp pathname, bỏ qua query string |
397
+
398
+ ---
399
+
400
+ ## 11. Bảo mật
401
+
402
+ - Không có token trên URL; token chỉ nằm trong MSAL cache (`sessionStorage` mặc định).
403
+ - `returnUrl` chỉ chấp nhận absolute **cùng origin**; fallback `${origin}/`.
404
+ - Không log token: logger redact JWT và `Authorization`.
405
+ - Email đăng nhập gần nhất được lưu làm `login_hint` (localStorage) để tab mới chọn đúng account; không phải token.
406
+ - Không interactive login/logout ngoài SSO Center.
407
+ - Không retry `prompt=none` trong cùng tab.
408
+ - Dùng SRI khi nhúng IIFE.
409
+
410
+ ---
411
+
412
+ ## 12. Phát triển thư viện
413
+
414
+ ```bash
415
+ npm install
416
+ npm run typecheck
417
+ npm test
418
+ npm run build # dist ESM/CJS/IIFE
419
+ npm run size
420
+ ```
421
+
422
+ Bundle IIFE được copy vào SSO Center bằng `scripts/copy-sso-client-dist.mjs` ở root monorepo.
423
+
424
+ Ví dụ tích hợp: `examples/vanilla/`. Playground trong monorepo: React/Vue/vanilla, Svelte, Angular và 12 framework khác.
@@ -0,0 +1,87 @@
1
+ 'use strict';
2
+
3
+ var chunkR6N5M4S6_cjs = require('../chunk-R6N5M4S6.cjs');
4
+ var core = require('@angular/core');
5
+ var rxjs = require('rxjs');
6
+
7
+ // src/angular/service.ts
8
+ var SsoService = class {
9
+ constructor(client) {
10
+ this.client = client;
11
+ this.getStatus = () => this.client.getStatus();
12
+ this.getSession = () => this.client.getSession();
13
+ this.getConfigWarnings = () => this.client.getConfigWarnings();
14
+ this.subscribe = (listener) => this.client.subscribe(listener);
15
+ this.login = (returnUrl, options) => this.client.login(returnUrl, options);
16
+ this.logout = (options) => this.client.logout(options);
17
+ this.requireSession = (returnUrl) => this.client.requireSession(returnUrl);
18
+ this.acquireToken = (options) => this.client.acquireToken(options);
19
+ this.fetch = (input, init) => this.client.fetch(input, init);
20
+ this.fetchJson = (input, init) => this.client.fetchJson(input, init);
21
+ this.handleUnauthorized = (status = 401) => this.client.handleUnauthorized(status);
22
+ }
23
+ };
24
+
25
+ // src/angular/provide.ts
26
+ var SSO_CLIENT = new core.InjectionToken(
27
+ "SSO_CLIENT"
28
+ );
29
+ function provideSso(config) {
30
+ return core.makeEnvironmentProviders([
31
+ {
32
+ provide: SSO_CLIENT,
33
+ useFactory: () => chunkR6N5M4S6_cjs.createSso(config)
34
+ },
35
+ {
36
+ provide: core.APP_INITIALIZER,
37
+ useFactory: (client) => () => client.init(),
38
+ deps: [SSO_CLIENT],
39
+ multi: true
40
+ },
41
+ {
42
+ provide: SsoService,
43
+ useFactory: (client) => new SsoService(client),
44
+ deps: [SSO_CLIENT]
45
+ }
46
+ ]);
47
+ }
48
+ var ssoGuard = (_route, state) => {
49
+ const sso = core.inject(SsoService);
50
+ if (sso.getStatus() === "authenticated") return true;
51
+ const origin = typeof window !== "undefined" ? window.location.origin : "";
52
+ sso.login(origin ? `${origin}${state.url}` : state.url);
53
+ return false;
54
+ };
55
+ var ssoInterceptor = (req, next) => {
56
+ const sso = core.inject(SsoService);
57
+ const token = sso.getSession()?.accessToken;
58
+ const request = token && !req.headers.has("Authorization") ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
59
+ return next(request).pipe(
60
+ rxjs.catchError((error) => {
61
+ const status = error?.status;
62
+ if (status === 401) {
63
+ void sso.handleUnauthorized(status);
64
+ }
65
+ return rxjs.throwError(() => error);
66
+ })
67
+ );
68
+ };
69
+ exports.SsoModule = class SsoModule {
70
+ static forRoot(config) {
71
+ return {
72
+ ngModule: exports.SsoModule,
73
+ providers: [provideSso(config)]
74
+ };
75
+ }
76
+ };
77
+ exports.SsoModule = chunkR6N5M4S6_cjs.__decorateClass([
78
+ core.NgModule({})
79
+ ], exports.SsoModule);
80
+
81
+ exports.SSO_CLIENT = SSO_CLIENT;
82
+ exports.SsoService = SsoService;
83
+ exports.provideSso = provideSso;
84
+ exports.ssoGuard = ssoGuard;
85
+ exports.ssoInterceptor = ssoInterceptor;
86
+ //# sourceMappingURL=index.cjs.map
87
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/angular/service.ts","../../src/angular/provide.ts","../../src/angular/guard.ts","../../src/angular/interceptor.ts","../../src/angular/module.ts"],"names":["InjectionToken","makeEnvironmentProviders","createSso","APP_INITIALIZER","inject","catchError","throwError","SsoModule","__decorateClass","NgModule"],"mappings":";;;;;;;AAQO,IAAM,aAAN,MAAiB;AAAA,EACtB,YAA6B,MAAA,EAAmB;AAAnB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAE7B,IAAA,IAAA,CAAA,SAAA,GAAY,MAAiB,IAAA,CAAK,MAAA,CAAO,SAAA,EAAU;AAEnD,IAAA,IAAA,CAAA,UAAA,GAAa,MAAyB,IAAA,CAAK,MAAA,CAAO,UAAA,EAAW;AAE7D,IAAA,IAAA,CAAA,iBAAA,GAAoB,MAAgB,IAAA,CAAK,MAAA,CAAO,iBAAA,EAAkB;AAElE,IAAA,IAAA,CAAA,SAAA,GAAY,CAAC,QAAA,KACX,IAAA,CAAK,MAAA,CAAO,UAAU,QAAQ,CAAA;AAEhC,IAAA,IAAA,CAAA,KAAA,GAAQ,CACN,SAAA,EACA,OAAA,KACS,KAAK,MAAA,CAAO,KAAA,CAAM,WAAW,OAAO,CAAA;AAE/C,IAAA,IAAA,CAAA,MAAA,GAAS,CAAC,OAAA,KAGW,IAAA,CAAK,MAAA,CAAO,OAAO,OAAO,CAAA;AAE/C,IAAA,IAAA,CAAA,cAAA,GAAiB,CAAC,SAAA,KAChB,IAAA,CAAK,MAAA,CAAO,eAAe,SAAS,CAAA;AAEtC,IAAA,IAAA,CAAA,YAAA,GAAe,CAAC,OAAA,KAGc,IAAA,CAAK,MAAA,CAAO,aAAa,OAAO,CAAA;AAE9D,IAAA,IAAA,CAAA,KAAA,GAAQ,CACN,KAAA,EACA,IAAA,KACsB,KAAK,MAAA,CAAO,KAAA,CAAM,OAAO,IAAI,CAAA;AAErD,IAAA,IAAA,CAAA,SAAA,GAAY,CACV,KAAA,EACA,IAAA,KACe,KAAK,MAAA,CAAO,SAAA,CAAa,OAAO,IAAI,CAAA;AAErD,IAAA,IAAA,CAAA,kBAAA,GAAqB,CAAC,MAAA,GAAS,GAAA,KAC7B,IAAA,CAAK,MAAA,CAAO,mBAAmB,MAAM,CAAA;AAAA,EAxCU;AAyCnD;;;ACxCO,IAAM,aAAa,IAAIA,mBAAA;AAAA,EAC5B;AACF;AAEO,SAAS,WACd,MAAA,EACsB;AACtB,EAAA,OAAOC,6BAAA,CAAyB;AAAA,IAC9B;AAAA,MACE,OAAA,EAAS,UAAA;AAAA,MACT,UAAA,EAAY,MAAMC,2BAAA,CAAU,MAAM;AAAA,KACpC;AAAA,IACA;AAAA,MACE,OAAA,EAASC,oBAAA;AAAA,MACT,UAAA,EAAY,CAAC,MAAA,KAAsB,MAAM,OAAO,IAAA,EAAK;AAAA,MACrD,IAAA,EAAM,CAAC,UAAU,CAAA;AAAA,MACjB,KAAA,EAAO;AAAA,KACT;AAAA,IACA;AAAA,MACE,OAAA,EAAS,UAAA;AAAA,MACT,UAAA,EAAY,CAAC,MAAA,KAAsB,IAAI,WAAW,MAAM,CAAA;AAAA,MACxD,IAAA,EAAM,CAAC,UAAU;AAAA;AACnB,GACD,CAAA;AACH;AC1BO,IAAM,QAAA,GAA0B,CAAC,MAAA,EAAQ,KAAA,KAAU;AACxD,EAAA,MAAM,GAAA,GAAMC,YAAO,UAAU,CAAA;AAC7B,EAAA,IAAI,GAAA,CAAI,SAAA,EAAU,KAAM,eAAA,EAAiB,OAAO,IAAA;AAEhD,EAAA,MAAM,SACJ,OAAO,MAAA,KAAW,WAAA,GAAc,MAAA,CAAO,SAAS,MAAA,GAAS,EAAA;AAC3D,EAAA,GAAA,CAAI,KAAA,CAAM,SAAS,CAAA,EAAG,MAAM,GAAG,KAAA,CAAM,GAAG,CAAA,CAAA,GAAK,KAAA,CAAM,GAAG,CAAA;AACtD,EAAA,OAAO,KAAA;AACT;ACNO,IAAM,cAAA,GAAoC,CAAC,GAAA,EAAK,IAAA,KAAS;AAC9D,EAAA,MAAM,GAAA,GAAMA,YAAO,UAAU,CAAA;AAC7B,EAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,UAAA,EAAW,EAAG,WAAA;AAEhC,EAAA,MAAM,UACJ,KAAA,IAAS,CAAC,IAAI,OAAA,CAAQ,GAAA,CAAI,eAAe,CAAA,GACrC,GAAA,CAAI,MAAM,EAAE,UAAA,EAAY,EAAE,aAAA,EAAe,CAAA,OAAA,EAAU,KAAK,CAAA,CAAA,EAAG,EAAG,CAAA,GAC9D,GAAA;AAEN,EAAA,OAAO,IAAA,CAAK,OAAO,CAAA,CAAE,IAAA;AAAA,IACnBC,eAAA,CAAW,CAAC,KAAA,KAAmB;AAC7B,MAAA,MAAM,SAAU,KAAA,EAAsC,MAAA;AACtD,MAAA,IAAI,WAAW,GAAA,EAAK;AAClB,QAAA,KAAK,GAAA,CAAI,mBAAmB,MAAM,CAAA;AAAA,MACpC;AACA,MAAA,OAAOC,eAAA,CAAW,MAAM,KAAK,CAAA;AAAA,IAC/B,CAAC;AAAA,GACH;AACF;ACnBaC,oBAAN,eAAA,CAAgB;AAAA,EACrB,OAAO,QACL,MAAA,EACgC;AAChC,IAAA,OAAO;AAAA,MACL,QAAA,EAAUA,iBAAA;AAAA,MACV,SAAA,EAAW,CAAC,UAAA,CAAW,MAAM,CAAC;AAAA,KAChC;AAAA,EACF;AACF;AATaA,iBAAA,GAANC,iCAAA,CAAA;AAAA,EADNC,aAAA,CAAS,EAAE;AAAA,CAAA,EACCF,iBAAA,CAAA","file":"index.cjs","sourcesContent":["import type {\n SsoClient,\n SsoFetchOptions,\n SsoSession,\n SsoState,\n SsoStatus,\n} from '../types';\n\nexport class SsoService {\n constructor(private readonly client: SsoClient) {}\n\n getStatus = (): SsoStatus => this.client.getStatus();\n\n getSession = (): SsoSession | null => this.client.getSession();\n\n getConfigWarnings = (): string[] => this.client.getConfigWarnings();\n\n subscribe = (listener: (state: SsoState) => void): (() => void) =>\n this.client.subscribe(listener);\n\n login = (\n returnUrl?: string | null,\n options?: { loginHint?: string | null },\n ): void => this.client.login(returnUrl, options);\n\n logout = (options?: {\n returnUrl?: string | null;\n broadcast?: boolean;\n }): Promise<void> => this.client.logout(options);\n\n requireSession = (returnUrl?: string | null): boolean =>\n this.client.requireSession(returnUrl);\n\n acquireToken = (options?: {\n forceRefresh?: boolean;\n scopes?: string[];\n }): Promise<string | null> => this.client.acquireToken(options);\n\n fetch = (\n input: string,\n init?: SsoFetchOptions,\n ): Promise<Response> => this.client.fetch(input, init);\n\n fetchJson = <T = unknown>(\n input: string,\n init?: SsoFetchOptions,\n ): Promise<T> => this.client.fetchJson<T>(input, init);\n\n handleUnauthorized = (status = 401): Promise<void> =>\n this.client.handleUnauthorized(status);\n}\n","import {\n APP_INITIALIZER,\n InjectionToken,\n makeEnvironmentProviders,\n type EnvironmentProviders,\n} from '@angular/core';\nimport { createSso } from '../core/client';\nimport type { SsoClient, SsoConfig } from '../types';\nimport { SsoService } from './service';\n\nexport const SSO_CLIENT = new InjectionToken<SsoClient>(\n 'SSO_CLIENT',\n);\n\nexport function provideSso(\n config: SsoConfig,\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: SSO_CLIENT,\n useFactory: () => createSso(config),\n },\n {\n provide: APP_INITIALIZER,\n useFactory: (client: SsoClient) => () => client.init(),\n deps: [SSO_CLIENT],\n multi: true,\n },\n {\n provide: SsoService,\n useFactory: (client: SsoClient) => new SsoService(client),\n deps: [SSO_CLIENT],\n },\n ]);\n}\n","import { inject } from '@angular/core';\nimport type { CanActivateFn } from '@angular/router';\nimport { SsoService } from './service';\n\n/**\n * Route guard:\n * { path: 'home', canActivate: [ssoGuard], component: HomeComponent }\n */\nexport const ssoGuard: CanActivateFn = (_route, state) => {\n const sso = inject(SsoService);\n if (sso.getStatus() === 'authenticated') return true;\n\n const origin =\n typeof window !== 'undefined' ? window.location.origin : '';\n sso.login(origin ? `${origin}${state.url}` : state.url);\n return false;\n};\n","import { inject } from '@angular/core';\nimport type { HttpInterceptorFn } from '@angular/common/http';\nimport { catchError, throwError } from 'rxjs';\nimport { SsoService } from './service';\n\n/**\n * Attach the Microsoft bearer token and route 401 to the hub login.\n *\n * provideHttpClient(withInterceptors([ssoInterceptor]))\n */\nexport const ssoInterceptor: HttpInterceptorFn = (req, next) => {\n const sso = inject(SsoService);\n const token = sso.getSession()?.accessToken;\n\n const request =\n token && !req.headers.has('Authorization')\n ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })\n : req;\n\n return next(request).pipe(\n catchError((error: unknown) => {\n const status = (error as { status?: number } | null)?.status;\n if (status === 401) {\n void sso.handleUnauthorized(status);\n }\n return throwError(() => error);\n }),\n );\n};\n","import {\n NgModule,\n type ModuleWithProviders,\n} from '@angular/core';\nimport type { SsoConfig } from '../types';\nimport { provideSso } from './provide';\n\n/** NgModule wrapper for Angular applications that are not standalone-first. */\n@NgModule({})\nexport class SsoModule {\n static forRoot(\n config: SsoConfig,\n ): ModuleWithProviders<SsoModule> {\n return {\n ngModule: SsoModule,\n providers: [provideSso(config)],\n };\n }\n}\n"]}
@@ -0,0 +1,51 @@
1
+ import { InjectionToken, EnvironmentProviders, ModuleWithProviders } from '@angular/core';
2
+ import { S as SsoClient, a as SsoConfig, b as SsoStatus, c as SsoSession, d as SsoState, e as SsoFetchOptions } from '../types-BK-kQIAX.cjs';
3
+ import { CanActivateFn } from '@angular/router';
4
+ import { HttpInterceptorFn } from '@angular/common/http';
5
+
6
+ declare const SSO_CLIENT: InjectionToken<SsoClient>;
7
+ declare function provideSso(config: SsoConfig): EnvironmentProviders;
8
+
9
+ declare class SsoService {
10
+ private readonly client;
11
+ constructor(client: SsoClient);
12
+ getStatus: () => SsoStatus;
13
+ getSession: () => SsoSession | null;
14
+ getConfigWarnings: () => string[];
15
+ subscribe: (listener: (state: SsoState) => void) => (() => void);
16
+ login: (returnUrl?: string | null, options?: {
17
+ loginHint?: string | null;
18
+ }) => void;
19
+ logout: (options?: {
20
+ returnUrl?: string | null;
21
+ broadcast?: boolean;
22
+ }) => Promise<void>;
23
+ requireSession: (returnUrl?: string | null) => boolean;
24
+ acquireToken: (options?: {
25
+ forceRefresh?: boolean;
26
+ scopes?: string[];
27
+ }) => Promise<string | null>;
28
+ fetch: (input: string, init?: SsoFetchOptions) => Promise<Response>;
29
+ fetchJson: <T = unknown>(input: string, init?: SsoFetchOptions) => Promise<T>;
30
+ handleUnauthorized: (status?: number) => Promise<void>;
31
+ }
32
+
33
+ /**
34
+ * Route guard:
35
+ * { path: 'home', canActivate: [ssoGuard], component: HomeComponent }
36
+ */
37
+ declare const ssoGuard: CanActivateFn;
38
+
39
+ /**
40
+ * Attach the Microsoft bearer token and route 401 to the hub login.
41
+ *
42
+ * provideHttpClient(withInterceptors([ssoInterceptor]))
43
+ */
44
+ declare const ssoInterceptor: HttpInterceptorFn;
45
+
46
+ /** NgModule wrapper for Angular applications that are not standalone-first. */
47
+ declare class SsoModule {
48
+ static forRoot(config: SsoConfig): ModuleWithProviders<SsoModule>;
49
+ }
50
+
51
+ export { SSO_CLIENT, SsoModule, SsoService, provideSso, ssoGuard, ssoInterceptor };
@@ -0,0 +1,51 @@
1
+ import { InjectionToken, EnvironmentProviders, ModuleWithProviders } from '@angular/core';
2
+ import { S as SsoClient, a as SsoConfig, b as SsoStatus, c as SsoSession, d as SsoState, e as SsoFetchOptions } from '../types-BK-kQIAX.js';
3
+ import { CanActivateFn } from '@angular/router';
4
+ import { HttpInterceptorFn } from '@angular/common/http';
5
+
6
+ declare const SSO_CLIENT: InjectionToken<SsoClient>;
7
+ declare function provideSso(config: SsoConfig): EnvironmentProviders;
8
+
9
+ declare class SsoService {
10
+ private readonly client;
11
+ constructor(client: SsoClient);
12
+ getStatus: () => SsoStatus;
13
+ getSession: () => SsoSession | null;
14
+ getConfigWarnings: () => string[];
15
+ subscribe: (listener: (state: SsoState) => void) => (() => void);
16
+ login: (returnUrl?: string | null, options?: {
17
+ loginHint?: string | null;
18
+ }) => void;
19
+ logout: (options?: {
20
+ returnUrl?: string | null;
21
+ broadcast?: boolean;
22
+ }) => Promise<void>;
23
+ requireSession: (returnUrl?: string | null) => boolean;
24
+ acquireToken: (options?: {
25
+ forceRefresh?: boolean;
26
+ scopes?: string[];
27
+ }) => Promise<string | null>;
28
+ fetch: (input: string, init?: SsoFetchOptions) => Promise<Response>;
29
+ fetchJson: <T = unknown>(input: string, init?: SsoFetchOptions) => Promise<T>;
30
+ handleUnauthorized: (status?: number) => Promise<void>;
31
+ }
32
+
33
+ /**
34
+ * Route guard:
35
+ * { path: 'home', canActivate: [ssoGuard], component: HomeComponent }
36
+ */
37
+ declare const ssoGuard: CanActivateFn;
38
+
39
+ /**
40
+ * Attach the Microsoft bearer token and route 401 to the hub login.
41
+ *
42
+ * provideHttpClient(withInterceptors([ssoInterceptor]))
43
+ */
44
+ declare const ssoInterceptor: HttpInterceptorFn;
45
+
46
+ /** NgModule wrapper for Angular applications that are not standalone-first. */
47
+ declare class SsoModule {
48
+ static forRoot(config: SsoConfig): ModuleWithProviders<SsoModule>;
49
+ }
50
+
51
+ export { SSO_CLIENT, SsoModule, SsoService, provideSso, ssoGuard, ssoInterceptor };