@plasgos/auth-verify 0.0.0-stage → 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 (69) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +15 -0
  3. package/README.md +122 -2
  4. package/THIRD_PARTY_NOTICES.md +31 -0
  5. package/dist/express.cjs +157 -0
  6. package/dist/express.cjs.map +1 -0
  7. package/dist/express.d.cts +90 -0
  8. package/dist/express.d.ts +90 -0
  9. package/dist/express.js +127 -0
  10. package/dist/express.js.map +1 -0
  11. package/dist/index.cjs +1254 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +67 -0
  14. package/dist/index.d.ts +67 -0
  15. package/dist/index.js +499 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/nestjs.cjs +1395 -0
  18. package/dist/nestjs.cjs.map +1 -0
  19. package/dist/nestjs.d.cts +153 -0
  20. package/dist/nestjs.d.ts +153 -0
  21. package/dist/nestjs.js +637 -0
  22. package/dist/nestjs.js.map +1 -0
  23. package/dist/types-CGtRnj59.d.cts +193 -0
  24. package/dist/types-CGtRnj59.d.ts +193 -0
  25. package/dist/webhook.cjs +296 -0
  26. package/dist/webhook.cjs.map +1 -0
  27. package/dist/webhook.d.cts +196 -0
  28. package/dist/webhook.d.ts +196 -0
  29. package/dist/webhook.js +265 -0
  30. package/dist/webhook.js.map +1 -0
  31. package/docs/bff-express.md +1314 -0
  32. package/docs/consumers.md +98 -0
  33. package/docs/contoh-hitungcuan.md +255 -0
  34. package/docs/contoh-plaslink.md +244 -0
  35. package/docs/error.md +613 -0
  36. package/docs/examples/auth-verify-readme.ts +42 -0
  37. package/docs/examples/bff-express.ts +370 -0
  38. package/docs/examples/bff-proxy.ts +335 -0
  39. package/docs/examples/bff-redis-lock.ts +187 -0
  40. package/docs/examples/bff-revocation.ts +136 -0
  41. package/docs/examples/config-error.ts +24 -0
  42. package/docs/examples/env.ts +150 -0
  43. package/docs/examples/failure-log.ts +18 -0
  44. package/docs/examples/login-client.ts +46 -0
  45. package/docs/examples/login-flow.ts +186 -0
  46. package/docs/examples/plaslink-connect.ts +48 -0
  47. package/docs/examples/readme.ts +60 -0
  48. package/docs/examples/service-client.ts +105 -0
  49. package/docs/examples/session-store.ts +53 -0
  50. package/docs/examples/token-commonjs.cjs +95 -0
  51. package/docs/examples/token-express.ts +56 -0
  52. package/docs/examples/token-fetch.ts +24 -0
  53. package/docs/examples/token-nestjs-jest.ts +77 -0
  54. package/docs/examples/token-nestjs.ts +127 -0
  55. package/docs/examples/token-socket.ts +59 -0
  56. package/docs/examples/token-testing.ts +100 -0
  57. package/docs/examples/token-verifier.ts +132 -0
  58. package/docs/examples/user-events.ts +110 -0
  59. package/docs/examples/webhook-express.ts +46 -0
  60. package/docs/examples/webhook-fetch.ts +60 -0
  61. package/docs/examples/webhook-nestjs.ts +59 -0
  62. package/docs/examples/webhook-testing.ts +60 -0
  63. package/docs/examples/webhook-verifier.ts +197 -0
  64. package/docs/login-web.md +650 -0
  65. package/docs/memulai.md +419 -0
  66. package/docs/server-ke-server.md +287 -0
  67. package/docs/verifikasi-token.md +1219 -0
  68. package/docs/webhook.md +810 -0
  69. package/package.json +101 -3
@@ -0,0 +1,287 @@
1
+ # Server ke server
2
+
3
+ Panduan ini untuk server yang memanggil API Plasgos **tanpa user**, misalnya membuat payment. Server memperkenalkan diri dengan kredensial client service (grant OAuth `client_credentials`), menerima access token berumur pendek, lalu memakai token itu di setiap panggilan.
4
+
5
+ `createServiceClient` mengurus semuanya: meminta token, menyimpannya di memori, memintanya lagi saat hampir habis, dan menempelkannya ke request.
6
+
7
+ Sebelum mulai, baca [`memulai.md`](memulai.md) untuk env dan cara mendapat kredensial.
8
+
9
+ ## 1. Yang dibutuhkan
10
+
11
+ - Client service untuk app Anda: client id dan client secret ([`memulai.md` §6](memulai.md#6-mendapat-kredensial)).
12
+ - Scope service yang sesuai dengan endpoint yang dipanggil ([§6](#6-scope-per-endpoint)).
13
+ - Env: `PLASGOS_ENV`, `PLASGOS_ISSUER`, `PLASGOS_API_URL`, `PLASGOS_SERVICE_CLIENT_ID`, `PLASGOS_SERVICE_CLIENT_SECRET`.
14
+
15
+ Dua URL yang berbeda, jangan tertukar:
16
+
17
+ | Opsi | Production | Dipakai untuk |
18
+ |---|---|---|
19
+ | `issuer` | `https://accounts.plasgos.co.id` | Meminta token (`/oidc/token`) |
20
+ | `apiUrl` | `https://api.plasgos.co.id` | Memanggil API (`/v5/service/*`) |
21
+
22
+ Host API tidak melayani `/oidc/*`, dan host issuer tidak melayani `/v5/service/*`.
23
+
24
+ ## 2. Membuat client
25
+
26
+ Buat satu client saat aplikasi start dan pakai terus. Cache token ada di dalam client itu, jadi client yang dibuat ulang di setiap request akan meminta token baru setiap kali.
27
+
28
+ Salin `env.ts`, `failure-log.ts`, dan `config-error.ts` dari [folder contoh](examples/) ke aplikasi Anda.
29
+
30
+ <!-- snippet: examples/snippets/service-client.ts#create -->
31
+ ```ts
32
+ /** Create it once at start and reuse it: the token cache lives in the client. */
33
+ export function createPlasgosClient(): ServiceClient {
34
+ const env = readPlasgosEnv();
35
+ const credentials = readServiceCredentials();
36
+ return createServiceClient({
37
+ environment: env.environment,
38
+ issuer: env.issuer,
39
+ apiUrl: env.apiUrl,
40
+ backchannelUrl: env.backchannelUrl,
41
+ clientId: credentials.clientId,
42
+ clientSecret: credentials.clientSecret,
43
+ scopes: ["platform:self.read", "payments:read", "payments:write"],
44
+ resource: credentials.audience,
45
+ onFailure: logFailure,
46
+ });
47
+ }
48
+ ```
49
+ <!-- /snippet -->
50
+
51
+ `readPlasgosEnv`, `readServiceCredentials` ada di `env.ts` ([`memulai.md` §5](memulai.md#5-env-yang-disarankan)). `logFailure` ada di [§8](#8-mencatat-kegagalan-onfailure).
52
+
53
+ Potongan kode di panduan ini berasal dari satu file yang lolos typecheck, lengkap dengan import-nya: [`service-client.ts`](examples/service-client.ts). Semua import berasal dari `@plasgos/oidc-client/service`.
54
+
55
+ ### Opsi `createServiceClient`
56
+
57
+ | Opsi | Wajib | Bawaan | Arti |
58
+ |---|---|---|---|
59
+ | `environment` | Ya | — | `"sandbox"` atau `"production"`. Pengaman, bukan pemilih URL ([`memulai.md` §5](memulai.md#sandbox-dan-production)) |
60
+ | `issuer` | Ya | — | Origin issuer, tanpa path. Token diminta ke `<issuer>/oidc/token` |
61
+ | `apiUrl` | Ya | — | Origin tempat `/v5/service/*` berada. `fetch` hanya memanggil origin ini. Boleh `http:` untuk alamat internal |
62
+ | `backchannelUrl` | Tidak | `issuer` | Alamat internal server Plasgos untuk permintaan token. Hanya untuk aplikasi di jaringan Plasgos. Boleh `http:` |
63
+ | `clientId` | Ya | — | Client id client service |
64
+ | `clientSecret` | Ya | — | Client secret. Hanya dikirim ke endpoint token, sebagai Basic auth |
65
+ | `scopes` | Ya | — | Daftar scope service, minimal satu. Scope user ditolak |
66
+ | `resource` | Tidak | `https://api.plasgos.co.id/platform` | Audience token. Isi hanya bila tim Plasgos memberi nilai lain untuk lingkungan itu |
67
+ | `allowInsecureHttp` | Tidak | `false` | Hanya sandbox: mengizinkan `issuer` dengan `http:` |
68
+ | `timeouts.tokenMs` | Tidak | `10000` | Batas waktu permintaan token, 1–60000 ms |
69
+ | `timeouts.requestMs` | Tidak | `10000` | Batas waktu setiap percobaan `fetch`, termasuk membaca body, 1–60000 ms |
70
+ | `fetch` | Tidak | `fetch` global | Pengganti `fetch`, untuk test |
71
+ | `onFailure` | Tidak | — | Dipanggil sekali untuk setiap kegagalan ([§8](#8-mencatat-kegagalan-onfailure)) |
72
+
73
+ Opsi yang salah membuat `createServiceClient` melempar `ConfigError` saat dipanggil ([`memulai.md` §7](memulai.md#7-bila-konfigurasi-salah)).
74
+
75
+ ### Yang dikembalikan
76
+
77
+ | Anggota | Arti |
78
+ |---|---|
79
+ | `environment` | Nilai `environment` yang diberikan |
80
+ | `clientId` | Client id yang diberikan |
81
+ | `getToken()` | Access token yang masih berlaku ([§3](#3-gettoken-cache-token)) |
82
+ | `fetch(path, init?)` | `fetch` ke `apiUrl + path` dengan token terpasang ([§4](#4-fetch-memanggil-api)) |
83
+
84
+ ## 3. `getToken`: cache token
85
+
86
+ `await plasgos.getToken()` mengembalikan access token sebagai string.
87
+
88
+ - Token disimpan di memori, per client. Tidak ada refresh token.
89
+ - Token dipakai ulang sampai 60 detik sebelum habis (atau sampai setengah umurnya, bila umur token kurang dari 2 menit). Setelah itu panggilan berikutnya meminta token baru. Umur token dari Plasgos biasanya 10 menit.
90
+ - Bila banyak request datang bersamaan saat token belum ada, hanya satu permintaan token yang dikirim. Semua request menunggu hasil yang sama.
91
+ - Permintaan token yang gagal tidak disimpan. Panggilan berikutnya mencoba lagi.
92
+ - Kegagalan dilempar sebagai `OidcError` ([§7](#7-bila-gagal)).
93
+
94
+ Biasanya Anda tidak perlu memanggil `getToken` sendiri. `fetch` sudah memanggilnya.
95
+
96
+ ## 4. `fetch`: memanggil API
97
+
98
+ `await plasgos.fetch(path, init)` bekerja seperti `fetch` biasa, dengan aturan berikut:
99
+
100
+ - `path` harus diawali satu `/`, misalnya `/v5/service/me`. URL lengkap dan path yang diawali `//` ditolak dengan `TypeError`. `fetch` tidak bisa memanggil host selain `apiUrl`.
101
+ - Header `Authorization: Bearer <token>` dipasang otomatis.
102
+ - **Jawaban non-2xx tidak dilempar.** `fetch` mengembalikan `Response` apa adanya. Periksa `res.ok` atau `res.status` sendiri.
103
+ - **Diulang satu kali** bila API menjawab `401` dengan `WWW-Authenticate: Bearer error="invalid_token"`. Token di cache dibuang, token baru diminta, lalu request dikirim lagi. Request dengan body berupa stream tidak diulang, karena stream sudah terpakai.
104
+ - **`403` tidak pernah diulang.** `403 app_disabled` berarti app dinonaktifkan. `403 insufficient_scope` berarti client tidak punya scope untuk endpoint itu.
105
+ - **Redirect tidak diikuti.** Bawaannya `redirect: "manual"`, supaya token tidak ikut terkirim ke host lain. Jawaban `3xx` dikembalikan apa adanya. Atur `init.redirect` sendiri bila memang perlu.
106
+ - Setiap percobaan dibatasi `timeouts.requestMs`, termasuk waktu membaca body. `init.signal` dari pemanggil tetap berlaku.
107
+ - Jaringan putus atau timeout dilempar sebagai `OidcError` dengan `reason: "unavailable"`.
108
+
109
+ ### Cek koneksi
110
+
111
+ Panggil sekali setelah deploy untuk membuktikan kredensial, scope, dan jalur jaringan. Butuh scope `platform:self.read`.
112
+
113
+ <!-- snippet: examples/snippets/service-client.ts#self-check -->
114
+ ```ts
115
+ /** GET /v5/service/me: proves the credentials, the scope and the network path. Needs platform:self.read. */
116
+ export async function checkConnection(plasgos: ServiceClient): Promise<unknown> {
117
+ const res = await plasgos.fetch("/v5/service/me");
118
+ if (!res.ok) throw new Error(`Plasgos self check answered ${String(res.status)}`);
119
+ return res.json();
120
+ }
121
+ ```
122
+ <!-- /snippet -->
123
+
124
+ ## 5. Contoh: payments
125
+
126
+ Membuat payment. Butuh scope `payments:write`.
127
+
128
+ <!-- snippet: examples/snippets/service-client.ts#create-payment -->
129
+ ```ts
130
+ export interface NewPayment {
131
+ /** Your own id of the bill. Sending the same body again returns the same payment (200, not 201). */
132
+ external_ref: string;
133
+ /** A payment purpose registered for your app, for example "subscription". */
134
+ purpose: string;
135
+ amount: { amount: number; currency: "IDR" };
136
+ customer: { name: string; email: string };
137
+ }
138
+
139
+ /** POST /v5/service/payments. Needs payments:write. */
140
+ export async function createPayment(plasgos: ServiceClient, payment: NewPayment): Promise<unknown> {
141
+ const res = await plasgos.fetch("/v5/service/payments", {
142
+ method: "POST",
143
+ headers: { "Content-Type": "application/json" },
144
+ body: JSON.stringify(payment),
145
+ });
146
+ if (!res.ok) throw new Error(`Plasgos payments answered ${String(res.status)}`);
147
+ return res.json();
148
+ }
149
+ ```
150
+ <!-- /snippet -->
151
+
152
+ - `external_ref` adalah id tagihan di sistem Anda. Mengirim body yang sama dua kali aman: Plasgos menjawab payment yang sama (`200`, bukan `201`). Jadi request yang timeout boleh dikirim ulang.
153
+ - `purpose` harus sudah didaftarkan untuk app Anda. Bila belum, Plasgos menjawab `422 purpose_not_allowed`.
154
+ - Bentuk lengkap body dan jawaban ada di dokumentasi API payments Plasgos.
155
+
156
+ Refund dan ganti metode bayar mewajibkan header `Idempotency-Key` (1–128 karakter ASCII). Pakai kunci yang sama saat mengulang request yang sama. Refund butuh scope `payments:refund`.
157
+
158
+ <!-- snippet: examples/snippets/service-client.ts#refund -->
159
+ ```ts
160
+ /** POST /v5/service/payments/{pay_id}/refunds. Needs payments:refund and an Idempotency-Key. */
161
+ export async function refundPayment(
162
+ plasgos: ServiceClient,
163
+ paymentId: string,
164
+ amount: number,
165
+ idempotencyKey: string,
166
+ ): Promise<unknown> {
167
+ const res = await plasgos.fetch(`/v5/service/payments/${encodeURIComponent(paymentId)}/refunds`, {
168
+ method: "POST",
169
+ headers: { "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
170
+ body: JSON.stringify({ amount: { amount, currency: "IDR" } }),
171
+ });
172
+ if (!res.ok) throw new Error(`Plasgos refunds answered ${String(res.status)}`);
173
+ return res.json();
174
+ }
175
+ ```
176
+ <!-- /snippet -->
177
+
178
+ ## 6. Scope per endpoint
179
+
180
+ | Scope | Endpoint |
181
+ |---|---|
182
+ | `platform:self.read` | `GET /v5/service/me` |
183
+ | `payments:read` | `GET /v5/service/payments/methods`, `GET /v5/service/payments/{pay_id}`, `GET /v5/service/payments/by-ref/{external_ref}` |
184
+ | `payments:write` | `POST /v5/service/payments`, `POST /v5/service/payments/{pay_id}/attempts`, `POST /v5/service/payments/{pay_id}/cancel` |
185
+ | `payments:refund` | `POST /v5/service/payments/{pay_id}/refunds` |
186
+
187
+ Scope berikut sudah dikenal SDK, tetapi baru bisa dipakai **setelah Plasgos merilisnya**. Endpoint-nya diumumkan bersama rilis itu, dan tim Plasgos menambahkan scope-nya ke client service Anda bila diperlukan.
188
+
189
+ | Scope | Arti |
190
+ |---|---|
191
+ | `users:profile.read` | Profil dan pencarian user yang tertaut ke app Anda |
192
+ | `users:legacy.read` | Impor tautan dan id user dari sistem lama, sementara |
193
+ | `packages:service.read` | Origin, layanan, wilayah, slot, quote, dan paket |
194
+ | `packages:service.write` | Membuat, mengirim, dan membatalkan paket |
195
+ | `subscriptions:catalog.write` | Mengirim dan membaca katalog modul dan fitur app Anda |
196
+ | `subscriptions:read` | Membaca entitlement dan grant |
197
+ | `subscriptions:grants.write` | Mengonfirmasi pengiriman grant |
198
+
199
+ Minta hanya scope yang dipakai. `scopes` adalah daftar string, satu scope per elemen:
200
+
201
+ ```text
202
+ Benar: scopes: ["payments:read", "payments:write"]
203
+ Salah: scopes: ["payments:read payments:write"]
204
+ Salah: scopes: ["payments:read,payments:write"]
205
+ ```
206
+
207
+ Bentuk dengan spasi ditolak SDK saat start dengan `ConfigError`. Bentuk dengan koma lolos dari SDK (scope yang tidak dikenal diteruskan), tetapi Plasgos menolaknya saat token diminta, dan `getToken` gagal dengan `config_invalid`.
208
+
209
+ ## 7. Bila gagal
210
+
211
+ Ada tiga macam kegagalan:
212
+
213
+ | Kegagalan | Bentuk | Kapan |
214
+ |---|---|---|
215
+ | Konfigurasi salah | `ConfigError` dilempar `createServiceClient` | Saat start |
216
+ | Token tidak didapat, atau jaringan gagal | `OidcError` dilempar `getToken` / `fetch` | Saat berjalan |
217
+ | API menolak request | `Response` dengan status `4xx`/`5xx` | Saat berjalan |
218
+
219
+ `OidcError.reason` yang bisa muncul di client service:
220
+
221
+ | `reason` | Arti | Penyebab umum | Yang dilakukan |
222
+ |---|---|---|---|
223
+ | `config_invalid` | Plasgos menolak client ini | Client secret salah, client dinonaktifkan atau dicabut, scope tidak dimiliki client, beberapa scope digabung dengan koma dalam satu string | Perbaiki konfigurasi. Jangan diulang otomatis. Pasang alert |
224
+ | `invalid_target` | Plasgos menolak `resource` | `resource` bukan audience platform lingkungan itu | Pakai audience yang diberikan tim Plasgos |
225
+ | `unavailable` | Plasgos tidak menjawab | Jaringan putus, timeout, `5xx`, atau `429` | Ulangi nanti dengan jeda |
226
+ | `provider_error` | Jawaban tidak terduga | Jawaban bukan JSON token, terlalu besar, atau redirect | Laporkan ke tim Plasgos dengan `requestId` |
227
+
228
+ Contoh memilah kegagalan:
229
+
230
+ <!-- snippet: examples/snippets/service-client.ts#errors -->
231
+ ```ts
232
+ /** What to do when `getToken()` or `fetch()` rejects. Anything that is not an OidcError is rethrown. */
233
+ export function describeFailure(error: unknown): { retry: boolean; message: string } {
234
+ if (!(error instanceof OidcError)) throw error;
235
+ switch (error.reason) {
236
+ case "unavailable":
237
+ return { retry: true, message: "Plasgos did not answer in time; try again later" };
238
+ case "config_invalid":
239
+ return { retry: false, message: "client id, client secret or scopes are wrong; fix the configuration" };
240
+ case "invalid_target":
241
+ return { retry: false, message: "the resource (audience) is not the one of this environment" };
242
+ default:
243
+ return { retry: false, message: `Plasgos refused the token request (${error.reason})` };
244
+ }
245
+ }
246
+ ```
247
+ <!-- /snippet -->
248
+
249
+ Status dari API yang sering ditemui:
250
+
251
+ | Status | Arti | Yang dilakukan |
252
+ |---|---|---|
253
+ | `401` setelah satu kali ulang | Client dinonaktifkan atau dicabut | Hubungi tim Plasgos |
254
+ | `403 app_disabled` | App dinonaktifkan | Hubungi tim Plasgos |
255
+ | `403 insufficient_scope` | Scope untuk endpoint itu tidak ada | Tambah scope di `scopes` dan pastikan client punya scope itu |
256
+ | `422` | Body ditolak | Perbaiki body sesuai pesan validasi |
257
+
258
+ Penjelasan semua `reason` ada di [`error.md`](error.md).
259
+
260
+ ## 8. Mencatat kegagalan (`onFailure`)
261
+
262
+ SDK tidak pernah menulis log. Setiap kegagalan diserahkan ke `onFailure` sebagai satu event yang aman ditulis ke log: tidak berisi token, secret, atau isi jawaban.
263
+
264
+ <!-- snippet: examples/snippets/failure-log.ts -->
265
+ ```ts
266
+ import type { OidcFailureEvent } from "@plasgos/oidc-client";
267
+
268
+ /** One line per failure. The event never holds a token, a secret or a response body, so it is safe to log. */
269
+ export function logFailure(event: OidcFailureEvent): void {
270
+ const line = [
271
+ "plasgos auth failed:",
272
+ `env=${event.environment}`,
273
+ `operation=${event.operation}`,
274
+ `reason=${event.reason}`,
275
+ `call=${event.method ?? "-"} ${event.path ?? "-"}`,
276
+ `status=${event.status === null ? "-" : String(event.status)}`,
277
+ `request_id=${event.requestId ?? "-"}`,
278
+ `provider_error=${event.providerError ?? "-"}`,
279
+ ].join(" ");
280
+ process.stderr.write(`${line}\n`);
281
+ // A wrong secret, scope or grant is a bug in this app's configuration: page someone.
282
+ if (event.reason === "config_invalid") process.stderr.write("ALERT plasgos client configuration refused\n");
283
+ }
284
+ ```
285
+ <!-- /snippet -->
286
+
287
+ Untuk client service, `operation` bernilai `service_token` (permintaan token) atau `service_request` (panggilan `fetch`). Isi event dijelaskan di [`error.md`](error.md).