It is always a recommended best practice to sign every HTTP request that contains any payload to ensure that the payload that sends along has not been tampered with. This module provides some handy methods to sign and unsign the data payload.
import { sign, unsign } from 'nodemod/dist/signatur/index.js';
(async () => {
const payload = {
id: 'b4cd8c1',
t: '1580581220222',
};
const signedRequest = await sign(payload, {
secret: 'fixed-secret',
separator: ':',
});
signedRequest === 'eyJpZCI6ImI0Y2Q4YzEiLCJ0IjoiMTU4MDU4MTIyMDIyMiJ9:vXRKs8XZlLq1iJrPaYDsBsrLegjedzUCd3pnQqMB2Qg'; /** true */
/** This shows how to handle error when a signature is invalid */
try {
await unsign(
'eyJpZCI6ImI0Y2Q4YzEiLCJ0IjoiMTU4MDU4MTIyMDIyMiJ9:vXRKs8XZlLq1iJrPaYDsBsrLegjedzUCd3pnQqMB2Qg',
{ secret: 'fixed-secret', /** separator: ':', error: new Error('Bad signature detected'), */ }
);
} catch (e) {
/** Handle error here */
e;
/**
* {
* error: {
* type: 'invalid-signature',
* message: 'Signature not match',
* }
* }
*/
}
})();
error
<Object> Error object for bad signature.
separator
<?string> Optional separator. Defaults to period (.
).
data
<T
> Raw data payload in the type ofT
.secret
<string> Secret used to encrypt the data payload.options
<?SignaturOptions> Options for signing the payload.- returns: <Promise<string>> Promise which resolves with a URL-safe base64 encoded
HMAC-SHA256
signature that encrypts the raw data payload with a required secret key.
signature
<string> URL-safe signature.secret
<string> Secret used to encrypt the data payload.options
<?SignaturOptions> Options for signing the payload.- returns: <Promise<
T
>> Promise which resolves with decoded data payload in the type ofT
.
Throws a error object for bad signature in the type of SignaturError.
This methods works the same as sign(data, secret[, options])
except that this is the synchronous version.
This methods works the same as unsign(signature, secret[, options])
except that this is the synchronous version.
MIT License © Rong Sen Ng