🚨 No longer maintained. Moved to @reallyland/node_mod. 🚨
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.
# Install via NPM
$ npm install --save @motss/signatur
const {
sign,
unsign,
// signSync,
// unsignSync,
} = require('@motss/signatur');
void async main() {
const payload = {
id: 'b4cd8c1',
t: '1580581220222',
};
const signedRequest = await sign(payload, {
secret: 'fixed-secret',
separator: ':',
});
assert.strictEqual(
signedRequest,
'eyJpZCI6ImI0Y2Q4YzEiLCJ0IjoiMTU4MDU4MTIyMDIyMiJ9:vXRKs8XZlLq1iJrPaYDsBsrLegjedzUCd3pnQqMB2Qg'
); // OK
try {
await unsign(
'eyJpZCI6ImI0Y2Q4YzEiLCJ0IjoiMTU4MDU4MTIyMDIyMiJ9:vXRKs8XZlLq1iJrPaYDsBsrLegjedzUCd3pnQqMB2Qg',
{
secret: 'fixed-secret',
// separator: ':',
// error: new Error('Bad signature detected'),
}
);
} catch (e) {
assert.deepEqual(e, {
error: {
type: 'invalid-signature',
message: 'Signature not match',
},
}); // OK
}
}()
// @ts-check
import {
sign,
unsign,
// signSync,
// unsignSync,
} from '@motss/signatur';
void async main() {
const payload = {
id: 'b4cd8c1',
t: '1580581220222',
};
const signedRequest = await sign(payload, {
secret: 'fixed-secret',
separator: ':',
});
assert.strictEqual(
signedRequest,
'eyJpZCI6ImI0Y2Q4YzEiLCJ0IjoiMTU4MDU4MTIyMDIyMiJ9:vXRKs8XZlLq1iJrPaYDsBsrLegjedzUCd3pnQqMB2Qg'
); // OK
try {
await unsign(
'eyJpZCI6ImI0Y2Q4YzEiLCJ0IjoiMTU4MDU4MTIyMDIyMiJ9:vXRKs8XZlLq1iJrPaYDsBsrLegjedzUCd3pnQqMB2Qg',
{
secret: 'fixed-secret',
// separator: ':',
// error: new Error('Bad signature detected'),
}
);
} catch (e) {
assert.deepEqual(e, {
error: {
type: 'invalid-signature',
message: 'Signature not match',
},
}); // OK
}
}()
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