@turnkey/api-key-stamper
Version:
API key stamper for @turnkey/http
70 lines (66 loc) • 2.67 kB
JavaScript
;
var encoding = require('@turnkey/encoding');
var elliptic_curves = require('./tink/elliptic_curves.js');
/// <reference lib="dom" />
// Header name for an API key stamp
const stampHeaderName = "X-Stamp";
// `window.document` ensures that we're in a browser context
// and `crypto.subtle` ensures that it supports the web crypto APIs
// Inspired by https://github.com/flexdinesh/browser-or-node/blob/master/src/index.ts
const isCryptoEnabledBrowser = typeof window !== "undefined" &&
typeof window.document !== "undefined" &&
typeof crypto !== "undefined" &&
typeof crypto.subtle !== "undefined";
// We check `process.versions.node`
// Taken from https://github.com/flexdinesh/browser-or-node/blob/master/src/index.ts
const isNode = typeof process !== "undefined" &&
process.versions != null &&
process.versions.node != null;
/**
* Signature function abstracting the differences between NodeJS and web environments for signing with API keys.
*/
const signWithApiKey = async (input) => {
if (isCryptoEnabledBrowser) {
const fn = await Promise.resolve().then(function () { return require('./webcrypto.js'); }).then((m) => m.signWithApiKey);
return fn(input);
}
else if (isNode) {
const fn = await Promise.resolve().then(function () { return require('./nodecrypto.js'); }).then((m) => m.signWithApiKey);
return fn(input);
}
else {
// If we don't have NodeJS or web crypto at our disposal, default to pure JS implementation
// This is the case for old browsers and react native environments
const fn = await Promise.resolve().then(function () { return require('./purejs.js'); }).then((m) => m.signWithApiKey);
return fn(input);
}
};
/**
* Stamper to use with `@turnkey/http`'s `TurnkeyClient`
*/
class ApiKeyStamper {
constructor(config) {
this.apiPublicKey = config.apiPublicKey;
this.apiPrivateKey = config.apiPrivateKey;
}
async stamp(payload) {
const signature = await signWithApiKey({
publicKey: this.apiPublicKey,
privateKey: this.apiPrivateKey,
content: payload,
});
const stamp = {
publicKey: this.apiPublicKey,
scheme: "SIGNATURE_SCHEME_TK_API_P256",
signature: signature,
};
return {
stampHeaderName: stampHeaderName,
stampHeaderValue: encoding.stringToBase64urlString(JSON.stringify(stamp)),
};
}
}
exports.pointDecode = elliptic_curves.pointDecode;
exports.ApiKeyStamper = ApiKeyStamper;
exports.signWithApiKey = signWithApiKey;
//# sourceMappingURL=index.js.map