-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathverify-signature.ts
76 lines (65 loc) · 2.01 KB
/
verify-signature.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import * as jose from "jose";
import { createDebug } from "./debug";
import { getJwksUrlFromSaleorApiUrl } from "./urls";
const debug = createDebug("verify-signature");
/**
* Verify Webhook payload signature with public key of given `domain`
* https://docs.saleor.io/docs/3.x/developer/extending/apps/asynchronous-webhooks#payload-signature
*
* Use Saleor URL to fetch JWKS
*
* TODO: Add test
*/
export const verifySignatureFromApiUrl = async (
saleorApiUrl: string,
signature: string,
rawBody: string
) => {
const [header, , jwsSignature] = signature.split(".");
const jws: jose.FlattenedJWSInput = {
protected: header,
payload: rawBody,
signature: jwsSignature,
};
const remoteJwks = jose.createRemoteJWKSet(
new URL(getJwksUrlFromSaleorApiUrl(saleorApiUrl))
) as jose.FlattenedVerifyGetKey;
debug("Created remote JWKS");
try {
await jose.flattenedVerify(jws, remoteJwks);
debug("JWKS verified");
} catch {
debug("JWKS verification failed");
throw new Error("JWKS verification failed");
}
};
/**
* Verify the Webhook payload signature from provided JWKS string.
* JWKS can be cached to avoid unnecessary calls.
*
* TODO: Add test
*/
export const verifySignatureWithJwks = async (jwks: string, signature: string, rawBody: string) => {
const [header, , jwsSignature] = signature.split(".");
const jws: jose.FlattenedJWSInput = {
protected: header,
payload: rawBody,
signature: jwsSignature,
};
let localJwks: jose.FlattenedVerifyGetKey;
try {
const parsedJWKS = JSON.parse(jwks);
localJwks = jose.createLocalJWKSet(parsedJWKS) as jose.FlattenedVerifyGetKey;
} catch {
debug("Could not create local JWKSSet from given data: %s", jwks);
throw new Error("JWKS verification failed - could not parse given JWKS");
}
debug("Created remote JWKS");
try {
await jose.flattenedVerify(jws, localJwks);
debug("JWKS verified");
} catch {
debug("JWKS verification failed");
throw new Error("JWKS verification failed");
}
};