@plasgos/oidc-client 0.0.0-stage → 0.1.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +15 -0
  3. package/README.md +145 -2
  4. package/dist/index.cjs +884 -0
  5. package/dist/index.cjs.map +1 -0
  6. package/dist/index.d.cts +33 -0
  7. package/dist/index.d.ts +33 -0
  8. package/dist/index.js +860 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/service.cjs +432 -0
  11. package/dist/service.cjs.map +1 -0
  12. package/dist/service.d.cts +88 -0
  13. package/dist/service.d.ts +88 -0
  14. package/dist/service.js +419 -0
  15. package/dist/service.js.map +1 -0
  16. package/dist/session.cjs +601 -0
  17. package/dist/session.cjs.map +1 -0
  18. package/dist/session.d.cts +289 -0
  19. package/dist/session.d.ts +289 -0
  20. package/dist/session.js +568 -0
  21. package/dist/session.js.map +1 -0
  22. package/dist/types-JE0OMyoi.d.cts +375 -0
  23. package/dist/types-JE0OMyoi.d.ts +375 -0
  24. package/docs/consumers.md +90 -0
  25. package/docs/contoh-hitungcuan.md +255 -0
  26. package/docs/contoh-plaslink.md +244 -0
  27. package/docs/error.md +428 -0
  28. package/docs/examples/auth-verify-readme.ts +18 -0
  29. package/docs/examples/config-error.ts +24 -0
  30. package/docs/examples/env.ts +99 -0
  31. package/docs/examples/failure-log.ts +18 -0
  32. package/docs/examples/login-client.ts +46 -0
  33. package/docs/examples/login-flow.ts +186 -0
  34. package/docs/examples/plaslink-connect.ts +48 -0
  35. package/docs/examples/readme.ts +60 -0
  36. package/docs/examples/service-client.ts +105 -0
  37. package/docs/examples/session-store.ts +53 -0
  38. package/docs/examples/webhook-express.ts +46 -0
  39. package/docs/examples/webhook-fetch.ts +60 -0
  40. package/docs/examples/webhook-nestjs.ts +59 -0
  41. package/docs/examples/webhook-testing.ts +60 -0
  42. package/docs/examples/webhook-verifier.ts +143 -0
  43. package/docs/login-web.md +618 -0
  44. package/docs/memulai.md +339 -0
  45. package/docs/server-ke-server.md +275 -0
  46. package/docs/webhook.md +625 -0
  47. package/package.json +67 -3
@@ -0,0 +1,186 @@
1
+ import { OidcError, accessTokenExpiry } from "@plasgos/oidc-client";
2
+ import type { OidcClient } from "@plasgos/oidc-client";
3
+ import type { AuthState, SessionHandle, SessionStore } from "@plasgos/oidc-client/session";
4
+
5
+ import { readLoginCredentials, readPlasgosEnv } from "./env.js";
6
+ import { createFirstPartyClient } from "./login-client.js";
7
+ import { createAppSessionStore } from "./session-store.js";
8
+ import type { AppSession } from "./session-store.js";
9
+
10
+ // #region setup
11
+ /** Everything the handlers need. Create it once at start and pass it to every handler. */
12
+ export interface AuthContext {
13
+ client: OidcClient;
14
+ store: SessionStore<AppSession>;
15
+ /** Public origin of this app, for the Origin check of the logout. */
16
+ appOrigin: string;
17
+ /** Where /v5/* lives. */
18
+ apiUrl: string;
19
+ }
20
+
21
+ export function createAuthContext(): AuthContext {
22
+ return {
23
+ client: createFirstPartyClient(),
24
+ store: createAppSessionStore(),
25
+ appOrigin: readLoginCredentials().appUrl,
26
+ apiUrl: readPlasgosEnv().apiUrl,
27
+ };
28
+ }
29
+
30
+ /** Only a path of this app is accepted as the place to return to after login. */
31
+ function safeReturnTo(value: string | null): string {
32
+ if (value === null || value.length > 512) return "/";
33
+ if (!value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) return "/";
34
+ return value;
35
+ }
36
+
37
+ function redirect(location: string, headers: Headers, status = 302): Response {
38
+ headers.set("Location", location);
39
+ headers.set("Cache-Control", "no-store");
40
+ return new Response(null, { status, headers });
41
+ }
42
+ // #endregion setup
43
+
44
+ // #region login
45
+ /** GET /login?returnTo=/path: a full-page redirect to Plasgos. */
46
+ export function handleLogin(context: AuthContext, request: Request): Response {
47
+ const returnTo = safeReturnTo(new URL(request.url).searchParams.get("returnTo"));
48
+ const { location, transaction } = context.client.startLogin({ returnTo });
49
+ const headers = new Headers();
50
+ headers.append("Set-Cookie", context.store.commitTransaction(transaction));
51
+ return redirect(location, headers);
52
+ }
53
+ // #endregion login
54
+
55
+ // #region callback
56
+ function loginFailed(headers: Headers, status: number): Response {
57
+ headers.set("Cache-Control", "no-store");
58
+ headers.set("Content-Type", "text/plain; charset=utf-8");
59
+ return new Response("Login gagal. Silakan coba lagi.", { status, headers });
60
+ }
61
+
62
+ /** GET /auth/callback: Plasgos sends the browser back here with `code` and `state`. */
63
+ export async function handleCallback(context: AuthContext, request: Request): Promise<Response> {
64
+ const { client, store } = context;
65
+ const headers = new Headers();
66
+ // The transaction is single use: its cookie is cleared whatever happens next.
67
+ headers.append("Set-Cookie", store.clearTransaction());
68
+ try {
69
+ const { tokens, claims, transaction } = await client.handleCallback(request.url, store.readTransaction(request));
70
+ const auth: AuthState = {
71
+ access_token: tokens.access_token,
72
+ refresh_token: tokens.refresh_token,
73
+ expires_at: accessTokenExpiry(tokens, Date.now()),
74
+ user: {
75
+ id: claims.sub,
76
+ name: claims.name ?? "",
77
+ email: claims.email ?? null,
78
+ avatar_url: claims.picture ?? null,
79
+ },
80
+ id_token: tokens.id_token,
81
+ auth_time: claims.auth_time,
82
+ };
83
+ const fits = store.fits(auth);
84
+ if (!fits.auth) return loginFailed(headers, 500);
85
+ const session = store.read(request);
86
+ // Without the ID token the session still works; only the logout then asks the user to confirm.
87
+ session.update({ auth: fits.idToken ? auth : { ...auth, id_token: undefined } });
88
+ for (const cookie of store.commit(session)) headers.append("Set-Cookie", cookie);
89
+ return redirect(safeReturnTo(transaction.return_to), headers);
90
+ } catch (error) {
91
+ if (!(error instanceof OidcError)) throw error;
92
+ return loginFailed(headers, error.reason === "unavailable" ? 503 : 400);
93
+ }
94
+ }
95
+ // #endregion callback
96
+
97
+ // #region logout
98
+ /** POST /logout, from a form of this app. */
99
+ export async function handleLogout(context: AuthContext, request: Request): Promise<Response> {
100
+ const { client, store } = context;
101
+ if (request.method !== "POST") return new Response(null, { status: 405, headers: { Allow: "POST" } });
102
+ // Another site must not be able to log the user out.
103
+ if (request.headers.get("Origin") !== context.appOrigin) return new Response(null, { status: 403 });
104
+
105
+ const session = store.read(request);
106
+ const auth = session.data.auth;
107
+ // Never rejects: a failed call to Plasgos is reported through onFailure and the logout goes on.
108
+ const result = await client.logout({
109
+ refreshToken: auth?.refresh_token,
110
+ idToken: auth?.id_token,
111
+ // clientIp: the address your reverse proxy vouches for, or null.
112
+ browser: { clientIp: null, userAgent: request.headers.get("User-Agent") },
113
+ });
114
+
115
+ session.destroy();
116
+ const headers = new Headers();
117
+ for (const cookie of store.commit(session)) headers.append("Set-Cookie", cookie);
118
+ if (result.kind !== "redirect") throw new Error('This app uses endSession "redirect"');
119
+ return redirect(result.location, headers, 303);
120
+ }
121
+ // #endregion logout
122
+
123
+ // #region fresh
124
+ /** The access token to use now, renewed when it is about to expire; null when nobody is signed in. */
125
+ async function freshAccessToken(
126
+ context: AuthContext,
127
+ session: SessionHandle<AppSession>,
128
+ force = false,
129
+ ): Promise<string | null> {
130
+ const current = session.data.auth;
131
+ if (current === undefined) return null;
132
+ const { auth, changed } = await context.client.ensureFresh(current, { force });
133
+ // Store a renewed auth at once: its refresh token replaced the old one at Plasgos.
134
+ if (changed) session.update({ auth });
135
+ return auth.access_token;
136
+ }
137
+
138
+ const isInvalidToken = (res: Response): boolean =>
139
+ res.status === 401 && (res.headers.get("WWW-Authenticate") ?? "").includes("invalid_token");
140
+
141
+ /** Calls a Plasgos API for the signed-in user and answers with its body. */
142
+ export async function callApi(context: AuthContext, request: Request, path: string): Promise<Response> {
143
+ const session = context.store.read(request);
144
+ /** Every answer carries the session cookies that changed, also an error answer. */
145
+ const respond = (body: ReadableStream<Uint8Array> | string | null, status: number, headers = new Headers()): Response => {
146
+ for (const cookie of context.store.commit(session)) headers.append("Set-Cookie", cookie);
147
+ headers.set("Cache-Control", "no-store");
148
+ return new Response(body, { status, headers });
149
+ };
150
+ const toLogin = (): Response => {
151
+ const { pathname, search } = new URL(request.url);
152
+ return respond(null, 302, new Headers({ Location: `/login?returnTo=${encodeURIComponent(pathname + search)}` }));
153
+ };
154
+ const call = (token: string): Promise<Response> =>
155
+ fetch(`${context.apiUrl}${path}`, { headers: { Authorization: `Bearer ${token}`, Accept: "application/json" } });
156
+
157
+ try {
158
+ let token = await freshAccessToken(context, session);
159
+ if (token === null) return toLogin();
160
+ let res = await call(token);
161
+ if (isInvalidToken(res)) {
162
+ // The API refused a token that looked valid: refresh once and try once more.
163
+ token = await freshAccessToken(context, session, true);
164
+ if (token === null) return toLogin();
165
+ res = await call(token);
166
+ }
167
+ return respond(res.body, res.status, new Headers({ "Content-Type": res.headers.get("Content-Type") ?? "application/json" }));
168
+ } catch (error) {
169
+ if (!(error instanceof OidcError)) throw error;
170
+ switch (error.reason) {
171
+ // The session is over at Plasgos: clear it here and send the user to login.
172
+ case "invalid_grant":
173
+ case "invalid_target":
174
+ case "missing":
175
+ session.update({ auth: undefined });
176
+ return toLogin();
177
+ // Plasgos did not answer and the access token has run out. The session is kept.
178
+ case "unavailable":
179
+ return respond("Layanan sedang tidak tersedia. Coba lagi sebentar.", 503);
180
+ // config_invalid and anything else: a bug to fix. The session is kept.
181
+ default:
182
+ return respond("Terjadi kesalahan.", 500);
183
+ }
184
+ }
185
+ }
186
+ // #endregion fresh
@@ -0,0 +1,48 @@
1
+ import { OidcError } from "@plasgos/oidc-client";
2
+ import type { OidcClient } from "@plasgos/oidc-client";
3
+ import type { SessionStore } from "@plasgos/oidc-client/session";
4
+
5
+ import type { AppSession } from "./session-store.js";
6
+
7
+ // #region start
8
+ /** GET /plasgos/connect: sends the seller to Plasgos to approve the connection. */
9
+ export function startConnect(client: OidcClient, store: SessionStore<AppSession>): Response {
10
+ const { location, transaction } = client.startLogin({ returnTo: "/settings/plasgos" });
11
+ return new Response(null, {
12
+ status: 302,
13
+ headers: {
14
+ Location: location,
15
+ "Set-Cookie": store.commitTransaction(transaction),
16
+ "Cache-Control": "no-store",
17
+ },
18
+ });
19
+ }
20
+ // #endregion start
21
+
22
+ // #region callback
23
+ /** The Plasgos account a seller connected. `subject` is stable for this client and differs per client. */
24
+ export interface ConnectedSeller {
25
+ subject: string;
26
+ name: string | null;
27
+ email: string | null;
28
+ }
29
+
30
+ /**
31
+ * GET /auth/callback: returns the connected seller, or null when the connection failed.
32
+ * Append `setCookie` to the response either way: it clears the single-use transaction cookie.
33
+ */
34
+ export async function finishConnect(
35
+ client: OidcClient,
36
+ store: SessionStore<AppSession>,
37
+ request: Request,
38
+ ): Promise<{ seller: ConnectedSeller | null; setCookie: string }> {
39
+ const setCookie = store.clearTransaction();
40
+ try {
41
+ const { claims } = await client.handleCallback(request.url, store.readTransaction(request));
42
+ return { seller: { subject: claims.sub, name: claims.name ?? null, email: claims.email ?? null }, setCookie };
43
+ } catch (error) {
44
+ if (!(error instanceof OidcError)) throw error;
45
+ return { seller: null, setCookie };
46
+ }
47
+ }
48
+ // #endregion callback
@@ -0,0 +1,60 @@
1
+ import { createOidcClient } from "@plasgos/oidc-client";
2
+ import type { OidcClient } from "@plasgos/oidc-client";
3
+ import { createServiceClient } from "@plasgos/oidc-client/service";
4
+ import { createSessionStore } from "@plasgos/oidc-client/session";
5
+ import type { SessionStore, SessionUser } from "@plasgos/oidc-client/session";
6
+
7
+ // #region login
8
+ export function createClient(): OidcClient {
9
+ return createOidcClient({
10
+ environment: "production",
11
+ issuer: "https://accounts.plasgos.co.id",
12
+ clientId: process.env.PLASGOS_LOGIN_CLIENT_ID ?? "",
13
+ clientSecret: process.env.PLASGOS_LOGIN_CLIENT_SECRET ?? "",
14
+ redirectUri: "https://app.example.com/auth/callback",
15
+ scopes: ["openid", "profile", "email"],
16
+ profile: "third-party",
17
+ });
18
+ }
19
+
20
+ /** GET /login: redirects the browser to Plasgos. */
21
+ export function login(client: OidcClient, store: SessionStore<object>): Response {
22
+ const { location, transaction } = client.startLogin({ returnTo: "/" });
23
+ const headers = { Location: location, "Set-Cookie": store.commitTransaction(transaction) };
24
+ return new Response(null, { status: 302, headers });
25
+ }
26
+ // #endregion login
27
+
28
+ // #region session
29
+ export function createStore(): SessionStore<object> {
30
+ return createSessionStore<object>({
31
+ environment: "production",
32
+ secrets: [process.env.SESSION_SECRET ?? ""],
33
+ hkdfSalt: "app-example",
34
+ cookies: { app: "ax", auth: "ax-auth", idToken: "ax-idt", transaction: "ax-oidc" },
35
+ authMaxAgeSeconds: 2_592_000,
36
+ // This app keeps no data of its own in the session, only the SDK's auth.
37
+ appSchema: { parse: () => ({}) },
38
+ });
39
+ }
40
+
41
+ /** The signed-in user of a request, or null. */
42
+ export function currentUser(store: SessionStore<object>, request: Request): SessionUser | null {
43
+ return store.read(request).data.auth?.user ?? null;
44
+ }
45
+ // #endregion session
46
+
47
+ // #region service
48
+ export async function whoAmI(): Promise<unknown> {
49
+ const plasgos = createServiceClient({
50
+ environment: "production",
51
+ issuer: "https://accounts.plasgos.co.id",
52
+ apiUrl: "https://api.plasgos.co.id",
53
+ clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? "",
54
+ clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? "",
55
+ scopes: ["platform:self.read"],
56
+ });
57
+ const res = await plasgos.fetch("/v5/service/me");
58
+ return res.json();
59
+ }
60
+ // #endregion service
@@ -0,0 +1,105 @@
1
+ import { OidcError, createServiceClient } from "@plasgos/oidc-client/service";
2
+ import type { ServiceClient } from "@plasgos/oidc-client/service";
3
+
4
+ import { readPlasgosEnv, readServiceCredentials } from "./env.js";
5
+ import { logFailure } from "./failure-log.js";
6
+
7
+ // #region create
8
+ /** Create it once at start and reuse it: the token cache lives in the client. */
9
+ export function createPlasgosClient(): ServiceClient {
10
+ const env = readPlasgosEnv();
11
+ const credentials = readServiceCredentials();
12
+ return createServiceClient({
13
+ environment: env.environment,
14
+ issuer: env.issuer,
15
+ apiUrl: env.apiUrl,
16
+ backchannelUrl: env.backchannelUrl,
17
+ clientId: credentials.clientId,
18
+ clientSecret: credentials.clientSecret,
19
+ scopes: ["platform:self.read", "payments:read", "payments:write"],
20
+ resource: credentials.audience,
21
+ onFailure: logFailure,
22
+ });
23
+ }
24
+ // #endregion create
25
+
26
+ // #region self-check
27
+ /** GET /v5/service/me: proves the credentials, the scope and the network path. Needs platform:self.read. */
28
+ export async function checkConnection(plasgos: ServiceClient): Promise<unknown> {
29
+ const res = await plasgos.fetch("/v5/service/me");
30
+ if (!res.ok) throw new Error(`Plasgos self check answered ${String(res.status)}`);
31
+ return res.json();
32
+ }
33
+ // #endregion self-check
34
+
35
+ // #region create-payment
36
+ export interface NewPayment {
37
+ /** Your own id of the bill. Sending the same body again returns the same payment (200, not 201). */
38
+ external_ref: string;
39
+ /** A payment purpose registered for your app, for example "subscription". */
40
+ purpose: string;
41
+ amount: { amount: number; currency: "IDR" };
42
+ customer: { name: string; email: string };
43
+ }
44
+
45
+ /** POST /v5/service/payments. Needs payments:write. */
46
+ export async function createPayment(plasgos: ServiceClient, payment: NewPayment): Promise<unknown> {
47
+ const res = await plasgos.fetch("/v5/service/payments", {
48
+ method: "POST",
49
+ headers: { "Content-Type": "application/json" },
50
+ body: JSON.stringify(payment),
51
+ });
52
+ if (!res.ok) throw new Error(`Plasgos payments answered ${String(res.status)}`);
53
+ return res.json();
54
+ }
55
+ // #endregion create-payment
56
+
57
+ // #region first-payment
58
+ /** A subscription bill of this app, paid through Plasgos. */
59
+ export function createSubscriptionPayment(
60
+ plasgos: ServiceClient,
61
+ bill: { id: string; amountRupiah: number; sellerName: string; sellerEmail: string },
62
+ ): Promise<unknown> {
63
+ return createPayment(plasgos, {
64
+ external_ref: bill.id,
65
+ purpose: "subscription",
66
+ amount: { amount: bill.amountRupiah, currency: "IDR" },
67
+ customer: { name: bill.sellerName, email: bill.sellerEmail },
68
+ });
69
+ }
70
+ // #endregion first-payment
71
+
72
+ // #region refund
73
+ /** POST /v5/service/payments/{pay_id}/refunds. Needs payments:refund and an Idempotency-Key. */
74
+ export async function refundPayment(
75
+ plasgos: ServiceClient,
76
+ paymentId: string,
77
+ amount: number,
78
+ idempotencyKey: string,
79
+ ): Promise<unknown> {
80
+ const res = await plasgos.fetch(`/v5/service/payments/${encodeURIComponent(paymentId)}/refunds`, {
81
+ method: "POST",
82
+ headers: { "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
83
+ body: JSON.stringify({ amount: { amount, currency: "IDR" } }),
84
+ });
85
+ if (!res.ok) throw new Error(`Plasgos refunds answered ${String(res.status)}`);
86
+ return res.json();
87
+ }
88
+ // #endregion refund
89
+
90
+ // #region errors
91
+ /** What to do when `getToken()` or `fetch()` rejects. Anything that is not an OidcError is rethrown. */
92
+ export function describeFailure(error: unknown): { retry: boolean; message: string } {
93
+ if (!(error instanceof OidcError)) throw error;
94
+ switch (error.reason) {
95
+ case "unavailable":
96
+ return { retry: true, message: "Plasgos did not answer in time; try again later" };
97
+ case "config_invalid":
98
+ return { retry: false, message: "client id, client secret or scopes are wrong; fix the configuration" };
99
+ case "invalid_target":
100
+ return { retry: false, message: "the resource (audience) is not the one of this environment" };
101
+ default:
102
+ return { retry: false, message: `Plasgos refused the token request (${error.reason})` };
103
+ }
104
+ }
105
+ // #endregion errors
@@ -0,0 +1,53 @@
1
+ import { createSessionStore } from "@plasgos/oidc-client/session";
2
+ import type { SessionSchema, SessionStore } from "@plasgos/oidc-client/session";
3
+
4
+ import { readEnvironment, readSessionSecrets } from "./env.js";
5
+
6
+ // #region app-schema
7
+ /** What this app keeps in its own cookie, next to the SDK's auth. Every field is optional. */
8
+ export interface AppSession {
9
+ flash?: string | undefined;
10
+ }
11
+
12
+ /** Returns the app data, or null when the cookie does not hold what this app wrote. */
13
+ export const appSchema: SessionSchema<AppSession> = {
14
+ parse(input) {
15
+ if (typeof input !== "object" || input === null) return null;
16
+ const flash: unknown = "flash" in input ? input.flash : undefined;
17
+ if (flash === undefined) return {};
18
+ return typeof flash === "string" && flash.length <= 200 ? { flash } : null;
19
+ },
20
+ };
21
+ // #endregion app-schema
22
+
23
+ // #region store
24
+ /** Create it once at start. */
25
+ export function createAppSessionStore(): SessionStore<AppSession> {
26
+ return createSessionStore<AppSession>({
27
+ environment: readEnvironment(),
28
+ secrets: readSessionSecrets(),
29
+ // Never change the salt or the names after the first release: the cookie keys are derived from them.
30
+ hkdfSalt: "contoh-app",
31
+ cookies: { app: "ca", auth: "ca-auth", idToken: "ca-idt", transaction: "ca-oidc" },
32
+ authMaxAgeSeconds: 2_592_000,
33
+ appSchema,
34
+ });
35
+ }
36
+ // #endregion store
37
+
38
+ // #region zod-adapter
39
+ /** The part of a zod schema the adapter uses. */
40
+ interface SafeParser<T> {
41
+ safeParse(input: unknown): { success: true; data: T } | { success: false };
42
+ }
43
+
44
+ /** Wraps a zod object schema: `appSchema: fromZod(z.object({ flash: z.string().max(200).optional() }))`. */
45
+ export function fromZod<T>(schema: SafeParser<T>): SessionSchema<T> {
46
+ return {
47
+ parse(input) {
48
+ const result = schema.safeParse(input);
49
+ return result.success ? result.data : null;
50
+ },
51
+ };
52
+ }
53
+ // #endregion zod-adapter
@@ -0,0 +1,46 @@
1
+ import type { WebhookVerifier } from "@plasgos/auth-verify/webhook";
2
+ import express from "express";
3
+ import type { Express, NextFunction, Request, Response } from "express";
4
+
5
+ import { handleWebhook } from "./webhook-verifier.js";
6
+ import type { ApplyEvent, WithTransaction } from "./webhook-verifier.js";
7
+
8
+ // #region route
9
+ /**
10
+ * Errors of the webhook route as JSON without a stack trace: 413 for a body over the `limit` of
11
+ * express.raw, 500 for anything else.
12
+ */
13
+ function webhookErrors(error: unknown, _req: Request, res: Response, next: NextFunction): void {
14
+ if (res.headersSent) {
15
+ next(error);
16
+ return;
17
+ }
18
+ const tooLarge = typeof error === "object" && error !== null && "type" in error && error.type === "entity.too.large";
19
+ if (tooLarge) res.status(413).json({ error: "payload_too_large" });
20
+ else res.status(500).json({ error: "processing_failed" });
21
+ }
22
+
23
+ export function createApp(verifier: WebhookVerifier, withTransaction: WithTransaction, apply: ApplyEvent): Express {
24
+ const app = express();
25
+
26
+ // The raw body on this route only, registered before the global express.json() below.
27
+ // `limit` protects memory: a larger body is answered 413 before it is held in full.
28
+ const rawJson = express.raw({ type: "application/json", limit: "1mb" });
29
+ app.post("/webhooks/plasgos", rawJson, (req, res, next) => {
30
+ const rawBody: unknown = req.body;
31
+ if (!Buffer.isBuffer(rawBody)) {
32
+ res.status(415).json({ error: "unsupported_media_type" });
33
+ return;
34
+ }
35
+ handleWebhook(verifier, withTransaction, apply, { headers: req.headers, rawBody })
36
+ .then((answer) => res.status(answer.status).json(answer.body))
37
+ .catch(next);
38
+ });
39
+ // Registered after the route and before express.json(): errors of the webhook route end here.
40
+ app.use("/webhooks/plasgos", webhookErrors);
41
+
42
+ app.use(express.json());
43
+ // ... the other routes of the app
44
+ return app;
45
+ }
46
+ // #endregion route
@@ -0,0 +1,60 @@
1
+ import type { WebhookVerifier } from "@plasgos/auth-verify/webhook";
2
+
3
+ import { handleWebhook } from "./webhook-verifier.js";
4
+ import type { ApplyEvent, WithTransaction } from "./webhook-verifier.js";
5
+
6
+ // #region read-body
7
+ /** 1 MiB. Plasgos webhooks are far smaller. */
8
+ const MAX_BODY_BYTES = 1_048_576;
9
+
10
+ /**
11
+ * The raw body as bytes, or null when it is larger than `maxBytes`. Reads chunk by chunk and stops as
12
+ * soon as the count passes the cap, so a missing or false content-length never fills memory.
13
+ */
14
+ export async function readRawBody(request: Request, maxBytes = MAX_BODY_BYTES): Promise<Uint8Array | null> {
15
+ if (Number(request.headers.get("content-length") ?? "0") > maxBytes) return null;
16
+ if (request.body === null) return new Uint8Array(0);
17
+
18
+ const reader = request.body.getReader();
19
+ const chunks: Uint8Array[] = [];
20
+ let total = 0;
21
+ for (;;) {
22
+ const result: { done: boolean; value?: unknown } = await reader.read();
23
+ if (result.done) break;
24
+ const chunk = result.value;
25
+ if (!(chunk instanceof Uint8Array)) {
26
+ await reader.cancel();
27
+ throw new TypeError("request body must be a byte stream");
28
+ }
29
+ total += chunk.byteLength;
30
+ if (total > maxBytes) {
31
+ await reader.cancel();
32
+ return null;
33
+ }
34
+ chunks.push(chunk);
35
+ }
36
+
37
+ const body = new Uint8Array(total);
38
+ let offset = 0;
39
+ for (const chunk of chunks) {
40
+ body.set(chunk, offset);
41
+ offset += chunk.byteLength;
42
+ }
43
+ return body;
44
+ }
45
+ // #endregion read-body
46
+
47
+ // #region route
48
+ /** POST /webhooks/plasgos. A React Router `action({ request })` can return it as is. */
49
+ export async function webhookRoute(
50
+ request: Request,
51
+ verifier: WebhookVerifier,
52
+ withTransaction: WithTransaction,
53
+ apply: ApplyEvent,
54
+ ): Promise<Response> {
55
+ const rawBody = await readRawBody(request);
56
+ if (rawBody === null) return Response.json({ error: "payload_too_large" }, { status: 413 });
57
+ const answer = await handleWebhook(verifier, withTransaction, apply, { headers: request.headers, rawBody });
58
+ return Response.json(answer.body, { status: answer.status });
59
+ }
60
+ // #endregion route
@@ -0,0 +1,59 @@
1
+ import { Controller, Inject, Module, Post, Req, Res } from "@nestjs/common";
2
+ import type { DynamicModule, RawBodyRequest, Type } from "@nestjs/common";
3
+ import { NestFactory } from "@nestjs/core";
4
+ import type { WebhookVerifier } from "@plasgos/auth-verify/webhook";
5
+ import type { Request, Response } from "express";
6
+
7
+ import { createPaymentsWebhookVerifier, handleWebhook } from "./webhook-verifier.js";
8
+ import type { ApplyEvent, WebhookAnswer, WithTransaction } from "./webhook-verifier.js";
9
+
10
+ // #region bootstrap
11
+ export async function bootstrap(appModule: Type, port: number): Promise<void> {
12
+ // rawBody: true keeps the raw bytes in req.rawBody, next to the parsed body.
13
+ const app = await NestFactory.create(appModule, { rawBody: true });
14
+ await app.listen(port);
15
+ }
16
+ // #endregion bootstrap
17
+
18
+ // #region controller
19
+ export const PLASGOS_WEBHOOK = "PLASGOS_WEBHOOK";
20
+
21
+ export interface WebhookDeps {
22
+ verifier: WebhookVerifier;
23
+ withTransaction: WithTransaction;
24
+ apply: ApplyEvent;
25
+ }
26
+
27
+ @Controller("webhooks")
28
+ export class PlasgosWebhookController {
29
+ constructor(@Inject(PLASGOS_WEBHOOK) private readonly deps: WebhookDeps) {}
30
+
31
+ @Post("plasgos")
32
+ async receive(
33
+ @Req() req: RawBodyRequest<Request>,
34
+ @Res({ passthrough: true }) res: Response,
35
+ ): Promise<WebhookAnswer["body"]> {
36
+ if (req.rawBody === undefined) {
37
+ res.status(415);
38
+ return { error: "unsupported_media_type" };
39
+ }
40
+ const { verifier, withTransaction, apply } = this.deps;
41
+ const answer = await handleWebhook(verifier, withTransaction, apply, { headers: req.headers, rawBody: req.rawBody });
42
+ res.status(answer.status);
43
+ return answer.body;
44
+ }
45
+ }
46
+
47
+ @Module({})
48
+ export class PlasgosWebhookModule {
49
+ /** `withTransaction` and `apply` come from the app's database layer. */
50
+ static register(deps: Omit<WebhookDeps, "verifier">): DynamicModule {
51
+ return {
52
+ module: PlasgosWebhookModule,
53
+ controllers: [PlasgosWebhookController],
54
+ // The verifier is created at bootstrap: a wrong option stops the app with one ConfigError.
55
+ providers: [{ provide: PLASGOS_WEBHOOK, useFactory: (): WebhookDeps => ({ ...deps, verifier: createPaymentsWebhookVerifier() }) }],
56
+ };
57
+ }
58
+ }
59
+ // #endregion controller
@@ -0,0 +1,60 @@
1
+ import { createHmac } from "node:crypto";
2
+
3
+ import { presets } from "@plasgos/auth-verify/webhook";
4
+ import type { WebhookPreset } from "@plasgos/auth-verify/webhook";
5
+
6
+ // #region sign
7
+ /** An event body as Plasgos sends it. `id` and `type` also go into the headers. */
8
+ export interface TestEvent {
9
+ id: string;
10
+ type: string;
11
+ [field: string]: unknown;
12
+ }
13
+
14
+ /**
15
+ * A delivery signed the way Plasgos signs one: `v1=` + hex HMAC-SHA256 of "<timestamp>.<raw body>".
16
+ * Use a test secret that your app under test also reads from its env, never a real one.
17
+ */
18
+ export function signTestDelivery(
19
+ secret: string,
20
+ event: TestEvent,
21
+ preset: WebhookPreset = presets.payments,
22
+ nowMs: number = Date.now(),
23
+ ): { headers: Record<string, string>; body: string } {
24
+ const body = JSON.stringify(event);
25
+ const timestamp = String(Math.floor(nowMs / 1000));
26
+ const signature = createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
27
+ return {
28
+ body,
29
+ headers: {
30
+ "content-type": "application/json",
31
+ [preset.headers.id]: event.id,
32
+ [preset.headers.type]: event.type,
33
+ [preset.headers.timestamp]: timestamp,
34
+ [preset.headers.signature]: `v1=${signature}`,
35
+ },
36
+ };
37
+ }
38
+ // #endregion sign
39
+
40
+ // #region route-test
41
+ /** Your running route accepts a signed delivery and refuses the same delivery with a changed body. */
42
+ export async function checkWebhookRoute(url: string, secret: string): Promise<void> {
43
+ const event: TestEvent = {
44
+ id: "whd_test_1",
45
+ type: "payment.paid",
46
+ sequence: 1,
47
+ occurred_at: new Date().toISOString(),
48
+ subject: { type: "payment", id: "pay_test_1" },
49
+ data: {},
50
+ };
51
+ const signed = signTestDelivery(secret, event);
52
+
53
+ const accepted = await fetch(url, { method: "POST", headers: signed.headers, body: signed.body });
54
+ if (accepted.status !== 200) throw new Error(`signed delivery answered ${String(accepted.status)}`);
55
+
56
+ const tampered = signed.body.replace("pay_test_1", "pay_test_2");
57
+ const refused = await fetch(url, { method: "POST", headers: signed.headers, body: tampered });
58
+ if (refused.status !== 401) throw new Error(`tampered delivery answered ${String(refused.status)}`);
59
+ }
60
+ // #endregion route-test