@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.
Files changed (69) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +15 -0
  3. package/README.md +122 -2
  4. package/THIRD_PARTY_NOTICES.md +31 -0
  5. package/dist/express.cjs +157 -0
  6. package/dist/express.cjs.map +1 -0
  7. package/dist/express.d.cts +90 -0
  8. package/dist/express.d.ts +90 -0
  9. package/dist/express.js +127 -0
  10. package/dist/express.js.map +1 -0
  11. package/dist/index.cjs +1254 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +67 -0
  14. package/dist/index.d.ts +67 -0
  15. package/dist/index.js +499 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/nestjs.cjs +1395 -0
  18. package/dist/nestjs.cjs.map +1 -0
  19. package/dist/nestjs.d.cts +153 -0
  20. package/dist/nestjs.d.ts +153 -0
  21. package/dist/nestjs.js +637 -0
  22. package/dist/nestjs.js.map +1 -0
  23. package/dist/types-CGtRnj59.d.cts +193 -0
  24. package/dist/types-CGtRnj59.d.ts +193 -0
  25. package/dist/webhook.cjs +296 -0
  26. package/dist/webhook.cjs.map +1 -0
  27. package/dist/webhook.d.cts +196 -0
  28. package/dist/webhook.d.ts +196 -0
  29. package/dist/webhook.js +265 -0
  30. package/dist/webhook.js.map +1 -0
  31. package/docs/bff-express.md +1314 -0
  32. package/docs/consumers.md +98 -0
  33. package/docs/contoh-hitungcuan.md +255 -0
  34. package/docs/contoh-plaslink.md +244 -0
  35. package/docs/error.md +613 -0
  36. package/docs/examples/auth-verify-readme.ts +42 -0
  37. package/docs/examples/bff-express.ts +370 -0
  38. package/docs/examples/bff-proxy.ts +335 -0
  39. package/docs/examples/bff-redis-lock.ts +187 -0
  40. package/docs/examples/bff-revocation.ts +136 -0
  41. package/docs/examples/config-error.ts +24 -0
  42. package/docs/examples/env.ts +150 -0
  43. package/docs/examples/failure-log.ts +18 -0
  44. package/docs/examples/login-client.ts +46 -0
  45. package/docs/examples/login-flow.ts +186 -0
  46. package/docs/examples/plaslink-connect.ts +48 -0
  47. package/docs/examples/readme.ts +60 -0
  48. package/docs/examples/service-client.ts +105 -0
  49. package/docs/examples/session-store.ts +53 -0
  50. package/docs/examples/token-commonjs.cjs +95 -0
  51. package/docs/examples/token-express.ts +56 -0
  52. package/docs/examples/token-fetch.ts +24 -0
  53. package/docs/examples/token-nestjs-jest.ts +77 -0
  54. package/docs/examples/token-nestjs.ts +127 -0
  55. package/docs/examples/token-socket.ts +59 -0
  56. package/docs/examples/token-testing.ts +100 -0
  57. package/docs/examples/token-verifier.ts +132 -0
  58. package/docs/examples/user-events.ts +110 -0
  59. package/docs/examples/webhook-express.ts +46 -0
  60. package/docs/examples/webhook-fetch.ts +60 -0
  61. package/docs/examples/webhook-nestjs.ts +59 -0
  62. package/docs/examples/webhook-testing.ts +60 -0
  63. package/docs/examples/webhook-verifier.ts +197 -0
  64. package/docs/login-web.md +650 -0
  65. package/docs/memulai.md +419 -0
  66. package/docs/server-ke-server.md +287 -0
  67. package/docs/verifikasi-token.md +1219 -0
  68. package/docs/webhook.md +810 -0
  69. package/package.json +101 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,27 @@
1
+ # @plasgos/auth-verify
2
+
3
+ ## 0.1.0-next.3
4
+
5
+ ### Minor Changes
6
+
7
+ - da4ecca: Verifikasi access token Plasgos di API milik aplikasi: `createAccessTokenVerifier` (JWKS, RS256, `at+jwt`, `iss` dan `aud` persis, scope, klaim wajib lewat `requireClaims`, `maxAuthAge`, hook `isRevoked`; JWKS yang tidak bisa dibaca dijawab `503`), `@plasgos/auth-verify/express` (`requirePlasgosToken`), dan `@plasgos/auth-verify/nestjs` (`PlasgosAuthModule`, `PlasgosAccessTokenGuard`, `@RequireScopes`, `@RequireRecentAuth`, `@PlasgosPrincipal`; NestJS 11). Ketiganya menjawab penolakan dengan status, `Cache-Control: no-store`, `WWW-Authenticate` bila ada, dan body `{"error":"<errorCode>"}`; middleware Express meneruskan penolakan ke `next(error)` bila respons sudah terkirim atau tidak bisa ditulis, dan error lain yang hanya meminjam nama `AuthVerifyError` diperlakukan sebagai error biasa. Token untuk audience `crm` wajib membawa `cv`. Build CommonJS memuat `jose` di dalamnya, sehingga bisa dipakai aplikasi CommonJS dan Jest tanpa pengaturan tambahan. `AuthVerifyError` ada di `@plasgos/auth-shared`. Panduan baru `docs/verifikasi-token.md` dan `docs/bff-express.md`; `error.md`, `memulai.md`, dan `login-web.md` diperbarui (ikut terbit di kedua paket).
8
+ - e7f5278: `presets.appEvents` di `@plasgos/auth-verify/webhook`: preset untuk endpoint webhook aplikasi yang menerima event pembayaran, langganan, paket, dan user dengan satu secret. Header dan cara verifikasinya sama dengan `presets.payments`; hanya nama preset di hasil verifikasi yang berbeda. Panduan `docs/webhook.md` diperbarui (ikut terbit di kedua paket).
9
+
10
+ ### Patch Changes
11
+
12
+ - Updated dependencies [da4ecca]
13
+ - Updated dependencies [ecc836b]
14
+ - Updated dependencies [cebfd60]
15
+ - @plasgos/auth-shared@0.1.0-next.3
16
+
17
+ ## 0.1.0-next.2
18
+
19
+ ### Minor Changes
20
+
21
+ - 08750ea: Rilis awal `@plasgos/auth-verify` dengan `@plasgos/auth-verify/webhook`: `createWebhookVerifier` dan `verifyWebhook` untuk webhook payments (`presets.payments`) dan pengiriman Plaslink (`presets.plaslinkShipping`), rotasi secret, batas waktu 300 detik, dan batas ukuran. `WebhookVerifyError` ada di `@plasgos/auth-shared`. Panduan baru `docs/webhook.md`; `contoh-hitungcuan.md`, `contoh-plaslink.md`, `error.md`, dan `memulai.md` diperbarui, dan panduan yang terbit di `@plasgos/oidc-client` ikut berubah. Panduan kini juga ikut di paket `@plasgos/auth-verify`. `LICENSE` di ketiga paket kini menyebut setiap paket (`@plasgos/oidc-client`, `@plasgos/auth-verify`, dan `@plasgos/auth-shared`) dan webhook Plasgos. Pesan `ConfigError` `logoutTicket requires backchannelUrl` di `@plasgos/oidc-client` kini menyebut alamat internal server Plasgos (`the internal Plasgos server URL`).
22
+
23
+ ### Patch Changes
24
+
25
+ - Updated dependencies [08750ea]
26
+ - Updated dependencies [1bbdbc4]
27
+ - @plasgos/auth-shared@0.1.0-next.2
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ Hak Cipta (c) 2026 Plasgos. Seluruh hak dilindungi.
2
+
3
+ Perangkat lunak ini (paket npm @plasgos/oidc-client, @plasgos/auth-verify, dan @plasgos/auth-shared beserta
4
+ dokumentasinya) adalah milik Plasgos dan disediakan HANYA untuk menghubungkan aplikasi ke layanan Plasgos
5
+ (login Plasgos, API Plasgos, dan webhook Plasgos) oleh pihak yang memiliki kredensial client resmi dari
6
+ Plasgos, sesuai ketentuan layanan Plasgos.
7
+
8
+ Pemegang kredensial tersebut dan pengembang yang bekerja untuk mereka boleh memasang dan memanggil perangkat
9
+ lunak ini di aplikasi mereka untuk keperluan itu. Selain itu, tanpa izin tertulis Plasgos, dilarang menyalin,
10
+ mengubah, menggabungkan, menerbitkan ulang, mendistribusikan, mensublisensikan, menjual, atau membuat karya
11
+ turunan dari perangkat lunak ini, seluruhnya maupun sebagian.
12
+
13
+ PERANGKAT LUNAK INI DISEDIAKAN "SEBAGAIMANA ADANYA", TANPA JAMINAN APA PUN. DALAM KEADAAN APA PUN PLASGOS
14
+ TIDAK BERTANGGUNG JAWAB ATAS KLAIM, KERUSAKAN, ATAU KEWAJIBAN LAIN YANG TIMBUL DARI ATAU BERKAITAN DENGAN
15
+ PERANGKAT LUNAK INI ATAU PEMAKAIANNYA, KECUALI DIATUR LAIN DALAM PERJANJIAN LAYANAN.
package/README.md CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # @plasgos/auth-verify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Verifikasi untuk server Node. Paket ini untuk aplikasi yang **menerima** sesuatu dari Plasgos dan harus memastikan keasliannya:
4
+
5
+ - webhook bertanda tangan dari Plasgos: payments, event aplikasi (pembayaran, langganan, paket, user), dan pengiriman Plaslink;
6
+ - access token JWT Plasgos di API milik aplikasi: verifier, middleware Express, dan modul serta guard NestJS 11.
7
+
8
+ Hanya untuk server (Node `>=22.22`), tersedia sebagai ESM dan CommonJS; build CommonJS bisa di-`require` tanpa flag dan bekerja di Jest. Dependensi runtime: `@plasgos/auth-shared` (versi yang sama) dan `jose`. Build CommonJS membawa salinan `jose` sendiri (lisensinya di `THIRD_PARTY_NOTICES.md`), jadi perbaikan keamanan `jose` datang lewat upgrade paket ini, bukan lewat `overrides` di aplikasi. `@nestjs/common` dan `@nestjs/core` 11 adalah peer dependency opsional, hanya untuk `/nestjs`.
9
+
10
+ **Link `@next`.** Link panduan di README ini (alamat `cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/…`) membuka pre-release yang ditunjuk tag `next` di npm, yang bisa lebih baru atau lebih lama dari versi yang Anda pasang. Untuk versi yang terpasang, baca `node_modules/@plasgos/auth-verify/docs/`.
11
+
12
+ ## Install
13
+
14
+ Paket ini ada di npmjs.com dan di-install tanpa token. Pakai nomor versi persis, karena versi yang terbit masih pre-release:
15
+
16
+ ```bash
17
+ pnpm add @plasgos/auth-verify@<versi> --save-exact
18
+ ```
19
+
20
+ Aplikasi yang juga memakai `@plasgos/oidc-client` memasang versi yang sama untuk keduanya. Aturan versi, Docker, dan CI ada di [`docs/consumers.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/consumers.md).
21
+
22
+ ## Lisensi
23
+
24
+ Bukan open source. Paket ini milik Plasgos dan hanya boleh dipakai untuk menghubungkan aplikasi ke layanan Plasgos oleh pemegang kredensial client resmi dari Plasgos. Lihat file `LICENSE` di paket ini.
25
+
26
+ ## Isi paket
27
+
28
+ | Import | Untuk | Panduan |
29
+ |---|---|---|
30
+ | `@plasgos/auth-verify` | Access token Plasgos di API sendiri: `createAccessTokenVerifier`, `authErrorResponse` | [`verifikasi-token.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/verifikasi-token.md) |
31
+ | `@plasgos/auth-verify/express` | Middleware Express 4 dan 5: `requirePlasgosToken`, `principalOf` | [`verifikasi-token.md` §9](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/verifikasi-token.md#9-express) |
32
+ | `@plasgos/auth-verify/nestjs` | NestJS 11: `PlasgosAuthModule`, `PlasgosAccessTokenGuard`, `@RequireScopes`, `@RequireRecentAuth`, `@PlasgosPrincipal` | [`verifikasi-token.md` §10](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/verifikasi-token.md#10-nestjs) |
33
+ | `@plasgos/auth-verify/webhook` | Webhook dari Plasgos: `createWebhookVerifier`, `verifyWebhook`, `presets` | [`webhook.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/webhook.md) |
34
+
35
+ Proyek TypeScript harus memakai `moduleResolution` `node16`, `nodenext`, atau `bundler`.
36
+
37
+ ## Contoh
38
+
39
+ Access token di API Express:
40
+
41
+ <!-- snippet: examples/snippets/auth-verify-readme.ts#token -->
42
+ ```ts
43
+ /** Once, at start: a wrong option throws one ConfigError here. */
44
+ export function createTokenVerifier(isRevoked: (principal: UserAccessPrincipal) => Promise<boolean>): AccessTokenVerifier {
45
+ return createAccessTokenVerifier({
46
+ environment: "production",
47
+ issuer: "https://accounts.plasgos.co.id",
48
+ audience: "https://api.plasgos.co.id/crm",
49
+ requireClaims: ["plasgos_public_id", "cv"],
50
+ isRevoked,
51
+ });
52
+ }
53
+
54
+ /** Per route: 401, 403 or 503 is answered by the middleware; the handler runs only with a valid token. */
55
+ export function mountContacts(app: Express, verifier: AccessTokenVerifier): void {
56
+ app.get("/contacts", requirePlasgosToken(verifier, { scopes: ["crm:access"] }), (req, res) => {
57
+ res.json({ owner: principalOf(req).claims.plasgos_public_id });
58
+ });
59
+ }
60
+ ```
61
+ <!-- /snippet -->
62
+
63
+ Verifier memeriksa header `Authorization`, tanda tangan RS256 dengan kunci publik Plasgos (JWKS, di-cache), `typ` `at+jwt`, `iss` dan `aud` yang persis, `exp`, klaim wajib, `isRevoked`, dan scope route. Token yang ditolak dijawab middleware dengan `401`, `403`, atau `503` beserta `WWW-Authenticate`. User dikenali dari `claims.plasgos_public_id`. Pencabutan sesi, NestJS, server berbasis `Request`, dan test ada di [`verifikasi-token.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/verifikasi-token.md).
64
+
65
+ Webhook:
66
+
67
+ <!-- snippet: examples/snippets/auth-verify-readme.ts#webhook -->
68
+ ```ts
69
+ /** Once, at start: a wrong option throws one ConfigError here. */
70
+ export function createVerifier(): WebhookVerifier {
71
+ return createWebhookVerifier({
72
+ environment: "production",
73
+ secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
74
+ preset: presets.payments,
75
+ });
76
+ }
77
+
78
+ /** Per delivery: the headers and the raw body, before JSON parsing. Throws WebhookVerifyError. */
79
+ export function receive(verifier: WebhookVerifier, request: Request, rawBody: Uint8Array): VerifiedWebhook {
80
+ return verifier.verify({ headers: request.headers, rawBody });
81
+ }
82
+ ```
83
+ <!-- /snippet -->
84
+
85
+ `verify` memeriksa empat header, ukuran body, waktu kirim (bawaan 300 detik), dan tanda tangan HMAC-SHA256 atas body mentah. `id` dan `type` hasil verifikasi diambil dari body yang ditandatangani. Saat rotasi secret, `secrets` berisi dua nilai, `[baru, lama]`. Body mentah per framework (Express, NestJS, `Request`), dedup di transaksi database, dan rotasi ada di [`webhook.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/webhook.md).
86
+
87
+ ## Daftar export
88
+
89
+ | Import | Fungsi dan nilai | Type |
90
+ |---|---|---|
91
+ | `@plasgos/auth-verify` | `createAccessTokenVerifier`, `authErrorResponse`, `AuthVerifyError`, `AUTH_VERIFY_REASONS`, `ConfigError` | `AccessTokenVerifier`, `AccessTokenVerifierOptions`, `VerifyOptions`, `AccessPrincipal`, `UserAccessPrincipal`, `ServiceAccessPrincipal`, `VerifiedAccessTokenClaims`, `AuthRejectEvent`, `JsonWebKeySet`, `JwksFetch`, `AuthVerifyReason`, `AccessTokenClaims`, `Environment` |
92
+ | `@plasgos/auth-verify/express` | `requirePlasgosToken`, `principalOf`, `AuthVerifyError`, `ConfigError` | `PlasgosRequirements`, `PlasgosRequestLike`, `PlasgosResponseLike`, `AccessTokenVerifier`, `AccessPrincipal`, `UserAccessPrincipal`, `ServiceAccessPrincipal`, `VerifiedAccessTokenClaims`, `AuthVerifyReason` |
93
+ | `@plasgos/auth-verify/nestjs` | `PlasgosAuthModule`, `PlasgosAccessTokenGuard`, `RequireScopes`, `RequireRecentAuth`, `PlasgosPrincipal`, `PLASGOS_ACCESS_TOKEN_VERIFIER`, `AuthVerifyError`, `ConfigError` | `PlasgosAuthModuleAsyncOptions`, `AccessTokenVerifier`, `AccessTokenVerifierOptions`, `AccessPrincipal`, `UserAccessPrincipal`, `ServiceAccessPrincipal`, `VerifiedAccessTokenClaims`, `AuthVerifyReason` |
94
+ | `@plasgos/auth-verify/webhook` | `createWebhookVerifier`, `verifyWebhook`, `presets` (`presets.payments`, `presets.appEvents`, `presets.plaslinkShipping`), `WebhookVerifyError`, `ConfigError` | `WebhookVerifier`, `WebhookVerifierOptions`, `WebhookVerifyInput`, `VerifiedWebhook`, `WebhookDedupStore`, `WebhookPreset`, `WebhookHeaders`, `WebhookVerifyReason`, `WebhookHeaderRole`, `Environment` |
95
+
96
+ Setiap export punya JSDoc dengan contoh.
97
+
98
+ ## Kegagalan
99
+
100
+ - Opsi yang salah: `ConfigError` saat `createAccessTokenVerifier` atau `createWebhookVerifier` dipanggil, memuat semua masalah sekaligus. Kelasnya sama dengan `ConfigError` dari `@plasgos/oidc-client`.
101
+ - Token yang ditolak: `AuthVerifyError` dengan `reason` (misalnya `expired_token`, `insufficient_scope`, `unavailable`) dan jawaban HTTP-nya (`status`, `errorCode`, `wwwAuthenticate`). Middleware Express dan guard NestJS menjawabnya sendiri.
102
+ - Kiriman webhook yang ditolak: `WebhookVerifyError` dengan `reason` (misalnya `signature_mismatch`, `stale_timestamp`) dan `header`.
103
+ - Argumen yang salah, misalnya body yang sudah di-parse atau persyaratan route yang tidak sah: `TypeError`.
104
+ - Paket tidak pernah menulis log. Token yang ditolak dilaporkan lewat hook `onReject`. Pesan error tidak pernah memuat token, klaim, secret, tanda tangan, nilai header, atau isi body.
105
+
106
+ Arti setiap `reason`, penyebab umum, dan jawaban HTTP yang disarankan ada di [`error.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/error.md).
107
+
108
+ ## Panduan
109
+
110
+ Panduan pemakaian (Bahasa Indonesia) ikut di paket ini, di folder `docs/`. Link di bawah membuka pre-release yang ditunjuk tag `next` secara online (jsDelivr). Untuk versi yang Anda pasang, bacanya di `node_modules/@plasgos/auth-verify/docs/`, atau di tab **Code** halaman paket di npmjs.com.
111
+
112
+ | Panduan | Untuk apa |
113
+ |---|---|
114
+ | [`memulai.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/memulai.md) | Mulai dari sini: paket mana untuk kebutuhan apa, env, sandbox dan production, cara mendapat kredensial dan secret webhook |
115
+ | [`verifikasi-token.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/verifikasi-token.md) | Memeriksa access token di API sendiri: verifier, Express, NestJS, pencabutan sesi, test |
116
+ | [`bff-express.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/bff-express.md) | BFF Node/Express di depan API Anda (dengan `@plasgos/oidc-client`): sesi, lock refresh Redis, pencabutan sesi, proxy |
117
+ | [`webhook.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/webhook.md) | Menerima webhook: verifier, body mentah per framework, dedup, rotasi secret, test |
118
+ | [`error.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/error.md) | Semua error dan `reason`: arti, penyebab umum, penanganan |
119
+ | [`contoh-hitungcuan.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/contoh-hitungcuan.md) | Contoh lengkap payments dan webhook payments |
120
+ | [`contoh-plaslink.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/contoh-plaslink.md) | Contoh lengkap login seller, payments, dan dua jenis webhook |
121
+ | [`consumers.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/consumers.md) | Install, Docker, CI, aturan versi, lisensi |
122
+
123
+ File contoh yang dikutip panduan ada di [`docs/examples/`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/examples/). Semuanya lolos typecheck terhadap versi paket ini.
@@ -0,0 +1,31 @@
1
+ # Third-party notices
2
+
3
+ The CommonJS files of this package (`dist/*.cjs`) contain a copy of the following package. The ESM files import it from `node_modules` instead.
4
+
5
+ ## jose 6.2.15
6
+
7
+ https://github.com/panva/jose
8
+
9
+ ```text
10
+ The MIT License (MIT)
11
+
12
+ Copyright (c) 2018 Filip Skokan
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ ```
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/express/index.ts
21
+ var express_exports = {};
22
+ __export(express_exports, {
23
+ AuthVerifyError: () => import_auth_shared4.AuthVerifyError,
24
+ ConfigError: () => import_auth_shared4.ConfigError,
25
+ principalOf: () => principalOf,
26
+ requirePlasgosToken: () => requirePlasgosToken
27
+ });
28
+ module.exports = __toCommonJS(express_exports);
29
+
30
+ // src/express/middleware.ts
31
+ var import_auth_shared3 = require("@plasgos/auth-shared");
32
+
33
+ // src/core/response.ts
34
+ var import_auth_shared = require("@plasgos/auth-shared");
35
+
36
+ // src/config.ts
37
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
38
+
39
+ // src/core/response.ts
40
+ var STATUSES = [401, 403, 503];
41
+ var ERROR_CODES = [
42
+ "invalid_token",
43
+ "insufficient_scope",
44
+ "insufficient_user_authentication",
45
+ "temporarily_unavailable"
46
+ ];
47
+ var REASONS = import_auth_shared.AUTH_VERIFY_REASONS;
48
+ function authRefusalOf(error) {
49
+ const fields = isObject(error) || error instanceof Error ? error : null;
50
+ if (fields === null) return null;
51
+ const challenge = fields["wwwAuthenticate"];
52
+ if (!REASONS.includes(fields["reason"]) || !STATUSES.includes(fields["status"]) || !ERROR_CODES.includes(fields["errorCode"]) || challenge !== null && typeof challenge !== "string") {
53
+ return null;
54
+ }
55
+ return {
56
+ status: fields["status"],
57
+ errorCode: fields["errorCode"],
58
+ wwwAuthenticate: challenge
59
+ };
60
+ }
61
+
62
+ // src/core/config.ts
63
+ var import_auth_shared2 = require("@plasgos/auth-shared");
64
+ var MAX_REQUIRED_CLAIMS = 16;
65
+ var CLAIM_NAME = /^[A-Za-z0-9_]{1,64}$/;
66
+ var PROBLEM = {
67
+ https: 'backchannelUrl must use https: when environment is "production" unless allowInsecureBackchannel is true',
68
+ isRevokedRequired: "isRevoked is required for a crm audience",
69
+ requireClaims: `requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`,
70
+ jwks: "jwks must be a JSON Web Key Set",
71
+ jwksSandboxOnly: 'jwks is only allowed when environment is "sandbox"'
72
+ };
73
+
74
+ // src/core/requirements.ts
75
+ var SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
76
+ function resolveRequirements(label, raw) {
77
+ if (raw === void 0) return { scopes: [], requireClaims: [], maxAuthAge: null };
78
+ if (!isObject(raw)) throw new TypeError(`${label}: options must be an object`);
79
+ const { scopes, requireClaims, maxAuthAge } = raw;
80
+ if (scopes !== void 0 && (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === "string" && SCOPE_TOKEN.test(scope)))) {
81
+ throw new TypeError(`${label}: scopes must be a list of scope tokens`);
82
+ }
83
+ if (requireClaims !== void 0 && (!Array.isArray(requireClaims) || requireClaims.length > MAX_REQUIRED_CLAIMS || !requireClaims.every((name) => typeof name === "string" && CLAIM_NAME.test(name)))) {
84
+ throw new TypeError(`${label}: requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`);
85
+ }
86
+ if (maxAuthAge !== void 0 && (typeof maxAuthAge !== "number" || !Number.isSafeInteger(maxAuthAge) || maxAuthAge <= 0)) {
87
+ throw new TypeError(`${label}: maxAuthAge must be a positive safe integer`);
88
+ }
89
+ return {
90
+ scopes: Object.freeze([...new Set(scopes ?? [])]),
91
+ requireClaims: Object.freeze([...new Set(requireClaims ?? [])]),
92
+ maxAuthAge: maxAuthAge ?? null
93
+ };
94
+ }
95
+
96
+ // src/express/middleware.ts
97
+ function refusalOf(error) {
98
+ const named = error instanceof import_auth_shared3.AuthVerifyError || error instanceof Error && error.name === "AuthVerifyError";
99
+ return named ? authRefusalOf(error) : null;
100
+ }
101
+ function isVerifier(verifier) {
102
+ return typeof verifier === "object" && verifier !== null && typeof verifier.verifyAuthorization === "function";
103
+ }
104
+ function requirePlasgosToken(verifier, requirements) {
105
+ if (!isVerifier(verifier)) {
106
+ throw new TypeError("requirePlasgosToken: verifier must come from createAccessTokenVerifier");
107
+ }
108
+ const checked = resolveRequirements("requirePlasgosToken", requirements);
109
+ const options = {
110
+ ...requirements?.scopes !== void 0 ? { scopes: checked.scopes } : {},
111
+ ...requirements?.requireClaims !== void 0 ? { requireClaims: checked.requireClaims } : {},
112
+ ...checked.maxAuthAge !== null ? { maxAuthAge: checked.maxAuthAge } : {}
113
+ };
114
+ return (req, res, next) => {
115
+ const { authorization, "x-request-id": requestId } = req.headers;
116
+ void verifier.verifyAuthorization(typeof authorization === "string" ? authorization : void 0, {
117
+ ...options,
118
+ ...typeof requestId === "string" ? { requestId } : {}
119
+ }).then(
120
+ (principal) => {
121
+ req.plasgosPrincipal = principal;
122
+ next();
123
+ },
124
+ (error) => {
125
+ const refusal = refusalOf(error);
126
+ if (refusal === null || res.headersSent === true) {
127
+ next(error);
128
+ return;
129
+ }
130
+ try {
131
+ res.status(refusal.status);
132
+ res.setHeader("Cache-Control", "no-store");
133
+ if (refusal.wwwAuthenticate !== null) res.setHeader("WWW-Authenticate", refusal.wwwAuthenticate);
134
+ res.json({ error: refusal.errorCode });
135
+ } catch (failure) {
136
+ next(failure);
137
+ }
138
+ }
139
+ );
140
+ };
141
+ }
142
+ function principalOf(req) {
143
+ const principal = req.plasgosPrincipal;
144
+ if (principal === void 0) throw new Error("principalOf: requirePlasgosToken did not run for this request");
145
+ return principal;
146
+ }
147
+
148
+ // src/express/index.ts
149
+ var import_auth_shared4 = require("@plasgos/auth-shared");
150
+ // Annotate the CommonJS export names for ESM import in node:
151
+ 0 && (module.exports = {
152
+ AuthVerifyError,
153
+ ConfigError,
154
+ principalOf,
155
+ requirePlasgosToken
156
+ });
157
+ //# sourceMappingURL=express.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/express/index.ts","../src/express/middleware.ts","../src/core/response.ts","../src/config.ts","../src/core/config.ts","../src/core/requirements.ts"],"sourcesContent":["export { principalOf, requirePlasgosToken } from \"./middleware.js\";\nexport type { PlasgosRequestLike, PlasgosRequirements, PlasgosResponseLike } from \"./middleware.js\";\nexport type {\n AccessPrincipal,\n AccessTokenVerifier,\n ServiceAccessPrincipal,\n UserAccessPrincipal,\n VerifiedAccessTokenClaims,\n} from \"../core/types.js\";\n// The classes this entry recognises and throws: the same classes as in @plasgos/auth-shared, so\n// `instanceof` holds across the packages.\nexport { AuthVerifyError, ConfigError } from \"@plasgos/auth-shared\";\nexport type { AuthVerifyReason } from \"@plasgos/auth-shared\";\n","import { AuthVerifyError } from \"@plasgos/auth-shared\";\n\nimport { authRefusalOf } from \"../core/response.js\";\nimport type { AuthRefusal } from \"../core/response.js\";\nimport { resolveRequirements } from \"../core/requirements.js\";\nimport type { AccessPrincipal, AccessTokenVerifier, VerifyOptions } from \"../core/types.js\";\n\n/**\n * The requirements of a route, checked on top of the verifier's own options.\n *\n * @example\n * const requirements: PlasgosRequirements = { scopes: [\"crm:access\"], requireClaims: [\"plasgos_public_id\", \"cv\"] };\n */\nexport interface PlasgosRequirements {\n /** Scopes the token must all hold; else 403 `insufficient_scope`. */\n scopes?: readonly string[] | undefined;\n /** Claim names the token must carry, added to the verifier's `requireClaims`; else 401. */\n requireClaims?: readonly string[] | undefined;\n /** Maximum age of the user's login in seconds; else 401 `insufficient_user_authentication`. */\n maxAuthAge?: number | undefined;\n}\n\n/**\n * The request fields the middleware uses. An Express 4 or 5 `Request` fits it; nothing is imported\n * from `express`.\n *\n * @example\n * const principal = principalOf(req); // req: express.Request\n */\nexport interface PlasgosRequestLike {\n /** The request headers with lower-case names, as Node gives them (`authorization`, `x-request-id`). */\n readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;\n /** Set by `requirePlasgosToken` once the token passed; read it with `principalOf`. */\n plasgosPrincipal?: AccessPrincipal | undefined;\n}\n\n/**\n * The response methods the middleware uses to answer a refused token. An Express 4 or 5 `Response`\n * fits it.\n *\n * @example\n * res.status(401).json({ error: \"invalid_token\" });\n */\nexport interface PlasgosResponseLike {\n /** True once the headers went out; the middleware then hands a refusal to `next(error)`. */\n readonly headersSent?: boolean | undefined;\n /** Sets the status code of the answer. */\n status(code: number): unknown;\n /** Sets one response header (`Cache-Control`, `WWW-Authenticate`). */\n setHeader(name: string, value: string): unknown;\n /** Sends the JSON body `{ \"error\": \"<errorCode>\" }`. */\n json(body: unknown): unknown;\n}\n\n/**\n * The answer of an `AuthVerifyError`, also one loaded through the other module system (same name);\n * null for any other error, including one that only borrows the name but has no known status.\n */\nfunction refusalOf(error: unknown): AuthRefusal | null {\n const named = error instanceof AuthVerifyError || (error instanceof Error && error.name === \"AuthVerifyError\");\n return named ? authRefusalOf(error) : null;\n}\n\n/** True when `verifier` has the methods of a verifier made by `createAccessTokenVerifier`. */\nfunction isVerifier(verifier: unknown): boolean {\n return (\n typeof verifier === \"object\" &&\n verifier !== null &&\n typeof (verifier as { verifyAuthorization?: unknown }).verifyAuthorization === \"function\"\n );\n}\n\n/**\n * Express middleware (Express 4 and 5) that lets a request through only with a valid Plasgos access\n * token. `verifier` comes from `createAccessTokenVerifier` of `@plasgos/auth-verify`; `requirements`\n * adds the route's scopes, required claims and maximum login age. The requirements are checked here,\n * when the middleware is created: a wrong one throws `TypeError` (naming the field, never the value).\n *\n * Per request, it reads `Authorization` and `X-Request-Id` (for the verifier's `onReject` event) and:\n * - token accepted: sets `req.plasgosPrincipal` and calls `next()`; read it with `principalOf(req)`;\n * - token refused (`AuthVerifyError`): answers itself with the error's status (401, 403 or 503),\n * `Cache-Control: no-store`, its `WWW-Authenticate` header when it has one, and the JSON body\n * `{ \"error\": \"<errorCode>\" }`;\n * - any other error (for example one thrown by your `isRevoked`): calls `next(error)`, so your error\n * handler answers it.\n *\n * The handler never returns a promise and catches every failure of its own: when the refusal cannot\n * be written (the headers were already sent, or a response method throws), it calls `next(error)`\n * instead, so no rejection is left unhandled in Express 4 or 5.\n *\n * @example\n * import { createAccessTokenVerifier } from \"@plasgos/auth-verify\";\n * import { principalOf, requirePlasgosToken } from \"@plasgos/auth-verify/express\";\n *\n * const verifier = createAccessTokenVerifier(options);\n * app.get(\"/contacts\", requirePlasgosToken(verifier, { scopes: [\"crm:access\"] }), (req, res) => {\n * res.json(listContacts(principalOf(req).claims.plasgos_public_id));\n * });\n */\nexport function requirePlasgosToken(\n verifier: AccessTokenVerifier<AccessPrincipal>,\n requirements?: PlasgosRequirements,\n): (req: PlasgosRequestLike, res: PlasgosResponseLike, next: (error?: unknown) => void) => void {\n if (!isVerifier(verifier)) {\n throw new TypeError(\"requirePlasgosToken: verifier must come from createAccessTokenVerifier\");\n }\n const checked = resolveRequirements(\"requirePlasgosToken\", requirements);\n const options: VerifyOptions = {\n ...(requirements?.scopes !== undefined ? { scopes: checked.scopes } : {}),\n ...(requirements?.requireClaims !== undefined ? { requireClaims: checked.requireClaims } : {}),\n ...(checked.maxAuthAge !== null ? { maxAuthAge: checked.maxAuthAge } : {}),\n };\n\n return (req, res, next) => {\n const { authorization, \"x-request-id\": requestId } = req.headers;\n void verifier\n .verifyAuthorization(typeof authorization === \"string\" ? authorization : undefined, {\n ...options,\n ...(typeof requestId === \"string\" ? { requestId } : {}),\n })\n .then(\n (principal) => {\n req.plasgosPrincipal = principal;\n next();\n },\n (error: unknown) => {\n const refusal = refusalOf(error);\n if (refusal === null || res.headersSent === true) {\n next(error);\n return;\n }\n try {\n res.status(refusal.status);\n res.setHeader(\"Cache-Control\", \"no-store\");\n if (refusal.wwwAuthenticate !== null) res.setHeader(\"WWW-Authenticate\", refusal.wwwAuthenticate);\n res.json({ error: refusal.errorCode });\n } catch (failure) {\n next(failure);\n }\n },\n );\n };\n}\n\n/**\n * The principal `requirePlasgosToken` set on this request. Throws `Error` when the middleware did not\n * run for the request: a wiring mistake, which your error handler should answer with 500.\n *\n * @example\n * app.get(\"/me\", requirePlasgosToken(verifier), (req, res) => {\n * const principal = principalOf(req);\n * res.json({ publicId: principal.claims.plasgos_public_id });\n * });\n */\nexport function principalOf(req: PlasgosRequestLike): AccessPrincipal {\n const principal = req.plasgosPrincipal;\n if (principal === undefined) throw new Error(\"principalOf: requirePlasgosToken did not run for this request\");\n return principal;\n}\n","import { AUTH_VERIFY_REASONS } from \"@plasgos/auth-shared\";\nimport type { AuthVerifyError } from \"@plasgos/auth-shared\";\n\nimport { isObject } from \"../config.js\";\n\nconst STATUSES: readonly unknown[] = [401, 403, 503];\nconst ERROR_CODES: readonly unknown[] = [\n \"invalid_token\",\n \"insufficient_scope\",\n \"insufficient_user_authentication\",\n \"temporarily_unavailable\",\n];\nconst REASONS: readonly unknown[] = AUTH_VERIFY_REASONS;\n\n/** The answer to a refused token, read from an `AuthVerifyError`'s fields. */\nexport interface AuthRefusal {\n readonly status: 401 | 403 | 503;\n readonly errorCode: string;\n readonly wwwAuthenticate: string | null;\n}\n\n/**\n * The answer fields of `error` when it has the shape of an `AuthVerifyError` (a known reason, status\n * and error code, and a string or null challenge), else null. It reads fields, not the class, so an\n * error loaded through the other module system works too; the adapters use it so that an error that\n * only borrows the name never reaches `res.status`.\n *\n * @example\n * const refusal = authRefusalOf(error);\n * if (refusal === null) throw error;\n */\nexport function authRefusalOf(error: unknown): AuthRefusal | null {\n const fields = isObject(error) || error instanceof Error ? (error as unknown as Record<string, unknown>) : null;\n if (fields === null) return null;\n const challenge = fields[\"wwwAuthenticate\"];\n if (\n !REASONS.includes(fields[\"reason\"]) ||\n !STATUSES.includes(fields[\"status\"]) ||\n !ERROR_CODES.includes(fields[\"errorCode\"]) ||\n (challenge !== null && typeof challenge !== \"string\")\n ) {\n return null;\n }\n return {\n status: fields[\"status\"] as AuthRefusal[\"status\"],\n errorCode: fields[\"errorCode\"] as string,\n wwwAuthenticate: challenge,\n };\n}\n\n/**\n * The HTTP answer to a refused token, for servers built on Web `Request`/`Response` (fetch handlers,\n * Hono, React Router, Next.js route handlers): the error's `status` (401, 403 or 503), its\n * `WWW-Authenticate` challenge when it has one, `Cache-Control: no-store`, and the JSON body\n * `{\"error\":\"<errorCode>\"}`. It reads the error's fields, so an `AuthVerifyError` loaded through the\n * other module system (ESM and CommonJS in one app) works too. Throws `TypeError` for anything that is\n * not an `AuthVerifyError`: rethrow such errors instead of answering them.\n *\n * @example\n * import { AuthVerifyError, authErrorResponse } from \"@plasgos/auth-verify\";\n *\n * try {\n * const principal = await verifier.verifyRequest(request, { scopes: [\"crm:access\"] });\n * return Response.json({ id: principal.claims.plasgos_public_id });\n * } catch (error) {\n * if (error instanceof AuthVerifyError) return authErrorResponse(error);\n * throw error;\n * }\n */\nexport function authErrorResponse(error: AuthVerifyError): Response {\n const refusal = authRefusalOf(error);\n if (refusal === null) throw new TypeError(\"authErrorResponse: error must be an AuthVerifyError\");\n const headers = new Headers({ \"content-type\": \"application/json\", \"cache-control\": \"no-store\" });\n if (refusal.wwwAuthenticate !== null) headers.set(\"www-authenticate\", refusal.wwwAuthenticate);\n return new Response(JSON.stringify({ error: refusal.errorCode }), { status: refusal.status, headers });\n}\n","// Option helpers shared by the entries of this package. Stateless functions only: tsup bundles them\n// into every entry that uses them, so the ESM and CommonJS builds hold no state that could split.\n\n/**\n * True for a non-null object that is not an array.\n *\n * @example\n * if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n */\nexport const isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * True for a string of whitespace only. Apps pass `process.env` values, where unset is often \"\".\n *\n * @example\n * const secrets = raw.filter((value) => value !== undefined && !isBlank(value));\n */\nexport const isBlank = (value: unknown): boolean => typeof value === \"string\" && value.trim() === \"\";\n\n/**\n * Bounds and default of {@link integerInRange}.\n *\n * @example\n * const range: IntegerRange = { min: 1, max: 900, fallback: 300 };\n */\nexport interface IntegerRange {\n readonly min: number;\n readonly max: number;\n /** Returned for `undefined`, and when the value is refused. */\n readonly fallback: number;\n}\n\n/**\n * An integer option: `undefined` gives the fallback; a safe integer from `min` to `max` is returned\n * as is; anything else collects `<field> must be an integer from <min> to <max>` and gives the\n * fallback. The problem names the field and the bounds, never the value.\n *\n * @example\n * const problems: string[] = [];\n * const toleranceSeconds = integerInRange(problems, raw.toleranceSeconds, \"toleranceSeconds\", {\n * min: 1,\n * max: 900,\n * fallback: 300,\n * });\n */\nexport function integerInRange(problems: string[], raw: unknown, field: string, range: IntegerRange): number {\n if (raw === undefined) return range.fallback;\n if (typeof raw === \"number\" && Number.isSafeInteger(raw) && raw >= range.min && raw <= range.max) return raw;\n problems.push(`${field} must be an integer from ${String(range.min)} to ${String(range.max)}`);\n return range.fallback;\n}\n\n/**\n * An optional function option: `undefined` stays `undefined`; anything that is not a function\n * collects `<field> must be a function` and gives `undefined`.\n *\n * @example\n * const onReject = optionalFunction(problems, raw.onReject, \"onReject\");\n */\nexport function optionalFunction(problems: string[], raw: unknown, field: string): ((...args: never[]) => unknown) | undefined {\n if (raw === undefined) return undefined;\n if (typeof raw === \"function\") return raw as (...args: never[]) => unknown;\n problems.push(`${field} must be a function`);\n return undefined;\n}\n","import { ConfigError, PRODUCTION_ISSUER, environmentProblems, parseAudience, parseIssuer } from \"@plasgos/auth-shared\";\nimport type { Environment } from \"@plasgos/auth-shared\";\n\nimport { integerInRange, isBlank, isObject, optionalFunction } from \"../config.js\";\nimport type { AccessPrincipal, AuthRejectEvent, JsonWebKeySet, JwksFetch } from \"./types.js\";\n\n/** Default leeway for `exp`/`nbf`: a resource server runs on its own clock. */\nconst DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;\nconst MAX_CLOCK_TOLERANCE_SECONDS = 60;\nconst DEFAULT_JWKS_MS = 5_000;\nconst MAX_TIMEOUT_MS = 60_000;\n/** At most this many required claim names, on the verifier and per call. */\nexport const MAX_REQUIRED_CLAIMS = 16;\n/** A claim name the verifier can require: letters, digits and `_`, at most 64 characters. */\nexport const CLAIM_NAME = /^[A-Za-z0-9_]{1,64}$/;\n/** The audience path whose user tokens must carry `cv`: the revocation check compares it. */\nconst CREDENTIAL_VERSION_PATH = \"/crm\";\n\nconst PROBLEM = {\n https: 'backchannelUrl must use https: when environment is \"production\" unless allowInsecureBackchannel is true',\n isRevokedRequired: \"isRevoked is required for a crm audience\",\n requireClaims: `requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`,\n jwks: \"jwks must be a JSON Web Key Set\",\n jwksSandboxOnly: 'jwks is only allowed when environment is \"sandbox\"',\n} as const;\n\n/**\n * The checked options of `createAccessTokenVerifier`, frozen.\n *\n * @example\n * const config = resolveVerifierConfig(options);\n * const jwksUrl = `${config.backchannelUrl ?? config.issuer}/oidc/jwks`;\n */\nexport interface ResolvedVerifierConfig {\n readonly environment: Environment;\n readonly issuer: string;\n readonly audience: string;\n readonly backchannelUrl: string | null;\n readonly allowInsecureBackchannel: boolean;\n readonly allowServiceTokens: boolean;\n /** The `requireClaims` option: distinct names, in the order given. */\n readonly requiredClaims: readonly string[];\n /** True when the audience path, trailing slashes removed, is `/crm`: user tokens must carry `cv`. */\n readonly requireCredentialVersion: boolean;\n readonly clockToleranceSeconds: number;\n readonly timeouts: Readonly<{ jwksMs: number }>;\n /** A frozen copy of the static key set, or null for the JWKS request. */\n readonly jwks: JsonWebKeySet | null;\n readonly fetch: JwksFetch;\n readonly isRevoked: ((principal: AccessPrincipal) => boolean | Promise<boolean>) | undefined;\n readonly onReject: ((event: AuthRejectEvent) => void | Promise<void>) | undefined;\n}\n\nconst RESOURCE_PROBLEM = 'environment is \"production\" but resource is not a production audience';\nconst AUDIENCE_PROBLEM = 'environment is \"production\" but audience is not a production audience';\n\n/** Resolved at call time, so a `globalThis.fetch` replaced later (a test spy, an instrumentation) is used. */\nconst globalFetch: JwksFetch = (input, init) => globalThis.fetch(input, init);\n\n/** True when the audience's path without trailing slashes is exactly `/crm`. */\nfunction needsCredentialVersion(audience: string): boolean {\n return new URL(audience).pathname.replace(/\\/+$/, \"\") === CREDENTIAL_VERSION_PATH;\n}\n\n/** Runs a single-problem parser of auth-shared; its problem is collected, not thrown. */\nfunction parsed(problems: string[], parse: () => string): string | undefined {\n try {\n return parse();\n } catch (error) {\n if (!(error instanceof ConfigError)) throw error;\n problems.push(...error.problems);\n return undefined;\n }\n}\n\n/** The required claim names, distinct and frozen; an empty list after the problem was collected. */\nfunction requiredClaimsOf(problems: string[], raw: unknown): readonly string[] {\n if (raw === undefined) return Object.freeze([]);\n if (\n !Array.isArray(raw) ||\n raw.length > MAX_REQUIRED_CLAIMS ||\n !raw.every((name): name is string => typeof name === \"string\" && CLAIM_NAME.test(name))\n ) {\n problems.push(PROBLEM.requireClaims);\n return Object.freeze([]);\n }\n return Object.freeze([...new Set(raw)]);\n}\n\n/** A frozen copy of a well-formed key set, or null after the problem was collected. */\nfunction jwksOf(problems: string[], raw: unknown): JsonWebKeySet | null {\n const keys: unknown = isObject(raw) ? raw[\"keys\"] : undefined;\n if (!Array.isArray(keys) || keys.length === 0 || !keys.every((key) => isObject(key))) {\n problems.push(PROBLEM.jwks);\n return null;\n }\n return Object.freeze({ keys: Object.freeze(keys.map((key) => Object.freeze({ ...key }))) });\n}\n\n/** The `timeouts` option: an object whose `jwksMs` is an integer from 1 to 60 000 ms. */\nfunction timeoutsOf(problems: string[], raw: unknown): Readonly<{ jwksMs: number }> {\n if (raw === undefined) return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });\n if (!isObject(raw)) {\n problems.push(\"timeouts must be an object\");\n return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });\n }\n const jwksMs = integerInRange(problems, raw[\"jwksMs\"], \"timeouts.jwksMs\", {\n min: 1,\n max: MAX_TIMEOUT_MS,\n fallback: DEFAULT_JWKS_MS,\n });\n return Object.freeze({ jwksMs });\n}\n\n/**\n * Checks the untyped options of `createAccessTokenVerifier`. Returns the frozen config, or throws one\n * `ConfigError` whose problems name fields only, never values: the environment guard first, then the\n * fields in the order of the option table.\n *\n * @example\n * const config = resolveVerifierConfig({\n * environment: \"production\",\n * issuer: \"https://accounts.plasgos.co.id\",\n * audience: \"https://api.plasgos.co.id/crm\",\n * isRevoked: () => false,\n * });\n * config.requireCredentialVersion; // true\n */\nexport function resolveVerifierConfig(raw: unknown): ResolvedVerifierConfig {\n if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n const problems: string[] = [];\n\n /** The option when it is a string; a present non-string is reported and counts as unusable. */\n const text = (field: string): string | undefined => {\n const value = raw[field];\n if (value === undefined || typeof value === \"string\") return value;\n problems.push(`${field} must be a string`);\n return undefined;\n };\n const given = (field: string): boolean => raw[field] !== undefined;\n /** A boolean option: `undefined` is `false`; anything else but a boolean is reported. */\n const flag = (field: string): boolean => {\n const value = raw[field];\n if (value === undefined || typeof value === \"boolean\") return value === true;\n problems.push(`${field} must be a boolean`);\n return false;\n };\n\n const environment = raw[\"environment\"];\n // For the URL checks a non-boolean counts as false; the environment guard still sees the raw value.\n const allowInsecureHttp = raw[\"allowInsecureHttp\"] === true;\n\n const issuerRaw = text(\"issuer\");\n const issuer =\n given(\"issuer\") && issuerRaw === undefined\n ? undefined\n : parsed(problems, () => parseIssuer(issuerRaw, { field: \"issuer\", allowInsecureHttp }));\n\n const audienceRaw = text(\"audience\");\n const audience =\n given(\"audience\") && audienceRaw === undefined\n ? undefined\n : parsed(problems, () => parseAudience(audienceRaw, { field: \"audience\", allowInsecureHttp }));\n\n // A blank backchannelUrl (an env var set to \"\") counts as not given.\n const backchannelRaw = given(\"backchannelUrl\") && !isBlank(raw[\"backchannelUrl\"]) ? text(\"backchannelUrl\") : undefined;\n const backchannelUrl =\n backchannelRaw === undefined\n ? undefined\n : parsed(problems, () => parseIssuer(backchannelRaw, { field: \"backchannelUrl\", allowInsecureHttp: true }));\n // The JWKS is the trust root: a plain-http back channel in production needs an explicit opt-in.\n const insecureBackchannelRaw = raw[\"allowInsecureBackchannel\"];\n if (\n environment === \"production\" &&\n backchannelUrl !== undefined &&\n new URL(backchannelUrl).protocol === \"http:\" &&\n insecureBackchannelRaw !== true\n ) {\n problems.push(PROBLEM.https);\n }\n const allowInsecureBackchannel = flag(\"allowInsecureBackchannel\");\n\n const allowServiceTokens = flag(\"allowServiceTokens\");\n const requiredClaims = requiredClaimsOf(problems, raw[\"requireClaims\"]);\n const clockToleranceSeconds = integerInRange(problems, raw[\"clockToleranceSeconds\"], \"clockToleranceSeconds\", {\n min: 0,\n max: MAX_CLOCK_TOLERANCE_SECONDS,\n fallback: DEFAULT_CLOCK_TOLERANCE_SECONDS,\n });\n const timeouts = timeoutsOf(problems, raw[\"timeouts\"]);\n\n const jwks = given(\"jwks\") ? jwksOf(problems, raw[\"jwks\"]) : null;\n if (given(\"jwks\") && environment === \"production\") problems.push(PROBLEM.jwksSandboxOnly);\n\n flag(\"allowInsecureHttp\");\n const fetch = optionalFunction(problems, raw[\"fetch\"], \"fetch\") as JwksFetch | undefined;\n\n const requireCredentialVersion = audience !== undefined && needsCredentialVersion(audience);\n const isRevoked = optionalFunction(problems, raw[\"isRevoked\"], \"isRevoked\") as ResolvedVerifierConfig[\"isRevoked\"];\n // A cv that nothing compares is a revocation check that silently does not run.\n if (requireCredentialVersion && !given(\"isRevoked\")) problems.push(PROBLEM.isRevokedRequired);\n const onReject = optionalFunction(problems, raw[\"onReject\"], \"onReject\") as ResolvedVerifierConfig[\"onReject\"];\n\n // The guard compares parsed values. An issuer that did not parse already has its problem, so the\n // guard gets a value it has nothing to say about and still judges the other fields.\n const guard = environmentProblems({\n environment,\n issuer: issuer ?? (environment === \"production\" ? PRODUCTION_ISSUER : \"\"),\n allowInsecureHttp: raw[\"allowInsecureHttp\"],\n ...(audience !== undefined ? { audiences: [audience] } : {}),\n ...(backchannelUrl !== undefined ? { backchannelUrl } : {}),\n });\n\n // The shared guard names the option of @plasgos/oidc-client (\"resource\"); here the option is \"audience\".\n const named = guard.map((problem) => (problem === RESOURCE_PROBLEM ? AUDIENCE_PROBLEM : problem));\n if (named.length > 0 || problems.length > 0) throw new ConfigError([...named, ...problems]);\n return Object.freeze({\n environment: environment as Environment,\n issuer: issuer as string,\n audience: audience as string,\n backchannelUrl: backchannelUrl ?? null,\n allowInsecureBackchannel,\n allowServiceTokens,\n requiredClaims,\n requireCredentialVersion,\n clockToleranceSeconds,\n timeouts,\n jwks,\n fetch: fetch ?? globalFetch,\n isRevoked,\n onReject,\n });\n}\n","// The checks of a route's requirements (`VerifyOptions`). No jose import: the framework adapters use\n// this file to check their requirements when a middleware or guard is created.\nimport { isObject } from \"../config.js\";\nimport { CLAIM_NAME, MAX_REQUIRED_CLAIMS } from \"./config.js\";\n\n/** An RFC 6749 §3.3 scope token: printable ASCII without space, `\"` and `\\`, so it fits a quoted challenge. */\nconst SCOPE_TOKEN = /^[\\x21\\x23-\\x5B\\x5D-\\x7E]+$/;\n\n/**\n * The checked requirements of one verification.\n *\n * @example\n * const requirements = resolveRequirements(\"verify\", { scopes: [\"crm:access\"] });\n */\nexport interface ResolvedRequirements {\n readonly scopes: readonly string[];\n readonly requireClaims: readonly string[];\n readonly maxAuthAge: number | null;\n}\n\n/** The checked requirements and the per-call fields of `VerifyOptions`. */\nexport interface ResolvedVerifyOptions extends ResolvedRequirements {\n /** `undefined` when the caller gave none. */\n readonly requestId: string | null | undefined;\n /** Epoch milliseconds, or null for `Date.now()`. */\n readonly now: number | null;\n}\n\n/**\n * Checks the route requirements (`scopes`, `requireClaims`, `maxAuthAge`) of plain JavaScript input.\n * Throws `TypeError` (`<label>: <field> must be …`) that names the field, never the value.\n *\n * @example\n * resolveRequirements(\"requirePlasgosToken\", { scopes: [\"crm:access\"], maxAuthAge: 600 });\n */\nexport function resolveRequirements(label: string, raw: unknown): ResolvedRequirements {\n if (raw === undefined) return { scopes: [], requireClaims: [], maxAuthAge: null };\n if (!isObject(raw)) throw new TypeError(`${label}: options must be an object`);\n const { scopes, requireClaims, maxAuthAge } = raw;\n if (\n scopes !== undefined &&\n (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === \"string\" && SCOPE_TOKEN.test(scope)))\n ) {\n throw new TypeError(`${label}: scopes must be a list of scope tokens`);\n }\n if (\n requireClaims !== undefined &&\n (!Array.isArray(requireClaims) ||\n requireClaims.length > MAX_REQUIRED_CLAIMS ||\n !requireClaims.every((name) => typeof name === \"string\" && CLAIM_NAME.test(name)))\n ) {\n throw new TypeError(`${label}: requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`);\n }\n if (maxAuthAge !== undefined && (typeof maxAuthAge !== \"number\" || !Number.isSafeInteger(maxAuthAge) || maxAuthAge <= 0)) {\n throw new TypeError(`${label}: maxAuthAge must be a positive safe integer`);\n }\n return {\n scopes: Object.freeze([...new Set((scopes ?? []) as string[])]),\n requireClaims: Object.freeze([...new Set((requireClaims ?? []) as string[])]),\n maxAuthAge: maxAuthAge ?? null,\n };\n}\n\n/**\n * Checks `VerifyOptions`: the requirements, plus `requestId` (a string, null or absent) and `now`\n * (finite epoch milliseconds). Throws `TypeError` without the value.\n *\n * @example\n * const options = resolveVerifyOptions(raw); // inside verifyAuthorization\n */\nexport function resolveVerifyOptions(raw: unknown): ResolvedVerifyOptions {\n const requirements = resolveRequirements(\"verify\", raw);\n const fields = isObject(raw) ? raw : {};\n const { requestId, now } = fields;\n if (requestId !== undefined && requestId !== null && typeof requestId !== \"string\") {\n throw new TypeError(\"verify: requestId must be a string\");\n }\n if (now !== undefined && (typeof now !== \"number\" || !Number.isFinite(now))) {\n throw new TypeError(\"verify: now must be a finite number\");\n }\n return { ...requirements, requestId, now: now ?? null };\n}\n"],"mappings":"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","names":["import_auth_shared","import_auth_shared","import_auth_shared"]}
@@ -0,0 +1,90 @@
1
+ import { A as AccessPrincipal, a as AccessTokenVerifier } from './types-CGtRnj59.cjs';
2
+ export { S as ServiceAccessPrincipal, U as UserAccessPrincipal, V as VerifiedAccessTokenClaims } from './types-CGtRnj59.cjs';
3
+ export { AuthVerifyError, AuthVerifyReason, ConfigError } from '@plasgos/auth-shared';
4
+
5
+ /**
6
+ * The requirements of a route, checked on top of the verifier's own options.
7
+ *
8
+ * @example
9
+ * const requirements: PlasgosRequirements = { scopes: ["crm:access"], requireClaims: ["plasgos_public_id", "cv"] };
10
+ */
11
+ interface PlasgosRequirements {
12
+ /** Scopes the token must all hold; else 403 `insufficient_scope`. */
13
+ scopes?: readonly string[] | undefined;
14
+ /** Claim names the token must carry, added to the verifier's `requireClaims`; else 401. */
15
+ requireClaims?: readonly string[] | undefined;
16
+ /** Maximum age of the user's login in seconds; else 401 `insufficient_user_authentication`. */
17
+ maxAuthAge?: number | undefined;
18
+ }
19
+ /**
20
+ * The request fields the middleware uses. An Express 4 or 5 `Request` fits it; nothing is imported
21
+ * from `express`.
22
+ *
23
+ * @example
24
+ * const principal = principalOf(req); // req: express.Request
25
+ */
26
+ interface PlasgosRequestLike {
27
+ /** The request headers with lower-case names, as Node gives them (`authorization`, `x-request-id`). */
28
+ readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;
29
+ /** Set by `requirePlasgosToken` once the token passed; read it with `principalOf`. */
30
+ plasgosPrincipal?: AccessPrincipal | undefined;
31
+ }
32
+ /**
33
+ * The response methods the middleware uses to answer a refused token. An Express 4 or 5 `Response`
34
+ * fits it.
35
+ *
36
+ * @example
37
+ * res.status(401).json({ error: "invalid_token" });
38
+ */
39
+ interface PlasgosResponseLike {
40
+ /** True once the headers went out; the middleware then hands a refusal to `next(error)`. */
41
+ readonly headersSent?: boolean | undefined;
42
+ /** Sets the status code of the answer. */
43
+ status(code: number): unknown;
44
+ /** Sets one response header (`Cache-Control`, `WWW-Authenticate`). */
45
+ setHeader(name: string, value: string): unknown;
46
+ /** Sends the JSON body `{ "error": "<errorCode>" }`. */
47
+ json(body: unknown): unknown;
48
+ }
49
+ /**
50
+ * Express middleware (Express 4 and 5) that lets a request through only with a valid Plasgos access
51
+ * token. `verifier` comes from `createAccessTokenVerifier` of `@plasgos/auth-verify`; `requirements`
52
+ * adds the route's scopes, required claims and maximum login age. The requirements are checked here,
53
+ * when the middleware is created: a wrong one throws `TypeError` (naming the field, never the value).
54
+ *
55
+ * Per request, it reads `Authorization` and `X-Request-Id` (for the verifier's `onReject` event) and:
56
+ * - token accepted: sets `req.plasgosPrincipal` and calls `next()`; read it with `principalOf(req)`;
57
+ * - token refused (`AuthVerifyError`): answers itself with the error's status (401, 403 or 503),
58
+ * `Cache-Control: no-store`, its `WWW-Authenticate` header when it has one, and the JSON body
59
+ * `{ "error": "<errorCode>" }`;
60
+ * - any other error (for example one thrown by your `isRevoked`): calls `next(error)`, so your error
61
+ * handler answers it.
62
+ *
63
+ * The handler never returns a promise and catches every failure of its own: when the refusal cannot
64
+ * be written (the headers were already sent, or a response method throws), it calls `next(error)`
65
+ * instead, so no rejection is left unhandled in Express 4 or 5.
66
+ *
67
+ * @example
68
+ * import { createAccessTokenVerifier } from "@plasgos/auth-verify";
69
+ * import { principalOf, requirePlasgosToken } from "@plasgos/auth-verify/express";
70
+ *
71
+ * const verifier = createAccessTokenVerifier(options);
72
+ * app.get("/contacts", requirePlasgosToken(verifier, { scopes: ["crm:access"] }), (req, res) => {
73
+ * res.json(listContacts(principalOf(req).claims.plasgos_public_id));
74
+ * });
75
+ */
76
+ declare function requirePlasgosToken(verifier: AccessTokenVerifier<AccessPrincipal>, requirements?: PlasgosRequirements): (req: PlasgosRequestLike, res: PlasgosResponseLike, next: (error?: unknown) => void) => void;
77
+ /**
78
+ * The principal `requirePlasgosToken` set on this request. Throws `Error` when the middleware did not
79
+ * run for the request: a wiring mistake, which your error handler should answer with 500.
80
+ *
81
+ * @example
82
+ * app.get("/me", requirePlasgosToken(verifier), (req, res) => {
83
+ * const principal = principalOf(req);
84
+ * res.json({ publicId: principal.claims.plasgos_public_id });
85
+ * });
86
+ */
87
+ declare function principalOf(req: PlasgosRequestLike): AccessPrincipal;
88
+
89
+ export { AccessPrincipal, AccessTokenVerifier, principalOf, requirePlasgosToken };
90
+ export type { PlasgosRequestLike, PlasgosRequirements, PlasgosResponseLike };
@@ -0,0 +1,90 @@
1
+ import { A as AccessPrincipal, a as AccessTokenVerifier } from './types-CGtRnj59.js';
2
+ export { S as ServiceAccessPrincipal, U as UserAccessPrincipal, V as VerifiedAccessTokenClaims } from './types-CGtRnj59.js';
3
+ export { AuthVerifyError, AuthVerifyReason, ConfigError } from '@plasgos/auth-shared';
4
+
5
+ /**
6
+ * The requirements of a route, checked on top of the verifier's own options.
7
+ *
8
+ * @example
9
+ * const requirements: PlasgosRequirements = { scopes: ["crm:access"], requireClaims: ["plasgos_public_id", "cv"] };
10
+ */
11
+ interface PlasgosRequirements {
12
+ /** Scopes the token must all hold; else 403 `insufficient_scope`. */
13
+ scopes?: readonly string[] | undefined;
14
+ /** Claim names the token must carry, added to the verifier's `requireClaims`; else 401. */
15
+ requireClaims?: readonly string[] | undefined;
16
+ /** Maximum age of the user's login in seconds; else 401 `insufficient_user_authentication`. */
17
+ maxAuthAge?: number | undefined;
18
+ }
19
+ /**
20
+ * The request fields the middleware uses. An Express 4 or 5 `Request` fits it; nothing is imported
21
+ * from `express`.
22
+ *
23
+ * @example
24
+ * const principal = principalOf(req); // req: express.Request
25
+ */
26
+ interface PlasgosRequestLike {
27
+ /** The request headers with lower-case names, as Node gives them (`authorization`, `x-request-id`). */
28
+ readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;
29
+ /** Set by `requirePlasgosToken` once the token passed; read it with `principalOf`. */
30
+ plasgosPrincipal?: AccessPrincipal | undefined;
31
+ }
32
+ /**
33
+ * The response methods the middleware uses to answer a refused token. An Express 4 or 5 `Response`
34
+ * fits it.
35
+ *
36
+ * @example
37
+ * res.status(401).json({ error: "invalid_token" });
38
+ */
39
+ interface PlasgosResponseLike {
40
+ /** True once the headers went out; the middleware then hands a refusal to `next(error)`. */
41
+ readonly headersSent?: boolean | undefined;
42
+ /** Sets the status code of the answer. */
43
+ status(code: number): unknown;
44
+ /** Sets one response header (`Cache-Control`, `WWW-Authenticate`). */
45
+ setHeader(name: string, value: string): unknown;
46
+ /** Sends the JSON body `{ "error": "<errorCode>" }`. */
47
+ json(body: unknown): unknown;
48
+ }
49
+ /**
50
+ * Express middleware (Express 4 and 5) that lets a request through only with a valid Plasgos access
51
+ * token. `verifier` comes from `createAccessTokenVerifier` of `@plasgos/auth-verify`; `requirements`
52
+ * adds the route's scopes, required claims and maximum login age. The requirements are checked here,
53
+ * when the middleware is created: a wrong one throws `TypeError` (naming the field, never the value).
54
+ *
55
+ * Per request, it reads `Authorization` and `X-Request-Id` (for the verifier's `onReject` event) and:
56
+ * - token accepted: sets `req.plasgosPrincipal` and calls `next()`; read it with `principalOf(req)`;
57
+ * - token refused (`AuthVerifyError`): answers itself with the error's status (401, 403 or 503),
58
+ * `Cache-Control: no-store`, its `WWW-Authenticate` header when it has one, and the JSON body
59
+ * `{ "error": "<errorCode>" }`;
60
+ * - any other error (for example one thrown by your `isRevoked`): calls `next(error)`, so your error
61
+ * handler answers it.
62
+ *
63
+ * The handler never returns a promise and catches every failure of its own: when the refusal cannot
64
+ * be written (the headers were already sent, or a response method throws), it calls `next(error)`
65
+ * instead, so no rejection is left unhandled in Express 4 or 5.
66
+ *
67
+ * @example
68
+ * import { createAccessTokenVerifier } from "@plasgos/auth-verify";
69
+ * import { principalOf, requirePlasgosToken } from "@plasgos/auth-verify/express";
70
+ *
71
+ * const verifier = createAccessTokenVerifier(options);
72
+ * app.get("/contacts", requirePlasgosToken(verifier, { scopes: ["crm:access"] }), (req, res) => {
73
+ * res.json(listContacts(principalOf(req).claims.plasgos_public_id));
74
+ * });
75
+ */
76
+ declare function requirePlasgosToken(verifier: AccessTokenVerifier<AccessPrincipal>, requirements?: PlasgosRequirements): (req: PlasgosRequestLike, res: PlasgosResponseLike, next: (error?: unknown) => void) => void;
77
+ /**
78
+ * The principal `requirePlasgosToken` set on this request. Throws `Error` when the middleware did not
79
+ * run for the request: a wiring mistake, which your error handler should answer with 500.
80
+ *
81
+ * @example
82
+ * app.get("/me", requirePlasgosToken(verifier), (req, res) => {
83
+ * const principal = principalOf(req);
84
+ * res.json({ publicId: principal.claims.plasgos_public_id });
85
+ * });
86
+ */
87
+ declare function principalOf(req: PlasgosRequestLike): AccessPrincipal;
88
+
89
+ export { AccessPrincipal, AccessTokenVerifier, principalOf, requirePlasgosToken };
90
+ export type { PlasgosRequestLike, PlasgosRequirements, PlasgosResponseLike };