@biza-gov/sso-login 0.0.0-stage → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,633 @@
1
- # Temporary Holding Version
1
+ # คู่มือ E-Service × IAM-GOV — ทำตามได้เลย
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
+ > อ่านครั้งเดียว ทำตามลำดับ — ครอบคลุมตั้งแต่ติดตั้ง library จนถึง Residence API และ Claim Flow
4
+
5
+ ---
6
+
7
+ ## ก่อนเริ่ม — สิ่งที่ต้องมี
8
+
9
+ | สิ่งที่ต้องมี | รายละเอียด |
10
+ |---|---|
11
+ | Node.js | >= 18 |
12
+ | React | >= 18 |
13
+ | Backend (NestJS) | มี endpoint `/auth/sso-callback` |
14
+ | IAM-GOV credentials | service code + API key (ลงทะเบียนที่ [govcenter.co](https://govcenter.co)) |
15
+
16
+ ---
17
+
18
+ ## ขั้นตอนที่ 1 — ติดตั้ง Library
19
+
20
+ ```bash
21
+ npm install @biza-gov/sso-login
22
+ ```
23
+
24
+ แก้ไข `next.config.ts` เพิ่ม `transpilePackages`:
25
+
26
+ ```typescript
27
+ const nextConfig = {
28
+ transpilePackages: ['@biza-gov/sso-login'],
29
+ };
30
+ export default nextConfig;
31
+ ```
32
+
33
+ ---
34
+
35
+ ## ขั้นตอนที่ 2 — ตั้งค่า Environment Variables
36
+
37
+ ### Frontend (`.env.local`)
38
+
39
+ ```env
40
+ NEXT_PUBLIC_API_URL=https://api.your-domain.com
41
+ NEXT_PUBLIC_IAM_GOV_FRONTEND_URL=https://auth.govcenter.co
42
+ NEXT_PUBLIC_E_SERVICE_CODE=your-service-code
43
+ NEXT_PUBLIC_FRONTEND_URL=https://your-domain.com
44
+ ```
45
+
46
+ ### Backend (`.env`)
47
+
48
+ ```env
49
+ IAM_API_URL=https://api-auth.govcenter.co
50
+ E_SERVICE_CODE=your-service-code
51
+ E_SERVICE_API_KEY=your-api-key # ← ห้ามใส่ฝั่ง frontend เด็ดขาด
52
+ ```
53
+
54
+ > **กฎเหล็ก:** `E_SERVICE_API_KEY` อยู่บน backend เท่านั้น ห้ามใส่ใน `NEXT_PUBLIC_*` หรือ `VITE_*`
55
+
56
+ ---
57
+
58
+ ## ขั้นตอนที่ 3 — สร้าง SSO Config (Frontend)
59
+
60
+ สร้างไฟล์ `lib/sso-config.ts`:
61
+
62
+ ```typescript
63
+ import type { GovSsoConfig } from '@biza-gov/sso-login';
64
+
65
+ export const ssoConfig: GovSsoConfig = {
66
+ iamAuthUrl: process.env.NEXT_PUBLIC_IAM_GOV_FRONTEND_URL || 'https://auth.govcenter.co',
67
+ serviceCode: process.env.NEXT_PUBLIC_E_SERVICE_CODE || 'your-service-code',
68
+ apiBaseUrl: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001',
69
+ callbackUrl: `${process.env.NEXT_PUBLIC_FRONTEND_URL || 'http://localhost:3000'}/auth/callback`,
70
+ };
71
+ ```
72
+
73
+ ---
74
+
75
+ ## ขั้นตอนที่ 4 — Wrap App ด้วย Provider
76
+
77
+ `app/layout.tsx`:
78
+
79
+ ```tsx
80
+ import { GovSsoProvider } from '@biza-gov/sso-login';
81
+ import { ssoConfig } from '@/lib/sso-config';
82
+
83
+ export default function RootLayout({ children }) {
84
+ return (
85
+ <GovSsoProvider config={ssoConfig} theme={{ primaryColor: '#1E7D55' }}>
86
+ {children}
87
+ </GovSsoProvider>
88
+ );
89
+ }
90
+ ```
91
+
92
+ > หลังจาก wrap แล้ว component ข้างในไม่ต้องส่ง `config` ซ้ำ
93
+
94
+ ---
95
+
96
+ ## ขั้นตอนที่ 5 — หน้า Login
97
+
98
+ ### วิธี A: ใช้ Component สำเร็จรูป
99
+
100
+ ```tsx
101
+ // app/login/page.tsx
102
+ import { SsoLoginButton } from '@biza-gov/sso-login';
103
+
104
+ export default function LoginPage() {
105
+ return <SsoLoginButton label="เข้าสู่ระบบด้วย Gov Center" />;
106
+ }
107
+ ```
108
+
109
+ ### วิธี B: ปรับ UI เอง
110
+
111
+ ```tsx
112
+ import { useGovSso } from '@biza-gov/sso-login';
113
+
114
+ export default function LoginPage() {
115
+ const { login } = useGovSso();
116
+ return <button onClick={login} className="my-btn">เข้าสู่ระบบ</button>;
117
+ }
118
+ ```
119
+
120
+ ---
121
+
122
+ ## ขั้นตอนที่ 6 — หน้า Callback (Frontend)
123
+
124
+ ```tsx
125
+ // app/auth/callback/page.tsx
126
+ 'use client';
127
+
128
+ import { SsoCallbackHandler } from '@biza-gov/sso-login';
129
+ import { useRouter } from 'next/navigation';
130
+
131
+ export default function CallbackPage() {
132
+ const router = useRouter();
133
+ return (
134
+ <SsoCallbackHandler
135
+ onSuccess={async (result) => {
136
+ const role = result.user?.role;
137
+ router.push(role === 'ADMIN' ? '/admin/dashboard' : '/home');
138
+ }}
139
+ onError={(err) => {
140
+ console.error(err);
141
+ router.push('/login');
142
+ }}
143
+ />
144
+ );
145
+ }
146
+ ```
147
+
148
+ > Library จัดการ CSRF state, retry (2 ครั้ง), และ error handling ให้อัตโนมัติ
149
+
150
+ ---
151
+
152
+ ## ขั้นตอนที่ 7 — Backend: รับ SSO Callback
153
+
154
+ Backend ต้องมี `POST /auth/sso-callback` ที่:
155
+ 1. รับ `{ code }` จาก frontend
156
+ 2. ส่ง code ไป IAM-GOV เพื่อ verify
157
+ 3. Upsert user และ residence snapshot ลงฐานข้อมูล
158
+ 4. สร้าง JWT session คืนกลับ
159
+
160
+ ```typescript
161
+ // auth.controller.ts
162
+ @Post('sso-callback')
163
+ async ssoCallback(@Body() body: { code: string }, @Res({ passthrough: true }) res: Response) {
164
+ const user = await this.authService.handleSsoCallback(body.code);
165
+ return this.authService.login(user, res);
166
+ }
167
+
168
+ // auth.service.ts
169
+ async handleSsoCallback(code: string) {
170
+ const trimmedCode = code.trim(); // ← trim เสมอ
171
+ const response = await fetch(`${process.env.IAM_API_URL}/e-services/sso/verify-code`, {
172
+ method: 'POST',
173
+ headers: {
174
+ 'Content-Type': 'application/json',
175
+ 'x-api-key': process.env.E_SERVICE_API_KEY,
176
+ },
177
+ body: JSON.stringify({ code: trimmedCode }),
178
+ });
179
+
180
+ if (!response.ok) throw new Error(`IAM verify failed: ${response.status}`);
181
+ const data = await response.json();
182
+
183
+ await this.upsertIamUser(data.user);
184
+ for (const item of data.residences ?? []) {
185
+ await this.upsertResidenceSnapshot(item.addressSnapshot);
186
+ await this.upsertUserResidenceLink({
187
+ iamUserId: data.user.id,
188
+ iamResidenceId: item.addressSnapshot.residenceId,
189
+ iamMembershipId: item.membershipId,
190
+ memberRole: item.role,
191
+ memberStatus: item.status,
192
+ verifiedAt: item.verifiedAt,
193
+ });
194
+ }
195
+
196
+ return this.upsertUser(data.user);
197
+ }
198
+ ```
199
+
200
+ ---
201
+
202
+ ## ขั้นตอนที่ 8 — ตรวจสอบข้อมูล Residence หลัง Login
203
+
204
+ ข้อมูลบ้านของ user จะมาพร้อม verify-code response ในฟิลด์ `residences`
205
+
206
+ ```typescript
207
+ // ตรวจ status ก่อนใช้งานในธุรกรรมจริง
208
+ const canUseForOfficialTransaction =
209
+ item.status === 'VERIFIED' && item.residence.status === 'VERIFIED';
210
+
211
+ const isPending =
212
+ item.status === 'PENDING' || item.residence.status === 'PENDING_REVIEW';
213
+ ```
214
+
215
+ ต้องตรวจ **ทั้งสองค่า** แยกกัน — membership status และ residence status
216
+
217
+ ### Scopes ที่ต้องขอไว้
218
+
219
+ | Scope | เปิดใช้ |
220
+ |---|---|
221
+ | `residence:read` | รับ `residences` ใน verify-code + อ่านรายละเอียดบ้าน |
222
+ | `residence:members:read` | ดูสมาชิกในบ้าน |
223
+ | `residence:claim:create` | ยื่นเพิ่มบ้านใหม่ + upload เอกสาร |
224
+ | `residence:claim:read` | ติดตามสถานะคำขอ |
225
+
226
+ ---
227
+
228
+ ## ขั้นตอนที่ 9 — โครงสร้าง DB ที่ต้องมี
229
+
230
+ ### iam_users
231
+
232
+ ```sql
233
+ create table iam_users (
234
+ iam_user_id text primary key,
235
+ email text,
236
+ name text,
237
+ avatar_url text,
238
+ system_role text,
239
+ last_sso_at timestamptz not null default now(),
240
+ raw_profile jsonb
241
+ );
242
+ ```
243
+
244
+ ### iam_residence_snapshots
245
+
246
+ ```sql
247
+ create table iam_residence_snapshots (
248
+ iam_residence_id text primary key,
249
+ residence_code text,
250
+ formatted_address text,
251
+ house_no text, moo text, soi text, road text, postal_code text,
252
+ village_name text, building_name text, floor text, room_no text,
253
+ province_id int, province_name_th text,
254
+ district_id int, district_name_th text,
255
+ subdistrict_id int, subdistrict_name_th text,
256
+ municipality_id text, municipality_name text,
257
+ latitude double precision, longitude double precision,
258
+ location_accuracy text,
259
+ residence_status text,
260
+ approved_at timestamptz,
261
+ raw_snapshot jsonb,
262
+ synced_at timestamptz not null default now()
263
+ );
264
+ ```
265
+
266
+ ### iam_user_residences
267
+
268
+ ```sql
269
+ create table iam_user_residences (
270
+ iam_user_id text not null,
271
+ iam_residence_id text not null,
272
+ iam_membership_id text not null,
273
+ member_role text,
274
+ member_status text,
275
+ verified_at timestamptz,
276
+ synced_at timestamptz not null default now(),
277
+ primary key (iam_user_id, iam_residence_id)
278
+ );
279
+ ```
280
+
281
+ ---
282
+
283
+ ## ขั้นตอนที่ 10 — Residence Search & Select UI
284
+
285
+ ถ้า e-service ต้องให้ user เลือกบ้านใน UI ของตัวเอง ให้ทำ proxy endpoint ฝั่ง backend ก่อน แล้ว frontend เรียกผ่าน backend เท่านั้น
286
+
287
+ ### Proxy Endpoints (NestJS → IAM-GOV)
288
+
289
+ ```typescript
290
+ @Injectable()
291
+ export class IamGovResidenceClient {
292
+ private readonly apiUrl = this.config.getOrThrow<string>('IAM_API_URL');
293
+ private readonly apiKey = this.config.getOrThrow<string>('E_SERVICE_API_KEY');
294
+
295
+ constructor(private readonly config: ConfigService) {}
296
+
297
+ async searchResidences(params: Record<string, string>) {
298
+ const qs = new URLSearchParams(params).toString();
299
+ const res = await fetch(`${this.apiUrl}/e-services/residences/search?${qs}`, {
300
+ headers: { 'x-api-key': this.apiKey },
301
+ });
302
+ if (!res.ok) throw new Error(`IAM search failed: ${res.status}`);
303
+ return res.json();
304
+ }
305
+ }
306
+
307
+ @Controller('api/residences')
308
+ export class ResidenceProxyController {
309
+ constructor(private readonly iamResidence: IamGovResidenceClient) {}
310
+
311
+ @Get('search')
312
+ search(@Query() query: SearchResidenceDto) {
313
+ return this.iamResidence.searchResidences(query);
314
+ }
315
+ }
316
+ ```
317
+
318
+ ### Endpoint ที่ต้องทำ
319
+
320
+ | E-Service Backend | IAM-GOV Endpoint | Scope ที่ต้องการ |
321
+ |---|---|---|
322
+ | `GET /api/residences/search` | `GET /e-services/residences/search` | — |
323
+ | `GET /api/residences/:id` | `GET /e-services/residences/:id` | `residence:read` |
324
+ | `GET /api/residences/:id/members` | `GET /e-services/residences/:id/members` | `residence:members:read` |
325
+ | `POST /api/residence-claims` | `POST /e-services/residence-claims` | `residence:claim:create` |
326
+ | `POST /api/residence-claims/:id/evidence` | `POST /e-services/residence-claims/:id/evidence` | `residence:claim:create` |
327
+ | `GET /api/residence-claims/:id` | `GET /e-services/residence-claims/:id` | `residence:claim:read` |
328
+
329
+ ### Search Query Parameters
330
+
331
+ | Query | ความหมาย |
332
+ |---|---|
333
+ | `q` | คำค้น เช่น บ้านเลขที่, ถนน, รหัสไปรษณีย์ |
334
+ | `municipalityId` | จำกัดเทศบาล |
335
+ | `provinceId / districtId / subdistrictId` | จำกัดพื้นที่ |
336
+ | `lat / lng / radiusMeters` | ค้นหาจากพิกัด |
337
+ | `limit` | จำนวนผลลัพธ์ |
338
+
339
+ Best practice:
340
+ - ใช้ debounce **300–500ms** ระหว่าง user พิมพ์
341
+ - อย่า search ถ้าคำน้อยกว่า **3 ตัวอักษร** (ยกเว้นมี lat/lng)
342
+ - ถ้า user ปักหมุด map ให้ search ด้วย lat/lng ก่อน แล้วค่อยสร้าง claim ถ้าไม่เจอ
343
+
344
+ ### State Machine สำหรับ UI
345
+
346
+ ```
347
+ Searching → (พบบ้าน) → SelectedResidence → [จบ]
348
+ Searching → (ไม่พบ) → DraftClaim → ClaimSubmitted → WaitingReview
349
+ ↓
350
+ Approved / Merged → SelectedResidence
351
+ Rejected → DraftClaim (แก้ไขและยื่นใหม่)
352
+ ```
353
+
354
+ ```typescript
355
+ // TypeScript state type
356
+ type ResidencePickerState =
357
+ | { step: 'searching' }
358
+ | { step: 'selected'; residenceId: string }
359
+ | { step: 'claim-draft' }
360
+ | { step: 'claim-submitted'; claimId: string };
361
+ ```
362
+
363
+ ---
364
+
365
+ ## ขั้นตอนที่ 11 — Claim Flow (เมื่อ User ไม่พบบ้าน)
366
+
367
+ เลือกได้สองแนวทาง:
368
+
369
+ ### แนวทาง A: Central Flow (ให้ IAM-GOV สร้าง UI ให้)
370
+
371
+ 1. Backend สร้าง Intent:
372
+
373
+ ```http
374
+ POST {IAM_API_URL}/e-services/residence-claim-intents
375
+ Content-Type: application/json
376
+ x-api-key: <E_SERVICE_API_KEY>
377
+
378
+ {
379
+ "expectedIamUserId": "iam-user-id",
380
+ "returnUrl": "https://my-service.govcenter.co/residence/callback",
381
+ "state": "signed-random-state",
382
+ "externalRequestId": "my-service-request-0001"
383
+ }
384
+ ```
385
+
386
+ 2. Frontend redirect user ไปที่ `launchUrl` จาก response
387
+ 3. IAM-GOV redirect กลับมาพร้อม `?code=<resultCode>&state=<state>`
388
+ 4. Backend verify `state` ก่อน แล้ว verify `resultCode`:
389
+
390
+ ```http
391
+ POST {IAM_API_URL}/e-services/residence-claim-results/verify
392
+ x-api-key: <E_SERVICE_API_KEY>
393
+
394
+ { "resultCode": "one-time-result-code" }
395
+ ```
396
+
397
+ ### แนวทาง B: Direct UI Flow (สร้าง UI เอง)
398
+
399
+ **1. Submit Claim:**
400
+
401
+ ```http
402
+ POST /e-services/residence-claims
403
+ x-api-key: <e-service-api-key>
404
+ Content-Type: application/json
405
+
406
+ {
407
+ "externalRequestId": "my-service-req-001",
408
+ "submittedByUserId": "iam-user-id-from-sso",
409
+ "municipalityId": "municipality-id",
410
+ "houseNo": "99/1",
411
+ "moo": "4",
412
+ "provinceId": 46,
413
+ "districtId": 4601,
414
+ "subdistrictId": 460101,
415
+ "latitude": 16.4321,
416
+ "longitude": 103.5012,
417
+ "locationAccuracy": "EXACT"
418
+ }
419
+ ```
420
+
421
+ > `submittedByUserId` ต้องมาจาก session — ห้ามรับจาก browser
422
+
423
+ **2. Upload Evidence** (หลังได้ `claimId`):
424
+
425
+ ```http
426
+ POST /e-services/residence-claims/:claimId/evidence
427
+ x-api-key: <e-service-api-key>
428
+ Content-Type: multipart/form-data
429
+
430
+ file: <PDF/JPEG/PNG/WEBP, max 10MB>
431
+ ```
432
+
433
+ **3. Poll สถานะ:**
434
+
435
+ ```http
436
+ GET /e-services/residence-claims/:claimId
437
+ x-api-key: <e-service-api-key>
438
+ ```
439
+
440
+ ### Claim Status → UI Text
441
+
442
+ | Status | แสดงผล |
443
+ |---|---|
444
+ | `SUBMITTED` | รอเจ้าหน้าที่ตรวจสอบ |
445
+ | `DUPLICATE_CANDIDATE` | พบข้อมูลใกล้เคียง รอตรวจสอบ |
446
+ | `NEEDS_REVIEW` | ต้องตรวจสอบเพิ่มเติม |
447
+ | `APPROVED` | อนุมัติแล้ว ✓ |
448
+ | `MERGED` | รวมกับบ้านที่มีอยู่แล้ว |
449
+ | `REJECTED` | ไม่อนุมัติ (แสดง `reviewNote`) |
450
+
451
+ > เมื่อ `APPROVED` หรือ `MERGED` ให้บันทึก `matchedResidenceId` เป็น residence ของ user
452
+
453
+ ---
454
+
455
+ ## SSO Flow ภาพรวม
456
+
457
+ ```
458
+ [Frontend] [IAM-GOV] [Backend]
459
+ │ │ │
460
+ │─── 1. redirect ──▶│ │
461
+ │ + state param │ │
462
+ │ │ 2. user login │
463
+ │◀── 3. ?code=XX ───│ │
464
+ │ &state=YY │ │
465
+ │ │ │
466
+ │─── 4. POST {code} ────────────────────▶│
467
+ │ (verify state ✅) │
468
+ │ │─── 5. POST verify-code ──▶ IAM-GOV
469
+ │ │◀── 6. user + residences ───
470
+ │ │─── 7. upsert DB
471
+ │◀── 8. JWT session + user ─────────────│
472
+ │ │
473
+ ✅ Login สำเร็จ → redirect ตาม role
474
+ ```
475
+
476
+ ---
477
+
478
+ ## Security Checklist
479
+
480
+ ### ✅ ต้องทำ
481
+
482
+ - เก็บ `E_SERVICE_API_KEY` บน backend เท่านั้น
483
+ - Trim SSO code ก่อนส่งเสมอ
484
+ - Verify code ครั้งเดียว (one-time use)
485
+ - สร้าง e-service session เองหลัง verify สำเร็จ — ไม่ใช้ IAM refresh token
486
+ - ตรวจทั้ง membership status และ residence status ก่อนทำธุรกรรม
487
+ - Verify `state` ใน central claim callback ทุกครั้ง
488
+ - Search ซ้ำก่อน submit claim เพื่อป้องกันข้อมูลซ้ำ
489
+ - Log IAM user id, claim id, request id — ห้าม log secret
490
+
491
+ ### ❌ ห้ามทำ
492
+
493
+ - ห้ามใส่ `x-api-key` ใน `NEXT_PUBLIC_*` / `VITE_*`
494
+ - ห้ามให้ browser เรียก IAM-GOV endpoints โดยตรง
495
+ - ห้าม assume `residences.length > 0`
496
+ - ห้ามใช้ status `PENDING` เป็นการยืนยันเจ้าของบ้าน
497
+ - ห้ามเก็บ IAM payload ทั้งก้อนใน browser cookie
498
+ - ห้ามให้ e-service สร้าง canonical residence โดยตรง — ต้องสร้างเป็น claim
499
+
500
+ ---
501
+
502
+ ## Theming (ปรับสีได้ 3 วิธี)
503
+
504
+ **วิธี 1: ผ่าน Provider** (ทั่วทั้ง app)
505
+
506
+ ```tsx
507
+ <GovSsoProvider config={ssoConfig} theme={{
508
+ primaryColor: '#0066CC',
509
+ primaryHoverColor: '#004C99',
510
+ errorColor: '#dc2626',
511
+ textColor: '#111827',
512
+ backgroundColor: '#f9fafb',
513
+ }}>
514
+ ```
515
+
516
+ **วิธี 2: ผ่าน Props** (เฉพาะ component นั้น)
517
+
518
+ ```tsx
519
+ <SsoLoginButton theme={{ primaryColor: '#7C3AED' }} />
520
+ ```
521
+
522
+ **วิธี 3: className** (CSS เอง)
523
+
524
+ ```tsx
525
+ <SsoLoginButton className="my-custom-btn" />
526
+ ```
527
+
528
+ | Property | Default | คำอธิบาย |
529
+ |---|---|---|
530
+ | `primaryColor` | `#1E7D55` | สีหลัก (ปุ่ม, loading, success) |
531
+ | `primaryHoverColor` | `#256B48` | สี hover ของปุ่ม |
532
+ | `errorColor` | `#ef4444` | สี error |
533
+ | `textColor` | `#1e293b` | สีข้อความหลัก |
534
+ | `borderRadius` | `0.5rem` | ขอบมน |
535
+
536
+ ---
537
+
538
+ ## Error Handling
539
+
540
+ ```typescript
541
+ import { GovSsoError } from '@biza-gov/sso-login';
542
+
543
+ try {
544
+ const result = await client.handleCallback(code);
545
+ } catch (err) {
546
+ if (err instanceof GovSsoError) {
547
+ console.log(err.code); // 'NETWORK_ERROR' | 'SERVER_ERROR' | ...
548
+ console.log(err.statusCode); // 500, 503, etc.
549
+ console.log(err.message); // ข้อความภาษาไทย
550
+ }
551
+ }
552
+ ```
553
+
554
+ | Error Code | เกิดเมื่อ |
555
+ |---|---|
556
+ | `NETWORK_ERROR` | เชื่อมต่อ server ไม่ได้ |
557
+ | `SERVER_ERROR` | Server ตอบ 500/502/503/504 |
558
+ | `INVALID_RESPONSE` | Server ตอบ JSON ไม่ถูกต้อง |
559
+ | `BROWSER_ONLY` | เรียกใน server-side context |
560
+ | `UNKNOWN_ERROR` | Error ที่ไม่ทราบสาเหตุ |
561
+
562
+ > Library มี auto-retry 2 ครั้งสำหรับ 5xx errors (exponential backoff 1s → 2s) — ไม่ต้อง config เพิ่ม
563
+
564
+ ---
565
+
566
+ ## Error Reference (IAM-GOV)
567
+
568
+ | Error | สาเหตุ | วิธีแก้ |
569
+ |---|---|---|
570
+ | `403 Invalid SSO code` | หา code ไม่เจอ | ตรวจ env, trim code, generate ใหม่ |
571
+ | `403 SSO code does not belong to this service` | API key เป็นของ service อื่น | ตรวจ `E_SERVICE_CODE` ตรงกับ `API_KEY` ไหม |
572
+ | `403 SSO code has already been used` | ใช้ code ซ้ำ | Generate code ใหม่ทุกครั้ง |
573
+ | `residences: []` | ไม่มี scope / ไม่มี linked residence | ตรวจ scope และ membership ใน IAM-GOV |
574
+ | `serviceAccess: []` | ไม่มี e_service_access row | IAM-GOV Admin → Manage E-Services → Assign |
575
+
576
+ ---
577
+
578
+ ## Troubleshooting (Library)
579
+
580
+ | ปัญหา | สาเหตุ | แก้ไข |
581
+ |---|---|---|
582
+ | `Module not found: gov-sso-login` | ยังไม่ได้ติดตั้ง | `npm install @biza-gov/sso-login` |
583
+ | SSO redirect แล้วไม่กลับมา | `callbackUrl` ไม่ตรง | ตรวจ `NEXT_PUBLIC_FRONTEND_URL` |
584
+ | Build error ใน Next.js | ไม่ได้ transpile | เพิ่ม `transpilePackages` ใน `next.config.ts` |
585
+ | "การตรวจสอบความปลอดภัยล้มเหลว" | CSRF state ไม่ตรง | ลอง login ใหม่ (อาจใช้ link เก่า) |
586
+ | `useGovSso: ต้องส่ง config` | ไม่มี Provider | Wrap ด้วย `<GovSsoProvider>` |
587
+ | Cookie ไม่ถูก set | domain ไม่ตรง | ตรวจ `FRONTEND_URL` ใน backend `.env` |
588
+
589
+ ---
590
+
591
+ ## Implementation Checklist (ทำตามลำดับ)
592
+
593
+ - [ ] ติดตั้ง `@biza-gov/sso-login` และตั้งค่า `next.config.ts`
594
+ - [ ] เพิ่ม env vars: frontend (4 ตัว) + backend (3 ตัว)
595
+ - [ ] สร้าง `lib/sso-config.ts`
596
+ - [ ] Wrap app ด้วย `GovSsoProvider` ใน `layout.tsx`
597
+ - [ ] สร้างหน้า login พร้อม `SsoLoginButton` หรือ `useGovSso`
598
+ - [ ] สร้างหน้า `/auth/callback` พร้อม `SsoCallbackHandler` หรือ `useGovSsoCallback`
599
+ - [ ] Implement `POST /auth/sso-callback` บน NestJS backend
600
+ - [ ] Implement `upsertIamUser`, `upsertResidenceSnapshot`, `upsertUserResidenceLink`
601
+ - [ ] สร้าง DB tables: `iam_users`, `iam_residence_snapshots`, `iam_user_residences`
602
+ - [ ] (ถ้าต้องการ) ทำ proxy endpoints สำหรับ Residence Search/Read
603
+ - [ ] (ถ้าต้องการ) ทำ UI แจ้งเพิ่มบ้าน + Claim API + upload evidence
604
+ - [ ] เขียน test: missing code, invalid code, empty residences, pending, verified, no API key leak
605
+ - [ ] Manual test ตาม script ด้านล่าง
606
+
607
+ ---
608
+
609
+ ## Manual Test Script
610
+
611
+ ```http
612
+ # 1. Generate SSO code (ใช้ IAM access token)
613
+ POST {IAM_API_URL}/e-services/sso/generate-code
614
+ Authorization: Bearer <IAM_ACCESS_TOKEN>
615
+ Content-Type: application/json
616
+
617
+ { "eServiceCode": "your-service-code" }
618
+
619
+ # 2. Verify code (จาก backend เท่านั้น)
620
+ POST {IAM_API_URL}/e-services/sso/verify-code
621
+ Content-Type: application/json
622
+ x-api-key: <E_SERVICE_API_KEY>
623
+
624
+ { "code": "<code-from-step-1>" }
625
+
626
+ # ตรวจ response:
627
+ # ✅ user.id มีค่า
628
+ # ✅ user.memberships เป็น array
629
+ # ✅ residences เป็น array (ถ้า user มี linked residence จะมี addressSnapshot)
630
+
631
+ # 3. Verify code เดิมซ้ำ → ต้องได้ error
632
+ # ✅ "SSO code has already been used"
633
+ ```