@plasgos/oidc-client 0.0.0-stage → 0.1.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/LICENSE +15 -0
- package/README.md +145 -2
- package/dist/index.cjs +884 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +33 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.js +860 -0
- package/dist/index.js.map +1 -0
- package/dist/service.cjs +432 -0
- package/dist/service.cjs.map +1 -0
- package/dist/service.d.cts +88 -0
- package/dist/service.d.ts +88 -0
- package/dist/service.js +419 -0
- package/dist/service.js.map +1 -0
- package/dist/session.cjs +601 -0
- package/dist/session.cjs.map +1 -0
- package/dist/session.d.cts +289 -0
- package/dist/session.d.ts +289 -0
- package/dist/session.js +568 -0
- package/dist/session.js.map +1 -0
- package/dist/types-JE0OMyoi.d.cts +375 -0
- package/dist/types-JE0OMyoi.d.ts +375 -0
- package/docs/consumers.md +90 -0
- package/docs/contoh-hitungcuan.md +255 -0
- package/docs/contoh-plaslink.md +244 -0
- package/docs/error.md +428 -0
- package/docs/examples/auth-verify-readme.ts +18 -0
- package/docs/examples/config-error.ts +24 -0
- package/docs/examples/env.ts +99 -0
- package/docs/examples/failure-log.ts +18 -0
- package/docs/examples/login-client.ts +46 -0
- package/docs/examples/login-flow.ts +186 -0
- package/docs/examples/plaslink-connect.ts +48 -0
- package/docs/examples/readme.ts +60 -0
- package/docs/examples/service-client.ts +105 -0
- package/docs/examples/session-store.ts +53 -0
- package/docs/examples/webhook-express.ts +46 -0
- package/docs/examples/webhook-fetch.ts +60 -0
- package/docs/examples/webhook-nestjs.ts +59 -0
- package/docs/examples/webhook-testing.ts +60 -0
- package/docs/examples/webhook-verifier.ts +143 -0
- package/docs/login-web.md +618 -0
- package/docs/memulai.md +339 -0
- package/docs/server-ke-server.md +275 -0
- package/docs/webhook.md +625 -0
- package/package.json +67 -3
package/docs/memulai.md
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
# Memulai
|
|
2
|
+
|
|
3
|
+
Panduan ini untuk tim yang menghubungkan aplikasi server (Node) ke Plasgos. Isinya: paket mana yang dipakai, env apa yang diatur, beda sandbox dan production, dua jenis client beserta scope-nya, dan cara mendapat kredensial.
|
|
4
|
+
|
|
5
|
+
Urutan kerja yang disarankan:
|
|
6
|
+
|
|
7
|
+
1. Tentukan kebutuhan aplikasi di [§1](#1-paket-mana-untuk-kebutuhan-apa).
|
|
8
|
+
2. Minta kredensial ke tim Plasgos ([§6](#6-mendapat-kredensial)).
|
|
9
|
+
3. Install paket ([§2](#2-install)) dan atur env ([§5](#5-env-yang-disarankan)).
|
|
10
|
+
4. Lanjut ke panduan sesuai kebutuhan: [`login-web.md`](login-web.md), [`server-ke-server.md`](server-ke-server.md), atau [`webhook.md`](webhook.md).
|
|
11
|
+
|
|
12
|
+
## 1. Paket mana untuk kebutuhan apa
|
|
13
|
+
|
|
14
|
+
| Kebutuhan aplikasi | Import | Fungsi utama | Panduan |
|
|
15
|
+
|---|---|---|---|
|
|
16
|
+
| User login dengan akun Plasgos | `@plasgos/oidc-client` | `createOidcClient` | [`login-web.md`](login-web.md) |
|
|
17
|
+
| Menyimpan sesi login di cookie | `@plasgos/oidc-client/session` | `createSessionStore` | [`login-web.md`](login-web.md) |
|
|
18
|
+
| Server memanggil API Plasgos tanpa user (misalnya payments) | `@plasgos/oidc-client/service` | `createServiceClient` | [`server-ke-server.md`](server-ke-server.md) |
|
|
19
|
+
| Menerima webhook dari Plasgos (payments, pengiriman Plaslink) | `@plasgos/auth-verify/webhook` | `createWebhookVerifier` | [`webhook.md`](webhook.md) |
|
|
20
|
+
| Memeriksa access token Plasgos di API sendiri | `@plasgos/auth-verify` | — | Menyusul |
|
|
21
|
+
|
|
22
|
+
Contoh per jenis aplikasi:
|
|
23
|
+
|
|
24
|
+
| Aplikasi | Yang dipakai | Contoh lengkap |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| Aplikasi Plasgos sendiri (accounts, Kirim Paket) | Login + sesi cookie | [`login-web.md`](login-web.md) |
|
|
27
|
+
| Plaslink | Login (seller menghubungkan akun) + payments + webhook | [`contoh-plaslink.md`](contoh-plaslink.md) |
|
|
28
|
+
| HitungCuan | Payments + webhook, tanpa login | [`contoh-hitungcuan.md`](contoh-hitungcuan.md) |
|
|
29
|
+
|
|
30
|
+
Semua paket hanya untuk server: Node `>=22.22`, tersedia sebagai ESM dan CommonJS. Tidak ada build untuk browser. Secret client tidak boleh sampai ke browser.
|
|
31
|
+
|
|
32
|
+
## 2. Install
|
|
33
|
+
|
|
34
|
+
Paket ada di npmjs.com dan di-install tanpa token, dengan nomor versi persis:
|
|
35
|
+
|
|
36
|
+
- login, sesi, dan server ke server: `pnpm add @plasgos/oidc-client@<versi> --save-exact`;
|
|
37
|
+
- menerima webhook: `pnpm add @plasgos/auth-verify@<versi> --save-exact`.
|
|
38
|
+
|
|
39
|
+
Install hanya paket yang dibutuhkan. Aplikasi yang memakai keduanya memasang versi yang sama untuk keduanya. `@plasgos/auth-shared` ikut terpasang sendiri. Aturan versi, Docker, CI, dan lisensi ada di [`consumers.md`](consumers.md).
|
|
40
|
+
|
|
41
|
+
Proyek TypeScript harus memakai `moduleResolution` `node16`, `nodenext`, atau `bundler` di `tsconfig.json`. Dengan `moduleResolution: node` yang lama, import `@plasgos/oidc-client/service` dan `/session` gagal dengan `Cannot find module`, begitu juga `@plasgos/auth-verify/webhook`. `@plasgos/auth-verify` tidak punya entry utama, jadi dengan `moduleResolution: node` tidak ada bagiannya yang bisa di-import. File di [folder contoh](examples/) saling meng-import dengan akhiran `.js` (gaya NodeNext); sesuaikan bila proyek Anda memakai gaya lain.
|
|
42
|
+
|
|
43
|
+
## 3. Dua jenis client
|
|
44
|
+
|
|
45
|
+
Satu paket melayani dua jenis client. Keduanya memakai kredensial yang berbeda dan scope yang tidak boleh tertukar.
|
|
46
|
+
|
|
47
|
+
| | Client login | Client service |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| Dipakai untuk | User login lewat browser | Server memanggil API Plasgos tanpa user |
|
|
50
|
+
| Fungsi | `createOidcClient` | `createServiceClient` |
|
|
51
|
+
| Import | `@plasgos/oidc-client` | `@plasgos/oidc-client/service` |
|
|
52
|
+
| Kredensial | Client interaktif | Client service milik app |
|
|
53
|
+
| Scope | Scope user ([§4](#scope-user-client-login)) | Scope service ([§4](#scope-service-client-service)) |
|
|
54
|
+
| Token mewakili | User yang login | App saja, tanpa user |
|
|
55
|
+
| Refresh token | Ada untuk aplikasi Plasgos sendiri; untuk pihak ketiga hanya bila punya `offline_access` | Tidak ada. Token baru diminta lagi saat hampir habis |
|
|
56
|
+
|
|
57
|
+
Bila scope tertukar, aplikasi gagal start dengan `ConfigError` yang menunjuk fungsi yang benar:
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
scopes: "payments:write" is a service scope; use createServiceClient from @plasgos/oidc-client/service
|
|
61
|
+
scopes: "openid" is a user scope; use createOidcClient from @plasgos/oidc-client
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Aplikasi yang butuh keduanya (Plaslink) membuat dua client dengan dua pasang kredensial.
|
|
65
|
+
|
|
66
|
+
**Token hanya membawa identitas.** Token Plasgos berisi siapa user-nya (`sub`, `name`, `picture`, `email`), scope yang disetujui, dan id sesi (`sid`). Token tidak pernah membawa role atau tim. Hak akses di dalam aplikasi Anda tetap diatur aplikasi Anda sendiri.
|
|
67
|
+
|
|
68
|
+
`sub` bersifat pairwise: user yang sama mendapat `sub` berbeda di setiap client. Jangan membandingkan `sub` antar client.
|
|
69
|
+
|
|
70
|
+
## 4. Daftar scope
|
|
71
|
+
|
|
72
|
+
`scopes` selalu berupa daftar string, satu scope per elemen: `["openid", "profile"]`. Jangan menulis satu string berisi beberapa scope (`"openid profile"` atau `"openid,profile"`). String yang memuat spasi ditolak SDK saat start (`scopes contains a value that is not a valid scope token`). Bentuk dengan koma tidak dikenali SDK, diteruskan apa adanya, lalu ditolak Plasgos.
|
|
73
|
+
|
|
74
|
+
Scope yang belum dikenal SDK diteruskan tanpa pemeriksaan. Plasgos yang memutuskan.
|
|
75
|
+
|
|
76
|
+
### Scope service (client service)
|
|
77
|
+
|
|
78
|
+
| Scope | Arti |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `platform:self.read` | `GET /v5/service/me`, untuk cek koneksi |
|
|
81
|
+
| `payments:read` | Melihat payment milik app sendiri dan daftar metode bayar |
|
|
82
|
+
| `payments:write` | Membuat payment, mengganti metode, membatalkan |
|
|
83
|
+
| `payments:refund` | Refund |
|
|
84
|
+
|
|
85
|
+
### Scope user (client login)
|
|
86
|
+
|
|
87
|
+
| Scope | Arti | Siapa yang boleh |
|
|
88
|
+
|---|---|---|
|
|
89
|
+
| `openid` | Wajib. Memberi `sub` | Semua |
|
|
90
|
+
| `profile` | `name`, `picture` | Semua |
|
|
91
|
+
| `email` | `email` | Semua |
|
|
92
|
+
| `offline_access` | Refresh token | Semua, bila client didaftarkan dengan scope ini |
|
|
93
|
+
| `plaslink:shipping` | Persetujuan seller untuk pengiriman lewat Plaslink | Client Plaslink |
|
|
94
|
+
| `plasgos:public_id` | Klaim `plasgos_public_id` (`usr-…`) | First-party saja |
|
|
95
|
+
| `account:read`, `account:write` | API akun | First-party saja, wajib `resource` |
|
|
96
|
+
| `packages:read`, `packages:write` | API seller Kirim Paket | First-party saja, wajib `resource` |
|
|
97
|
+
|
|
98
|
+
"First-party" berarti aplikasi milik Plasgos sendiri (`profile: "first-party"`). Aplikasi lain memakai `profile: "third-party"` dan tidak bisa meminta scope first-party.
|
|
99
|
+
|
|
100
|
+
## 5. Env yang disarankan
|
|
101
|
+
|
|
102
|
+
Nama env bebas, tetapi nama di bawah dipakai di semua contoh panduan ini.
|
|
103
|
+
|
|
104
|
+
| Env | Wajib | Contoh | Arti |
|
|
105
|
+
|---|---|---|---|
|
|
106
|
+
| `PLASGOS_ENV` | Ya | `sandbox` | `sandbox` atau `production`. Tidak punya nilai bawaan |
|
|
107
|
+
| `PLASGOS_ISSUER` | Bila ada login atau panggilan API | `https://accounts.plasgos.co.id` | Host tempat user login dan token diterbitkan (`/oidc/*`) |
|
|
108
|
+
| `PLASGOS_API_URL` | Bila ada login atau panggilan API | `https://api.plasgos.co.id` | Host API Plasgos (`/v5/*`) |
|
|
109
|
+
| `PLASGOS_BACKCHANNEL_URL` | Tidak | `http://plasgos-internal:3010` (alamat internal, contoh) | Alamat internal server Plasgos. Hanya untuk aplikasi yang berjalan di jaringan Plasgos |
|
|
110
|
+
| `PLASGOS_LOGIN_CLIENT_ID`, `PLASGOS_LOGIN_CLIENT_SECRET` | Bila ada login | | Kredensial client login |
|
|
111
|
+
| `PLASGOS_SERVICE_CLIENT_ID`, `PLASGOS_SERVICE_CLIENT_SECRET` | Bila ada panggilan server-ke-server | | Kredensial client service |
|
|
112
|
+
| `PLASGOS_AUDIENCE` | Tidak | `https://api.sandbox.plasgos.co.id/platform` | Audience token service. Audience = API yang dituju token (`resource`). Diisi hanya bila tim Plasgos memberi nilai yang berbeda dari bawaan |
|
|
113
|
+
| `PLASGOS_RESOURCE` | First-party saja | `https://api.plasgos.co.id/packages` | Audience API yang dipanggil atas nama user |
|
|
114
|
+
| `APP_URL` | Bila ada login | `https://app.example.com` | Origin publik aplikasi Anda, dasar `redirectUri` |
|
|
115
|
+
| `SESSION_SECRET` | Bila memakai `/session` | | Secret cookie sesi, minimal 32 byte. Saat rotasi: `baru,lama` |
|
|
116
|
+
| `PLASGOS_WEBHOOK_SECRET` | Bila menerima webhook payments | | Secret webhook payments (`whsec_…`). Saat rotasi: `baru,lama`, bila kedua secret tidak memuat koma dan tidak diawali atau diakhiri spasi; bila memuat, pakai dua env ([`webhook.md` §4](webhook.md#4-membuat-verifier), [§8](webhook.md#8-rotasi-secret)) |
|
|
117
|
+
| `PLASGOS_SHIPPING_WEBHOOK_SECRET` | Bila menerima webhook pengiriman Plaslink | | Secret webhook pengiriman Plaslink. Saat rotasi: `baru,lama`, dengan aturan yang sama |
|
|
118
|
+
|
|
119
|
+
Semua nilai secret (`*_CLIENT_SECRET`, `SESSION_SECRET`, `PLASGOS_WEBHOOK_SECRET`, `PLASGOS_SHIPPING_WEBHOOK_SECRET`) disimpan di secret manager aplikasi. Jangan di-commit, jangan ditulis ke log.
|
|
120
|
+
|
|
121
|
+
Contoh pembacaan env yang gagal dengan jelas bila ada nilai yang kosong. File ini dipakai contoh lain di panduan:
|
|
122
|
+
|
|
123
|
+
<!-- snippet: examples/snippets/env.ts -->
|
|
124
|
+
```ts
|
|
125
|
+
/** Same values as the SDK's `Environment` type. */
|
|
126
|
+
type Environment = "sandbox" | "production";
|
|
127
|
+
|
|
128
|
+
function required(name: string): string {
|
|
129
|
+
const value = process.env[name]?.trim() ?? "";
|
|
130
|
+
if (value === "") throw new Error(`Environment variable ${name} is required`);
|
|
131
|
+
return value;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function optional(name: string): string | undefined {
|
|
135
|
+
const value = process.env[name]?.trim() ?? "";
|
|
136
|
+
return value === "" ? undefined : value;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** PLASGOS_ENV: "sandbox" or "production". There is no default on purpose. */
|
|
140
|
+
export function readEnvironment(): Environment {
|
|
141
|
+
const value = required("PLASGOS_ENV");
|
|
142
|
+
if (value !== "sandbox" && value !== "production") {
|
|
143
|
+
throw new Error('Environment variable PLASGOS_ENV must be "sandbox" or "production"');
|
|
144
|
+
}
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** What every Plasgos client of this app shares. */
|
|
149
|
+
export interface PlasgosEnv {
|
|
150
|
+
environment: Environment;
|
|
151
|
+
/** PLASGOS_ISSUER: where users log in and tokens are issued. */
|
|
152
|
+
issuer: string;
|
|
153
|
+
/** PLASGOS_API_URL: where /v5/* lives. */
|
|
154
|
+
apiUrl: string;
|
|
155
|
+
/** PLASGOS_BACKCHANNEL_URL: optional internal origin of the Plasgos server, only inside the Plasgos network. */
|
|
156
|
+
backchannelUrl: string | undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function readPlasgosEnv(): PlasgosEnv {
|
|
160
|
+
return {
|
|
161
|
+
environment: readEnvironment(),
|
|
162
|
+
issuer: required("PLASGOS_ISSUER"),
|
|
163
|
+
apiUrl: required("PLASGOS_API_URL"),
|
|
164
|
+
backchannelUrl: optional("PLASGOS_BACKCHANNEL_URL"),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Credentials of the service client (server-to-server). */
|
|
169
|
+
export interface ServiceCredentials {
|
|
170
|
+
clientId: string;
|
|
171
|
+
clientSecret: string;
|
|
172
|
+
/** PLASGOS_AUDIENCE: only when the environment does not use the default platform audience. */
|
|
173
|
+
audience: string | undefined;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function readServiceCredentials(): ServiceCredentials {
|
|
177
|
+
return {
|
|
178
|
+
clientId: required("PLASGOS_SERVICE_CLIENT_ID"),
|
|
179
|
+
clientSecret: required("PLASGOS_SERVICE_CLIENT_SECRET"),
|
|
180
|
+
audience: optional("PLASGOS_AUDIENCE"),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Credentials of the login client (interactive), and the public origin of this app. */
|
|
185
|
+
export interface LoginCredentials {
|
|
186
|
+
clientId: string;
|
|
187
|
+
clientSecret: string;
|
|
188
|
+
/** APP_URL: public origin of this app, for example https://app.example.com. */
|
|
189
|
+
appUrl: string;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function readLoginCredentials(): LoginCredentials {
|
|
193
|
+
return {
|
|
194
|
+
clientId: required("PLASGOS_LOGIN_CLIENT_ID"),
|
|
195
|
+
clientSecret: required("PLASGOS_LOGIN_CLIENT_SECRET"),
|
|
196
|
+
appUrl: required("APP_URL").replace(/\/$/, ""),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** SESSION_SECRET: one secret, or "new,old" while a rotation is in progress. */
|
|
201
|
+
export function readSessionSecrets(): string[] {
|
|
202
|
+
const secrets = required("SESSION_SECRET")
|
|
203
|
+
.split(",")
|
|
204
|
+
.map((secret) => secret.trim())
|
|
205
|
+
.filter((secret) => secret !== "");
|
|
206
|
+
if (secrets.length > 2) throw new Error("Environment variable SESSION_SECRET holds at most two secrets");
|
|
207
|
+
return secrets;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* A webhook secret: one secret, or "new,old" while a rotation is in progress. Names used in the guides:
|
|
212
|
+
* PLASGOS_WEBHOOK_SECRET (payments) and PLASGOS_SHIPPING_WEBHOOK_SECRET (Plaslink shipping).
|
|
213
|
+
*/
|
|
214
|
+
export function readWebhookSecrets(name: string): string[] {
|
|
215
|
+
const secrets = required(name)
|
|
216
|
+
.split(",")
|
|
217
|
+
.map((secret) => secret.trim())
|
|
218
|
+
.filter((secret) => secret !== "");
|
|
219
|
+
if (secrets.length > 2) throw new Error(`Environment variable ${name} holds at most two secrets`);
|
|
220
|
+
return secrets;
|
|
221
|
+
}
|
|
222
|
+
```
|
|
223
|
+
<!-- /snippet -->
|
|
224
|
+
|
|
225
|
+
### Sandbox dan production
|
|
226
|
+
|
|
227
|
+
Kode aplikasi sama di semua lingkungan. Yang berbeda hanya nilai env. Setiap lingkungan punya server, kunci, client, dan secret sendiri. Kredensial sandbox tidak berlaku di production, dan sebaliknya.
|
|
228
|
+
|
|
229
|
+
| | `production` | `sandbox` |
|
|
230
|
+
|---|---|---|
|
|
231
|
+
| `PLASGOS_ISSUER` | `https://accounts.plasgos.co.id` | Host accounts sandbox. Tanyakan tim Plasgos |
|
|
232
|
+
| `PLASGOS_API_URL` | `https://api.plasgos.co.id` | `https://api.sandbox.plasgos.co.id` |
|
|
233
|
+
| Audience | Diawali `https://api.plasgos.co.id/` | Sesuai yang diberikan tim Plasgos |
|
|
234
|
+
|
|
235
|
+
`sandbox` mencakup staging dan development lokal.
|
|
236
|
+
|
|
237
|
+
**`environment` adalah pengaman, bukan pemilih URL.** SDK tidak mengubah URL berdasarkan `environment`. SDK hanya mencocokkan `environment` dengan URL yang Anda berikan, dan menolak start bila tidak cocok:
|
|
238
|
+
|
|
239
|
+
| `environment` | Aturan |
|
|
240
|
+
|---|---|
|
|
241
|
+
| `production` | `issuer` harus persis `https://accounts.plasgos.co.id`. Audience (`resource`) harus diawali `https://api.plasgos.co.id/`. `allowInsecureHttp` ditolak. |
|
|
242
|
+
| `sandbox` | `issuer`, `backchannelUrl`, dan `apiUrl` tidak boleh mengarah ke host production (`accounts.plasgos.co.id`, `api.plasgos.co.id`). `allowInsecureHttp: true` boleh, untuk development lokal dengan `http:`. |
|
|
243
|
+
|
|
244
|
+
Nilai selain `"sandbox"` dan `"production"`, atau kosong, ditolak. Tujuannya supaya aplikasi sandbox tidak pernah mengirim secret atau transaksi ke production karena salah env.
|
|
245
|
+
|
|
246
|
+
`backchannelUrl` adalah alamat internal server Plasgos untuk panggilan server-ke-server milik SDK: token, pencabutan token, dan logout ticket. Boleh `http:` karena berada di jaringan internal. Aplikasi di luar jaringan Plasgos tidak mengisinya. Tanpa `backchannelUrl`, panggilan token memakai `issuer`.
|
|
247
|
+
|
|
248
|
+
## 6. Mendapat kredensial
|
|
249
|
+
|
|
250
|
+
Tim Plasgos membuat kredensial untuk aplikasi Anda, sekali untuk setiap lingkungan (sandbox dulu, lalu production). Secret hanya tampil satu kali saat dibuat. Tim Plasgos menyerahkannya kepada Anda lewat kanal secret yang disetujui, tidak lewat chat atau tiket.
|
|
251
|
+
|
|
252
|
+
### Client login (client interaktif)
|
|
253
|
+
|
|
254
|
+
Yang Anda kirim ke tim Plasgos:
|
|
255
|
+
|
|
256
|
+
- nama aplikasi dan lingkungannya;
|
|
257
|
+
- redirect URI yang persis, misalnya `https://app.example.com/auth/callback` (tanpa wildcard dan fragment; wajib `https`, kecuali `http://localhost` untuk development);
|
|
258
|
+
- URL setelah logout bila dipakai, misalnya `https://app.example.com/`;
|
|
259
|
+
- scope yang dibutuhkan.
|
|
260
|
+
|
|
261
|
+
Tim Plasgos mendaftarkan client itu, lalu menyerahkan client id dan client secret kepada Anda.
|
|
262
|
+
|
|
263
|
+
Client first-party hanya untuk aplikasi milik Plasgos. Untuk client ini, tim Plasgos juga menyalakan refresh token, audience (`resource`), dan logout ticket.
|
|
264
|
+
|
|
265
|
+
### Client service
|
|
266
|
+
|
|
267
|
+
Client service terikat ke satu app di katalog aplikasi Plasgos. Yang Anda kirim ke tim Plasgos: nama app Anda (atau kode app, bila sudah ada) dan scope yang dibutuhkan.
|
|
268
|
+
|
|
269
|
+
Tim Plasgos menyiapkan app dan client service-nya, lalu menyerahkan client id dan client secret kepada Anda.
|
|
270
|
+
|
|
271
|
+
### Secret webhook
|
|
272
|
+
|
|
273
|
+
Yang Anda kirim ke tim Plasgos: URL webhook aplikasi Anda (`https`), satu untuk setiap lingkungan. Tim Plasgos mendaftarkan URL itu, lalu menyerahkan secret webhook kepada Anda. Webhook payments dan webhook pengiriman Plaslink memakai secret yang berbeda. Rotasinya ada di [`webhook.md` §8](webhook.md#8-rotasi-secret).
|
|
274
|
+
|
|
275
|
+
### Yang Anda terima
|
|
276
|
+
|
|
277
|
+
| Lewat kanal secret | Bukan rahasia |
|
|
278
|
+
|---|---|
|
|
279
|
+
| Client id dan client secret (per client) | Issuer (`PLASGOS_ISSUER`) |
|
|
280
|
+
| Secret webhook (payments: `whsec_…`), bila menerima webhook | Host API (`PLASGOS_API_URL`) |
|
|
281
|
+
| | Audience, bila berbeda dari bawaan |
|
|
282
|
+
|
|
283
|
+
## 7. Bila konfigurasi salah
|
|
284
|
+
|
|
285
|
+
`createOidcClient`, `createServiceClient`, `createSessionStore`, dan `createWebhookVerifier` memeriksa semua opsi saat dipanggil. Bila ada yang salah, semuanya melempar satu `ConfigError` yang memuat **semua** masalah sekaligus. Pesannya hanya menyebut nama opsi, tidak pernah nilainya, jadi aman ditulis ke log.
|
|
286
|
+
|
|
287
|
+
Contoh pesan:
|
|
288
|
+
|
|
289
|
+
```text
|
|
290
|
+
Invalid Plasgos auth configuration:
|
|
291
|
+
- environment is "sandbox" but issuer is a production host
|
|
292
|
+
- clientSecret is required
|
|
293
|
+
- scopes must include "openid"
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
Buat client saat aplikasi start, bukan saat request pertama, supaya salah konfigurasi ketahuan saat deploy:
|
|
297
|
+
|
|
298
|
+
<!-- snippet: examples/snippets/config-error.ts -->
|
|
299
|
+
```ts
|
|
300
|
+
/**
|
|
301
|
+
* The problems of a ConfigError, or null when `error` is something else. `instanceof ConfigError`
|
|
302
|
+
* works too when the class is imported from `@plasgos/oidc-client`; checking the name also works
|
|
303
|
+
* when the app loads the SDK through both `import` and `require`.
|
|
304
|
+
*/
|
|
305
|
+
export function configProblems(error: unknown): string[] | null {
|
|
306
|
+
if (!(error instanceof Error) || error.name !== "ConfigError") return null;
|
|
307
|
+
const problems: unknown = "problems" in error ? error.problems : undefined;
|
|
308
|
+
if (!Array.isArray(problems)) return [error.message];
|
|
309
|
+
return problems.filter((problem): problem is string => typeof problem === "string");
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Runs `create` at start. A configuration mistake stops the process with every problem printed. */
|
|
313
|
+
export function createOrExit<T>(create: () => T): T {
|
|
314
|
+
try {
|
|
315
|
+
return create();
|
|
316
|
+
} catch (error) {
|
|
317
|
+
const problems = configProblems(error);
|
|
318
|
+
if (problems === null) throw error;
|
|
319
|
+
process.stderr.write("Plasgos configuration is invalid:\n");
|
|
320
|
+
for (const problem of problems) process.stderr.write(`- ${problem}\n`);
|
|
321
|
+
process.exit(1);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
<!-- /snippet -->
|
|
326
|
+
|
|
327
|
+
Pemakaiannya: `const plasgos = createOrExit(createPlasgosClient);` (`createPlasgosClient` ada di [`server-ke-server.md` §2](server-ke-server.md#2-membuat-client)). Untuk webhook: `const verifier = createOrExit(createPaymentsWebhookVerifier);` ([`webhook.md` §4](webhook.md#4-membuat-verifier)).
|
|
328
|
+
|
|
329
|
+
`ConfigError` juga diekspor oleh `@plasgos/oidc-client` (dan `/session`, `/service`) dan oleh `@plasgos/auth-verify/webhook`, semuanya kelas yang sama, jadi `error instanceof ConfigError` bekerja bila kelasnya di-import dari sana. Contoh di atas memeriksa `error.name` supaya juga bekerja di aplikasi yang mencampur `import` dan `require` ([`error.md` §3](error.md#3-instanceof-dan-dua-loader)).
|
|
330
|
+
|
|
331
|
+
Daftar lengkap pesan `ConfigError` dan cara memperbaikinya ada di [`error.md`](error.md).
|
|
332
|
+
|
|
333
|
+
## 8. Langkah berikutnya
|
|
334
|
+
|
|
335
|
+
- Login user di aplikasi web: [`login-web.md`](login-web.md)
|
|
336
|
+
- Memanggil API Plasgos dari server: [`server-ke-server.md`](server-ke-server.md)
|
|
337
|
+
- Menerima webhook dari Plasgos: [`webhook.md`](webhook.md)
|
|
338
|
+
- Arti setiap kegagalan: [`error.md`](error.md)
|
|
339
|
+
- Contoh lengkap: [`contoh-hitungcuan.md`](contoh-hitungcuan.md), [`contoh-plaslink.md`](contoh-plaslink.md)
|
|
@@ -0,0 +1,275 @@
|
|
|
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
|
+
Minta hanya scope yang dipakai. `scopes` adalah daftar string, satu scope per elemen:
|
|
188
|
+
|
|
189
|
+
```text
|
|
190
|
+
Benar: scopes: ["payments:read", "payments:write"]
|
|
191
|
+
Salah: scopes: ["payments:read payments:write"]
|
|
192
|
+
Salah: scopes: ["payments:read,payments:write"]
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
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`.
|
|
196
|
+
|
|
197
|
+
## 7. Bila gagal
|
|
198
|
+
|
|
199
|
+
Ada tiga macam kegagalan:
|
|
200
|
+
|
|
201
|
+
| Kegagalan | Bentuk | Kapan |
|
|
202
|
+
|---|---|---|
|
|
203
|
+
| Konfigurasi salah | `ConfigError` dilempar `createServiceClient` | Saat start |
|
|
204
|
+
| Token tidak didapat, atau jaringan gagal | `OidcError` dilempar `getToken` / `fetch` | Saat berjalan |
|
|
205
|
+
| API menolak request | `Response` dengan status `4xx`/`5xx` | Saat berjalan |
|
|
206
|
+
|
|
207
|
+
`OidcError.reason` yang bisa muncul di client service:
|
|
208
|
+
|
|
209
|
+
| `reason` | Arti | Penyebab umum | Yang dilakukan |
|
|
210
|
+
|---|---|---|---|
|
|
211
|
+
| `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 |
|
|
212
|
+
| `invalid_target` | Plasgos menolak `resource` | `resource` bukan audience platform lingkungan itu | Pakai audience yang diberikan tim Plasgos |
|
|
213
|
+
| `unavailable` | Plasgos tidak menjawab | Jaringan putus, timeout, `5xx`, atau `429` | Ulangi nanti dengan jeda |
|
|
214
|
+
| `provider_error` | Jawaban tidak terduga | Jawaban bukan JSON token, terlalu besar, atau redirect | Laporkan ke tim Plasgos dengan `requestId` |
|
|
215
|
+
|
|
216
|
+
Contoh memilah kegagalan:
|
|
217
|
+
|
|
218
|
+
<!-- snippet: examples/snippets/service-client.ts#errors -->
|
|
219
|
+
```ts
|
|
220
|
+
/** What to do when `getToken()` or `fetch()` rejects. Anything that is not an OidcError is rethrown. */
|
|
221
|
+
export function describeFailure(error: unknown): { retry: boolean; message: string } {
|
|
222
|
+
if (!(error instanceof OidcError)) throw error;
|
|
223
|
+
switch (error.reason) {
|
|
224
|
+
case "unavailable":
|
|
225
|
+
return { retry: true, message: "Plasgos did not answer in time; try again later" };
|
|
226
|
+
case "config_invalid":
|
|
227
|
+
return { retry: false, message: "client id, client secret or scopes are wrong; fix the configuration" };
|
|
228
|
+
case "invalid_target":
|
|
229
|
+
return { retry: false, message: "the resource (audience) is not the one of this environment" };
|
|
230
|
+
default:
|
|
231
|
+
return { retry: false, message: `Plasgos refused the token request (${error.reason})` };
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
<!-- /snippet -->
|
|
236
|
+
|
|
237
|
+
Status dari API yang sering ditemui:
|
|
238
|
+
|
|
239
|
+
| Status | Arti | Yang dilakukan |
|
|
240
|
+
|---|---|---|
|
|
241
|
+
| `401` setelah satu kali ulang | Client dinonaktifkan atau dicabut | Hubungi tim Plasgos |
|
|
242
|
+
| `403 app_disabled` | App dinonaktifkan | Hubungi tim Plasgos |
|
|
243
|
+
| `403 insufficient_scope` | Scope untuk endpoint itu tidak ada | Tambah scope di `scopes` dan pastikan client punya scope itu |
|
|
244
|
+
| `422` | Body ditolak | Perbaiki body sesuai pesan validasi |
|
|
245
|
+
|
|
246
|
+
Penjelasan semua `reason` ada di [`error.md`](error.md).
|
|
247
|
+
|
|
248
|
+
## 8. Mencatat kegagalan (`onFailure`)
|
|
249
|
+
|
|
250
|
+
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.
|
|
251
|
+
|
|
252
|
+
<!-- snippet: examples/snippets/failure-log.ts -->
|
|
253
|
+
```ts
|
|
254
|
+
import type { OidcFailureEvent } from "@plasgos/oidc-client";
|
|
255
|
+
|
|
256
|
+
/** One line per failure. The event never holds a token, a secret or a response body, so it is safe to log. */
|
|
257
|
+
export function logFailure(event: OidcFailureEvent): void {
|
|
258
|
+
const line = [
|
|
259
|
+
"plasgos auth failed:",
|
|
260
|
+
`env=${event.environment}`,
|
|
261
|
+
`operation=${event.operation}`,
|
|
262
|
+
`reason=${event.reason}`,
|
|
263
|
+
`call=${event.method ?? "-"} ${event.path ?? "-"}`,
|
|
264
|
+
`status=${event.status === null ? "-" : String(event.status)}`,
|
|
265
|
+
`request_id=${event.requestId ?? "-"}`,
|
|
266
|
+
`provider_error=${event.providerError ?? "-"}`,
|
|
267
|
+
].join(" ");
|
|
268
|
+
process.stderr.write(`${line}\n`);
|
|
269
|
+
// A wrong secret, scope or grant is a bug in this app's configuration: page someone.
|
|
270
|
+
if (event.reason === "config_invalid") process.stderr.write("ALERT plasgos client configuration refused\n");
|
|
271
|
+
}
|
|
272
|
+
```
|
|
273
|
+
<!-- /snippet -->
|
|
274
|
+
|
|
275
|
+
Untuk client service, `operation` bernilai `service_token` (permintaan token) atau `service_request` (panggilan `fetch`). Isi event dijelaskan di [`error.md`](error.md).
|