@plasgos/oidc-client 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.
@@ -0,0 +1,1219 @@
1
+ # Verifikasi access token
2
+
3
+ Panduan ini untuk API milik Anda yang dipanggil dengan access token Plasgos (`Authorization: Bearer <token>`). `@plasgos/auth-verify` memeriksa bahwa token itu benar diterbitkan Plasgos untuk API Anda, masih berlaku, belum dicabut, dan membawa scope yang dibutuhkan route. Setelah itu kode Anda tahu siapa pemanggilnya.
4
+
5
+ Panduan ini ditulis untuk developer backend yang belum pernah melihat bagian dalam Plasgos. Semua contoh lolos typecheck dan bisa disalin. Istilah yang dipakai di sini (audience, BFF, `sub` pairwise, `sid`, `cv`, dan `plasgos_public_id`) dijelaskan di [`memulai.md` §3](memulai.md#istilah).
6
+
7
+ Urutan kerja:
8
+
9
+ 1. Pastikan panduan ini yang Anda butuhkan ([§1](#1-untuk-siapa-dan-kapan-dipakai)).
10
+ 2. Minta audience API Anda ke tim Plasgos dan install paket ([§2](#2-prasyarat)).
11
+ 3. Atur env ([§3](#3-env)).
12
+ 4. Buat verifier saat aplikasi start ([§4](#4-membuat-verifier)).
13
+ 5. Pasang di route: Express ([§9](#9-express)), NestJS ([§10](#10-nestjs)), atau server berbasis `Request` ([§11](#11-server-berbasis-request)).
14
+ 6. Pasang pemeriksaan pencabutan ([§8](#8-pencabutan-sesi-isrevoked)).
15
+ 7. Uji API Anda dengan token buatan test ([§15](#15-menguji-api-anda)).
16
+ 8. Periksa daftar sebelum production ([§18](#18-sebelum-production)).
17
+
18
+ ## 1. Untuk siapa dan kapan dipakai
19
+
20
+ | Situasi aplikasi Anda | Panduan |
21
+ |---|---|
22
+ | API Anda menerima request dengan `Authorization: Bearer <access token Plasgos>` | Panduan ini |
23
+ | Aplikasi web Anda butuh user login dengan akun Plasgos | [`login-web.md`](login-web.md) |
24
+ | Server Node/Express yang memegang sesi user untuk SPA atau PWA dan meneruskan request ke API Anda (BFF) | [`bff-express.md`](bff-express.md). BFF **mendapat** token; API di belakangnya yang **memverifikasi** token dengan panduan ini |
25
+ | Server Anda memanggil API Plasgos tanpa user | [`server-ke-server.md`](server-ke-server.md) |
26
+ | Server Anda menerima kiriman bertanda tangan dari Plasgos | [`webhook.md`](webhook.md) |
27
+
28
+ Gambaran umumnya:
29
+
30
+ ```text
31
+ Browser / PWA ──cookie sesi──> BFF ──Authorization: Bearer <token>──> API Anda
32
+ │ │
33
+ │ login, refresh │ kunci publik (JWKS), di-cache
34
+ └──────────────> Plasgos <────────────┘
35
+ ```
36
+
37
+ - Token diterbitkan Plasgos untuk satu **audience**: alamat yang mewakili API Anda, misalnya `https://api.plasgos.co.id/crm`. Token untuk API lain ditolak.
38
+ - Verifikasi tidak butuh secret. SDK memeriksa tanda tangan token dengan kunci publik Plasgos (JWKS), yang diambil sekali lalu di-cache.
39
+ - Token hanya membawa identitas, sesi, dan scope. Token tidak membawa role atau tim. Hak akses data di API Anda tetap diatur API Anda sendiri.
40
+
41
+ ## 2. Prasyarat
42
+
43
+ - Node `>=22.22`. Paket tersedia sebagai ESM dan CommonJS; keduanya bekerja tanpa flag ([§16](#16-commonjs-esm-dan-test-runner)).
44
+ - Proyek TypeScript memakai `moduleResolution` `node16`, `nodenext`, atau `bundler`. Dengan `moduleResolution: node` yang lama, import `@plasgos/auth-verify/express` dan `/nestjs` gagal dengan `Cannot find module`.
45
+ - Untuk NestJS: `@nestjs/common` dan `@nestjs/core` versi 11 (sudah ada di aplikasi NestJS Anda). Express tidak butuh apa pun dari SDK selain paket ini.
46
+
47
+ Install dengan nomor versi persis:
48
+
49
+ ```bash
50
+ pnpm add @plasgos/auth-verify@<versi> --save-exact
51
+ # atau
52
+ npm install @plasgos/auth-verify@<versi> --save-exact
53
+ ```
54
+
55
+ `@plasgos/auth-shared` dan `jose` ikut terpasang. Aplikasi yang juga memakai `@plasgos/oidc-client` memasang versi yang sama untuk keduanya. Aturan versi, Docker, dan CI ada di [`consumers.md`](consumers.md).
56
+
57
+ **Yang disiapkan bersama tim Plasgos.** Tim Plasgos menyiapkan hal berikut dan menyerahkannya kepada Anda, satu kali untuk sandbox dan satu kali untuk production:
58
+
59
+ | Yang Anda terima | Untuk apa |
60
+ |---|---|
61
+ | Audience API Anda, misalnya `https://api.plasgos.co.id/crm` (production) | `PLASGOS_TOKEN_AUDIENCE`. Aplikasi yang memanggil API Anda meminta token dengan `resource` berisi nilai yang sama |
62
+ | Scope yang memberi akses ke API Anda, misalnya `crm:access` | Persyaratan scope di route ([§7](#7-klaim-wajib-scope-dan-login-terakhir)) |
63
+ | Klaim yang dibawa token untuk audience Anda: `plasgos_public_id` dan `cv` | `requireClaims` ([§7](#7-klaim-wajib-scope-dan-login-terakhir)) |
64
+ | Aturan untuk aplikasi yang memanggil API Anda: client first-party yang meminta token wajib meminta scope `plasgos:public_id` | Tanpa scope itu token tidak membawa `plasgos_public_id`, dan `requireClaims: ["plasgos_public_id", …]` menolak setiap tokennya dengan `401` (`invalid_claims`). Sampaikan aturan ini ke tim aplikasi pemanggil, misalnya BFF Anda ([`bff-express.md` §3](bff-express.md#3-prasyarat)) |
65
+ | Issuer lingkungan itu | `PLASGOS_ISSUER` |
66
+ | Secret webhook, setelah Anda mengirim URL webhook aplikasi | Event `user.*` untuk pencabutan sesi ([§8](#8-pencabutan-sesi-isrevoked), [`webhook.md`](webhook.md)) |
67
+ | Alamat internal server Plasgos, hanya bila API Anda berjalan di jaringan Plasgos | `PLASGOS_BACKCHANNEL_URL` ([§13](#13-alamat-internal-backchannelurl)) |
68
+
69
+ Tidak ada client id atau client secret untuk memverifikasi token. Kredensial hanya dibutuhkan aplikasi yang **meminta** token (lihat [`memulai.md` §6](memulai.md#6-mendapat-kredensial)).
70
+
71
+ ## 3. Env
72
+
73
+ Nama env bebas, tetapi nama di bawah dipakai di semua contoh.
74
+
75
+ | Env | Wajib | Contoh sandbox | Production | Aturan |
76
+ |---|---|---|---|---|
77
+ | `PLASGOS_ENV` | Ya | `sandbox` | `production` | Pengaman: dicocokkan dengan issuer, audience, dan alamat internal |
78
+ | `PLASGOS_ISSUER` | Ya | `https://accounts.sandbox.example` (contoh; host accounts sandbox dari tim Plasgos) | `https://accounts.plasgos.co.id` | Sandbox tidak boleh host production. Production persis nilai itu (satu `/` di akhir dibuang) |
79
+ | `PLASGOS_TOKEN_AUDIENCE` | Ya | `https://api.sandbox.plasgos.co.id/crm` (contoh) | `https://api.plasgos.co.id/crm` (contoh) | Audience dari tim Plasgos, ditulis persis seperti yang diserahkan, termasuk ada atau tidaknya `/` di akhir. Production diawali `https://api.plasgos.co.id/` |
80
+ | `PLASGOS_BACKCHANNEL_URL` | Tidak | `http://plasgos.internal.example:8080` (contoh) | Alamat `https:` dari tim Plasgos | Hanya untuk API di jaringan Plasgos. Sandbox boleh `http:`, tetapi tidak boleh host production. Production wajib `https:`, kecuali `PLASGOS_ALLOW_INSECURE_BACKCHANNEL=true` |
81
+ | `PLASGOS_ALLOW_INSECURE_BACKCHANNEL` | Tidak | Tidak diisi (tidak berpengaruh di sandbox) | `true` hanya untuk alamat `http:` di jaringan privat | Hanya untuk `http:` di jaringan privat yang Anda percaya ([§13](#13-alamat-internal-backchannelurl)) |
82
+
83
+ Kode aplikasi sama di semua lingkungan; yang berbeda hanya nilai env. `PLASGOS_ENV` adalah pengaman, bukan pemilih URL: SDK menolak start bila `environment` tidak cocok dengan issuer, audience, dan alamat internal ([`memulai.md` §5](memulai.md#sandbox-dan-production)).
84
+
85
+ Env milik aplikasi Anda sendiri, misalnya alamat Redis untuk marker pencabutan, tidak dibaca SDK dan boleh bernama apa saja.
86
+
87
+ Pembacaan env, dari `env.ts` ([`memulai.md` §5](memulai.md#5-env-yang-disarankan)):
88
+
89
+ <!-- snippet: examples/snippets/env.ts#token-verifier -->
90
+ ```ts
91
+ /** What an API that verifies Plasgos access tokens reads. */
92
+ export interface TokenVerifierEnv {
93
+ environment: Environment;
94
+ /** PLASGOS_ISSUER: the token's `iss` must equal it. */
95
+ issuer: string;
96
+ /** PLASGOS_TOKEN_AUDIENCE: the audience of this API, given by the Plasgos team; the token's `aud` must equal it. */
97
+ audience: string;
98
+ /** PLASGOS_BACKCHANNEL_URL: optional internal origin for the key set (JWKS), only inside the Plasgos network. */
99
+ backchannelUrl: string | undefined;
100
+ /** PLASGOS_ALLOW_INSECURE_BACKCHANNEL=true: production only, an http: back channel on a private network you trust. */
101
+ allowInsecureBackchannel: boolean;
102
+ }
103
+
104
+ export function readTokenVerifierEnv(): TokenVerifierEnv {
105
+ return {
106
+ environment: readEnvironment(),
107
+ issuer: required("PLASGOS_ISSUER"),
108
+ audience: required("PLASGOS_TOKEN_AUDIENCE"),
109
+ backchannelUrl: optional("PLASGOS_BACKCHANNEL_URL"),
110
+ allowInsecureBackchannel: optional("PLASGOS_ALLOW_INSECURE_BACKCHANNEL") === "true",
111
+ };
112
+ }
113
+ ```
114
+ <!-- /snippet -->
115
+
116
+ ## 4. Membuat verifier
117
+
118
+ Buat verifier **sekali saat aplikasi start**, lalu berikan ke setiap route. Semua opsi diperiksa saat itu juga: bila ada yang salah, `createAccessTokenVerifier` melempar satu `ConfigError` berisi semua masalah, sebelum request pertama.
119
+
120
+ <!-- snippet: examples/snippets/token-verifier.ts#create -->
121
+ ```ts
122
+ /** Create it once at start: a wrong option throws one ConfigError there, before the first request. */
123
+ export function createApiTokenVerifier(store: RevocationStore): AccessTokenVerifier {
124
+ const env = readTokenVerifierEnv();
125
+ return createAccessTokenVerifier({
126
+ environment: env.environment,
127
+ issuer: env.issuer,
128
+ audience: env.audience,
129
+ backchannelUrl: env.backchannelUrl,
130
+ allowInsecureBackchannel: env.allowInsecureBackchannel,
131
+ // Every token must carry the user's public id and credential version.
132
+ requireClaims: ["plasgos_public_id", "cv"],
133
+ // Required for a crm audience: compares the session, the user and cv with the app's markers.
134
+ isRevoked: revocationCheck(store),
135
+ onReject: logReject,
136
+ });
137
+ }
138
+ ```
139
+ <!-- /snippet -->
140
+
141
+ `revocationCheck` ada di [§8](#8-pencabutan-sesi-isrevoked). `logReject` menulis satu baris log untuk setiap token yang ditolak:
142
+
143
+ <!-- snippet: examples/snippets/token-verifier.ts#on-reject -->
144
+ ```ts
145
+ /** One line per refused token. The event never holds the token or a claim value, so it is safe to log. */
146
+ export function logReject(event: AuthRejectEvent): void {
147
+ const line = [
148
+ "plasgos token refused:",
149
+ `env=${event.environment}`,
150
+ `reason=${event.reason}`,
151
+ `client_id=${event.clientId ?? "-"}`,
152
+ `request_id=${event.requestId ?? "-"}`,
153
+ ].join(" ");
154
+ process.stderr.write(`${line}\n`);
155
+ // The key set of Plasgos cannot be read: every request answers 503 until it recovers.
156
+ if (event.reason === "unavailable") process.stderr.write("ALERT plasgos key set unavailable\n");
157
+ }
158
+ ```
159
+ <!-- /snippet -->
160
+
161
+ Pola `createOrExit` di [`memulai.md` §7](memulai.md#7-bila-konfigurasi-salah) juga berlaku: `const verifier = createOrExit(() => createApiTokenVerifier(redis));`.
162
+
163
+ Potongan kode di panduan ini berasal dari file yang lolos typecheck, lengkap dengan import-nya: [`token-verifier.ts`](examples/token-verifier.ts), [`token-express.ts`](examples/token-express.ts), [`token-nestjs.ts`](examples/token-nestjs.ts), [`token-fetch.ts`](examples/token-fetch.ts), [`token-testing.ts`](examples/token-testing.ts), [`token-nestjs-jest.ts`](examples/token-nestjs-jest.ts), [`token-socket.ts`](examples/token-socket.ts), [`user-events.ts`](examples/user-events.ts), [`token-commonjs.cjs`](examples/token-commonjs.cjs) (JavaScript), dan [`env.ts`](examples/env.ts). Import SDK berasal dari `@plasgos/auth-verify`, `@plasgos/auth-verify/express`, dan `@plasgos/auth-verify/nestjs`.
164
+
165
+ ### Opsi `createAccessTokenVerifier`
166
+
167
+ | Opsi | Wajib | Bawaan | Arti |
168
+ |---|---|---|---|
169
+ | `environment` | Ya | — | `"sandbox"` atau `"production"`. Dicocokkan dengan `issuer`, `audience`, dan `backchannelUrl` |
170
+ | `issuer` | Ya | — | Origin issuer, tanpa path (satu `/` di akhir dibuang). Nilai `iss` token harus sama persis. Di production: `https://accounts.plasgos.co.id` |
171
+ | `audience` | Ya | — | Audience API Anda. Nilai `aud` token harus sama persis (string, bukan array). Di production diawali `https://api.plasgos.co.id/` |
172
+ | `backchannelUrl` | Tidak | `issuer` | Alamat internal server Plasgos untuk mengambil kunci (`<backchannelUrl>/oidc/jwks`). Di production wajib `https:` kecuali `allowInsecureBackchannel` ([§13](#13-alamat-internal-backchannelurl)) |
173
+ | `allowInsecureBackchannel` | Tidak | `false` | Hanya berarti di production: menerima `backchannelUrl` `http:` di jaringan privat yang Anda percaya |
174
+ | `allowServiceTokens` | Tidak | `false` | Juga menerima token service (`client_credentials`, tanpa sesi user) ([§12](#12-token-service-allowservicetokens)) |
175
+ | `requireClaims` | Tidak | Tidak ada | Nama klaim yang wajib ada di setiap token, misalnya `["plasgos_public_id", "cv"]`. Paling banyak 16 nama, masing-masing huruf, angka, atau `_` (1–64 karakter) |
176
+ | `clockToleranceSeconds` | Tidak | `30` | Toleransi jam untuk `exp` dan `nbf`, bilangan bulat 0–60 detik |
177
+ | `timeouts.jwksMs` | Tidak | `5000` | Batas waktu mengambil kunci, termasuk membaca body, 1–60000 ms |
178
+ | `jwks` | Tidak | — | Kunci tetap sebagai pengganti pengambilan kunci, untuk test. Hanya sandbox ([§15](#15-menguji-api-anda)) |
179
+ | `allowInsecureHttp` | Tidak | `false` | Hanya sandbox: `issuer` `http:` untuk development lokal |
180
+ | `fetch` | Tidak | `fetch` global | Pengganti `fetch` untuk mengambil kunci, untuk test |
181
+ | `isRevoked` | Untuk audience `/crm` | — | `(principal) => boolean \| Promise<boolean>`. `true` menolak token sebagai `revoked` ([§8](#8-pencabutan-sesi-isrevoked)). Wajib bila path audience adalah `/crm` |
182
+ | `onReject` | Tidak | — | Dipanggil sekali untuk setiap token yang ditolak, dengan `{ environment, reason, clientId, requestId }`. Exception di hook diabaikan |
183
+
184
+ ### Yang dikembalikan
185
+
186
+ | Anggota | Arti |
187
+ |---|---|
188
+ | `environment`, `issuer`, `audience` | Nilai konfigurasi (hanya baca) |
189
+ | `verifyAuthorization(header, options?)` | Memeriksa nilai header `Authorization`. Mengembalikan principal ([§6](#6-siapa-pemanggilnya-accessprincipal)), atau menolak dengan `AuthVerifyError` |
190
+ | `verifyRequest(request, options?)` | Sama, untuk Web `Request`. Juga membaca `X-Request-Id` untuk event `onReject` |
191
+
192
+ `options` (per route, ditambahkan ke opsi verifier):
193
+
194
+ | Opsi | Arti |
195
+ |---|---|
196
+ | `scopes` | Scope yang wajib dimiliki token, semuanya. Bila kurang: `insufficient_scope` (`403`) |
197
+ | `requireClaims` | Klaim tambahan yang wajib ada, ditambahkan ke `requireClaims` milik verifier. Bila kurang: `invalid_claims` (`401`) |
198
+ | `maxAuthAge` | Umur login user paling lama, dalam detik (`now − auth_time`). Bila lebih: `stale_auth` (`401`) |
199
+ | `requestId` | Id request untuk event `onReject`, bila Anda memanggil `verifyAuthorization` sendiri |
200
+ | `now` | Waktu sekarang dalam milidetik epoch, untuk test |
201
+
202
+ ## 5. Yang diperiksa, berurutan
203
+
204
+ Setiap token diperiksa dengan urutan berikut. Kegagalan pertama yang ditemukan yang dilaporkan, sebagai `AuthVerifyError` dengan `reason`:
205
+
206
+ 1. Header `Authorization` ada dan diawali `Bearer ` (huruf besar atau kecil). Bila tidak: `missing_token`.
207
+ 2. Isinya sebuah JWT (tiga bagian base64url), paling panjang 8 KiB. Bila tidak: `malformed_token`.
208
+ 3. Header JWT: `alg` harus `RS256` dan `kid` harus ada, bila tidak `unknown_key`; `typ` harus `at+jwt`, bila tidak `invalid_claims`. Token `alg: none` dan HS256 ditolak di sini, sebelum ada kunci yang dipakai.
209
+ 4. Kunci dengan `kid` itu ada di JWKS Plasgos. Bila tidak ada setelah satu kali ambil ulang: `unknown_key`. Bila JWKS tidak bisa dibaca: `unavailable`.
210
+ 5. Tanda tangan, `iss`, dan `aud`: bila salah, `invalid_token`. `exp` dan `nbf` dengan toleransi `clockToleranceSeconds`: bila lewat, `expired_token`.
211
+ 6. Bentuk klaim (`sub`, `client_id`, `sid`, `auth_time`, `cv`, `plasgos_public_id`, `scope`) dan `requireClaims`. Bila salah atau kurang: `invalid_claims`.
212
+ 7. `isRevoked`. Bila mengembalikan `true`: `revoked`.
213
+ 8. Scope route. Bila kurang: `insufficient_scope`.
214
+ 9. `maxAuthAge` route. Bila login terlalu lama: `stale_auth`.
215
+
216
+ Jawaban HTTP-nya sudah ada di error itu (`status`, `errorCode`, `wwwAuthenticate`), dan adapter Express, NestJS, dan `authErrorResponse` menulisnya untuk Anda:
217
+
218
+ | `reason` | Status | `WWW-Authenticate` | Body |
219
+ |---|---|---|---|
220
+ | `missing_token` | `401` | `Bearer` | `{"error":"invalid_token"}` |
221
+ | `malformed_token`, `unknown_key`, `expired_token`, `invalid_token`, `invalid_claims`, `revoked` | `401` | `Bearer error="invalid_token"` | `{"error":"invalid_token"}` |
222
+ | `insufficient_scope` | `403` | `Bearer error="insufficient_scope", scope="<scope route>"` | `{"error":"insufficient_scope"}` |
223
+ | `stale_auth` | `401` | `Bearer error="insufficient_user_authentication", max_age=<detik>` | `{"error":"insufficient_user_authentication"}` |
224
+ | `unavailable` | `503` | Tidak ada | `{"error":"temporarily_unavailable"}` |
225
+
226
+ Hal yang perlu diketahui:
227
+
228
+ - **Jam server.** `exp` dan `nbf` diberi toleransi 30 detik (bawaan). `exp` bersifat eksklusif: token yang `exp`-nya tepat 30 detik lalu sudah ditolak. Pastikan jam server sinkron (NTP).
229
+ - **Rotasi kunci.** Kunci disimpan di cache selama 10 menit. Token dengan `kid` baru membuat SDK mengambil JWKS sekali lagi (paling sering sekali per 30 detik), jadi rotasi kunci Plasgos tidak butuh tindakan Anda.
230
+ - **Pengambilan kunci dibatasi.** Redirect tidak diikuti, body paling besar 64 KiB, jawaban selain `200` ditolak, dan batas waktunya `timeouts.jwksMs`. Semua kegagalan itu menjadi `unavailable` (`503`), bukan `401`, supaya gangguan sebentar di Plasgos tidak membuat semua client login ulang.
231
+
232
+ ## 6. Siapa pemanggilnya: `AccessPrincipal`
233
+
234
+ Token yang lolos menghasilkan principal. Tanpa `allowServiceTokens`, principal selalu `UserAccessPrincipal`:
235
+
236
+ | Field | Isi |
237
+ |---|---|
238
+ | `kind` | `"user"` |
239
+ | `subject` | `sub`: id user yang **pairwise**, berbeda untuk setiap client yang memanggil API Anda |
240
+ | `clientId` | `client_id`: aplikasi yang meminta token |
241
+ | `sessionId` | `sid`: sesi user di Plasgos |
242
+ | `authTime` | `auth_time`: waktu user terakhir login, detik epoch |
243
+ | `credentialVersion` | `cv`: versi kredensial user saat token diterbitkan, atau `null` bila token tidak membawanya |
244
+ | `scopes` | Scope yang disetujui, dari klaim `scope` |
245
+ | `claims` | Seluruh payload token yang sudah diverifikasi, dibekukan. `claims.plasgos_public_id` bertipe `string \| undefined` |
246
+
247
+ Dengan `allowServiceTokens: true` principal juga bisa `ServiceAccessPrincipal` (`kind: "service"`, `subject`, `clientId`, `scopes`, `claims`), lihat [§12](#12-token-service-allowservicetokens).
248
+
249
+ **Kenali user dari `claims.plasgos_public_id`, bukan dari `subject`.** `subject` berbeda untuk setiap client: user yang sama yang memanggil API Anda lewat aplikasi web dan lewat aplikasi mobile datang dengan dua `subject`. `plasgos_public_id` (`usr-…`) sama di semua aplikasi. API yang dipanggil lebih dari satu client mewajibkan klaim itu (`requireClaims`) dan memakainya sebagai kunci user:
250
+
251
+ <!-- snippet: examples/snippets/token-verifier.ts#identity -->
252
+ ```ts
253
+ /** The caller as this API knows it. */
254
+ export interface Caller {
255
+ /** The user's public id (`usr-…`): the same in every app, so it is the user key of this API. */
256
+ publicId: string;
257
+ /** The Plasgos session (`sid`). */
258
+ sessionId: string;
259
+ /** The credential version (`cv`) the token was issued with. */
260
+ credentialVersion: number;
261
+ }
262
+
263
+ /**
264
+ * The caller of a verified token. `principal.subject` is pairwise (a different value for every client
265
+ * that calls this API), so the user is identified by `claims.plasgos_public_id`, never by `subject`.
266
+ */
267
+ export function callerOf(principal: AccessPrincipal): Caller {
268
+ if (principal.kind !== "user") throw new Error("this API accepts user tokens only");
269
+ const publicId = principal.claims.plasgos_public_id;
270
+ const credentialVersion = principal.credentialVersion;
271
+ // requireClaims: ["plasgos_public_id", "cv"] guarantees both; the check narrows the types.
272
+ if (publicId === undefined || credentialVersion === null) {
273
+ throw new Error("the verifier must require plasgos_public_id and cv");
274
+ }
275
+ return { publicId, sessionId: principal.sessionId, credentialVersion };
276
+ }
277
+ ```
278
+ <!-- /snippet -->
279
+
280
+ `credentialVersion` bertipe `number | null` karena `cv` opsional untuk audience lain. Dengan `requireClaims: ["cv"]` (atau audience `/crm`) nilainya selalu angka, dan pemeriksaan `=== null` di atas cukup untuk mempersempit tipenya.
281
+
282
+ ## 7. Klaim wajib, scope, dan login terakhir
283
+
284
+ **Klaim wajib (`requireClaims`).** Ada dua tingkat yang saling menambah: opsi verifier (berlaku di setiap route) dan opsi per route (`requirePlasgosToken(verifier, { requireClaims })`, atau `options.requireClaims`). Sebuah klaim dianggap ada bila ada di payload, bukan `null`, dan bukan string kosong. Klaim yang kurang menghasilkan `invalid_claims` (`401`), sebelum `isRevoked` dipanggil.
285
+
286
+ **`cv` selalu wajib untuk audience `/crm`.** Bila path audience Anda adalah `/crm` (dengan atau tanpa `/` di akhir), token user tanpa `cv` selalu ditolak, apa pun isi `requireClaims`, dan `isRevoked` wajib diisi. `cv` yang tidak pernah dibandingkan berarti pemeriksaan pencabutan diam-diam tidak berjalan. Untuk audience lain `cv` opsional, kecuali Anda mewajibkannya.
287
+
288
+ **Scope.** Scope adalah persyaratan route: token harus memiliki semua scope yang diminta, bila tidak `insufficient_scope` (`403`) dengan `scope="…"` di `WWW-Authenticate`. Scope `crm:access` hanya bisa diminta aplikasi first-party Plasgos ([`memulai.md` §4](memulai.md#4-daftar-scope)).
289
+
290
+ **Login terakhir (`maxAuthAge`).** Untuk aksi sensitif (ekspor data, mengganti pemilik, menghapus), minta login yang baru: `maxAuthAge: 600` menolak token yang login user-nya lebih dari 10 menit lalu dengan `401` dan `WWW-Authenticate: Bearer error="insufficient_user_authentication", max_age=600`. Aplikasi pemanggil (BFF) membaca `max_age`, lalu memulai login ulang dengan `startLogin({ returnTo, maxAge: 600 })` ([`login-web.md` §10](login-web.md#10-login-ulang-untuk-aksi-sensitif)). Token service tidak punya waktu login, jadi selalu ditolak oleh `maxAuthAge`.
291
+
292
+ ## 8. Pencabutan sesi (`isRevoked`)
293
+
294
+ Tanpa `isRevoked`, token yang sudah diterbitkan tetap diterima sampai `exp`-nya lewat, walaupun user sudah logout di semua perangkat, sudah mengganti password, atau sudah diblokir. Untuk API yang menyimpan data penting, itu terlalu lama.
295
+
296
+ Dengan `isRevoked`, API Anda menyimpan **marker** di penyimpanan cepat miliknya (misalnya Redis) dan memeriksanya di setiap request:
297
+
298
+ | Marker | Diisi saat | Token ditolak bila |
299
+ |---|---|---|
300
+ | Sesi dicabut | Plasgos mengirim event bahwa sebuah sesi (`sid`) dicabut, misalnya `user.session_revoked` | `principal.sessionId` punya marker |
301
+ | User diblokir | Plasgos mengirim event perubahan status user, misalnya `user.status_changed` | `plasgos_public_id` punya marker |
302
+ | Versi kredensial | Plasgos mengirim event bahwa kredensial user berubah, misalnya `user.credentials_revoked`, dengan versi barunya | Versi yang tersimpan lebih besar dari `cv` token |
303
+
304
+ Marker diisi oleh penerima webhook aplikasi Anda: satu endpoint dengan `presets.appEvents` menerima semua event `user.*` ([`webhook.md` §6](webhook.md#satu-endpoint-untuk-semua-event-aplikasi)). Isi `data` ketiga event itu adalah kontrak event aplikasi yang diterbitkan Plasgos:
305
+
306
+ | Event | Kapan | `data` |
307
+ |---|---|---|
308
+ | `user.credentials_revoked` | Versi kredensial user naik: keluar dari semua sesi, ganti atau reset password, dicabut admin, akun diblokir, staff dinonaktifkan, atau hash password diperbarui | `user` (id publik `usr-…`), `credential_version` (bilangan bulat, versi baru, sama dengan klaim `cv` token baru), `reason` (`all_revoked`, `password_changed`, `password_reset`, `admin_revoked`, `status_blocked`, `staff_disabled`, `password_rehash`) |
309
+ | `user.session_revoked` | Satu sesi Plasgos berakhir (logout, atau dicabut user) dan sesi itu pernah memberi token ke aplikasi Anda | `user`, `sid` (sama dengan klaim `sid` token), `reason` (`logout`, `user_revoked`) |
310
+ | `user.status_changed` | Status user berubah, atau tautan user ke aplikasi Anda dicabut atau dipulihkan | `user`, `status` (`active`, `pending`, `suspended`, `banned`, `unlinked`) |
311
+
312
+ Cara menulis markernya:
313
+
314
+ - **Versi kredensial** (`user.credentials_revoked`): simpan sebagai **nilai terbesar** dari yang tersimpan dan yang baru, dalam satu langkah atomik (compare-and-set, misalnya skrip Lua di Redis). Event milik satu user bisa datang tidak berurutan; `SET` biasa bisa menurunkan versi dan meloloskan lagi token yang sudah dicabut. Beri TTL 1 jam: jauh lebih lama dari umur access token Plasgos, jadi saat marker hilang semua token yang diterbitkan sebelum event itu sudah kedaluwarsa.
315
+ - **Sesi dicabut** (`user.session_revoked`): marker untuk `sid` itu, TTL 1 jam dengan alasan yang sama.
316
+ - **User diblokir** (`user.status_changed`): status selain `active` memblokir user, `active` membuka blokirnya. Simpan status secara permanen di database Anda (di transaksi yang sama dengan id event, [`webhook.md` §7](webhook.md#7-dedup-di-transaksi-yang-sama)), lalu cache di Redis tanpa TTL selama user diblokir. Bila Redis Anda bisa kehilangan datanya, isi ulang marker blokir dari database.
317
+ - Data event yang rusak dilempar sebagai error: kiriman dijawab `500` dan Plasgos mengirim ulang, jadi pencabutan tidak hilang diam-diam.
318
+
319
+ Handler `user` untuk `routeByType` ([`webhook.md` §6](webhook.md#satu-endpoint-untuk-semua-event-aplikasi)) yang menulis ketiga marker:
320
+
321
+ <!-- snippet: examples/snippets/user-events.ts#user-events -->
322
+ ```ts
323
+ /** The Redis commands the marker writer uses. An ioredis client fits it. */
324
+ export interface MarkerRedis {
325
+ eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
326
+ set(key: string, value: string, mode: "EX", seconds: number): Promise<unknown>;
327
+ set(key: string, value: string): Promise<unknown>;
328
+ del(key: string): Promise<number>;
329
+ }
330
+
331
+ /**
332
+ * The credential-version and session markers live 1 hour: much longer than a Plasgos access token, so
333
+ * every token issued before the event has expired before its marker does.
334
+ */
335
+ export const MARKER_TTL_SECONDS = 3_600;
336
+
337
+ /**
338
+ * Stores the larger of the stored and the new credential version (compare-and-set in one Redis step).
339
+ * Events of one user can arrive out of order; a plain SET could lower the version and let a revoked
340
+ * token through again.
341
+ */
342
+ const RAISE_TO_MAX = `
343
+ local current = tonumber(redis.call("GET", KEYS[1]))
344
+ if current == nil or tonumber(ARGV[1]) > current then
345
+ redis.call("SET", KEYS[1], ARGV[1], "EX", tonumber(ARGV[2]))
346
+ end
347
+ return 0`;
348
+
349
+ /** The user.* event data, the published contract of the app events (`data` of the event body). */
350
+ interface UserEventData {
351
+ /** The user's public id (`usr-…`), the same value as the token's plasgos_public_id. */
352
+ user: string;
353
+ /** user.credentials_revoked: the user's new credential version (the token claim `cv`). */
354
+ credential_version?: number;
355
+ /** user.session_revoked: the revoked Plasgos session, the same value as the token claim `sid`. */
356
+ sid?: string;
357
+ /** user.status_changed: active, pending, suspended, banned or unlinked. */
358
+ status?: string;
359
+ }
360
+
361
+ const isText = (value: unknown): value is string => typeof value === "string" && value !== "" && value.length <= 128;
362
+
363
+ /** The event's `data`, checked. A malformed one throws: the delivery fails (500) and Plasgos sends it again. */
364
+ function userDataOf(event: VerifiedWebhook): UserEventData {
365
+ const data = event.body["data"];
366
+ if (typeof data !== "object" || data === null) throw new Error(`user event ${event.id}: data is not an object`);
367
+ const fields = data as Record<string, unknown>;
368
+ const user = fields["user"];
369
+ if (!isText(user)) throw new Error(`user event ${event.id}: data.user is missing`);
370
+ const version = fields["credential_version"];
371
+ const sid = fields["sid"];
372
+ const status = fields["status"];
373
+ return {
374
+ user,
375
+ ...(typeof version === "number" && Number.isSafeInteger(version) ? { credential_version: version } : {}),
376
+ ...(isText(sid) ? { sid } : {}),
377
+ ...(isText(status) ? { status } : {}),
378
+ };
379
+ }
380
+
381
+ /**
382
+ * The `user` handler of routeByType (webhook.md §6): writes the revocation markers that isRevoked reads.
383
+ * - user.credentials_revoked → the credential version, stored as the maximum, TTL 1 hour;
384
+ * - user.session_revoked → the session marker, TTL 1 hour;
385
+ * - user.status_changed → the status is persisted in the app's database (same transaction as the
386
+ * event id) and cached in Redis: any status other than "active" sets the blocked marker, "active"
387
+ * removes it. Refill the blocked markers from the database if your Redis can lose its data.
388
+ * A user.* type the app does not know has no effect.
389
+ */
390
+ export function userEventHandler(redis: MarkerRedis): ApplyEvent {
391
+ return async (tx: Tx, event: VerifiedWebhook) => {
392
+ const data = userDataOf(event);
393
+ switch (event.type) {
394
+ case "user.credentials_revoked": {
395
+ if (data.credential_version === undefined) throw new Error(`user event ${event.id}: data.credential_version is missing`);
396
+ const key = revocationKeys.credentialVersion(data.user);
397
+ await redis.eval(RAISE_TO_MAX, 1, key, data.credential_version, MARKER_TTL_SECONDS);
398
+ return;
399
+ }
400
+ case "user.session_revoked": {
401
+ if (data.sid === undefined) throw new Error(`user event ${event.id}: data.sid is missing`);
402
+ await redis.set(revocationKeys.session(data.sid), "1", "EX", MARKER_TTL_SECONDS);
403
+ return;
404
+ }
405
+ case "user.status_changed": {
406
+ if (data.status === undefined) throw new Error(`user event ${event.id}: data.status is missing`);
407
+ // The lasting record. sequence keeps an older event from overwriting a newer status.
408
+ const sequence = typeof event.body["sequence"] === "number" ? event.body["sequence"] : 0;
409
+ const stored = await tx.query(
410
+ `INSERT INTO plasgos_user_status (public_id, status, sequence) VALUES ($1, $2, $3)
411
+ ON CONFLICT (public_id) DO UPDATE SET status = EXCLUDED.status, sequence = EXCLUDED.sequence
412
+ WHERE plasgos_user_status.sequence < EXCLUDED.sequence`,
413
+ [data.user, data.status, sequence],
414
+ );
415
+ if (stored.rowCount !== 1) return;
416
+ // The cache isRevoked reads, without an expiry: it holds as long as the user is blocked.
417
+ if (data.status === "active") await redis.del(revocationKeys.blockedUser(data.user));
418
+ else await redis.set(revocationKeys.blockedUser(data.user), data.status);
419
+ return;
420
+ }
421
+ default:
422
+ return;
423
+ }
424
+ };
425
+ }
426
+ ```
427
+ <!-- /snippet -->
428
+
429
+ Pemeriksaannya di API, sebagai `isRevoked`:
430
+
431
+ <!-- snippet: examples/snippets/token-verifier.ts#revocation -->
432
+ ```ts
433
+ /** The part of a key-value store the check reads. An ioredis or node-redis client fits it. */
434
+ export interface RevocationStore {
435
+ get(key: string): Promise<string | null>;
436
+ }
437
+
438
+ /** Thrown when the marker store cannot be read. The app's error handler answers it with 503. */
439
+ export class RevocationStoreUnavailableError extends Error {
440
+ constructor(options?: ErrorOptions) {
441
+ super("revocation store unavailable", options);
442
+ this.name = "RevocationStoreUnavailableError";
443
+ }
444
+ }
445
+
446
+ /**
447
+ * The app's own marker keys (the prefix is yours). Your webhook receiver writes them from the user.*
448
+ * events Plasgos sends to your app's webhook endpoint.
449
+ */
450
+ export const revocationKeys = {
451
+ /** The newest credential version Plasgos announced for the user, as text ("3"). */
452
+ credentialVersion: (publicId: string): string => `myapp:revocation:cv:${publicId}`,
453
+ /** Present when the Plasgos session (`sid`) was revoked. */
454
+ session: (sessionId: string): string => `myapp:revocation:sid:${sessionId}`,
455
+ /** Present while the user is blocked. */
456
+ blockedUser: (publicId: string): string => `myapp:revocation:blocked:${publicId}`,
457
+ };
458
+
459
+ /**
460
+ * The `isRevoked` hook: true refuses the token as `revoked` (401). Three checks:
461
+ * - the session was revoked (logout everywhere, a removed device);
462
+ * - the user is blocked;
463
+ * - the user's credentials changed after the token was issued (stored version above the token's `cv`).
464
+ *
465
+ * Without such a hook a token stays valid until it expires. When the store cannot be read the hook
466
+ * throws: the request fails with 503 instead of letting a revoked token through, and without a 401
467
+ * that would send every client to log in again because of an outage.
468
+ */
469
+ export function revocationCheck(store: RevocationStore): (principal: UserAccessPrincipal) => Promise<boolean> {
470
+ return async (principal) => {
471
+ const publicId = principal.claims.plasgos_public_id;
472
+ const tokenVersion = principal.credentialVersion;
473
+ // requireClaims: ["plasgos_public_id", "cv"] already refuses such a token; the hook stays safe alone.
474
+ if (publicId === undefined || tokenVersion === null) return true;
475
+
476
+ let markers: (string | null)[];
477
+ try {
478
+ markers = await Promise.all([
479
+ store.get(revocationKeys.session(principal.sessionId)),
480
+ store.get(revocationKeys.blockedUser(publicId)),
481
+ store.get(revocationKeys.credentialVersion(publicId)),
482
+ ]);
483
+ } catch (error) {
484
+ // Never swallowed: an unreadable store must not count as "not revoked".
485
+ throw new RevocationStoreUnavailableError({ cause: error });
486
+ }
487
+ const [revokedSession, blocked, storedVersion] = markers;
488
+ if (revokedSession !== null || blocked !== null) return true;
489
+ if (storedVersion === null || storedVersion === undefined) return false;
490
+ const stored = Number(storedVersion);
491
+ // A marker this app did not write is a store problem, not a token problem.
492
+ if (!Number.isSafeInteger(stored)) throw new RevocationStoreUnavailableError();
493
+ return stored > tokenVersion;
494
+ };
495
+ }
496
+ ```
497
+ <!-- /snippet -->
498
+
499
+ Aturannya:
500
+
501
+ - `isRevoked` hanya dipanggil untuk token yang lolos tanda tangan, `iss`, `aud`, `exp`, dan klaim wajib. Hasil `true` ditolak sebagai `revoked` (`401`), sebelum pemeriksaan scope.
502
+ - Hook boleh mengembalikan `boolean` atau `Promise<boolean>`. Nilai lain menjadi `TypeError("isRevoked must return a boolean")`.
503
+ - **Bila penyimpanan marker tidak bisa dibaca, lempar error.** Jangan kembalikan `false`. Error yang dilempar hook tidak diubah SDK menjadi `401`: ia diteruskan ke error handler Anda (Express: `next(error)`, NestJS: exception filter), yang menjawab `503`. Dengan begitu token yang sudah dicabut tidak lolos saat Redis mati, dan client tidak disuruh login ulang karena gangguan di sisi Anda.
504
+ - Hook dipanggil di setiap request yang membawa token, jadi buat cepat: satu round trip ke penyimpanan (`Promise.all`), tanpa panggilan ke Plasgos.
505
+
506
+ ## 9. Express
507
+
508
+ `requirePlasgosToken(verifier, requirements)` membuat middleware untuk Express 4 dan 5. Di aplikasi CommonJS: `const { requirePlasgosToken, principalOf } = require("@plasgos/auth-verify/express")`. Di ESM atau TypeScript: `import { requirePlasgosToken, principalOf } from "@plasgos/auth-verify/express"`. Verifier-nya dari `require("@plasgos/auth-verify")` atau `import`, dengan cara yang sama.
509
+
510
+ <!-- snippet: examples/snippets/token-express.ts#app -->
511
+ ```ts
512
+ /** The verifier comes from createApiTokenVerifier, created once at start. Tests pass their own. */
513
+ export function createApp(verifier: AccessTokenVerifier): Express {
514
+ const app = express();
515
+ app.use(express.json({ limit: "100kb" }));
516
+
517
+ // Created once, used by many routes. The requirements are checked here: a wrong one throws TypeError.
518
+ // requireClaims repeats the verifier's list: harmless, and the routes stay safe if the verifier changes.
519
+ const requireToken = requirePlasgosToken(verifier, {
520
+ scopes: ["crm:access"],
521
+ requireClaims: ["plasgos_public_id", "cv"],
522
+ });
523
+ // A sensitive action also needs a login of at most 10 minutes ago (else 401 with max_age=600).
524
+ const requireRecentLogin = requirePlasgosToken(verifier, { scopes: ["crm:access"], maxAuthAge: 600 });
525
+
526
+ app.get("/api/contacts", requireToken, (req, res) => {
527
+ const caller = callerOf(principalOf(req));
528
+ res.json({ owner: caller.publicId, contacts: [] });
529
+ });
530
+
531
+ app.post("/api/contacts/export", requireRecentLogin, (req, res) => {
532
+ const caller = callerOf(principalOf(req));
533
+ res.status(202).json({ owner: caller.publicId, queued: true });
534
+ });
535
+
536
+ app.use(apiErrors);
537
+ return app;
538
+ }
539
+ ```
540
+ <!-- /snippet -->
541
+
542
+ Error handler aplikasi, dipasang setelah route:
543
+
544
+ <!-- snippet: examples/snippets/token-express.ts#errors -->
545
+ ```ts
546
+ /**
547
+ * The app's error handler, registered after the routes. A token the SDK refuses never gets here: the
548
+ * middleware answers 401, 403 or 503 itself. What gets here is the app's own errors, for example the
549
+ * marker store being down inside isRevoked: 503, because the token itself may be fine.
550
+ */
551
+ function apiErrors(error: unknown, _req: Request, res: Response, next: NextFunction): void {
552
+ if (res.headersSent) {
553
+ next(error);
554
+ return;
555
+ }
556
+ if (error instanceof RevocationStoreUnavailableError) {
557
+ res.setHeader("Retry-After", "5");
558
+ res.status(503).json({ error: "temporarily_unavailable" });
559
+ return;
560
+ }
561
+ res.status(500).json({ error: "internal_error" });
562
+ }
563
+ ```
564
+ <!-- /snippet -->
565
+
566
+ Perilaku middleware:
567
+
568
+ | Hasil | Yang terjadi |
569
+ |---|---|
570
+ | Token diterima | `req.plasgosPrincipal` diisi, lalu `next()`. Baca dengan `principalOf(req)` |
571
+ | `AuthVerifyError` | Middleware menjawab sendiri: status, `Cache-Control: no-store`, `WWW-Authenticate` bila ada, dan `{"error":"<errorCode>"}`. Handler route tidak dipanggil. Bila header respons sudah terkirim, atau method respons melempar error, middleware memanggil `next(error)` |
572
+ | Error lain (misalnya dari `isRevoked`) | `next(error)`: error handler Anda yang menjawab |
573
+
574
+ - `requirements` diperiksa saat middleware dibuat. Scope atau nama klaim yang salah melempar `TypeError` saat start.
575
+ - Buat middleware sekali (di luar handler) dan pakai di banyak route. Untuk satu router: `router.use(requireToken)`.
576
+ - `principalOf(req)` di route tanpa middleware melempar `Error` (bug wiring, dijawab `500`).
577
+ - Middleware tidak pernah mengembalikan promise dan menangkap semua kegagalannya sendiri, jadi Express 4 maupun 5 tidak meninggalkan rejection yang tak tertangani.
578
+ - Selalu isi `scopes`. Tanpa scope, setiap token yang sah untuk audience Anda lolos, termasuk token yang diminta untuk keperluan lain.
579
+
580
+ ### CommonJS JavaScript
581
+
582
+ Aplikasi CommonJS JavaScript (tanpa `"type"` di `package.json`, dengan `require` biasa) memakai paket yang sama tanpa flag. Contoh di panduan ini TypeScript; versi JavaScript-nya sama tanpa tipe. Contoh lengkap, satu route dengan pemeriksaan pencabutan dan error handler:
583
+
584
+ <!-- snippet: examples/snippets/token-commonjs.cjs#commonjs -->
585
+ ```js
586
+ "use strict";
587
+ // CommonJS JavaScript (no "type" in package.json, plain require), Express 4 or 5.
588
+ const express = require("express");
589
+ const { createAccessTokenVerifier } = require("@plasgos/auth-verify");
590
+ const { principalOf, requirePlasgosToken } = require("@plasgos/auth-verify/express");
591
+
592
+ /** @param {string} name */
593
+ function requiredEnv(name) {
594
+ const value = process.env[name];
595
+ if (value === undefined || value.trim() === "") throw new Error(`${name} is not set`);
596
+ return value.trim();
597
+ }
598
+
599
+ /** @returns {"sandbox" | "production"} */
600
+ function readEnvironment() {
601
+ const value = requiredEnv("PLASGOS_ENV");
602
+ if (value !== "sandbox" && value !== "production") throw new Error('PLASGOS_ENV must be "sandbox" or "production"');
603
+ return value;
604
+ }
605
+
606
+ /** Thrown when the marker store cannot be read; the error handler answers 503. */
607
+ class RevocationStoreUnavailableError extends Error {}
608
+
609
+ /**
610
+ * The marker check of verifikasi-token.md §8 in JavaScript: a revoked session, a blocked user, or a
611
+ * credential version above the token's cv refuses the token. A store error is thrown, never "false".
612
+ * @param {{ get(key: string): Promise<string | null> }} store an ioredis client fits it
613
+ * @returns {(principal: import("@plasgos/auth-verify").UserAccessPrincipal) => Promise<boolean>}
614
+ */
615
+ function revocationCheck(store) {
616
+ return async (principal) => {
617
+ const publicId = principal.claims.plasgos_public_id;
618
+ const tokenVersion = principal.credentialVersion;
619
+ if (publicId === undefined || tokenVersion === null) return true;
620
+ /** @type {(string | null)[]} */
621
+ let markers;
622
+ try {
623
+ markers = await Promise.all([
624
+ store.get(`myapp:revocation:sid:${principal.sessionId}`),
625
+ store.get(`myapp:revocation:blocked:${publicId}`),
626
+ store.get(`myapp:revocation:cv:${publicId}`),
627
+ ]);
628
+ } catch (error) {
629
+ throw new RevocationStoreUnavailableError("revocation store unavailable", { cause: error });
630
+ }
631
+ const [revokedSession, blocked, storedVersion] = markers;
632
+ if (revokedSession !== null || blocked !== null) return true;
633
+ if (storedVersion === null || storedVersion === undefined) return false;
634
+ const stored = Number(storedVersion);
635
+ if (!Number.isSafeInteger(stored)) throw new RevocationStoreUnavailableError("revocation store unavailable");
636
+ return stored > tokenVersion;
637
+ };
638
+ }
639
+
640
+ /**
641
+ * The app with one protected route. Create it once at start: a wrong option throws one ConfigError.
642
+ * @param {{ get(key: string): Promise<string | null> }} store
643
+ * @returns {import("express").Express}
644
+ */
645
+ function createCrmApp(store) {
646
+ const verifier = createAccessTokenVerifier({
647
+ environment: readEnvironment(),
648
+ issuer: requiredEnv("PLASGOS_ISSUER"),
649
+ audience: requiredEnv("PLASGOS_TOKEN_AUDIENCE"),
650
+ requireClaims: ["plasgos_public_id", "cv"],
651
+ isRevoked: revocationCheck(store),
652
+ });
653
+
654
+ const app = express();
655
+ const requireToken = requirePlasgosToken(verifier, { scopes: ["crm:access"], requireClaims: ["plasgos_public_id", "cv"] });
656
+
657
+ app.get("/v2/crm/contacts", requireToken, (req, res) => {
658
+ res.json({ owner: principalOf(req).claims.plasgos_public_id, contacts: [] });
659
+ });
660
+
661
+ /** @type {import("express").ErrorRequestHandler} */
662
+ const apiErrors = (error, _req, res, next) => {
663
+ if (res.headersSent) {
664
+ next(error);
665
+ return;
666
+ }
667
+ if (error instanceof RevocationStoreUnavailableError) {
668
+ res.setHeader("Retry-After", "5");
669
+ res.status(503).json({ error: "temporarily_unavailable" });
670
+ return;
671
+ }
672
+ res.status(500).json({ error: "internal_error" });
673
+ };
674
+ app.use(apiErrors);
675
+ return app;
676
+ }
677
+
678
+ module.exports = { createCrmApp, revocationCheck };
679
+ ```
680
+ <!-- /snippet -->
681
+
682
+ Untuk memakai file contoh TypeScript lain dari JavaScript, hapus tipenya, atau kompilasi sekali dengan `tsc` (`module` dan `moduleResolution` `node16`) lalu salin hasilnya.
683
+
684
+ ### Socket
685
+
686
+ API yang juga melayani socket (misalnya Socket.IO di server Express yang sama) memeriksa token di handshake, dengan verifier dan scope yang sama. Di belakang BFF, header `Authorization` handshake disisipkan BFF dari sesi user ([`bff-express.md` §14](bff-express.md#14-proxy-socket)).
687
+
688
+ <!-- snippet: examples/snippets/token-socket.ts#socket -->
689
+ ```ts
690
+ /** The parts of a Socket.IO server socket this example uses. A socket.io 4 `Socket` fits it. */
691
+ export interface SocketLike {
692
+ readonly handshake: { readonly headers: IncomingHttpHeaders };
693
+ data: { principal?: UserAccessPrincipal };
694
+ disconnect(close?: boolean): unknown;
695
+ }
696
+
697
+ /**
698
+ * `io.use(socketAuth(verifier))`: checks the Authorization header of the handshake, which the BFF sets
699
+ * from the user's session, with the same verifier and scope as the HTTP routes. The error message
700
+ * reaches the browser as `connect_error`, so it names no reason and no value.
701
+ */
702
+ export function socketAuth(verifier: AccessTokenVerifier) {
703
+ return (socket: SocketLike, next: (error?: Error) => void): void => {
704
+ verifier.verifyAuthorization(socket.handshake.headers.authorization, { scopes: ["crm:access"] }).then(
705
+ (principal) => {
706
+ socket.data.principal = principal;
707
+ next();
708
+ },
709
+ (error: unknown) => {
710
+ // A refused token: the browser renews its session (/auth/me at the BFF) and connects again.
711
+ // Anything else (the marker store is down): try again later.
712
+ next(new Error(error instanceof AuthVerifyError ? "unauthorized" : "unavailable"));
713
+ },
714
+ );
715
+ };
716
+ }
717
+
718
+ /**
719
+ * A socket outlives its token. Every few minutes each open socket's handshake token is verified again:
720
+ * expired, revoked or blocked closes the socket, and the browser connects again through the BFF with
721
+ * the session's current token. A store outage keeps the socket and checks it at the next round.
722
+ * With socket.io: `recheckSockets(verifier, () => io.of("/").sockets.values())`.
723
+ */
724
+ export function recheckSockets(verifier: AccessTokenVerifier, sockets: () => Iterable<SocketLike>, everyMs = 5 * 60_000): () => void {
725
+ const timer = setInterval(() => {
726
+ for (const socket of sockets()) {
727
+ verifier.verifyAuthorization(socket.handshake.headers.authorization, { scopes: ["crm:access"] }).then(
728
+ (principal) => {
729
+ socket.data.principal = principal;
730
+ },
731
+ (error: unknown) => {
732
+ if (error instanceof AuthVerifyError) socket.disconnect(true);
733
+ },
734
+ );
735
+ }
736
+ }, everyMs);
737
+ timer.unref();
738
+ return () => {
739
+ clearInterval(timer);
740
+ };
741
+ }
742
+ ```
743
+ <!-- /snippet -->
744
+
745
+ - `socketAuth` memanggil `verifier.verifyAuthorization(...)` dengan header `Authorization` dari handshake. Token ditolak: koneksi ditolak dengan pesan umum (`unauthorized`), tanpa `reason` atau nilai token. Penyimpanan marker gagal: `unavailable`, dan client mencoba lagi.
746
+ - Socket hidup lebih lama dari token-nya. `recheckSockets` memeriksa ulang token handshake setiap beberapa menit; token yang kedaluwarsa, dicabut, atau user yang diblokir memutus socket itu. Browser lalu menyambung lagi lewat BFF, yang menyisipkan token sesi yang masih berlaku.
747
+ - Event yang dikirim selama socket terputus tidak sampai. Bila itu penting, muat ulang keadaan terbaru setelah tersambung lagi (atau pakai fitur pemulihan koneksi Socket.IO).
748
+
749
+ ## 10. NestJS
750
+
751
+ `@plasgos/auth-verify/nestjs` menyediakan modul global, guard, dan decorator. Daftarkan modulnya sekali di modul utama. Opsinya bisa tetap (`PlasgosAuthModule.forRoot(options)`) atau dari factory (`forRootAsync`), seperti di contoh berikut:
752
+
753
+ <!-- snippet: examples/snippets/token-nestjs.ts#module -->
754
+ ```ts
755
+ /** Injection token of the app's marker store (for example a Redis client). */
756
+ export const REVOCATION_STORE = "REVOCATION_STORE";
757
+
758
+ @Module({})
759
+ export class RevocationStoreModule {
760
+ static register(store: RevocationStore): DynamicModule {
761
+ return {
762
+ module: RevocationStoreModule,
763
+ providers: [{ provide: REVOCATION_STORE, useValue: store }],
764
+ exports: [REVOCATION_STORE],
765
+ };
766
+ }
767
+ }
768
+
769
+ /**
770
+ * The SDK's global module with options from a factory. The factory runs at bootstrap, so a wrong
771
+ * option stops the app with one ConfigError.
772
+ */
773
+ export function plasgosAuthModule(store: RevocationStore): DynamicModule {
774
+ return PlasgosAuthModule.forRootAsync({
775
+ imports: [RevocationStoreModule.register(store)],
776
+ inject: [REVOCATION_STORE],
777
+ useFactory: (revocations: RevocationStore) => {
778
+ const env = readTokenVerifierEnv();
779
+ return {
780
+ environment: env.environment,
781
+ issuer: env.issuer,
782
+ audience: env.audience,
783
+ backchannelUrl: env.backchannelUrl,
784
+ allowInsecureBackchannel: env.allowInsecureBackchannel,
785
+ // Every route of the API: the user's public id and credential version are required.
786
+ requireClaims: ["plasgos_public_id", "cv"],
787
+ isRevoked: revocationCheck(revocations),
788
+ onReject: logReject,
789
+ };
790
+ },
791
+ });
792
+ }
793
+ ```
794
+ <!-- /snippet -->
795
+
796
+ Controller memakai guard dan decorator:
797
+
798
+ <!-- snippet: examples/snippets/token-nestjs.ts#controller -->
799
+ ```ts
800
+ @Controller("api/contacts")
801
+ @UseGuards(PlasgosAccessTokenGuard)
802
+ @RequireScopes("crm:access")
803
+ export class ContactsController {
804
+ @Get()
805
+ list(@PlasgosPrincipal() principal: UserAccessPrincipal): { owner: string; contacts: unknown[] } {
806
+ return { owner: callerOf(principal).publicId, contacts: [] };
807
+ }
808
+
809
+ /** A sensitive action: the user signed in at most 10 minutes ago, else 401 with max_age=600. */
810
+ @Post("export")
811
+ @HttpCode(202)
812
+ @RequireRecentAuth(600)
813
+ exportContacts(@PlasgosPrincipal() principal: UserAccessPrincipal): { owner: string; queued: true } {
814
+ return { owner: callerOf(principal).publicId, queued: true };
815
+ }
816
+ }
817
+ ```
818
+ <!-- /snippet -->
819
+
820
+ Error penyimpanan marker dijawab `503` oleh exception filter:
821
+
822
+ <!-- snippet: examples/snippets/token-nestjs.ts#filter -->
823
+ ```ts
824
+ /** The marker store is down inside isRevoked: 503, because the token itself may be fine. */
825
+ @Catch(RevocationStoreUnavailableError)
826
+ export class RevocationStoreUnavailableFilter implements ExceptionFilter {
827
+ catch(_error: RevocationStoreUnavailableError, host: ArgumentsHost): void {
828
+ const res = host.switchToHttp().getResponse<Response>();
829
+ res.setHeader("Retry-After", "5");
830
+ res.status(503).json({ error: "temporarily_unavailable" });
831
+ }
832
+ }
833
+ ```
834
+ <!-- /snippet -->
835
+
836
+ <!-- snippet: examples/snippets/token-nestjs.ts#app-module -->
837
+ ```ts
838
+ /** NestFactory.create(AppModule.register(redis)): the store is the app's own client. */
839
+ @Module({})
840
+ export class AppModule {
841
+ static register(store: RevocationStore): DynamicModule {
842
+ return {
843
+ module: AppModule,
844
+ imports: [plasgosAuthModule(store)],
845
+ controllers: [ContactsController],
846
+ providers: [{ provide: APP_FILTER, useClass: RevocationStoreUnavailableFilter }],
847
+ };
848
+ }
849
+ }
850
+ ```
851
+ <!-- /snippet -->
852
+
853
+ | Export | Arti |
854
+ |---|---|
855
+ | `PlasgosAuthModule.forRoot(options)` | Modul global dengan opsi tetap (opsi `createAccessTokenVerifier`). Verifier dibuat saat bootstrap, jadi `ConfigError` menghentikan aplikasi saat start |
856
+ | `PlasgosAuthModule.forRootAsync({ imports, inject, useFactory })` | Sama, dengan opsi dari factory (misalnya dari config service) |
857
+ | `PlasgosAccessTokenGuard` | Guard untuk `@UseGuards(...)` atau `APP_GUARD`. Menolak dengan `HttpException({ error }, status)` dan memasang `Cache-Control: no-store` dan `WWW-Authenticate` (Express dan Fastify) |
858
+ | `@RequireScopes(...scopes)` | Scope wajib di class atau method. Scope di class dan method digabung. Tanpa scope sama sekali: `TypeError` |
859
+ | `@RequireRecentAuth(maxAgeSeconds = 600)` | `maxAuthAge` untuk class atau method. Nilai di method mengganti nilai di class |
860
+ | `@PlasgosPrincipal()` | Principal yang diverifikasi guard, sebagai parameter route |
861
+ | `PLASGOS_ACCESS_TOKEN_VERIFIER` | Token injeksi verifier, untuk dipakai sendiri: `@Inject(PLASGOS_ACCESS_TOKEN_VERIFIER)` |
862
+
863
+ - **Selalu pasang `@RequireScopes`** di setiap controller (atau method). Tanpa scope, setiap token yang sah untuk audience Anda lolos, termasuk token yang diminta untuk keperluan lain.
864
+ - `requireClaims` di opsi modul berlaku untuk seluruh API. Tidak ada decorator per route untuk klaim.
865
+ - **Exception filter global.** Filter milik aplikasi yang menangkap semua `HttpException` (misalnya untuk format error seragam) juga menulis ulang body penolakan guard. Status, `Cache-Control`, dan `WWW-Authenticate` tetap, karena dipasang sebelum exception dilempar, tetapi body `{"error":"<errorCode>"}` menjadi format filter Anda. Bila client Anda membaca body itu, biarkan filter meneruskan `exception.getResponse()` apa adanya.
866
+ - Error lain dari verifier (misalnya dari `isRevoked`) diteruskan apa adanya ke exception layer Nest; tanpa filter, Nest menjawab `500`.
867
+ - `@PlasgosPrincipal()` di route tanpa guard melempar `Error` (`500`).
868
+ - Tidak butuh `emitDecoratorMetadata`: semua injeksi SDK memakai token eksplisit.
869
+ - Versi yang didukung: NestJS 11.
870
+
871
+ **Guard untuk seluruh aplikasi.** Daftarkan guard sekali sebagai `APP_GUARD` daripada `@UseGuards` di setiap controller:
872
+
873
+ <!-- snippet: examples/snippets/token-nestjs.ts#global-guard -->
874
+ ```ts
875
+ /**
876
+ * Every route of the app behind the guard: register it once as APP_GUARD instead of @UseGuards on each
877
+ * controller. The SDK has no decorator that opens a route again, so serve health checks and other
878
+ * public routes from a separate app or port. Keep @RequireScopes on every controller: without a scope
879
+ * any valid token for your audience passes.
880
+ */
881
+ @Module({})
882
+ export class GuardedAppModule {
883
+ static register(store: RevocationStore): DynamicModule {
884
+ return {
885
+ module: GuardedAppModule,
886
+ imports: [plasgosAuthModule(store)],
887
+ controllers: [ContactsController],
888
+ providers: [
889
+ { provide: APP_GUARD, useClass: PlasgosAccessTokenGuard },
890
+ { provide: APP_FILTER, useClass: RevocationStoreUnavailableFilter },
891
+ ],
892
+ };
893
+ }
894
+ }
895
+ ```
896
+ <!-- /snippet -->
897
+
898
+ Dengan `APP_GUARD`, **setiap** route butuh token. SDK tidak punya decorator untuk membuka route kembali, jadi layani health check dan route publik lain dari aplikasi atau port terpisah. `@RequireScopes` tetap dipasang di setiap controller.
899
+
900
+ ## 11. Server berbasis `Request`
901
+
902
+ Untuk server yang memakai Web `Request` dan `Response` (React Router, Hono, Next.js route handler, dan sejenisnya), pakai `verifyRequest` dan `authErrorResponse`:
903
+
904
+ <!-- snippet: examples/snippets/token-fetch.ts#route -->
905
+ ```ts
906
+ /** GET /api/contacts in a server built on Request and Response (React Router, Hono, route handlers). */
907
+ export async function contactsRoute(request: Request, verifier: AccessTokenVerifier): Promise<Response> {
908
+ let principal: UserAccessPrincipal;
909
+ try {
910
+ // verifyRequest reads Authorization, and X-Request-Id for the onReject event.
911
+ principal = await verifier.verifyRequest(request, { scopes: ["crm:access"] });
912
+ } catch (error) {
913
+ // A refused token: 401, 403 or 503 with the right WWW-Authenticate header and a JSON body.
914
+ if (error instanceof AuthVerifyError) return authErrorResponse(error);
915
+ // isRevoked could not read its store: fail closed, without a 401 that sends the client to login.
916
+ if (error instanceof RevocationStoreUnavailableError) {
917
+ return Response.json({ error: "temporarily_unavailable" }, { status: 503, headers: { "Retry-After": "5" } });
918
+ }
919
+ throw error;
920
+ }
921
+ return Response.json({ owner: callerOf(principal).publicId, contacts: [] });
922
+ }
923
+ ```
924
+ <!-- /snippet -->
925
+
926
+ `authErrorResponse(error)` membuat `Response` dengan status, `WWW-Authenticate` (bila ada), `Cache-Control: no-store`, dan body `{"error":"<errorCode>"}`. Ia melempar `TypeError` untuk error yang bukan `AuthVerifyError`; error seperti itu dilempar ulang, bukan dijawab.
927
+
928
+ ## 12. Token service (`allowServiceTokens`)
929
+
930
+ Token service diminta server lain dengan `client_credentials` ([`server-ke-server.md`](server-ke-server.md)). Token itu tidak punya sesi user (`sid`), dan `sub` sama dengan `client_id`. Bawaannya ditolak (`invalid_claims`).
931
+
932
+ Bila API Anda juga dipanggil server lain tanpa user:
933
+
934
+ - isi `allowServiceTokens: true`. Principal menjadi `AccessPrincipal` (user atau service); bedakan dengan `principal.kind`;
935
+ - dengan TypeScript, tipe opsinya `AccessTokenVerifierOptions<AccessPrincipal>`, dan `isRevoked` menerima kedua jenis principal. Di NestJS: `PlasgosAuthModule.forRoot<AccessPrincipal>({ …, allowServiceTokens: true })`;
936
+ - `cv` wajib untuk audience `/crm` hanya berlaku untuk token user;
937
+ - `maxAuthAge` selalu menolak token service (`stale_auth`), karena token service tidak punya waktu login;
938
+ - token tanpa `sid` yang `sub`-nya berbeda dari `client_id` (token user tanpa sesi) selalu ditolak.
939
+
940
+ Batasi route mana yang boleh dipanggil token service dengan scope service yang berbeda dari scope user.
941
+
942
+ ## 13. Alamat internal (`backchannelUrl`)
943
+
944
+ Kunci diambil dari `<backchannelUrl>/oidc/jwks`, atau dari `<issuer>/oidc/jwks` bila `backchannelUrl` tidak diisi. API di luar jaringan Plasgos tidak mengisinya.
945
+
946
+ API yang berjalan di jaringan Plasgos boleh memakai alamat internal yang diserahkan tim Plasgos:
947
+
948
+ - **Production: wajib `https:`.** JWKS adalah dasar kepercayaan: siapa pun yang bisa menjawab di alamat itu bisa membuat token yang diterima API Anda. `backchannelUrl` `http:` di production ditolak saat start.
949
+ - `allowInsecureBackchannel: true` (env `PLASGOS_ALLOW_INSECURE_BACKCHANNEL=true`) menerima `http:` di production, **hanya** untuk jaringan privat yang Anda percaya (misalnya alamat service di dalam cluster yang tidak bisa dijangkau dari luar). Risikonya tetap: siapa pun yang bisa menjawab di alamat itu bisa menandatangani token yang diterima API Anda.
950
+ - Sandbox: `http:` boleh, tetapi tidak boleh mengarah ke host production.
951
+
952
+ ## 14. Error dan jawaban HTTP
953
+
954
+ | `reason` | Status | Yang dilakukan API Anda | Yang dilakukan pemanggil |
955
+ |---|---|---|---|
956
+ | `missing_token` | `401` | Jawab (adapter melakukannya) | Kirim token. Bila belum login, login |
957
+ | `malformed_token` | `401` | Jawab | Bug di pemanggil: kirim access token utuh, bukan ID token atau cookie |
958
+ | `unknown_key` | `401` | Jawab. Bila semua token gagal: periksa `issuer` dan lingkungan | Login ulang bila berulang |
959
+ | `expired_token` | `401` | Jawab. Bila sering: periksa jam server | Refresh token, lalu ulangi sekali |
960
+ | `invalid_token` | `401` | Jawab. Bila semua token gagal: periksa `audience` dan `issuer` | Refresh sekali; bila tetap gagal, periksa `resource` saat meminta token |
961
+ | `invalid_claims` | `401` | Jawab. Bila semua token gagal: periksa `requireClaims` dan `allowServiceTokens` | Refresh sekali; bila tetap gagal, laporkan |
962
+ | `revoked` | `401` | Jawab | Sesi berakhir: login ulang |
963
+ | `insufficient_scope` | `403` | Jawab | Jangan diulang. Token tidak punya scope itu |
964
+ | `stale_auth` | `401` | Jawab | Login ulang dengan `maxAge` dari `max_age` di `WWW-Authenticate` |
965
+ | `unavailable` | `503` | Jawab. Pasang alert: kunci Plasgos tidak bisa dibaca | Coba lagi sebentar. **Jangan** logout |
966
+
967
+ Ketiga cara menjawab memberi header yang sama: status di atas, `Cache-Control: no-store` (penolakan tidak boleh disimpan cache), `WWW-Authenticate` bila ada, dan body `{"error":"<errorCode>"}`. Itu berlaku untuk `requirePlasgosToken`, guard NestJS, dan `authErrorResponse`. Di Express, bila header respons sudah terkirim (atau method respons melempar error), middleware tidak menulis penolakan dan meneruskan error ke `next(error)`, jadi error handler Anda yang menutup respons.
968
+
969
+ Kegagalan lain:
970
+
971
+ | Error | Kapan | Yang dilakukan |
972
+ |---|---|---|
973
+ | `ConfigError` | Saat start: opsi salah | Perbaiki opsi. Semua masalah ada di `problems` |
974
+ | Error dari `isRevoked` | Penyimpanan marker gagal | Error handler Anda menjawab `503` ([§8](#8-pencabutan-sesi-isrevoked)) |
975
+ | `TypeError` | Argumen salah: requirement yang tidak sah, `isRevoked` yang tidak mengembalikan boolean | Bug di kode Anda |
976
+ | `Error` dari `principalOf` atau `@PlasgosPrincipal()` | Route tanpa middleware atau guard | Bug wiring (`500`) |
977
+
978
+ Pesan error dan event `onReject` tidak pernah memuat token, klaim, atau nilai header, jadi aman ditulis ke log. Daftar lengkap pesan dan penyebabnya ada di [`error.md` §8](error.md#8-authverifyerror).
979
+
980
+ ## 15. Menguji API Anda
981
+
982
+ Untuk test, buat pasangan kunci sendiri saat test berjalan dan tandatangani token dengan cara yang sama seperti Plasgos. Cukup `node:crypto`; aplikasi Anda tidak butuh `jose` sendiri. Jangan pernah meng-commit kunci.
983
+
984
+ <!-- snippet: examples/snippets/token-testing.ts#signer -->
985
+ ```ts
986
+ /** A key pair made when the tests start, with node:crypto only. Never commit a key. */
987
+ export interface TestSigner {
988
+ /** The public key, for the sandbox-only `jwks` option of createAccessTokenVerifier. */
989
+ jwks: JsonWebKeySet;
990
+ /** An access token with these claims, signed the way Plasgos signs one (RS256, typ at+jwt). */
991
+ sign(claims: Record<string, unknown>): string;
992
+ }
993
+
994
+ const base64url = (value: string | Buffer): string => Buffer.from(value).toString("base64url");
995
+
996
+ export function createTestSigner(): TestSigner {
997
+ const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
998
+ const kid = `test-${randomUUID()}`;
999
+ const publicJwk = { ...publicKey.export({ format: "jwk" }), kid, alg: "RS256", use: "sig" };
1000
+ return {
1001
+ jwks: { keys: [publicJwk] },
1002
+ sign(claims) {
1003
+ const header = base64url(JSON.stringify({ alg: "RS256", typ: "at+jwt", kid }));
1004
+ // JSON.stringify drops a claim whose value is undefined: testClaims({ cv: undefined }) has no cv.
1005
+ const payload = base64url(JSON.stringify(claims));
1006
+ const signature = sign("RSA-SHA256", Buffer.from(`${header}.${payload}`), privateKey);
1007
+ return `${header}.${payload}.${base64url(signature)}`;
1008
+ },
1009
+ };
1010
+ }
1011
+ ```
1012
+ <!-- /snippet -->
1013
+
1014
+ Verifier untuk test memakai aturan yang sama dengan production, dengan opsi `jwks` (hanya sandbox) di tempat pengambilan kunci. Karena aplikasi menerima verifier sebagai argumen (`createApp(verifier)` di [§9](#9-express)), test cukup memberikan verifier ini:
1015
+
1016
+ <!-- snippet: examples/snippets/token-testing.ts#verifier -->
1017
+ ```ts
1018
+ /** Test values: a sandbox issuer and a sandbox audience whose path is /crm, like the API's own. */
1019
+ export const TEST_ISSUER = "https://accounts.sandbox.example";
1020
+ export const TEST_AUDIENCE = "https://api.sandbox.example/crm";
1021
+
1022
+ /** The API's verifier for tests: the same rules as in production, the test key instead of the JWKS request. */
1023
+ export function createTestVerifier(signer: TestSigner, store: RevocationStore): AccessTokenVerifier {
1024
+ return createAccessTokenVerifier({
1025
+ environment: "sandbox",
1026
+ issuer: TEST_ISSUER,
1027
+ audience: TEST_AUDIENCE,
1028
+ // Sandbox only: a fixed key set, no request to Plasgos.
1029
+ jwks: signer.jwks,
1030
+ requireClaims: ["plasgos_public_id", "cv"],
1031
+ isRevoked: revocationCheck(store),
1032
+ });
1033
+ }
1034
+
1035
+ /** A marker store in memory, for tests. */
1036
+ export function memoryRevocationStore(entries: Record<string, string> = {}): RevocationStore {
1037
+ const markers = new Map(Object.entries(entries));
1038
+ return { get: (key) => Promise.resolve(markers.get(key) ?? null) };
1039
+ }
1040
+
1041
+ /** The claims of a user token as Plasgos issues them for this API. Override a claim, or drop it with undefined. */
1042
+ export function testClaims(overrides: Record<string, unknown> = {}): Record<string, unknown> {
1043
+ const now = Math.floor(Date.now() / 1000);
1044
+ return {
1045
+ iss: TEST_ISSUER,
1046
+ aud: TEST_AUDIENCE,
1047
+ sub: "pairwise-subject-1",
1048
+ client_id: "test-client",
1049
+ sid: "test-session-1",
1050
+ auth_time: now - 60,
1051
+ cv: 1,
1052
+ plasgos_public_id: "usr-test-0001",
1053
+ scope: "openid crm:access",
1054
+ iat: now,
1055
+ exp: now + 300,
1056
+ ...overrides,
1057
+ };
1058
+ }
1059
+ ```
1060
+ <!-- /snippet -->
1061
+
1062
+ Lalu kirim request ke API Anda yang sedang berjalan:
1063
+
1064
+ <!-- snippet: examples/snippets/token-testing.ts#route-test -->
1065
+ ```ts
1066
+ /** Your running API: 401 without a token, 200 with a good one, 403 without the scope, 401 when expired. */
1067
+ export async function checkTokenRoute(url: string, signer: TestSigner): Promise<void> {
1068
+ const call = (token: string | null): Promise<Response> =>
1069
+ fetch(url, { headers: token === null ? {} : { Authorization: `Bearer ${token}` } });
1070
+ const expectStatus = (res: Response, status: number, label: string): void => {
1071
+ if (res.status !== status) throw new Error(`${label} answered ${String(res.status)}, expected ${String(status)}`);
1072
+ };
1073
+
1074
+ const missing = await call(null);
1075
+ expectStatus(missing, 401, "no token");
1076
+ if (missing.headers.get("WWW-Authenticate") !== "Bearer") throw new Error("no token: WWW-Authenticate must be Bearer");
1077
+
1078
+ expectStatus(await call(signer.sign(testClaims())), 200, "good token");
1079
+ expectStatus(await call(signer.sign(testClaims({ scope: "openid" }))), 403, "token without crm:access");
1080
+ const past = Math.floor(Date.now() / 1000) - 600;
1081
+ expectStatus(await call(signer.sign(testClaims({ iat: past, exp: past + 300 }))), 401, "expired token");
1082
+ expectStatus(await call(signer.sign(testClaims({ cv: undefined }))), 401, "token without cv");
1083
+ }
1084
+ ```
1085
+ <!-- /snippet -->
1086
+
1087
+ Untuk menguji pencabutan, isi store test dengan marker, misalnya `memoryRevocationStore({ [revocationKeys.credentialVersion("usr-test-0001")]: "2" })`, dan harapkan `401` untuk token dengan `cv: 1`. Untuk `stale_auth`, beri `auth_time` yang lebih tua dari `maxAuthAge` route.
1088
+
1089
+ ### NestJS dengan Jest
1090
+
1091
+ Test NestJS memakai `Test.createTestingModule` dengan `PlasgosAuthModule.forRoot` berisi opsi test (sandbox, `jwks` dari `createTestSigner`), lalu memanggil route lewat `supertest`. Contoh ini berjalan di Jest 30 dengan ts-jest, tanpa pengaturan ESM. Simpan sebagai file test proyek Anda, misalnya `test/contacts.e2e-spec.ts` (nama file contohnya sengaja bukan `*.test.ts`, supaya salinannya di folder `docs/examples/` paket tidak ikut dijalankan test runner):
1092
+
1093
+ <!-- snippet: examples/snippets/token-nestjs-jest.ts#jest -->
1094
+ ```ts
1095
+ describe("GET /api/contacts", () => {
1096
+ const signer = createTestSigner();
1097
+ // usr-test-0002 changed its password: tokens with cv below 2 are revoked.
1098
+ const store = memoryRevocationStore({ [revocationKeys.credentialVersion("usr-test-0002")]: "2" });
1099
+ let app: INestApplication;
1100
+ let server: Server;
1101
+
1102
+ beforeAll(async () => {
1103
+ const moduleRef = await Test.createTestingModule({
1104
+ imports: [
1105
+ // The production options, with the test key instead of the JWKS request (sandbox only).
1106
+ PlasgosAuthModule.forRoot({
1107
+ environment: "sandbox",
1108
+ issuer: TEST_ISSUER,
1109
+ audience: TEST_AUDIENCE,
1110
+ jwks: signer.jwks,
1111
+ requireClaims: ["plasgos_public_id", "cv"],
1112
+ isRevoked: revocationCheck(store),
1113
+ }),
1114
+ ],
1115
+ controllers: [ContactsController],
1116
+ providers: [{ provide: APP_FILTER, useClass: RevocationStoreUnavailableFilter }],
1117
+ }).compile();
1118
+ app = moduleRef.createNestApplication();
1119
+ await app.init();
1120
+ server = app.getHttpServer() as Server;
1121
+ });
1122
+
1123
+ afterAll(async () => {
1124
+ await app.close();
1125
+ });
1126
+
1127
+ const get = (token?: string) => {
1128
+ const call = request(server).get("/api/contacts");
1129
+ return token === undefined ? call : call.set("Authorization", `Bearer ${token}`);
1130
+ };
1131
+
1132
+ it("401 without a token", async () => {
1133
+ const res = await get();
1134
+ expect(res.status).toBe(401);
1135
+ expect(res.get("WWW-Authenticate")).toBe("Bearer");
1136
+ });
1137
+
1138
+ it("200 with a good token", async () => {
1139
+ const res = await get(signer.sign(testClaims()));
1140
+ expect(res.status).toBe(200);
1141
+ expect(res.text).toBe('{"owner":"usr-test-0001","contacts":[]}');
1142
+ });
1143
+
1144
+ it("403 without the scope", async () => {
1145
+ const res = await get(signer.sign(testClaims({ scope: "openid" })));
1146
+ expect(res.status).toBe(403);
1147
+ expect(res.get("WWW-Authenticate")).toBe('Bearer error="insufficient_scope", scope="crm:access"');
1148
+ });
1149
+
1150
+ it("401 when the credential version went up after the token was issued", async () => {
1151
+ const res = await get(signer.sign(testClaims({ plasgos_public_id: "usr-test-0002", cv: 1 })));
1152
+ expect(res.status).toBe(401);
1153
+ });
1154
+ });
1155
+ ```
1156
+ <!-- /snippet -->
1157
+
1158
+ Bila file contoh disalin ke proyek Jest, baca juga [§16](#16-commonjs-esm-dan-test-runner) untuk `moduleNameMapper`.
1159
+
1160
+ ## 16. CommonJS, ESM, dan test runner
1161
+
1162
+ - Paket punya build ESM dan CommonJS. Aplikasi CommonJS memakai `require` biasa, tanpa flag Node.
1163
+ - Build CommonJS bekerja di Jest (termasuk ts-jest) tanpa `transformIgnorePatterns` dan tanpa mode ESM Jest.
1164
+ - File contoh saling meng-import dengan akhiran `.js` (`./token-verifier.js`, gaya NodeNext). SDK sendiri tidak butuh pengaturan Jest, tetapi file contoh yang disalin ke proyek Jest butuh `moduleNameMapper` supaya `./x.js` menemukan `./x.ts`; tanpa itu Jest melapor `Cannot find module './token-verifier.js'`:
1165
+
1166
+ ```js
1167
+ // jest.config.js
1168
+ module.exports = {
1169
+ preset: "ts-jest",
1170
+ testEnvironment: "node",
1171
+ moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1" },
1172
+ };
1173
+ ```
1174
+
1175
+ - Dengan `module: "node16"` (atau `nodenext`) di `tsconfig.json`, ts-jest menulis peringatan `TS151002` (`Using hybrid module kind … is only supported in "isolatedModules: true"`). Hilangkan dengan `"isolatedModules": true` di `tsconfig.json` (file contoh sudah memenuhinya), atau, bila tidak bisa, dengan opsi ts-jest `diagnostics: { ignoreCodes: ["TS151002"] }`.
1176
+ - NestJS yang didukung: versi 11.
1177
+ - Build CommonJS membawa salinan `jose` di dalamnya (lisensinya di `THIRD_PARTY_NOTICES.md` paket). Akibatnya, mengganti versi `jose` lewat `overrides` di aplikasi hanya mengubah build ESM. Untuk perbaikan keamanan `jose`, **upgrade `@plasgos/auth-verify`**: setiap advisory keamanan `jose` dirilis Plasgos sebagai versi patch.
1178
+ - Kelas `AuthVerifyError` dan `ConfigError` dari `import` dan dari `require` adalah dua salinan. Aplikasi yang mencampur keduanya memeriksa `error.name`, bukan `instanceof` ([`error.md` §3](error.md#3-instanceof-dan-dua-loader)). Adapter Express dan NestJS sudah mengenali keduanya.
1179
+
1180
+ ## 17. Masalah umum
1181
+
1182
+ | Gejala | Penyebab | Perbaikan |
1183
+ |---|---|---|
1184
+ | Semua token `401 invalid_token` | `audience` tidak sama persis dengan `aud` token: audience lingkungan lain, `/` di akhir yang berbeda, atau pemanggil meminta token tanpa `resource` (token untuk audience lain) | Samakan `PLASGOS_TOKEN_AUDIENCE` dengan audience dari tim Plasgos, huruf demi huruf. Pemanggil meminta token dengan `resource` berisi nilai yang sama |
1185
+ | Semua token `401 invalid_token`, audience sudah benar | `issuer` dari lingkungan lain, atau origin yang tidak sama persis dengan issuer token (misalnya `http` dan `https`, atau port berbeda) | `PLASGOS_ISSUER` persis origin issuer lingkungan itu |
1186
+ | Semua token `401 unknown_key` | Token dari lingkungan lain (kuncinya berbeda), atau `backchannelUrl` mengarah ke server Plasgos lingkungan lain | Samakan lingkungan token, `issuer`, dan `backchannelUrl` |
1187
+ | Semua token `401 invalid_claims` | Pemanggil mengirim ID token, bukan access token (`typ` salah); klaim di `requireClaims` tidak dibawa token untuk audience Anda; token service tanpa `allowServiceTokens` | Kirim access token. Cocokkan `requireClaims` dengan klaim yang diserahkan tim Plasgos |
1188
+ | Kadang `401 expired_token` untuk token yang baru | Jam server meleset lebih dari 30 detik | Sinkronkan jam (NTP). Jangan menaikkan `clockToleranceSeconds` untuk menutupinya |
1189
+ | `401 missing_token` padahal pemanggil mengirim token | Proxy atau load balancer membuang header `Authorization` | Teruskan header `Authorization` di proxy |
1190
+ | Semua request `503 temporarily_unavailable` | JWKS tidak bisa dibaca: `backchannelUrl` salah, firewall, DNS, atau alamat yang menjawab redirect | Periksa alamat `<backchannelUrl atau issuer>/oidc/jwks` dari server API. Event `onReject` menunjukkan `reason=unavailable` |
1191
+ | `503` dari error handler Anda | `isRevoked` tidak bisa membaca penyimpanan marker | Periksa Redis atau penyimpanan Anda. Ini perilaku yang benar (fail closed) |
1192
+ | `ConfigError: isRevoked is required for a crm audience` | Audience `/crm` tanpa `isRevoked` | Pasang `isRevoked` ([§8](#8-pencabutan-sesi-isrevoked)) |
1193
+ | `ConfigError: backchannelUrl must use https: …` | `backchannelUrl` `http:` di production | Pakai `https:`, atau `allowInsecureBackchannel: true` hanya untuk jaringan privat yang Anda percaya |
1194
+ | `ConfigError: environment is "production" but audience is not a production audience` | Audience sandbox di production | Pakai audience production (diawali `https://api.plasgos.co.id/`) |
1195
+ | `ConfigError: jwks is only allowed when environment is "sandbox"` | Kunci tetap untuk test terbawa ke production | Hapus `jwks` di luar test |
1196
+ | `500` dengan `principalOf: requirePlasgosToken did not run for this request` | Route memanggil `principalOf` tanpa middleware | Pasang `requirePlasgosToken` di route itu |
1197
+ | `403 insufficient_scope` untuk semua user | Pemanggil tidak meminta scope yang dibutuhkan route | Pemanggil menambahkan scope itu saat login |
1198
+ | `401 revoked` setelah user mengganti password | Perilaku yang benar: token lama dicabut | Pemanggil mengarahkan user login ulang |
1199
+ | `Cannot find module '@plasgos/auth-verify/express'` | `moduleResolution: node` di `tsconfig.json` | Pakai `node16`, `nodenext`, atau `bundler` |
1200
+ | `error instanceof AuthVerifyError` bernilai `false` | Aplikasi memuat SDK lewat `import` dan `require` sekaligus | Periksa `error.name === "AuthVerifyError"` |
1201
+
1202
+ ## 18. Sebelum production
1203
+
1204
+ - [ ] Verifier dibuat sekali saat start, dan `ConfigError` menghentikan aplikasi.
1205
+ - [ ] `PLASGOS_ENV=production`, `PLASGOS_ISSUER=https://accounts.plasgos.co.id`, dan `PLASGOS_TOKEN_AUDIENCE` berisi audience production dari tim Plasgos.
1206
+ - [ ] Setiap route yang butuh login memakai middleware atau guard, dengan scope yang benar.
1207
+ - [ ] User dikenali dari `claims.plasgos_public_id`, bukan dari `subject`; `requireClaims` memuat `plasgos_public_id` (dan `cv`).
1208
+ - [ ] Aplikasi yang memanggil API Anda meminta scope `plasgos:public_id`, sehingga token membawa `plasgos_public_id`.
1209
+ - [ ] `isRevoked` terpasang, membaca marker yang diisi penerima webhook `user.*`, dan melempar error (bukan `false`) bila penyimpanannya gagal.
1210
+ - [ ] Penerima webhook menulis versi kredensial sebagai nilai terbesar (TTL 1 jam), marker sesi dengan TTL 1 jam, dan status blokir di database plus cache.
1211
+ - [ ] Error handler menjawab error penyimpanan marker dengan `503`, dan error lain dengan `500` tanpa stack trace.
1212
+ - [ ] Aksi sensitif memakai `maxAuthAge` atau `@RequireRecentAuth`.
1213
+ - [ ] `backchannelUrl` di production memakai `https:`, atau `allowInsecureBackchannel` dipakai dengan sadar untuk jaringan privat.
1214
+ - [ ] `jwks` hanya dipakai di test.
1215
+ - [ ] Jam server sinkron (NTP).
1216
+ - [ ] Log mencatat `reason`, `clientId`, dan `requestId` dari `onReject`, dan ada alert untuk `unavailable`.
1217
+ - [ ] Proxy meneruskan header `Authorization` dan `X-Request-Id`.
1218
+ - [ ] Test mengirim token yang benar, tanpa token, tanpa scope, kedaluwarsa, dan dicabut ke API Anda ([§15](#15-menguji-api-anda)).
1219
+ - [ ] Rencana upgrade `@plasgos/auth-verify` untuk advisory keamanan `jose` sudah dipahami tim ([§16](#16-commonjs-esm-dan-test-runner)).