UNPKG

@httpc/kit

Version:

httpc toolbox for building function-based API with minimal code and end-to-end type safety

68 lines (67 loc) 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClaimParserError = void 0; class ClaimParserError extends Error { constructor(claim) { super(`Fail to parse claim: ${claim}`); this.claim = claim; } } exports.ClaimParserError = ClaimParserError; function parseToken(token) { return token.includes(":") ? token.split(":") : token; } function parseAuthSingle(claim) { if (!claim) { throw new ClaimParserError(claim); } const idxScope = claim.indexOf("@"); const token = idxScope < 0 ? claim : claim.substring(0, idxScope); const scope = idxScope < 0 ? undefined : claim.substring(idxScope + 1); return { token: parseToken(token), scope: scope ? parseToken(scope) : undefined, }; } function parseAuthorization(claim) { if (!claim) return []; return claim.split(" ").map(parseAuthSingle); } function parseAssertionSingle(assertion) { if (!assertion) { throw new ClaimParserError(assertion); } let negative = false; if (assertion.charAt(0) === "!") { negative = true; assertion = assertion.substring(1); } return { ...parseAuthSingle(assertion), negative }; } function parseAssertion(assertion) { if (!assertion) return []; return assertion.split(" ").map(parseAssertionSingle); } function parseGrantSingle(grant) { const subjectIdx = grant.indexOf(">"); if (subjectIdx < 0) { throw new ClaimParserError(grant); } return { ...parseAuthSingle(grant.substring(subjectIdx + 1)), subject: parseToken(grant.substring(0, subjectIdx)), }; } function parseGrants(grants) { if (!grants) return []; return grants.split(" ").map(parseGrantSingle); } exports.default = { parseToken, parseAuthorization, parseAssertion, parseGrants, };