@plasgos/auth-verify 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.
@@ -0,0 +1,143 @@
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 dedup
34
+ /** The part of a database transaction this example needs. Your driver's transaction object fits it. */
35
+ export interface Tx {
36
+ query(sql: string, params: readonly unknown[]): Promise<{ rowCount: number | null }>;
37
+ }
38
+
39
+ /** Runs `fn` in one transaction: commits when it resolves, rolls back when it throws. */
40
+ export type WithTransaction = <T>(fn: (tx: Tx) => Promise<T>) => Promise<T>;
41
+
42
+ /** Keeps the event id in the same transaction that applies the event's effect. */
43
+ export const dedup: WebhookDedupStore<Tx> = {
44
+ async saveOnce(tx, event) {
45
+ const result = await tx.query(
46
+ "INSERT INTO plasgos_webhook_events (event_id, event_type) VALUES ($1, $2) ON CONFLICT (event_id) DO NOTHING",
47
+ [event.id, event.type],
48
+ );
49
+ return result.rowCount === 1;
50
+ },
51
+ };
52
+ // #endregion dedup
53
+
54
+ // #region with-transaction
55
+ /** A connection pool that hands out one connection per transaction. node-postgres' `Pool` fits it. */
56
+ export interface TxPool {
57
+ connect(): Promise<Tx & { release(): void }>;
58
+ }
59
+
60
+ /** `WithTransaction` over a pool: BEGIN, then COMMIT when `fn` resolves or ROLLBACK when it throws. */
61
+ export function transactions(pool: TxPool): WithTransaction {
62
+ return async (fn) => {
63
+ const client = await pool.connect();
64
+ try {
65
+ await client.query("BEGIN", []);
66
+ const result = await fn(client);
67
+ await client.query("COMMIT", []);
68
+ return result;
69
+ } catch (error) {
70
+ await client.query("ROLLBACK", []);
71
+ throw error;
72
+ } finally {
73
+ client.release();
74
+ }
75
+ };
76
+ }
77
+ // #endregion with-transaction
78
+
79
+ // #region handle
80
+ /** What the route answers. Each framework example turns it into its own response. */
81
+ export interface WebhookAnswer {
82
+ status: number;
83
+ body: { ok: true } | { error: string };
84
+ }
85
+
86
+ /** The business effect of one event. Runs in the same transaction as `saveOnce`. */
87
+ export type ApplyEvent = (tx: Tx, event: VerifiedWebhook) => Promise<void>;
88
+
89
+ /**
90
+ * One delivery. Plasgos counts every answer other than 2xx (400, 401 and redirects too) as a failed
91
+ * attempt and sends it again later. Answer within about 10 seconds: heavy work goes to an inbox
92
+ * table that a worker processes later.
93
+ */
94
+ export async function handleWebhook(
95
+ verifier: WebhookVerifier,
96
+ withTransaction: WithTransaction,
97
+ apply: ApplyEvent,
98
+ input: WebhookVerifyInput,
99
+ ): Promise<WebhookAnswer> {
100
+ let event: VerifiedWebhook;
101
+ try {
102
+ event = verifier.verify(input);
103
+ } catch (error) {
104
+ if (!(error instanceof WebhookVerifyError)) throw error;
105
+ // reason and header never hold a secret, a signature or a header value: safe to log.
106
+ const header = error.header ?? "-";
107
+ process.stderr.write(`plasgos webhook refused: preset=${verifier.preset} reason=${error.reason} header=${header}\n`);
108
+ const status = error.reason === "signature_mismatch" || error.reason === "stale_timestamp" ? 401 : 400;
109
+ return { status, body: { error: error.reason } };
110
+ }
111
+
112
+ try {
113
+ await withTransaction(async (tx) => {
114
+ // false: a redelivery of an event that is already processed. Commit and do nothing else.
115
+ if (!(await dedup.saveOnce(tx, event))) return;
116
+ await apply(tx, event);
117
+ });
118
+ } catch {
119
+ // Rolled back, the event id too: Plasgos sends the event again and it is processed then.
120
+ process.stderr.write(`plasgos webhook failed: preset=${verifier.preset} id=${event.id} type=${event.type}\n`);
121
+ return { status: 500, body: { error: "processing_failed" } };
122
+ }
123
+ // Committed: only now answer 2xx.
124
+ return { status: 200, body: { ok: true } };
125
+ }
126
+ // #endregion handle
127
+
128
+ // #region apply-paid
129
+ /** The payment id (`pay_…`) of a payments event, or null. */
130
+ function paymentId(event: VerifiedWebhook): string | null {
131
+ const subject = event.body.subject;
132
+ if (typeof subject !== "object" || subject === null || !("id" in subject)) return null;
133
+ return typeof subject.id === "string" ? subject.id : null;
134
+ }
135
+
136
+ /** Marks the bill paid from a verified payment.paid, in the transaction of saveOnce. Other types are only recorded. */
137
+ export const applyPaymentEvent: ApplyEvent = async (tx, event) => {
138
+ if (event.type !== "payment.paid") return;
139
+ const payment = paymentId(event);
140
+ if (payment === null) throw new Error(`payment.paid ${event.id} has no subject id`);
141
+ await tx.query("UPDATE bills SET status = 'paid', paid_at = now() WHERE payment_id = $1 AND status <> 'paid'", [payment]);
142
+ };
143
+ // #endregion apply-paid