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