@dodgeball/trust-sdk-server
Version:
292 lines (291 loc) • 16.5 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { DodgeballApiVersion, VerificationOutcome, VerificationStatus, DodgeballMissingParameterError, DodgeballMissingConfigError, DodgeballInvalidConfigError, } from "./types";
import { Logger, DodgeballLogLevel, Severity } from "./logger";
import { constructApiHeaders, constructApiUrl, makeRequest, sleep, } from "./utilities";
import { DEFAULT_CONFIG, BASE_CHECKPOINT_TIMEOUT_MS, MAX_RETRY_COUNT, MAX_TIMEOUT, } from "./constants";
import cloneDeep from "lodash.clonedeep";
// Export a class that accepts a config object
var Dodgeball = /** @class */ (function () {
// Constructor
function Dodgeball(secretKey, config) {
var _a;
if (secretKey == null || (secretKey === null || secretKey === void 0 ? void 0 : secretKey.length) === 0) {
throw new DodgeballMissingConfigError("secretApiKey", secretKey);
}
this.secretKey = secretKey;
this.config = Object.assign(cloneDeep(DEFAULT_CONFIG), cloneDeep(config || {}));
if (Object.keys(DodgeballApiVersion).indexOf(this.config.apiVersion) < 0) {
throw new DodgeballInvalidConfigError("config.apiVersion", this.config.apiVersion, Object.keys(DodgeballApiVersion));
}
var logLevel = (_a = this.config.logLevel) !== null && _a !== void 0 ? _a : DodgeballLogLevel.INFO;
if (Object.keys(DodgeballLogLevel).indexOf(logLevel) < 0) {
throw new DodgeballInvalidConfigError("config.logLevel", logLevel, Object.keys(DodgeballLogLevel));
}
Logger.filterLevel = Severity[logLevel];
}
Dodgeball.prototype.createErrorResponse = function (code, message) {
return {
success: false,
errors: [{ code: code, message: message }],
version: DodgeballApiVersion.v1,
verification: {
id: "",
status: VerificationStatus.FAILED,
outcome: VerificationOutcome.ERROR,
},
};
};
Dodgeball.prototype.event = function (_a) {
var _b = _a.userId, userId = _b === void 0 ? "" : _b, _c = _a.sessionId, sessionId = _c === void 0 ? "" : _c, _d = _a.sourceToken, sourceToken = _d === void 0 ? "" : _d, event = _a.event;
return __awaiter(this, void 0, void 0, function () {
var response;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
if (!event.eventTime) {
event.eventTime = Date.now();
}
return [4 /*yield*/, makeRequest({
url: constructApiUrl(this.config.apiUrl, this.config.apiVersion) + "track",
method: "POST",
headers: constructApiHeaders(this.secretKey, "", sourceToken, userId, sessionId),
data: __assign({}, event),
options: {},
})];
case 1:
response = _e.sent();
return [2 /*return*/];
}
});
});
};
Dodgeball.prototype.checkpoint = function (_a) {
var _b, _c, _d, _e, _f;
var checkpointName = _a.checkpointName, event = _a.event, _g = _a.sourceToken, sourceToken = _g === void 0 ? "" : _g, _h = _a.userId, userId = _h === void 0 ? "" : _h, _j = _a.sessionId, sessionId = _j === void 0 ? "" : _j, _k = _a.useVerificationId, useVerificationId = _k === void 0 ? "" : _k, _l = _a.options, options = _l === void 0 ? {} : _l;
return __awaiter(this, void 0, void 0, function () {
var trivialTimeout, largeTimeout, mustPoll, activeTimeout, maximalTimeout, internalOptions, response, numRepeats, numFailures, isResolved, verificationId, status, timeoutResponse;
return __generator(this, function (_m) {
switch (_m.label) {
case 0:
trivialTimeout = !options.timeout || options.timeout <= 0;
largeTimeout = options.timeout && options.timeout > 5 * BASE_CHECKPOINT_TIMEOUT_MS;
mustPoll = trivialTimeout || largeTimeout;
activeTimeout = mustPoll
? BASE_CHECKPOINT_TIMEOUT_MS
: (_b = options.timeout) !== null && _b !== void 0 ? _b : BASE_CHECKPOINT_TIMEOUT_MS;
maximalTimeout = MAX_TIMEOUT;
internalOptions = {
sync: options.sync === null || options.sync === undefined
? true
: options.sync,
timeout: activeTimeout,
webhook: options.webhook,
};
response = null;
numRepeats = 0;
numFailures = 0;
// Validate required parameters are present
if (checkpointName == null) {
throw new DodgeballMissingParameterError("checkpointName", checkpointName);
}
if (event == null) {
throw new DodgeballMissingParameterError("event", event);
}
else if (!event.hasOwnProperty("ip")) {
throw new DodgeballMissingParameterError("event.ip", event.ip);
}
if (sessionId == null && sourceToken == null) {
throw new DodgeballMissingParameterError("Must provide either a sessionId or sourceToken", "sessionId = " + sessionId + ", sourceToken = " + sourceToken);
}
if (!this.config.isEnabled) {
// Return a default verification response to allow for development without making requests
return [2 /*return*/, {
success: true,
errors: [],
version: DodgeballApiVersion.v1,
verification: {
id: "DODGEBALL_IS_DISABLED",
status: VerificationStatus.COMPLETE,
outcome: VerificationOutcome.APPROVED,
stepData: {},
},
}];
}
_m.label = 1;
case 1:
if (!(!response && numRepeats < 3)) return [3 /*break*/, 3];
return [4 /*yield*/, makeRequest({
url: constructApiUrl(this.config.apiUrl, this.config.apiVersion) + "checkpoint",
method: "POST",
headers: constructApiHeaders(this.secretKey, useVerificationId, sourceToken, userId, sessionId),
data: {
event: __assign({ type: checkpointName }, event),
options: internalOptions,
},
options: {},
})];
case 2:
response = (_m.sent());
numRepeats += 1;
return [3 /*break*/, 1];
case 3:
if (!response) {
return [2 /*return*/, this.createErrorResponse(500, "Unknown evaluation error")];
}
else if (!response.success) {
return [2 /*return*/, response];
}
isResolved = ((_c = response.verification) === null || _c === void 0 ? void 0 : _c.status) !== VerificationStatus.PENDING;
verificationId = (_d = response.verification) === null || _d === void 0 ? void 0 : _d.id;
_m.label = 4;
case 4:
if (!((trivialTimeout ||
((_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : BASE_CHECKPOINT_TIMEOUT_MS) >
numRepeats * activeTimeout) &&
!isResolved &&
numFailures < MAX_RETRY_COUNT)) return [3 /*break*/, 7];
return [4 /*yield*/, sleep(activeTimeout)];
case 5:
_m.sent();
activeTimeout =
activeTimeout < maximalTimeout ? 2 * activeTimeout : activeTimeout;
return [4 /*yield*/, makeRequest({
url: constructApiUrl(this.config.apiUrl, this.config.apiVersion) + "verification/" + verificationId,
method: "GET",
headers: constructApiHeaders(this.secretKey, useVerificationId, sourceToken, userId, sessionId),
})];
case 6:
response = (_m.sent());
if (response && response.success) {
status = (_f = response.verification) === null || _f === void 0 ? void 0 : _f.status;
if (!status) {
numFailures += 1;
}
else {
isResolved = status !== VerificationStatus.PENDING;
numRepeats += 1;
}
}
else {
numFailures += 1;
}
return [3 /*break*/, 4];
case 7:
if (numFailures >= MAX_RETRY_COUNT) {
Logger.error("Service Unavailable: Maximum retry count exceeded").log();
timeoutResponse = {
success: false,
version: DodgeballApiVersion.v1,
errors: [
{
code: 503,
message: "Service Unavailable: Maximum retry count exceeded",
},
],
isTimeout: true,
};
return [2 /*return*/, timeoutResponse];
}
Logger.trace("Returning response:", { response: response }).log();
return [2 /*return*/, response];
}
});
});
};
Dodgeball.prototype.isRunning = function (checkpointResponse) {
var _a;
if (checkpointResponse.success) {
switch ((_a = checkpointResponse.verification) === null || _a === void 0 ? void 0 : _a.status) {
case VerificationStatus.PENDING:
case VerificationStatus.BLOCKED:
return true;
default:
return false;
}
}
return false;
};
Dodgeball.prototype.isAllowed = function (checkpointResponse) {
var _a, _b;
return (checkpointResponse.success &&
((_a = checkpointResponse.verification) === null || _a === void 0 ? void 0 : _a.status) === VerificationStatus.COMPLETE &&
((_b = checkpointResponse.verification) === null || _b === void 0 ? void 0 : _b.outcome) === VerificationOutcome.APPROVED);
};
Dodgeball.prototype.isDenied = function (checkpointResponse) {
var _a;
if (checkpointResponse.success) {
switch ((_a = checkpointResponse.verification) === null || _a === void 0 ? void 0 : _a.outcome) {
case VerificationOutcome.DENIED:
return true;
default:
return false;
}
}
return false;
};
Dodgeball.prototype.isUndecided = function (checkpointResponse) {
var _a, _b;
return (checkpointResponse.success &&
((_a = checkpointResponse.verification) === null || _a === void 0 ? void 0 : _a.status) === VerificationStatus.COMPLETE &&
((_b = checkpointResponse.verification) === null || _b === void 0 ? void 0 : _b.outcome) === VerificationOutcome.PENDING);
};
Dodgeball.prototype.hasError = function (checkpointResponse) {
var _a, _b, _c;
return (!checkpointResponse.success &&
((((_a = checkpointResponse.verification) === null || _a === void 0 ? void 0 : _a.status) === VerificationStatus.FAILED &&
((_b = checkpointResponse.verification) === null || _b === void 0 ? void 0 : _b.outcome) ===
VerificationOutcome.ERROR) ||
((_c = checkpointResponse.errors) === null || _c === void 0 ? void 0 : _c.length) > 0));
};
Dodgeball.prototype.isTimeout = function (checkpointResponse) {
return (!checkpointResponse.success && checkpointResponse.isTimeout);
};
return Dodgeball;
}());
export { Dodgeball };