@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/error.md
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
# Error dan kegagalan
|
|
2
|
+
|
|
3
|
+
Acuan untuk semua kegagalan yang bisa datang dari `@plasgos/oidc-client` dan `@plasgos/auth-verify`: artinya, penyebab umum, dan yang harus dilakukan.
|
|
4
|
+
|
|
5
|
+
| Error | Kapan | Bagian |
|
|
6
|
+
|---|---|---|
|
|
7
|
+
| `ConfigError` | Saat start: opsi salah | [§4](#4-configerror), untuk webhook [§7](#configerror-dari-createwebhookverifier) |
|
|
8
|
+
| `OidcError` | Saat berjalan: login, refresh, atau token service gagal | [§1](#1-oidcerror) |
|
|
9
|
+
| `SessionTooLargeError` | Cookie sesi tidak muat | [§5](#5-sessiontoolargeerror) |
|
|
10
|
+
| `TypeError` | Argumen fungsi salah (bug di kode pemanggil) | [§6](#6-typeerror) |
|
|
11
|
+
| `WebhookVerifyError` | Kiriman webhook ditolak (`@plasgos/auth-verify/webhook`) | [§7](#7-webhookverifyerror) |
|
|
12
|
+
| `AuthVerifyError` | Verifikasi access token | [§8](#8-authverifyerror) |
|
|
13
|
+
|
|
14
|
+
Aturan yang berlaku untuk semuanya: pesan error dan event **tidak pernah** memuat token, code, secret, isi cookie, isi jawaban Plasgos, tanda tangan webhook, nilai header, atau isi body webhook. Semuanya aman ditulis ke log.
|
|
15
|
+
|
|
16
|
+
## 1. `OidcError`
|
|
17
|
+
|
|
18
|
+
| Properti | Isi |
|
|
19
|
+
|---|---|
|
|
20
|
+
| `name` | `"OidcError"` |
|
|
21
|
+
| `reason` | Kode alasan (tabel di bawah) |
|
|
22
|
+
| `message` | `"OIDC <reason>"`, tidak lebih |
|
|
23
|
+
| `upstream` | `{ method, path, status, requestId }` dari panggilan ke Plasgos yang gagal, atau `null` bila kegagalan terjadi sebelum ada panggilan |
|
|
24
|
+
|
|
25
|
+
Dari mana `OidcError` bisa datang:
|
|
26
|
+
|
|
27
|
+
| Fungsi | Melempar `OidcError`? |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `client.handleCallback` | Ya |
|
|
30
|
+
| `client.refresh`, `client.ensureFresh` | Ya |
|
|
31
|
+
| `serviceClient.getToken`, `serviceClient.fetch` | Ya |
|
|
32
|
+
| `client.logout` | **Tidak pernah.** Kegagalannya hanya dilaporkan lewat `onFailure` |
|
|
33
|
+
| `client.startLogin` | Tidak. Ia tidak memanggil Plasgos |
|
|
34
|
+
|
|
35
|
+
### Semua `reason`
|
|
36
|
+
|
|
37
|
+
| `reason` | Arti | Datang dari |
|
|
38
|
+
|---|---|---|
|
|
39
|
+
| [`state_mismatch`](#state_mismatch) | `state` di callback tidak cocok dengan transaksi | `handleCallback` |
|
|
40
|
+
| [`expired`](#expired) | Transaksi login lebih tua dari 10 menit | `handleCallback` |
|
|
41
|
+
| [`missing`](#missing) | Ada yang seharusnya ada tetapi tidak ada: transaksi, `code`, atau refresh token | `handleCallback`, `refresh`, `ensureFresh` |
|
|
42
|
+
| [`provider_error`](#provider_error) | Plasgos menolak atau menjawab di luar dugaan | Semua |
|
|
43
|
+
| [`invalid_grant`](#invalid_grant) | `code` atau refresh token ditolak | `handleCallback`, `refresh`, `ensureFresh` |
|
|
44
|
+
| [`invalid_target`](#invalid_target) | `resource` (audience) ditolak | Semua |
|
|
45
|
+
| [`id_token_invalid`](#id_token_invalid) | ID token tidak lolos pemeriksaan | `handleCallback` |
|
|
46
|
+
| [`unavailable`](#unavailable) | Plasgos tidak bisa dihubungi atau sedang gangguan | Semua |
|
|
47
|
+
| [`config_invalid`](#config_invalid) | Plasgos menolak konfigurasi client ini | `handleCallback`, `refresh`, `ensureFresh`, `getToken`, `fetch` |
|
|
48
|
+
|
|
49
|
+
"Semua" berarti `handleCallback`, `refresh`, `ensureFresh`, `getToken`, dan `fetch` milik client service.
|
|
50
|
+
|
|
51
|
+
### `state_mismatch`
|
|
52
|
+
|
|
53
|
+
- **Arti:** parameter `state` di URL callback tidak ada, atau tidak sama dengan yang disimpan di cookie transaksi.
|
|
54
|
+
- **Penyebab umum:** user membuka dua tab login dan menyelesaikan yang lebih lama; URL callback lama dibuka lagi dari riwayat atau bookmark; percobaan menyisipkan callback dari situs lain.
|
|
55
|
+
- **Yang dilakukan:** tampilkan halaman "login gagal" dengan tombol coba lagi. Jangan dilanjutkan. Hapus cookie transaksi.
|
|
56
|
+
|
|
57
|
+
### `expired`
|
|
58
|
+
|
|
59
|
+
- **Arti:** transaksi login dibuat lebih dari 10 menit lalu, atau waktunya berada lebih dari 5 detik di masa depan.
|
|
60
|
+
- **Penyebab umum:** user terlalu lama di halaman login; jam server antar instance tidak sama.
|
|
61
|
+
- **Yang dilakukan:** mulai login lagi. Bila sering terjadi, periksa sinkronisasi jam server.
|
|
62
|
+
|
|
63
|
+
### `missing`
|
|
64
|
+
|
|
65
|
+
- **Arti di `handleCallback`:** cookie transaksi tidak ada atau tidak terbaca, URL callback tidak bisa diurai, atau URL tidak memuat tepat satu `code`.
|
|
66
|
+
- **Penyebab umum:** cookie diblokir browser; callback dibuka di browser lain dari tempat login dimulai (termasuk PWA iOS yang cookie-nya terpisah); callback dimuat ulang setelah cookie transaksi dihapus; `SESSION_SECRET` berbeda antar instance.
|
|
67
|
+
- **Arti di `refresh` / `ensureFresh`:** access token sudah habis (atau `force`) dan sesi tidak punya refresh token.
|
|
68
|
+
- **Penyebab umum:** client pihak ketiga tanpa `offline_access`, jadi memang tidak ada refresh token.
|
|
69
|
+
- **Yang dilakukan:** di callback, mulai login lagi. Di refresh, hapus `auth` dari sesi dan arahkan user ke login.
|
|
70
|
+
|
|
71
|
+
### `provider_error`
|
|
72
|
+
|
|
73
|
+
- **Arti:** Plasgos menolak dengan alasan yang tidak punya kode khusus di SDK, atau jawabannya tidak sesuai bentuk yang diharapkan.
|
|
74
|
+
- **Penyebab umum:**
|
|
75
|
+
- callback membawa `error=…`, misalnya `access_denied` karena user menolak persetujuan (`providerError` di event berisi kodenya);
|
|
76
|
+
- `iss` di callback bukan issuer yang dikonfigurasi;
|
|
77
|
+
- jawaban endpoint token bukan JSON token yang benar, lebih besar dari 16 KiB, atau berupa redirect (`3xx`; SDK tidak pernah mengikuti redirect);
|
|
78
|
+
- client first-party tidak menerima refresh token.
|
|
79
|
+
- **Yang dilakukan:** di callback, tampilkan "login gagal" dan tawarkan coba lagi. Di tempat lain, jangan hapus sesi. Bila berulang, laporkan ke tim Plasgos dengan `requestId`.
|
|
80
|
+
|
|
81
|
+
### `invalid_grant`
|
|
82
|
+
|
|
83
|
+
- **Arti:** `code` atau refresh token tidak diterima Plasgos.
|
|
84
|
+
- **Penyebab umum:** `code` dipakai dua kali atau sudah kedaluwarsa (callback dimuat ulang); refresh token sudah diganti, dicabut, atau sesi user di Plasgos sudah berakhir (misalnya logout di tempat lain, atau akses aplikasi dicabut); refresh token yang sama dipakai dua kali oleh dua instance tanpa `refreshLock` bersama.
|
|
85
|
+
- **Yang dilakukan:** di callback, mulai login lagi. Di `refresh` / `ensureFresh`, **sesi berakhir**: hapus `auth` dari sesi dan arahkan user ke login.
|
|
86
|
+
|
|
87
|
+
### `invalid_target`
|
|
88
|
+
|
|
89
|
+
- **Arti:** Plasgos menolak `resource` (audience) yang diminta.
|
|
90
|
+
- **Penyebab umum:** `resource` bukan audience lingkungan itu (misalnya audience production di sandbox yang memakai audience sendiri); client tidak diizinkan memakai audience itu.
|
|
91
|
+
- **Yang dilakukan:** ini bug konfigurasi. Perbaiki `resource`. Di `refresh` / `ensureFresh`, sesi berakhir (refresh token sudah terpakai): hapus `auth` dan arahkan user ke login. Di client service, isi `resource` dengan audience yang diberikan tim Plasgos.
|
|
92
|
+
|
|
93
|
+
### `id_token_invalid`
|
|
94
|
+
|
|
95
|
+
- **Arti:** ID token dari Plasgos tidak ada, atau tidak lolos salah satu pemeriksaan: `alg`, `iss`, `aud`, `azp`, `exp`, `iat`, `nonce`, atau `auth_time` saat `maxAge` diminta. Error sengaja tidak menyebut pemeriksaan yang gagal.
|
|
96
|
+
- **Penyebab umum:** jam server meleset lebih dari 60 detik; `issuer` di konfigurasi tidak sama persis dengan issuer Plasgos lingkungan itu; `clientId` salah.
|
|
97
|
+
- **Yang dilakukan:** periksa jam server (NTP) dan nilai `issuer`. User mencoba login lagi.
|
|
98
|
+
|
|
99
|
+
### `unavailable`
|
|
100
|
+
|
|
101
|
+
- **Arti:** tidak ada jawaban yang bisa dipakai dari Plasgos.
|
|
102
|
+
- **Penyebab umum:** jaringan putus, DNS, timeout (`timeouts`), jawaban `5xx`, atau `429`.
|
|
103
|
+
- **Yang dilakukan:** boleh diulang dengan jeda. Di callback, tampilkan "coba lagi sebentar" (`503`). Di `ensureFresh`: selama access token masih berlaku, kegagalan ini ditelan dan sesi tetap dipakai; setelah token habis, jawab `503` **tanpa menghapus sesi**. Di client service, ulangi nanti.
|
|
104
|
+
|
|
105
|
+
### `config_invalid`
|
|
106
|
+
|
|
107
|
+
- **Arti:** endpoint token Plasgos menjawab bahwa konfigurasi client ini sendiri yang salah: `invalid_client`, `unauthorized_client`, `invalid_scope`, atau `unsupported_grant_type`. Kode aslinya ada di `providerError` pada event.
|
|
108
|
+
- **Penyebab umum:** client secret salah atau sudah dirotasi; client dinonaktifkan atau dicabut; scope yang diminta tidak terdaftar pada client; beberapa scope digabung dengan koma dalam satu string.
|
|
109
|
+
- **Ini bug konfigurasi, bukan akhir sesi user.**
|
|
110
|
+
- Pasang alert untuk `reason === "config_invalid"` di `onFailure`. Kegagalan ini tidak sembuh sendiri.
|
|
111
|
+
- **Jangan hapus sesi user.** `ensureFresh` tetap mengembalikan sesi selama access token masih berlaku. Setelah token habis, request gagal (`500`) tanpa menghapus sesi. Begitu konfigurasi diperbaiki, user lanjut tanpa login ulang.
|
|
112
|
+
- Jangan diulang otomatis.
|
|
113
|
+
- **Bedanya dengan `ConfigError`:** `ConfigError` dilempar SDK saat start, sebelum ada panggilan ke Plasgos, untuk opsi yang bentuknya salah. `config_invalid` datang dari Plasgos saat berjalan, untuk opsi yang bentuknya benar tetapi nilainya ditolak.
|
|
114
|
+
|
|
115
|
+
## 2. `OidcFailureEvent`
|
|
116
|
+
|
|
117
|
+
SDK tidak pernah menulis log. Setiap kegagalan, yang dilempar maupun yang ditelan (logout, refresh yang ditoleransi), diserahkan ke hook `onFailure` sebagai satu event:
|
|
118
|
+
|
|
119
|
+
| Field | Isi |
|
|
120
|
+
|---|---|
|
|
121
|
+
| `environment` | `"sandbox"` atau `"production"` |
|
|
122
|
+
| `operation` | Langkah yang gagal: `callback`, `token`, `refresh`, `revocation`, `logout_ticket`, `service_token`, `service_request` |
|
|
123
|
+
| `reason` | `reason` yang sama dengan `OidcError` |
|
|
124
|
+
| `method` | Method HTTP panggilan yang gagal, atau `null` |
|
|
125
|
+
| `path` | Path panggilan yang gagal, tanpa query, atau `null` |
|
|
126
|
+
| `status` | Status HTTP jawaban Plasgos, atau `null` bila tidak ada jawaban |
|
|
127
|
+
| `requestId` | `x-request-id` dari jawaban Plasgos, atau `null`. Sertakan saat melapor ke tim Plasgos |
|
|
128
|
+
| `providerError` | Kode `error` dari Plasgos (misalnya `invalid_client`, `access_denied`), atau `null` |
|
|
129
|
+
|
|
130
|
+
Arti `operation`:
|
|
131
|
+
|
|
132
|
+
| `operation` | Langkah |
|
|
133
|
+
|---|---|
|
|
134
|
+
| `callback` | Pemeriksaan URL callback dan ID token |
|
|
135
|
+
| `token` | Menukar `code` dengan token |
|
|
136
|
+
| `refresh` | Refresh token |
|
|
137
|
+
| `revocation` | Mencabut refresh token saat logout |
|
|
138
|
+
| `logout_ticket` | Meminta logout ticket saat logout |
|
|
139
|
+
| `service_token` | Permintaan token client service |
|
|
140
|
+
| `service_request` | Panggilan `fetch` client service yang tidak sampai |
|
|
141
|
+
|
|
142
|
+
Contoh hook yang menulis satu baris per kegagalan dan memberi tanda untuk alert:
|
|
143
|
+
|
|
144
|
+
<!-- snippet: examples/snippets/failure-log.ts -->
|
|
145
|
+
```ts
|
|
146
|
+
import type { OidcFailureEvent } from "@plasgos/oidc-client";
|
|
147
|
+
|
|
148
|
+
/** One line per failure. The event never holds a token, a secret or a response body, so it is safe to log. */
|
|
149
|
+
export function logFailure(event: OidcFailureEvent): void {
|
|
150
|
+
const line = [
|
|
151
|
+
"plasgos auth failed:",
|
|
152
|
+
`env=${event.environment}`,
|
|
153
|
+
`operation=${event.operation}`,
|
|
154
|
+
`reason=${event.reason}`,
|
|
155
|
+
`call=${event.method ?? "-"} ${event.path ?? "-"}`,
|
|
156
|
+
`status=${event.status === null ? "-" : String(event.status)}`,
|
|
157
|
+
`request_id=${event.requestId ?? "-"}`,
|
|
158
|
+
`provider_error=${event.providerError ?? "-"}`,
|
|
159
|
+
].join(" ");
|
|
160
|
+
process.stderr.write(`${line}\n`);
|
|
161
|
+
// A wrong secret, scope or grant is a bug in this app's configuration: page someone.
|
|
162
|
+
if (event.reason === "config_invalid") process.stderr.write("ALERT plasgos client configuration refused\n");
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
<!-- /snippet -->
|
|
166
|
+
|
|
167
|
+
Exception yang dilempar hook diabaikan SDK. Hook tidak bisa mengubah hasil operasi.
|
|
168
|
+
|
|
169
|
+
## 3. `instanceof` dan dua loader
|
|
170
|
+
|
|
171
|
+
Setiap paket tersedia sebagai ESM dan CommonJS. Keduanya adalah dua salinan modul yang berbeda, jadi kelas `OidcError` dari `import` bukan kelas yang sama dengan `OidcError` dari `require`. Hal yang sama berlaku untuk `WebhookVerifyError` dan `ConfigError`.
|
|
172
|
+
|
|
173
|
+
- Aplikasi yang hanya memakai satu cara (semua `import`, atau semua `require`): `error instanceof OidcError` dan `error instanceof WebhookVerifyError` bekerja.
|
|
174
|
+
- Aplikasi yang mencampur keduanya (misalnya kode ESM dan sebuah dependensi CommonJS yang sama-sama memuat SDK): periksa nama dan `reason`, bukan `instanceof`:
|
|
175
|
+
|
|
176
|
+
```text
|
|
177
|
+
error.name === "OidcError" lalu baca error.reason
|
|
178
|
+
error.name === "WebhookVerifyError" lalu baca error.reason dan error.header
|
|
179
|
+
error.name === "ConfigError" lalu baca error.problems
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
`ConfigError` diekspor oleh `@plasgos/oidc-client`, `/session`, dan `/service`, dan ketiganya adalah kelas yang sama. Bila kelasnya di-import dari `@plasgos/oidc-client`, `error instanceof ConfigError` bekerja dengan aturan yang sama seperti `OidcError` di atas. Contoh di [`memulai.md` §7](memulai.md#7-bila-konfigurasi-salah) tetap memeriksa `error.name`, supaya juga bekerja di aplikasi yang mencampur `import` dan `require`.
|
|
183
|
+
|
|
184
|
+
`ConfigError` yang diekspor `@plasgos/auth-verify/webhook` adalah kelas yang sama dengan `ConfigError` dari `@plasgos/oidc-client`, karena keduanya berasal dari `@plasgos/auth-shared`. `WebhookVerifyError` juga berasal dari sana. Aturan dua loader di atas tetap berlaku.
|
|
185
|
+
|
|
186
|
+
## 4. `ConfigError`
|
|
187
|
+
|
|
188
|
+
Dilempar oleh `createOidcClient`, `createServiceClient`, `createSessionStore`, dan `createWebhookVerifier` saat dipanggil. Pesan khusus webhook ada di [§7](#configerror-dari-createwebhookverifier).
|
|
189
|
+
|
|
190
|
+
| Properti | Isi |
|
|
191
|
+
|---|---|
|
|
192
|
+
| `name` | `"ConfigError"` |
|
|
193
|
+
| `problems` | Daftar semua masalah, satu string per masalah |
|
|
194
|
+
| `message` | `"Invalid Plasgos auth configuration:"` diikuti daftar yang sama |
|
|
195
|
+
|
|
196
|
+
Semua masalah dilaporkan sekaligus. Pesan hanya menyebut nama opsi, tidak pernah nilainya. Nama scope disebut hanya bila scope itu dikenal SDK.
|
|
197
|
+
|
|
198
|
+
Di tabel berikut, `<opsi>` adalah nama opsi dan `<scope>` adalah nama scope.
|
|
199
|
+
|
|
200
|
+
### Lingkungan (`environment`)
|
|
201
|
+
|
|
202
|
+
Berlaku untuk `createOidcClient` dan `createServiceClient`. Baris pertama juga berlaku untuk `createSessionStore`.
|
|
203
|
+
|
|
204
|
+
| Pesan | Perbaikan |
|
|
205
|
+
|---|---|
|
|
206
|
+
| `environment must be "sandbox" or "production"` | Isi `environment` (env `PLASGOS_ENV`) dengan salah satu dari dua nilai itu. Tidak ada nilai bawaan |
|
|
207
|
+
| `environment is "production" but issuer is not the production issuer` | Di production, `issuer` harus persis `https://accounts.plasgos.co.id` |
|
|
208
|
+
| `environment is "production" but resource is not a production audience` | Di production, `resource` harus diawali `https://api.plasgos.co.id/` |
|
|
209
|
+
| `allowInsecureHttp is not allowed when environment is "production"` | Hapus `allowInsecureHttp` di production |
|
|
210
|
+
| `environment is "sandbox" but issuer is a production host` | Kredensial sandbox tidak boleh diarahkan ke production. Pakai issuer sandbox, atau ganti `environment` dan kredensialnya ke production |
|
|
211
|
+
| `environment is "sandbox" but backchannelUrl is a production host` | Sama, untuk `backchannelUrl` |
|
|
212
|
+
| `environment is "sandbox" but apiUrl is a production host` | Sama, untuk `apiUrl` |
|
|
213
|
+
|
|
214
|
+
### URL
|
|
215
|
+
|
|
216
|
+
| Pesan | Berlaku untuk | Perbaikan |
|
|
217
|
+
|---|---|---|
|
|
218
|
+
| `<opsi> is required` | `issuer`, `apiUrl`, `redirectUri`, `clientId`, `clientSecret` | Isi opsi itu. Biasanya env-nya kosong; nilai yang hanya berisi spasi juga dianggap kosong. Opsi tidak wajib yang kosong (`postLogoutRedirectUri`, `backchannelUrl`, `resource`) dianggap tidak diisi |
|
|
219
|
+
| `<opsi> must be a string` | Semua opsi teks | Nilainya bukan string (misalnya objek `URL` atau angka) |
|
|
220
|
+
| `<opsi> must be an absolute URL` | Semua URL | Tulis URL lengkap dengan skema: `https://…` |
|
|
221
|
+
| `<opsi> must use https` | `issuer`, `resource`, `redirectUri`, `postLogoutRedirectUri` | Pakai `https`. Untuk development lokal: `environment: "sandbox"` dan `allowInsecureHttp: true` |
|
|
222
|
+
| `<opsi> must be an origin without a path` | `issuer`, `backchannelUrl`, `apiUrl` | Hapus path. Benar: `https://accounts.plasgos.co.id`. Salah: `https://accounts.plasgos.co.id/oidc` |
|
|
223
|
+
| `<opsi> must be a canonical origin (lower-case scheme and host, no default port)` | `issuer`, `backchannelUrl`, `apiUrl` | Tulis dengan huruf kecil dan tanpa port bawaan (`:443`, `:80`) |
|
|
224
|
+
| `<opsi> must not contain a query` | `issuer`, `backchannelUrl`, `apiUrl`, `resource` | Hapus `?…` |
|
|
225
|
+
| `<opsi> must not contain a fragment` | Semua URL | Hapus `#…` |
|
|
226
|
+
| `<opsi> must not contain credentials` | Semua URL | Hapus `user:pass@` dari URL |
|
|
227
|
+
| `<opsi> must not contain whitespace, control characters or a backslash` | `resource`, `redirectUri`, `postLogoutRedirectUri` | Periksa spasi atau karakter tersembunyi di nilai env |
|
|
228
|
+
| `<opsi> must not contain a wildcard` | `redirectUri`, `postLogoutRedirectUri` | Tulis URL yang persis, tanpa `*` |
|
|
229
|
+
|
|
230
|
+
`redirectUri` dan `postLogoutRedirectUri` boleh memuat query, selama sama persis dengan yang didaftarkan di Plasgos.
|
|
231
|
+
|
|
232
|
+
### Scope
|
|
233
|
+
|
|
234
|
+
| Pesan | Perbaikan |
|
|
235
|
+
|---|---|
|
|
236
|
+
| `scopes must be a non-empty list` | `scopes` harus array berisi minimal satu string |
|
|
237
|
+
| `scopes contains a value that is not a valid scope token` | Ada elemen yang bukan string, kosong, atau memuat spasi. Tulis satu scope per elemen |
|
|
238
|
+
| `scopes must include "openid"` | Client login wajib meminta `openid` |
|
|
239
|
+
| `scopes: "<scope>" is a service scope; use createServiceClient from @plasgos/oidc-client/service` | Scope service diberikan ke `createOidcClient`. Pakai `createServiceClient` dengan kredensial client service |
|
|
240
|
+
| `scopes: "<scope>" is a user scope; use createOidcClient from @plasgos/oidc-client` | Scope user diberikan ke `createServiceClient`. Pakai `createOidcClient` dengan kredensial client login |
|
|
241
|
+
| `scopes: "<scope>" is for first-party clients only` | Client `third-party` meminta scope khusus aplikasi Plasgos. Hapus scope itu |
|
|
242
|
+
| `scopes: "<scope>" requires the resource option` | Scope `account:*` / `packages:*` butuh `resource` |
|
|
243
|
+
|
|
244
|
+
### `createOidcClient`
|
|
245
|
+
|
|
246
|
+
| Pesan | Perbaikan |
|
|
247
|
+
|---|---|
|
|
248
|
+
| `options must be an object` | Argumen bukan objek |
|
|
249
|
+
| `profile must be "first-party" or "third-party"` | Isi `profile` |
|
|
250
|
+
| `resource is not allowed for profile "third-party"` | Client pihak ketiga tidak memakai `resource`. Hapus |
|
|
251
|
+
| `logoutTicket must be a boolean` | Pakai `true` atau `false`, bukan string |
|
|
252
|
+
| `logoutTicket is not allowed for profile "third-party"` | Hanya first-party yang boleh. Hapus |
|
|
253
|
+
| `logoutTicket is not used with endSession "form-post"` | Pilih salah satu |
|
|
254
|
+
| `logoutTicket requires backchannelUrl (the internal Plasgos server URL)` | Isi `backchannelUrl`, atau hapus `logoutTicket: true` |
|
|
255
|
+
| `endSession must be "redirect" or "form-post"` | Perbaiki nilainya |
|
|
256
|
+
| `endSession "form-post" requires redirectUri on the issuer origin` | Hanya di production. `"form-post"` hanya untuk aplikasi di origin issuer. Aplikasi lain memakai `"redirect"` |
|
|
257
|
+
| `extraClaims contains an invalid claim name` | `extraClaims` harus array nama klaim (huruf, angka, `_ : . -`, 1–64 karakter). Klaim standar (`sub`, `email`, …) tidak boleh didaftarkan: nama itu ditolak dengan pesan yang sama. `null` juga ditolak; tanpa klaim tambahan, hapus opsinya |
|
|
258
|
+
| `allowInsecureHttp must be a boolean` | Pakai `true` atau `false`. String `"true"` dari env ditolak |
|
|
259
|
+
| `timeouts must be an object` | Bentuknya `{ tokenMs, logoutMs }` |
|
|
260
|
+
| `timeouts.<nama> must be an integer from 1 to 60000` | Bilangan bulat dalam milidetik |
|
|
261
|
+
| `fetch must be a function`, `onFailure must be a function` | Perbaiki tipe nilainya |
|
|
262
|
+
| `refreshLock must have a run function` | `refreshLock` harus memenuhi `RefreshLockStore` |
|
|
263
|
+
|
|
264
|
+
### `createServiceClient`
|
|
265
|
+
|
|
266
|
+
Pesan lingkungan, URL, dan scope di atas, ditambah `options must be an object`, `allowInsecureHttp must be a boolean`, `timeouts must be an object`, `timeouts.<nama> must be an integer from 1 to 60000` (`tokenMs`, `requestMs`), `fetch must be a function`, dan `onFailure must be a function`.
|
|
267
|
+
|
|
268
|
+
### `createSessionStore`
|
|
269
|
+
|
|
270
|
+
| Pesan | Perbaikan |
|
|
271
|
+
|---|---|
|
|
272
|
+
| `options must be an object` | Argumen bukan objek |
|
|
273
|
+
| `environment must be "sandbox" or "production"` | Beri nilai yang sama dengan client |
|
|
274
|
+
| `hostPrefix must be a boolean` | Pakai `true` atau `false` |
|
|
275
|
+
| `hostPrefix: false is not allowed when environment is "production"` | Production selalu memakai `__Host-` dan `Secure`. Hapus `hostPrefix: false` |
|
|
276
|
+
| `hkdfSalt is required`, `hkdfSalt must be a string` | Isi `hkdfSalt` dengan string tetap |
|
|
277
|
+
| `secrets must hold one or two values` | `secrets` harus array berisi satu atau dua string. Periksa `SESSION_SECRET` |
|
|
278
|
+
| `secrets values must each be at least 32 bytes` | Buat secret yang lebih panjang |
|
|
279
|
+
| `cookies.<peran> must match /^[a-z0-9-]{1,32}$/` | Nama cookie `app`, `auth`, `idToken`, `transaction` wajib ada: huruf kecil, angka, `-` |
|
|
280
|
+
| `cookies names must be distinct` | Keempat nama harus berbeda |
|
|
281
|
+
| `authMaxAgeSeconds must be a positive integer or a function` | Isi dengan detik (bilangan bulat positif) atau fungsi |
|
|
282
|
+
| `authMaxAgeSeconds must return a positive integer` | Dilempar saat cookie ditulis: fungsi `authMaxAgeSeconds` mengembalikan nilai yang salah |
|
|
283
|
+
| `appSchema must have a parse function` | Beri `{ parse(input) }` |
|
|
284
|
+
| `compactKeys must be an object` | Beri objek `{ panjang: "ringkas" }`, atau hapus |
|
|
285
|
+
| `compactKeys: keys must match /^[A-Za-z0-9_]{1,32}$/ and must not be a reserved name` | Perbaiki nama kunci |
|
|
286
|
+
| `compactKeys: "<kunci>" must map to "<ringkas>"` | Kunci itu ada di tabel inti SDK dan harus memakai nama ringkas yang sama |
|
|
287
|
+
| `compactKeys: short key "<ringkas>" is used twice` | Dua kunci panjang memakai nama ringkas yang sama |
|
|
288
|
+
| `compactKeys: short key "<ringkas>" is also a long key` | Nama ringkas tidak boleh sama dengan nama panjang lain |
|
|
289
|
+
| `onFailure must be a function` | Perbaiki tipe nilainya |
|
|
290
|
+
|
|
291
|
+
## 5. `SessionTooLargeError`
|
|
292
|
+
|
|
293
|
+
Diekspor dari `@plasgos/oidc-client/session`.
|
|
294
|
+
|
|
295
|
+
- **Arti:** satu `Set-Cookie` akan lebih besar dari 4000 karakter, batas yang masih diterima browser.
|
|
296
|
+
- **Dilempar oleh:** `commitApp`, `commitAuth`, `commitIdToken`. `commit()` **tidak** melemparnya: ia menghapus cookie yang tidak muat, membuang datanya dari sesi, dan memanggil `onFailure` milik store dengan `{ kind: "session_too_large", cookie, size }`.
|
|
297
|
+
- **Isi:** `name` (`"SessionTooLargeError"`), `size`, dan pesan `Session cookie too large: <size> chars (limit 4000)`. Tidak pernah isi cookie.
|
|
298
|
+
- **Penyebab umum:** terlalu banyak data di cookie `app`; token yang sangat panjang.
|
|
299
|
+
- **Yang dilakukan:** simpan lebih sedikit di cookie `app` (data besar ke database). Di callback, panggil `store.fits(auth)` sebelum menyimpan login ([`login-web.md` §4](login-web.md#callback)).
|
|
300
|
+
|
|
301
|
+
## 6. `TypeError`
|
|
302
|
+
|
|
303
|
+
`TypeError` berarti kode pemanggil memberi argumen yang salah. Ini bug di aplikasi, bukan kegagalan Plasgos, dan tidak dilaporkan lewat `onFailure`.
|
|
304
|
+
|
|
305
|
+
| Pesan | Penyebab |
|
|
306
|
+
|---|---|
|
|
307
|
+
| `startLogin: returnTo must start with exactly one "/" and be at most 512 characters` | `returnTo` belum disanitasi |
|
|
308
|
+
| `startLogin: prompt must be "login", "consent" or "none"` | Nilai `prompt` salah |
|
|
309
|
+
| `startLogin: maxAge must be a non-negative integer` | `maxAge` bukan bilangan bulat ≥ 0 |
|
|
310
|
+
| `startLogin: loginHint must be a string of at most 512 characters` | `loginHint` terlalu panjang atau bukan string |
|
|
311
|
+
| `startLogin: reauth must be a boolean`, `startLogin: input must be an object`, `startLogin: now must be a finite number` | Tipe argumen salah |
|
|
312
|
+
| `skewSeconds must be a non-negative integer` | Opsi `ensureFresh` salah |
|
|
313
|
+
| `serviceClient.fetch: path must start with a single /` | `path` berupa URL lengkap, diawali `//`, atau tidak diawali `/` |
|
|
314
|
+
| `serviceClient.fetch: init must be an object` | Argumen kedua `fetch` bukan objek |
|
|
315
|
+
|
|
316
|
+
Selain itu, `serviceClient.fetch` meneruskan pembatalan dari `init.signal` milik pemanggil apa adanya (alasan `abort` yang Anda berikan).
|
|
317
|
+
|
|
318
|
+
`TypeError` dari verifikasi webhook ada di [§7](#typeerror-dari-verify).
|
|
319
|
+
|
|
320
|
+
## 7. `WebhookVerifyError`
|
|
321
|
+
|
|
322
|
+
Dilempar oleh `verifier.verify` dan `verifyWebhook` dari `@plasgos/auth-verify/webhook` bila sebuah kiriman webhook ditolak. Cara menanganinya ada di [`webhook.md` §6](webhook.md#6-menangani-kiriman).
|
|
323
|
+
|
|
324
|
+
| Properti | Isi |
|
|
325
|
+
|---|---|
|
|
326
|
+
| `name` | `"WebhookVerifyError"` |
|
|
327
|
+
| `reason` | Kode alasan (tabel di bawah) |
|
|
328
|
+
| `header` | Header yang bermasalah: `"id"`, `"type"`, `"timestamp"`, atau `"signature"`. Hanya untuk `missing_header`, `malformed_header`, dan `header_mismatch`; selain itu `null` |
|
|
329
|
+
| `message` | `"Webhook <reason>"`, tidak lebih |
|
|
330
|
+
|
|
331
|
+
`header` menyebut peran header, bukan namanya. Untuk `presets.payments`, `"signature"` berarti `X-Signature`; untuk `presets.plaslinkShipping`, `X-Plasgos-Signature`. Pesan dan properti tidak pernah memuat secret, tanda tangan, nilai header, atau isi body.
|
|
332
|
+
|
|
333
|
+
### Semua `reason`
|
|
334
|
+
|
|
335
|
+
Diperiksa dengan urutan berikut. Kegagalan pertama yang ditemukan yang dilaporkan.
|
|
336
|
+
|
|
337
|
+
| `reason` | Arti | Jawaban HTTP |
|
|
338
|
+
|---|---|---|
|
|
339
|
+
| [`missing_header`](#missing_header) | Salah satu dari empat header tidak ada | `400` |
|
|
340
|
+
| [`malformed_header`](#malformed_header) | Header ada, tetapi bentuknya salah | `400` |
|
|
341
|
+
| [`body_too_large`](#body_too_large) | Body lebih besar dari `maxBodyBytes` | `400` |
|
|
342
|
+
| [`stale_timestamp`](#stale_timestamp) | Waktu kirim di luar `toleranceSeconds` | `401` |
|
|
343
|
+
| [`signature_mismatch`](#signature_mismatch) | Tidak ada tanda tangan `v1` yang cocok dengan secret | `401` |
|
|
344
|
+
| [`invalid_body`](#invalid_body) | Body yang ditandatangani bukan objek JSON dengan `id` dan `type` berupa string | `400` |
|
|
345
|
+
| [`header_mismatch`](#header_mismatch) | `id` atau `type` di body berbeda dari header | `400` |
|
|
346
|
+
|
|
347
|
+
Plasgos mengulang setiap jawaban selain `2xx` ([`webhook.md` §2](webhook.md#2-aturan-pengiriman)). Kiriman yang ditolak karena kesalahan di sisi Anda (secret salah, jam server meleset) terus diulang sampai batasnya (bawaannya 15 percobaan, sekitar 6,4 jam, untuk payments dan 20 percobaan, sekitar 11,4 jam, untuk pengiriman Plaslink), lalu menahan event berikutnya untuk payment atau pengiriman yang sama sampai tim Plasgos mengirim ulang atau melewatinya. Event yang dilewati membuat `sequence` melompat ([`webhook.md` §1](webhook.md#1-apa-itu-webhook-plasgos)). Perbaiki penyebabnya, lalu minta tim Plasgos mengirim ulang atau melewatinya.
|
|
348
|
+
|
|
349
|
+
### `missing_header`
|
|
350
|
+
|
|
351
|
+
- **Arti:** salah satu header id, type, waktu kirim, atau tanda tangan tidak ada. `header` menyebut yang mana.
|
|
352
|
+
- **Penyebab umum:** request bukan dari Plasgos (pemindai, panggilan manual); proxy membuang header; preset salah, misalnya kiriman pengiriman Plaslink diperiksa dengan `presets.payments`.
|
|
353
|
+
- **Yang dilakukan:** jawab `400`. Bila semua kiriman asli gagal dengan alasan ini, periksa preset dan konfigurasi proxy.
|
|
354
|
+
|
|
355
|
+
### `malformed_header`
|
|
356
|
+
|
|
357
|
+
- **Arti:** header ada, tetapi isinya tidak sesuai format. Id dan type: huruf, angka, `_ . : -`, paling panjang 200 karakter. Waktu kirim: angka saja (detik epoch), tanpa nol di depan, paling panjang 15 digit. Tanda tangan: paling panjang 1024 karakter, paling banyak 10 nilai dipisah koma, minimal satu `v1=` diikuti tepat 64 karakter hex. Juga dilaporkan bila objek header memuat nama yang sama dua kali dengan huruf besar dan kecil berbeda, atau nilai yang bukan string.
|
|
358
|
+
- **Penyebab umum:** request bukan dari Plasgos; proxy menggabungkan atau mengulang header; kode test yang menyusun header sendiri.
|
|
359
|
+
- **Yang dilakukan:** jawab `400`. Pada test, bandingkan dengan `signTestDelivery` di [`webhook.md` §10](webhook.md#10-menguji-penerima).
|
|
360
|
+
|
|
361
|
+
### `body_too_large`
|
|
362
|
+
|
|
363
|
+
- **Arti:** body mentah lebih besar dari `maxBodyBytes` (bawaan 1 MiB). Diperiksa sebelum tanda tangan dihitung.
|
|
364
|
+
- **Penyebab umum:** request bukan dari Plasgos; `maxBodyBytes` diatur terlalu kecil.
|
|
365
|
+
- **Yang dilakukan:** jawab `400`. Batas body di framework tetap wajib, karena `maxBodyBytes` hanya menolak body yang sudah terbaca ([`webhook.md` §5](webhook.md#5-body-mentah-per-framework)).
|
|
366
|
+
|
|
367
|
+
### `stale_timestamp`
|
|
368
|
+
|
|
369
|
+
- **Arti:** waktu kirim berbeda lebih dari `toleranceSeconds` (bawaan 300 detik) dari jam server, ke masa lalu atau ke masa depan.
|
|
370
|
+
- **Penyebab umum:** jam server meleset; kiriman lama yang diputar ulang; request tertahan lama di antrean atau proxy sebelum sampai ke `verify`.
|
|
371
|
+
- **Yang dilakukan:** jawab `401`. Periksa sinkronisasi jam server (NTP). Jangan menaikkan `toleranceSeconds` untuk menutupi jam yang salah.
|
|
372
|
+
|
|
373
|
+
### `signature_mismatch`
|
|
374
|
+
|
|
375
|
+
- **Arti:** tidak ada nilai `v1=` di header tanda tangan yang cocok dengan salah satu secret di `secrets`.
|
|
376
|
+
- **Penyebab umum:**
|
|
377
|
+
- secret salah: secret sandbox di production, secret lama setelah rotasi selesai, atau secret jenis lain (secret payments untuk pengiriman Plaslink);
|
|
378
|
+
- body berubah sebelum diverifikasi: JSON di-parse lalu di-`JSON.stringify` lagi, body parser global berjalan lebih dulu, atau proxy mengubah body;
|
|
379
|
+
- request palsu.
|
|
380
|
+
- **Yang dilakukan:** jawab `401`. Bila semua kiriman asli gagal dengan alasan ini, periksa secret dan pastikan body mentah yang diberikan ke `verify`. Pasang alert: alasan ini yang berulang biasanya berarti secret salah, dan antrean akan tertahan.
|
|
381
|
+
|
|
382
|
+
### `invalid_body`
|
|
383
|
+
|
|
384
|
+
- **Arti:** tanda tangan cocok, tetapi body bukan UTF-8 yang sah, bukan JSON, bukan objek, atau tidak punya `id` dan `type` berupa string.
|
|
385
|
+
- **Penyebab umum:** tidak terjadi pada kiriman Plasgos. Biasanya kode test yang menandatangani body yang salah.
|
|
386
|
+
- **Yang dilakukan:** jawab `400`. Bila terjadi pada kiriman asli, laporkan ke tim Plasgos dengan waktu kirim dan header id event-nya.
|
|
387
|
+
|
|
388
|
+
### `header_mismatch`
|
|
389
|
+
|
|
390
|
+
- **Arti:** tanda tangan cocok, tetapi `id` atau `type` di body berbeda dari header id atau type. `header` menyebut yang mana.
|
|
391
|
+
- **Penyebab umum:** header diubah di jalan, misalnya kiriman lama diputar ulang dengan id baru supaya lolos dedup. Header id dan type tidak ikut ditandatangani, jadi SDK memakai nilai dari body.
|
|
392
|
+
- **Yang dilakukan:** jawab `400`. Jangan proses.
|
|
393
|
+
|
|
394
|
+
### `ConfigError` dari `createWebhookVerifier`
|
|
395
|
+
|
|
396
|
+
`createWebhookVerifier` (dan `verifyWebhook`, di setiap panggilan) melempar satu `ConfigError` berisi semua masalah. Bentuk `ConfigError` sama dengan [§4](#4-configerror).
|
|
397
|
+
|
|
398
|
+
| Pesan | Perbaikan |
|
|
399
|
+
|---|---|
|
|
400
|
+
| `options must be an object` | Argumen bukan objek |
|
|
401
|
+
| `environment must be "sandbox" or "production"` | Isi `environment` (env `PLASGOS_ENV`) dengan salah satu dari dua nilai itu |
|
|
402
|
+
| `secrets must hold one or two values` | `secrets` harus array berisi satu atau dua string setelah nilai kosong dibuang. Biasanya env secret kosong, atau berisi lebih dari dua nilai |
|
|
403
|
+
| `secrets values must each be at least 32 bytes` | Secret terlalu pendek. Periksa bahwa env berisi secret utuh dari tim Plasgos |
|
|
404
|
+
| `preset is required` | Isi `preset` dengan `presets.payments` atau `presets.plaslinkShipping` |
|
|
405
|
+
| `preset must be one of presets or an object with name and headers` | `preset` berupa string atau bentuknya salah. Pakai `presets.payments`, bukan `"payments"` |
|
|
406
|
+
| `preset.name must match /^[A-Za-z0-9_-]{1,64}$/` | Preset sendiri: perbaiki `name` |
|
|
407
|
+
| `preset.headers.<peran> must be an HTTP header name of at most 64 characters` | Preset sendiri: nama header untuk `id`, `type`, `timestamp`, atau `signature` salah |
|
|
408
|
+
| `preset.headers must name four distinct headers` | Preset sendiri: dua peran memakai header yang sama |
|
|
409
|
+
| `toleranceSeconds must be an integer from 1 to 900` | Pakai bilangan bulat detik, bukan string |
|
|
410
|
+
| `toleranceSeconds above 300 is not allowed when environment is "production"` | Di production, paling besar 300 |
|
|
411
|
+
| `maxBodyBytes must be an integer from 1024 to 16777216` | Pakai bilangan bulat byte |
|
|
412
|
+
|
|
413
|
+
### `TypeError` dari `verify`
|
|
414
|
+
|
|
415
|
+
Argumen `verify` yang salah adalah bug di kode pemanggil, bukan kiriman yang ditolak.
|
|
416
|
+
|
|
417
|
+
| Pesan | Penyebab |
|
|
418
|
+
|---|---|
|
|
419
|
+
| `verifyWebhook: input must be an object with headers and rawBody` | Argumen bukan objek |
|
|
420
|
+
| `verifyWebhook: headers must be a Headers or a plain object of header values` | `headers` bukan `Headers` dan bukan objek |
|
|
421
|
+
| `verifyWebhook: rawBody must be the raw request body as a string or Uint8Array, before JSON parsing` | Body yang diberikan sudah di-parse (objek), kosong (`undefined`), atau tipe lain. Berikan body mentah ([`webhook.md` §5](webhook.md#5-body-mentah-per-framework)) |
|
|
422
|
+
| `verifyWebhook: now must be a finite number of epoch milliseconds` | `now` bukan angka milidetik |
|
|
423
|
+
|
|
424
|
+
Pesan yang sama dipakai oleh `verifier.verify` dan `verifyWebhook`.
|
|
425
|
+
|
|
426
|
+
## 8. `AuthVerifyError`
|
|
427
|
+
|
|
428
|
+
**Menyusul bersama verifikasi access token** (`@plasgos/auth-verify`).
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { createWebhookVerifier, presets } from "@plasgos/auth-verify/webhook";
|
|
2
|
+
import type { VerifiedWebhook, WebhookVerifier } from "@plasgos/auth-verify/webhook";
|
|
3
|
+
|
|
4
|
+
// #region webhook
|
|
5
|
+
/** Once, at start: a wrong option throws one ConfigError here. */
|
|
6
|
+
export function createVerifier(): WebhookVerifier {
|
|
7
|
+
return createWebhookVerifier({
|
|
8
|
+
environment: "production",
|
|
9
|
+
secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
|
|
10
|
+
preset: presets.payments,
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Per delivery: the headers and the raw body, before JSON parsing. Throws WebhookVerifyError. */
|
|
15
|
+
export function receive(verifier: WebhookVerifier, request: Request, rawBody: Uint8Array): VerifiedWebhook {
|
|
16
|
+
return verifier.verify({ headers: request.headers, rawBody });
|
|
17
|
+
}
|
|
18
|
+
// #endregion webhook
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The problems of a ConfigError, or null when `error` is something else. `instanceof ConfigError`
|
|
3
|
+
* works too when the class is imported from `@plasgos/oidc-client`; checking the name also works
|
|
4
|
+
* when the app loads the SDK through both `import` and `require`.
|
|
5
|
+
*/
|
|
6
|
+
export function configProblems(error: unknown): string[] | null {
|
|
7
|
+
if (!(error instanceof Error) || error.name !== "ConfigError") return null;
|
|
8
|
+
const problems: unknown = "problems" in error ? error.problems : undefined;
|
|
9
|
+
if (!Array.isArray(problems)) return [error.message];
|
|
10
|
+
return problems.filter((problem): problem is string => typeof problem === "string");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Runs `create` at start. A configuration mistake stops the process with every problem printed. */
|
|
14
|
+
export function createOrExit<T>(create: () => T): T {
|
|
15
|
+
try {
|
|
16
|
+
return create();
|
|
17
|
+
} catch (error) {
|
|
18
|
+
const problems = configProblems(error);
|
|
19
|
+
if (problems === null) throw error;
|
|
20
|
+
process.stderr.write("Plasgos configuration is invalid:\n");
|
|
21
|
+
for (const problem of problems) process.stderr.write(`- ${problem}\n`);
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/** Same values as the SDK's `Environment` type. */
|
|
2
|
+
type Environment = "sandbox" | "production";
|
|
3
|
+
|
|
4
|
+
function required(name: string): string {
|
|
5
|
+
const value = process.env[name]?.trim() ?? "";
|
|
6
|
+
if (value === "") throw new Error(`Environment variable ${name} is required`);
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function optional(name: string): string | undefined {
|
|
11
|
+
const value = process.env[name]?.trim() ?? "";
|
|
12
|
+
return value === "" ? undefined : value;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** PLASGOS_ENV: "sandbox" or "production". There is no default on purpose. */
|
|
16
|
+
export function readEnvironment(): Environment {
|
|
17
|
+
const value = required("PLASGOS_ENV");
|
|
18
|
+
if (value !== "sandbox" && value !== "production") {
|
|
19
|
+
throw new Error('Environment variable PLASGOS_ENV must be "sandbox" or "production"');
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** What every Plasgos client of this app shares. */
|
|
25
|
+
export interface PlasgosEnv {
|
|
26
|
+
environment: Environment;
|
|
27
|
+
/** PLASGOS_ISSUER: where users log in and tokens are issued. */
|
|
28
|
+
issuer: string;
|
|
29
|
+
/** PLASGOS_API_URL: where /v5/* lives. */
|
|
30
|
+
apiUrl: string;
|
|
31
|
+
/** PLASGOS_BACKCHANNEL_URL: optional internal origin of the Plasgos server, only inside the Plasgos network. */
|
|
32
|
+
backchannelUrl: string | undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function readPlasgosEnv(): PlasgosEnv {
|
|
36
|
+
return {
|
|
37
|
+
environment: readEnvironment(),
|
|
38
|
+
issuer: required("PLASGOS_ISSUER"),
|
|
39
|
+
apiUrl: required("PLASGOS_API_URL"),
|
|
40
|
+
backchannelUrl: optional("PLASGOS_BACKCHANNEL_URL"),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Credentials of the service client (server-to-server). */
|
|
45
|
+
export interface ServiceCredentials {
|
|
46
|
+
clientId: string;
|
|
47
|
+
clientSecret: string;
|
|
48
|
+
/** PLASGOS_AUDIENCE: only when the environment does not use the default platform audience. */
|
|
49
|
+
audience: string | undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function readServiceCredentials(): ServiceCredentials {
|
|
53
|
+
return {
|
|
54
|
+
clientId: required("PLASGOS_SERVICE_CLIENT_ID"),
|
|
55
|
+
clientSecret: required("PLASGOS_SERVICE_CLIENT_SECRET"),
|
|
56
|
+
audience: optional("PLASGOS_AUDIENCE"),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Credentials of the login client (interactive), and the public origin of this app. */
|
|
61
|
+
export interface LoginCredentials {
|
|
62
|
+
clientId: string;
|
|
63
|
+
clientSecret: string;
|
|
64
|
+
/** APP_URL: public origin of this app, for example https://app.example.com. */
|
|
65
|
+
appUrl: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function readLoginCredentials(): LoginCredentials {
|
|
69
|
+
return {
|
|
70
|
+
clientId: required("PLASGOS_LOGIN_CLIENT_ID"),
|
|
71
|
+
clientSecret: required("PLASGOS_LOGIN_CLIENT_SECRET"),
|
|
72
|
+
appUrl: required("APP_URL").replace(/\/$/, ""),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** SESSION_SECRET: one secret, or "new,old" while a rotation is in progress. */
|
|
77
|
+
export function readSessionSecrets(): string[] {
|
|
78
|
+
const secrets = required("SESSION_SECRET")
|
|
79
|
+
.split(",")
|
|
80
|
+
.map((secret) => secret.trim())
|
|
81
|
+
.filter((secret) => secret !== "");
|
|
82
|
+
if (secrets.length > 2) throw new Error("Environment variable SESSION_SECRET holds at most two secrets");
|
|
83
|
+
return secrets;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// #region webhook-secrets
|
|
87
|
+
/**
|
|
88
|
+
* A webhook secret: one secret, or "new,old" while a rotation is in progress. Names used in the guides:
|
|
89
|
+
* PLASGOS_WEBHOOK_SECRET (payments) and PLASGOS_SHIPPING_WEBHOOK_SECRET (Plaslink shipping).
|
|
90
|
+
*/
|
|
91
|
+
export function readWebhookSecrets(name: string): string[] {
|
|
92
|
+
const secrets = required(name)
|
|
93
|
+
.split(",")
|
|
94
|
+
.map((secret) => secret.trim())
|
|
95
|
+
.filter((secret) => secret !== "");
|
|
96
|
+
if (secrets.length > 2) throw new Error(`Environment variable ${name} holds at most two secrets`);
|
|
97
|
+
return secrets;
|
|
98
|
+
}
|
|
99
|
+
// #endregion webhook-secrets
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { OidcFailureEvent } from "@plasgos/oidc-client";
|
|
2
|
+
|
|
3
|
+
/** One line per failure. The event never holds a token, a secret or a response body, so it is safe to log. */
|
|
4
|
+
export function logFailure(event: OidcFailureEvent): void {
|
|
5
|
+
const line = [
|
|
6
|
+
"plasgos auth failed:",
|
|
7
|
+
`env=${event.environment}`,
|
|
8
|
+
`operation=${event.operation}`,
|
|
9
|
+
`reason=${event.reason}`,
|
|
10
|
+
`call=${event.method ?? "-"} ${event.path ?? "-"}`,
|
|
11
|
+
`status=${event.status === null ? "-" : String(event.status)}`,
|
|
12
|
+
`request_id=${event.requestId ?? "-"}`,
|
|
13
|
+
`provider_error=${event.providerError ?? "-"}`,
|
|
14
|
+
].join(" ");
|
|
15
|
+
process.stderr.write(`${line}\n`);
|
|
16
|
+
// A wrong secret, scope or grant is a bug in this app's configuration: page someone.
|
|
17
|
+
if (event.reason === "config_invalid") process.stderr.write("ALERT plasgos client configuration refused\n");
|
|
18
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createOidcClient } from "@plasgos/oidc-client";
|
|
2
|
+
import type { OidcClient } from "@plasgos/oidc-client";
|
|
3
|
+
|
|
4
|
+
import { readLoginCredentials, readPlasgosEnv } from "./env.js";
|
|
5
|
+
import { logFailure } from "./failure-log.js";
|
|
6
|
+
|
|
7
|
+
// #region first-party
|
|
8
|
+
/** A Plasgos app (BFF): tokens for one Plasgos API, refresh token, logout without a confirmation page. */
|
|
9
|
+
export function createFirstPartyClient(): OidcClient {
|
|
10
|
+
const env = readPlasgosEnv();
|
|
11
|
+
const credentials = readLoginCredentials();
|
|
12
|
+
return createOidcClient({
|
|
13
|
+
environment: env.environment,
|
|
14
|
+
issuer: env.issuer,
|
|
15
|
+
backchannelUrl: env.backchannelUrl,
|
|
16
|
+
clientId: credentials.clientId,
|
|
17
|
+
clientSecret: credentials.clientSecret,
|
|
18
|
+
redirectUri: `${credentials.appUrl}/auth/callback`,
|
|
19
|
+
postLogoutRedirectUri: `${credentials.appUrl}/`,
|
|
20
|
+
scopes: ["openid", "profile", "email", "packages:read", "packages:write"],
|
|
21
|
+
profile: "first-party",
|
|
22
|
+
// The audience of the API this app calls. Required by the packages:* scopes.
|
|
23
|
+
resource: process.env.PLASGOS_RESOURCE,
|
|
24
|
+
onFailure: logFailure,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
// #endregion first-party
|
|
28
|
+
|
|
29
|
+
// #region third-party
|
|
30
|
+
/** An app outside Plasgos: identity only. No resource, no logout ticket. */
|
|
31
|
+
export function createThirdPartyClient(): OidcClient {
|
|
32
|
+
const env = readPlasgosEnv();
|
|
33
|
+
const credentials = readLoginCredentials();
|
|
34
|
+
return createOidcClient({
|
|
35
|
+
environment: env.environment,
|
|
36
|
+
issuer: env.issuer,
|
|
37
|
+
clientId: credentials.clientId,
|
|
38
|
+
clientSecret: credentials.clientSecret,
|
|
39
|
+
redirectUri: `${credentials.appUrl}/auth/callback`,
|
|
40
|
+
postLogoutRedirectUri: `${credentials.appUrl}/`,
|
|
41
|
+
scopes: ["openid", "profile", "email", "plaslink:shipping"],
|
|
42
|
+
profile: "third-party",
|
|
43
|
+
onFailure: logFailure,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
// #endregion third-party
|