@plasgos/auth-verify 0.1.0-next.2 → 0.1.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +51 -15
  3. package/THIRD_PARTY_NOTICES.md +31 -0
  4. package/dist/express.cjs +157 -0
  5. package/dist/express.cjs.map +1 -0
  6. package/dist/express.d.cts +90 -0
  7. package/dist/express.d.ts +90 -0
  8. package/dist/express.js +127 -0
  9. package/dist/express.js.map +1 -0
  10. package/dist/index.cjs +1254 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.cts +67 -0
  13. package/dist/index.d.ts +67 -0
  14. package/dist/index.js +499 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/nestjs.cjs +1395 -0
  17. package/dist/nestjs.cjs.map +1 -0
  18. package/dist/nestjs.d.cts +153 -0
  19. package/dist/nestjs.d.ts +153 -0
  20. package/dist/nestjs.js +637 -0
  21. package/dist/nestjs.js.map +1 -0
  22. package/dist/types-CGtRnj59.d.cts +193 -0
  23. package/dist/types-CGtRnj59.d.ts +193 -0
  24. package/dist/webhook.cjs +8 -6
  25. package/dist/webhook.cjs.map +1 -1
  26. package/dist/webhook.d.cts +9 -3
  27. package/dist/webhook.d.ts +9 -3
  28. package/dist/webhook.js +8 -6
  29. package/dist/webhook.js.map +1 -1
  30. package/docs/bff-express.md +1314 -0
  31. package/docs/consumers.md +10 -2
  32. package/docs/error.md +195 -10
  33. package/docs/examples/auth-verify-readme.ts +24 -0
  34. package/docs/examples/bff-express.ts +370 -0
  35. package/docs/examples/bff-proxy.ts +335 -0
  36. package/docs/examples/bff-redis-lock.ts +187 -0
  37. package/docs/examples/bff-revocation.ts +136 -0
  38. package/docs/examples/env.ts +52 -1
  39. package/docs/examples/token-commonjs.cjs +95 -0
  40. package/docs/examples/token-express.ts +56 -0
  41. package/docs/examples/token-fetch.ts +24 -0
  42. package/docs/examples/token-nestjs-jest.ts +77 -0
  43. package/docs/examples/token-nestjs.ts +127 -0
  44. package/docs/examples/token-socket.ts +59 -0
  45. package/docs/examples/token-testing.ts +100 -0
  46. package/docs/examples/token-verifier.ts +132 -0
  47. package/docs/examples/user-events.ts +110 -0
  48. package/docs/examples/webhook-verifier.ts +54 -0
  49. package/docs/login-web.md +39 -7
  50. package/docs/memulai.md +94 -14
  51. package/docs/server-ke-server.md +12 -0
  52. package/docs/verifikasi-token.md +1219 -0
  53. package/docs/webhook.md +191 -6
  54. package/package.json +61 -5
@@ -0,0 +1,132 @@
1
+ import { createAccessTokenVerifier } from "@plasgos/auth-verify";
2
+ import type { AccessPrincipal, AccessTokenVerifier, AuthRejectEvent, UserAccessPrincipal } from "@plasgos/auth-verify";
3
+
4
+ import { readTokenVerifierEnv } from "./env.js";
5
+
6
+ // #region revocation
7
+ /** The part of a key-value store the check reads. An ioredis or node-redis client fits it. */
8
+ export interface RevocationStore {
9
+ get(key: string): Promise<string | null>;
10
+ }
11
+
12
+ /** Thrown when the marker store cannot be read. The app's error handler answers it with 503. */
13
+ export class RevocationStoreUnavailableError extends Error {
14
+ constructor(options?: ErrorOptions) {
15
+ super("revocation store unavailable", options);
16
+ this.name = "RevocationStoreUnavailableError";
17
+ }
18
+ }
19
+
20
+ /**
21
+ * The app's own marker keys (the prefix is yours). Your webhook receiver writes them from the user.*
22
+ * events Plasgos sends to your app's webhook endpoint.
23
+ */
24
+ export const revocationKeys = {
25
+ /** The newest credential version Plasgos announced for the user, as text ("3"). */
26
+ credentialVersion: (publicId: string): string => `myapp:revocation:cv:${publicId}`,
27
+ /** Present when the Plasgos session (`sid`) was revoked. */
28
+ session: (sessionId: string): string => `myapp:revocation:sid:${sessionId}`,
29
+ /** Present while the user is blocked. */
30
+ blockedUser: (publicId: string): string => `myapp:revocation:blocked:${publicId}`,
31
+ };
32
+
33
+ /**
34
+ * The `isRevoked` hook: true refuses the token as `revoked` (401). Three checks:
35
+ * - the session was revoked (logout everywhere, a removed device);
36
+ * - the user is blocked;
37
+ * - the user's credentials changed after the token was issued (stored version above the token's `cv`).
38
+ *
39
+ * Without such a hook a token stays valid until it expires. When the store cannot be read the hook
40
+ * throws: the request fails with 503 instead of letting a revoked token through, and without a 401
41
+ * that would send every client to log in again because of an outage.
42
+ */
43
+ export function revocationCheck(store: RevocationStore): (principal: UserAccessPrincipal) => Promise<boolean> {
44
+ return async (principal) => {
45
+ const publicId = principal.claims.plasgos_public_id;
46
+ const tokenVersion = principal.credentialVersion;
47
+ // requireClaims: ["plasgos_public_id", "cv"] already refuses such a token; the hook stays safe alone.
48
+ if (publicId === undefined || tokenVersion === null) return true;
49
+
50
+ let markers: (string | null)[];
51
+ try {
52
+ markers = await Promise.all([
53
+ store.get(revocationKeys.session(principal.sessionId)),
54
+ store.get(revocationKeys.blockedUser(publicId)),
55
+ store.get(revocationKeys.credentialVersion(publicId)),
56
+ ]);
57
+ } catch (error) {
58
+ // Never swallowed: an unreadable store must not count as "not revoked".
59
+ throw new RevocationStoreUnavailableError({ cause: error });
60
+ }
61
+ const [revokedSession, blocked, storedVersion] = markers;
62
+ if (revokedSession !== null || blocked !== null) return true;
63
+ if (storedVersion === null || storedVersion === undefined) return false;
64
+ const stored = Number(storedVersion);
65
+ // A marker this app did not write is a store problem, not a token problem.
66
+ if (!Number.isSafeInteger(stored)) throw new RevocationStoreUnavailableError();
67
+ return stored > tokenVersion;
68
+ };
69
+ }
70
+ // #endregion revocation
71
+
72
+ // #region on-reject
73
+ /** One line per refused token. The event never holds the token or a claim value, so it is safe to log. */
74
+ export function logReject(event: AuthRejectEvent): void {
75
+ const line = [
76
+ "plasgos token refused:",
77
+ `env=${event.environment}`,
78
+ `reason=${event.reason}`,
79
+ `client_id=${event.clientId ?? "-"}`,
80
+ `request_id=${event.requestId ?? "-"}`,
81
+ ].join(" ");
82
+ process.stderr.write(`${line}\n`);
83
+ // The key set of Plasgos cannot be read: every request answers 503 until it recovers.
84
+ if (event.reason === "unavailable") process.stderr.write("ALERT plasgos key set unavailable\n");
85
+ }
86
+ // #endregion on-reject
87
+
88
+ // #region create
89
+ /** Create it once at start: a wrong option throws one ConfigError there, before the first request. */
90
+ export function createApiTokenVerifier(store: RevocationStore): AccessTokenVerifier {
91
+ const env = readTokenVerifierEnv();
92
+ return createAccessTokenVerifier({
93
+ environment: env.environment,
94
+ issuer: env.issuer,
95
+ audience: env.audience,
96
+ backchannelUrl: env.backchannelUrl,
97
+ allowInsecureBackchannel: env.allowInsecureBackchannel,
98
+ // Every token must carry the user's public id and credential version.
99
+ requireClaims: ["plasgos_public_id", "cv"],
100
+ // Required for a crm audience: compares the session, the user and cv with the app's markers.
101
+ isRevoked: revocationCheck(store),
102
+ onReject: logReject,
103
+ });
104
+ }
105
+ // #endregion create
106
+
107
+ // #region identity
108
+ /** The caller as this API knows it. */
109
+ export interface Caller {
110
+ /** The user's public id (`usr-…`): the same in every app, so it is the user key of this API. */
111
+ publicId: string;
112
+ /** The Plasgos session (`sid`). */
113
+ sessionId: string;
114
+ /** The credential version (`cv`) the token was issued with. */
115
+ credentialVersion: number;
116
+ }
117
+
118
+ /**
119
+ * The caller of a verified token. `principal.subject` is pairwise (a different value for every client
120
+ * that calls this API), so the user is identified by `claims.plasgos_public_id`, never by `subject`.
121
+ */
122
+ export function callerOf(principal: AccessPrincipal): Caller {
123
+ if (principal.kind !== "user") throw new Error("this API accepts user tokens only");
124
+ const publicId = principal.claims.plasgos_public_id;
125
+ const credentialVersion = principal.credentialVersion;
126
+ // requireClaims: ["plasgos_public_id", "cv"] guarantees both; the check narrows the types.
127
+ if (publicId === undefined || credentialVersion === null) {
128
+ throw new Error("the verifier must require plasgos_public_id and cv");
129
+ }
130
+ return { publicId, sessionId: principal.sessionId, credentialVersion };
131
+ }
132
+ // #endregion identity
@@ -0,0 +1,110 @@
1
+ import type { VerifiedWebhook } from "@plasgos/auth-verify/webhook";
2
+
3
+ import { revocationKeys } from "./token-verifier.js";
4
+ import type { ApplyEvent, Tx } from "./webhook-verifier.js";
5
+
6
+ // #region user-events
7
+ /** The Redis commands the marker writer uses. An ioredis client fits it. */
8
+ export interface MarkerRedis {
9
+ eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
10
+ set(key: string, value: string, mode: "EX", seconds: number): Promise<unknown>;
11
+ set(key: string, value: string): Promise<unknown>;
12
+ del(key: string): Promise<number>;
13
+ }
14
+
15
+ /**
16
+ * The credential-version and session markers live 1 hour: much longer than a Plasgos access token, so
17
+ * every token issued before the event has expired before its marker does.
18
+ */
19
+ export const MARKER_TTL_SECONDS = 3_600;
20
+
21
+ /**
22
+ * Stores the larger of the stored and the new credential version (compare-and-set in one Redis step).
23
+ * Events of one user can arrive out of order; a plain SET could lower the version and let a revoked
24
+ * token through again.
25
+ */
26
+ const RAISE_TO_MAX = `
27
+ local current = tonumber(redis.call("GET", KEYS[1]))
28
+ if current == nil or tonumber(ARGV[1]) > current then
29
+ redis.call("SET", KEYS[1], ARGV[1], "EX", tonumber(ARGV[2]))
30
+ end
31
+ return 0`;
32
+
33
+ /** The user.* event data, the published contract of the app events (`data` of the event body). */
34
+ interface UserEventData {
35
+ /** The user's public id (`usr-…`), the same value as the token's plasgos_public_id. */
36
+ user: string;
37
+ /** user.credentials_revoked: the user's new credential version (the token claim `cv`). */
38
+ credential_version?: number;
39
+ /** user.session_revoked: the revoked Plasgos session, the same value as the token claim `sid`. */
40
+ sid?: string;
41
+ /** user.status_changed: active, pending, suspended, banned or unlinked. */
42
+ status?: string;
43
+ }
44
+
45
+ const isText = (value: unknown): value is string => typeof value === "string" && value !== "" && value.length <= 128;
46
+
47
+ /** The event's `data`, checked. A malformed one throws: the delivery fails (500) and Plasgos sends it again. */
48
+ function userDataOf(event: VerifiedWebhook): UserEventData {
49
+ const data = event.body["data"];
50
+ if (typeof data !== "object" || data === null) throw new Error(`user event ${event.id}: data is not an object`);
51
+ const fields = data as Record<string, unknown>;
52
+ const user = fields["user"];
53
+ if (!isText(user)) throw new Error(`user event ${event.id}: data.user is missing`);
54
+ const version = fields["credential_version"];
55
+ const sid = fields["sid"];
56
+ const status = fields["status"];
57
+ return {
58
+ user,
59
+ ...(typeof version === "number" && Number.isSafeInteger(version) ? { credential_version: version } : {}),
60
+ ...(isText(sid) ? { sid } : {}),
61
+ ...(isText(status) ? { status } : {}),
62
+ };
63
+ }
64
+
65
+ /**
66
+ * The `user` handler of routeByType (webhook.md §6): writes the revocation markers that isRevoked reads.
67
+ * - user.credentials_revoked → the credential version, stored as the maximum, TTL 1 hour;
68
+ * - user.session_revoked → the session marker, TTL 1 hour;
69
+ * - user.status_changed → the status is persisted in the app's database (same transaction as the
70
+ * event id) and cached in Redis: any status other than "active" sets the blocked marker, "active"
71
+ * removes it. Refill the blocked markers from the database if your Redis can lose its data.
72
+ * A user.* type the app does not know has no effect.
73
+ */
74
+ export function userEventHandler(redis: MarkerRedis): ApplyEvent {
75
+ return async (tx: Tx, event: VerifiedWebhook) => {
76
+ const data = userDataOf(event);
77
+ switch (event.type) {
78
+ case "user.credentials_revoked": {
79
+ if (data.credential_version === undefined) throw new Error(`user event ${event.id}: data.credential_version is missing`);
80
+ const key = revocationKeys.credentialVersion(data.user);
81
+ await redis.eval(RAISE_TO_MAX, 1, key, data.credential_version, MARKER_TTL_SECONDS);
82
+ return;
83
+ }
84
+ case "user.session_revoked": {
85
+ if (data.sid === undefined) throw new Error(`user event ${event.id}: data.sid is missing`);
86
+ await redis.set(revocationKeys.session(data.sid), "1", "EX", MARKER_TTL_SECONDS);
87
+ return;
88
+ }
89
+ case "user.status_changed": {
90
+ if (data.status === undefined) throw new Error(`user event ${event.id}: data.status is missing`);
91
+ // The lasting record. sequence keeps an older event from overwriting a newer status.
92
+ const sequence = typeof event.body["sequence"] === "number" ? event.body["sequence"] : 0;
93
+ const stored = await tx.query(
94
+ `INSERT INTO plasgos_user_status (public_id, status, sequence) VALUES ($1, $2, $3)
95
+ ON CONFLICT (public_id) DO UPDATE SET status = EXCLUDED.status, sequence = EXCLUDED.sequence
96
+ WHERE plasgos_user_status.sequence < EXCLUDED.sequence`,
97
+ [data.user, data.status, sequence],
98
+ );
99
+ if (stored.rowCount !== 1) return;
100
+ // The cache isRevoked reads, without an expiry: it holds as long as the user is blocked.
101
+ if (data.status === "active") await redis.del(revocationKeys.blockedUser(data.user));
102
+ else await redis.set(revocationKeys.blockedUser(data.user), data.status);
103
+ return;
104
+ }
105
+ default:
106
+ return;
107
+ }
108
+ };
109
+ }
110
+ // #endregion user-events
@@ -30,6 +30,20 @@ export function createShippingWebhookVerifier(): WebhookVerifier {
30
30
  }
31
31
  // #endregion create-shipping
32
32
 
33
+ // #region create-app-events
34
+ /**
35
+ * Every event Plasgos sends to the app's webhook endpoint (payments, subscriptions, add-ons, packages,
36
+ * users), with one secret. Same headers and signature as presets.payments; the result's preset reads "appEvents".
37
+ */
38
+ export function createAppEventsWebhookVerifier(): WebhookVerifier {
39
+ return createWebhookVerifier({
40
+ environment: readEnvironment(),
41
+ secrets: readWebhookSecrets("PLASGOS_WEBHOOK_SECRET"),
42
+ preset: presets.appEvents,
43
+ });
44
+ }
45
+ // #endregion create-app-events
46
+
33
47
  // #region dedup
34
48
  /** The part of a database transaction this example needs. Your driver's transaction object fits it. */
35
49
  export interface Tx {
@@ -141,3 +155,43 @@ export const applyPaymentEvent: ApplyEvent = async (tx, event) => {
141
155
  await tx.query("UPDATE bills SET status = 'paid', paid_at = now() WHERE payment_id = $1 AND status <> 'paid'", [payment]);
142
156
  };
143
157
  // #endregion apply-paid
158
+
159
+ // #region route-by-type
160
+ /** The app's own effect for each event family. Each one runs in the transaction of saveOnce. */
161
+ export interface AppEventHandlers {
162
+ /** payment.* */
163
+ payment: ApplyEvent;
164
+ /** subscription.*, entitlements.* and addon.* */
165
+ subscription: ApplyEvent;
166
+ /** package.* */
167
+ package: ApplyEvent;
168
+ /** user.* */
169
+ user: ApplyEvent;
170
+ }
171
+
172
+ /**
173
+ * The `apply` of handleWebhook for an appEvents endpoint: it runs after saveOnce(tx, event) stored a new
174
+ * event and hands the event to the handler of its family. A type the app does not know has no effect:
175
+ * handleWebhook commits the event id and answers 2xx, so a new event type never blocks the queue.
176
+ */
177
+ export function routeByType(handlers: AppEventHandlers): ApplyEvent {
178
+ return async (tx, event) => {
179
+ const family = event.type.split(".", 1)[0];
180
+ switch (family) {
181
+ case "payment":
182
+ return handlers.payment(tx, event);
183
+ case "subscription":
184
+ case "entitlements":
185
+ case "addon":
186
+ return handlers.subscription(tx, event);
187
+ case "package":
188
+ return handlers.package(tx, event);
189
+ case "user":
190
+ return handlers.user(tx, event);
191
+ default:
192
+ // Unknown type: no effect. The id is still stored, so a redelivery is not processed either.
193
+ return;
194
+ }
195
+ };
196
+ }
197
+ // #endregion route-by-type
package/docs/login-web.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Login user di aplikasi web
2
2
 
3
- Panduan ini untuk aplikasi web yang punya server sendiri (pola BFF) dan ingin user login dengan akun Plasgos. Server aplikasi yang berbicara dengan Plasgos dan menyimpan token di cookie terenkripsi. JavaScript di browser tidak pernah memegang token.
3
+ Panduan ini untuk aplikasi web yang punya server sendiri (pola BFF) dan ingin user login dengan akun Plasgos. Server aplikasi yang berbicara dengan Plasgos dan menyimpan token di cookie terenkripsi. JavaScript di browser tidak pernah memegang token. Untuk BFF dengan Node/Express di depan SPA atau PWA (lock Redis, proxy API dan socket, pencabutan sesi), lanjutkan ke [`bff-express.md`](bff-express.md).
4
4
 
5
5
  Sebelum mulai, baca [`memulai.md`](memulai.md) untuk env dan cara mendapat kredensial client login.
6
6
 
@@ -109,7 +109,7 @@ export function createThirdPartyClient(): OidcClient {
109
109
  | `postLogoutRedirectUri` | Tidak | — | URL tujuan setelah logout, sama persis dengan yang didaftarkan. Tanpa ini, Plasgos menampilkan halaman "sudah keluar" miliknya |
110
110
  | `scopes` | Ya | — | Daftar scope user. Wajib memuat `"openid"` ([`memulai.md` §4](memulai.md#4-daftar-scope)) |
111
111
  | `profile` | Ya | — | `"first-party"` (aplikasi Plasgos) atau `"third-party"` |
112
- | `resource` | Bila memakai scope `account:*` / `packages:*` | — | Audience API yang dipanggil atas nama user. Tidak boleh untuk `"third-party"` |
112
+ | `resource` | Bila memakai scope `account:*` / `packages:*` / `crm:access` | — | Audience API yang dipanggil atas nama user, misalnya `https://api.plasgos.co.id/crm` untuk `crm:access` di production. Tidak boleh untuk `"third-party"` |
113
113
  | `logoutTicket` | Tidak | Lihat di bawah | Menukar ID token dengan tiket sekali pakai saat logout, supaya Plasgos tidak menampilkan halaman konfirmasi |
114
114
  | `endSession` | Tidak | `"redirect"` | `"redirect"`: logout berupa URL. `"form-post"`: hanya untuk aplikasi yang berada di origin issuer sendiri (accounts). Di production, `redirectUri` di origin lain adalah `ConfigError`. Di sandbox SDK menerimanya (aplikasi dan issuer lokal berjalan di dua port), tetapi Plasgos menjawab form `POST` dari origin lain dengan `403` |
115
115
  | `extraClaims` | Tidak | `[]` | Nama klaim ID token tambahan yang dikembalikan di `claims.extra`, misalnya `["plasgos_public_id"]` |
@@ -208,7 +208,8 @@ export function fromZod<T>(schema: SafeParser<T>): SessionSchema<T> {
208
208
  | `secrets` | Ya | — | Satu atau dua secret, masing-masing minimal 32 byte. Yang pertama menyegel, semuanya bisa membuka ([§7](#7-rotasi-secret-sesi)) |
209
209
  | `hkdfSalt` | Ya | — | Salt turunan kunci, misalnya nama aplikasi. Jangan diubah setelah rilis |
210
210
  | `cookies` | Ya | — | Nama empat cookie: `app`, `auth`, `idToken`, `transaction`. Huruf kecil, angka, dan `-`, 1–32 karakter, harus berbeda satu sama lain. Jangan diubah setelah rilis |
211
- | `hostPrefix` | Tidak | `true` | `true`: nama cookie diawali `__Host-` dan memakai `Secure`. `false` hanya untuk development lokal dengan `http:` |
211
+ | `hostPrefix` | Tidak | `true` | `true`: nama cookie diberi awalan dan memakai `Secure` (`__Host-` dengan `path` bawaan, `__Secure-` dengan `path` lain). `false` hanya untuk development lokal dengan `http:` |
212
+ | `path` | Tidak | `"/"` | Path cookie. Dengan `"/"` tidak ada yang berubah. Path lain, misalnya `"/crm/"`, untuk aplikasi di bawah sub-path sebuah host bersama: setiap cookie yang ditulis atau dihapus memakai `Path=<path>`, dan nama cookie memakai `__Secure-` ([§6](#aplikasi-di-bawah-sub-path)). Harus diawali dan diakhiri `/`, hanya karakter ASCII yang terlihat, tanpa `;`, `,`, `%`, `..`, atau `//`. String kosong dianggap tidak diisi. Jangan diubah setelah rilis |
212
213
  | `authMaxAgeSeconds` | Ya | — | Umur cookie `auth` dan `idToken` dalam detik. Bilangan bulat positif, atau fungsi `(auth) => number` |
213
214
  | `appSchema` | Ya | — | `{ parse(input) }` yang mengembalikan data aplikasi atau `null`. Semua field aplikasi harus opsional |
214
215
  | `compactKeys` | Tidak | — | Tabel nama kunci ringkas untuk memperkecil cookie. Aplikasi baru tidak perlu mengisinya ([§8](#8-aplikasi-yang-sudah-punya-cookie-sesi-migrasi)) |
@@ -228,7 +229,7 @@ Mengubah `hkdfSalt` atau nama cookie membuat semua cookie lama tidak terbaca, se
228
229
  | `readTransaction(request)` | Transaksi login, atau `null` bila tidak ada, rusak, atau lebih tua dari 10 menit |
229
230
  | `commitTransaction(tx)`, `clearTransaction()` | `Set-Cookie` untuk menyimpan dan menghapus transaksi login |
230
231
  | `commitApp`, `commitAuth`, `commitIdToken` | Satu cookie saja. Melempar `SessionTooLargeError` bila tidak muat. Biasanya cukup `commit` |
231
- | `cookieNames` | Nama cookie yang benar-benar dikirim (dengan `__Host-` bila `hostPrefix`) |
232
+ | `cookieNames` | Nama cookie yang benar-benar dikirim: `__Host-<nama>` (bawaan), `__Secure-<nama>` (dengan `path` lain), atau nama polos (`hostPrefix: false`) |
232
233
 
233
234
  `read` mengembalikan pegangan sesi untuk satu request:
234
235
 
@@ -531,7 +532,7 @@ Hanya `invalid_grant` dan `invalid_target` (dan `missing`) yang mengakhiri sesi.
531
532
 
532
533
  Plasgos mengganti refresh token setiap kali dipakai. Refresh kedua dengan token yang sama dianggap pencurian token, dan Plasgos mencabut seluruh sesi. Karena itu SDK menjalankan refresh satu per satu untuk setiap refresh token (`refreshLock`), dan hasilnya dipakai ulang selama 30 detik untuk request yang masih membawa token lama.
533
534
 
534
- Bawaannya `memoryLockStore()`: kunci di memori satu proses. Bila aplikasi berjalan di beberapa instance, dua instance bisa me-refresh token yang sama bersamaan. Untuk itu, berikan `refreshLock` buatan sendiri di atas penyimpanan bersama (misalnya Redis) yang memenuhi interface `RefreshLockStore`:
535
+ Bawaannya `memoryLockStore()`: kunci di memori satu proses. Bila aplikasi berjalan di beberapa instance, dua instance bisa me-refresh token yang sama bersamaan. Untuk itu, berikan `refreshLock` buatan sendiri di atas penyimpanan bersama (misalnya Redis) yang memenuhi interface `RefreshLockStore`. Contoh lengkap di atas Redis, dengan aturannya: [`bff-express.md` §9](bff-express.md#9-refresh-dan-lock-redis).
535
536
 
536
537
  | Anggota | Arti |
537
538
  |---|---|
@@ -550,8 +551,8 @@ Sesi dibagi menjadi empat cookie:
550
551
  | `idToken` | ID token saja, untuk logout | `authMaxAgeSeconds` |
551
552
  | `transaction` | Transaksi login yang sedang berjalan | 10 menit |
552
553
 
553
- - Atribut semua cookie: `Path=/`, `HttpOnly`, `SameSite=Lax`, dan `Secure` (kecuali `hostPrefix: false`). Tidak ada `Domain`.
554
- - Dengan `hostPrefix: true`, nama yang dikirim adalah `__Host-<nama>`. Browser hanya menerima cookie `__Host-` lewat `https`.
554
+ - Atribut semua cookie: `Path=<path>` (bawaan `Path=/`), `HttpOnly`, `SameSite=Lax`, dan `Secure` (kecuali `hostPrefix: false`). Tidak ada `Domain`.
555
+ - Dengan `hostPrefix: true` dan `path` bawaan, nama yang dikirim adalah `__Host-<nama>`. Browser hanya menerima cookie `__Host-` lewat `https`, tanpa `Domain`, dan dengan `Path=/`, jadi cookie itu terikat ke host aplikasi Anda saja.
555
556
  - Batas ukuran satu `Set-Cookie` adalah 4000 karakter. Browser membuang cookie yang lebih besar.
556
557
  - `commit()` menangani cookie yang terlalu besar sendiri: cookie itu dihapus, datanya dibuang dari sesi, dan `onFailure` milik store dipanggil dengan nama cookie dan ukurannya. Bila yang terlalu besar hanya `idToken`, login tetap jalan, tetapi logout akan menampilkan halaman konfirmasi Plasgos.
557
558
  - Pakai `fits(auth)` di callback supaya login yang tidak muat ditolak dengan jelas, bukan hilang diam-diam.
@@ -559,6 +560,37 @@ Sesi dibagi menjadi empat cookie:
559
560
 
560
561
  Development lokal dengan `http://localhost`: pakai `environment: "sandbox"`, `allowInsecureHttp: true` di client, dan `hostPrefix: false` di store. Contoh di atas tidak menyetel keduanya; tambahkan sendiri.
561
562
 
563
+ ### Aplikasi di bawah sub-path
564
+
565
+ Pakai `path` hanya bila aplikasi Anda (biasanya sebuah BFF) dilayani di bawah sebuah path dari host yang dipakai bersama aplikasi lain, misalnya `https://app.example.com/crm/`. Bila aplikasi bisa punya host sendiri (`https://crm.example.com`), pakai host sendiri dan biarkan `path` bawaan: cookie `__Host-` lebih kuat.
566
+
567
+ Dengan `path: "/crm/"`:
568
+
569
+ - nama cookie menjadi `__Secure-<nama>`, karena browser hanya menerima cookie `__Host-` dengan `Path=/`;
570
+ - setiap cookie yang ditulis **dan dihapus** memakai `Path=/crm/`. Browser hanya menghapus cookie bila nama dan path-nya sama, jadi SDK selalu menulis keduanya;
571
+ - route login, callback, dan logout aplikasi juga berada di bawah `/crm/` (misalnya `redirectUri` `https://app.example.com/crm/auth/callback`), supaya browser mengirim cookie ke route itu;
572
+ - isi cookie dan cara menyegelnya tidak berubah. Yang berubah hanya nama dan atribut cookie, jadi mengganti `path` setelah rilis sama dengan mengganti nama cookie: semua user harus login ulang.
573
+
574
+ **Risiko yang diterima.** Cookie `__Secure-` dengan `Path` tidak terikat ke satu host seperti `__Host-`. Aplikasi lain di host yang sama, atau di subdomain saudara, bisa menulis cookie dengan nama yang sama (cookie tossing). Ia tidak bisa memalsukan isi sesi, karena isinya tersegel dengan secret Anda; cookie yang tidak bisa dibuka dianggap tidak ada. Mitigasinya: callback selalu menulis sesi baru, tidak pernah menggabungkan dengan sesi lama ([§4](#callback)), dan request yang mengubah data hanya diterima dari `Origin` aplikasi sendiri. Contoh lengkap BFF di bawah sub-path ada di [`bff-express.md` §11](bff-express.md#11-bff-di-bawah-sub-path).
575
+
576
+ ### Membaca klaim access token sesi (`readAccessTokenClaims`)
577
+
578
+ `readAccessTokenClaims(accessToken)` dari `@plasgos/oidc-client/session` membaca `sid` (sesi Plasgos), `cv` (versi kredensial user), dan `plasgos_public_id` dari access token yang disimpan sesi Anda. Hasilnya objek `{ sid, cv, plasgos_public_id }`, masing-masing `null` bila tidak ada atau bentuknya salah; atau `null` bila input bukan token. Fungsi ini tidak pernah melempar.
579
+
580
+ - **Tidak memverifikasi token.** Pakai hanya untuk token milik sesi Anda sendiri (`session.data.auth.access_token`): aplikasi Anda menerimanya langsung dari Plasgos lewat TLS dan menyimpannya di cookie tersegel. Token yang datang dari request (header `Authorization`) wajib diverifikasi dengan `@plasgos/auth-verify` ([`verifikasi-token.md`](verifikasi-token.md)).
581
+ - **Nilainya milik token saat diterbitkan.** Setelah `ensureFresh` mengganti token, baca lagi dari token yang baru.
582
+ - Kegunaannya: pemeriksaan pencabutan sesi di BFF pada setiap request (sesi dicabut, user diblokir, kredensial berubah). Alurnya ada di [`bff-express.md` §12](bff-express.md#12-pencabutan-sesi).
583
+
584
+ ### Masalah umum dengan cookie
585
+
586
+ | Gejala | Penyebab | Perbaikan |
587
+ |---|---|---|
588
+ | Setelah login, user langsung dianggap belum login | Cookie `__Host-` atau `__Secure-` ditolak browser karena aplikasi dibuka lewat `http:` | Pakai `https`. Untuk development lokal: `hostPrefix: false` dan `environment: "sandbox"` |
589
+ | Callback selalu gagal dengan `missing` | Route callback berada di luar `path` store, jadi browser tidak mengirim cookie transaksi | Letakkan callback di bawah `path` yang sama |
590
+ | Logout tidak menghapus cookie | Cookie lama ditulis dengan path atau nama lain (misalnya sebelum `path` diubah) | Hapus juga cookie lama dengan nama dan path lamanya, satu kali |
591
+ | Semua user keluar setelah deploy | `hkdfSalt`, nama cookie, `path`, atau `SESSION_SECRET` berubah tanpa rotasi | Kembalikan nilainya, atau rotasi secret dengan `baru,lama` ([§7](#7-rotasi-secret-sesi)) |
592
+ | `ConfigError: path must start and end with "/" …` | `path` tanpa `/` di awal atau akhir, atau memuat karakter terlarang | Tulis seperti `"/crm/"` |
593
+
562
594
  ## 7. Rotasi secret sesi
563
595
 
564
596
  `secrets` menerima satu atau dua nilai. Yang pertama dipakai menyegel. Semuanya dipakai membuka.
package/docs/memulai.md CHANGED
@@ -7,7 +7,7 @@ Urutan kerja yang disarankan:
7
7
  1. Tentukan kebutuhan aplikasi di [§1](#1-paket-mana-untuk-kebutuhan-apa).
8
8
  2. Minta kredensial ke tim Plasgos ([§6](#6-mendapat-kredensial)).
9
9
  3. Install paket ([§2](#2-install)) dan atur env ([§5](#5-env-yang-disarankan)).
10
- 4. Lanjut ke panduan sesuai kebutuhan: [`login-web.md`](login-web.md), [`server-ke-server.md`](server-ke-server.md), atau [`webhook.md`](webhook.md).
10
+ 4. Lanjut ke panduan sesuai kebutuhan: [`login-web.md`](login-web.md), [`server-ke-server.md`](server-ke-server.md), [`webhook.md`](webhook.md), atau [`verifikasi-token.md`](verifikasi-token.md).
11
11
 
12
12
  ## 1. Paket mana untuk kebutuhan apa
13
13
 
@@ -16,8 +16,11 @@ Urutan kerja yang disarankan:
16
16
  | User login dengan akun Plasgos | `@plasgos/oidc-client` | `createOidcClient` | [`login-web.md`](login-web.md) |
17
17
  | Menyimpan sesi login di cookie | `@plasgos/oidc-client/session` | `createSessionStore` | [`login-web.md`](login-web.md) |
18
18
  | Server memanggil API Plasgos tanpa user (misalnya payments) | `@plasgos/oidc-client/service` | `createServiceClient` | [`server-ke-server.md`](server-ke-server.md) |
19
- | Menerima webhook dari Plasgos (payments, pengiriman Plaslink) | `@plasgos/auth-verify/webhook` | `createWebhookVerifier` | [`webhook.md`](webhook.md) |
20
- | Memeriksa access token Plasgos di API sendiri | `@plasgos/auth-verify` | — | Menyusul |
19
+ | Menerima webhook dari Plasgos (payments, event aplikasi, pengiriman Plaslink) | `@plasgos/auth-verify/webhook` | `createWebhookVerifier` | [`webhook.md`](webhook.md) |
20
+ | Memeriksa access token Plasgos di API sendiri | `@plasgos/auth-verify` | `createAccessTokenVerifier` | [`verifikasi-token.md`](verifikasi-token.md) |
21
+ | Sama, sebagai middleware Express | `@plasgos/auth-verify/express` | `requirePlasgosToken` | [`verifikasi-token.md`](verifikasi-token.md#9-express) |
22
+ | Sama, sebagai modul dan guard NestJS | `@plasgos/auth-verify/nestjs` | `PlasgosAuthModule`, `PlasgosAccessTokenGuard` | [`verifikasi-token.md`](verifikasi-token.md#10-nestjs) |
23
+ | BFF Node/Express untuk SPA atau PWA: sesi cookie, lock refresh Redis, proxy ke API sendiri | `@plasgos/oidc-client`, `@plasgos/oidc-client/session` | `createOidcClient`, `createSessionStore`, `readAccessTokenClaims` | [`bff-express.md`](bff-express.md) |
21
24
 
22
25
  Contoh per jenis aplikasi:
23
26
 
@@ -26,6 +29,7 @@ Contoh per jenis aplikasi:
26
29
  | Aplikasi Plasgos sendiri (accounts, Kirim Paket) | Login + sesi cookie | [`login-web.md`](login-web.md) |
27
30
  | Plaslink | Login (seller menghubungkan akun) + payments + webhook | [`contoh-plaslink.md`](contoh-plaslink.md) |
28
31
  | HitungCuan | Payments + webhook, tanpa login | [`contoh-hitungcuan.md`](contoh-hitungcuan.md) |
32
+ | API yang dipanggil aplikasi lain dengan token user (misalnya API CRM) | Verifikasi token + webhook event aplikasi + client service (`/service`) | [`verifikasi-token.md`](verifikasi-token.md), [`webhook.md`](webhook.md), [`server-ke-server.md`](server-ke-server.md) |
29
33
 
30
34
  Semua paket hanya untuk server: Node `>=22.22`, tersedia sebagai ESM dan CommonJS. Tidak ada build untuk browser. Secret client tidak boleh sampai ke browser.
31
35
 
@@ -34,11 +38,11 @@ Semua paket hanya untuk server: Node `>=22.22`, tersedia sebagai ESM dan CommonJ
34
38
  Paket ada di npmjs.com dan di-install tanpa token, dengan nomor versi persis:
35
39
 
36
40
  - login, sesi, dan server ke server: `pnpm add @plasgos/oidc-client@<versi> --save-exact`;
37
- - menerima webhook: `pnpm add @plasgos/auth-verify@<versi> --save-exact`.
41
+ - menerima webhook atau memeriksa access token di API sendiri: `pnpm add @plasgos/auth-verify@<versi> --save-exact`. Import-nya `@plasgos/auth-verify` (verifier token), `@plasgos/auth-verify/express` (middleware Express), `@plasgos/auth-verify/nestjs` (modul dan guard NestJS 11), dan `@plasgos/auth-verify/webhook`.
38
42
 
39
43
  Install hanya paket yang dibutuhkan. Aplikasi yang memakai keduanya memasang versi yang sama untuk keduanya. `@plasgos/auth-shared` ikut terpasang sendiri. Aturan versi, Docker, CI, dan lisensi ada di [`consumers.md`](consumers.md).
40
44
 
41
- Proyek TypeScript harus memakai `moduleResolution` `node16`, `nodenext`, atau `bundler` di `tsconfig.json`. Dengan `moduleResolution: node` yang lama, import `@plasgos/oidc-client/service` dan `/session` gagal dengan `Cannot find module`, begitu juga `@plasgos/auth-verify/webhook`. `@plasgos/auth-verify` tidak punya entry utama, jadi dengan `moduleResolution: node` tidak ada bagiannya yang bisa di-import. File di [folder contoh](examples/) saling meng-import dengan akhiran `.js` (gaya NodeNext); sesuaikan bila proyek Anda memakai gaya lain.
45
+ Proyek TypeScript harus memakai `moduleResolution` `node16`, `nodenext`, atau `bundler` di `tsconfig.json`. Dengan `moduleResolution: node` yang lama, import `@plasgos/oidc-client/service` dan `/session` gagal dengan `Cannot find module`, begitu juga `@plasgos/auth-verify/webhook`, `/express`, dan `/nestjs`. File di [folder contoh](examples/) saling meng-import dengan akhiran `.js` (gaya NodeNext); sesuaikan bila proyek Anda memakai gaya lain.
42
46
 
43
47
  ## 3. Dua jenis client
44
48
 
@@ -67,6 +71,19 @@ Aplikasi yang butuh keduanya (Plaslink) membuat dua client dengan dua pasang kre
67
71
 
68
72
  `sub` bersifat pairwise: user yang sama mendapat `sub` berbeda di setiap client. Jangan membandingkan `sub` antar client.
69
73
 
74
+ ### Istilah
75
+
76
+ Istilah berikut dipakai di semua panduan:
77
+
78
+ | Istilah | Arti |
79
+ |---|---|
80
+ | Audience | Alamat yang mewakili satu API, misalnya `https://api.plasgos.co.id/crm`. Token diterbitkan untuk satu audience (klaim `aud`), dan API hanya menerima token untuk audience-nya sendiri. Aplikasi yang meminta token menyebut audience itu sebagai `resource` |
81
+ | BFF | Backend-for-frontend: server milik aplikasi yang memegang sesi login user untuk SPA atau PWA, menyimpan token Plasgos di server, dan meneruskan request browser ke API aplikasi dengan token itu. Token tidak pernah sampai ke browser ([`bff-express.md`](bff-express.md)) |
82
+ | `sub` pairwise | Klaim `sub` (id user) yang berbeda untuk setiap client: user yang sama punya `sub` lain di aplikasi lain. Jangan dipakai untuk mengenali user lintas aplikasi |
83
+ | `sid` | Id sesi login user di Plasgos. Satu login di satu browser adalah satu sesi; logout atau pencabutan sesi mengakhirinya |
84
+ | `cv` | Versi kredensial user (credential version). Naik setiap kali kredensial user berubah atau semua sesinya dicabut, misalnya saat ganti password. Token membawa versi saat token diterbitkan, jadi token dengan `cv` lebih kecil dari versi terbaru sudah dicabut |
85
+ | `plasgos_public_id` | Id publik user (`usr-…`), sama di semua aplikasi. Dibawa token hanya bila client meminta scope `plasgos:public_id`. Inilah kunci user di API yang dipanggil lebih dari satu client |
86
+
70
87
  ## 4. Daftar scope
71
88
 
72
89
  `scopes` selalu berupa daftar string, satu scope per elemen: `["openid", "profile"]`. Jangan menulis satu string berisi beberapa scope (`"openid profile"` atau `"openid,profile"`). String yang memuat spasi ditolak SDK saat start (`scopes contains a value that is not a valid scope token`). Bentuk dengan koma tidak dikenali SDK, diteruskan apa adanya, lalu ditolak Plasgos.
@@ -81,6 +98,13 @@ Scope yang belum dikenal SDK diteruskan tanpa pemeriksaan. Plasgos yang memutusk
81
98
  | `payments:read` | Melihat payment milik app sendiri dan daftar metode bayar |
82
99
  | `payments:write` | Membuat payment, mengganti metode, membatalkan |
83
100
  | `payments:refund` | Refund |
101
+ | `users:profile.read` | Profil dan pencarian user yang tertaut ke app Anda. Tersedia setelah Plasgos merilisnya |
102
+ | `users:legacy.read` | Impor tautan dan id user dari sistem lama, sementara. Tersedia setelah Plasgos merilisnya |
103
+ | `packages:service.read` | Origin, layanan, wilayah, slot, quote, dan paket. Tersedia setelah Plasgos merilisnya |
104
+ | `packages:service.write` | Membuat, mengirim, dan membatalkan paket. Tersedia setelah Plasgos merilisnya |
105
+ | `subscriptions:catalog.write` | Mengirim dan membaca katalog modul dan fitur app Anda. Tersedia setelah Plasgos merilisnya |
106
+ | `subscriptions:read` | Membaca entitlement dan grant. Tersedia setelah Plasgos merilisnya |
107
+ | `subscriptions:grants.write` | Mengonfirmasi pengiriman grant. Tersedia setelah Plasgos merilisnya |
84
108
 
85
109
  ### Scope user (client login)
86
110
 
@@ -89,14 +113,18 @@ Scope yang belum dikenal SDK diteruskan tanpa pemeriksaan. Plasgos yang memutusk
89
113
  | `openid` | Wajib. Memberi `sub` | Semua |
90
114
  | `profile` | `name`, `picture` | Semua |
91
115
  | `email` | `email` | Semua |
116
+ | `phone` | `phone_number` dan `phone_number_verified`, hanya bila nomor ponsel akun sudah terverifikasi (tanpa nomor terverifikasi, keduanya tidak dikirim). Pada login dengan `resource`, klaim ada di ID token dan dibaca lewat opsi `extraClaims`. Lihat catatan klaim profil di bawah tabel | Semua |
92
117
  | `offline_access` | Refresh token | Semua, bila client didaftarkan dengan scope ini |
93
118
  | `plaslink:shipping` | Persetujuan seller untuk pengiriman lewat Plaslink | Client Plaslink |
94
119
  | `plasgos:public_id` | Klaim `plasgos_public_id` (`usr-…`) | First-party saja |
95
120
  | `account:read`, `account:write` | API akun | First-party saja, wajib `resource` |
96
121
  | `packages:read`, `packages:write` | API seller Kirim Paket | First-party saja, wajib `resource` |
122
+ | `crm:access` | API CRM, dengan `resource` berisi audience CRM (`https://api.plasgos.co.id/crm` di production). Tersedia setelah Plasgos merilisnya | First-party saja, wajib `resource` |
97
123
 
98
124
  "First-party" berarti aplikasi milik Plasgos sendiri (`profile: "first-party"`). Aplikasi lain memakai `profile: "third-party"` dan tidak bisa meminta scope first-party.
99
125
 
126
+ Klaim profil (`name`, `picture`, `email`, `phone_number`) masuk ID token hanya pada login dengan `resource`. Tanpa `resource`, termasuk semua client pihak ketiga, ID token hanya membawa `sub`, dan klaim itu diambil dari endpoint userinfo (`/oidc/me`) dengan access token hasil login. SDK ini belum menyediakan fungsi untuk memanggil userinfo.
127
+
100
128
  ## 5. Env yang disarankan
101
129
 
102
130
  Nama env bebas, tetapi nama di bawah dipakai di semua contoh panduan ini.
@@ -106,14 +134,17 @@ Nama env bebas, tetapi nama di bawah dipakai di semua contoh panduan ini.
106
134
  | `PLASGOS_ENV` | Ya | `sandbox` | `sandbox` atau `production`. Tidak punya nilai bawaan |
107
135
  | `PLASGOS_ISSUER` | Bila ada login atau panggilan API | `https://accounts.plasgos.co.id` | Host tempat user login dan token diterbitkan (`/oidc/*`) |
108
136
  | `PLASGOS_API_URL` | Bila ada login atau panggilan API | `https://api.plasgos.co.id` | Host API Plasgos (`/v5/*`) |
109
- | `PLASGOS_BACKCHANNEL_URL` | Tidak | `http://plasgos-internal:3010` (alamat internal, contoh) | Alamat internal server Plasgos. Hanya untuk aplikasi yang berjalan di jaringan Plasgos |
137
+ | `PLASGOS_BACKCHANNEL_URL` | Tidak | `http://plasgos.internal.example:8080` (alamat internal, contoh) | Alamat internal server Plasgos. Hanya untuk aplikasi yang berjalan di jaringan Plasgos |
110
138
  | `PLASGOS_LOGIN_CLIENT_ID`, `PLASGOS_LOGIN_CLIENT_SECRET` | Bila ada login | | Kredensial client login |
111
139
  | `PLASGOS_SERVICE_CLIENT_ID`, `PLASGOS_SERVICE_CLIENT_SECRET` | Bila ada panggilan server-ke-server | | Kredensial client service |
112
140
  | `PLASGOS_AUDIENCE` | Tidak | `https://api.sandbox.plasgos.co.id/platform` | Audience token service. Audience = API yang dituju token (`resource`). Diisi hanya bila tim Plasgos memberi nilai yang berbeda dari bawaan |
113
141
  | `PLASGOS_RESOURCE` | First-party saja | `https://api.plasgos.co.id/packages` | Audience API yang dipanggil atas nama user |
142
+ | `PLASGOS_TOKEN_AUDIENCE` | Bila API Anda memverifikasi access token | `https://api.plasgos.co.id/crm` | Audience API Anda sendiri, dari tim Plasgos. `aud` setiap token harus sama persis ([`verifikasi-token.md` §3](verifikasi-token.md#3-env)) |
143
+ | `PLASGOS_ALLOW_INSECURE_BACKCHANNEL` | Tidak | `true` | Hanya untuk verifikasi token di production: menerima `PLASGOS_BACKCHANNEL_URL` `http:` di jaringan privat yang Anda percaya ([`verifikasi-token.md` §13](verifikasi-token.md#13-alamat-internal-backchannelurl)) |
114
144
  | `APP_URL` | Bila ada login | `https://app.example.com` | Origin publik aplikasi Anda, dasar `redirectUri` |
145
+ | `APP_API_URL` | Bila memakai BFF | `http://api.internal:8080` (contoh) | Origin API milik aplikasi di belakang BFF ([`bff-express.md` §4](bff-express.md#4-env)). Bukan nilai dari Plasgos |
115
146
  | `SESSION_SECRET` | Bila memakai `/session` | | Secret cookie sesi, minimal 32 byte. Saat rotasi: `baru,lama` |
116
- | `PLASGOS_WEBHOOK_SECRET` | Bila menerima webhook payments | | Secret webhook payments (`whsec_…`). Saat rotasi: `baru,lama`, bila kedua secret tidak memuat koma dan tidak diawali atau diakhiri spasi; bila memuat, pakai dua env ([`webhook.md` §4](webhook.md#4-membuat-verifier), [§8](webhook.md#8-rotasi-secret)) |
147
+ | `PLASGOS_WEBHOOK_SECRET` | Bila menerima webhook aplikasi | | Secret endpoint webhook aplikasi (`whsec_…`): satu endpoint dan satu secret untuk event payments dan event aplikasi lain (langganan, paket, `user.*`). Saat rotasi: `baru,lama`, bila kedua secret tidak memuat koma dan tidak diawali atau diakhiri spasi; bila memuat, pakai dua env ([`webhook.md` §4](webhook.md#4-membuat-verifier), [§8](webhook.md#8-rotasi-secret)) |
117
148
  | `PLASGOS_SHIPPING_WEBHOOK_SECRET` | Bila menerima webhook pengiriman Plaslink | | Secret webhook pengiriman Plaslink. Saat rotasi: `baru,lama`, dengan aturan yang sama |
118
149
 
119
150
  Semua nilai secret (`*_CLIENT_SECRET`, `SESSION_SECRET`, `PLASGOS_WEBHOOK_SECRET`, `PLASGOS_SHIPPING_WEBHOOK_SECRET`) disimpan di secret manager aplikasi. Jangan di-commit, jangan ditulis ke log.
@@ -209,7 +240,8 @@ export function readSessionSecrets(): string[] {
209
240
 
210
241
  /**
211
242
  * A webhook secret: one secret, or "new,old" while a rotation is in progress. Names used in the guides:
212
- * PLASGOS_WEBHOOK_SECRET (payments) and PLASGOS_SHIPPING_WEBHOOK_SECRET (Plaslink shipping).
243
+ * PLASGOS_WEBHOOK_SECRET (the app webhook endpoint: payments and every other app event, one secret)
244
+ * and PLASGOS_SHIPPING_WEBHOOK_SECRET (Plaslink shipping).
213
245
  */
214
246
  export function readWebhookSecrets(name: string): string[] {
215
247
  const secrets = required(name)
@@ -219,6 +251,52 @@ export function readWebhookSecrets(name: string): string[] {
219
251
  if (secrets.length > 2) throw new Error(`Environment variable ${name} holds at most two secrets`);
220
252
  return secrets;
221
253
  }
254
+
255
+ /** What an API that verifies Plasgos access tokens reads. */
256
+ export interface TokenVerifierEnv {
257
+ environment: Environment;
258
+ /** PLASGOS_ISSUER: the token's `iss` must equal it. */
259
+ issuer: string;
260
+ /** PLASGOS_TOKEN_AUDIENCE: the audience of this API, given by the Plasgos team; the token's `aud` must equal it. */
261
+ audience: string;
262
+ /** PLASGOS_BACKCHANNEL_URL: optional internal origin for the key set (JWKS), only inside the Plasgos network. */
263
+ backchannelUrl: string | undefined;
264
+ /** PLASGOS_ALLOW_INSECURE_BACKCHANNEL=true: production only, an http: back channel on a private network you trust. */
265
+ allowInsecureBackchannel: boolean;
266
+ }
267
+
268
+ export function readTokenVerifierEnv(): TokenVerifierEnv {
269
+ return {
270
+ environment: readEnvironment(),
271
+ issuer: required("PLASGOS_ISSUER"),
272
+ audience: required("PLASGOS_TOKEN_AUDIENCE"),
273
+ backchannelUrl: optional("PLASGOS_BACKCHANNEL_URL"),
274
+ allowInsecureBackchannel: optional("PLASGOS_ALLOW_INSECURE_BACKCHANNEL") === "true",
275
+ };
276
+ }
277
+
278
+ /** What a backend-for-frontend (BFF) reads besides its login credentials and its session secret. */
279
+ export interface BffEnv {
280
+ environment: Environment;
281
+ /** PLASGOS_ISSUER: where users log in and tokens are issued. */
282
+ issuer: string;
283
+ /** PLASGOS_BACKCHANNEL_URL: optional internal origin of the Plasgos server, only inside the Plasgos network. */
284
+ backchannelUrl: string | undefined;
285
+ /** PLASGOS_RESOURCE: the audience of the app's own API; every token is requested for it. */
286
+ resource: string;
287
+ /** APP_API_URL: origin of the app's own API behind the BFF (not a Plasgos value). */
288
+ apiOrigin: string;
289
+ }
290
+
291
+ export function readBffEnv(): BffEnv {
292
+ return {
293
+ environment: readEnvironment(),
294
+ issuer: required("PLASGOS_ISSUER"),
295
+ backchannelUrl: optional("PLASGOS_BACKCHANNEL_URL"),
296
+ resource: required("PLASGOS_RESOURCE"),
297
+ apiOrigin: required("APP_API_URL").replace(/\/$/, ""),
298
+ };
299
+ }
222
300
  ```
223
301
  <!-- /snippet -->
224
302
 
@@ -243,7 +321,7 @@ Kode aplikasi sama di semua lingkungan. Yang berbeda hanya nilai env. Setiap lin
243
321
 
244
322
  Nilai selain `"sandbox"` dan `"production"`, atau kosong, ditolak. Tujuannya supaya aplikasi sandbox tidak pernah mengirim secret atau transaksi ke production karena salah env.
245
323
 
246
- `backchannelUrl` adalah alamat internal server Plasgos untuk panggilan server-ke-server milik SDK: token, pencabutan token, dan logout ticket. Boleh `http:` karena berada di jaringan internal. Aplikasi di luar jaringan Plasgos tidak mengisinya. Tanpa `backchannelUrl`, panggilan token memakai `issuer`.
324
+ `backchannelUrl` adalah alamat internal server Plasgos untuk panggilan server-ke-server milik SDK: token, pencabutan token, dan logout ticket. Boleh `http:` karena berada di jaringan internal. Aplikasi di luar jaringan Plasgos tidak mengisinya. Tanpa `backchannelUrl`, panggilan token memakai `issuer`. Pengecualian: verifier access token mengambil kunci publik Plasgos lewat alamat ini, jadi di production `createAccessTokenVerifier` mewajibkan `https:` kecuali `allowInsecureBackchannel: true` ([`verifikasi-token.md` §13](verifikasi-token.md#13-alamat-internal-backchannelurl)).
247
325
 
248
326
  ## 6. Mendapat kredensial
249
327
 
@@ -270,19 +348,19 @@ Tim Plasgos menyiapkan app dan client service-nya, lalu menyerahkan client id da
270
348
 
271
349
  ### Secret webhook
272
350
 
273
- Yang Anda kirim ke tim Plasgos: URL webhook aplikasi Anda (`https`), satu untuk setiap lingkungan. Tim Plasgos mendaftarkan URL itu, lalu menyerahkan secret webhook kepada Anda. Webhook payments dan webhook pengiriman Plaslink memakai secret yang berbeda. Rotasinya ada di [`webhook.md` §8](webhook.md#8-rotasi-secret).
351
+ Yang Anda kirim ke tim Plasgos: URL webhook aplikasi Anda (`https`), satu untuk setiap lingkungan. Tim Plasgos mendaftarkan URL itu, lalu menyerahkan secret webhook kepada Anda (`PLASGOS_WEBHOOK_SECRET`). Satu endpoint dengan satu secret menerima semua event aplikasi: payments, langganan, paket, dan `user.*` ([`webhook.md` §6](webhook.md#satu-endpoint-untuk-semua-event-aplikasi)). Webhook pengiriman Plaslink memakai endpoint dan secret sendiri. Rotasinya ada di [`webhook.md` §8](webhook.md#8-rotasi-secret).
274
352
 
275
353
  ### Yang Anda terima
276
354
 
277
355
  | Lewat kanal secret | Bukan rahasia |
278
356
  |---|---|
279
357
  | Client id dan client secret (per client) | Issuer (`PLASGOS_ISSUER`) |
280
- | Secret webhook (payments: `whsec_…`), bila menerima webhook | Host API (`PLASGOS_API_URL`) |
358
+ | Secret webhook aplikasi (`whsec_…`, untuk payments dan event aplikasi), bila menerima webhook | Host API (`PLASGOS_API_URL`) |
281
359
  | | Audience, bila berbeda dari bawaan |
282
360
 
283
361
  ## 7. Bila konfigurasi salah
284
362
 
285
- `createOidcClient`, `createServiceClient`, `createSessionStore`, dan `createWebhookVerifier` memeriksa semua opsi saat dipanggil. Bila ada yang salah, semuanya melempar satu `ConfigError` yang memuat **semua** masalah sekaligus. Pesannya hanya menyebut nama opsi, tidak pernah nilainya, jadi aman ditulis ke log.
363
+ `createOidcClient`, `createServiceClient`, `createSessionStore`, `createWebhookVerifier`, dan `createAccessTokenVerifier` memeriksa semua opsi saat dipanggil. Bila ada yang salah, semuanya melempar satu `ConfigError` yang memuat **semua** masalah sekaligus. Pesannya hanya menyebut nama opsi, tidak pernah nilainya, jadi aman ditulis ke log.
286
364
 
287
365
  Contoh pesan:
288
366
 
@@ -324,16 +402,18 @@ export function createOrExit<T>(create: () => T): T {
324
402
  ```
325
403
  <!-- /snippet -->
326
404
 
327
- Pemakaiannya: `const plasgos = createOrExit(createPlasgosClient);` (`createPlasgosClient` ada di [`server-ke-server.md` §2](server-ke-server.md#2-membuat-client)). Untuk webhook: `const verifier = createOrExit(createPaymentsWebhookVerifier);` ([`webhook.md` §4](webhook.md#4-membuat-verifier)).
405
+ Pemakaiannya: `const plasgos = createOrExit(createPlasgosClient);` (`createPlasgosClient` ada di [`server-ke-server.md` §2](server-ke-server.md#2-membuat-client)). Untuk webhook: `const verifier = createOrExit(createPaymentsWebhookVerifier);` ([`webhook.md` §4](webhook.md#4-membuat-verifier)). Untuk verifikasi token: `const verifier = createOrExit(() => createApiTokenVerifier(redis));` ([`verifikasi-token.md` §4](verifikasi-token.md#4-membuat-verifier)).
328
406
 
329
- `ConfigError` juga diekspor oleh `@plasgos/oidc-client` (dan `/session`, `/service`) dan oleh `@plasgos/auth-verify/webhook`, semuanya kelas yang sama, jadi `error instanceof ConfigError` bekerja bila kelasnya di-import dari sana. Contoh di atas memeriksa `error.name` supaya juga bekerja di aplikasi yang mencampur `import` dan `require` ([`error.md` §3](error.md#3-instanceof-dan-dua-loader)).
407
+ `ConfigError` juga diekspor oleh `@plasgos/oidc-client` (dan `/session`, `/service`) dan oleh `@plasgos/auth-verify` (dan `/webhook`, `/express`, `/nestjs`), semuanya kelas yang sama, jadi `error instanceof ConfigError` bekerja bila kelasnya di-import dari sana. Contoh di atas memeriksa `error.name` supaya juga bekerja di aplikasi yang mencampur `import` dan `require` ([`error.md` §3](error.md#3-instanceof-dan-dua-loader)).
330
408
 
331
409
  Daftar lengkap pesan `ConfigError` dan cara memperbaikinya ada di [`error.md`](error.md).
332
410
 
333
411
  ## 8. Langkah berikutnya
334
412
 
335
413
  - Login user di aplikasi web: [`login-web.md`](login-web.md)
414
+ - BFF Node/Express untuk SPA atau PWA (lock Redis, proxy, pencabutan sesi): [`bff-express.md`](bff-express.md)
336
415
  - Memanggil API Plasgos dari server: [`server-ke-server.md`](server-ke-server.md)
337
416
  - Menerima webhook dari Plasgos: [`webhook.md`](webhook.md)
417
+ - Memeriksa access token Plasgos di API sendiri: [`verifikasi-token.md`](verifikasi-token.md)
338
418
  - Arti setiap kegagalan: [`error.md`](error.md)
339
419
  - Contoh lengkap: [`contoh-hitungcuan.md`](contoh-hitungcuan.md), [`contoh-plaslink.md`](contoh-plaslink.md)