@plasgos/auth-verify 0.0.0-stage → 0.1.0-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/LICENSE +15 -0
- package/README.md +122 -2
- package/THIRD_PARTY_NOTICES.md +31 -0
- package/dist/express.cjs +157 -0
- package/dist/express.cjs.map +1 -0
- package/dist/express.d.cts +90 -0
- package/dist/express.d.ts +90 -0
- package/dist/express.js +127 -0
- package/dist/express.js.map +1 -0
- package/dist/index.cjs +1254 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +67 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.js +499 -0
- package/dist/index.js.map +1 -0
- package/dist/nestjs.cjs +1395 -0
- package/dist/nestjs.cjs.map +1 -0
- package/dist/nestjs.d.cts +153 -0
- package/dist/nestjs.d.ts +153 -0
- package/dist/nestjs.js +637 -0
- package/dist/nestjs.js.map +1 -0
- package/dist/types-CGtRnj59.d.cts +193 -0
- package/dist/types-CGtRnj59.d.ts +193 -0
- package/dist/webhook.cjs +296 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +196 -0
- package/dist/webhook.d.ts +196 -0
- package/dist/webhook.js +265 -0
- package/dist/webhook.js.map +1 -0
- package/docs/bff-express.md +1314 -0
- package/docs/consumers.md +98 -0
- package/docs/contoh-hitungcuan.md +255 -0
- package/docs/contoh-plaslink.md +244 -0
- package/docs/error.md +613 -0
- package/docs/examples/auth-verify-readme.ts +42 -0
- package/docs/examples/bff-express.ts +370 -0
- package/docs/examples/bff-proxy.ts +335 -0
- package/docs/examples/bff-redis-lock.ts +187 -0
- package/docs/examples/bff-revocation.ts +136 -0
- package/docs/examples/config-error.ts +24 -0
- package/docs/examples/env.ts +150 -0
- package/docs/examples/failure-log.ts +18 -0
- package/docs/examples/login-client.ts +46 -0
- package/docs/examples/login-flow.ts +186 -0
- package/docs/examples/plaslink-connect.ts +48 -0
- package/docs/examples/readme.ts +60 -0
- package/docs/examples/service-client.ts +105 -0
- package/docs/examples/session-store.ts +53 -0
- package/docs/examples/token-commonjs.cjs +95 -0
- package/docs/examples/token-express.ts +56 -0
- package/docs/examples/token-fetch.ts +24 -0
- package/docs/examples/token-nestjs-jest.ts +77 -0
- package/docs/examples/token-nestjs.ts +127 -0
- package/docs/examples/token-socket.ts +59 -0
- package/docs/examples/token-testing.ts +100 -0
- package/docs/examples/token-verifier.ts +132 -0
- package/docs/examples/user-events.ts +110 -0
- package/docs/examples/webhook-express.ts +46 -0
- package/docs/examples/webhook-fetch.ts +60 -0
- package/docs/examples/webhook-nestjs.ts +59 -0
- package/docs/examples/webhook-testing.ts +60 -0
- package/docs/examples/webhook-verifier.ts +197 -0
- package/docs/login-web.md +650 -0
- package/docs/memulai.md +419 -0
- package/docs/server-ke-server.md +287 -0
- package/docs/verifikasi-token.md +1219 -0
- package/docs/webhook.md +810 -0
- package/package.json +101 -3
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { VerifiedWebhook } from "@plasgos/auth-verify/webhook";
|
|
2
|
+
|
|
3
|
+
import { revocationKeys } from "./token-verifier.js";
|
|
4
|
+
import type { ApplyEvent, Tx } from "./webhook-verifier.js";
|
|
5
|
+
|
|
6
|
+
// #region user-events
|
|
7
|
+
/** The Redis commands the marker writer uses. An ioredis client fits it. */
|
|
8
|
+
export interface MarkerRedis {
|
|
9
|
+
eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
|
|
10
|
+
set(key: string, value: string, mode: "EX", seconds: number): Promise<unknown>;
|
|
11
|
+
set(key: string, value: string): Promise<unknown>;
|
|
12
|
+
del(key: string): Promise<number>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The credential-version and session markers live 1 hour: much longer than a Plasgos access token, so
|
|
17
|
+
* every token issued before the event has expired before its marker does.
|
|
18
|
+
*/
|
|
19
|
+
export const MARKER_TTL_SECONDS = 3_600;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Stores the larger of the stored and the new credential version (compare-and-set in one Redis step).
|
|
23
|
+
* Events of one user can arrive out of order; a plain SET could lower the version and let a revoked
|
|
24
|
+
* token through again.
|
|
25
|
+
*/
|
|
26
|
+
const RAISE_TO_MAX = `
|
|
27
|
+
local current = tonumber(redis.call("GET", KEYS[1]))
|
|
28
|
+
if current == nil or tonumber(ARGV[1]) > current then
|
|
29
|
+
redis.call("SET", KEYS[1], ARGV[1], "EX", tonumber(ARGV[2]))
|
|
30
|
+
end
|
|
31
|
+
return 0`;
|
|
32
|
+
|
|
33
|
+
/** The user.* event data, the published contract of the app events (`data` of the event body). */
|
|
34
|
+
interface UserEventData {
|
|
35
|
+
/** The user's public id (`usr-…`), the same value as the token's plasgos_public_id. */
|
|
36
|
+
user: string;
|
|
37
|
+
/** user.credentials_revoked: the user's new credential version (the token claim `cv`). */
|
|
38
|
+
credential_version?: number;
|
|
39
|
+
/** user.session_revoked: the revoked Plasgos session, the same value as the token claim `sid`. */
|
|
40
|
+
sid?: string;
|
|
41
|
+
/** user.status_changed: active, pending, suspended, banned or unlinked. */
|
|
42
|
+
status?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const isText = (value: unknown): value is string => typeof value === "string" && value !== "" && value.length <= 128;
|
|
46
|
+
|
|
47
|
+
/** The event's `data`, checked. A malformed one throws: the delivery fails (500) and Plasgos sends it again. */
|
|
48
|
+
function userDataOf(event: VerifiedWebhook): UserEventData {
|
|
49
|
+
const data = event.body["data"];
|
|
50
|
+
if (typeof data !== "object" || data === null) throw new Error(`user event ${event.id}: data is not an object`);
|
|
51
|
+
const fields = data as Record<string, unknown>;
|
|
52
|
+
const user = fields["user"];
|
|
53
|
+
if (!isText(user)) throw new Error(`user event ${event.id}: data.user is missing`);
|
|
54
|
+
const version = fields["credential_version"];
|
|
55
|
+
const sid = fields["sid"];
|
|
56
|
+
const status = fields["status"];
|
|
57
|
+
return {
|
|
58
|
+
user,
|
|
59
|
+
...(typeof version === "number" && Number.isSafeInteger(version) ? { credential_version: version } : {}),
|
|
60
|
+
...(isText(sid) ? { sid } : {}),
|
|
61
|
+
...(isText(status) ? { status } : {}),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The `user` handler of routeByType (webhook.md §6): writes the revocation markers that isRevoked reads.
|
|
67
|
+
* - user.credentials_revoked → the credential version, stored as the maximum, TTL 1 hour;
|
|
68
|
+
* - user.session_revoked → the session marker, TTL 1 hour;
|
|
69
|
+
* - user.status_changed → the status is persisted in the app's database (same transaction as the
|
|
70
|
+
* event id) and cached in Redis: any status other than "active" sets the blocked marker, "active"
|
|
71
|
+
* removes it. Refill the blocked markers from the database if your Redis can lose its data.
|
|
72
|
+
* A user.* type the app does not know has no effect.
|
|
73
|
+
*/
|
|
74
|
+
export function userEventHandler(redis: MarkerRedis): ApplyEvent {
|
|
75
|
+
return async (tx: Tx, event: VerifiedWebhook) => {
|
|
76
|
+
const data = userDataOf(event);
|
|
77
|
+
switch (event.type) {
|
|
78
|
+
case "user.credentials_revoked": {
|
|
79
|
+
if (data.credential_version === undefined) throw new Error(`user event ${event.id}: data.credential_version is missing`);
|
|
80
|
+
const key = revocationKeys.credentialVersion(data.user);
|
|
81
|
+
await redis.eval(RAISE_TO_MAX, 1, key, data.credential_version, MARKER_TTL_SECONDS);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
case "user.session_revoked": {
|
|
85
|
+
if (data.sid === undefined) throw new Error(`user event ${event.id}: data.sid is missing`);
|
|
86
|
+
await redis.set(revocationKeys.session(data.sid), "1", "EX", MARKER_TTL_SECONDS);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
case "user.status_changed": {
|
|
90
|
+
if (data.status === undefined) throw new Error(`user event ${event.id}: data.status is missing`);
|
|
91
|
+
// The lasting record. sequence keeps an older event from overwriting a newer status.
|
|
92
|
+
const sequence = typeof event.body["sequence"] === "number" ? event.body["sequence"] : 0;
|
|
93
|
+
const stored = await tx.query(
|
|
94
|
+
`INSERT INTO plasgos_user_status (public_id, status, sequence) VALUES ($1, $2, $3)
|
|
95
|
+
ON CONFLICT (public_id) DO UPDATE SET status = EXCLUDED.status, sequence = EXCLUDED.sequence
|
|
96
|
+
WHERE plasgos_user_status.sequence < EXCLUDED.sequence`,
|
|
97
|
+
[data.user, data.status, sequence],
|
|
98
|
+
);
|
|
99
|
+
if (stored.rowCount !== 1) return;
|
|
100
|
+
// The cache isRevoked reads, without an expiry: it holds as long as the user is blocked.
|
|
101
|
+
if (data.status === "active") await redis.del(revocationKeys.blockedUser(data.user));
|
|
102
|
+
else await redis.set(revocationKeys.blockedUser(data.user), data.status);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
default:
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
// #endregion user-events
|
|
@@ -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
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { WebhookVerifyError, createWebhookVerifier, presets } from "@plasgos/auth-verify/webhook";
|
|
2
|
+
import type {
|
|
3
|
+
VerifiedWebhook,
|
|
4
|
+
WebhookDedupStore,
|
|
5
|
+
WebhookVerifier,
|
|
6
|
+
WebhookVerifyInput,
|
|
7
|
+
} from "@plasgos/auth-verify/webhook";
|
|
8
|
+
|
|
9
|
+
import { readEnvironment, readWebhookSecrets } from "./env.js";
|
|
10
|
+
|
|
11
|
+
// #region create
|
|
12
|
+
/** Payments webhooks. Create it once at start: a wrong option throws one ConfigError there. */
|
|
13
|
+
export function createPaymentsWebhookVerifier(): WebhookVerifier {
|
|
14
|
+
return createWebhookVerifier({
|
|
15
|
+
environment: readEnvironment(),
|
|
16
|
+
secrets: readWebhookSecrets("PLASGOS_WEBHOOK_SECRET"),
|
|
17
|
+
preset: presets.payments,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
// #endregion create
|
|
21
|
+
|
|
22
|
+
// #region create-shipping
|
|
23
|
+
/** Plaslink shipping webhooks: other header names and a secret of their own. */
|
|
24
|
+
export function createShippingWebhookVerifier(): WebhookVerifier {
|
|
25
|
+
return createWebhookVerifier({
|
|
26
|
+
environment: readEnvironment(),
|
|
27
|
+
secrets: readWebhookSecrets("PLASGOS_SHIPPING_WEBHOOK_SECRET"),
|
|
28
|
+
preset: presets.plaslinkShipping,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
// #endregion create-shipping
|
|
32
|
+
|
|
33
|
+
// #region create-app-events
|
|
34
|
+
/**
|
|
35
|
+
* Every event Plasgos sends to the app's webhook endpoint (payments, subscriptions, add-ons, packages,
|
|
36
|
+
* users), with one secret. Same headers and signature as presets.payments; the result's preset reads "appEvents".
|
|
37
|
+
*/
|
|
38
|
+
export function createAppEventsWebhookVerifier(): WebhookVerifier {
|
|
39
|
+
return createWebhookVerifier({
|
|
40
|
+
environment: readEnvironment(),
|
|
41
|
+
secrets: readWebhookSecrets("PLASGOS_WEBHOOK_SECRET"),
|
|
42
|
+
preset: presets.appEvents,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
// #endregion create-app-events
|
|
46
|
+
|
|
47
|
+
// #region dedup
|
|
48
|
+
/** The part of a database transaction this example needs. Your driver's transaction object fits it. */
|
|
49
|
+
export interface Tx {
|
|
50
|
+
query(sql: string, params: readonly unknown[]): Promise<{ rowCount: number | null }>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Runs `fn` in one transaction: commits when it resolves, rolls back when it throws. */
|
|
54
|
+
export type WithTransaction = <T>(fn: (tx: Tx) => Promise<T>) => Promise<T>;
|
|
55
|
+
|
|
56
|
+
/** Keeps the event id in the same transaction that applies the event's effect. */
|
|
57
|
+
export const dedup: WebhookDedupStore<Tx> = {
|
|
58
|
+
async saveOnce(tx, event) {
|
|
59
|
+
const result = await tx.query(
|
|
60
|
+
"INSERT INTO plasgos_webhook_events (event_id, event_type) VALUES ($1, $2) ON CONFLICT (event_id) DO NOTHING",
|
|
61
|
+
[event.id, event.type],
|
|
62
|
+
);
|
|
63
|
+
return result.rowCount === 1;
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
// #endregion dedup
|
|
67
|
+
|
|
68
|
+
// #region with-transaction
|
|
69
|
+
/** A connection pool that hands out one connection per transaction. node-postgres' `Pool` fits it. */
|
|
70
|
+
export interface TxPool {
|
|
71
|
+
connect(): Promise<Tx & { release(): void }>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** `WithTransaction` over a pool: BEGIN, then COMMIT when `fn` resolves or ROLLBACK when it throws. */
|
|
75
|
+
export function transactions(pool: TxPool): WithTransaction {
|
|
76
|
+
return async (fn) => {
|
|
77
|
+
const client = await pool.connect();
|
|
78
|
+
try {
|
|
79
|
+
await client.query("BEGIN", []);
|
|
80
|
+
const result = await fn(client);
|
|
81
|
+
await client.query("COMMIT", []);
|
|
82
|
+
return result;
|
|
83
|
+
} catch (error) {
|
|
84
|
+
await client.query("ROLLBACK", []);
|
|
85
|
+
throw error;
|
|
86
|
+
} finally {
|
|
87
|
+
client.release();
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
// #endregion with-transaction
|
|
92
|
+
|
|
93
|
+
// #region handle
|
|
94
|
+
/** What the route answers. Each framework example turns it into its own response. */
|
|
95
|
+
export interface WebhookAnswer {
|
|
96
|
+
status: number;
|
|
97
|
+
body: { ok: true } | { error: string };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The business effect of one event. Runs in the same transaction as `saveOnce`. */
|
|
101
|
+
export type ApplyEvent = (tx: Tx, event: VerifiedWebhook) => Promise<void>;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* One delivery. Plasgos counts every answer other than 2xx (400, 401 and redirects too) as a failed
|
|
105
|
+
* attempt and sends it again later. Answer within about 10 seconds: heavy work goes to an inbox
|
|
106
|
+
* table that a worker processes later.
|
|
107
|
+
*/
|
|
108
|
+
export async function handleWebhook(
|
|
109
|
+
verifier: WebhookVerifier,
|
|
110
|
+
withTransaction: WithTransaction,
|
|
111
|
+
apply: ApplyEvent,
|
|
112
|
+
input: WebhookVerifyInput,
|
|
113
|
+
): Promise<WebhookAnswer> {
|
|
114
|
+
let event: VerifiedWebhook;
|
|
115
|
+
try {
|
|
116
|
+
event = verifier.verify(input);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (!(error instanceof WebhookVerifyError)) throw error;
|
|
119
|
+
// reason and header never hold a secret, a signature or a header value: safe to log.
|
|
120
|
+
const header = error.header ?? "-";
|
|
121
|
+
process.stderr.write(`plasgos webhook refused: preset=${verifier.preset} reason=${error.reason} header=${header}\n`);
|
|
122
|
+
const status = error.reason === "signature_mismatch" || error.reason === "stale_timestamp" ? 401 : 400;
|
|
123
|
+
return { status, body: { error: error.reason } };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
await withTransaction(async (tx) => {
|
|
128
|
+
// false: a redelivery of an event that is already processed. Commit and do nothing else.
|
|
129
|
+
if (!(await dedup.saveOnce(tx, event))) return;
|
|
130
|
+
await apply(tx, event);
|
|
131
|
+
});
|
|
132
|
+
} catch {
|
|
133
|
+
// Rolled back, the event id too: Plasgos sends the event again and it is processed then.
|
|
134
|
+
process.stderr.write(`plasgos webhook failed: preset=${verifier.preset} id=${event.id} type=${event.type}\n`);
|
|
135
|
+
return { status: 500, body: { error: "processing_failed" } };
|
|
136
|
+
}
|
|
137
|
+
// Committed: only now answer 2xx.
|
|
138
|
+
return { status: 200, body: { ok: true } };
|
|
139
|
+
}
|
|
140
|
+
// #endregion handle
|
|
141
|
+
|
|
142
|
+
// #region apply-paid
|
|
143
|
+
/** The payment id (`pay_…`) of a payments event, or null. */
|
|
144
|
+
function paymentId(event: VerifiedWebhook): string | null {
|
|
145
|
+
const subject = event.body.subject;
|
|
146
|
+
if (typeof subject !== "object" || subject === null || !("id" in subject)) return null;
|
|
147
|
+
return typeof subject.id === "string" ? subject.id : null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Marks the bill paid from a verified payment.paid, in the transaction of saveOnce. Other types are only recorded. */
|
|
151
|
+
export const applyPaymentEvent: ApplyEvent = async (tx, event) => {
|
|
152
|
+
if (event.type !== "payment.paid") return;
|
|
153
|
+
const payment = paymentId(event);
|
|
154
|
+
if (payment === null) throw new Error(`payment.paid ${event.id} has no subject id`);
|
|
155
|
+
await tx.query("UPDATE bills SET status = 'paid', paid_at = now() WHERE payment_id = $1 AND status <> 'paid'", [payment]);
|
|
156
|
+
};
|
|
157
|
+
// #endregion apply-paid
|
|
158
|
+
|
|
159
|
+
// #region route-by-type
|
|
160
|
+
/** The app's own effect for each event family. Each one runs in the transaction of saveOnce. */
|
|
161
|
+
export interface AppEventHandlers {
|
|
162
|
+
/** payment.* */
|
|
163
|
+
payment: ApplyEvent;
|
|
164
|
+
/** subscription.*, entitlements.* and addon.* */
|
|
165
|
+
subscription: ApplyEvent;
|
|
166
|
+
/** package.* */
|
|
167
|
+
package: ApplyEvent;
|
|
168
|
+
/** user.* */
|
|
169
|
+
user: ApplyEvent;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The `apply` of handleWebhook for an appEvents endpoint: it runs after saveOnce(tx, event) stored a new
|
|
174
|
+
* event and hands the event to the handler of its family. A type the app does not know has no effect:
|
|
175
|
+
* handleWebhook commits the event id and answers 2xx, so a new event type never blocks the queue.
|
|
176
|
+
*/
|
|
177
|
+
export function routeByType(handlers: AppEventHandlers): ApplyEvent {
|
|
178
|
+
return async (tx, event) => {
|
|
179
|
+
const family = event.type.split(".", 1)[0];
|
|
180
|
+
switch (family) {
|
|
181
|
+
case "payment":
|
|
182
|
+
return handlers.payment(tx, event);
|
|
183
|
+
case "subscription":
|
|
184
|
+
case "entitlements":
|
|
185
|
+
case "addon":
|
|
186
|
+
return handlers.subscription(tx, event);
|
|
187
|
+
case "package":
|
|
188
|
+
return handlers.package(tx, event);
|
|
189
|
+
case "user":
|
|
190
|
+
return handlers.user(tx, event);
|
|
191
|
+
default:
|
|
192
|
+
// Unknown type: no effect. The id is still stored, so a redelivery is not processed either.
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
// #endregion route-by-type
|