@plasgos/oidc-client 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.
package/docs/webhook.md CHANGED
@@ -6,14 +6,15 @@ Sebelum mulai, baca [`memulai.md`](memulai.md) untuk env dan cara mendapat secre
6
6
 
7
7
  ## 1. Apa itu webhook Plasgos
8
8
 
9
- Plasgos memberi tahu aplikasi Anda tentang sebuah kejadian dengan `POST` JSON ke URL webhook yang Anda daftarkan. Ada dua jenis:
9
+ Plasgos memberi tahu aplikasi Anda tentang sebuah kejadian dengan `POST` JSON ke URL webhook yang Anda daftarkan. Ada dua jenis: webhook aplikasi dan webhook pengiriman Plaslink. Webhook aplikasi punya dua preset dengan header dan tanda tangan yang sama:
10
10
 
11
11
  | Jenis | Untuk | Contoh `type` | Preset |
12
12
  |---|---|---|---|
13
13
  | Payments | Aplikasi yang membuat payment lewat Plasgos | `payment.paid`, `payment.expired` | `presets.payments` |
14
+ | Event aplikasi | Endpoint aplikasi yang menerima event pembayaran, langganan, paket, dan user ([§6](#satu-endpoint-untuk-semua-event-aplikasi)) | `payment.paid`, `subscription.activated`, `user.session_revoked` | `presets.appEvents` |
14
15
  | Pengiriman Plaslink | Plaslink, untuk pengiriman seller | event pengiriman | `presets.plaslinkShipping` |
15
16
 
16
- Setiap jenis punya secret sendiri. Aplikasi yang menerima keduanya (Plaslink) memakai dua secret dan dua verifier.
17
+ Webhook aplikasi dan webhook pengiriman Plaslink masing-masing punya secret sendiri. Aplikasi yang menerima keduanya (Plaslink) memakai dua secret dan dua verifier.
17
18
 
18
19
  Hal yang selalu berlaku:
19
20
 
@@ -54,7 +55,7 @@ Akibatnya:
54
55
 
55
56
  Setiap kiriman membawa empat header. Nama header-nya berbeda per jenis:
56
57
 
57
- | Isi | `presets.payments` | `presets.plaslinkShipping` |
58
+ | Isi | `presets.payments` dan `presets.appEvents` | `presets.plaslinkShipping` |
58
59
  |---|---|---|
59
60
  | Id event | `X-Event-Id` | `X-Plasgos-Event-Id` |
60
61
  | Type event | `X-Event-Type` | `X-Plasgos-Event-Type` |
@@ -113,7 +114,8 @@ export function createShippingWebhookVerifier(): WebhookVerifier {
113
114
  ```ts
114
115
  /**
115
116
  * A webhook secret: one secret, or "new,old" while a rotation is in progress. Names used in the guides:
116
- * PLASGOS_WEBHOOK_SECRET (payments) and PLASGOS_SHIPPING_WEBHOOK_SECRET (Plaslink shipping).
117
+ * PLASGOS_WEBHOOK_SECRET (the app webhook endpoint: payments and every other app event, one secret)
118
+ * and PLASGOS_SHIPPING_WEBHOOK_SECRET (Plaslink shipping).
117
119
  */
118
120
  export function readWebhookSecrets(name: string): string[] {
119
121
  const secrets = required(name)
@@ -138,7 +140,7 @@ Potongan kode di panduan ini berasal dari file yang lolos typecheck, lengkap den
138
140
  |---|---|---|---|
139
141
  | `environment` | Ya | — | `"sandbox"` atau `"production"`. Ikut tercatat di setiap hasil. `"production"` menolak `toleranceSeconds` di atas 300 |
140
142
  | `secrets` | Ya | — | Satu atau dua secret webhook, masing-masing minimal 32 byte. `undefined` dan nilai kosong dibuang lebih dulu, nilai yang sama dipakai sekali. Saat rotasi: `[baru, lama]`, urutannya bebas ([§8](#8-rotasi-secret)) |
141
- | `preset` | Ya | — | `presets.payments`, `presets.plaslinkShipping`, atau preset sendiri dengan bentuk yang sama |
143
+ | `preset` | Ya | — | `presets.payments`, `presets.appEvents`, `presets.plaslinkShipping`, atau preset sendiri dengan bentuk yang sama |
142
144
  | `toleranceSeconds` | Tidak | `300` | Selisih terbesar antara waktu kirim dan jam server, dalam detik. Bilangan bulat 1–900, paling besar 300 di production |
143
145
  | `maxBodyBytes` | Tidak | `1048576` | Body mentah terbesar yang diterima, dalam byte. Bilangan bulat 1024–16777216 |
144
146
 
@@ -429,7 +431,190 @@ Semua jawaban selain `2xx` diulang Plasgos ([§2](#2-aturan-pengiriman)). Arti s
429
431
  | `timestamp` | Waktu kirim percobaan ini, dalam detik epoch. Untuk event yang dikirim ulang, nilai ini berbeda di setiap percobaan |
430
432
  | `body` | Seluruh body sebagai objek JSON yang dibekukan (tidak bisa diubah) |
431
433
  | `environment` | `environment` milik verifier |
432
- | `preset` | Nama preset yang memverifikasi: `payments` atau `plaslinkShipping` |
434
+ | `preset` | Nama preset yang memverifikasi: `payments`, `appEvents`, atau `plaslinkShipping` |
435
+
436
+ ### Satu endpoint untuk semua event aplikasi
437
+
438
+ Satu endpoint webhook aplikasi dengan satu secret menerima semua event yang Plasgos kirim ke aplikasi Anda: pembayaran (`payment.*`), langganan (`subscription.*`, `entitlements.*`, `addon.*`), paket (`package.*`), dan user (`user.*`).
439
+
440
+ Pilih preset menurut isi endpoint:
441
+
442
+ - `presets.appEvents` untuk endpoint yang menerima lebih dari event payments. Hasil verifikasinya membawa `preset: "appEvents"`, jadi log aplikasi tidak menyebut "payments" untuk event user atau langganan.
443
+ - `presets.payments` tetap sah untuk aplikasi yang sudah memakainya. Header, tanda tangan, dan pemeriksaannya sama persis; kiriman yang lolos dengan satu preset juga lolos dengan yang lain.
444
+
445
+ <!-- snippet: examples/snippets/webhook-verifier.ts#create-app-events -->
446
+ ```ts
447
+ /**
448
+ * Every event Plasgos sends to the app's webhook endpoint (payments, subscriptions, add-ons, packages,
449
+ * users), with one secret. Same headers and signature as presets.payments; the result's preset reads "appEvents".
450
+ */
451
+ export function createAppEventsWebhookVerifier(): WebhookVerifier {
452
+ return createWebhookVerifier({
453
+ environment: readEnvironment(),
454
+ secrets: readWebhookSecrets("PLASGOS_WEBHOOK_SECRET"),
455
+ preset: presets.appEvents,
456
+ });
457
+ }
458
+ ```
459
+ <!-- /snippet -->
460
+
461
+ Aturan yang lain tidak berubah: dedup tetap dengan `event.id` ([§7](#7-dedup-di-transaksi-yang-sama)), dan `sequence` tetap naik per subjek event (payment, langganan, user, dan seterusnya).
462
+
463
+ Setelah `saveOnce(tx, event)` menyimpan event baru, teruskan event ke handler milik aplikasi menurut awalan `type`. Type yang belum dikenal aplikasi dijawab `2xx` tanpa efek: id-nya tetap tersimpan dan transaksinya di-commit. Dengan begitu type event baru dari Plasgos tidak pernah menahan antrean.
464
+
465
+ <!-- snippet: examples/snippets/webhook-verifier.ts#route-by-type -->
466
+ ```ts
467
+ /** The app's own effect for each event family. Each one runs in the transaction of saveOnce. */
468
+ export interface AppEventHandlers {
469
+ /** payment.* */
470
+ payment: ApplyEvent;
471
+ /** subscription.*, entitlements.* and addon.* */
472
+ subscription: ApplyEvent;
473
+ /** package.* */
474
+ package: ApplyEvent;
475
+ /** user.* */
476
+ user: ApplyEvent;
477
+ }
478
+
479
+ /**
480
+ * The `apply` of handleWebhook for an appEvents endpoint: it runs after saveOnce(tx, event) stored a new
481
+ * event and hands the event to the handler of its family. A type the app does not know has no effect:
482
+ * handleWebhook commits the event id and answers 2xx, so a new event type never blocks the queue.
483
+ */
484
+ export function routeByType(handlers: AppEventHandlers): ApplyEvent {
485
+ return async (tx, event) => {
486
+ const family = event.type.split(".", 1)[0];
487
+ switch (family) {
488
+ case "payment":
489
+ return handlers.payment(tx, event);
490
+ case "subscription":
491
+ case "entitlements":
492
+ case "addon":
493
+ return handlers.subscription(tx, event);
494
+ case "package":
495
+ return handlers.package(tx, event);
496
+ case "user":
497
+ return handlers.user(tx, event);
498
+ default:
499
+ // Unknown type: no effect. The id is still stored, so a redelivery is not processed either.
500
+ return;
501
+ }
502
+ };
503
+ }
504
+ ```
505
+ <!-- /snippet -->
506
+
507
+ Pakai sebagai `apply` di `handleWebhook`: `handleWebhook(verifier, withTransaction, routeByType(handlers), input)`.
508
+
509
+ **Event `user.*`.** Isi `data` ketiga event user (`user.credentials_revoked`, `user.session_revoked`, `user.status_changed`) adalah kontrak event aplikasi; tabelnya, dan aturan marker pencabutan yang diisi dari event itu, ada di [`verifikasi-token.md` §8](verifikasi-token.md#8-pencabutan-sesi-isrevoked). Handler `user` untuk `routeByType`, dengan client Redis milik aplikasi: `userEventHandler(redis)`.
510
+
511
+ <!-- snippet: examples/snippets/user-events.ts#user-events -->
512
+ ```ts
513
+ /** The Redis commands the marker writer uses. An ioredis client fits it. */
514
+ export interface MarkerRedis {
515
+ eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
516
+ set(key: string, value: string, mode: "EX", seconds: number): Promise<unknown>;
517
+ set(key: string, value: string): Promise<unknown>;
518
+ del(key: string): Promise<number>;
519
+ }
520
+
521
+ /**
522
+ * The credential-version and session markers live 1 hour: much longer than a Plasgos access token, so
523
+ * every token issued before the event has expired before its marker does.
524
+ */
525
+ export const MARKER_TTL_SECONDS = 3_600;
526
+
527
+ /**
528
+ * Stores the larger of the stored and the new credential version (compare-and-set in one Redis step).
529
+ * Events of one user can arrive out of order; a plain SET could lower the version and let a revoked
530
+ * token through again.
531
+ */
532
+ const RAISE_TO_MAX = `
533
+ local current = tonumber(redis.call("GET", KEYS[1]))
534
+ if current == nil or tonumber(ARGV[1]) > current then
535
+ redis.call("SET", KEYS[1], ARGV[1], "EX", tonumber(ARGV[2]))
536
+ end
537
+ return 0`;
538
+
539
+ /** The user.* event data, the published contract of the app events (`data` of the event body). */
540
+ interface UserEventData {
541
+ /** The user's public id (`usr-…`), the same value as the token's plasgos_public_id. */
542
+ user: string;
543
+ /** user.credentials_revoked: the user's new credential version (the token claim `cv`). */
544
+ credential_version?: number;
545
+ /** user.session_revoked: the revoked Plasgos session, the same value as the token claim `sid`. */
546
+ sid?: string;
547
+ /** user.status_changed: active, pending, suspended, banned or unlinked. */
548
+ status?: string;
549
+ }
550
+
551
+ const isText = (value: unknown): value is string => typeof value === "string" && value !== "" && value.length <= 128;
552
+
553
+ /** The event's `data`, checked. A malformed one throws: the delivery fails (500) and Plasgos sends it again. */
554
+ function userDataOf(event: VerifiedWebhook): UserEventData {
555
+ const data = event.body["data"];
556
+ if (typeof data !== "object" || data === null) throw new Error(`user event ${event.id}: data is not an object`);
557
+ const fields = data as Record<string, unknown>;
558
+ const user = fields["user"];
559
+ if (!isText(user)) throw new Error(`user event ${event.id}: data.user is missing`);
560
+ const version = fields["credential_version"];
561
+ const sid = fields["sid"];
562
+ const status = fields["status"];
563
+ return {
564
+ user,
565
+ ...(typeof version === "number" && Number.isSafeInteger(version) ? { credential_version: version } : {}),
566
+ ...(isText(sid) ? { sid } : {}),
567
+ ...(isText(status) ? { status } : {}),
568
+ };
569
+ }
570
+
571
+ /**
572
+ * The `user` handler of routeByType (webhook.md §6): writes the revocation markers that isRevoked reads.
573
+ * - user.credentials_revoked → the credential version, stored as the maximum, TTL 1 hour;
574
+ * - user.session_revoked → the session marker, TTL 1 hour;
575
+ * - user.status_changed → the status is persisted in the app's database (same transaction as the
576
+ * event id) and cached in Redis: any status other than "active" sets the blocked marker, "active"
577
+ * removes it. Refill the blocked markers from the database if your Redis can lose its data.
578
+ * A user.* type the app does not know has no effect.
579
+ */
580
+ export function userEventHandler(redis: MarkerRedis): ApplyEvent {
581
+ return async (tx: Tx, event: VerifiedWebhook) => {
582
+ const data = userDataOf(event);
583
+ switch (event.type) {
584
+ case "user.credentials_revoked": {
585
+ if (data.credential_version === undefined) throw new Error(`user event ${event.id}: data.credential_version is missing`);
586
+ const key = revocationKeys.credentialVersion(data.user);
587
+ await redis.eval(RAISE_TO_MAX, 1, key, data.credential_version, MARKER_TTL_SECONDS);
588
+ return;
589
+ }
590
+ case "user.session_revoked": {
591
+ if (data.sid === undefined) throw new Error(`user event ${event.id}: data.sid is missing`);
592
+ await redis.set(revocationKeys.session(data.sid), "1", "EX", MARKER_TTL_SECONDS);
593
+ return;
594
+ }
595
+ case "user.status_changed": {
596
+ if (data.status === undefined) throw new Error(`user event ${event.id}: data.status is missing`);
597
+ // The lasting record. sequence keeps an older event from overwriting a newer status.
598
+ const sequence = typeof event.body["sequence"] === "number" ? event.body["sequence"] : 0;
599
+ const stored = await tx.query(
600
+ `INSERT INTO plasgos_user_status (public_id, status, sequence) VALUES ($1, $2, $3)
601
+ ON CONFLICT (public_id) DO UPDATE SET status = EXCLUDED.status, sequence = EXCLUDED.sequence
602
+ WHERE plasgos_user_status.sequence < EXCLUDED.sequence`,
603
+ [data.user, data.status, sequence],
604
+ );
605
+ if (stored.rowCount !== 1) return;
606
+ // The cache isRevoked reads, without an expiry: it holds as long as the user is blocked.
607
+ if (data.status === "active") await redis.del(revocationKeys.blockedUser(data.user));
608
+ else await redis.set(revocationKeys.blockedUser(data.user), data.status);
609
+ return;
610
+ }
611
+ default:
612
+ return;
613
+ }
614
+ };
615
+ }
616
+ ```
617
+ <!-- /snippet -->
433
618
 
434
619
  ## 7. Dedup di transaksi yang sama
435
620
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plasgos/oidc-client",
3
- "version": "0.1.0-next.2",
3
+ "version": "0.1.0-next.3",
4
4
  "description": "Plasgos OIDC client for Node servers: user login (code + PKCE), sealed session cookies and client_credentials.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -62,7 +62,7 @@
62
62
  "main": "./dist/index.cjs",
63
63
  "types": "./dist/index.d.cts",
64
64
  "dependencies": {
65
- "@plasgos/auth-shared": "0.1.0-next.2"
65
+ "@plasgos/auth-shared": "0.1.0-next.3"
66
66
  },
67
67
  "scripts": {
68
68
  "build": "tsup"