l402
Version:
L402 client and tools for Javascript.
52 lines • 2.33 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupL402Interceptor = void 0;
const axios_1 = __importDefault(require("axios"));
function setupL402Interceptor(instance, wallet, store) {
instance.interceptors.request.use((config) => {
const url = axios_1.default.getUri(config);
const method = config.method?.toUpperCase() || 'GET';
const token = store.get(url || '', method);
if (token) {
config.headers['Authorization'] = `${token}`;
}
return config;
});
instance.interceptors.response.use((response) => response, async (error) => {
if (axios_1.default.isAxiosError(error) && error.config && error.response && error.response.status === 402) {
const config = error.config;
const authHeader = error.response.headers['www-authenticate'] || '';
const challenge = parseHeader(authHeader);
if (challenge && challenge.invoice) {
const paymentResult = await wallet.payInvoice(challenge.invoice);
if (paymentResult.success) {
const l402Token = `${challenge.header_key} ${challenge.macaroon}:${paymentResult.preimage}`;
const url = axios_1.default.getUri(config);
const method = config.method?.toUpperCase() || 'GET';
store.put(url || '', l402Token, method);
error.config.headers['Authorization'] = l402Token;
return instance.request(error.config);
}
}
}
return Promise.reject(error);
});
}
exports.setupL402Interceptor = setupL402Interceptor;
function parseHeader(header) {
const headerKeyMatch = /^(LSAT|L402)/.exec(header);
const invoiceMatch = /invoice="([\w|\d]+)"/.exec(header);
const macaroonMatch = /macaroon="([\w|\d\+\/=_-]+)"/.exec(header);
if (invoiceMatch && macaroonMatch) {
return {
header_key: headerKeyMatch ? headerKeyMatch[0] : '',
invoice: invoiceMatch[1],
macaroon: macaroonMatch[1],
};
}
return null;
}
//# sourceMappingURL=axios.js.map