@plasgos/auth-verify 0.1.0-next.2 → 0.1.0-next.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +51 -15
  3. package/THIRD_PARTY_NOTICES.md +31 -0
  4. package/dist/express.cjs +157 -0
  5. package/dist/express.cjs.map +1 -0
  6. package/dist/express.d.cts +90 -0
  7. package/dist/express.d.ts +90 -0
  8. package/dist/express.js +127 -0
  9. package/dist/express.js.map +1 -0
  10. package/dist/index.cjs +1254 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.cts +67 -0
  13. package/dist/index.d.ts +67 -0
  14. package/dist/index.js +499 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/nestjs.cjs +1395 -0
  17. package/dist/nestjs.cjs.map +1 -0
  18. package/dist/nestjs.d.cts +153 -0
  19. package/dist/nestjs.d.ts +153 -0
  20. package/dist/nestjs.js +637 -0
  21. package/dist/nestjs.js.map +1 -0
  22. package/dist/types-CGtRnj59.d.cts +193 -0
  23. package/dist/types-CGtRnj59.d.ts +193 -0
  24. package/dist/webhook.cjs +8 -6
  25. package/dist/webhook.cjs.map +1 -1
  26. package/dist/webhook.d.cts +9 -3
  27. package/dist/webhook.d.ts +9 -3
  28. package/dist/webhook.js +8 -6
  29. package/dist/webhook.js.map +1 -1
  30. package/docs/bff-express.md +1314 -0
  31. package/docs/consumers.md +10 -2
  32. package/docs/error.md +195 -10
  33. package/docs/examples/auth-verify-readme.ts +24 -0
  34. package/docs/examples/bff-express.ts +370 -0
  35. package/docs/examples/bff-proxy.ts +335 -0
  36. package/docs/examples/bff-redis-lock.ts +187 -0
  37. package/docs/examples/bff-revocation.ts +136 -0
  38. package/docs/examples/env.ts +52 -1
  39. package/docs/examples/token-commonjs.cjs +95 -0
  40. package/docs/examples/token-express.ts +56 -0
  41. package/docs/examples/token-fetch.ts +24 -0
  42. package/docs/examples/token-nestjs-jest.ts +77 -0
  43. package/docs/examples/token-nestjs.ts +127 -0
  44. package/docs/examples/token-socket.ts +59 -0
  45. package/docs/examples/token-testing.ts +100 -0
  46. package/docs/examples/token-verifier.ts +132 -0
  47. package/docs/examples/user-events.ts +110 -0
  48. package/docs/examples/webhook-verifier.ts +54 -0
  49. package/docs/login-web.md +39 -7
  50. package/docs/memulai.md +94 -14
  51. package/docs/server-ke-server.md +12 -0
  52. package/docs/verifikasi-token.md +1219 -0
  53. package/docs/webhook.md +191 -6
  54. package/package.json +61 -5
package/docs/consumers.md CHANGED
@@ -14,7 +14,7 @@ Setelah paket terpasang, lanjut ke [`memulai.md`](memulai.md).
14
14
  pnpm add @plasgos/oidc-client@<versi> --save-exact
15
15
  ```
16
16
 
17
- Aplikasi yang menerima webhook dari Plasgos meng-install `@plasgos/auth-verify`, sendiri atau di samping `@plasgos/oidc-client`, dengan versi yang sama:
17
+ Aplikasi yang menerima webhook dari Plasgos atau memeriksa access token Plasgos di API-nya sendiri meng-install `@plasgos/auth-verify`, sendiri atau di samping `@plasgos/oidc-client`, dengan versi yang sama:
18
18
 
19
19
  ```bash
20
20
  pnpm add @plasgos/auth-verify@<versi> --save-exact
@@ -24,6 +24,14 @@ Ganti `<versi>` dengan nomor versi persis (lihat §5). `@plasgos/auth-shared` ik
24
24
 
25
25
  Perintah ini sama di laptop, di Docker, dan di CI. Tidak ada token yang perlu dibuat atau diatur.
26
26
 
27
+ ### Node, CommonJS, dan NestJS
28
+
29
+ - Paket butuh Node `>=22.22` (`engines`). Image Docker aplikasi juga harus memakai Node 22.22 atau lebih baru; tag `node:22-slim` atau `node:22-alpine` yang lama bisa masih di bawah itu, jadi cek dengan `docker run --rm <image> node --version`.
30
+ - Setiap paket punya build ESM dan CommonJS. Aplikasi CommonJS (tanpa `"type": "module"`, memakai `require`) dan test di Jest (dengan ts-jest) memakai build CommonJS tanpa flag atau pengaturan tambahan: tidak perlu `--experimental-vm-modules`, `transformIgnorePatterns`, atau `require(esm)`.
31
+ - `@plasgos/auth-verify` memakai `jose` untuk memeriksa tanda tangan token. Build ESM meng-import `jose` dari `node_modules`; build CommonJS (`.` dan `/nestjs`) membawa salinan `jose` sendiri di dalamnya, karena `jose` hanya tersedia sebagai ESM. Lisensi salinan itu ada di `THIRD_PARTY_NOTICES.md` di dalam paket.
32
+ - Akibatnya, `overrides` untuk `jose` (pnpm atau npm) hanya mengganti `jose` yang dipakai build ESM, bukan salinan di build CommonJS. Bila ada perbaikan keamanan `jose`, tim Plasgos merilis patch `@plasgos/auth-verify` dengan `jose` yang sudah diperbaiki; naikkan versi `@plasgos/auth-verify`, jangan hanya meng-override `jose`.
33
+ - `@plasgos/auth-verify/nestjs` memakai `@nestjs/common` dan `@nestjs/core` versi 11 (`^11.0.0`) milik aplikasi. Keduanya peer dependency opsional: aplikasi yang tidak memakai `/nestjs` tidak perlu meng-install NestJS, dan `/express` tidak butuh paket `express` sebagai dependensi. NestJS 12 belum didukung.
34
+
27
35
  ## 2. `.npmrc` di repo aplikasi
28
36
 
29
37
  Tidak perlu baris apa pun untuk `@plasgos`. Paket diambil dari registry bawaan (`registry.npmjs.org`).
@@ -85,6 +93,6 @@ Perintah di §1 menulis versi persis (`x.y.z-next.n`) ke `package.json`, dan ver
85
93
 
86
94
  ## 6. Isi paket dan lisensi
87
95
 
88
- - Paket berisi `dist` (ESM, CJS, `.d.ts`, dan source map), `README.md`, `CHANGELOG.md`, dan `LICENSE`. `@plasgos/oidc-client` dan `@plasgos/auth-verify` juga membawa folder `docs/` dengan isi yang sama: panduan ini dan file contohnya (`docs/examples/`).
96
+ - Paket berisi `dist` (ESM, CJS, `.d.ts`, dan source map), `README.md`, `CHANGELOG.md`, dan `LICENSE`. `@plasgos/auth-verify` juga membawa `THIRD_PARTY_NOTICES.md`, lisensi `jose` yang ada di dalam build CommonJS-nya. `@plasgos/oidc-client` dan `@plasgos/auth-verify` juga membawa folder `docs/` dengan isi yang sama: panduan ini dan file contohnya (`docs/examples/`).
89
97
  - Source map ikut terbit lengkap dengan `sourcesContent`, supaya stack trace menunjuk ke sumber TypeScript. Karena paketnya publik, sumber TypeScript paket ikut terbaca siapa pun yang mengunduh paket. Ini disengaja.
90
98
  - Lisensi: bukan open source. Paket milik Plasgos dan hanya boleh dipakai untuk menghubungkan aplikasi ke layanan Plasgos (login dan API Plasgos) oleh pemegang kredensial client resmi dari Plasgos dan pengembang yang bekerja untuk mereka. Menyalin, mengubah, menerbitkan ulang, atau mendistribusikan paket tanpa izin tertulis Plasgos dilarang. Teks lengkapnya ada di file [`LICENSE`](../LICENSE) di setiap paket.
package/docs/error.md CHANGED
@@ -4,14 +4,14 @@ Acuan untuk semua kegagalan yang bisa datang dari `@plasgos/oidc-client` dan `@p
4
4
 
5
5
  | Error | Kapan | Bagian |
6
6
  |---|---|---|
7
- | `ConfigError` | Saat start: opsi salah | [§4](#4-configerror), untuk webhook [§7](#configerror-dari-createwebhookverifier) |
7
+ | `ConfigError` | Saat start: opsi salah | [§4](#4-configerror), untuk webhook [§7](#configerror-dari-createwebhookverifier), untuk verifikasi token [§8](#configerror-dari-createaccesstokenverifier) |
8
8
  | `OidcError` | Saat berjalan: login, refresh, atau token service gagal | [§1](#1-oidcerror) |
9
9
  | `SessionTooLargeError` | Cookie sesi tidak muat | [§5](#5-sessiontoolargeerror) |
10
10
  | `TypeError` | Argumen fungsi salah (bug di kode pemanggil) | [§6](#6-typeerror) |
11
11
  | `WebhookVerifyError` | Kiriman webhook ditolak (`@plasgos/auth-verify/webhook`) | [§7](#7-webhookverifyerror) |
12
- | `AuthVerifyError` | Verifikasi access token | [§8](#8-authverifyerror) |
12
+ | `AuthVerifyError` | Access token ditolak (`@plasgos/auth-verify`, `/express`, `/nestjs`) | [§8](#8-authverifyerror) |
13
13
 
14
- Aturan yang berlaku untuk semuanya: pesan error dan event **tidak pernah** memuat token, code, secret, isi cookie, isi jawaban Plasgos, tanda tangan webhook, nilai header, atau isi body webhook. Semuanya aman ditulis ke log.
14
+ Aturan yang berlaku untuk semuanya: pesan error dan event **tidak pernah** memuat token, klaim token, code, secret, isi cookie, isi jawaban Plasgos, tanda tangan webhook, nilai header, atau isi body webhook. Semuanya aman ditulis ke log.
15
15
 
16
16
  ## 1. `OidcError`
17
17
 
@@ -168,7 +168,7 @@ Exception yang dilempar hook diabaikan SDK. Hook tidak bisa mengubah hasil opera
168
168
 
169
169
  ## 3. `instanceof` dan dua loader
170
170
 
171
- Setiap paket tersedia sebagai ESM dan CommonJS. Keduanya adalah dua salinan modul yang berbeda, jadi kelas `OidcError` dari `import` bukan kelas yang sama dengan `OidcError` dari `require`. Hal yang sama berlaku untuk `WebhookVerifyError` dan `ConfigError`.
171
+ Setiap paket tersedia sebagai ESM dan CommonJS. Keduanya adalah dua salinan modul yang berbeda, jadi kelas `OidcError` dari `import` bukan kelas yang sama dengan `OidcError` dari `require`. Hal yang sama berlaku untuk `WebhookVerifyError`, `AuthVerifyError`, dan `ConfigError`.
172
172
 
173
173
  - Aplikasi yang hanya memakai satu cara (semua `import`, atau semua `require`): `error instanceof OidcError` dan `error instanceof WebhookVerifyError` bekerja.
174
174
  - Aplikasi yang mencampur keduanya (misalnya kode ESM dan sebuah dependensi CommonJS yang sama-sama memuat SDK): periksa nama dan `reason`, bukan `instanceof`:
@@ -176,16 +176,17 @@ Setiap paket tersedia sebagai ESM dan CommonJS. Keduanya adalah dua salinan modu
176
176
  ```text
177
177
  error.name === "OidcError" lalu baca error.reason
178
178
  error.name === "WebhookVerifyError" lalu baca error.reason dan error.header
179
+ error.name === "AuthVerifyError" lalu baca error.reason, error.status, error.errorCode, error.wwwAuthenticate
179
180
  error.name === "ConfigError" lalu baca error.problems
180
181
  ```
181
182
 
182
183
  `ConfigError` diekspor oleh `@plasgos/oidc-client`, `/session`, dan `/service`, dan ketiganya adalah kelas yang sama. Bila kelasnya di-import dari `@plasgos/oidc-client`, `error instanceof ConfigError` bekerja dengan aturan yang sama seperti `OidcError` di atas. Contoh di [`memulai.md` §7](memulai.md#7-bila-konfigurasi-salah) tetap memeriksa `error.name`, supaya juga bekerja di aplikasi yang mencampur `import` dan `require`.
183
184
 
184
- `ConfigError` yang diekspor `@plasgos/auth-verify/webhook` adalah kelas yang sama dengan `ConfigError` dari `@plasgos/oidc-client`, karena keduanya berasal dari `@plasgos/auth-shared`. `WebhookVerifyError` juga berasal dari sana. Aturan dua loader di atas tetap berlaku.
185
+ `ConfigError` yang diekspor `@plasgos/auth-verify`, `/webhook`, `/express`, dan `/nestjs` adalah kelas yang sama dengan `ConfigError` dari `@plasgos/oidc-client`, karena semuanya berasal dari `@plasgos/auth-shared`. `WebhookVerifyError` dan `AuthVerifyError` juga berasal dari sana: `AuthVerifyError` dari `@plasgos/auth-verify`, `/express`, dan `/nestjs` adalah satu kelas. Aturan dua loader di atas tetap berlaku. Middleware Express, guard NestJS, dan `authErrorResponse` sudah mengenali `AuthVerifyError` dari kedua loader.
185
186
 
186
187
  ## 4. `ConfigError`
187
188
 
188
- Dilempar oleh `createOidcClient`, `createServiceClient`, `createSessionStore`, dan `createWebhookVerifier` saat dipanggil. Pesan khusus webhook ada di [§7](#configerror-dari-createwebhookverifier).
189
+ Dilempar oleh `createOidcClient`, `createServiceClient`, `createSessionStore`, `createWebhookVerifier`, dan `createAccessTokenVerifier` saat dipanggil. Pesan khusus webhook ada di [§7](#configerror-dari-createwebhookverifier), dan pesan khusus verifikasi token di [§8](#configerror-dari-createaccesstokenverifier).
189
190
 
190
191
  | Properti | Isi |
191
192
  |---|---|
@@ -272,7 +273,9 @@ Pesan lingkungan, URL, dan scope di atas, ditambah `options must be an object`,
272
273
  | `options must be an object` | Argumen bukan objek |
273
274
  | `environment must be "sandbox" or "production"` | Beri nilai yang sama dengan client |
274
275
  | `hostPrefix must be a boolean` | Pakai `true` atau `false` |
275
- | `hostPrefix: false is not allowed when environment is "production"` | Production selalu memakai `__Host-` dan `Secure`. Hapus `hostPrefix: false` |
276
+ | `hostPrefix: false is not allowed when environment is "production"` | Production selalu memakai awalan (`__Host-`, atau `__Secure-` dengan `path` lain) dan `Secure`. Hapus `hostPrefix: false` |
277
+ | `path must be a string` | `path` bukan string. Hapus, atau tulis seperti `"/crm/"` |
278
+ | `path must start and end with "/" and contain only printable ASCII without ";", ",", "%", ".." or "//"` | `path` harus diawali dan diakhiri `/`, tanpa spasi, karakter kontrol, huruf non-ASCII, `;`, `,`, `%`, `..`, atau `//`. Contoh: `"/crm/"` ([`login-web.md` §6](login-web.md#aplikasi-di-bawah-sub-path)) |
276
279
  | `hkdfSalt is required`, `hkdfSalt must be a string` | Isi `hkdfSalt` dengan string tetap |
277
280
  | `secrets must hold one or two values` | `secrets` harus array berisi satu atau dua string. Periksa `SESSION_SECRET` |
278
281
  | `secrets values must each be at least 32 bytes` | Buat secret yang lebih panjang |
@@ -315,7 +318,7 @@ Diekspor dari `@plasgos/oidc-client/session`.
315
318
 
316
319
  Selain itu, `serviceClient.fetch` meneruskan pembatalan dari `init.signal` milik pemanggil apa adanya (alasan `abort` yang Anda berikan).
317
320
 
318
- `TypeError` dari verifikasi webhook ada di [§7](#typeerror-dari-verify).
321
+ `TypeError` dari verifikasi webhook ada di [§7](#typeerror-dari-verify), dan dari verifikasi token di [§8](#typeerror-dan-error-dari-verifikasi-token).
319
322
 
320
323
  ## 7. `WebhookVerifyError`
321
324
 
@@ -401,7 +404,7 @@ Plasgos mengulang setiap jawaban selain `2xx` ([`webhook.md` §2](webhook.md#2-a
401
404
  | `environment must be "sandbox" or "production"` | Isi `environment` (env `PLASGOS_ENV`) dengan salah satu dari dua nilai itu |
402
405
  | `secrets must hold one or two values` | `secrets` harus array berisi satu atau dua string setelah nilai kosong dibuang. Biasanya env secret kosong, atau berisi lebih dari dua nilai |
403
406
  | `secrets values must each be at least 32 bytes` | Secret terlalu pendek. Periksa bahwa env berisi secret utuh dari tim Plasgos |
404
- | `preset is required` | Isi `preset` dengan `presets.payments` atau `presets.plaslinkShipping` |
407
+ | `preset is required` | Isi `preset` dengan `presets.payments`, `presets.appEvents`, atau `presets.plaslinkShipping` |
405
408
  | `preset must be one of presets or an object with name and headers` | `preset` berupa string atau bentuknya salah. Pakai `presets.payments`, bukan `"payments"` |
406
409
  | `preset.name must match /^[A-Za-z0-9_-]{1,64}$/` | Preset sendiri: perbaiki `name` |
407
410
  | `preset.headers.<peran> must be an HTTP header name of at most 64 characters` | Preset sendiri: nama header untuk `id`, `type`, `timestamp`, atau `signature` salah |
@@ -425,4 +428,186 @@ Pesan yang sama dipakai oleh `verifier.verify` dan `verifyWebhook`.
425
428
 
426
429
  ## 8. `AuthVerifyError`
427
430
 
428
- **Menyusul bersama verifikasi access token** (`@plasgos/auth-verify`).
431
+ Ditolak (reject) oleh `verifier.verifyAuthorization` dan `verifier.verifyRequest` dari `@plasgos/auth-verify` bila sebuah access token tidak diterima. Middleware Express (`requirePlasgosToken`), guard NestJS (`PlasgosAccessTokenGuard`), dan `authErrorResponse` menjawabnya untuk Anda. Cara memasangnya ada di [`verifikasi-token.md`](verifikasi-token.md).
432
+
433
+ | Properti | Isi |
434
+ |---|---|
435
+ | `name` | `"AuthVerifyError"` |
436
+ | `reason` | Kode alasan (tabel di bawah). Daftar lengkapnya juga diekspor sebagai `AUTH_VERIFY_REASONS` |
437
+ | `status` | Status HTTP jawaban: `401`, `403` (`insufficient_scope`), atau `503` (`unavailable`) |
438
+ | `errorCode` | Nilai `error` di body JSON: `invalid_token`, `insufficient_scope`, `insufficient_user_authentication`, atau `temporarily_unavailable` |
439
+ | `wwwAuthenticate` | Nilai header `WWW-Authenticate`, atau `null` bila tidak ada header yang dikirim |
440
+ | `message` | `"Access token <reason>"`, tidak lebih |
441
+
442
+ Pesan dan properti tidak pernah memuat token, klaim, atau nilai header. `scope="…"` dan `max_age=` di `wwwAuthenticate` berasal dari persyaratan route Anda, bukan dari token.
443
+
444
+ ### Semua `reason` dari verifikasi token
445
+
446
+ Diperiksa dengan urutan berikut. Kegagalan pertama yang ditemukan yang dilaporkan.
447
+
448
+ | `reason` | Arti | Status | `WWW-Authenticate` |
449
+ |---|---|---|---|
450
+ | [`missing_token`](#missing_token) | Tidak ada header `Authorization: Bearer …` | `401` | `Bearer` |
451
+ | [`malformed_token`](#malformed_token) | Isinya bukan JWT yang sah | `401` | `Bearer error="invalid_token"` |
452
+ | [`unknown_key`](#unknown_key) | `alg` bukan `RS256`, `kid` tidak ada, atau kuncinya tidak dikenal | `401` | `Bearer error="invalid_token"` |
453
+ | [`expired_token`](#expired_token) | `exp` lewat atau `nbf` belum tiba | `401` | `Bearer error="invalid_token"` |
454
+ | [`invalid_token`](#invalid_token) | Tanda tangan, `iss`, atau `aud` salah | `401` | `Bearer error="invalid_token"` |
455
+ | [`invalid_claims`](#invalid_claims) | `typ` salah, bentuk klaim salah, atau klaim wajib kurang | `401` | `Bearer error="invalid_token"` |
456
+ | [`revoked`](#revoked) | `isRevoked` mengembalikan `true` | `401` | `Bearer error="invalid_token"` |
457
+ | [`insufficient_scope`](#insufficient_scope) | Token tidak punya semua scope route | `403` | `Bearer error="insufficient_scope", scope="<scope route>"` |
458
+ | [`stale_auth`](#stale_auth) | Login user lebih lama dari `maxAuthAge` | `401` | `Bearer error="insufficient_user_authentication", max_age=<detik>` |
459
+ | [`unavailable`](#unavailable-access-token) | Kunci Plasgos (JWKS) tidak bisa dibaca | `503` | Tidak ada |
460
+
461
+ Body jawaban selalu `{"error":"<errorCode>"}`: `insufficient_scope` untuk `insufficient_scope`, `insufficient_user_authentication` untuk `stale_auth`, `temporarily_unavailable` untuk `unavailable`, dan `invalid_token` untuk yang lain.
462
+
463
+ ### `missing_token`
464
+
465
+ - **Arti:** header `Authorization` tidak ada, bukan string, atau tidak diawali `Bearer `.
466
+ - **Penyebab umum:** pemanggil belum login; proxy membuang header `Authorization`; token dikirim di cookie atau query.
467
+ - **Yang dilakukan:** jawab `401` dengan `WWW-Authenticate: Bearer`. Pemanggil mengirim access token di header `Authorization`.
468
+
469
+ ### `malformed_token`
470
+
471
+ - **Arti:** isi header bukan `Bearer` diikuti satu JWT (tiga bagian base64url), lebih panjang dari 8 KiB, atau header atau payload JWT bukan objek JSON.
472
+ - **Penyebab umum:** token terpotong; yang dikirim bukan access token (misalnya isi cookie atau id acak); token dikutip dua kali.
473
+ - **Yang dilakukan:** jawab `401`. Bug di pemanggil.
474
+
475
+ ### `unknown_key`
476
+
477
+ - **Arti:** header JWT memakai `alg` selain `RS256` (termasuk `none` dan `HS256`), tidak punya `kid`, atau `kid`-nya tidak ada di JWKS Plasgos setelah satu kali ambil ulang.
478
+ - **Penyebab umum:** token dari lingkungan lain (sandbox ke production atau sebaliknya); `backchannelUrl` mengarah ke server Plasgos lingkungan lain; token buatan sendiri.
479
+ - **Yang dilakukan:** jawab `401`. Bila semua token gagal dengan alasan ini, samakan lingkungan token, `issuer`, dan `backchannelUrl`. Rotasi kunci Plasgos tidak menyebabkan alasan ini: kunci baru diambil sendiri.
480
+
481
+ ### `expired_token`
482
+
483
+ - **Arti:** `exp` sudah lewat, atau `nbf` belum tiba, setelah toleransi `clockToleranceSeconds` (bawaan 30 detik). `exp` eksklusif: token yang `exp`-nya tepat sebesar toleransi di masa lalu sudah ditolak.
484
+ - **Penyebab umum:** pemanggil tidak me-refresh token; jam server API atau pemanggil meleset.
485
+ - **Yang dilakukan:** jawab `401`. Pemanggil me-refresh token (`ensureFresh`) lalu mengulang sekali. Bila token yang baru pun ditolak, periksa jam server (NTP).
486
+
487
+ ### `invalid_token`
488
+
489
+ - **Arti:** tanda tangan tidak cocok dengan kunci, `iss` tidak sama persis dengan `issuer`, atau `aud` tidak sama persis dengan `audience`. Juga untuk header atau klaim yang ditolak pustaka JWT tanpa alasan khusus (misalnya `crit` yang tidak dikenal).
490
+ - **Penyebab umum:** token untuk API lain (pemanggil meminta token tanpa `resource` atau dengan audience lain); `audience` berbeda satu karakter, termasuk `/` di akhir; issuer lingkungan lain.
491
+ - **Yang dilakukan:** jawab `401`. Pemanggil me-refresh sekali. Bila semua token gagal, samakan `audience` dan `issuer` dengan nilai dari tim Plasgos.
492
+
493
+ ### `invalid_claims`
494
+
495
+ - **Arti:** salah satu:
496
+ - `typ` bukan `at+jwt` (misalnya ID token yang dikirim sebagai access token);
497
+ - `aud` berupa array, `sub` atau `client_id` kosong, `scope` bukan string;
498
+ - token user dengan `sid` kosong, `auth_time` yang bukan bilangan bulat ≥ 0, `cv` yang bukan bilangan bulat, atau `plasgos_public_id` kosong atau lebih dari 128 karakter;
499
+ - `exp` tidak ada;
500
+ - klaim di `requireClaims` (verifier atau route) tidak ada, `null`, atau string kosong; untuk audience `/crm`, token user tanpa `cv`;
501
+ - token tanpa `sid` (token service) tanpa `allowServiceTokens`, atau token tanpa `sid` yang `sub`-nya berbeda dari `client_id`.
502
+ - **Penyebab umum:** ID token dikirim di tempat access token; `requireClaims` memuat klaim yang tidak dibawa token untuk audience Anda; API dipanggil dengan token service padahal `allowServiceTokens` belum dinyalakan.
503
+ - **Yang dilakukan:** jawab `401`. Bila semua token gagal, cocokkan `requireClaims` dan `allowServiceTokens` dengan token yang diterbitkan untuk API Anda.
504
+
505
+ ### `revoked`
506
+
507
+ - **Arti:** hook `isRevoked` mengembalikan `true`.
508
+ - **Penyebab umum:** sesi user dicabut, user diblokir, atau kredensial user berubah setelah token diterbitkan.
509
+ - **Yang dilakukan:** jawab `401`. Pemanggil mengakhiri sesinya dan mengarahkan user ke login.
510
+
511
+ ### `insufficient_scope`
512
+
513
+ - **Arti:** token tidak punya semua scope yang diminta route. `WWW-Authenticate` menyebut scope yang diminta.
514
+ - **Penyebab umum:** pemanggil tidak meminta scope itu saat login; client pihak ketiga meminta scope khusus first-party.
515
+ - **Yang dilakukan:** jawab `403`. Jangan diulang dengan token yang sama.
516
+
517
+ ### `stale_auth`
518
+
519
+ - **Arti:** user login lebih lama dari `maxAuthAge` route (`now − auth_time`). Untuk token service selalu, karena token service tidak punya `auth_time`.
520
+ - **Penyebab umum:** aksi sensitif yang meminta login baru.
521
+ - **Yang dilakukan:** jawab `401` dengan `max_age=<detik>`. Pemanggil memulai login ulang dengan `maxAge` itu ([`login-web.md` §10](login-web.md#10-login-ulang-untuk-aksi-sensitif)), lalu mengulang aksinya.
522
+
523
+ ### `unavailable` (access token)
524
+
525
+ - **Arti:** JWKS Plasgos tidak bisa dibaca: jaringan, DNS, timeout (`timeouts.jwksMs`), jawaban selain `200`, redirect, body lebih dari 64 KiB, atau JSON yang bukan key set. Bukan masalah token.
526
+ - **Penyebab umum:** `backchannelUrl` salah; firewall; gangguan di Plasgos.
527
+ - **Yang dilakukan:** jawab `503` tanpa `WWW-Authenticate`. Pemanggil mencoba lagi sebentar dan **tidak** mengakhiri sesi. Pasang alert.
528
+
529
+ ### `onReject` (`AuthRejectEvent`)
530
+
531
+ SDK tidak pernah menulis log. Setiap token yang ditolak diserahkan ke hook `onReject` milik verifier sebagai satu event:
532
+
533
+ | Field | Isi |
534
+ |---|---|
535
+ | `environment` | `"sandbox"` atau `"production"` |
536
+ | `reason` | `reason` yang sama dengan `AuthVerifyError` |
537
+ | `clientId` | `client_id` token, hanya setelah tanda tangannya lolos dan hanya bila berupa id biasa (huruf, angka, `_ . : -`, paling panjang 128); selain itu `null` |
538
+ | `requestId` | Header `X-Request-Id` request (adapter dan `verifyRequest` membacanya) atau `options.requestId`, dengan aturan yang sama; selain itu `null` |
539
+
540
+ Contoh hook:
541
+
542
+ <!-- snippet: examples/snippets/token-verifier.ts#on-reject -->
543
+ ```ts
544
+ /** One line per refused token. The event never holds the token or a claim value, so it is safe to log. */
545
+ export function logReject(event: AuthRejectEvent): void {
546
+ const line = [
547
+ "plasgos token refused:",
548
+ `env=${event.environment}`,
549
+ `reason=${event.reason}`,
550
+ `client_id=${event.clientId ?? "-"}`,
551
+ `request_id=${event.requestId ?? "-"}`,
552
+ ].join(" ");
553
+ process.stderr.write(`${line}\n`);
554
+ // The key set of Plasgos cannot be read: every request answers 503 until it recovers.
555
+ if (event.reason === "unavailable") process.stderr.write("ALERT plasgos key set unavailable\n");
556
+ }
557
+ ```
558
+ <!-- /snippet -->
559
+
560
+ Exception atau promise yang ditolak dari hook diabaikan SDK. Hook tidak bisa mengubah hasil verifikasi. Error dari `isRevoked` tidak memanggil `onReject`, karena itu bukan penolakan token.
561
+
562
+ ### `ConfigError` dari `createAccessTokenVerifier`
563
+
564
+ `createAccessTokenVerifier` (juga lewat `PlasgosAuthModule.forRoot` dan `forRootAsync`) melempar satu `ConfigError` berisi semua masalah. Bentuknya sama dengan [§4](#4-configerror). `issuer` dan `backchannelUrl` mengikuti aturan URL `issuer` di §4, dan `audience` mengikuti aturan `resource`.
565
+
566
+ | Pesan | Perbaikan |
567
+ |---|---|
568
+ | `options must be an object` | Argumen bukan objek |
569
+ | `environment must be "sandbox" or "production"` | Isi `environment` (env `PLASGOS_ENV`) |
570
+ | `environment is "production" but issuer is not the production issuer` | Di production, `issuer` harus `https://accounts.plasgos.co.id` |
571
+ | `environment is "production" but audience is not a production audience` | Di production, `audience` harus diawali `https://api.plasgos.co.id/` |
572
+ | `environment is "sandbox" but issuer is a production host`, `… backchannelUrl is a production host` | Sandbox tidak boleh mengarah ke host production |
573
+ | `allowInsecureHttp is not allowed when environment is "production"` | Hapus `allowInsecureHttp` di production |
574
+ | `issuer is required`, `audience is required` | Isi opsinya. Biasanya env-nya kosong |
575
+ | `backchannelUrl must use https: when environment is "production" unless allowInsecureBackchannel is true` | Pakai `https:`, atau `allowInsecureBackchannel: true` hanya untuk jaringan privat yang Anda percaya ([`verifikasi-token.md` §13](verifikasi-token.md#13-alamat-internal-backchannelurl)) |
576
+ | `allowInsecureBackchannel must be a boolean`, `allowServiceTokens must be a boolean`, `allowInsecureHttp must be a boolean` | Pakai `true` atau `false`. String `"true"` dari env ditolak |
577
+ | `requireClaims must be a list of at most 16 claim names` | Array berisi paling banyak 16 nama klaim: huruf, angka, atau `_`, 1–64 karakter |
578
+ | `clockToleranceSeconds must be an integer from 0 to 60` | Bilangan bulat detik |
579
+ | `timeouts must be an object`, `timeouts.jwksMs must be an integer from 1 to 60000` | Bentuknya `{ jwksMs }`, dalam milidetik |
580
+ | `jwks must be a JSON Web Key Set` | `{ keys: [ … ] }` dengan minimal satu kunci |
581
+ | `jwks is only allowed when environment is "sandbox"` | `jwks` hanya untuk test. Hapus di production |
582
+ | `fetch must be a function`, `isRevoked must be a function`, `onReject must be a function` | Perbaiki tipe nilainya |
583
+ | `isRevoked is required for a crm audience` | Audience dengan path `/crm` wajib punya `isRevoked` ([`verifikasi-token.md` §8](verifikasi-token.md#8-pencabutan-sesi-isrevoked)) |
584
+
585
+ ### `TypeError` dan `Error` dari verifikasi token
586
+
587
+ Bug di kode pemanggil, bukan token yang ditolak. Tidak dilaporkan lewat `onReject`.
588
+
589
+ | Pesan | Penyebab |
590
+ |---|---|
591
+ | `verify: options must be an object` | Argumen kedua `verifyAuthorization` atau `verifyRequest` bukan objek |
592
+ | `verify: scopes must be a list of scope tokens` | `scopes` bukan array scope (string tanpa spasi, `"`, atau `\`) |
593
+ | `verify: requireClaims must be a list of at most 16 claim names` | `requireClaims` salah bentuk |
594
+ | `verify: maxAuthAge must be a positive safe integer` | `maxAuthAge` bukan bilangan bulat positif detik |
595
+ | `verify: requestId must be a string` | `requestId` bukan string atau `null` |
596
+ | `verify: now must be a finite number` | `now` bukan angka milidetik |
597
+ | `verifyRequest: request must be a Web Request` | Argumen `verifyRequest` bukan `Request`. Untuk `req` Express, pakai middleware atau `verifyAuthorization(req.headers.authorization)` |
598
+ | `isRevoked must return a boolean` | Hook `isRevoked` mengembalikan nilai selain `true` atau `false` |
599
+ | `requirePlasgosToken: verifier must come from createAccessTokenVerifier` | Argumen pertama bukan verifier |
600
+ | `requirePlasgosToken: options must be an object`, `requirePlasgosToken: scopes must be a list of scope tokens`, `requirePlasgosToken: requireClaims must be a list of at most 16 claim names`, `requirePlasgosToken: maxAuthAge must be a positive safe integer` | Persyaratan route salah. Dilempar saat middleware dibuat |
601
+ | `RequireScopes: give at least one scope`, `RequireScopes: scopes must be a list of scope tokens` | Decorator tanpa scope atau dengan scope yang tidak sah. Dilempar saat class dimuat |
602
+ | `RequireRecentAuth: maxAgeSeconds must be a positive safe integer` | Argumen decorator salah |
603
+ | `authErrorResponse: error must be an AuthVerifyError` | `authErrorResponse` diberi error lain. Lempar ulang error seperti itu |
604
+ | `AuthVerifyError: …` | `new AuthVerifyError(…)` dibuat sendiri dengan argumen yang salah |
605
+
606
+ Dua `Error` (bukan `TypeError`) menandai bug wiring dan dijawab `500`:
607
+
608
+ | Pesan | Penyebab |
609
+ |---|---|
610
+ | `principalOf: requirePlasgosToken did not run for this request` | `principalOf(req)` di route tanpa `requirePlasgosToken` |
611
+ | `PlasgosPrincipal: PlasgosAccessTokenGuard did not run for this request` | `@PlasgosPrincipal()` di route tanpa `PlasgosAccessTokenGuard` |
612
+
613
+ Error yang dilempar hook `isRevoked` milik Anda diteruskan apa adanya, tidak dibungkus SDK. Jawab dengan `503` ([`verifikasi-token.md` §8](verifikasi-token.md#8-pencabutan-sesi-isrevoked)).
@@ -1,5 +1,9 @@
1
+ import { createAccessTokenVerifier } from "@plasgos/auth-verify";
2
+ import type { AccessTokenVerifier, UserAccessPrincipal } from "@plasgos/auth-verify";
3
+ import { principalOf, requirePlasgosToken } from "@plasgos/auth-verify/express";
1
4
  import { createWebhookVerifier, presets } from "@plasgos/auth-verify/webhook";
2
5
  import type { VerifiedWebhook, WebhookVerifier } from "@plasgos/auth-verify/webhook";
6
+ import type { Express } from "express";
3
7
 
4
8
  // #region webhook
5
9
  /** Once, at start: a wrong option throws one ConfigError here. */
@@ -16,3 +20,23 @@ export function receive(verifier: WebhookVerifier, request: Request, rawBody: Ui
16
20
  return verifier.verify({ headers: request.headers, rawBody });
17
21
  }
18
22
  // #endregion webhook
23
+
24
+ // #region token
25
+ /** Once, at start: a wrong option throws one ConfigError here. */
26
+ export function createTokenVerifier(isRevoked: (principal: UserAccessPrincipal) => Promise<boolean>): AccessTokenVerifier {
27
+ return createAccessTokenVerifier({
28
+ environment: "production",
29
+ issuer: "https://accounts.plasgos.co.id",
30
+ audience: "https://api.plasgos.co.id/crm",
31
+ requireClaims: ["plasgos_public_id", "cv"],
32
+ isRevoked,
33
+ });
34
+ }
35
+
36
+ /** Per route: 401, 403 or 503 is answered by the middleware; the handler runs only with a valid token. */
37
+ export function mountContacts(app: Express, verifier: AccessTokenVerifier): void {
38
+ app.get("/contacts", requirePlasgosToken(verifier, { scopes: ["crm:access"] }), (req, res) => {
39
+ res.json({ owner: principalOf(req).claims.plasgos_public_id });
40
+ });
41
+ }
42
+ // #endregion token