2022-11-28 09:04:26 +00:00
|
|
|
import * as jose from "jose";
|
|
|
|
|
|
|
|
import { createDebug } from "./debug";
|
2023-01-11 15:55:10 +00:00
|
|
|
import { getJwksUrlFromSaleorApiUrl } from "./urls";
|
2022-11-28 09:04:26 +00:00
|
|
|
|
|
|
|
const debug = createDebug("verify-jwt");
|
|
|
|
|
|
|
|
export interface DashboardTokenPayload extends jose.JWTPayload {
|
|
|
|
app: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface verifyJWTArguments {
|
|
|
|
appId: string;
|
2023-01-12 12:39:49 +00:00
|
|
|
saleorApiUrl: string;
|
2022-11-28 09:04:26 +00:00
|
|
|
token: string;
|
|
|
|
}
|
|
|
|
|
2023-01-12 12:39:49 +00:00
|
|
|
export const verifyJWT = async ({ saleorApiUrl, token, appId }: verifyJWTArguments) => {
|
2022-11-28 09:04:26 +00:00
|
|
|
let tokenClaims: DashboardTokenPayload;
|
|
|
|
const ERROR_MESSAGE = "JWT verification failed:";
|
|
|
|
|
|
|
|
try {
|
|
|
|
tokenClaims = jose.decodeJwt(token as string) as DashboardTokenPayload;
|
|
|
|
debug("Token Claims decoded from jwt");
|
|
|
|
} catch (e) {
|
|
|
|
debug("Token Claims could not be decoded from JWT, will respond with Bad Request");
|
|
|
|
throw new Error(`${ERROR_MESSAGE} Could not decode authorization token.`);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (tokenClaims.app !== appId) {
|
|
|
|
debug(
|
|
|
|
"Resolved App ID value from token to be different than in request, will respond with Bad Request"
|
|
|
|
);
|
|
|
|
|
|
|
|
throw new Error(`${ERROR_MESSAGE} Token's app property is different than app ID.`);
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
debug("Trying to create JWKS");
|
|
|
|
|
2023-01-12 12:39:49 +00:00
|
|
|
const JWKS = jose.createRemoteJWKSet(new URL(getJwksUrlFromSaleorApiUrl(saleorApiUrl)));
|
2022-11-28 09:04:26 +00:00
|
|
|
debug("Trying to compare JWKS with token");
|
|
|
|
await jose.jwtVerify(token, JWKS);
|
|
|
|
} catch (e) {
|
|
|
|
debug("Failure: %s", e);
|
|
|
|
debug("Will return with Bad Request");
|
|
|
|
|
|
|
|
console.error(e);
|
|
|
|
|
|
|
|
throw new Error(`${ERROR_MESSAGE} JWT signature verification failed.`);
|
|
|
|
}
|
|
|
|
};
|