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 './tap-encryption-extension';
import '@iotize/tap/service/impl/group';
import '@iotize/tap/service/impl/interface';
import { bufferToHexString } from '@iotize/common/byte-converter';
import { KaitaiStreamWriter } from '@iotize/common/byte-stream';
import { StringConverter } from '@iotize/tap/client/impl';
import { hmacSHA256, pbkdf2 } from '@iotize/tap/crypto';
import { debug } from './debug';
import { TapAuthError } from './tap-auth-error';
import { hashLoginPassword, XOR } from './utility';
var TAG = 'Scram';
export function DEFAULT_SCRAM_SALT_GENERATOR() {
    var data = new Array(ScramAuth.USER_SALT_SIZE).fill(0).map(function (_) {
        return Math.floor(Math.random() * 0xff);
    });
    // To be 100% sure that salt will never be [0,0,0,0] which will disable login for the user
    if (data[0] === 0) {
        data[0] = 1;
    }
    return Uint8Array.from(data);
}
var ScramAuth = /** @class */ (function () {
    // protected _sessionState!: BehaviorSubject<SessionState>;
    // /**
    //  * Listen to session state changed
    //  */
    // public get sessionState(): Observable<SessionState> {
    //     return this._sessionState.asObservable();
    // }
    // /**
    //  * Get current session state
    //  */
    // public get sessionStateSnapshot(): SessionState {
    //     return this._sessionState.value;
    // }
    function ScramAuth(tap) {
        this.tap = tap;
        this.nonceGenerator = function () {
            return Math.floor(Math.random() * 0xffffffff);
        };
        this.saltGenerator = DEFAULT_SCRAM_SALT_GENERATOR;
        // this.sessionData = {};
    }
    // async changeCurrentUserPassword(newPassword: string): Promise<void> {
    //     let groupId = (await this.device.service.interface.getCurrentGroupId()).body()!;
    //     if (!this.sessionData.options || !groupId){
    //         throw new AuthError(AuthError.Code.NOT_LOGGED_IN, 'Cannot change password, your are not logged in');
    //     }
    //     let newPasswordKey: Uint8Array = ScramAuth.createScramPasswordKey(newPassword, this.sessionData.options);
    //     (await this.device.service.group.changePasswordKey(groupId, newPasswordKey)).successful();
    // }
    // /**
    //  * Enable/Disable scram for this tap
    //  * @param enabled
    //  */
    // async enable(enabled = true): Promise<void> {
    //     const lockInfo = (await this.device.service.interface.getSecurityOptions()).body();
    //     if (lockInfo.scramActivated === enabled) {
    //         return;
    //     }
    //     lockInfo.scramActivated = enabled;
    //     if (enabled) {
    //         lockInfo.hashPassword = true;
    //     }
    //     (await this.device.service.interface.putSecurityOptions(lockInfo)).successful();
    // }
    ScramAuth.prototype.changePassword = function (newPassword, groupId, salt) {
        if (salt === void 0) { salt = this.saltGenerator(); }
        return __awaiter(this, void 0, void 0, function () {
            var options, _a, newPasswordKey;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = {};
                        return [4 /*yield*/, this.tap.service.scram.getHashIteration()];
                    case 1:
                        options = (_a.iterationNumber = (_b.sent()).body(),
                            _a.salt = salt,
                            _a);
                        newPasswordKey = ScramAuth.createScramPasswordKey(newPassword, options);
                        debug(TAG, "Changing password key: " + bufferToHexString(newPasswordKey) + " salt=" + bufferToHexString(salt) + "; iteration=" + options.iterationNumber + " for user id \"" + groupId + "\"");
                        return [4 /*yield*/, this.tap.service.group.changePasswordKey(groupId, newPasswordKey)];
                    case 2:
                        (_b.sent()).successful();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Perform login
     *
     * @param params
     *
     * @throws Error if scram is not activated
     */
    ScramAuth.prototype.login = function (params) {
        return __awaiter(this, void 0, void 0, function () {
            var clientNonce, loginParams, loginBody, keys, sessionData, serverNonce, deviceServerProof, expectedServerProof;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        clientNonce = this.generateNonce();
                        debug(TAG, 'clientNonce', clientNonce);
                        loginParams = {
                            username: params.username,
                            clientNonce: clientNonce
                        };
                        return [4 /*yield*/, this.tap.service.scram.login(loginParams)];
                    case 1:
                        loginBody = (_a.sent()).body();
                        keys = ScramAuth.computeKeys(params, loginBody, clientNonce);
                        sessionData = {};
                        sessionData.storedKey = keys.storedKey;
                        sessionData.serverKey = keys.serverKey;
                        serverNonce = loginBody.serverNonce;
                        return [4 /*yield*/, this.tap.service.scram.loginProof(keys.clientProof)];
                    case 2:
                        deviceServerProof = (_a.sent()).body();
                        expectedServerProof = keys.serverProof;
                        // TODO maybe we can find something better to test array equals ...
                        if (bufferToHexString(expectedServerProof) !==
                            bufferToHexString(deviceServerProof)) {
                            throw new TapAuthError.InvalidServerKey(expectedServerProof, deviceServerProof);
                        }
                        sessionData.clientNonce = clientNonce;
                        sessionData.key = ScramAuth.computeSessionKey(clientNonce, serverNonce, loginBody.salt, keys.serverKey, keys.storedKey);
                        return [2 /*return*/, sessionData];
                }
            });
        });
    };
    ScramAuth.createScramPasswordKey = function (newPassword, options) {
        var keys = ScramAuth.computeBaseKeys(newPassword, options);
        var saltCopy = new Uint8Array(options.salt);
        var buffer = KaitaiStreamWriter.create(ScramAuth.SCRAM_PASSWORD_LENGTH);
        buffer
            .writeBytes(keys.storedKey, ScramAuth.KEY_SIZE)
            .writeBytes(keys.serverKey, ScramAuth.KEY_SIZE)
            .writeBytes(saltCopy, ScramAuth.USER_SALT_SIZE);
        return buffer.toBytes;
    };
    ScramAuth.computeBaseKeys = function (password, options) {
        var hashedPassword = hashLoginPassword(password);
        // debug(TAG, 'ScramAuth', 'hashedPassword', bufferToHexString(hashedPassword));
        var saltedPassword = ScramAuth.saltedPassword(hashedPassword, options.salt, options.iterationNumber);
        // debug(TAG, 'ScramAuth', 'saltedPassword', bufferToHexString(saltedPassword));
        // let clientKey: Uint8Array = ScramAuth.clientKey(saltedPassword);
        // debug(TAG, 'ScramAuth', 'clientKey', bufferToHexString(clientKey));
        var storedKey = ScramAuth.storedKey(saltedPassword);
        debug(TAG, 'storeKey', bufferToHexString(storedKey));
        var serverKey = ScramAuth.serverKey(saltedPassword);
        debug(TAG, 'serverKey', bufferToHexString(serverKey));
        return {
            hashedPassword: hashedPassword,
            saltedPassword: saltedPassword,
            storedKey: storedKey,
            serverKey: serverKey
        };
    };
    ScramAuth.computeKeys = function (credentials, loginBody, clientNonce) {
        var keys = ScramAuth.computeBaseKeys(credentials.password, loginBody);
        var clientProof = ScramAuth.clientProof(keys.storedKey, clientNonce, loginBody.serverNonce);
        // debug(TAG, 'ScramAuth', 'clientProof', bufferToHexString(clientProof));
        var serverProof = ScramAuth.serverProof(keys.serverKey, clientNonce, loginBody.serverNonce);
        // debug(TAG, 'ScramAuth', 'serverProof', bufferToHexString(serverProof));
        return __assign(__assign({}, keys), { clientProof: clientProof,
            serverProof: serverProof });
    };
    ScramAuth.prototype.logout = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                response = this.tap.service.interface.logout();
                this.tap.encryption.stop();
                return [2 /*return*/, response];
            });
        });
    };
    ScramAuth.clientProof = function (storedKey, clientNonce, serverNonce) {
        return ScramAuth.computeProof(storedKey, clientNonce, serverNonce).subarray(0, ScramAuth.KEY_SIZE);
    };
    ScramAuth.serverProof = function (serverKey, clientNonce, serverNonce) {
        return ScramAuth.computeProof(serverKey, serverNonce, clientNonce).subarray(0, ScramAuth.KEY_SIZE);
    };
    // getSessionKey(): Uint8Array {
    //     if (!this.sessionData.key) {
    //         throw new Error('Session not started');
    //     }
    //     return this.sessionData.key;
    // }
    ScramAuth.prototype.generateNonce = function () {
        return this.nonceGenerator();
    };
    /**
     * SaltedPwd = PBKDF2 ( HashedPassword, UserSalt, ItCnt )
     * @param password
     * @param userSalt
     * @param iteration
     */
    ScramAuth.saltedPassword = function (hashedPassword, userSalt, iterations) {
        return pbkdf2(hashedPassword, userSalt, iterations);
    };
    /**
     * ClientKey = HMAC ( SaltedPwd | « ClientKey »)
     * @param saltedPassword
     */
    // public static clientKey(saltedPassword: InputDataType): Uint8Array{
    //     let encodedLabel = ScramAuth.encodeLabel(ScramAuth.CLIENT_KEY_LABEL);
    //     let encodedLabel2 : Uint8Array = KaitaiStreamWriter.mergeArrays(
    //         encodedLabel,
    //         Uint8Array.from([0])
    //     ).data;
    //     // debug(TAG, 'ScramAuth', 'clientKey()', 'data => ', bufferToHexString(data), 'len', data.length, `(${saltedPassword.length} + ${encodedLabel.length})`);
    //     return ScramAuth.HMAC(
    //         saltedPassword,
    //         // userSalt
    //         encodedLabel2
    //     ).subarray(0, ScramAuth.KEY_SIZE);
    // }
    /**
     * StoredKey = H ( ClientKey )
     * @param saltedPassword
     */
    ScramAuth.storedKey = function (saltedPassword) {
        return ScramAuth.HASH(saltedPassword, ScramAuth.CLIENT_KEY_LABEL, ScramAuth.CLIENT_KEY_ITERATION_NUMBER);
    };
    ScramAuth.serverKey = function (saltedPassword) {
        return ScramAuth.HASH(saltedPassword, ScramAuth.SERVER_KEY_LABEL, ScramAuth.SERVER_KEY_ITERATION_NUMBER);
    };
    ScramAuth.HASH = function (key, label, iteration) {
        return pbkdf2(key, label, iteration, ScramAuth.KEY_SIZE / 4);
    };
    /**
     * ClientSignature = HMAC ( StoredKey | ClientNonce | ServerNonce )
     * @param key
     * @param nonce1
     * @param nonce2
     */
    ScramAuth.computeProof = function (key, nonce1, nonce2) {
        var buffer = KaitaiStreamWriter.create(key.length +
            ScramAuth.CLIENT_NONCE_SIZE +
            ScramAuth.SERVER_NONCE_SIZE);
        buffer
            .writeU(nonce1, ScramAuth.CLIENT_NONCE_SIZE)
            .writeBytes(key)
            .writeU(nonce2, ScramAuth.SERVER_NONCE_SIZE);
        return hmacSHA256(buffer.toBytes, key);
    };
    /**
     * ClientProofCheck = StoredKey ^ ClientProof
     * @param storedKey
     * @param clientProof
     */
    ScramAuth.clientProofCheck = function (storedKey, clientProof) {
        return XOR(storedKey, clientProof);
    };
    /**
     * CommunicationKey = H ( ClientNonce | ServerNonce | StoredKey | « CommunicationKey » )
     * @param clientNonce
     * @param serverNonce
     * @param storedKey
     */
    ScramAuth.computeSessionKey = function (clientNonce, serverNonce, userSalt, serverKey, storedKey) {
        var encodedLabel = ScramAuth.encodeLabel(ScramAuth.COMMUNICATION_KEY_LABEL);
        var buffer = KaitaiStreamWriter.create(ScramAuth.CLIENT_NONCE_SIZE +
            ScramAuth.SERVER_NONCE_SIZE +
            userSalt.length +
            serverKey.length +
            storedKey.length
        // + encodedLabel.length
        );
        buffer
            .writeU(clientNonce, ScramAuth.CLIENT_NONCE_SIZE)
            .writeBytes(serverKey)
            .writeBytes(userSalt)
            .writeBytes(storedKey)
            .writeU(serverNonce, ScramAuth.SERVER_NONCE_SIZE);
        // .add(encodedLabel)
        return hmacSHA256(buffer.toBytes, serverKey).subarray(0, ScramAuth.KEY_SIZE);
    };
    /**
     *
     * @param input
     */
    ScramAuth.encodeLabel = function (input) {
        return this.stringConverter.encode(input);
    };
    ScramAuth.CRC_LENGTH = 4;
    ScramAuth.CLIENT_NONCE_SIZE = 4;
    ScramAuth.SERVER_NONCE_SIZE = 4;
    ScramAuth.ITERATION_NUMBER_SIZE = 4;
    // public sessionData: ScramAuth.SessionData;
    ScramAuth.COMMUNICATION_KEY_LABEL = 'CommunicationKey';
    // static CLIENT_PROOF_LABEL: string = "ClientProof";
    ScramAuth.CLIENT_KEY_LABEL = 'ClientKey';
    ScramAuth.SERVER_KEY_LABEL = 'ServerKey';
    ScramAuth.KEY_SIZE = 16;
    ScramAuth.CLIENT_KEY_ITERATION_NUMBER = 2;
    ScramAuth.SERVER_KEY_ITERATION_NUMBER = 2;
    ScramAuth.USER_SALT_SIZE = 4;
    ScramAuth.SCRAM_PASSWORD_LENGTH = ScramAuth.KEY_SIZE * 2 + ScramAuth.USER_SALT_SIZE;
    ScramAuth.stringConverter = StringConverter.ascii();
    return ScramAuth;
}());
export { ScramAuth };
//# sourceMappingURL=data:application/json;base64, 