@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.
- package/CHANGELOG.md +27 -0
- package/LICENSE +15 -0
- package/README.md +122 -2
- package/THIRD_PARTY_NOTICES.md +31 -0
- package/dist/express.cjs +157 -0
- package/dist/express.cjs.map +1 -0
- package/dist/express.d.cts +90 -0
- package/dist/express.d.ts +90 -0
- package/dist/express.js +127 -0
- package/dist/express.js.map +1 -0
- package/dist/index.cjs +1254 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +67 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.js +499 -0
- package/dist/index.js.map +1 -0
- package/dist/nestjs.cjs +1395 -0
- package/dist/nestjs.cjs.map +1 -0
- package/dist/nestjs.d.cts +153 -0
- package/dist/nestjs.d.ts +153 -0
- package/dist/nestjs.js +637 -0
- package/dist/nestjs.js.map +1 -0
- package/dist/types-CGtRnj59.d.cts +193 -0
- package/dist/types-CGtRnj59.d.ts +193 -0
- package/dist/webhook.cjs +296 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +196 -0
- package/dist/webhook.d.ts +196 -0
- package/dist/webhook.js +265 -0
- package/dist/webhook.js.map +1 -0
- package/docs/bff-express.md +1314 -0
- package/docs/consumers.md +98 -0
- package/docs/contoh-hitungcuan.md +255 -0
- package/docs/contoh-plaslink.md +244 -0
- package/docs/error.md +613 -0
- package/docs/examples/auth-verify-readme.ts +42 -0
- package/docs/examples/bff-express.ts +370 -0
- package/docs/examples/bff-proxy.ts +335 -0
- package/docs/examples/bff-redis-lock.ts +187 -0
- package/docs/examples/bff-revocation.ts +136 -0
- package/docs/examples/config-error.ts +24 -0
- package/docs/examples/env.ts +150 -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/token-commonjs.cjs +95 -0
- package/docs/examples/token-express.ts +56 -0
- package/docs/examples/token-fetch.ts +24 -0
- package/docs/examples/token-nestjs-jest.ts +77 -0
- package/docs/examples/token-nestjs.ts +127 -0
- package/docs/examples/token-socket.ts +59 -0
- package/docs/examples/token-testing.ts +100 -0
- package/docs/examples/token-verifier.ts +132 -0
- package/docs/examples/user-events.ts +110 -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 +197 -0
- package/docs/login-web.md +650 -0
- package/docs/memulai.md +419 -0
- package/docs/server-ke-server.md +287 -0
- package/docs/verifikasi-token.md +1219 -0
- package/docs/webhook.md +810 -0
- package/package.json +101 -3
|
@@ -0,0 +1,1314 @@
|
|
|
1
|
+
# BFF untuk Node/Express
|
|
2
|
+
|
|
3
|
+
Panduan ini untuk tim yang membangun **BFF** (backend-for-frontend) dengan Node dan Express: server milik aplikasi yang memegang sesi login user untuk sebuah SPA atau PWA, lalu meneruskan request browser ke API milik aplikasi dengan access token Plasgos. Isinya: login, sesi cookie, refresh dengan lock Redis untuk banyak instance, logout, BFF di bawah sub-path, pencabutan sesi, proxy HTTP dan socket, dan CSRF.
|
|
4
|
+
|
|
5
|
+
Panduan ini ditulis untuk developer backend yang belum pernah melihat bagian dalam Plasgos. Semua contoh lolos typecheck dan bisa disalin. Istilah yang dipakai di sini (audience, BFF, `sub` pairwise, `sid`, `cv`, dan `plasgos_public_id`) dijelaskan di [`memulai.md` §3](memulai.md#istilah).
|
|
6
|
+
|
|
7
|
+
Urutan kerja:
|
|
8
|
+
|
|
9
|
+
1. Pastikan BFF yang Anda butuhkan ([§1](#1-apa-itu-bff-dan-kapan-dipakai)).
|
|
10
|
+
2. Minta client login ke tim Plasgos dan install paket ([§3](#3-prasyarat)), lalu atur env ([§4](#4-env)).
|
|
11
|
+
3. Buat client, session store, dan lock Redis saat start ([§5](#5-setup)).
|
|
12
|
+
4. Pasang route login, callback, `/auth/me`, dan logout ([§6](#6-login)–[§10](#10-logout-dan-logout-ticket)).
|
|
13
|
+
5. Pasang pemeriksaan pencabutan sesi ([§12](#12-pencabutan-sesi)).
|
|
14
|
+
6. Pasang proxy API dan socket ([§13](#13-proxy-ke-api), [§14](#14-proxy-socket)) dan aturan CSRF ([§15](#15-csrf)).
|
|
15
|
+
7. Periksa daftar sebelum production ([§19](#19-sebelum-production)).
|
|
16
|
+
|
|
17
|
+
## 1. Apa itu BFF dan kapan dipakai
|
|
18
|
+
|
|
19
|
+
Dengan BFF, **token Plasgos tidak pernah sampai ke browser**. Browser hanya memegang cookie sesi yang tersegel (`HttpOnly`, tidak bisa dibaca JavaScript). SPA atau PWA memanggil BFF di origin-nya sendiri; BFF menyisipkan access token dan meneruskan request ke API Anda. Script jahat di halaman tidak bisa mencuri token yang tidak pernah ada di halaman.
|
|
20
|
+
|
|
21
|
+
| Situasi | Panduan |
|
|
22
|
+
|---|---|
|
|
23
|
+
| SPA atau PWA dengan server Node/Express sendiri yang memegang sesi dan meneruskan request ke API Anda | Panduan ini |
|
|
24
|
+
| Aplikasi web yang merender halaman di server (React Router, framework berbasis `Request`) | [`login-web.md`](login-web.md). Aturan login, sesi, dan refresh-nya sama; panduan ini menambahkan versi Express, lock Redis, proxy, dan pencabutan sesi |
|
|
25
|
+
| API Anda yang menerima token dari BFF | [`verifikasi-token.md`](verifikasi-token.md) |
|
|
26
|
+
| Server Anda memanggil API Plasgos tanpa user | [`server-ke-server.md`](server-ke-server.md) |
|
|
27
|
+
|
|
28
|
+
## 2. Arsitektur
|
|
29
|
+
|
|
30
|
+
```text
|
|
31
|
+
cookie sesi (HttpOnly) Authorization: Bearer <token>
|
|
32
|
+
Browser (SPA/PWA) ─────────────────────> BFF ───────────────────────────────> API Anda
|
|
33
|
+
│ │ (verifikasi token,
|
|
34
|
+
login, refresh, logout ──────┘ │ @plasgos/auth-verify)
|
|
35
|
+
Plasgos │ lock refresh, marker pencabutan
|
|
36
|
+
└────────────> Redis <──── penerima webhook (event user.*)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Route BFF:
|
|
40
|
+
|
|
41
|
+
| Route | Untuk |
|
|
42
|
+
|---|---|
|
|
43
|
+
| `GET /auth/login?return_to=/path` | Mulai login: redirect satu halaman penuh ke Plasgos |
|
|
44
|
+
| `GET /auth/callback` | Plasgos mengembalikan browser ke sini; BFF menulis sesi |
|
|
45
|
+
| `GET /auth/me` | Siapa yang login (tanpa token). Juga memperbarui access token yang hampir habis |
|
|
46
|
+
| `POST /auth/logout` | Logout dari form aplikasi |
|
|
47
|
+
| `/api/*` | Proxy ke `/api/*` API Anda, dengan access token sesi |
|
|
48
|
+
| `/socket.io/` | Proxy Socket.IO ke `/socket.io/` API Anda: upgrade WebSocket dan request long-polling |
|
|
49
|
+
|
|
50
|
+
## 3. Prasyarat
|
|
51
|
+
|
|
52
|
+
- Node `>=22.22`, Express 4 atau 5, dan client Redis (misalnya `ioredis`) milik aplikasi Anda. Contoh tidak meng-import library Redis atau proxy: Redis dipakai lewat interface `RedisLike` (tiga perintah), dan proxy memakai `node:http` dan `fetch`.
|
|
53
|
+
- Install dengan nomor versi persis:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pnpm add @plasgos/oidc-client@<versi> --save-exact
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
**Yang disiapkan bersama tim Plasgos** (satu kali untuk sandbox dan satu kali untuk production). Anda mengirim ke tim Plasgos: redirect URI yang persis (misalnya `https://app.example.com/auth/callback`, atau `https://app.example.com/crm/auth/callback` di bawah sub-path), URL setelah logout, scope yang dibutuhkan, dan URL webhook bila BFF atau API Anda menerima event `user.*`. Tim Plasgos menyerahkan kepada Anda:
|
|
60
|
+
|
|
61
|
+
| Yang Anda terima | Env |
|
|
62
|
+
|---|---|
|
|
63
|
+
| Client id dan client secret client login first-party | `PLASGOS_LOGIN_CLIENT_ID`, `PLASGOS_LOGIN_CLIENT_SECRET` |
|
|
64
|
+
| Issuer lingkungan itu | `PLASGOS_ISSUER` |
|
|
65
|
+
| Audience API Anda (resource), misalnya `https://api.plasgos.co.id/crm` | `PLASGOS_RESOURCE` |
|
|
66
|
+
| Alamat internal server Plasgos, hanya bila BFF berjalan di jaringan Plasgos | `PLASGOS_BACKCHANNEL_URL` |
|
|
67
|
+
| Secret webhook, bila menerima event | Lihat [`webhook.md`](webhook.md) |
|
|
68
|
+
|
|
69
|
+
Scope seperti `crm:access` hanya untuk client first-party dan wajib bersama `resource` ([`memulai.md` §4](memulai.md#4-daftar-scope)). Minta juga scope `plasgos:public_id` (juga hanya untuk client first-party): tanpa scope itu access token tidak membawa `plasgos_public_id`, API yang mewajibkan klaim itu menolak setiap token dengan `401`, dan pemeriksaan blokir user di BFF ([§12](#12-pencabutan-sesi)) tidak bisa berjalan.
|
|
70
|
+
|
|
71
|
+
## 4. Env
|
|
72
|
+
|
|
73
|
+
| Env | Wajib | Contoh | Sandbox | Production |
|
|
74
|
+
|---|---|---|---|---|
|
|
75
|
+
| `PLASGOS_ENV` | Ya | `sandbox` | `sandbox` | `production` |
|
|
76
|
+
| `PLASGOS_ISSUER` | Ya | `https://accounts.plasgos.co.id` | Host accounts sandbox dari tim Plasgos | Persis `https://accounts.plasgos.co.id` |
|
|
77
|
+
| `PLASGOS_BACKCHANNEL_URL` | Tidak | `http://plasgos.internal.example:8080` (contoh) | Boleh `http:`, bukan host production | Hanya di jaringan Plasgos. Tanpa nilai ini tidak ada logout ticket ([§10](#10-logout-dan-logout-ticket)) |
|
|
78
|
+
| `PLASGOS_LOGIN_CLIENT_ID`, `PLASGOS_LOGIN_CLIENT_SECRET` | Ya | | Kredensial sandbox | Kredensial production. Secret di secret manager |
|
|
79
|
+
| `PLASGOS_RESOURCE` | Ya | `https://api.plasgos.co.id/crm` | Audience sandbox dari tim Plasgos | Diawali `https://api.plasgos.co.id/` |
|
|
80
|
+
| `APP_URL` | Ya | `https://app.example.com` | Origin publik BFF sandbox | Origin publik BFF production. Tanpa path dan tanpa `/` di akhir |
|
|
81
|
+
| `APP_API_URL` | Ya | `http://api.internal:8080` (contoh) | Origin API Anda | Origin API Anda. Nilai milik aplikasi, bukan dari Plasgos |
|
|
82
|
+
| `SESSION_SECRET` | Ya | | Minimal 32 byte | Berbeda dari sandbox. Saat rotasi: `baru,lama` ([`login-web.md` §7](login-web.md#7-rotasi-secret-sesi)) |
|
|
83
|
+
|
|
84
|
+
Alamat Redis adalah milik aplikasi Anda dan tidak dibaca SDK. Pembacaan env, dari `env.ts` ([`memulai.md` §5](memulai.md#5-env-yang-disarankan)):
|
|
85
|
+
|
|
86
|
+
<!-- snippet: examples/snippets/env.ts#bff -->
|
|
87
|
+
```ts
|
|
88
|
+
/** What a backend-for-frontend (BFF) reads besides its login credentials and its session secret. */
|
|
89
|
+
export interface BffEnv {
|
|
90
|
+
environment: Environment;
|
|
91
|
+
/** PLASGOS_ISSUER: where users log in and tokens are issued. */
|
|
92
|
+
issuer: string;
|
|
93
|
+
/** PLASGOS_BACKCHANNEL_URL: optional internal origin of the Plasgos server, only inside the Plasgos network. */
|
|
94
|
+
backchannelUrl: string | undefined;
|
|
95
|
+
/** PLASGOS_RESOURCE: the audience of the app's own API; every token is requested for it. */
|
|
96
|
+
resource: string;
|
|
97
|
+
/** APP_API_URL: origin of the app's own API behind the BFF (not a Plasgos value). */
|
|
98
|
+
apiOrigin: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function readBffEnv(): BffEnv {
|
|
102
|
+
return {
|
|
103
|
+
environment: readEnvironment(),
|
|
104
|
+
issuer: required("PLASGOS_ISSUER"),
|
|
105
|
+
backchannelUrl: optional("PLASGOS_BACKCHANNEL_URL"),
|
|
106
|
+
resource: required("PLASGOS_RESOURCE"),
|
|
107
|
+
apiOrigin: required("APP_API_URL").replace(/\/$/, ""),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
<!-- /snippet -->
|
|
112
|
+
|
|
113
|
+
## 5. Setup
|
|
114
|
+
|
|
115
|
+
Client, session store, dan lock Redis dibuat **sekali saat start**. Opsi yang salah menghentikan proses dengan satu `ConfigError` ([`memulai.md` §7](memulai.md#7-bila-konfigurasi-salah)).
|
|
116
|
+
|
|
117
|
+
<!-- snippet: examples/snippets/bff-express.ts#setup -->
|
|
118
|
+
```ts
|
|
119
|
+
/** This BFF keeps no data of its own in the session, only the SDK's auth. */
|
|
120
|
+
export type BffSession = object;
|
|
121
|
+
export type BffSessionHandle = SessionHandle<BffSession>;
|
|
122
|
+
|
|
123
|
+
const bffSchema: SessionSchema<BffSession> = {
|
|
124
|
+
parse: (input) => (typeof input === "object" && input !== null ? {} : null),
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/** Everything the routes need. Created once at start: a wrong option stops the process with a ConfigError. */
|
|
128
|
+
export interface Bff {
|
|
129
|
+
client: OidcClient;
|
|
130
|
+
store: SessionStore<BffSession>;
|
|
131
|
+
redis: RedisLike;
|
|
132
|
+
markerKeys: MarkerKeys;
|
|
133
|
+
/** Public origin of the BFF (APP_URL), for the Origin checks and the callback URL. */
|
|
134
|
+
appOrigin: string;
|
|
135
|
+
/** "" at the root of the host, or a sub-path such as "/crm". */
|
|
136
|
+
basePath: string;
|
|
137
|
+
/** Origin of the app's own API, which verifies the token with @plasgos/auth-verify. */
|
|
138
|
+
apiOrigin: string;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function createBff(redis: RedisLike, basePath = ""): Bff {
|
|
142
|
+
const env = readBffEnv();
|
|
143
|
+
const credentials = readLoginCredentials();
|
|
144
|
+
const secrets = readSessionSecrets();
|
|
145
|
+
const client = createOidcClient({
|
|
146
|
+
environment: env.environment,
|
|
147
|
+
issuer: env.issuer,
|
|
148
|
+
// Only inside the Plasgos network. There is no logoutTicket option here on purpose: it is on by
|
|
149
|
+
// default for a first-party client with endSession "redirect" and a backchannelUrl, and an
|
|
150
|
+
// explicit true without backchannelUrl is a ConfigError. Without backchannelUrl there is no
|
|
151
|
+
// ticket, and Plasgos asks the user to confirm the logout.
|
|
152
|
+
backchannelUrl: env.backchannelUrl,
|
|
153
|
+
clientId: credentials.clientId,
|
|
154
|
+
clientSecret: credentials.clientSecret,
|
|
155
|
+
redirectUri: `${credentials.appUrl}${basePath}/auth/callback`,
|
|
156
|
+
postLogoutRedirectUri: `${credentials.appUrl}${basePath}/`,
|
|
157
|
+
// plasgos:public_id puts the user's public id (plasgos_public_id) into the access token; without it
|
|
158
|
+
// an API that requires the claim refuses every token with 401. crm:access is the example API's scope.
|
|
159
|
+
scopes: ["openid", "profile", "email", "plasgos:public_id", "crm:access"],
|
|
160
|
+
profile: "first-party",
|
|
161
|
+
// The audience of the app's own API: every access token is issued for it.
|
|
162
|
+
resource: env.resource,
|
|
163
|
+
// One refresh per refresh token across every instance of the BFF.
|
|
164
|
+
refreshLock: redisRefreshLock(redis, tokenSealer(secrets)),
|
|
165
|
+
onFailure: logFailure,
|
|
166
|
+
});
|
|
167
|
+
const store = createSessionStore<BffSession>({
|
|
168
|
+
environment: env.environment,
|
|
169
|
+
secrets,
|
|
170
|
+
// Never change the salt, the names or the path after the first release: every user would be signed out.
|
|
171
|
+
hkdfSalt: "contoh-bff",
|
|
172
|
+
cookies: { app: "bff", auth: "bff-auth", idToken: "bff-idt", transaction: "bff-oidc" },
|
|
173
|
+
// "/" at the root of the host: __Host- cookies. Under a sub-path: __Secure- cookies with that Path.
|
|
174
|
+
path: `${basePath}/`,
|
|
175
|
+
authMaxAgeSeconds: 2_592_000,
|
|
176
|
+
appSchema: bffSchema,
|
|
177
|
+
});
|
|
178
|
+
return { client, store, redis, markerKeys, appOrigin: credentials.appUrl, basePath, apiOrigin: env.apiOrigin };
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
<!-- /snippet -->
|
|
182
|
+
|
|
183
|
+
- `refreshLock: redisRefreshLock(…)` menjalankan satu refresh per refresh token di semua instance ([§9](#9-refresh-dan-lock-redis)).
|
|
184
|
+
- `logoutTicket` sengaja tidak diisi. Bawaannya `true` untuk client first-party dengan `endSession: "redirect"` dan `backchannelUrl`; `logoutTicket: true` tanpa `backchannelUrl` adalah `ConfigError`.
|
|
185
|
+
- `path` dari `basePath`: `"/"` di root host (cookie `__Host-`), atau sub-path ([§11](#11-bff-di-bawah-sub-path)).
|
|
186
|
+
- `hkdfSalt`, nama cookie, dan `path` jangan diubah setelah rilis: semua user harus login ulang.
|
|
187
|
+
|
|
188
|
+
Potongan kode di panduan ini berasal dari file yang lolos typecheck, lengkap dengan import-nya: [`bff-express.ts`](examples/bff-express.ts), [`bff-redis-lock.ts`](examples/bff-redis-lock.ts), [`bff-revocation.ts`](examples/bff-revocation.ts), [`bff-proxy.ts`](examples/bff-proxy.ts), [`env.ts`](examples/env.ts), dan [`failure-log.ts`](examples/failure-log.ts). Import SDK berasal dari `@plasgos/oidc-client` dan `@plasgos/oidc-client/session`.
|
|
189
|
+
|
|
190
|
+
## 6. Login
|
|
191
|
+
|
|
192
|
+
<!-- snippet: examples/snippets/bff-express.ts#login -->
|
|
193
|
+
```ts
|
|
194
|
+
/**
|
|
195
|
+
* Only a path of this app: basePath itself or a path below it ("/crm", "/crm/…"; any path when basePath
|
|
196
|
+
* is ""). Printable ASCII, no "//", no backslash, no "." or ".." segment (also as %2e), no encoded "/"
|
|
197
|
+
* or "\" (%2f, %5c). It starts with "/" and has no "//", so it never carries a scheme or another host.
|
|
198
|
+
*/
|
|
199
|
+
export function safeReturnTo(value: unknown, basePath: string): string {
|
|
200
|
+
const fallback = `${basePath}/`;
|
|
201
|
+
if (typeof value !== "string" || value.length > 512) return fallback;
|
|
202
|
+
if (!/^\/[\x21-\x7E]*$/.test(value) || value.includes("//") || value.includes("\\")) return fallback;
|
|
203
|
+
if (value !== basePath && !value.startsWith(`${basePath}/`)) return fallback;
|
|
204
|
+
const path = value.split(/[?#]/, 1)[0] ?? "";
|
|
205
|
+
if (/%(?:2f|5c)/i.test(path)) return fallback;
|
|
206
|
+
const segments = path.split("/").map((segment) => segment.replace(/%2e/gi, "."));
|
|
207
|
+
if (segments.some((segment) => segment === "." || segment === "..")) return fallback;
|
|
208
|
+
return value;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** GET /auth/login?return_to=/path: a full-page redirect to Plasgos. */
|
|
212
|
+
function login(bff: Bff, req: Request, res: Response): void {
|
|
213
|
+
const returnTo = safeReturnTo(req.query["return_to"], bff.basePath);
|
|
214
|
+
const { location, transaction } = bff.client.startLogin({ returnTo });
|
|
215
|
+
res.append("Set-Cookie", bff.store.commitTransaction(transaction));
|
|
216
|
+
res.set("Cache-Control", "no-store").redirect(302, location);
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
<!-- /snippet -->
|
|
220
|
+
|
|
221
|
+
- SPA mengarahkan browser (navigasi satu halaman penuh, bukan `fetch`) ke `/auth/login?return_to=<path sekarang>`.
|
|
222
|
+
- `return_to` datang dari URL, jadi hanya path milik BFF yang diterima: `basePath` itu sendiri atau path di bawahnya (`/crm` atau `/crm/…`; di root host, path apa saja), hanya karakter ASCII yang terlihat, tanpa `//`, tanpa backslash, tanpa segmen `.` atau `..` (juga dalam bentuk `%2e`), dan tanpa `/` atau `\` yang di-encode (`%2f`, `%5c`). Karena selalu diawali `/` tanpa `//`, nilai itu tidak pernah membawa skema atau host lain. Nilai lain diganti halaman utama BFF. Dengan begitu login tidak bisa dipakai untuk mengarahkan user ke situs lain atau ke aplikasi lain di host yang sama.
|
|
223
|
+
- `startLogin` tidak memanggil Plasgos. Transaksinya (`state`, `nonce`, `code_verifier`) disimpan di cookie transaksi yang berumur 10 menit.
|
|
224
|
+
|
|
225
|
+
## 7. Callback
|
|
226
|
+
|
|
227
|
+
<!-- snippet: examples/snippets/bff-express.ts#callback -->
|
|
228
|
+
```ts
|
|
229
|
+
function loginFailed(res: Response, status: number): void {
|
|
230
|
+
res.status(status).set("Cache-Control", "no-store").type("text/plain").send("Login gagal. Silakan coba lagi.");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** GET /auth/callback: Plasgos sends the browser back here with code and state. */
|
|
234
|
+
async function callback(bff: Bff, req: Request, res: Response): Promise<void> {
|
|
235
|
+
const { client, store } = bff;
|
|
236
|
+
// The transaction is single use: its cookie is cleared on every path.
|
|
237
|
+
res.append("Set-Cookie", store.clearTransaction());
|
|
238
|
+
try {
|
|
239
|
+
// The full URL from the configured origin, never from the Host header.
|
|
240
|
+
const url = `${bff.appOrigin}${req.originalUrl}`;
|
|
241
|
+
const { tokens, claims, transaction } = await client.handleCallback(url, store.readTransaction(req.headers.cookie));
|
|
242
|
+
const auth: AuthState = {
|
|
243
|
+
access_token: tokens.access_token,
|
|
244
|
+
refresh_token: tokens.refresh_token,
|
|
245
|
+
expires_at: accessTokenExpiry(tokens, Date.now()),
|
|
246
|
+
user: { id: claims.sub, name: claims.name ?? "", email: claims.email ?? null, avatar_url: claims.picture ?? null },
|
|
247
|
+
id_token: tokens.id_token,
|
|
248
|
+
auth_time: claims.auth_time,
|
|
249
|
+
};
|
|
250
|
+
const fits = store.fits(auth);
|
|
251
|
+
if (!fits.auth) {
|
|
252
|
+
loginFailed(res, 500);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
// A fresh session, never merged into what the browser sent: a session planted before the login
|
|
256
|
+
// (for example by another app on the same host) cannot survive it.
|
|
257
|
+
const session = store.read(null);
|
|
258
|
+
session.destroy();
|
|
259
|
+
session.update({ auth: fits.idToken ? auth : { ...auth, id_token: undefined } });
|
|
260
|
+
for (const cookie of store.commit(session)) res.append("Set-Cookie", cookie);
|
|
261
|
+
res.set("Cache-Control", "no-store").redirect(302, safeReturnTo(transaction.return_to, bff.basePath));
|
|
262
|
+
} catch (error) {
|
|
263
|
+
if (!(error instanceof OidcError)) throw error;
|
|
264
|
+
loginFailed(res, error.reason === "unavailable" ? 503 : 400);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
```
|
|
268
|
+
<!-- /snippet -->
|
|
269
|
+
|
|
270
|
+
Urutannya:
|
|
271
|
+
|
|
272
|
+
1. Hapus cookie transaksi di semua jalur. Transaksi hanya boleh dipakai sekali.
|
|
273
|
+
2. Susun URL lengkap dari `APP_URL` dan path request, bukan dari header `Host` yang dikirim browser.
|
|
274
|
+
3. `handleCallback` memeriksa `state`, menukar `code` dengan token, dan memeriksa ID token. Kegagalan dilempar sebagai `OidcError`.
|
|
275
|
+
4. `fits(auth)`: pastikan cookie muat sebelum disimpan.
|
|
276
|
+
5. **Tulis sesi baru.** `store.read(null)` lalu `destroy()`: sesi lama dari browser tidak pernah digabung, jadi cookie yang ditanam sebelum login (misalnya oleh aplikasi lain di host yang sama) tidak ikut terbawa.
|
|
277
|
+
6. Redirect ke `return_to` yang disimpan di transaksi, setelah diperiksa lagi.
|
|
278
|
+
|
|
279
|
+
Jawaban gagal: `503` bila Plasgos tidak bisa dihubungi, `400` untuk kegagalan lain. Tampilkan "login gagal" dengan tombol coba lagi; jangan tampilkan `reason` mentah ([`error.md` §1](error.md#1-oidcerror)).
|
|
280
|
+
|
|
281
|
+
## 8. Sesi dan `/auth/me`
|
|
282
|
+
|
|
283
|
+
SPA memanggil `GET /auth/me` saat dimuat untuk tahu siapa yang login. Jawabannya profil user, **tidak pernah token**.
|
|
284
|
+
|
|
285
|
+
<!-- snippet: examples/snippets/bff-express.ts#me -->
|
|
286
|
+
```ts
|
|
287
|
+
/** GET /auth/me: who is signed in, for the SPA; never a token. Also renews an expiring access token. */
|
|
288
|
+
async function me(bff: Bff, req: Request, res: Response): Promise<void> {
|
|
289
|
+
const session = bff.store.read(req.headers.cookie);
|
|
290
|
+
try {
|
|
291
|
+
const auth = await checkedAuth(bff, session, requestRefresh(bff, session));
|
|
292
|
+
if (auth === null) {
|
|
293
|
+
sendJson(res, bff, session, 401, { error: "login_required" });
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
const { name, email, avatar_url } = auth.user;
|
|
297
|
+
sendJson(res, bff, session, 200, { user: { name, email, avatar_url } });
|
|
298
|
+
} catch (error) {
|
|
299
|
+
sendFailure(res, bff, session, error);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
<!-- /snippet -->
|
|
304
|
+
|
|
305
|
+
`/auth/me` menjalankan langkah yang sama dengan setiap request yang membawa sesi: perbarui access token bila hampir habis, lalu periksa pencabutan ([§12](#12-pencabutan-sesi)):
|
|
306
|
+
|
|
307
|
+
<!-- snippet: examples/snippets/bff-express.ts#fresh -->
|
|
308
|
+
```ts
|
|
309
|
+
/** OidcError reasons that end the session: Plasgos no longer accepts it. */
|
|
310
|
+
const ENDING_REASONS: ReadonlySet<string> = new Set(["invalid_grant", "invalid_target", "missing"]);
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The session's auth, renewed when the access token is about to expire (always with `force`). Null when
|
|
314
|
+
* there is no session or Plasgos ended it; the session is then destroyed here. Any other failure is
|
|
315
|
+
* thrown and the session is kept (see sendFailure).
|
|
316
|
+
*/
|
|
317
|
+
export async function freshAuth(bff: Bff, session: BffSessionHandle, force = false): Promise<AuthState | null> {
|
|
318
|
+
const current = session.data.auth;
|
|
319
|
+
if (current === undefined) return null;
|
|
320
|
+
try {
|
|
321
|
+
const { auth, changed } = await bff.client.ensureFresh(current, { force });
|
|
322
|
+
// Store a renewed auth at once: its refresh token replaced the old one at Plasgos.
|
|
323
|
+
if (changed) session.update({ auth });
|
|
324
|
+
return auth;
|
|
325
|
+
} catch (error) {
|
|
326
|
+
if (error instanceof OidcError && ENDING_REASONS.has(error.reason)) {
|
|
327
|
+
session.destroy();
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
// Redis failed before the refresh ran, so the refresh token is unused. An access token that still
|
|
331
|
+
// works carries this request; a forced refresh (its token was refused or is below a marker) cannot.
|
|
332
|
+
if (error instanceof RefreshLockUnavailableError && !force && current.expires_at * 1000 > Date.now()) return current;
|
|
333
|
+
throw error;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** The forced refreshes of one request (see ForcedRefresh), and whether one already ran. */
|
|
338
|
+
export interface RequestRefresh extends ForcedRefresh {
|
|
339
|
+
/** True once force() ran in this request: the proxy then passes an API 401 on instead of retrying. */
|
|
340
|
+
readonly forced: boolean;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Per request: at most one refresh because the token expires soon (checkedAuth), at most one forced
|
|
345
|
+
* refresh (the credential-version check or the proxy's retry after a 401, whichever asks first; the
|
|
346
|
+
* other gets the same result), and only for the credential-version check one follow-up (again()).
|
|
347
|
+
*/
|
|
348
|
+
export function requestRefresh(bff: Bff, session: BffSessionHandle): RequestRefresh {
|
|
349
|
+
let forced: Promise<AuthState | null> | undefined;
|
|
350
|
+
let again: Promise<AuthState | null> | undefined;
|
|
351
|
+
return {
|
|
352
|
+
get forced() {
|
|
353
|
+
return forced !== undefined;
|
|
354
|
+
},
|
|
355
|
+
force: () => (forced ??= freshAuth(bff, session, true)),
|
|
356
|
+
// freshAuth reads the session's auth, which force() replaced: the newest refresh token.
|
|
357
|
+
again: () => (again ??= freshAuth(bff, session, true)),
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** The request's auth: renewed when needed, then checked against the revocation markers. Null: signed out. */
|
|
362
|
+
export async function checkedAuth(bff: Bff, session: BffSessionHandle, refresh: RequestRefresh): Promise<AuthState | null> {
|
|
363
|
+
if ((await freshAuth(bff, session)) === null) return null;
|
|
364
|
+
if (!(await checkSession(bff.redis, bff.markerKeys, session, refresh))) return null;
|
|
365
|
+
return session.data.auth ?? null;
|
|
366
|
+
}
|
|
367
|
+
```
|
|
368
|
+
<!-- /snippet -->
|
|
369
|
+
|
|
370
|
+
Setiap jawaban menyertakan cookie sesi yang berubah, juga jawaban gagal:
|
|
371
|
+
|
|
372
|
+
<!-- snippet: examples/snippets/bff-express.ts#respond -->
|
|
373
|
+
```ts
|
|
374
|
+
/** Express 4 does not catch a rejected handler promise; Express 5 does. This form works with both. */
|
|
375
|
+
export function route(handler: (req: Request, res: Response) => Promise<void>) {
|
|
376
|
+
return (req: Request, res: Response, next: NextFunction): void => {
|
|
377
|
+
void handler(req, res).catch(next);
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Sends JSON with every session cookie that changed: a renewed auth, or a destroyed session. */
|
|
382
|
+
export function sendJson(res: Response, bff: Bff, session: BffSessionHandle, status: number, body: unknown): void {
|
|
383
|
+
for (const cookie of bff.store.commit(session)) res.append("Set-Cookie", cookie);
|
|
384
|
+
res.set("Cache-Control", "no-store").status(status).json(body);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* A failure that is not the end of the session. Plasgos or Redis unreachable (the markers or the
|
|
389
|
+
* refresh lock), or a refresh lock that timed out: 503, the session is kept. config_invalid or provider_error: 500 (a bug to fix, already
|
|
390
|
+
* reported through onFailure), the session is kept. Anything else is thrown to the error handler.
|
|
391
|
+
*/
|
|
392
|
+
export function sendFailure(res: Response, bff: Bff, session: BffSessionHandle, error: unknown): void {
|
|
393
|
+
const temporary =
|
|
394
|
+
(error instanceof OidcError && error.reason === "unavailable") ||
|
|
395
|
+
error instanceof RefreshLockTimeoutError ||
|
|
396
|
+
error instanceof RefreshLockUnavailableError ||
|
|
397
|
+
error instanceof MarkerStoreUnavailableError;
|
|
398
|
+
if (temporary) {
|
|
399
|
+
res.set("Retry-After", "5");
|
|
400
|
+
sendJson(res, bff, session, 503, { error: "temporarily_unavailable" });
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (error instanceof OidcError) {
|
|
404
|
+
sendJson(res, bff, session, 500, { error: "internal_error" });
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
throw error;
|
|
408
|
+
}
|
|
409
|
+
```
|
|
410
|
+
<!-- /snippet -->
|
|
411
|
+
|
|
412
|
+
- Hanya `invalid_grant`, `invalid_target`, dan `missing` yang mengakhiri sesi (tabel di [`login-web.md` §5](login-web.md#yang-dilakukan-untuk-setiap-reason)). Plasgos yang tidak bisa dihubungi, lock yang menunggu terlalu lama, atau Redis lock yang tidak bisa dihubungi dijawab `503` dan sesi **tetap**. Bila Redis lock gagal saat token hanya hampir habis (belum habis), request itu memakai access token yang masih berlaku.
|
|
413
|
+
- Dalam satu request, refresh terjadi paling banyak: sekali karena token hampir habis, sekali refresh paksa (pemeriksaan versi kredensial atau retry proxy setelah `401`, mana yang lebih dulu; yang lain memakai hasil yang sama), dan, hanya untuk pemeriksaan versi kredensial, satu refresh lanjutan ([§12](#12-pencabutan-sesi)). `requestRefresh` mencatatnya per request.
|
|
414
|
+
- Access token yang diperbarui langsung disimpan ke cookie, karena refresh token lamanya sudah tidak berlaku di Plasgos.
|
|
415
|
+
- Cookie sesi memakai atribut bawaan `login-web.md` ([§6 di sana](login-web.md#6-cookie)): `HttpOnly`, `Secure`, `SameSite=Lax`, tanpa `Domain`.
|
|
416
|
+
- Sesi tidak disimpan di server, hanya di cookie. Aplikasi yang harus mengakhiri sesi berdasarkan id sesi atau user tanpa menunggu request (misalnya memutus semua socket user yang diblokir sekaligus) menyimpan indeks sesinya sendiri di server.
|
|
417
|
+
|
|
418
|
+
## 9. Refresh dan lock Redis
|
|
419
|
+
|
|
420
|
+
Plasgos mengganti refresh token setiap kali dipakai. Bila refresh token yang sama dipakai dua kali, Plasgos menganggapnya pencurian dan **mencabut seluruh sesi user**. Dengan satu instance, `memoryLockStore()` (bawaan SDK) cukup. Dengan lebih dari satu instance, dua instance bisa me-refresh token yang sama bersamaan, jadi lock-nya harus bersama, misalnya di Redis.
|
|
421
|
+
|
|
422
|
+
Interface Redis yang dipakai, tiga perintah; client `ioredis` memenuhinya:
|
|
423
|
+
|
|
424
|
+
<!-- snippet: examples/snippets/bff-redis-lock.ts#redis-type -->
|
|
425
|
+
```ts
|
|
426
|
+
/** The three commands used; an ioredis client satisfies it. */
|
|
427
|
+
export interface RedisLike {
|
|
428
|
+
set(key: string, value: string, px: "PX", ms: number, nx: "NX"): Promise<"OK" | null>;
|
|
429
|
+
get(key: string): Promise<string | null>;
|
|
430
|
+
del(key: string): Promise<number>;
|
|
431
|
+
}
|
|
432
|
+
```
|
|
433
|
+
<!-- /snippet -->
|
|
434
|
+
|
|
435
|
+
<!-- snippet: examples/snippets/bff-redis-lock.ts#lock -->
|
|
436
|
+
```ts
|
|
437
|
+
/** No result and no free lock within `waitMs`. The route answers 503 and keeps the session. */
|
|
438
|
+
export class RefreshLockTimeoutError extends Error {
|
|
439
|
+
constructor() {
|
|
440
|
+
super("refresh lock: timed out waiting for another refresh");
|
|
441
|
+
this.name = "RefreshLockTimeoutError";
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Redis could not be reached while taking the lock or reading a stored result. Temporary: the route
|
|
447
|
+
* answers 503 and keeps the session (or keeps using an access token that is still valid).
|
|
448
|
+
*/
|
|
449
|
+
export class RefreshLockUnavailableError extends Error {
|
|
450
|
+
constructor(options?: ErrorOptions) {
|
|
451
|
+
super("refresh lock: redis unavailable", options);
|
|
452
|
+
this.name = "RefreshLockUnavailableError";
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** A Redis call of the lock; its failure becomes RefreshLockUnavailableError, never a raw client error. */
|
|
457
|
+
async function lockCall<T>(call: () => Promise<T>): Promise<T> {
|
|
458
|
+
try {
|
|
459
|
+
return await call();
|
|
460
|
+
} catch (error) {
|
|
461
|
+
throw new RefreshLockUnavailableError({ cause: error });
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export interface RedisRefreshLockOptions extends TokenSealer {
|
|
466
|
+
/** The app's own key prefix. Default "bff:refresh:". */
|
|
467
|
+
keyPrefix?: string | undefined;
|
|
468
|
+
/** Lock expiry: longer than the token request's timeout (10 s by default). Default 15 000 ms. */
|
|
469
|
+
lockMs?: number | undefined;
|
|
470
|
+
/** How long a caller waits for another caller's refresh. Default 12 000 ms. */
|
|
471
|
+
waitMs?: number | undefined;
|
|
472
|
+
/** Pause between two looks at Redis while waiting. Default 100 ms. */
|
|
473
|
+
pollMs?: number | undefined;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** The stored token set, after its seal is checked; null when absent or not ours. */
|
|
477
|
+
function readTokenSet(sealed: string | null, sealer: TokenSealer): TokenSet | null {
|
|
478
|
+
const json = sealed === null ? null : sealer.open(sealed);
|
|
479
|
+
if (json === null) return null;
|
|
480
|
+
let value: unknown;
|
|
481
|
+
try {
|
|
482
|
+
value = JSON.parse(json);
|
|
483
|
+
} catch {
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
if (typeof value !== "object" || value === null) return null;
|
|
487
|
+
const { access_token, refresh_token, id_token, expires_in, scope } = value as Record<string, unknown>;
|
|
488
|
+
if (typeof access_token !== "string" || typeof expires_in !== "number") return null;
|
|
489
|
+
return {
|
|
490
|
+
access_token,
|
|
491
|
+
expires_in,
|
|
492
|
+
token_type: "Bearer",
|
|
493
|
+
...(typeof refresh_token === "string" ? { refresh_token } : {}),
|
|
494
|
+
...(typeof id_token === "string" ? { id_token } : {}),
|
|
495
|
+
...(typeof scope === "string" ? { scope } : {}),
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* A RefreshLockStore shared by every instance of the app. Plasgos rotates the refresh token on every
|
|
501
|
+
* use, and a second use of the old token revokes the whole session. So for one refresh token
|
|
502
|
+
* (`key` is the SHA-256 the SDK hands in, never the token):
|
|
503
|
+
* - the caller that wins `SET lock NX PX` runs refresh() once, stores the result for `reuseMs`, then
|
|
504
|
+
* releases the lock;
|
|
505
|
+
* - every other caller, on this instance or another, waits for that result and returns it; it never
|
|
506
|
+
* calls refresh() itself while the lock is held;
|
|
507
|
+
* - a caller that finds neither a result nor a lock (the winner failed: a failed refresh did not
|
|
508
|
+
* consume the token) takes the lock itself;
|
|
509
|
+
* - a caller that waits longer than `waitMs` throws RefreshLockTimeoutError;
|
|
510
|
+
* - Redis failing before refresh() ran throws RefreshLockUnavailableError (the refresh token is unused);
|
|
511
|
+
* - a failure is never stored, and the stored token set is sealed.
|
|
512
|
+
* Callers on one instance share one promise per key, so one instance makes one round of Redis calls.
|
|
513
|
+
*/
|
|
514
|
+
export function redisRefreshLock(redis: RedisLike, options: RedisRefreshLockOptions): RefreshLockStore {
|
|
515
|
+
const prefix = options.keyPrefix ?? "bff:refresh:";
|
|
516
|
+
const lockMs = options.lockMs ?? 15_000;
|
|
517
|
+
const waitMs = options.waitMs ?? 12_000;
|
|
518
|
+
const pollMs = options.pollMs ?? 100;
|
|
519
|
+
const inFlight = new Map<string, Promise<TokenSet>>();
|
|
520
|
+
|
|
521
|
+
async function runShared(key: string, refresh: () => Promise<TokenSet>, reuseMs: number): Promise<TokenSet> {
|
|
522
|
+
const resultKey = `${prefix}result:${key}`;
|
|
523
|
+
const lockKey = `${prefix}lock:${key}`;
|
|
524
|
+
const deadline = Date.now() + waitMs;
|
|
525
|
+
for (;;) {
|
|
526
|
+
const done = readTokenSet(await lockCall(() => redis.get(resultKey)), options);
|
|
527
|
+
if (done !== null) return done;
|
|
528
|
+
|
|
529
|
+
const owner = randomUUID();
|
|
530
|
+
if ((await lockCall(() => redis.set(lockKey, owner, "PX", lockMs, "NX"))) === "OK") {
|
|
531
|
+
try {
|
|
532
|
+
// Another instance may have stored its result between our first look and our lock.
|
|
533
|
+
const late = readTokenSet(await lockCall(() => redis.get(resultKey)), options);
|
|
534
|
+
if (late !== null) return late;
|
|
535
|
+
const tokens = await refresh();
|
|
536
|
+
// The old refresh token is spent now: whatever Redis does next, this caller gets the new set.
|
|
537
|
+
await redis.set(resultKey, options.seal(JSON.stringify(tokens)), "PX", reuseMs, "NX").catch(() => null);
|
|
538
|
+
return tokens;
|
|
539
|
+
} finally {
|
|
540
|
+
// Release only our own lock. The lock outlives the token request, so it is still ours here;
|
|
541
|
+
// if Redis fails now, the lock expires by itself after lockMs.
|
|
542
|
+
await redis
|
|
543
|
+
.get(lockKey)
|
|
544
|
+
.then((holder) => (holder === owner ? redis.del(lockKey) : 0))
|
|
545
|
+
.catch(() => 0);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
if (Date.now() >= deadline) throw new RefreshLockTimeoutError();
|
|
550
|
+
await sleep(pollMs);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
return {
|
|
555
|
+
run(key, refresh, reuseMs) {
|
|
556
|
+
const running = inFlight.get(key);
|
|
557
|
+
if (running !== undefined) return running;
|
|
558
|
+
const promise = runShared(key, refresh, reuseMs).finally(() => inFlight.delete(key));
|
|
559
|
+
inFlight.set(key, promise);
|
|
560
|
+
return promise;
|
|
561
|
+
},
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
```
|
|
565
|
+
<!-- /snippet -->
|
|
566
|
+
|
|
567
|
+
Aturannya:
|
|
568
|
+
|
|
569
|
+
1. Kuncinya `key` dari SDK (SHA-256 dari refresh token, bukan token itu sendiri), diberi awalan milik aplikasi.
|
|
570
|
+
2. Pemanggil yang menang `SET lock NX PX` menjalankan `refresh()` sekali, menyimpan hasilnya selama `reuseMs`, lalu melepas lock.
|
|
571
|
+
3. Pemanggil lain, di instance yang sama atau lain, menunggu hasil itu dan memakainya. Ia **tidak pernah** memanggil `refresh()` sendiri selama lock dipegang.
|
|
572
|
+
4. Umur lock lebih panjang dari batas waktu permintaan token, jadi instance yang mati tidak memegang lock lama-lama, dan instance yang lambat tidak kehilangan lock di tengah permintaan.
|
|
573
|
+
5. Pemanggil yang tidak menemukan hasil maupun lock (pemenangnya gagal) boleh mengambil lock sendiri, karena refresh yang gagal tidak menghabiskan token.
|
|
574
|
+
6. Pemanggil yang menunggu lebih lama dari `waitMs` melempar `RefreshLockTimeoutError`; route menjawab `503` **tanpa menghapus sesi**.
|
|
575
|
+
7. Kegagalan tidak pernah disimpan. Hasil yang disimpan berisi token, jadi disegel (AES-256-GCM) dengan kunci turunan `SESSION_SECRET`.
|
|
576
|
+
8. Redis yang gagal sebelum `refresh()` berjalan (saat mengambil lock atau membaca hasil) dilempar sebagai `RefreshLockUnavailableError`, bukan error mentah client Redis. Refresh token belum terpakai; route menjawab `503` dan sesi tetap, atau memakai access token yang masih berlaku ([§8](#8-sesi-dan-authme)).
|
|
577
|
+
9. Pemanggil di satu instance berbagi satu promise per kunci, jadi satu instance hanya sekali bolak-balik ke Redis per refresh.
|
|
578
|
+
|
|
579
|
+
Penyegelnya:
|
|
580
|
+
|
|
581
|
+
<!-- snippet: examples/snippets/bff-redis-lock.ts#seal -->
|
|
582
|
+
```ts
|
|
583
|
+
/** Seals and opens the stored token set. The app's own code: the stored value holds tokens. */
|
|
584
|
+
export interface TokenSealer {
|
|
585
|
+
seal(value: string): string;
|
|
586
|
+
/** The plaintext, or null when the value was not sealed with one of the secrets. */
|
|
587
|
+
open(sealed: string): string | null;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const keyOf = (secret: string): Buffer =>
|
|
591
|
+
Buffer.from(hkdfSync("sha256", secret, "bff-refresh-lock", "token-set", 32));
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* AES-256-GCM with a key derived from the session secrets: the first seals, all open (rotation,
|
|
595
|
+
* as SESSION_SECRET="new,old"). Output: base64url of IV (12 bytes) + tag (16 bytes) + ciphertext.
|
|
596
|
+
*/
|
|
597
|
+
export function tokenSealer(secrets: readonly string[]): TokenSealer {
|
|
598
|
+
const keys = secrets.map(keyOf);
|
|
599
|
+
const [current] = keys;
|
|
600
|
+
if (current === undefined) throw new Error("tokenSealer needs at least one secret");
|
|
601
|
+
return {
|
|
602
|
+
seal(value) {
|
|
603
|
+
const iv = randomBytes(12);
|
|
604
|
+
const cipher = createCipheriv("aes-256-gcm", current, iv);
|
|
605
|
+
const body = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
|
606
|
+
return Buffer.concat([iv, cipher.getAuthTag(), body]).toString("base64url");
|
|
607
|
+
},
|
|
608
|
+
open(sealed) {
|
|
609
|
+
const bytes = Buffer.from(sealed, "base64url");
|
|
610
|
+
if (bytes.length < 29) return null;
|
|
611
|
+
for (const key of keys) {
|
|
612
|
+
try {
|
|
613
|
+
const decipher = createDecipheriv("aes-256-gcm", key, bytes.subarray(0, 12));
|
|
614
|
+
decipher.setAuthTag(bytes.subarray(12, 28));
|
|
615
|
+
return Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]).toString("utf8");
|
|
616
|
+
} catch {
|
|
617
|
+
// Not this key: try the next one.
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
return null;
|
|
621
|
+
},
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
```
|
|
625
|
+
<!-- /snippet -->
|
|
626
|
+
|
|
627
|
+
## 10. Logout dan logout ticket
|
|
628
|
+
|
|
629
|
+
<!-- snippet: examples/snippets/bff-express.ts#logout -->
|
|
630
|
+
```ts
|
|
631
|
+
const escapeHtml = (text: string): string => text.replace(/[&<>"']/g, (char) => `&#${String(char.charCodeAt(0))};`);
|
|
632
|
+
|
|
633
|
+
/** POST /auth/logout, from a form of this app (csrfGuard checks its Origin). */
|
|
634
|
+
async function logout(bff: Bff, req: Request, res: Response): Promise<void> {
|
|
635
|
+
const session = bff.store.read(req.headers.cookie);
|
|
636
|
+
const auth = session.data.auth;
|
|
637
|
+
// Never rejects: a failed call to Plasgos is reported through onFailure and the logout goes on.
|
|
638
|
+
const result = await bff.client.logout({
|
|
639
|
+
refreshToken: auth?.refresh_token,
|
|
640
|
+
idToken: auth?.id_token,
|
|
641
|
+
// clientIp: the address your reverse proxy vouches for, or null.
|
|
642
|
+
browser: { clientIp: null, userAgent: req.get("user-agent") ?? null },
|
|
643
|
+
});
|
|
644
|
+
// The local session ends whatever Plasgos answered, also when it could not be reached.
|
|
645
|
+
session.destroy();
|
|
646
|
+
for (const cookie of bff.store.commit(session)) res.append("Set-Cookie", cookie);
|
|
647
|
+
res.set("Cache-Control", "no-store");
|
|
648
|
+
// LogoutResult is a union: read `location` only after checking `kind`.
|
|
649
|
+
if (result.kind === "redirect") {
|
|
650
|
+
res.redirect(303, result.location);
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
// "form" comes only with endSession "form-post", for an app on the issuer's own origin: not a BFF.
|
|
654
|
+
const fields = Object.entries(result.fields)
|
|
655
|
+
.map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`)
|
|
656
|
+
.join("");
|
|
657
|
+
res
|
|
658
|
+
.type("html")
|
|
659
|
+
.send(`<!doctype html><form method="post" action="${escapeHtml(result.action)}">${fields}</form><script>document.forms[0].submit()</script>`);
|
|
660
|
+
}
|
|
661
|
+
```
|
|
662
|
+
<!-- /snippet -->
|
|
663
|
+
|
|
664
|
+
- Logout berupa form `POST` dari halaman aplikasi (navigasi penuh, bukan `fetch`), dengan pemeriksaan `Origin` ([§15](#15-csrf)). Logout lewat `GET` bisa dipicu situs lain.
|
|
665
|
+
- `logout()` tidak pernah melempar. Ia mencabut refresh token dan, bila ada logout ticket, meminta tiket, masing-masing dengan batas waktu. Kegagalan hanya dilaporkan lewat `onFailure`.
|
|
666
|
+
- **Sesi lokal selalu dihapus**, juga saat Plasgos tidak bisa dihubungi.
|
|
667
|
+
- **Logout ticket** membuat Plasgos langsung mengakhiri sesinya tanpa halaman konfirmasi. Tiket diminta lewat alamat internal, jadi butuh `backchannelUrl`. Tanpa itu, user melihat halaman konfirmasi keluar di Plasgos.
|
|
668
|
+
- `LogoutResult` adalah union: periksa `result.kind` sebelum membaca `result.location`.
|
|
669
|
+
|
|
670
|
+
## 11. BFF di bawah sub-path
|
|
671
|
+
|
|
672
|
+
Bila BFF dilayani di bawah path sebuah host bersama, misalnya `https://app.example.com/crm/`, semua diturunkan dari `basePath`:
|
|
673
|
+
|
|
674
|
+
<!-- snippet: examples/snippets/bff-express.ts#setup-subpath -->
|
|
675
|
+
```ts
|
|
676
|
+
/**
|
|
677
|
+
* The same BFF served under https://app.example.com/crm/. Everything follows from the base path:
|
|
678
|
+
* - cookies __Secure-bff, __Secure-bff-auth, __Secure-bff-idt, __Secure-bff-oidc, each with Path=/crm/,
|
|
679
|
+
* when set and when cleared;
|
|
680
|
+
* - the redirect URI to register: https://app.example.com/crm/auth/callback;
|
|
681
|
+
* - the routes are mounted under /crm (startBff in bff-proxy.ts).
|
|
682
|
+
*/
|
|
683
|
+
export function createSubpathBff(redis: RedisLike): Bff {
|
|
684
|
+
return createBff(redis, "/crm");
|
|
685
|
+
}
|
|
686
|
+
```
|
|
687
|
+
<!-- /snippet -->
|
|
688
|
+
|
|
689
|
+
- Cookie bernama `__Secure-bff`, `__Secure-bff-auth`, `__Secure-bff-idt`, `__Secure-bff-oidc`, dengan `Path=/crm/` saat ditulis **dan** saat dihapus. Browser hanya menghapus cookie bila nama dan path-nya sama.
|
|
690
|
+
- Redirect URI yang didaftarkan: `https://app.example.com/crm/auth/callback`. Semua route BFF berada di bawah `/crm`.
|
|
691
|
+
- `__Host-` tidak bisa dipakai, karena browser hanya menerimanya dengan `Path=/`. Cookie `__Secure-` dengan `Path` tidak terikat ke satu host: aplikasi lain di host yang sama atau subdomain saudara bisa menulis cookie dengan nama yang sama. Ia tidak bisa memalsukan isi sesi (tersegel dengan secret Anda). Mitigasinya: callback selalu menulis sesi baru ([§7](#7-callback)) dan aturan CSRF ([§15](#15-csrf)). Bila bisa, pakai host sendiri. Rinciannya di [`login-web.md` §6](login-web.md#aplikasi-di-bawah-sub-path).
|
|
692
|
+
|
|
693
|
+
## 12. Pencabutan sesi
|
|
694
|
+
|
|
695
|
+
Sesi di BFF bisa hidup lebih lama dari sesi user di Plasgos: user logout di perangkat lain, mengganti password, atau diblokir. BFF memeriksa **marker** di Redis pada setiap request yang membawa sesi, sebelum proxy atau `/auth/me` menjawab. Marker diisi penerima webhook aplikasi Anda dari event `user.*` (satu endpoint dengan `presets.appEvents`, [`webhook.md` §6](webhook.md#satu-endpoint-untuk-semua-event-aplikasi)); aturan markernya sama dengan yang dipakai API Anda ([`verifikasi-token.md` §8](verifikasi-token.md#8-pencabutan-sesi-isrevoked)).
|
|
696
|
+
|
|
697
|
+
<!-- snippet: examples/snippets/bff-revocation.ts#markers -->
|
|
698
|
+
```ts
|
|
699
|
+
/**
|
|
700
|
+
* The app's own marker keys. The app's webhook receiver writes them from the user.* events Plasgos
|
|
701
|
+
* sends to the app's webhook endpoint; the names and the prefix are yours.
|
|
702
|
+
*/
|
|
703
|
+
export interface MarkerKeys {
|
|
704
|
+
/** Present when the Plasgos session `sid` was revoked. */
|
|
705
|
+
session(sid: string): string;
|
|
706
|
+
/** Present while the user is blocked. */
|
|
707
|
+
blockedUser(publicId: string): string;
|
|
708
|
+
/** The newest credential version Plasgos announced for the user, as text ("3"). */
|
|
709
|
+
credentialVersion(publicId: string): string;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
export const markerKeys: MarkerKeys = {
|
|
713
|
+
session: (sid) => `myapp:revocation:sid:${sid}`,
|
|
714
|
+
blockedUser: (publicId) => `myapp:revocation:blocked:${publicId}`,
|
|
715
|
+
credentialVersion: (publicId) => `myapp:revocation:cv:${publicId}`,
|
|
716
|
+
};
|
|
717
|
+
|
|
718
|
+
/** Redis could not be read. The request is answered 503 and the session is kept. */
|
|
719
|
+
export class MarkerStoreUnavailableError extends Error {
|
|
720
|
+
constructor(options?: ErrorOptions) {
|
|
721
|
+
super("revocation markers unavailable", options);
|
|
722
|
+
this.name = "MarkerStoreUnavailableError";
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
interface Markers {
|
|
727
|
+
/** The session was revoked or the user is blocked. */
|
|
728
|
+
ended: boolean;
|
|
729
|
+
/** The stored credential version, or null when there is none. */
|
|
730
|
+
credentialVersion: number | null;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
async function readMarkers(redis: RedisLike, keys: MarkerKeys, sid: string, publicId: string | null): Promise<Markers> {
|
|
734
|
+
let values: (string | null)[];
|
|
735
|
+
try {
|
|
736
|
+
values = await Promise.all([
|
|
737
|
+
redis.get(keys.session(sid)),
|
|
738
|
+
// Without a public id the user markers cannot be looked up. An audience whose sessions must end
|
|
739
|
+
// by user has Plasgos issue plasgos_public_id on its tokens.
|
|
740
|
+
publicId === null ? null : redis.get(keys.blockedUser(publicId)),
|
|
741
|
+
publicId === null ? null : redis.get(keys.credentialVersion(publicId)),
|
|
742
|
+
]);
|
|
743
|
+
} catch (error) {
|
|
744
|
+
throw new MarkerStoreUnavailableError({ cause: error });
|
|
745
|
+
}
|
|
746
|
+
const [revokedSession, blocked, version] = values;
|
|
747
|
+
if (version === null || version === undefined) {
|
|
748
|
+
return { ended: revokedSession !== null || blocked !== null, credentialVersion: null };
|
|
749
|
+
}
|
|
750
|
+
const credentialVersion = Number(version);
|
|
751
|
+
// A marker this app did not write is a store problem, not a reason to log the user out.
|
|
752
|
+
if (!Number.isSafeInteger(credentialVersion)) throw new MarkerStoreUnavailableError();
|
|
753
|
+
return { ended: revokedSession !== null || blocked !== null, credentialVersion };
|
|
754
|
+
}
|
|
755
|
+
```
|
|
756
|
+
<!-- /snippet -->
|
|
757
|
+
|
|
758
|
+
<!-- snippet: examples/snippets/bff-revocation.ts#check -->
|
|
759
|
+
```ts
|
|
760
|
+
/**
|
|
761
|
+
* The forced refreshes (ensureFresh({ force: true }) through the Redis lock) checkSession may run for
|
|
762
|
+
* one request. Each resolves the renewed auth, or null when Plasgos ended the session (the session is
|
|
763
|
+
* then destroyed).
|
|
764
|
+
*/
|
|
765
|
+
export interface ForcedRefresh {
|
|
766
|
+
/** At most one per request: the revocation check and the proxy's retry share it. */
|
|
767
|
+
force(): Promise<AuthState | null>;
|
|
768
|
+
/**
|
|
769
|
+
* At most one per request, and only after force(): one more forced refresh with the refresh token
|
|
770
|
+
* force() stored, the newest one. The lock may hand force() a token set another request received
|
|
771
|
+
* a few seconds earlier, before the credential version went up; this one is a new refresh.
|
|
772
|
+
*/
|
|
773
|
+
again(): Promise<AuthState | null>;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* The per-request revocation check of a BFF, before the proxy or /auth/me answers. True: the session
|
|
778
|
+
* may go on (possibly with a renewed token). False: the session is destroyed here; the caller commits
|
|
779
|
+
* the cookies (every one cleared, with the store's Path) and answers 401.
|
|
780
|
+
*
|
|
781
|
+
* sid, cv and plasgos_public_id come from the access token the session holds, read without
|
|
782
|
+
* verification: the BFF received that token itself from the Plasgos token endpoint. They are the
|
|
783
|
+
* values of the token's issue, so they are read again after every refresh. An app that must end
|
|
784
|
+
* sessions by sid or by user without waiting for a request keeps its own index of sessions on the
|
|
785
|
+
* server.
|
|
786
|
+
*
|
|
787
|
+
* Throws MarkerStoreUnavailableError when Redis cannot be read: answer 503 and keep the session.
|
|
788
|
+
*/
|
|
789
|
+
export async function checkSession<App extends object>(
|
|
790
|
+
redis: RedisLike,
|
|
791
|
+
keys: MarkerKeys,
|
|
792
|
+
session: SessionHandle<App>,
|
|
793
|
+
refresh: ForcedRefresh,
|
|
794
|
+
): Promise<boolean> {
|
|
795
|
+
const auth = session.data.auth;
|
|
796
|
+
if (auth === undefined) return false;
|
|
797
|
+
const claims = readAccessTokenClaims(auth.access_token);
|
|
798
|
+
// A user token without a session id cannot be checked.
|
|
799
|
+
if (claims === null || claims.sid === null) {
|
|
800
|
+
session.destroy();
|
|
801
|
+
return false;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
const markers = await readMarkers(redis, keys, claims.sid, claims.plasgos_public_id);
|
|
805
|
+
if (markers.ended) {
|
|
806
|
+
session.destroy();
|
|
807
|
+
return false;
|
|
808
|
+
}
|
|
809
|
+
const stored = markers.credentialVersion;
|
|
810
|
+
if (stored === null || (claims.cv !== null && claims.cv >= stored)) return true;
|
|
811
|
+
|
|
812
|
+
// The user's credentials changed after this token was issued: a forced refresh. Plasgos refuses it
|
|
813
|
+
// when the change ended the session; otherwise the new token carries the new version.
|
|
814
|
+
const below = (renewed: AuthState): boolean => {
|
|
815
|
+
const fresh = readAccessTokenClaims(renewed.access_token);
|
|
816
|
+
return fresh === null || fresh.cv === null || fresh.cv < stored;
|
|
817
|
+
};
|
|
818
|
+
let renewed = await refresh.force();
|
|
819
|
+
if (renewed === null) return false;
|
|
820
|
+
// Still below: the lock may have reused a token set from before the marker. One new refresh with the
|
|
821
|
+
// newest refresh token; never an older one, which Plasgos would treat as reuse.
|
|
822
|
+
if (below(renewed)) renewed = await refresh.again();
|
|
823
|
+
if (renewed === null) return false;
|
|
824
|
+
if (below(renewed)) {
|
|
825
|
+
session.destroy();
|
|
826
|
+
return false;
|
|
827
|
+
}
|
|
828
|
+
return true;
|
|
829
|
+
}
|
|
830
|
+
```
|
|
831
|
+
<!-- /snippet -->
|
|
832
|
+
|
|
833
|
+
Alurnya:
|
|
834
|
+
|
|
835
|
+
1. `readAccessTokenClaims(session.data.auth.access_token)` dari `@plasgos/oidc-client/session` memberi `sid`, `cv`, dan `plasgos_public_id` token milik sesi. Token itu **tidak diverifikasi** di sini: BFF menerimanya langsung dari Plasgos dan menyimpannya di cookie tersegel. Nilainya milik token saat diterbitkan, jadi dibaca lagi setelah setiap refresh. Token tanpa `sid` membuat sesi diakhiri, karena tidak bisa diperiksa.
|
|
836
|
+
2. Marker sesi dicabut (untuk `sid`) atau user diblokir (untuk `plasgos_public_id`) ada: sesi dihapus di jawaban itu juga (semua cookie dihapus dengan `Path`-nya), jawab `401`, dan browser diarahkan ke login. Token tanpa `plasgos_public_id` hanya diperiksa marker sesinya.
|
|
837
|
+
3. Versi kredensial yang tersimpan lebih besar dari `cv` token (atau token tidak punya `cv`): satu refresh paksa (`ensureFresh({ force: true })`) lewat lock Redis, simpan sesi baru, lalu bandingkan lagi dengan `cv` token baru. Lock bisa mengembalikan token yang diterima request lain beberapa detik sebelumnya, sebelum versi naik. Karena itu, bila token baru masih di bawah marker, BFF menjalankan **satu** refresh lagi dengan refresh token terbaru yang baru disimpan (tidak pernah dengan refresh token lama, yang dianggap Plasgos sebagai pemakaian ulang). Sesi diakhiri bila salah satu refresh gagal dengan alasan yang mengakhiri sesi, atau token setelah refresh kedua masih di bawah marker. Bila berhasil, request lanjut dengan token baru.
|
|
838
|
+
4. Refresh paksa dipakai bersama retry proxy ([§13](#13-proxy-ke-api)): bila pemeriksaan ini sudah memaksa refresh, proxy tidak me-refresh dan tidak mengulang lagi setelah `401` dari API.
|
|
839
|
+
5. Redis tidak bisa dibaca: jawab `503` dan sesi **tetap** (gagal tertutup untuk request itu, tanpa logout karena gangguan).
|
|
840
|
+
6. Socket yang sedang terbuka diperiksa ulang secara berkala dengan pemeriksaan yang sama ([§14](#14-proxy-socket)).
|
|
841
|
+
|
|
842
|
+
Marker ditulis penerima webhook dengan aturan di [`verifikasi-token.md` §8](verifikasi-token.md#8-pencabutan-sesi-isrevoked): versi kredensial disimpan sebagai nilai terbesar dan berumur 1 jam, marker sesi berumur 1 jam, dan status blokir disimpan permanen di database Anda lalu di-cache di Redis.
|
|
843
|
+
|
|
844
|
+
## 13. Proxy ke API
|
|
845
|
+
|
|
846
|
+
<!-- snippet: examples/snippets/bff-proxy.ts#http -->
|
|
847
|
+
```ts
|
|
848
|
+
/** A JSON body up to this size is buffered and can be retried. Anything else is streamed, never retried. */
|
|
849
|
+
const MAX_BUFFERED_BODY = 64 * 1024;
|
|
850
|
+
/**
|
|
851
|
+
* The browser's request headers the API gets: an allowlist. Everything else stays at the BFF: the
|
|
852
|
+
* browser's credentials, hop-by-hop headers, and headers the browser could forge to impersonate the
|
|
853
|
+
* BFF or another client.
|
|
854
|
+
*/
|
|
855
|
+
const FORWARDED_REQUEST_HEADERS: readonly string[] = [
|
|
856
|
+
"accept",
|
|
857
|
+
"accept-language",
|
|
858
|
+
"content-type",
|
|
859
|
+
"content-length",
|
|
860
|
+
"if-none-match",
|
|
861
|
+
"if-modified-since",
|
|
862
|
+
"range",
|
|
863
|
+
"x-request-id",
|
|
864
|
+
];
|
|
865
|
+
/** Your app's own extra request headers for its API, for example "x-client-version". Never credentials. */
|
|
866
|
+
export const APP_REQUEST_HEADERS: readonly string[] = [];
|
|
867
|
+
/** Never sent from the browser to the API, whatever the lists above say. */
|
|
868
|
+
function neverForwarded(name: string): boolean {
|
|
869
|
+
return (
|
|
870
|
+
["authorization", "cookie", "host", "x-auth-agent", "fingerprint"].includes(name) ||
|
|
871
|
+
name.startsWith("x-mobile-") ||
|
|
872
|
+
name.startsWith("x-forwarded-")
|
|
873
|
+
);
|
|
874
|
+
}
|
|
875
|
+
/** The API's answer headers the browser gets. Set-Cookie of the API never reaches the browser. */
|
|
876
|
+
const PASSED_RESPONSE_HEADERS = [
|
|
877
|
+
"content-type",
|
|
878
|
+
"content-language",
|
|
879
|
+
"content-disposition",
|
|
880
|
+
"content-range",
|
|
881
|
+
"accept-ranges",
|
|
882
|
+
"cache-control",
|
|
883
|
+
"etag",
|
|
884
|
+
"last-modified",
|
|
885
|
+
"location",
|
|
886
|
+
"retry-after",
|
|
887
|
+
"www-authenticate",
|
|
888
|
+
"x-request-id",
|
|
889
|
+
];
|
|
890
|
+
|
|
891
|
+
const isSmallJson = (req: IncomingMessage): boolean =>
|
|
892
|
+
(req.headers["content-type"] ?? "").startsWith("application/json") &&
|
|
893
|
+
Number(req.headers["content-length"] ?? Number.NaN) <= MAX_BUFFERED_BODY;
|
|
894
|
+
|
|
895
|
+
const hasBody = (req: IncomingMessage): boolean =>
|
|
896
|
+
req.headers["transfer-encoding"] !== undefined || Number(req.headers["content-length"] ?? "0") > 0;
|
|
897
|
+
|
|
898
|
+
/** The allowed browser headers plus `extra`, each name once, never one of the forbidden ones. */
|
|
899
|
+
export function allowedHeaders(req: IncomingMessage, extra: readonly string[] = []): Record<string, string> {
|
|
900
|
+
const headers: Record<string, string> = {};
|
|
901
|
+
for (const name of [...FORWARDED_REQUEST_HEADERS, ...APP_REQUEST_HEADERS, ...extra]) {
|
|
902
|
+
const value = req.headers[name];
|
|
903
|
+
if (value === undefined || neverForwarded(name)) continue;
|
|
904
|
+
headers[name] = Array.isArray(value) ? value.join(", ") : value;
|
|
905
|
+
}
|
|
906
|
+
// One id per request in the logs of the BFF and the API: the browser's, or a new one.
|
|
907
|
+
headers["x-request-id"] ??= randomUUID();
|
|
908
|
+
return headers;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** A Web stream of the browser's body for fetch, typed alike with and without the DOM lib. */
|
|
912
|
+
function bodyStream(source: AsyncIterable<Uint8Array>): ReadableStream<Uint8Array> {
|
|
913
|
+
const chunks = source[Symbol.asyncIterator]();
|
|
914
|
+
return new ReadableStream<Uint8Array>({
|
|
915
|
+
async pull(controller) {
|
|
916
|
+
const next = await chunks.next();
|
|
917
|
+
if (next.done === true) controller.close();
|
|
918
|
+
else controller.enqueue(next.value);
|
|
919
|
+
},
|
|
920
|
+
async cancel() {
|
|
921
|
+
await chunks.return?.();
|
|
922
|
+
},
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
const isInvalidToken = (answer: globalThis.Response): boolean =>
|
|
927
|
+
answer.status === 401 && (answer.headers.get("www-authenticate") ?? "").includes("invalid_token");
|
|
928
|
+
|
|
929
|
+
/** A request of the BFF to the same request on the app's own API (`upstreamPath`), with the session's token. */
|
|
930
|
+
async function forward(bff: Bff, req: Request, res: Response, upstreamPath: string): Promise<void> {
|
|
931
|
+
const session = bff.store.read(req.headers.cookie);
|
|
932
|
+
const refresh = requestRefresh(bff, session);
|
|
933
|
+
try {
|
|
934
|
+
let auth = await checkedAuth(bff, session, refresh);
|
|
935
|
+
if (auth === null) {
|
|
936
|
+
sendJson(res, bff, session, 401, { error: "login_required" });
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
const buffered: unknown = req.body;
|
|
940
|
+
// A copy as a plain Uint8Array: fetch accepts it whatever the project's lib setting.
|
|
941
|
+
const body = Buffer.isBuffer(buffered) ? new Uint8Array(buffered) : null;
|
|
942
|
+
const streamed = body === null && hasBody(req);
|
|
943
|
+
const call = async (token: string): Promise<globalThis.Response | null> => {
|
|
944
|
+
const headers = allowedHeaders(req);
|
|
945
|
+
// fetch sets the length of a buffered body itself (express.raw may have inflated it).
|
|
946
|
+
if (body !== null) delete headers["content-length"];
|
|
947
|
+
headers["authorization"] = `Bearer ${token}`;
|
|
948
|
+
// A variable, not a literal: `duplex` is missing from the DOM lib's RequestInit.
|
|
949
|
+
const init: RequestInit & { duplex: "half" } = {
|
|
950
|
+
method: req.method,
|
|
951
|
+
headers,
|
|
952
|
+
body: body ?? (streamed ? bodyStream(req) : null),
|
|
953
|
+
duplex: "half",
|
|
954
|
+
// A redirect of the API goes to the browser as it is (Location passed on), never followed here.
|
|
955
|
+
redirect: "manual",
|
|
956
|
+
};
|
|
957
|
+
try {
|
|
958
|
+
return await fetch(`${bff.apiOrigin}${upstreamPath}`, init);
|
|
959
|
+
} catch {
|
|
960
|
+
return null;
|
|
961
|
+
}
|
|
962
|
+
};
|
|
963
|
+
|
|
964
|
+
let answer = await call(auth.access_token);
|
|
965
|
+
// The API refused a token that looked valid: one forced refresh and one retry, only when the body
|
|
966
|
+
// can be sent again (never a streamed upload) and the revocation check has not already forced a
|
|
967
|
+
// refresh in this request (a second one would not give a newer token).
|
|
968
|
+
if (answer !== null && isInvalidToken(answer) && !streamed && !refresh.forced) {
|
|
969
|
+
await answer.body?.cancel();
|
|
970
|
+
auth = await refresh.force();
|
|
971
|
+
if (auth === null) {
|
|
972
|
+
sendJson(res, bff, session, 401, { error: "login_required" });
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
answer = await call(auth.access_token);
|
|
976
|
+
}
|
|
977
|
+
if (answer === null) {
|
|
978
|
+
sendJson(res, bff, session, 502, { error: "bad_gateway" });
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// The API's status (a 503 or a 3xx too) and body are passed on as they are, with the session
|
|
983
|
+
// cookies that changed.
|
|
984
|
+
for (const cookie of bff.store.commit(session)) res.append("Set-Cookie", cookie);
|
|
985
|
+
res.status(answer.status);
|
|
986
|
+
for (const name of PASSED_RESPONSE_HEADERS) {
|
|
987
|
+
const value = answer.headers.get(name);
|
|
988
|
+
if (value !== null) res.setHeader(name, value);
|
|
989
|
+
}
|
|
990
|
+
if (answer.body === null) {
|
|
991
|
+
res.end();
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
// pipeline closes the upstream request when the browser disconnects (long-polls, downloads).
|
|
995
|
+
pipeline(Readable.from(answer.body), res, () => {});
|
|
996
|
+
} catch (error) {
|
|
997
|
+
sendFailure(res, bff, session, error);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/** /api/* of the BFF to /api/* of the app's own API. */
|
|
1002
|
+
export function apiProxy(bff: Bff): Router {
|
|
1003
|
+
const proxy = express.Router();
|
|
1004
|
+
// Buffers a small JSON body (it can be retried); anything else stays a stream.
|
|
1005
|
+
proxy.use(express.raw({ type: isSmallJson, limit: MAX_BUFFERED_BODY }));
|
|
1006
|
+
proxy.use(route((req, res) => forward(bff, req, res, `/api${req.url}`)));
|
|
1007
|
+
return proxy;
|
|
1008
|
+
}
|
|
1009
|
+
```
|
|
1010
|
+
<!-- /snippet -->
|
|
1011
|
+
|
|
1012
|
+
Aturannya:
|
|
1013
|
+
|
|
1014
|
+
- **Header request memakai daftar izin.** Dari browser hanya `Accept`, `Accept-Language`, `Content-Type`, `Content-Length`, `If-None-Match`, `If-Modified-Since`, `Range`, dan `X-Request-Id` yang diteruskan. Header lain milik aplikasi Anda (misalnya `X-Client-Version`) ditambahkan di `APP_REQUEST_HEADERS`.
|
|
1015
|
+
- **Tidak pernah diteruskan dari browser**, apa pun isi daftar itu: `Authorization`, `Cookie`, `X-Auth-Agent`, `Fingerprint`, semua `X-Mobile-*`, dan semua `X-Forwarded-*`. Header seperti itu bisa dipalsukan browser untuk menyamar sebagai BFF atau client lain. Yang dikirim ke API adalah access token sesi sebagai `Authorization: Bearer`.
|
|
1016
|
+
- `X-Request-Id` diteruskan, atau dibuat bila tidak ada, supaya log BFF dan API bisa dicocokkan.
|
|
1017
|
+
- Jawaban `401` dengan `invalid_token` di `WWW-Authenticate` memicu **satu** refresh paksa dan **satu** pengulangan, hanya bila body request bisa dikirim ulang (body JSON kecil sampai 64 KiB yang sudah dibaca, atau tanpa body) **dan** pemeriksaan pencabutan belum memaksa refresh di request yang sama ([§12](#12-pencabutan-sesi)). Upload yang di-stream tidak pernah diulang; `401`-nya diteruskan ke browser.
|
|
1018
|
+
- Status, body (di-stream), dan header jawaban API berikut diteruskan: `Content-Type`, `Content-Language`, `Content-Disposition`, `Content-Range`, `Accept-Ranges`, `Cache-Control`, `ETag`, `Last-Modified`, `Location`, `Retry-After`, `WWW-Authenticate`, dan `X-Request-Id`. Redirect dari API tidak diikuti BFF: `3xx` dan `Location`-nya sampai ke browser apa adanya, begitu juga unduhan (`Content-Disposition`) dan potongan file (`206` dengan `Content-Range`). `Set-Cookie` dari API tidak pernah sampai ke browser; cookie sesi yang berubah ditambahkan BFF.
|
|
1019
|
+
- Contoh `fetch` lolos typecheck dengan dan tanpa lib `DOM` di `tsconfig.json`: body dikirim sebagai `Uint8Array` atau `ReadableStream`, dan opsi `duplex` (tidak dikenal lib `DOM`) ada di variabel bertipe, bukan objek literal.
|
|
1020
|
+
- `503` dari API diteruskan apa adanya. API yang tidak bisa dihubungi dijawab `502`.
|
|
1021
|
+
|
|
1022
|
+
## 14. Proxy socket
|
|
1023
|
+
|
|
1024
|
+
<!-- snippet: examples/snippets/bff-proxy.ts#socket -->
|
|
1025
|
+
```ts
|
|
1026
|
+
/** Socket.IO's default path. Under a sub-path the browser's client uses `path: "/crm/socket.io/"`. */
|
|
1027
|
+
export const SOCKET_PATH = "/socket.io";
|
|
1028
|
+
/** A token needs this many seconds of validity left to open a socket: the upgrade never refreshes. */
|
|
1029
|
+
const SOCKET_MIN_VALIDITY_SECONDS = 60;
|
|
1030
|
+
/** How often the sessions of open sockets are checked again against the revocation markers. */
|
|
1031
|
+
const SOCKET_RECHECK_MS = 2 * 60_000;
|
|
1032
|
+
/** The upgrade path cannot write cookies, so it cannot refresh: a needed refresh ends the attempt. */
|
|
1033
|
+
const noRefresh: ForcedRefresh = { force: () => Promise.resolve(null), again: () => Promise.resolve(null) };
|
|
1034
|
+
/** The WebSocket handshake headers, forwarded next to the allowed headers of the http region. */
|
|
1035
|
+
const WEBSOCKET_HEADERS = ["sec-websocket-key", "sec-websocket-version", "sec-websocket-extensions", "sec-websocket-protocol"];
|
|
1036
|
+
|
|
1037
|
+
function refuse(socket: Duplex, status: number, reason: string): void {
|
|
1038
|
+
socket.end(`HTTP/1.1 ${String(status)} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/**
|
|
1042
|
+
* Socket.IO's HTTP long-polling requests: `${basePath}/socket.io/*` of the BFF to `/socket.io/*` of the
|
|
1043
|
+
* app's own API, through the same forward as /api/*. Every method must come from this app's pages
|
|
1044
|
+
* (sameOriginOnly); there is no custom header to require. Polling bodies are not JSON, so they are
|
|
1045
|
+
* streamed and never retried.
|
|
1046
|
+
*/
|
|
1047
|
+
export function socketPollingProxy(bff: Bff): Router {
|
|
1048
|
+
const polling = express.Router();
|
|
1049
|
+
polling.use(sameOriginOnly(bff.appOrigin));
|
|
1050
|
+
polling.use(route((req, res) => forward(bff, req, res, `${SOCKET_PATH}${req.url}`)));
|
|
1051
|
+
return polling;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* Forwards WebSocket upgrades under `${basePath}/socket.io/` to `/socket.io/` of the app's own API with
|
|
1056
|
+
* the session's token. The upgrade never refreshes, because a renewed session could not be written back
|
|
1057
|
+
* to the cookie from here: with no token, or one about to expire, it answers 401; the browser calls
|
|
1058
|
+
* /auth/me (which refreshes the normal way) and connects again. Returns a function that stops the
|
|
1059
|
+
* periodic re-check.
|
|
1060
|
+
*/
|
|
1061
|
+
export function attachSocketProxy(server: Server, bff: Bff): () => void {
|
|
1062
|
+
const prefix = `${bff.basePath}${SOCKET_PATH}`;
|
|
1063
|
+
const open = new Map<Duplex, { cookie: string | undefined; upstream: Duplex }>();
|
|
1064
|
+
|
|
1065
|
+
async function upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {
|
|
1066
|
+
// Only pages of this app may open a socket with the user's session. Browsers always send Origin here.
|
|
1067
|
+
if (req.headers.origin !== bff.appOrigin) {
|
|
1068
|
+
refuse(socket, 403, "Forbidden");
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
const session = bff.store.read(req.headers.cookie);
|
|
1072
|
+
const auth = session.data.auth;
|
|
1073
|
+
if (auth === undefined || auth.expires_at - Math.floor(Date.now() / 1000) < SOCKET_MIN_VALIDITY_SECONDS) {
|
|
1074
|
+
refuse(socket, 401, "Unauthorized");
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
if (!(await checkSession(bff.redis, bff.markerKeys, session, noRefresh))) {
|
|
1078
|
+
refuse(socket, 401, "Unauthorized");
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// The same path on the API: /crm/socket.io/?EIO=4 → /socket.io/?EIO=4.
|
|
1083
|
+
const target = new URL(`${bff.apiOrigin}${(req.url ?? "/").slice(bff.basePath.length)}`);
|
|
1084
|
+
// The same allowlist as the http region, plus the handshake; the browser's credentials never pass.
|
|
1085
|
+
const headers: Record<string, string> = { ...allowedHeaders(req, WEBSOCKET_HEADERS), connection: "Upgrade", upgrade: "websocket" };
|
|
1086
|
+
headers["authorization"] = `Bearer ${auth.access_token}`;
|
|
1087
|
+
const send = target.protocol === "https:" ? httpsRequest : httpRequest;
|
|
1088
|
+
const upstreamRequest = send(target, { method: "GET", headers });
|
|
1089
|
+
|
|
1090
|
+
upstreamRequest.on("upgrade", (answer: IncomingMessage, upstream: Duplex, upstreamHead: Buffer) => {
|
|
1091
|
+
const lines = [`HTTP/1.1 101 ${answer.statusMessage ?? "Switching Protocols"}`];
|
|
1092
|
+
for (let index = 0; index + 1 < answer.rawHeaders.length; index += 2) {
|
|
1093
|
+
const name = answer.rawHeaders[index] ?? "";
|
|
1094
|
+
if (name.toLowerCase() !== "set-cookie") lines.push(`${name}: ${answer.rawHeaders[index + 1] ?? ""}`);
|
|
1095
|
+
}
|
|
1096
|
+
socket.write(`${lines.join("\r\n")}\r\n\r\n`);
|
|
1097
|
+
if (upstreamHead.length > 0) socket.write(upstreamHead);
|
|
1098
|
+
if (head.length > 0) upstream.write(head);
|
|
1099
|
+
upstream.pipe(socket).pipe(upstream);
|
|
1100
|
+
const close = (): void => {
|
|
1101
|
+
open.delete(socket);
|
|
1102
|
+
socket.destroy();
|
|
1103
|
+
upstream.destroy();
|
|
1104
|
+
};
|
|
1105
|
+
for (const side of [socket, upstream]) side.on("close", close).on("error", close);
|
|
1106
|
+
open.set(socket, { cookie: req.headers.cookie, upstream });
|
|
1107
|
+
});
|
|
1108
|
+
// The API answered without upgrading (for example 401): pass the status on and close.
|
|
1109
|
+
upstreamRequest.on("response", (answer: IncomingMessage) => {
|
|
1110
|
+
answer.resume();
|
|
1111
|
+
refuse(socket, answer.statusCode ?? 502, answer.statusMessage ?? "Bad Gateway");
|
|
1112
|
+
});
|
|
1113
|
+
upstreamRequest.on("error", () => {
|
|
1114
|
+
refuse(socket, 502, "Bad Gateway");
|
|
1115
|
+
});
|
|
1116
|
+
upstreamRequest.end();
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
server.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {
|
|
1120
|
+
const url = req.url ?? "";
|
|
1121
|
+
// Other paths are left to the server's other upgrade listeners.
|
|
1122
|
+
if (url !== prefix && !url.startsWith(`${prefix}/`) && !url.startsWith(`${prefix}?`)) return;
|
|
1123
|
+
upgrade(req, socket, head).catch(() => {
|
|
1124
|
+
// The markers could not be read: no socket now, the session is kept.
|
|
1125
|
+
refuse(socket, 503, "Service Unavailable");
|
|
1126
|
+
});
|
|
1127
|
+
});
|
|
1128
|
+
|
|
1129
|
+
// A revoked session or a blocked user also closes the sockets that are already open.
|
|
1130
|
+
const timer = setInterval(() => {
|
|
1131
|
+
for (const [socket, entry] of open) {
|
|
1132
|
+
const session = bff.store.read(entry.cookie);
|
|
1133
|
+
checkSession(bff.redis, bff.markerKeys, session, noRefresh).then(
|
|
1134
|
+
(ok) => {
|
|
1135
|
+
if (ok) return;
|
|
1136
|
+
socket.destroy();
|
|
1137
|
+
entry.upstream.destroy();
|
|
1138
|
+
},
|
|
1139
|
+
() => {
|
|
1140
|
+
// Redis unreachable: keep the socket and check again at the next round.
|
|
1141
|
+
},
|
|
1142
|
+
);
|
|
1143
|
+
}
|
|
1144
|
+
}, SOCKET_RECHECK_MS);
|
|
1145
|
+
timer.unref();
|
|
1146
|
+
return () => {
|
|
1147
|
+
clearInterval(timer);
|
|
1148
|
+
};
|
|
1149
|
+
}
|
|
1150
|
+
```
|
|
1151
|
+
<!-- /snippet -->
|
|
1152
|
+
|
|
1153
|
+
Path socket-nya `${basePath}/socket.io/`, path bawaan Socket.IO: `/socket.io/` di root host, `/crm/socket.io/` di bawah sub-path. BFF meneruskannya ke path yang sama di API Anda (`/socket.io/`). Di browser, client Socket.IO di bawah sub-path diberi `path: "/crm/socket.io/"`.
|
|
1154
|
+
|
|
1155
|
+
- **Upgrade WebSocket** hanya diterima dari `Origin` aplikasi sendiri (browser selalu mengirim `Origin` saat upgrade). Sesi dibaca dari cookie. Header yang diteruskan memakai daftar izin yang sama dengan proxy API ([§13](#13-proxy-ke-api)), ditambah header handshake WebSocket; `Authorization` dan `Cookie` kiriman browser dibuang dan access token sesi disisipkan.
|
|
1156
|
+
- **Upgrade tidak pernah me-refresh**: sesi yang diperbarui tidak bisa ditulis kembali ke cookie dari jawaban upgrade. Bila token tidak ada atau habis dalam 60 detik, upgrade ditolak `401`; browser memanggil `/auth/me` (yang me-refresh dengan cara biasa), lalu menyambung lagi.
|
|
1157
|
+
- **Long-polling Socket.IO** (`GET` dan `POST` ke `${basePath}/socket.io/`) adalah request HTTP biasa yang membawa cookie sesi. Route-nya `socketPollingProxy`: request diteruskan lewat `forward` yang sama dengan proxy API, ke `/socket.io/` di API Anda. Setiap method, juga `GET`, wajib berasal dari halaman aplikasi sendiri (`sameOriginOnly`): `Origin`, bila dikirim browser, harus sama dengan `APP_URL`; browser tidak mengirim `Origin` pada `GET` ke origin yang sama, jadi request tanpa `Origin` wajib membawa `Sec-Fetch-Site: same-origin`. Header CSRF khusus ([§15](#15-csrf)) tidak diwajibkan di path ini, karena client Socket.IO tidak mengirimnya.
|
|
1158
|
+
- Setiap beberapa menit, sesi socket yang terbuka diperiksa lagi terhadap marker pencabutan; socket dari sesi yang dicabut atau user yang diblokir ditutup. Di sisi API, handshake dan socket yang terbuka juga diperiksa ([`verifikasi-token.md` §9](verifikasi-token.md#socket)).
|
|
1159
|
+
|
|
1160
|
+
## 15. CSRF
|
|
1161
|
+
|
|
1162
|
+
<!-- snippet: examples/snippets/bff-express.ts#csrf -->
|
|
1163
|
+
```ts
|
|
1164
|
+
/**
|
|
1165
|
+
* The custom header the SPA sends on every API call that changes data. A form of another site cannot
|
|
1166
|
+
* set a custom header. The name and value are this app's own choice; pick your own pair.
|
|
1167
|
+
*/
|
|
1168
|
+
export const CSRF_HEADER_NAME = "x-bff-request";
|
|
1169
|
+
export const CSRF_HEADER_VALUE = "1";
|
|
1170
|
+
const SAFE_METHODS: ReadonlySet<string> = new Set(["GET", "HEAD", "OPTIONS"]);
|
|
1171
|
+
|
|
1172
|
+
/**
|
|
1173
|
+
* A request that changes something must come from this app's own pages: its Origin must be the app's
|
|
1174
|
+
* origin, and API calls also carry the custom header. The logout is a plain form post, which cannot
|
|
1175
|
+
* send a custom header, so it is checked by Origin only. The BFF sends no CORS headers, so no other
|
|
1176
|
+
* origin can read its answers.
|
|
1177
|
+
*/
|
|
1178
|
+
export function csrfGuard(appOrigin: string, requireHeader: boolean) {
|
|
1179
|
+
return (req: Request, res: Response, next: NextFunction): void => {
|
|
1180
|
+
if (SAFE_METHODS.has(req.method)) {
|
|
1181
|
+
next();
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1184
|
+
if (req.get("origin") !== appOrigin || (requireHeader && req.get(CSRF_HEADER_NAME) !== CSRF_HEADER_VALUE)) {
|
|
1185
|
+
res.status(403).json({ error: "forbidden" });
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
next();
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/**
|
|
1193
|
+
* For Socket.IO's long-polling requests: they carry the session cookie, so every method, GET included,
|
|
1194
|
+
* must come from this app's pages. No custom header (the Socket.IO client does not send one). A browser
|
|
1195
|
+
* sends Origin on every POST and every cross-origin request; on a same-origin GET it leaves Origin out
|
|
1196
|
+
* but sends Sec-Fetch-Site: same-origin. A request with neither is refused.
|
|
1197
|
+
*/
|
|
1198
|
+
export function sameOriginOnly(appOrigin: string) {
|
|
1199
|
+
return (req: Request, res: Response, next: NextFunction): void => {
|
|
1200
|
+
const origin = req.get("origin");
|
|
1201
|
+
const sameOrigin = origin === undefined ? req.get("sec-fetch-site") === "same-origin" : origin === appOrigin;
|
|
1202
|
+
if (!sameOrigin) {
|
|
1203
|
+
res.status(403).json({ error: "forbidden" });
|
|
1204
|
+
return;
|
|
1205
|
+
}
|
|
1206
|
+
next();
|
|
1207
|
+
};
|
|
1208
|
+
}
|
|
1209
|
+
```
|
|
1210
|
+
<!-- /snippet -->
|
|
1211
|
+
|
|
1212
|
+
- Request yang mengubah data (selain `GET`, `HEAD`, `OPTIONS`) wajib membawa `Origin` aplikasi sendiri.
|
|
1213
|
+
- Panggilan API dari SPA juga wajib membawa header khusus, di contoh ini `X-Bff-Request: 1` (`CSRF_HEADER_NAME` dan `CSRF_HEADER_VALUE`). Form dari situs lain tidak bisa mengirim header khusus. Nama dan nilainya pilihan aplikasi Anda sendiri; misalnya sebuah aplikasi CRM memakai `X-Requested-With: plasgos-crm`. Yang penting SPA dan BFF memakai pasangan yang sama.
|
|
1214
|
+
- Path socket `${basePath}/socket.io/` tidak memakai header khusus, tetapi setiap method-nya diperiksa asal-usulnya ([§14](#14-proxy-socket)).
|
|
1215
|
+
- Logout adalah form `POST` biasa (tanpa header khusus), jadi diperiksa lewat `Origin` saja.
|
|
1216
|
+
- BFF tidak mengirim header CORS: origin lain tidak bisa membaca jawabannya.
|
|
1217
|
+
- `SameSite=Lax` di cookie sesi menambah lapisan, tetapi tidak menggantikan pemeriksaan di atas.
|
|
1218
|
+
|
|
1219
|
+
Route dan server lengkapnya:
|
|
1220
|
+
|
|
1221
|
+
<!-- snippet: examples/snippets/bff-express.ts#router -->
|
|
1222
|
+
```ts
|
|
1223
|
+
/** The auth routes. Mounted at the root of the host, or under the sub-path (startBff in bff-proxy.ts). */
|
|
1224
|
+
export function createBffRouter(bff: Bff): Router {
|
|
1225
|
+
const router = express.Router();
|
|
1226
|
+
router.get("/auth/login", (req, res) => {
|
|
1227
|
+
login(bff, req, res);
|
|
1228
|
+
});
|
|
1229
|
+
router.get("/auth/callback", route((req, res) => callback(bff, req, res)));
|
|
1230
|
+
router.get("/auth/me", route((req, res) => me(bff, req, res)));
|
|
1231
|
+
router.post("/auth/logout", csrfGuard(bff.appOrigin, false), route((req, res) => logout(bff, req, res)));
|
|
1232
|
+
return router;
|
|
1233
|
+
}
|
|
1234
|
+
```
|
|
1235
|
+
<!-- /snippet -->
|
|
1236
|
+
|
|
1237
|
+
<!-- snippet: examples/snippets/bff-proxy.ts#server -->
|
|
1238
|
+
```ts
|
|
1239
|
+
/** The whole BFF: the auth routes, the API proxy (with the CSRF header) and the socket proxy. */
|
|
1240
|
+
export function startBff(redis: RedisLike, port: number, basePath = ""): Server {
|
|
1241
|
+
const bff = createBff(redis, basePath);
|
|
1242
|
+
const routes = express.Router();
|
|
1243
|
+
routes.use(createBffRouter(bff));
|
|
1244
|
+
routes.use("/api", csrfGuard(bff.appOrigin, true), apiProxy(bff));
|
|
1245
|
+
// Socket.IO long-polling: the same path on the API, Origin checked on every method.
|
|
1246
|
+
routes.use(SOCKET_PATH, socketPollingProxy(bff));
|
|
1247
|
+
|
|
1248
|
+
const app = express();
|
|
1249
|
+
app.disable("x-powered-by");
|
|
1250
|
+
app.use(basePath === "" ? "/" : basePath, routes);
|
|
1251
|
+
const server = app.listen(port);
|
|
1252
|
+
server.on("close", attachSocketProxy(server, bff));
|
|
1253
|
+
return server;
|
|
1254
|
+
}
|
|
1255
|
+
```
|
|
1256
|
+
<!-- /snippet -->
|
|
1257
|
+
|
|
1258
|
+
Pemakaiannya: `startBff(new Redis(process.env.REDIS_URL), 3000)` di root host, atau `startBff(redis, 3000, "/crm")` di bawah sub-path (`Redis` dari `ioredis`).
|
|
1259
|
+
|
|
1260
|
+
## 16. PWA
|
|
1261
|
+
|
|
1262
|
+
PWA yang dipasang di iOS punya penyimpanan cookie sendiri, terpisah dari Safari, jadi login yang dimulai di satu tempat tidak selesai di tempat lain. Aturannya ada di [`login-web.md` §9](login-web.md#9-pwa).
|
|
1263
|
+
|
|
1264
|
+
## 17. Error dan jawaban
|
|
1265
|
+
|
|
1266
|
+
| Keadaan | Jawaban BFF | Sesi | Yang dilakukan SPA |
|
|
1267
|
+
|---|---|---|---|
|
|
1268
|
+
| Tidak ada sesi, atau sesi diakhiri (dicabut, diblokir, refresh ditolak) | `401 {"error":"login_required"}` | Dihapus | Arahkan ke `/auth/login?return_to=<path>` |
|
|
1269
|
+
| Plasgos atau Redis (marker atau lock refresh) tidak bisa dihubungi, lock refresh terlalu lama | `503 {"error":"temporarily_unavailable"}` dengan `Retry-After` | Tetap | Coba lagi sebentar. Jangan logout |
|
|
1270
|
+
| `config_invalid` atau `provider_error` dari Plasgos | `500 {"error":"internal_error"}` | Tetap | Tampilkan pesan gagal. Ini bug konfigurasi; alert lewat `onFailure` |
|
|
1271
|
+
| Request tanpa `Origin` aplikasi atau tanpa header CSRF khusus; request polling socket dari origin lain | `403 {"error":"forbidden"}` | Tetap | Bug di SPA: kirim header itu, dan buka socket dari halaman aplikasi sendiri |
|
|
1272
|
+
| API Anda tidak bisa dihubungi | `502 {"error":"bad_gateway"}` | Tetap | Coba lagi sebentar |
|
|
1273
|
+
| Jawaban API (termasuk `401`, `403`, `503`) | Diteruskan apa adanya | Tetap, cookie yang berubah ikut dikirim | Sesuai jawaban API ([`verifikasi-token.md` §14](verifikasi-token.md#14-error-dan-jawaban-http)) |
|
|
1274
|
+
| Callback gagal | `400` atau `503`, teks "Login gagal" | Transaksi dihapus | Tawarkan login lagi |
|
|
1275
|
+
|
|
1276
|
+
Daftar lengkap `reason` dari `OidcError` ada di [`error.md` §1](error.md#1-oidcerror).
|
|
1277
|
+
|
|
1278
|
+
## 18. Masalah umum
|
|
1279
|
+
|
|
1280
|
+
| Gejala | Penyebab | Perbaikan |
|
|
1281
|
+
|---|---|---|
|
|
1282
|
+
| User sering keluar sendiri, log menunjukkan `invalid_grant` saat refresh | Beberapa instance me-refresh token yang sama tanpa lock bersama | Pasang `redisRefreshLock` di semua instance ([§9](#9-refresh-dan-lock-redis)) |
|
|
1283
|
+
| Banyak `503` dengan `RefreshLockTimeoutError` | Redis lambat atau tidak bisa dihubungi, atau `waitMs` lebih pendek dari waktu refresh | Periksa Redis. `lockMs` lebih panjang dari batas waktu token, `waitMs` sedikit di bawahnya |
|
|
1284
|
+
| Long-polling Socket.IO dijawab `403` hanya di Safari lama (sebelum 16.4) | Browser itu tidak mengirim `Origin` maupun `Sec-Fetch-Site` pada polling GET ke origin yang sama | Biarkan Socket.IO memakai WebSocket (upgrade tetap memeriksa `Origin`), atau minta user memperbarui Safari |
|
|
1285
|
+
| Callback selalu `400` dengan `missing` | Cookie transaksi tidak terkirim: callback di luar `path` store, aplikasi dibuka lewat `http:`, atau `SESSION_SECRET` berbeda antar instance | Callback di bawah `basePath`, pakai `https`, samakan secret |
|
|
1286
|
+
| Plasgos menolak login karena redirect URI tidak cocok | Redirect URI tidak sama persis dengan yang didaftarkan (misalnya lupa `/crm`) | Daftarkan URI persis seperti yang dibuat `createBff` |
|
|
1287
|
+
| Logout tidak menghapus cookie | Cookie lama ditulis dengan path atau nama lain | Hapus cookie lama dengan nama dan path lamanya, satu kali |
|
|
1288
|
+
| Logout selalu menampilkan halaman konfirmasi Plasgos | Tidak ada logout ticket: BFF di luar jaringan Plasgos tanpa `backchannelUrl`, atau ID token tidak muat di cookie | Perilaku yang benar tanpa `backchannelUrl` |
|
|
1289
|
+
| Semua panggilan API `401 invalid_token` walaupun sudah login | `PLASGOS_RESOURCE` berbeda dari audience yang diverifikasi API | Samakan `PLASGOS_RESOURCE` dengan `PLASGOS_TOKEN_AUDIENCE` di API |
|
|
1290
|
+
| `POST` ke `/api/*` selalu `403` | SPA tidak mengirim header CSRF khusus (`X-Bff-Request: 1` di contoh), atau `APP_URL` tidak sama persis dengan origin halaman | Kirim header itu; samakan `APP_URL` (skema, host, port) |
|
|
1291
|
+
| Semua route `404`, atau cookie sesi tidak terkirim | Reverse proxy (misalnya nginx) membuang awalan `/crm` sebelum meneruskan ke BFF, sehingga route dan `Path=/crm/` cookie tidak cocok | Jangan buang awalannya: teruskan `/crm/…` utuh ke BFF (`proxy_pass` tanpa path di nginx) |
|
|
1292
|
+
| Socket.IO tidak tersambung, request polling `404` | Client Socket.IO memakai path bawaan `/socket.io/` di bawah sub-path | Di browser: `io({ path: "/crm/socket.io/" })` |
|
|
1293
|
+
| Socket langsung ditutup `401` | Token hampir habis dan upgrade tidak me-refresh | SPA memanggil `/auth/me` lalu menyambung lagi |
|
|
1294
|
+
| Socket atau request polling ditolak `403` | `Origin` handshake bukan `APP_URL`, atau request polling tanpa `Origin` dan tanpa `Sec-Fetch-Site: same-origin` | Buka socket dari halaman aplikasi sendiri |
|
|
1295
|
+
| Upload besar gagal `401` tanpa diulang | Upload di-stream tidak diulang setelah refresh | SPA memanggil `/auth/me` lalu mengulang upload |
|
|
1296
|
+
|
|
1297
|
+
## 19. Sebelum production
|
|
1298
|
+
|
|
1299
|
+
- [ ] Client, session store, dan lock Redis dibuat saat start; `ConfigError` menghentikan proses.
|
|
1300
|
+
- [ ] Env production: `PLASGOS_ENV=production`, issuer production, `PLASGOS_RESOURCE` production, secret production di secret manager.
|
|
1301
|
+
- [ ] Redirect URI dan URL setelah logout terdaftar persis, termasuk sub-path.
|
|
1302
|
+
- [ ] `redisRefreshLock` dipakai di semua instance; `lockMs` lebih panjang dari batas waktu token.
|
|
1303
|
+
- [ ] Callback menghapus cookie transaksi di semua jalur dan menulis sesi baru.
|
|
1304
|
+
- [ ] `return_to` hanya menerima path di bawah `basePath`, tanpa segmen `.`/`..`.
|
|
1305
|
+
- [ ] Scope login memuat `plasgos:public_id` bila API Anda mewajibkan `plasgos_public_id`.
|
|
1306
|
+
- [ ] Hanya `invalid_grant`, `invalid_target`, dan `missing` yang mengakhiri sesi; `503` tidak pernah menghapus sesi.
|
|
1307
|
+
- [ ] Pemeriksaan pencabutan berjalan di setiap request yang membawa sesi, dan marker diisi dari event `user.*`.
|
|
1308
|
+
- [ ] Proxy meneruskan header request dari daftar izin saja (tanpa `Authorization`, `Cookie`, `X-Auth-Agent`, `Fingerprint`, `X-Mobile-*`, `X-Forwarded-*`), dan tidak meneruskan `Set-Cookie` dari API.
|
|
1309
|
+
- [ ] Upgrade socket memeriksa `Origin` dan tidak pernah me-refresh; request polling `/socket.io/` diperiksa asal-usulnya di setiap method.
|
|
1310
|
+
- [ ] Request yang mengubah data diperiksa `Origin`-nya, panggilan API memakai header CSRF khusus milik aplikasi, dan tidak ada header CORS.
|
|
1311
|
+
- [ ] Reverse proxy meneruskan sub-path (`/crm/…`) utuh ke BFF.
|
|
1312
|
+
- [ ] Logout lewat form `POST` dan selalu menghapus sesi lokal.
|
|
1313
|
+
- [ ] `onFailure` menulis log dan memberi alert untuk `config_invalid`.
|
|
1314
|
+
- [ ] Jawaban `/auth/me` tidak pernah memuat token.
|