@portive/auth
Version:
A library to help generate auth tokens for use with Portive's cloud services for open source components
72 lines (71 loc) • 2.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAuthToken = exports._createAuthToken = exports.stringifyApiKey = exports.parseApiKey = void 0;
const jwt_utils_1 = require("@portive/jwt-utils");
const api_types_1 = require("@portive/api-types");
/**
* Takes an `apiKey` comprising of the parts separates by underscores. The
* first part being a preamble checking that it starts with `PRTV`, the
* second is the API key id, and the last pare is the API secret key.
*
* The key has these properties for a few reasons:
*
* 1. Easy to cut and paste. Double-click and underscores and alphanumeric
* are all selected.
* 2. `PRTV` makes sure we haven't confused the API key with some other API key
* 3. We encode it into one so that we don't need multiple environment vars
* to store the API key which also ensures the key id and secret key stay
* together.
*
* e.g. PRTV_xxxxxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
*/
function parseApiKey(apiKey) {
const parts = apiKey.split("_");
if (parts.length !== 3) {
throw new Error(`Expected apiKey to split on _ into exactly 3 parts but is ${parts.length}`);
}
const [keyType, keyId, secretKey] = parts;
if (keyType !== "PRTV")
throw new Error(`Expected first part of API key to be PRTV but is ${JSON.stringify(keyType)}`);
return {
keyType,
keyId,
secretKey,
};
}
exports.parseApiKey = parseApiKey;
/**
* Takes the API key id and the API secret key and merges them into a single
* API key which includes the `PRTV` preamble.
*
* e.g. PRTV_xxxxxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
*/
function stringifyApiKey({ keyId, secretKey, }) {
return `PRTV_${keyId}_${secretKey}`;
}
exports.stringifyApiKey = stringifyApiKey;
/**
* A lower level version of `generateAuth` which `generateAuth` uses.
* Takes the `claims`, `keyId`, `secretKey` and `expiresIn` as separate
* arguments to improve readability.
*
* Probably okay to merge this into `generateAuth` later.
*/
function _createAuthToken(claims, { keyId, secretKey, expiresIn, }) {
const jwt = (0, jwt_utils_1.signJWT)(claims, api_types_1.AuthPayloadStruct, api_types_1.AuthHeaderStruct, secretKey, {
keyid: keyId,
expiresIn,
});
return jwt;
}
exports._createAuthToken = _createAuthToken;
/**
* Takes an apiKey (which includes the `keyId` and `secretKey`) and a set of
* PermitOptions and then generates a permit from it.
*/
function createAuthToken(apiKey, { expiresIn, ...claims } // PermitPrivateClaims & { expiresIn: ExpiresIn }
) {
const { keyId, secretKey } = parseApiKey(apiKey);
return _createAuthToken(claims, { keyId, secretKey, expiresIn });
}
exports.createAuthToken = createAuthToken;