Skip to content

Register a watcher from API

Thibaut SEVERAC edited this page Jun 17, 2023 · 1 revision

You can manually register a watcher .

to do this, you will need to init a watcher with fake credentials, and then call registerWatcher to register a watcher

const watcherClient = new WatcherClient({
    url: 'https://crowdsec.lan',
    auth: {
        machineID: 'node-watcher',
        password: 'myPassword'
    }
});

await watcherClient.registerWatcher({
    machine_id: 'node-watcher',
    password: 'myPassword'
});

registering a watcher will not allow you to connect with this credentials directly . It will need a manual action to be authorized on the crowdsec API .

But you can do something like :

const machineID = 'node-watcher';
const password = 'myPassword';
const watcherClient = new WatcherClient({
    url: 'https://crowdsec.lan',
    auth: {
        machineID,
        password
    }
});

try {
    await watcherClient.login();
} catch (e) {
    if (e instanceof CrowdSecServerError && e.code === 401) {
        // crowdsec seems to refuse the current credentials, try to register them ?
        try {
            await watcherClient.registerWatcher({
                machine_id: machineID,
                password
            });
        } catch (registerError) {
            if (registerError instanceof CrowdSecServerError && registerError.code === 403) {
                throw new Error('watcher seems already register');
            }

            console.error(`unknown error when registering a watcher : `, registerError);
            throw registerError;
        }
    } else {
        console.error(`unknown error when login`, e);
        throw e;
    }
}

//do something with the watcher

Actually the errors message are : Fail to login : ent: machine not found Fail to register : "message": "user 'node-watcher': user already exist"

but I think matching errors is not a future proof solution

Clone this wiki locally