trustbroker-client
Version:
Official Client SDK for the TrustBroker Data Exchange Platform.
164 lines • 6.16 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TrustBrokerClient = void 0;
const axios_1 = __importDefault(require("axios"));
const errors_1 = require("./lib/errors");
const events_1 = __importDefault(require("events"));
const utilits_1 = require("./lib/utilits");
class TrustBrokerClient extends events_1.default {
clientId;
publicKey;
privateKey;
http;
logger;
constructor(options) {
super();
// Use default logger or none
this.logger = options?.logger ?? undefined;
const { TB_CLIENT_ID, TB_PUBLIC_KEY, TB_PRIVATE_KEY, TB_BROKER_URL } = process.env;
if (!TB_CLIENT_ID || !TB_PUBLIC_KEY || !TB_PRIVATE_KEY) {
throw new errors_1.InitializationError("Missing credentials in .env");
}
this.clientId = TB_CLIENT_ID;
this.publicKey = Buffer.from(TB_PUBLIC_KEY, "base64").toString("utf8");
this.privateKey = Buffer.from(TB_PRIVATE_KEY, "base64").toString("utf8");
const baseURL = (TB_BROKER_URL || "https://broker.trustbroker.io").replace(/\/+$/, "");
this.http = axios_1.default.create({ baseURL });
this.http.interceptors.request.use((config) => {
config.headers = config.headers ?? {};
config.headers["Client-Id"] = this.clientId;
const signature = (0, utilits_1.signPayload)(this.clientId, this.privateKey);
config.headers["Signature"] = signature;
return config;
});
}
getClientId() {
return this.clientId;
}
async getMyInstitution() {
try {
const { data } = await this.http.get("/institution/me");
return data;
}
catch (err) {
this.handleApiError(err, "getMyInstitution");
}
}
async getInstitutionById(id) {
try {
const { data } = await this.http.get("/institution/" + id);
return data;
}
catch (err) {
this.handleApiError(err, "getMyInstitution");
}
}
async getPublicKey() {
try {
const { data } = await this.http.get("/system/public-key");
return data;
}
catch (err) {
this.handleApiError(err, "getMyInstitution");
}
}
async createDataRequest(params) {
// 1. Build the raw payload
const payload = {
requesterId: this.clientId, // your client ID
providerId: params.providerId,
dataOwnerId: params.dataOwnerId,
dataSchemaId: params.schemaId,
relationshipId: params.relationshipId,
expiresAt: params.expiresAt,
signature: "", // placeholder
};
const serialized = JSON.stringify({
...payload,
signature: undefined, // sign only the data fields
});
payload.signature = (0, utilits_1.signPayload)(serialized, this.privateKey);
try {
// 4. POST to /requests (or whatever endpoint your broker uses)
const { data } = await this.http.post("/requests", payload);
return data;
}
catch (err) {
this.handleApiError(err, "createDataRequest");
}
}
/**
* Get status of a specific data request.
*/
async getRequestStatus(requestId) {
try {
const { data } = await this.http.get(`/requests/${requestId}`);
return data;
}
catch (err) {
this.handleApiError(err, "getRequestStatus");
}
}
async requestDataFromProvider(requestId, platformSignature, mySignature, providerEndpoint) {
// 2. Canonicalize and sign it
const body = {
requesterId: this.clientId,
platformSignature,
requestId,
signature: mySignature,
};
try {
// 3. POST to the provider directly
const { data } = await axios_1.default.post(providerEndpoint, body, {
headers: {
"Content-Type": "application/json",
},
});
return data;
}
catch (err) {
if (axios_1.default.isAxiosError(err) && err.response) {
throw new errors_1.RequestError("PROVIDER_ERROR", `requestDataFromProvider: ${err.response.data?.error || err.message}`);
}
throw new errors_1.RequestError("UNKNOWN", `requestDataFromProvider: ${err.message}`);
}
}
async submitRequesterSignature(requestId, providerId, providerSignature, platformSignature, requesterSignature) {
const body = {
providerId,
providerSignature,
platformSignature,
requesterSignature,
};
try {
const { data } = await this.http.post(`/requests/${requestId}/requester-signature`, body);
return data;
}
catch (err) {
this.handleApiError(err, "submitRequesterSignature");
}
}
signPayload(payload) {
const serialized = typeof payload === "string" ? payload : JSON.stringify(payload);
return (0, utilits_1.signPayload)(serialized, this.privateKey);
}
/**
* Verify a signature against a payload using the given public key.
*/
verifyPayloadSignature(payload, signature, publicKey) {
const serialized = typeof payload === "string" ? payload : JSON.stringify(payload);
return (0, utilits_1.verifySignature)(serialized, signature, publicKey);
}
handleApiError(err, context) {
if (axios_1.default.isAxiosError(err) && err.response) {
const msg = err.response.data?.error || err.message;
throw new errors_1.RequestError("API_ERROR", `${context}: ${msg}`);
}
throw new errors_1.RequestError("UNKNOWN", `${context}: ${err.message}`);
}
}
exports.TrustBrokerClient = TrustBrokerClient;
//# sourceMappingURL=index.js.map