LocalAuthority / scripts / host_manager.pl
Newer Older
1870 lines | 69.704kb
Xdev Host Manager authored 2 days ago
1
#!/usr/bin/env perl
2
#
3
# host_manager.pl - Minimal host registry web app with no CPAN dependencies.
4
#
5

            
6
use strict;
7
use warnings;
8

            
9
use Cwd qw(abs_path);
10
use Digest::SHA qw(hmac_sha1 hmac_sha256_hex sha256_hex);
11
use File::Basename qw(dirname);
12
use File::Path qw(make_path);
13
use IO::Socket::INET;
14
use POSIX qw(strftime);
15
use Time::HiRes qw(time);
16

            
17
my $script_dir = dirname(abs_path($0));
18
my $project_dir = dirname($script_dir);
19

            
20
my %opt = (
21
    bind => $ENV{HOST_MANAGER_BIND} || '127.0.0.1',
22
    port => $ENV{HOST_MANAGER_PORT} || 8088,
23
    data => $ENV{HOST_MANAGER_DATA} || "$project_dir/config/hosts.yaml",
24
    local_hosts_tsv => $ENV{HOST_MANAGER_LOCAL_HOSTS_TSV} || "$project_dir/config/local-hosts.tsv",
Xdev Host Manager authored 2 days ago
25
    work_orders => $ENV{HOST_MANAGER_WORK_ORDERS} || "$project_dir/config/work-orders.yaml",
Xdev Host Manager authored 2 days ago
26
);
27

            
28
while (@ARGV) {
29
    my $arg = shift @ARGV;
30
    if ($arg eq '--bind') {
31
        $opt{bind} = shift @ARGV;
32
    } elsif ($arg eq '--port') {
33
        $opt{port} = shift @ARGV;
34
    } elsif ($arg eq '--data') {
35
        $opt{data} = shift @ARGV;
36
    } elsif ($arg eq '--local-hosts-tsv') {
37
        $opt{local_hosts_tsv} = shift @ARGV;
Xdev Host Manager authored 2 days ago
38
    } elsif ($arg eq '--work-orders') {
39
        $opt{work_orders} = shift @ARGV;
Xdev Host Manager authored 2 days ago
40
    } elsif ($arg eq '--help' || $arg eq '-h') {
41
        usage();
42
        exit 0;
43
    } else {
44
        die "Unknown option: $arg\n";
45
    }
46
}
47

            
48
my $session_secret = $ENV{HOST_MANAGER_SESSION_SECRET} || random_hex(32);
49
my %sessions;
50

            
51
my $server = IO::Socket::INET->new(
52
    LocalHost => $opt{bind},
53
    LocalPort => $opt{port},
54
    Proto => 'tcp',
55
    Listen => 10,
56
    ReuseAddr => 1,
57
) or die "Cannot listen on $opt{bind}:$opt{port}: $!\n";
58

            
59
print "host-manager listening on http://$opt{bind}:$opt{port}\n";
60
print "data file: $opt{data}\n";
61
print "OTP login: " . ($ENV{HOST_MANAGER_TOTP_SECRET} ? "enabled\n" : "disabled; set HOST_MANAGER_TOTP_SECRET\n");
62

            
63
while (my $client = $server->accept) {
64
    eval {
65
        $client->autoflush(1);
66
        handle_client($client);
67
    };
68
    if ($@) {
69
        eval { send_json($client, 500, { error => 'internal_error', detail => "$@" }); };
70
    }
71
    close $client;
72
}
73

            
74
sub usage {
75
    print <<"EOF";
76
Usage: perl scripts/host_manager.pl [--bind 127.0.0.1] [--port 8088]
77

            
78
Environment:
79
  HOST_MANAGER_TOTP_SECRET      Base32 TOTP secret required for write access.
80
  HOST_MANAGER_SESSION_SECRET   Optional session signing secret.
81
  HOST_MANAGER_DATA             Defaults to config/hosts.yaml.
82
  HOST_MANAGER_LOCAL_HOSTS_TSV  Defaults to config/local-hosts.tsv.
Xdev Host Manager authored 2 days ago
83
  HOST_MANAGER_WORK_ORDERS      Defaults to config/work-orders.yaml.
Xdev Host Manager authored 2 days ago
84

            
Xdev Host Manager authored 2 days ago
85
The nginx vhost keeps registry, CA, work order and download endpoints behind OTP.
Xdev Host Manager authored 2 days ago
86
EOF
87
}
88

            
89
sub handle_client {
90
    my ($client) = @_;
91
    my $request_line = <$client>;
92
    return unless defined $request_line;
93
    $request_line =~ s/\r?\n$//;
94
    my ($method, $target) = $request_line =~ m{^([A-Z]+)\s+(\S+)\s+HTTP/};
95
    return send_text($client, 400, 'bad request') unless $method && $target;
96

            
97
    my %headers;
98
    while (my $line = <$client>) {
99
        $line =~ s/\r?\n$//;
100
        last if $line eq '';
101
        my ($k, $v) = split /:\s*/, $line, 2;
102
        $headers{lc $k} = $v if defined $k && defined $v;
103
    }
104

            
105
    my $body = '';
106
    if (($headers{'content-length'} || 0) > 0) {
107
        read($client, $body, int($headers{'content-length'}));
108
    }
109

            
110
    my ($path, $query) = split /\?/, $target, 2;
111
    my %query = parse_params($query || '');
112

            
113
    if ($method eq 'GET' && $path eq '/') {
114
        return send_html($client, 200, app_html());
115
    }
116
    if ($method eq 'GET' && $path eq '/healthz') {
Xdev Host Manager authored 2 days ago
117
        return send_json($client, 200, { ok => json_bool(1) });
Xdev Host Manager authored 2 days ago
118
    }
119
    if ($method eq 'GET' && $path eq '/api/session') {
120
        return send_json($client, 200, { authenticated => is_authenticated(\%headers) ? json_bool(1) : json_bool(0) });
121
    }
Xdev Host Manager authored 2 days ago
122
    if ($method eq 'POST' && $path eq '/api/login') {
123
        return send_json($client, 503, { error => 'otp_not_configured' }) unless $ENV{HOST_MANAGER_TOTP_SECRET};
124
        my $payload = request_payload(\%headers, $body);
125
        my $otp = $payload->{otp} || '';
126
        if (!verify_totp($ENV{HOST_MANAGER_TOTP_SECRET} || '', $otp)) {
127
            return send_json($client, 401, { error => 'invalid_otp' });
128
        }
129
        my $token = create_session();
130
        return send_json($client, 200, { ok => json_bool(1) }, [ "Set-Cookie: hm_session=$token; HttpOnly; SameSite=Strict; Path=/" ]);
131
    }
132
    if ($method eq 'POST' && $path eq '/api/logout') {
133
        expire_session(\%headers);
134
        return send_json($client, 200, { ok => json_bool(1) }, [ "Set-Cookie: hm_session=deleted; Max-Age=0; Path=/" ]);
135
    }
136

            
137
    return send_json($client, 401, { error => 'authentication_required' }) unless is_authenticated(\%headers);
138

            
Xdev Host Manager authored 2 days ago
139
    if ($method eq 'GET' && $path eq '/api/hosts') {
140
        my $registry = load_registry();
141
        return send_json($client, 200, registry_payload($registry));
142
    }
Xdev Host Manager authored 2 days ago
143
    if ($method eq 'GET' && $path eq '/api/work-orders') {
144
        return send_json($client, 200, work_orders_payload(load_work_orders()));
145
    }
Xdev Host Manager authored 2 days ago
146
    if ($method eq 'GET' && $path eq '/download/hosts.yaml') {
147
        return send_file($client, $opt{data}, 'application/x-yaml; charset=utf-8', 'hosts.yaml');
148
    }
149
    if ($method eq 'GET' && $path eq '/download/local-hosts.tsv') {
150
        my $registry = load_registry();
151
        return send_download($client, 200, render_local_hosts_tsv($registry), 'text/tab-separated-values; charset=utf-8', 'local-hosts.tsv');
152
    }
153
    if ($method eq 'GET' && $path eq '/download/monitoring.json') {
154
        my $registry = load_registry();
155
        return send_download($client, 200, json_encode(render_monitoring($registry)), 'application/json; charset=utf-8', 'monitoring-hosts.json');
156
    }
Xdev Host Manager authored 2 days ago
157
    if ($method eq 'GET' && $path eq '/api/ca/status') {
158
        return send_json_raw($client, 200, ca_manager_json('status-json'));
159
    }
160
    if ($method eq 'GET' && $path eq '/api/ca/certificates') {
161
        return send_json_raw($client, 200, ca_manager_json('list-json'));
162
    }
163
    if ($method eq 'GET' && $path eq '/download/ca.crt') {
164
        return send_file($client, ca_cert_path(), 'application/x-pem-file; charset=utf-8', 'xdev-madagascar-host-ca.crt');
165
    }
Xdev Host Manager authored 2 days ago
166

            
167
    if ($method eq 'POST' && $path =~ m{^/api/}) {
168
        if ($path eq '/api/hosts/upsert') {
169
            my $payload = request_payload(\%headers, $body);
170
            return upsert_host($client, $payload);
171
        }
172
        if ($path eq '/api/hosts/delete') {
173
            my $payload = request_payload(\%headers, $body);
174
            return delete_host($client, $payload->{id} || '');
175
        }
Xdev Host Manager authored 2 days ago
176
        if ($path eq '/api/work-orders/confirm') {
177
            my $payload = request_payload(\%headers, $body);
178
            return confirm_work_order($client, $payload);
179
        }
Xdev Host Manager authored 2 days ago
180
        if ($path eq '/api/work-orders/checklist') {
181
            my $payload = request_payload(\%headers, $body);
182
            return update_work_order_checklist($client, $payload);
183
        }
Xdev Host Manager authored 2 days ago
184
        if ($path eq '/api/render/local-hosts-tsv') {
185
            my $registry = load_registry();
186
            my $content = render_local_hosts_tsv($registry);
187
            backup_file($opt{local_hosts_tsv});
188
            write_file($opt{local_hosts_tsv}, $content);
189
            return send_json($client, 200, { ok => json_bool(1), file => $opt{local_hosts_tsv} });
190
        }
191
    }
192

            
193
    return send_json($client, 404, { error => 'not_found' });
194
}
195

            
196
sub load_registry {
197
    return parse_hosts_yaml(read_file($opt{data}));
198
}
199

            
200
sub save_registry {
201
    my ($registry) = @_;
202
    $registry->{updated_at} = iso_now();
203
    backup_file($opt{data});
204
    write_file($opt{data}, render_hosts_yaml($registry));
205
}
206

            
Xdev Host Manager authored 2 days ago
207
sub load_work_orders {
208
    return { version => 1, work_orders => [] } unless -f $opt{work_orders};
209
    return parse_work_orders_yaml(read_file($opt{work_orders}));
210
}
211

            
212
sub save_work_orders {
213
    my ($orders) = @_;
214
    backup_file($opt{work_orders});
215
    write_file($opt{work_orders}, render_work_orders_yaml($orders));
216
}
217

            
218
sub work_orders_payload {
219
    my ($orders) = @_;
220
    my $pending = 0;
221
    for my $wo (@{ $orders->{work_orders} || [] }) {
222
        $pending++ if ($wo->{status} || 'pending') eq 'pending';
223
    }
224
    return {
225
        version => $orders->{version},
226
        work_orders => $orders->{work_orders} || [],
227
        counts => {
228
            work_orders => scalar @{ $orders->{work_orders} || [] },
229
            pending => $pending,
230
        },
231
    };
232
}
233

            
234
sub confirm_work_order {
235
    my ($client, $payload) = @_;
236
    my $id = clean_scalar($payload->{id} || '');
237
    return send_json($client, 400, { error => 'invalid_work_order_id' }) unless $id =~ /\AWO-[A-Za-z0-9_.-]+\z/;
238
    return send_json($client, 400, { error => 'confirmation_required' }) unless clean_scalar($payload->{confirm} || '') eq $id;
239

            
240
    my $orders = load_work_orders();
241
    my $work_order;
242
    for my $wo (@{ $orders->{work_orders} || [] }) {
243
        if (($wo->{id} || '') eq $id) {
244
            $work_order = $wo;
245
            last;
246
        }
247
    }
248
    return send_json($client, 404, { error => 'work_order_not_found' }) unless $work_order;
249
    return send_json($client, 409, { error => 'work_order_not_pending' }) unless ($work_order->{status} || 'pending') eq 'pending';
Xdev Host Manager authored 2 days ago
250
    my $incomplete = incomplete_work_order_items($work_order);
251
    return send_json($client, 409, {
252
        error => 'work_order_incomplete',
253
        incomplete => $incomplete,
254
    }) if @$incomplete;
Xdev Host Manager authored 2 days ago
255

            
256
    my $registry = load_registry();
257
    my $results = apply_work_order($registry, $work_order);
258
    $work_order->{status} = 'confirmed';
259
    $work_order->{confirmed_at} = iso_now();
260
    $work_order->{result} = scalar(@$results) . ' action(s) applied';
261

            
262
    save_registry($registry);
263
    save_work_orders($orders);
264
    backup_file($opt{local_hosts_tsv});
265
    write_file($opt{local_hosts_tsv}, render_local_hosts_tsv($registry));
266

            
267
    return send_json($client, 200, {
268
        ok => json_bool(1),
269
        work_order => $work_order,
270
        results => $results,
271
        local_hosts_tsv => $opt{local_hosts_tsv},
272
    });
273
}
274

            
Xdev Host Manager authored 2 days ago
275
sub update_work_order_checklist {
276
    my ($client, $payload) = @_;
277
    my $id = clean_scalar($payload->{id} || '');
278
    my $item_id = clean_scalar($payload->{item_id} || '');
279
    my $status = clean_scalar($payload->{status} || '');
280
    my $notes = clean_scalar($payload->{notes} || '');
281
    return send_json($client, 400, { error => 'invalid_work_order_id' }) unless $id =~ /\AWO-[A-Za-z0-9_.-]+\z/;
282
    return send_json($client, 400, { error => 'invalid_checklist_item' }) unless $item_id =~ /\A[A-Za-z0-9_.-]+\z/;
283
    return send_json($client, 400, { error => 'invalid_checklist_status' }) unless $status =~ /\A(?:pending|done|blocked)\z/;
284

            
285
    my $orders = load_work_orders();
286
    my $work_order;
287
    for my $wo (@{ $orders->{work_orders} || [] }) {
288
        if (($wo->{id} || '') eq $id) {
289
            $work_order = $wo;
290
            last;
291
        }
292
    }
293
    return send_json($client, 404, { error => 'work_order_not_found' }) unless $work_order;
294
    return send_json($client, 409, { error => 'work_order_not_pending' }) unless ($work_order->{status} || 'pending') eq 'pending';
295

            
296
    my $item;
297
    for my $candidate (@{ $work_order->{checklist} || [] }) {
298
        if (($candidate->{id} || '') eq $item_id) {
299
            $item = $candidate;
300
            last;
301
        }
302
    }
303
    return send_json($client, 404, { error => 'checklist_item_not_found' }) unless $item;
304

            
305
    $item->{status} = $status;
306
    $item->{updated_at} = iso_now();
307
    $item->{notes} = $notes if length $notes;
308
    save_work_orders($orders);
309
    return send_json($client, 200, { ok => json_bool(1), work_order => $work_order });
310
}
311

            
312
sub incomplete_work_order_items {
313
    my ($work_order) = @_;
314
    my @incomplete;
315
    for my $item (@{ $work_order->{checklist} || [] }) {
316
        push @incomplete, $item unless ($item->{status} || 'pending') eq 'done';
317
    }
318
    return \@incomplete;
319
}
320

            
Xdev Host Manager authored 2 days ago
321
sub apply_work_order {
322
    my ($registry, $work_order) = @_;
323
    my @results;
324
    for my $action (@{ $work_order->{actions} || [] }) {
325
        my $type = $action->{type} || '';
326
        if ($type eq 'remove_name') {
327
            my $host_id = $action->{host_id} || '';
328
            my $name = $action->{name} || '';
329
            my $removed = 0;
330
            for my $host (@{ $registry->{hosts} || [] }) {
331
                next unless ($host->{id} || '') eq $host_id;
332
                my @kept = grep { $_ ne $name } @{ $host->{names} || [] };
333
                $removed = @kept != @{ $host->{names} || [] };
334
                $host->{names} = \@kept;
335
                last;
336
            }
337
            push @results, {
338
                type => $type,
339
                host_id => $host_id,
340
                name => $name,
341
                removed => json_bool($removed),
342
            };
343
        } else {
344
            die "Unsupported work order action: $type\n";
345
        }
346
    }
347
    return \@results;
348
}
349

            
Xdev Host Manager authored 2 days ago
350
sub registry_payload {
351
    my ($registry) = @_;
352
    my $problems = analyze_hosts($registry->{hosts});
Xdev Host Manager authored 2 days ago
353
    my @hosts = map { host_payload($_) } @{ $registry->{hosts} };
Xdev Host Manager authored 2 days ago
354
    return {
355
        version => $registry->{version},
356
        updated_at => $registry->{updated_at},
357
        policy => $registry->{policy},
Xdev Host Manager authored 2 days ago
358
        hosts => \@hosts,
Xdev Host Manager authored 2 days ago
359
        problems => $problems,
360
        counts => {
361
            hosts => scalar @{ $registry->{hosts} },
362
            problems => scalar @$problems,
363
        },
364
    };
365
}
366

            
367
sub upsert_host {
368
    my ($client, $payload) = @_;
369
    my $id = clean_id($payload->{id} || '');
370
    return send_json($client, 400, { error => 'invalid_id' }) unless $id;
371

            
372
    my $hosts_ip = clean_scalar($payload->{hosts_ip} || '');
373
    my $dns_ip = clean_scalar($payload->{dns_ip} || '');
374
    return send_json($client, 400, { error => 'missing_ip' }) unless $hosts_ip && $dns_ip;
375

            
Xdev Host Manager authored 2 days ago
376
    my @names = remove_derived_names(clean_list($payload->{names}));
Xdev Host Manager authored 2 days ago
377
    return send_json($client, 400, { error => 'missing_names' }) unless @names;
378

            
379
    my $registry = load_registry();
380
    my %host = (
381
        id => $id,
382
        status => clean_scalar($payload->{status} || 'active'),
383
        hosts_ip => $hosts_ip,
384
        dns_ip => $dns_ip,
385
        names => \@names,
386
        roles => [ clean_list($payload->{roles}) ],
387
        sources => [ clean_list($payload->{sources}) ],
388
        monitoring => clean_scalar($payload->{monitoring} || 'pending'),
389
        notes => clean_scalar($payload->{notes} || ''),
390
    );
391

            
392
    my $replaced = 0;
393
    for my $i (0 .. $#{ $registry->{hosts} }) {
394
        if ($registry->{hosts}->[$i]{id} eq $id) {
395
            $registry->{hosts}->[$i] = \%host;
396
            $replaced = 1;
397
            last;
398
        }
399
    }
400
    push @{ $registry->{hosts} }, \%host unless $replaced;
401
    save_registry($registry);
402
    return send_json($client, 200, { ok => json_bool(1), host => \%host });
403
}
404

            
405
sub delete_host {
406
    my ($client, $id) = @_;
407
    $id = clean_id($id);
408
    return send_json($client, 400, { error => 'invalid_id' }) unless $id;
409

            
410
    my $registry = load_registry();
411
    my @kept = grep { $_->{id} ne $id } @{ $registry->{hosts} };
412
    return send_json($client, 404, { error => 'not_found' }) if @kept == @{ $registry->{hosts} };
413
    $registry->{hosts} = \@kept;
414
    save_registry($registry);
415
    return send_json($client, 200, { ok => json_bool(1) });
416
}
417

            
418
sub analyze_hosts {
419
    my ($hosts) = @_;
420
    my @problems;
421
    my (%names, %ids);
422
    for my $host (@$hosts) {
423
        push @problems, problem($host, 'duplicate-id', "Duplicate id $host->{id}") if $ids{ $host->{id} }++;
424
        my @fqdn = grep { /\.madagascar\.xdev\.ro$/ } @{ $host->{names} || [] };
425
        push @problems, problem($host, 'missing-fqdn', 'No madagascar.xdev.ro FQDN') unless @fqdn || ($host->{status} || '') ne 'active';
426
        push @problems, problem($host, 'deprecated-vad-is', 'Deprecated vad.is.xdev.ro name present')
427
            if grep { /\.vad\.is\.xdev\.ro$/ } @{ $host->{names} || [] };
428
        push @problems, problem($host, 'legacy-prefix', 'Legacy prefix should be normalized out')
429
            if grep { /^(is|vad|b)-/ } @{ $host->{names} || [] };
430
        for my $name (@{ $host->{names} || [] }) {
431
            push @problems, problem($host, 'duplicate-name', "Duplicate name $name") if $names{$name}++;
432
        }
Xdev Host Manager authored 2 days ago
433
        my %declared = map { $_ => 1 } @{ $host->{names} || [] };
434
        for my $derived (derived_names($host)) {
435
            push @problems, problem($host, 'redundant-derived-name', "Name $derived is derived from madagascar.xdev.ro")
436
                if $declared{$derived};
437
        }
Xdev Host Manager authored 2 days ago
438
        if (($host->{hosts_ip} || '') ne ($host->{dns_ip} || '') && ($host->{hosts_ip} || '') ne '127.0.0.1') {
439
            push @problems, problem($host, 'split-ip', 'hosts_ip differs from dns_ip; check that this is intentional');
440
        }
441
    }
442
    return \@problems;
443
}
444

            
Xdev Host Manager authored 2 days ago
445
sub host_payload {
446
    my ($host) = @_;
447
    my %copy = %$host;
448
    $copy{names} = [ effective_names($host) ];
449
    $copy{declared_names} = [ @{ $host->{names} || [] } ];
450
    $copy{derived_names} = [ derived_names($host) ];
451
    return \%copy;
452
}
453

            
454
sub effective_names {
455
    my ($host) = @_;
456
    my @names = @{ $host->{names} || [] };
457
    push @names, derived_names($host);
458
    return unique_preserve(@names);
459
}
460

            
461
sub derived_names {
462
    my ($host) = @_;
463
    my @derived;
464
    for my $name (@{ $host->{names} || [] }) {
465
        next unless $name =~ /^(.+)\.madagascar\.xdev\.ro$/;
466
        push @derived, $1 if length $1;
467
    }
468
    return unique_preserve(@derived);
469
}
470

            
471
sub remove_derived_names {
472
    my @names = @_;
473
    my %derived;
474
    for my $name (@names) {
475
        next unless $name =~ /^(.+)\.madagascar\.xdev\.ro$/;
476
        $derived{$1} = 1;
477
    }
478
    return grep { !$derived{$_} } @names;
479
}
480

            
481
sub unique_preserve {
482
    my @values = @_;
483
    my %seen;
484
    return grep { !$seen{$_}++ } @values;
485
}
486

            
Xdev Host Manager authored 2 days ago
487
sub problem {
488
    my ($host, $code, $message) = @_;
489
    return { host_id => $host->{id}, code => $code, message => $message };
490
}
491

            
492
sub render_local_hosts_tsv {
493
    my ($registry) = @_;
494
    my $out = "# Local DNS manifest for the madagascar network.\n";
495
    $out .= "# Generated by scripts/host_manager.pl from config/hosts.yaml.\n";
496
    $out .= "#\n";
497
    $out .= "# Format:\n";
498
    $out .= "# hosts_ip<TAB>dns_ip<TAB>name [aliases...]\n";
499
    $out .= "#\n";
500
    $out .= "# Priority rule:\n";
501
    $out .= "# - DHCP lease/reservation on 192.168.2.1 is canonical for LAN IP allocation.\n";
502
    $out .= "# - madagascar.json is canonical for cluster roles and service interfaces.\n";
503
    $out .= "# - This file publishes approved local DNS records derived from those sources.\n";
504
    for my $host (sort { $a->{id} cmp $b->{id} } @{ $registry->{hosts} }) {
505
        next unless ($host->{status} || 'active') eq 'active';
Xdev Host Manager authored 2 days ago
506
        my @names = effective_names($host);
507
        next unless @names;
508
        $out .= join("\t", $host->{hosts_ip}, $host->{dns_ip}, join(' ', @names)) . "\n";
Xdev Host Manager authored 2 days ago
509
    }
510
    return $out;
511
}
512

            
513
sub render_monitoring {
514
    my ($registry) = @_;
515
    my @hosts;
516
    for my $host (sort { $a->{id} cmp $b->{id} } @{ $registry->{hosts} }) {
517
        next unless ($host->{status} || 'active') eq 'active';
518
        next if ($host->{monitoring} || 'pending') eq 'disabled';
Xdev Host Manager authored 2 days ago
519
        my @names = effective_names($host);
Xdev Host Manager authored 2 days ago
520
        push @hosts, {
521
            id => $host->{id},
Xdev Host Manager authored 2 days ago
522
            primary_name => $names[0],
Xdev Host Manager authored 2 days ago
523
            address => $host->{dns_ip},
Xdev Host Manager authored 2 days ago
524
            aliases => \@names,
525
            declared_names => [ @{ $host->{names} || [] } ],
526
            derived_names => [ derived_names($host) ],
Xdev Host Manager authored 2 days ago
527
            roles => [ @{ $host->{roles} || [] } ],
528
            monitoring => $host->{monitoring} || 'pending',
529
            notes => $host->{notes} || '',
530
        };
531
    }
532
    return {
533
        version => $registry->{version},
534
        generated_at => iso_now(),
535
        source => 'config/hosts.yaml',
536
        hosts => \@hosts,
537
    };
538
}
539

            
Xdev Host Manager authored 2 days ago
540
sub ca_script_path {
541
    return "$project_dir/scripts/ca_manager.sh";
542
}
543

            
544
sub ca_dir {
545
    return $ENV{HOST_MANAGER_CA_DIR} || "$project_dir/var/ca";
546
}
547

            
548
sub ca_cert_path {
549
    return ca_dir() . "/certs/ca.cert.pem";
550
}
551

            
552
sub ca_manager_json {
553
    my ($command) = @_;
554
    my $script = ca_script_path();
555
    die "CA manager script is missing\n" unless -x $script;
556
    local $ENV{HOST_MANAGER_CA_DIR} = ca_dir();
557
    open my $fh, '-|', $script, $command or die "Cannot run CA manager\n";
558
    local $/;
559
    my $out = <$fh>;
560
    close $fh or die "CA manager failed\n";
561
    return $out || '{}';
562
}
563

            
Xdev Host Manager authored 2 days ago
564
sub parse_hosts_yaml {
565
    my ($text) = @_;
566
    my %registry = (
567
        version => 1,
568
        updated_at => '',
569
        policy => {},
570
        hosts => [],
571
    );
572
    my ($section, $current, $list_key);
573
    for my $line (split /\n/, $text) {
574
        next if $line =~ /^\s*$/ || $line =~ /^\s*#/;
575
        if ($line =~ /^version:\s*(\d+)/) {
576
            $registry{version} = int($1);
577
        } elsif ($line =~ /^updated_at:\s*(.+)$/) {
578
            $registry{updated_at} = yaml_unquote($1);
579
        } elsif ($line =~ /^policy:\s*$/) {
580
            $section = 'policy';
581
        } elsif ($line =~ /^hosts:\s*$/) {
582
            $section = 'hosts';
583
        } elsif (($section || '') eq 'policy' && $line =~ /^  ([A-Za-z0-9_]+):\s*(.+)$/) {
584
            $registry{policy}{$1} = yaml_unquote($2);
585
        } elsif (($section || '') eq 'hosts' && $line =~ /^  - id:\s*(.+)$/) {
586
            $current = {
587
                id => yaml_unquote($1),
588
                status => 'active',
589
                hosts_ip => '',
590
                dns_ip => '',
591
                names => [],
592
                roles => [],
593
                sources => [],
594
                monitoring => 'pending',
595
                notes => '',
596
            };
597
            push @{ $registry{hosts} }, $current;
598
            $list_key = undef;
599
        } elsif ($current && $line =~ /^    ([A-Za-z0-9_]+):\s*$/) {
600
            $list_key = $1;
601
            $current->{$list_key} ||= [];
602
        } elsif ($current && defined $list_key && $line =~ /^      -\s*(.+)$/) {
603
            push @{ $current->{$list_key} }, yaml_unquote($1);
604
        } elsif ($current && $line =~ /^    ([A-Za-z0-9_]+):\s*(.*)$/) {
605
            $current->{$1} = yaml_unquote($2);
606
            $list_key = undef;
607
        }
608
    }
609
    return \%registry;
610
}
611

            
612
sub render_hosts_yaml {
613
    my ($registry) = @_;
614
    my $out = "version: " . int($registry->{version} || 1) . "\n";
615
    $out .= "updated_at: " . yq($registry->{updated_at} || iso_now()) . "\n";
616
    $out .= "policy:\n";
617
    for my $key (sort keys %{ $registry->{policy} || {} }) {
618
        $out .= "  $key: " . yq($registry->{policy}{$key}) . "\n";
619
    }
620
    $out .= "hosts:\n";
621
    for my $host (sort { $a->{id} cmp $b->{id} } @{ $registry->{hosts} || [] }) {
622
        $out .= "  - id: " . yq($host->{id}) . "\n";
623
        for my $key (qw(status hosts_ip dns_ip)) {
624
            $out .= "    $key: " . yq($host->{$key} || '') . "\n";
625
        }
626
        for my $key (qw(names roles sources)) {
627
            $out .= "    $key:\n";
628
            for my $value (@{ $host->{$key} || [] }) {
629
                $out .= "      - " . yq($value) . "\n";
630
            }
631
        }
632
        $out .= "    monitoring: " . yq($host->{monitoring} || 'pending') . "\n";
633
        $out .= "    notes: " . yq($host->{notes} || '') . "\n";
634
    }
635
    return $out;
636
}
637

            
Xdev Host Manager authored 2 days ago
638
sub parse_work_orders_yaml {
639
    my ($text) = @_;
640
    my %orders = (
641
        version => 1,
642
        work_orders => [],
643
    );
Xdev Host Manager authored 2 days ago
644
    my ($section, $current, $list_section, $current_action, $current_item);
Xdev Host Manager authored 2 days ago
645
    for my $line (split /\n/, $text) {
646
        next if $line =~ /^\s*$/ || $line =~ /^\s*#/;
647
        if ($line =~ /^version:\s*(\d+)/) {
648
            $orders{version} = int($1);
649
        } elsif ($line =~ /^work_orders:\s*$/) {
650
            $section = 'work_orders';
651
        } elsif (($section || '') eq 'work_orders' && $line =~ /^  - id:\s*(.+)$/) {
652
            $current = {
653
                id => yaml_unquote($1),
654
                status => 'pending',
Xdev Host Manager authored 2 days ago
655
                checklist => [],
Xdev Host Manager authored 2 days ago
656
                actions => [],
657
            };
658
            push @{ $orders{work_orders} }, $current;
Xdev Host Manager authored 2 days ago
659
            $list_section = '';
Xdev Host Manager authored 2 days ago
660
            $current_action = undef;
Xdev Host Manager authored 2 days ago
661
            $current_item = undef;
662
        } elsif ($current && $line =~ /^    checklist:\s*$/) {
663
            $list_section = 'checklist';
664
            $current->{checklist} ||= [];
665
        } elsif ($current && $list_section eq 'checklist' && $line =~ /^      - id:\s*(.+)$/) {
666
            $current_item = { id => yaml_unquote($1), status => 'pending' };
667
            push @{ $current->{checklist} }, $current_item;
668
            $current_action = undef;
669
        } elsif ($current_item && $list_section eq 'checklist' && $line =~ /^        ([A-Za-z0-9_]+):\s*(.*)$/) {
670
            $current_item->{$1} = yaml_unquote($2);
Xdev Host Manager authored 2 days ago
671
        } elsif ($current && $line =~ /^    actions:\s*$/) {
Xdev Host Manager authored 2 days ago
672
            $list_section = 'actions';
Xdev Host Manager authored 2 days ago
673
            $current->{actions} ||= [];
Xdev Host Manager authored 2 days ago
674
        } elsif ($current && $list_section eq 'actions' && $line =~ /^      - type:\s*(.+)$/) {
Xdev Host Manager authored 2 days ago
675
            $current_action = { type => yaml_unquote($1) };
676
            push @{ $current->{actions} }, $current_action;
Xdev Host Manager authored 2 days ago
677
            $current_item = undef;
678
        } elsif ($current_action && $list_section eq 'actions' && $line =~ /^        ([A-Za-z0-9_]+):\s*(.*)$/) {
Xdev Host Manager authored 2 days ago
679
            $current_action->{$1} = yaml_unquote($2);
680
        } elsif ($current && $line =~ /^    ([A-Za-z0-9_]+):\s*(.*)$/) {
681
            $current->{$1} = yaml_unquote($2);
Xdev Host Manager authored 2 days ago
682
            $list_section = '';
Xdev Host Manager authored 2 days ago
683
            $current_action = undef;
Xdev Host Manager authored 2 days ago
684
            $current_item = undef;
Xdev Host Manager authored 2 days ago
685
        }
686
    }
687
    return \%orders;
688
}
689

            
690
sub render_work_orders_yaml {
691
    my ($orders) = @_;
692
    my $out = "version: " . int($orders->{version} || 1) . "\n";
693
    $out .= "work_orders:\n";
694
    for my $wo (@{ $orders->{work_orders} || [] }) {
695
        $out .= "  - id: " . yq($wo->{id}) . "\n";
696
        for my $key (qw(status title reason created_at confirmed_at result)) {
697
            next unless exists $wo->{$key} && length($wo->{$key} || '');
698
            $out .= "    $key: " . yq($wo->{$key}) . "\n";
699
        }
Xdev Host Manager authored 2 days ago
700
        $out .= "    checklist:\n";
701
        for my $item (@{ $wo->{checklist} || [] }) {
702
            $out .= "      - id: " . yq($item->{id}) . "\n";
703
            for my $key (qw(text status owner notes updated_at)) {
704
                next unless exists $item->{$key} && length($item->{$key} || '');
705
                $out .= "        $key: " . yq($item->{$key}) . "\n";
706
            }
707
        }
Xdev Host Manager authored 2 days ago
708
        $out .= "    actions:\n";
709
        for my $action (@{ $wo->{actions} || [] }) {
710
            $out .= "      - type: " . yq($action->{type}) . "\n";
711
            for my $key (qw(host_id name)) {
712
                next unless exists $action->{$key} && length($action->{$key} || '');
713
                $out .= "        $key: " . yq($action->{$key}) . "\n";
714
            }
715
        }
716
    }
717
    return $out;
718
}
719

            
Xdev Host Manager authored 2 days ago
720
sub request_payload {
721
    my ($headers, $body) = @_;
722
    my $type = $headers->{'content-type'} || '';
723
    if ($type =~ m{application/json}) {
724
        return json_decode($body || '{}');
725
    }
726
    return { parse_params($body || '') };
727
}
728

            
729
sub json_bool {
730
    my ($value) = @_;
731
    return bless \(my $bool = $value ? 1 : 0), 'HostManager::JSONBool';
732
}
733

            
734
sub json_encode {
735
    my ($value) = @_;
736
    if (!defined $value) {
737
        return 'null';
738
    }
739
    my $ref = ref($value);
740
    if (!$ref) {
741
        return $value if $value =~ /\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?\z/;
742
        return json_string($value);
743
    }
744
    if ($ref eq 'HostManager::JSONBool') {
745
        return $$value ? 'true' : 'false';
746
    }
747
    if ($ref eq 'ARRAY') {
748
        return '[' . join(',', map { json_encode($_) } @$value) . ']';
749
    }
750
    if ($ref eq 'HASH') {
751
        return '{' . join(',', map { json_string($_) . ':' . json_encode($value->{$_}) } sort keys %$value) . '}';
752
    }
753
    return json_string("$value");
754
}
755

            
756
sub json_string {
757
    my ($value) = @_;
758
    $value = '' unless defined $value;
759
    $value =~ s/\\/\\\\/g;
760
    $value =~ s/"/\\"/g;
761
    $value =~ s/\n/\\n/g;
762
    $value =~ s/\r/\\r/g;
763
    $value =~ s/\t/\\t/g;
764
    $value =~ s/([\x00-\x1f])/sprintf("\\u%04x", ord($1))/eg;
765
    return qq("$value");
766
}
767

            
768
sub json_decode {
769
    my ($text) = @_;
770
    my $i = 0;
771
    my $len = length($text);
772
    my ($parse_value, $parse_string, $parse_array, $parse_object, $parse_number, $skip_ws);
773

            
774
    $skip_ws = sub {
775
        $i++ while $i < $len && substr($text, $i, 1) =~ /\s/;
776
    };
777

            
778
    $parse_string = sub {
779
        die "Expected JSON string\n" unless substr($text, $i, 1) eq '"';
780
        $i++;
781
        my $out = '';
782
        while ($i < $len) {
783
            my $ch = substr($text, $i++, 1);
784
            return $out if $ch eq '"';
785
            if ($ch eq "\\") {
786
                die "Bad JSON escape\n" if $i >= $len;
787
                my $esc = substr($text, $i++, 1);
788
                if ($esc eq '"' || $esc eq "\\" || $esc eq '/') {
789
                    $out .= $esc;
790
                } elsif ($esc eq 'b') {
791
                    $out .= "\b";
792
                } elsif ($esc eq 'f') {
793
                    $out .= "\f";
794
                } elsif ($esc eq 'n') {
795
                    $out .= "\n";
796
                } elsif ($esc eq 'r') {
797
                    $out .= "\r";
798
                } elsif ($esc eq 't') {
799
                    $out .= "\t";
800
                } elsif ($esc eq 'u') {
801
                    my $hex = substr($text, $i, 4);
802
                    die "Bad JSON unicode escape\n" unless $hex =~ /\A[0-9A-Fa-f]{4}\z/;
803
                    $out .= chr(hex($hex));
804
                    $i += 4;
805
                } else {
806
                    die "Bad JSON escape\n";
807
                }
808
            } else {
809
                $out .= $ch;
810
            }
811
        }
812
        die "Unterminated JSON string\n";
813
    };
814

            
815
    $parse_number = sub {
816
        my $start = $i;
817
        $i++ if substr($text, $i, 1) eq '-';
818
        $i++ while $i < $len && substr($text, $i, 1) =~ /[0-9]/;
819
        if ($i < $len && substr($text, $i, 1) eq '.') {
820
            $i++;
821
            $i++ while $i < $len && substr($text, $i, 1) =~ /[0-9]/;
822
        }
823
        if ($i < $len && substr($text, $i, 1) =~ /[eE]/) {
824
            $i++;
825
            $i++ if $i < $len && substr($text, $i, 1) =~ /[+-]/;
826
            $i++ while $i < $len && substr($text, $i, 1) =~ /[0-9]/;
827
        }
828
        return 0 + substr($text, $start, $i - $start);
829
    };
830

            
831
    $parse_array = sub {
832
        die "Expected JSON array\n" unless substr($text, $i, 1) eq '[';
833
        $i++;
834
        my @out;
835
        $skip_ws->();
836
        if ($i < $len && substr($text, $i, 1) eq ']') {
837
            $i++;
838
            return \@out;
839
        }
840
        while (1) {
841
            push @out, $parse_value->();
842
            $skip_ws->();
843
            my $ch = substr($text, $i++, 1);
844
            last if $ch eq ']';
845
            die "Expected JSON array comma\n" unless $ch eq ',';
846
        }
847
        return \@out;
848
    };
849

            
850
    $parse_object = sub {
851
        die "Expected JSON object\n" unless substr($text, $i, 1) eq '{';
852
        $i++;
853
        my %out;
854
        $skip_ws->();
855
        if ($i < $len && substr($text, $i, 1) eq '}') {
856
            $i++;
857
            return \%out;
858
        }
859
        while (1) {
860
            $skip_ws->();
861
            my $key = $parse_string->();
862
            $skip_ws->();
863
            die "Expected JSON object colon\n" unless substr($text, $i++, 1) eq ':';
864
            $out{$key} = $parse_value->();
865
            $skip_ws->();
866
            my $ch = substr($text, $i++, 1);
867
            last if $ch eq '}';
868
            die "Expected JSON object comma\n" unless $ch eq ',';
869
        }
870
        return \%out;
871
    };
872

            
873
    $parse_value = sub {
874
        $skip_ws->();
875
        die "Unexpected end of JSON\n" if $i >= $len;
876
        my $ch = substr($text, $i, 1);
877
        return $parse_string->() if $ch eq '"';
878
        return $parse_object->() if $ch eq '{';
879
        return $parse_array->() if $ch eq '[';
880
        if (substr($text, $i, 4) eq 'true') {
881
            $i += 4;
882
            return json_bool(1);
883
        }
884
        if (substr($text, $i, 5) eq 'false') {
885
            $i += 5;
886
            return json_bool(0);
887
        }
888
        if (substr($text, $i, 4) eq 'null') {
889
            $i += 4;
890
            return undef;
891
        }
892
        return $parse_number->() if $ch =~ /[-0-9]/;
893
        die "Unexpected JSON token\n";
894
    };
895

            
896
    my $value = $parse_value->();
897
    $skip_ws->();
898
    die "Trailing JSON content\n" if $i != $len;
899
    return $value;
900
}
901

            
902
sub parse_params {
903
    my ($text) = @_;
904
    my %out;
905
    for my $pair (split /&/, $text) {
906
        next unless length $pair;
907
        my ($k, $v) = split /=/, $pair, 2;
908
        $out{url_decode($k)} = url_decode($v || '');
909
    }
910
    return %out;
911
}
912

            
913
sub clean_id {
914
    my ($value) = @_;
915
    $value = lc clean_scalar($value);
916
    $value =~ s/[^a-z0-9_.-]+/-/g;
917
    $value =~ s/^-+|-+$//g;
918
    return $value;
919
}
920

            
921
sub clean_scalar {
922
    my ($value) = @_;
923
    $value = '' unless defined $value;
924
    $value =~ s/[\r\n\t]+/ /g;
925
    $value =~ s/^\s+|\s+$//g;
926
    return $value;
927
}
928

            
929
sub clean_list {
930
    my ($value) = @_;
931
    return () unless defined $value;
932
    my @items = ref($value) eq 'ARRAY' ? @$value : split /[\s,]+/, $value;
933
    my @clean;
934
    for my $item (@items) {
935
        $item = clean_scalar($item);
936
        push @clean, $item if length $item;
937
    }
938
    return @clean;
939
}
940

            
941
sub yq {
942
    my ($value) = @_;
943
    $value = '' unless defined $value;
944
    $value =~ s/\\/\\\\/g;
945
    $value =~ s/"/\\"/g;
946
    return qq("$value");
947
}
948

            
949
sub yaml_unquote {
950
    my ($value) = @_;
951
    $value = '' unless defined $value;
952
    $value =~ s/^\s+|\s+$//g;
953
    if ($value =~ /^"(.*)"$/) {
954
        $value = $1;
955
        $value =~ s/\\"/"/g;
956
        $value =~ s/\\\\/\\/g;
957
    }
958
    return $value;
959
}
960

            
961
sub verify_totp {
962
    my ($secret, $otp) = @_;
963
    return 0 unless $secret && $otp =~ /^\d{6}$/;
964
    my $key = eval { base32_decode($secret) };
965
    return 0 if $@ || !length $key;
966
    my $counter = int(time() / 30);
967
    for my $offset (-1, 0, 1) {
968
        return 1 if totp_code($key, $counter + $offset) eq $otp;
969
    }
970
    return 0;
971
}
972

            
973
sub totp_code {
974
    my ($key, $counter) = @_;
975
    my $msg = pack('NN', int($counter / 4294967296), $counter & 0xffffffff);
976
    my $hash = hmac_sha1($msg, $key);
977
    my $offset = ord(substr($hash, -1)) & 0x0f;
978
    my $bin = unpack('N', substr($hash, $offset, 4)) & 0x7fffffff;
979
    return sprintf('%06d', $bin % 1_000_000);
980
}
981

            
982
sub base32_decode {
983
    my ($text) = @_;
984
    $text = uc($text || '');
985
    $text =~ s/[^A-Z2-7]//g;
986
    my %map;
987
    my @chars = ('A'..'Z', '2'..'7');
988
    @map{@chars} = (0..31);
989
    my ($bits, $value, $out) = (0, 0, '');
990
    for my $char (split //, $text) {
991
        die "Invalid base32\n" unless exists $map{$char};
992
        $value = ($value << 5) | $map{$char};
993
        $bits += 5;
994
        while ($bits >= 8) {
995
            $bits -= 8;
996
            $out .= chr(($value >> $bits) & 0xff);
997
        }
998
    }
999
    return $out;
1000
}
1001

            
1002
sub create_session {
1003
    my $nonce = random_hex(24);
1004
    my $expires = int(time() + 8 * 3600);
1005
    my $sig = hmac_sha256_hex("$nonce:$expires", $session_secret);
1006
    my $token = "$nonce:$expires:$sig";
1007
    $sessions{$token} = $expires;
1008
    return $token;
1009
}
1010

            
1011
sub is_authenticated {
1012
    my ($headers) = @_;
1013
    my $token = cookie_value($headers->{'cookie'} || '', 'hm_session');
1014
    return 0 unless $token;
1015
    my ($nonce, $expires, $sig) = split /:/, $token;
1016
    return 0 unless $nonce && $expires && $sig;
1017
    return 0 if $expires < time();
1018
    return 0 unless hmac_sha256_hex("$nonce:$expires", $session_secret) eq $sig;
1019
    return exists $sessions{$token};
1020
}
1021

            
1022
sub expire_session {
1023
    my ($headers) = @_;
1024
    my $token = cookie_value($headers->{'cookie'} || '', 'hm_session');
1025
    delete $sessions{$token} if $token;
1026
}
1027

            
1028
sub cookie_value {
1029
    my ($cookie, $name) = @_;
1030
    for my $part (split /;\s*/, $cookie) {
1031
        my ($k, $v) = split /=/, $part, 2;
1032
        return $v if defined $k && $k eq $name;
1033
    }
1034
    return '';
1035
}
1036

            
1037
sub send_json {
1038
    my ($client, $status, $payload, $extra_headers) = @_;
1039
    return send_response($client, $status, json_encode($payload), 'application/json; charset=utf-8', $extra_headers);
1040
}
1041

            
Xdev Host Manager authored 2 days ago
1042
sub send_json_raw {
1043
    my ($client, $status, $json_body, $extra_headers) = @_;
1044
    return send_response($client, $status, $json_body, 'application/json; charset=utf-8', $extra_headers);
1045
}
1046

            
Xdev Host Manager authored 2 days ago
1047
sub send_html {
1048
    my ($client, $status, $html) = @_;
1049
    return send_response($client, $status, $html, 'text/html; charset=utf-8');
1050
}
1051

            
1052
sub send_text {
1053
    my ($client, $status, $text) = @_;
1054
    return send_response($client, $status, $text, 'text/plain; charset=utf-8');
1055
}
1056

            
1057
sub send_download {
1058
    my ($client, $status, $content, $type, $filename) = @_;
1059
    return send_response($client, $status, $content, $type, [ qq(Content-Disposition: attachment; filename="$filename") ]);
1060
}
1061

            
1062
sub send_file {
1063
    my ($client, $path, $type, $filename) = @_;
1064
    return send_json($client, 404, { error => 'missing_file' }) unless -f $path;
1065
    return send_download($client, 200, read_file($path), $type, $filename);
1066
}
1067

            
1068
sub send_response {
1069
    my ($client, $status, $body, $type, $extra_headers) = @_;
Xdev Host Manager authored 2 days ago
1070
    my %reason = (200 => 'OK', 400 => 'Bad Request', 401 => 'Unauthorized', 404 => 'Not Found', 409 => 'Conflict', 500 => 'Internal Server Error', 503 => 'Service Unavailable');
Xdev Host Manager authored 2 days ago
1071
    $body = '' unless defined $body;
1072
    print $client "HTTP/1.1 $status " . ($reason{$status} || 'OK') . "\r\n";
1073
    print $client "Content-Type: $type\r\n";
1074
    print $client "Content-Length: " . length($body) . "\r\n";
1075
    print $client "Cache-Control: no-store\r\n";
1076
    print $client "$_\r\n" for @{ $extra_headers || [] };
1077
    print $client "Connection: close\r\n\r\n";
1078
    print $client $body;
1079
}
1080

            
1081
sub read_file {
1082
    my ($path) = @_;
1083
    open my $fh, '<', $path or die "Cannot read $path: $!";
1084
    local $/;
1085
    return <$fh>;
1086
}
1087

            
1088
sub write_file {
1089
    my ($path, $content) = @_;
1090
    open my $fh, '>', $path or die "Cannot write $path: $!";
1091
    print {$fh} $content;
1092
    close $fh or die "Cannot close $path: $!";
1093
}
1094

            
1095
sub backup_file {
1096
    my ($path) = @_;
1097
    return unless -f $path;
1098
    my $backup_dir = "$project_dir/backups/host-manager";
1099
    make_path($backup_dir) unless -d $backup_dir;
1100
    my $name = $path;
1101
    $name =~ s{.*/}{};
1102
    my $stamp = strftime('%Y%m%d_%H%M%S', localtime);
1103
    write_file("$backup_dir/$name.$stamp.bak", read_file($path));
1104
}
1105

            
1106
sub url_decode {
1107
    my ($value) = @_;
1108
    $value = '' unless defined $value;
1109
    $value =~ tr/+/ /;
1110
    $value =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
1111
    return $value;
1112
}
1113

            
1114
sub random_hex {
1115
    my ($bytes) = @_;
1116
    if (open my $fh, '<:raw', '/dev/urandom') {
1117
        read($fh, my $raw, $bytes);
1118
        close $fh;
1119
        return unpack('H*', $raw);
1120
    }
1121
    return sha256_hex(rand() . time() . $$);
1122
}
1123

            
1124
sub iso_now {
1125
    return strftime('%Y-%m-%dT%H:%M:%SZ', gmtime);
1126
}
1127

            
Bogdan Timofte authored a day ago
1128
sub build_info {
1129
    my %info = (
1130
        revision => '',
1131
        branch => '',
1132
        built_at => '',
1133
        deployed_at => '',
1134
        dirty => '',
1135
    );
1136

            
1137
    if ($ENV{HOST_MANAGER_BUILD}) {
1138
        $info{revision} = clean_scalar($ENV{HOST_MANAGER_BUILD});
1139
        return \%info;
1140
    }
1141

            
1142
    my $build_file = "$project_dir/BUILD";
1143
    if (-f $build_file) {
1144
        for my $line (split /\n/, read_file($build_file)) {
1145
            next unless $line =~ /\A([A-Za-z0-9_.-]+)=(.*)\z/;
1146
            $info{$1} = clean_scalar($2);
1147
        }
1148
        return \%info if $info{revision} || $info{built_at};
1149
    }
1150

            
1151
    my $revision = git_value('rev-parse --short=12 HEAD');
1152
    my $branch = git_value('rev-parse --abbrev-ref HEAD');
1153
    $info{revision} = $revision if $revision;
1154
    $info{branch} = $branch if $branch && $branch ne 'HEAD';
1155
    return \%info;
1156
}
1157

            
1158
sub git_value {
1159
    my ($args) = @_;
1160
    return '' unless -d "$project_dir/.git";
1161
    open my $fh, '-|', "git -C '$project_dir' $args 2>/dev/null" or return '';
1162
    my $value = <$fh> || '';
1163
    close $fh;
1164
    chomp $value;
1165
    return clean_scalar($value);
1166
}
1167

            
1168
sub build_label {
1169
    my $info = build_info();
1170
    my $revision = $info->{revision} || 'unknown';
1171
    my $branch = $info->{branch} || '';
1172
    $branch = '' if $branch eq 'HEAD';
1173
    my $label = $branch ? "$branch $revision" : $revision;
1174
    $label .= '+dirty' if ($info->{dirty} || '') eq '1';
1175
    return $label;
1176
}
1177

            
1178
sub build_title {
1179
    my $info = build_info();
1180
    my $label = build_label();
1181
    my $stamp = $info->{deployed_at} || $info->{built_at} || '';
1182
    return $stamp ? "$label deployed $stamp" : $label;
1183
}
1184

            
1185
sub html_escape {
1186
    my ($value) = @_;
1187
    $value = '' unless defined $value;
1188
    $value =~ s/&/&amp;/g;
1189
    $value =~ s/</&lt;/g;
1190
    $value =~ s/>/&gt;/g;
1191
    $value =~ s/"/&quot;/g;
1192
    $value =~ s/'/&#039;/g;
1193
    return $value;
1194
}
1195

            
Xdev Host Manager authored 2 days ago
1196
sub app_html {
Bogdan Timofte authored a day ago
1197
    my $build = html_escape(build_label());
1198
    my $build_title = html_escape(build_title());
1199
    my $html = <<'HTML';
Xdev Host Manager authored 2 days ago
1200
<!doctype html>
1201
<html lang="ro">
1202
<head>
1203
  <meta charset="utf-8">
1204
  <meta name="viewport" content="width=device-width, initial-scale=1">
Bogdan Timofte authored a day ago
1205
  <meta name="xdev-build" content="__HOST_MANAGER_BUILD_TITLE__">
Xdev Host Manager authored 2 days ago
1206
  <title>Madagascar Local Authority</title>
Xdev Host Manager authored 2 days ago
1207
  <style>
1208
    :root {
1209
      color-scheme: light;
1210
      --ink: #152033;
1211
      --muted: #647084;
1212
      --line: #d8dee8;
1213
      --soft: #f4f6f9;
1214
      --panel: #ffffff;
1215
      --accent: #1267d8;
1216
      --bad: #b42318;
1217
      --warn: #946200;
1218
      --ok: #137333;
1219
    }
1220
    * { box-sizing: border-box; }
1221
    body { margin: 0; font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: var(--ink); background: #eef2f6; font-size: 14px; }
Xdev Host Manager authored 2 days ago
1222

            
1223
    /* ── Login screen ── */
1224
    #login-screen {
1225
      display: flex;
Xdev Host Manager authored 2 days ago
1226
      align-items: flex-start;
Xdev Host Manager authored 2 days ago
1227
      justify-content: center;
1228
      min-height: 100dvh;
Xdev Host Manager authored 2 days ago
1229
      padding: clamp(48px, 10vh, 96px) 24px clamp(140px, 20vh, 220px);
Xdev Host Manager authored 2 days ago
1230
      background: #13182a;
Xdev Host Manager authored 2 days ago
1231
      overflow: auto;
Xdev Host Manager authored 2 days ago
1232
    }
1233
    .login-card {
Xdev Host Manager authored 2 days ago
1234
      --otp-size: 48px;
Xdev Host Manager authored 2 days ago
1235
      --otp-gap: 18px;
Xdev Host Manager authored 2 days ago
1236
      --login-form-width: calc((var(--otp-size) * 6) + (var(--otp-gap) * 5));
Xdev Host Manager authored 2 days ago
1237
      background: #fff;
1238
      border-radius: 16px;
Bogdan Timofte authored a day ago
1239
      padding: 54px 64px 34px;
Xdev Host Manager authored 2 days ago
1240
      width: 100%;
Xdev Host Manager authored 2 days ago
1241
      max-width: 680px;
Bogdan Timofte authored a day ago
1242
      min-height: 360px;
Xdev Host Manager authored 2 days ago
1243
      display: grid;
Xdev Host Manager authored 2 days ago
1244
      align-content: start;
1245
      justify-items: center;
1246
      gap: 28px;
Xdev Host Manager authored 2 days ago
1247
      box-shadow: 0 8px 40px rgba(0,0,0,.28);
1248
    }
Xdev Host Manager authored 2 days ago
1249
    .login-card .brand { text-align: center; display: grid; gap: 8px; justify-items: center; }
Xdev Host Manager authored 2 days ago
1250
    .login-card .brand .icon {
Xdev Host Manager authored 2 days ago
1251
      margin: 0 0 8px;
Xdev Host Manager authored 2 days ago
1252
      width: 64px; height: 64px; border-radius: 18px;
Xdev Host Manager authored 2 days ago
1253
      background: #e8f0fe; display: flex; align-items: center; justify-content: center;
1254
    }
Xdev Host Manager authored 2 days ago
1255
    .login-card .brand .icon svg { width: 38px; height: 38px; fill: none; stroke: var(--accent); stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; }
1256
    .login-card .brand h1 { margin: 0; font-size: 32px; line-height: 1.05; font-weight: 750; color: var(--ink); }
1257
    .login-card .brand p { margin: 0; color: var(--muted); font-size: 16px; }
Xdev Host Manager authored 2 days ago
1258
    .login-card form {
1259
      display: grid;
1260
      width: min(100%, var(--login-form-width));
Xdev Host Manager authored 2 days ago
1261
      justify-self: center;
Bogdan Timofte authored 2 days ago
1262
      padding-bottom: 0;
Xdev Host Manager authored 2 days ago
1263
    }
Xdev Host Manager authored 2 days ago
1264
    .login-card form.busy { opacity: .72; pointer-events: none; }
Bogdan Timofte authored a day ago
1265
    .pm-helper-fields {
1266
      position: absolute;
1267
      left: -10000px;
1268
      top: auto;
1269
      width: 1px;
1270
      height: 1px;
1271
      overflow: hidden;
1272
      opacity: 0.01;
1273
    }
1274
    .pm-helper-fields input {
1275
      width: 1px;
1276
      height: 1px;
1277
      padding: 0;
1278
      border: 0;
1279
    }
Xdev Host Manager authored 2 days ago
1280
    /* 6 separate OTP digit boxes */
Xdev Host Manager authored 2 days ago
1281
    .otp-row {
1282
      display: flex;
1283
      gap: var(--otp-gap);
1284
      justify-content: center;
1285
    }
Xdev Host Manager authored 2 days ago
1286
    .otp-row input {
Xdev Host Manager authored 2 days ago
1287
      width: var(--otp-size); height: 56px; border: 1.5px solid #dde2ec; border-radius: 10px;
Xdev Host Manager authored 2 days ago
1288
      font-size: 22px; font-weight: 600; text-align: center; color: var(--ink);
1289
      background: #f8fafc; caret-color: transparent; outline: none;
1290
      transition: border-color .15s, background .15s;
1291
    }
1292
    .otp-row input:focus { border-color: var(--accent); background: #fff; }
1293
    .otp-row input.filled { border-color: #b3c6f0; background: #fff; }
1294
    #login-error {
1295
      color: var(--bad); font-size: 13px; text-align: center;
Xdev Host Manager authored 2 days ago
1296
      min-height: 18px; margin-top: -52px;
Xdev Host Manager authored 2 days ago
1297
    }
1298
    @media (max-width: 760px) {
1299
      .login-card {
Xdev Host Manager authored 2 days ago
1300
        max-width: 520px;
Xdev Host Manager authored 2 days ago
1301
        min-height: 0;
1302
        padding: 48px 36px 44px;
1303
        gap: 26px;
1304
      }
1305
      .login-card .brand h1 { font-size: 24px; }
1306
      .login-card .brand p { font-size: 14px; }
Bogdan Timofte authored 2 days ago
1307
      .login-card form { padding-bottom: 0; }
1308
      #login-error { margin-top: -24px; }
Xdev Host Manager authored 2 days ago
1309
    }
Xdev Host Manager authored 2 days ago
1310
    @media (max-width: 430px) {
1311
      #login-screen { padding: 24px 16px 120px; }
1312
      .login-card {
1313
        --otp-size: 42px;
Xdev Host Manager authored 2 days ago
1314
        --otp-gap: 12px;
Xdev Host Manager authored 2 days ago
1315
        padding: 36px 22px 34px;
1316
      }
1317
      .otp-row input { height: 52px; }
Bogdan Timofte authored 2 days ago
1318
      .login-card form { padding-bottom: 0; }
Xdev Host Manager authored 2 days ago
1319
    }
1320
    @media (max-height: 720px) {
1321
      #login-screen { padding-top: 28px; padding-bottom: 96px; }
1322
      .login-card { padding-top: 34px; padding-bottom: 34px; gap: 20px; }
Bogdan Timofte authored 2 days ago
1323
      .login-card form { padding-bottom: 0; }
Xdev Host Manager authored 2 days ago
1324
      #login-error { margin-top: -32px; }
Xdev Host Manager authored 2 days ago
1325
    }
Xdev Host Manager authored 2 days ago
1326

            
1327
    /* ── App shell (hidden until authenticated) ── */
1328
    #app { display: none; }
1329
    header { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 12px 18px; background: var(--panel); border-bottom: 1px solid var(--line); position: sticky; top: 0; z-index: 2; }
1330
    h1 { margin: 0; font-size: 17px; font-weight: 700; }
1331
    .header-right { display: flex; align-items: center; gap: 10px; }
Xdev Host Manager authored 2 days ago
1332
    main { padding: 16px; display: grid; gap: 16px; max-width: 1280px; margin: 0 auto; }
1333
    .toolbar, .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; }
1334
    .toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px; }
1335
    .panel { overflow: hidden; }
1336
    .panel-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-bottom: 1px solid var(--line); background: #fafbfc; }
1337
    .panel-head h2 { margin: 0; font-size: 14px; }
1338
    .stats { display: flex; gap: 8px; flex-wrap: wrap; }
1339
    .stat { padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--soft); font-size: 12px; color: var(--muted); }
1340
    button, input, select, textarea { font: inherit; }
1341
    button, .linkbtn { border: 1px solid var(--line); background: #fff; color: var(--ink); border-radius: 6px; padding: 7px 10px; min-height: 34px; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; }
1342
    button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
Xdev Host Manager authored 2 days ago
1343
    button:disabled { opacity: .45; cursor: not-allowed; }
Xdev Host Manager authored 2 days ago
1344
    button.danger { color: var(--bad); }
Xdev Host Manager authored 2 days ago
1345
    button:disabled, .linkbtn[aria-disabled="true"] { opacity: .55; cursor: not-allowed; pointer-events: none; }
Xdev Host Manager authored 2 days ago
1346
    input, select, textarea { width: 100%; border: 1px solid var(--line); border-radius: 6px; padding: 8px; background: #fff; color: var(--ink); }
1347
    textarea { min-height: 74px; resize: vertical; }
1348
    table { width: 100%; border-collapse: collapse; table-layout: fixed; }
1349
    th, td { padding: 9px 10px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; overflow-wrap: anywhere; }
1350
    th { color: var(--muted); font-size: 12px; font-weight: 700; background: #fafbfc; }
1351
    tr:hover td { background: #f8fafc; }
1352
    .pill { display: inline-block; padding: 2px 6px; border-radius: 999px; background: var(--soft); border: 1px solid var(--line); color: var(--muted); font-size: 12px; margin: 0 4px 4px 0; }
1353
    .pill.ok { color: var(--ok); border-color: #b7dfc1; background: #edf8ef; }
1354
    .pill.warn { color: var(--warn); border-color: #f1d184; background: #fff7df; }
1355
    .pill.bad { color: var(--bad); border-color: #f0b8b3; background: #fff0ee; }
1356
    .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; padding: 14px; }
1357
    .span2 { grid-column: 1 / -1; }
1358
    label { display: grid; gap: 5px; color: var(--muted); font-size: 12px; font-weight: 650; }
1359
    .muted { color: var(--muted); }
Bogdan Timofte authored a day ago
1360
    .build-badge {
1361
      position: fixed;
1362
      right: 10px;
1363
      bottom: 8px;
1364
      z-index: 5;
1365
      color: rgba(255,255,255,.46);
1366
      background: rgba(19,24,42,.28);
1367
      border: 1px solid rgba(255,255,255,.08);
1368
      border-radius: 4px;
1369
      padding: 2px 5px;
1370
      font-size: 10px;
1371
      line-height: 1.2;
1372
      pointer-events: none;
1373
      user-select: none;
1374
    }
1375
    body.is-app .build-badge {
1376
      color: rgba(100,112,132,.58);
1377
      background: rgba(255,255,255,.72);
1378
      border-color: rgba(216,222,232,.72);
1379
    }
Xdev Host Manager authored 2 days ago
1380
    .problems { padding: 10px 14px; display: grid; gap: 8px; }
1381
    .problem { border-left: 3px solid var(--warn); padding: 7px 9px; background: #fffaf0; }
Bogdan Timofte authored a day ago
1382
    .work-order-card { display: grid; gap: 8px; min-width: 0; }
1383
    .work-order-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
1384
    .work-order-title { color: var(--ink); font-size: 14px; font-weight: 650; }
1385
    .work-order-checklist, .work-order-actions { display: grid; gap: 6px; min-width: 0; }
1386
    .work-order-actions { gap: 4px; }
1387
    .work-order-checkitem { display: flex; align-items: flex-start; gap: 8px; min-width: 0; color: var(--ink); font-size: 13px; font-weight: 400; }
1388
    .work-order-checkitem input[type="checkbox"] { width: auto; flex: 0 0 auto; margin: 2px 0 0; }
1389
    .work-order-checkitem span { min-width: 0; overflow-wrap: anywhere; }
Xdev Host Manager authored 2 days ago
1390
    @media (max-width: 760px) {
1391
      .grid { grid-template-columns: 1fr; }
1392
      table { min-width: 760px; }
1393
      .table-wrap { overflow-x: auto; }
1394
    }
1395
  </style>
1396
</head>
Bogdan Timofte authored a day ago
1397
<body class="is-login">
Xdev Host Manager authored 2 days ago
1398

            
Xdev Host Manager authored 2 days ago
1399
  <!-- ── Login screen ── -->
1400
  <div id="login-screen">
1401
    <div class="login-card">
1402
      <div class="brand">
1403
        <div class="icon">
Xdev Host Manager authored 2 days ago
1404
          <svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
1405
            <rect x="16" y="10" width="32" height="44" rx="4"/>
1406
            <rect x="21" y="16" width="22" height="8" rx="2"/>
1407
            <rect x="21" y="28" width="22" height="8" rx="2"/>
1408
            <rect x="21" y="40" width="22" height="8" rx="2"/>
1409
            <path d="M26 20h8M26 32h8M26 44h8"/>
1410
            <path d="M40 20h.01M40 32h.01M40 44h.01"/>
Xdev Host Manager authored 2 days ago
1411
          </svg>
1412
        </div>
Xdev Host Manager authored 2 days ago
1413
        <h1>Madagascar Local Authority</h1>
1414
        <p>Hosts, DNS &amp; Local CA</p>
Xdev Host Manager authored 2 days ago
1415
      </div>
Bogdan Timofte authored a day ago
1416
      <form id="login-form" method="post" action="/api/login" autocomplete="on" novalidate>
1417
        <div class="pm-helper-fields" aria-hidden="true">
1418
          <input type="text" id="login-account" name="username" autocomplete="username" autocapitalize="off" spellcheck="false">
1419
          <input type="text" id="otp-autofill" name="code" inputmode="numeric" pattern="[0-9]*" autocomplete="one-time-code">
1420
          <input type="hidden" id="otp-hidden" name="otp">
1421
        </div>
Xdev Host Manager authored 2 days ago
1422
        <div class="otp-row">
Bogdan Timofte authored a day ago
1423
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 1">
1424
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 2">
1425
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 3">
1426
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 4">
1427
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 5">
1428
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 6">
Xdev Host Manager authored 2 days ago
1429
        </div>
1430
      </form>
1431
      <div id="login-error"></div>
1432
    </div>
1433
  </div>
1434

            
1435
  <!-- ── App (shown after login) ── -->
1436
  <div id="app">
1437
    <header>
Xdev Host Manager authored 2 days ago
1438
      <h1>Madagascar Local Authority</h1>
Xdev Host Manager authored 2 days ago
1439
      <div class="header-right">
1440
        <span class="muted" id="app-updated"></span>
1441
        <button type="button" id="logout">Logout</button>
Xdev Host Manager authored 2 days ago
1442
      </div>
Xdev Host Manager authored 2 days ago
1443
    </header>
1444
    <main>
1445
      <section class="toolbar">
1446
        <button id="refresh">Refresh</button>
1447
        <a class="linkbtn" href="/download/hosts.yaml">hosts.yaml</a>
1448
        <a class="linkbtn" href="/download/local-hosts.tsv">local-hosts.tsv</a>
1449
        <a class="linkbtn" href="/download/monitoring.json">monitoring.json</a>
1450
        <button id="write-tsv">Write local-hosts.tsv</button>
1451
        <span id="message" class="muted"></span>
1452
      </section>
1453

            
1454
      <section class="panel">
1455
        <div class="panel-head">
1456
          <h2>Overview</h2>
1457
          <div class="stats" id="stats"></div>
1458
        </div>
1459
        <div class="problems" id="problems"></div>
1460
      </section>
Xdev Host Manager authored 2 days ago
1461

            
Xdev Host Manager authored 2 days ago
1462
      <section class="panel">
1463
        <div class="panel-head">
Xdev Host Manager authored 2 days ago
1464
          <h2>Local Certificate Authority</h2>
Xdev Host Manager authored 2 days ago
1465
          <a class="linkbtn" href="/download/ca.crt">ca.crt</a>
1466
        </div>
1467
        <div class="problems" id="ca-status"></div>
1468
      </section>
1469

            
Xdev Host Manager authored 2 days ago
1470
      <section class="panel">
1471
        <div class="panel-head">
1472
          <h2>Work Orders</h2>
1473
          <div class="stats" id="wo-stats"></div>
1474
        </div>
1475
        <div class="problems" id="work-orders"></div>
1476
      </section>
1477

            
Xdev Host Manager authored 2 days ago
1478
      <section class="panel">
1479
        <div class="panel-head">
1480
          <h2>Hosts</h2>
1481
          <input id="filter" placeholder="filter" style="max-width: 240px">
Xdev Host Manager authored 2 days ago
1482
        </div>
Xdev Host Manager authored 2 days ago
1483
        <div class="table-wrap">
1484
          <table>
1485
            <thead>
1486
              <tr>
1487
                <th style="width: 120px">ID</th>
1488
                <th style="width: 130px">hosts_ip</th>
1489
                <th style="width: 130px">dns_ip</th>
1490
                <th>Names</th>
1491
                <th style="width: 150px">Roles</th>
1492
                <th style="width: 110px">Monitoring</th>
1493
                <th style="width: 90px">Status</th>
1494
              </tr>
1495
            </thead>
1496
            <tbody id="hosts"></tbody>
1497
          </table>
1498
        </div>
1499
      </section>
1500

            
1501
      <section class="panel">
1502
        <div class="panel-head">
1503
          <h2>Edit host</h2>
1504
        </div>
1505
        <form id="host-form" class="grid">
1506
          <label>ID<input name="id" required></label>
1507
          <label>Status<select name="status"><option>active</option><option>planned</option><option>retired</option></select></label>
1508
          <label>hosts_ip<input name="hosts_ip" required></label>
1509
          <label>dns_ip<input name="dns_ip" required></label>
1510
          <label class="span2">Names<textarea name="names" required></textarea></label>
1511
          <label>Roles<input name="roles"></label>
1512
          <label>Sources<input name="sources"></label>
1513
          <label>Monitoring<select name="monitoring"><option>pending</option><option>enabled</option><option>disabled</option></select></label>
1514
          <label>Notes<input name="notes"></label>
1515
          <div class="span2">
1516
            <button class="primary" type="submit">Save host</button>
1517
            <button class="danger" type="button" id="delete-host">Delete host</button>
1518
          </div>
1519
        </form>
1520
      </section>
1521
    </main>
1522
  </div>
1523

            
Bogdan Timofte authored a day ago
1524
  <div class="build-badge" title="Running build __HOST_MANAGER_BUILD_TITLE__">build __HOST_MANAGER_BUILD__</div>
1525

            
Xdev Host Manager authored 2 days ago
1526
  <script>
Xdev Host Manager authored 2 days ago
1527
    let state = { hosts: [], problems: [], workOrders: [], authenticated: false };
Xdev Host Manager authored 2 days ago
1528

            
1529
    const $ = (id) => document.getElementById(id);
1530
    const msg = (text) => { $('message').textContent = text || ''; };
1531

            
1532
    async function api(path, options = {}) {
1533
      const res = await fetch(path, options);
1534
      const body = await res.json();
1535
      if (!res.ok) throw new Error(body.error || res.statusText);
1536
      return body;
1537
    }
1538

            
Xdev Host Manager authored 2 days ago
1539
    function showLogin(errorText) {
Bogdan Timofte authored a day ago
1540
      document.body.classList.remove('is-app');
1541
      document.body.classList.add('is-login');
Xdev Host Manager authored 2 days ago
1542
      $('app').style.display = 'none';
1543
      $('login-screen').style.display = 'flex';
1544
      $('login-error').textContent = errorText || '';
Bogdan Timofte authored a day ago
1545
      clearOtp();
Xdev Host Manager authored 2 days ago
1546
    }
1547

            
1548
    function showApp() {
Bogdan Timofte authored a day ago
1549
      document.body.classList.remove('is-login');
1550
      document.body.classList.add('is-app');
Xdev Host Manager authored 2 days ago
1551
      $('login-screen').style.display = 'none';
1552
      $('app').style.display = 'block';
1553
    }
1554

            
Xdev Host Manager authored 2 days ago
1555
    async function refresh() {
1556
      const session = await api('/api/session');
1557
      state.authenticated = session.authenticated;
Xdev Host Manager authored 2 days ago
1558
      if (!state.authenticated) { showLogin(); return; }
1559
      showApp();
Xdev Host Manager authored 2 days ago
1560
      const data = await api('/api/hosts');
1561
      state.hosts = data.hosts || [];
1562
      state.problems = data.problems || [];
1563
      render(data);
Xdev Host Manager authored 2 days ago
1564
      await renderCa();
Xdev Host Manager authored 2 days ago
1565
      await renderWorkOrders();
Xdev Host Manager authored 2 days ago
1566
    }
1567

            
1568
    function render(data) {
Xdev Host Manager authored 2 days ago
1569
      $('app-updated').textContent = data.updated_at ? 'updated ' + data.updated_at : '';
1570

            
Xdev Host Manager authored 2 days ago
1571
      $('stats').innerHTML = [
1572
        ['hosts', data.counts.hosts],
1573
        ['problems', data.counts.problems],
1574
      ].map(([k, v]) => `<span class="stat">${k}: ${escapeHtml(String(v))}</span>`).join('');
1575

            
1576
      $('problems').innerHTML = state.problems.length
1577
        ? state.problems.map(p => `<div class="problem"><strong>${escapeHtml(p.host_id)}</strong> ${escapeHtml(p.code)}: ${escapeHtml(p.message)}</div>`).join('')
1578
        : '<div class="muted" style="padding: 8px 0">No registry problems detected.</div>';
1579

            
1580
      renderHosts();
1581
    }
1582

            
Xdev Host Manager authored 2 days ago
1583
    async function renderCa() {
1584
      try {
1585
        const status = await api('/api/ca/status');
1586
        if (!status.initialized) {
1587
          $('ca-status').innerHTML = '<div class="problem"><strong>not initialized</strong> Run <code>sudo scripts/ca_manager.sh init</code> on jumper.</div>';
1588
          return;
1589
        }
1590
        const certs = await api('/api/ca/certificates');
1591
        $('ca-status').innerHTML = `
1592
          <div class="muted" style="display:grid;gap:6px">
1593
            <div><strong>${escapeHtml(status.subject || '')}</strong></div>
1594
            <div>SHA256 ${escapeHtml(status.fingerprint_sha256 || '')}</div>
1595
            <div>valid ${escapeHtml(status.not_before || '')} - ${escapeHtml(status.not_after || '')}</div>
1596
            <div>${certs.length} issued certificate(s)</div>
1597
          </div>`;
1598
      } catch (e) {
1599
        $('ca-status').innerHTML = `<div class="problem"><strong>CA status unavailable</strong> ${escapeHtml(e.message)}</div>`;
1600
      }
1601
    }
1602

            
Xdev Host Manager authored 2 days ago
1603
    async function renderWorkOrders() {
1604
      try {
1605
        const data = await api('/api/work-orders');
1606
        state.workOrders = data.work_orders || [];
1607
        $('wo-stats').innerHTML = [
1608
          ['pending', data.counts.pending],
1609
          ['total', data.counts.work_orders],
1610
        ].map(([k, v]) => `<span class="stat">${k}: ${escapeHtml(String(v))}</span>`).join('');
1611

            
1612
        if (!state.workOrders.length) {
1613
          $('work-orders').innerHTML = '<div class="muted" style="padding: 8px 0">No work orders.</div>';
1614
          return;
1615
        }
1616

            
1617
        $('work-orders').innerHTML = state.workOrders.map(wo => {
Xdev Host Manager authored 2 days ago
1618
          const checklist = wo.checklist || [];
1619
          const doneItems = checklist.filter(item => (item.status || 'pending') === 'done').length;
1620
          const checklistComplete = checklist.length === 0 || doneItems === checklist.length;
1621
          const checklistHtml = checklist.map(item => {
1622
            const checked = (item.status || 'pending') === 'done' ? 'checked' : '';
Bogdan Timofte authored a day ago
1623
            return `<label class="work-order-checkitem">
Xdev Host Manager authored 2 days ago
1624
              <input type="checkbox" data-wo-checklist="${escapeHtml(wo.id)}" data-item-id="${escapeHtml(item.id || '')}" ${checked}>
1625
              <span><strong>${escapeHtml(item.id || '')}</strong> ${escapeHtml(item.text || '')}</span>
1626
            </label>`;
1627
          }).join('');
Xdev Host Manager authored 2 days ago
1628
          const actions = (wo.actions || []).map(a => {
1629
            const target = [a.host_id, a.name].filter(Boolean).join(' ');
1630
            return `<div><span class="pill">${escapeHtml(a.type || '')}</span> ${escapeHtml(target)}</div>`;
1631
          }).join('');
1632
          const statusClass = (wo.status || 'pending') === 'pending' ? 'warn' : 'ok';
1633
          const button = (wo.status || 'pending') === 'pending'
Xdev Host Manager authored 2 days ago
1634
            ? `<button type="button" class="primary" data-confirm-wo="${escapeHtml(wo.id)}" ${checklistComplete ? '' : 'disabled'}>Confirm</button>`
Xdev Host Manager authored 2 days ago
1635
            : '';
Bogdan Timofte authored a day ago
1636
          return `<div class="problem work-order-card">
1637
            <div class="work-order-head">
Xdev Host Manager authored 2 days ago
1638
              <div><strong>${escapeHtml(wo.id || '')}</strong> <span class="pill ${statusClass}">${escapeHtml(wo.status || 'pending')}</span> <span class="pill">${doneItems}/${checklist.length} done</span></div>
Xdev Host Manager authored 2 days ago
1639
              ${button}
1640
            </div>
Bogdan Timofte authored a day ago
1641
            <div class="work-order-title">${escapeHtml(wo.title || '')}</div>
Xdev Host Manager authored 2 days ago
1642
            <div class="muted">${escapeHtml(wo.reason || '')}</div>
Bogdan Timofte authored a day ago
1643
            <div class="work-order-checklist">${checklistHtml}</div>
1644
            <div class="work-order-actions">${actions}</div>
Xdev Host Manager authored 2 days ago
1645
            ${wo.confirmed_at ? `<div class="muted">confirmed ${escapeHtml(wo.confirmed_at)}</div>` : ''}
1646
          </div>`;
1647
        }).join('');
Xdev Host Manager authored 2 days ago
1648
        document.querySelectorAll('[data-wo-checklist]').forEach(input => input.addEventListener('change', () => updateWorkOrderChecklist(input.dataset.woChecklist, input.dataset.itemId, input.checked)));
Xdev Host Manager authored 2 days ago
1649
        document.querySelectorAll('[data-confirm-wo]').forEach(button => button.addEventListener('click', () => confirmWorkOrder(button.dataset.confirmWo)));
1650
      } catch (e) {
1651
        $('work-orders').innerHTML = `<div class="problem"><strong>Work orders unavailable</strong> ${escapeHtml(e.message)}</div>`;
1652
      }
1653
    }
1654

            
Xdev Host Manager authored 2 days ago
1655
    async function updateWorkOrderChecklist(id, itemId, checked) {
1656
      try {
1657
        await api('/api/work-orders/checklist', {
1658
          method: 'POST',
1659
          headers: { 'Content-Type': 'application/json' },
1660
          body: JSON.stringify({ id, item_id: itemId, status: checked ? 'done' : 'pending' })
1661
        });
1662
        msg('work order updated');
1663
        await refresh();
1664
      } catch (e) { msg(e.message); await refresh(); }
1665
    }
1666

            
Xdev Host Manager authored 2 days ago
1667
    async function confirmWorkOrder(id) {
1668
      const typed = prompt(`Type ${id} to confirm this work order`);
1669
      if (typed !== id) return;
1670
      try {
1671
        await api('/api/work-orders/confirm', {
1672
          method: 'POST',
1673
          headers: { 'Content-Type': 'application/json' },
1674
          body: JSON.stringify({ id, confirm: typed })
1675
        });
1676
        msg('work order confirmed; local-hosts.tsv written');
1677
        await refresh();
1678
      } catch (e) { msg(e.message); }
1679
    }
1680

            
Xdev Host Manager authored 2 days ago
1681
    function renderHosts() {
1682
      const filter = $('filter').value.toLowerCase();
1683
      $('hosts').innerHTML = state.hosts
1684
        .filter(h => JSON.stringify(h).toLowerCase().includes(filter))
1685
        .map(h => {
1686
          const problems = state.problems.filter(p => p.host_id === h.id);
1687
          const cls = problems.length ? 'warn' : 'ok';
1688
          return `<tr data-id="${escapeHtml(h.id)}">
1689
            <td><button type="button" data-edit="${escapeHtml(h.id)}">${escapeHtml(h.id)}</button></td>
1690
            <td>${escapeHtml(h.hosts_ip || '')}</td>
1691
            <td>${escapeHtml(h.dns_ip || '')}</td>
1692
            <td>${(h.names || []).map(n => `<span class="pill">${escapeHtml(n)}</span>`).join('')}</td>
1693
            <td>${(h.roles || []).map(n => `<span class="pill">${escapeHtml(n)}</span>`).join('')}</td>
1694
            <td><span class="pill ${cls}">${escapeHtml(h.monitoring || '')}</span></td>
1695
            <td>${escapeHtml(h.status || '')}</td>
1696
          </tr>`;
1697
        }).join('');
1698
      document.querySelectorAll('[data-edit]').forEach(button => button.addEventListener('click', () => editHost(button.dataset.edit)));
1699
    }
1700

            
1701
    function editHost(id) {
1702
      const host = state.hosts.find(h => h.id === id);
1703
      if (!host) return;
1704
      const form = $('host-form');
1705
      for (const key of ['id', 'status', 'hosts_ip', 'dns_ip', 'monitoring', 'notes']) form.elements[key].value = host[key] || '';
1706
      form.elements.names.value = (host.names || []).join('\n');
1707
      form.elements.roles.value = (host.roles || []).join(' ');
1708
      form.elements.sources.value = (host.sources || []).join(' ');
Xdev Host Manager authored 2 days ago
1709
      form.scrollIntoView({ behavior: 'smooth', block: 'start' });
Xdev Host Manager authored 2 days ago
1710
    }
1711

            
1712
    function formObject(form) {
1713
      return Object.fromEntries(new FormData(form).entries());
1714
    }
1715

            
1716
    function escapeHtml(value) {
1717
      return value.replace(/[&<>"']/g, ch => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[ch]));
1718
    }
1719

            
Bogdan Timofte authored a day ago
1720
    const ACCOUNT_STORAGE_KEY = 'mla_last_account';
1721

            
Xdev Host Manager authored 2 days ago
1722
    // OTP digit boxes — auto-advance, backspace, paste
1723
    const otpDigits = Array.from(document.querySelectorAll('.otp-digit'));
Bogdan Timofte authored a day ago
1724
    const otpAutofill = $('otp-autofill');
1725
    const otpHidden = $('otp-hidden');
1726
    const loginAccount = $('login-account');
1727

            
1728
    if (loginAccount) {
1729
      const rememberedAccount = localStorage.getItem(ACCOUNT_STORAGE_KEY);
1730
      if (rememberedAccount && !loginAccount.value) loginAccount.value = rememberedAccount;
1731
      loginAccount.addEventListener('input', () => {
1732
        const value = (loginAccount.value || '').trim();
1733
        if (value) localStorage.setItem(ACCOUNT_STORAGE_KEY, value);
1734
      });
1735
    }
1736

            
Xdev Host Manager authored 2 days ago
1737
    otpDigits[0].focus();
1738

            
1739
    otpDigits.forEach((input, idx) => {
1740
      input.addEventListener('keydown', (e) => {
1741
        if (e.key === 'Backspace') {
Bogdan Timofte authored a day ago
1742
          if (input.value) setOtpDigit(idx, '');
1743
          else if (idx > 0) { setOtpDigit(idx - 1, ''); otpDigits[idx - 1].focus(); }
1744
          syncOtpFields();
Xdev Host Manager authored 2 days ago
1745
          e.preventDefault();
1746
        }
1747
      });
Xdev Host Manager authored 2 days ago
1748
      input.addEventListener('input', () => {
1749
        const digits = input.value.replace(/\D/g, '');
1750
        if (digits.length > 1) {
1751
          fillOtp(digits, digits.length >= otpDigits.length ? 0 : idx);
1752
          return;
1753
        }
1754
        setOtpDigit(idx, digits);
Bogdan Timofte authored a day ago
1755
        syncOtpFields();
Xdev Host Manager authored 2 days ago
1756
        if (digits && idx < otpDigits.length - 1) otpDigits[idx + 1].focus();
1757
        maybeSubmitOtp();
Xdev Host Manager authored 2 days ago
1758
      });
1759
      input.addEventListener('paste', (e) => {
1760
        const text = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '');
1761
        e.preventDefault();
Xdev Host Manager authored 2 days ago
1762
        fillOtp(text, text.length >= otpDigits.length ? 0 : idx);
Xdev Host Manager authored 2 days ago
1763
      });
1764
    });
1765

            
Xdev Host Manager authored 2 days ago
1766
    function setOtpDigit(idx, value) {
1767
      const digit = (value || '').replace(/\D/g, '').slice(0, 1);
1768
      otpDigits[idx].value = digit;
1769
      otpDigits[idx].classList.toggle('filled', !!digit);
1770
    }
1771

            
1772
    function fillOtp(text, startIdx = 0) {
1773
      const digits = (text || '').replace(/\D/g, '').slice(0, otpDigits.length);
1774
      if (!digits) return;
1775
      if (digits.length >= otpDigits.length) {
1776
        otpDigits.forEach((_, i) => setOtpDigit(i, digits[i] || ''));
1777
      } else {
1778
        digits.split('').forEach((ch, offset) => {
1779
          const targetIdx = startIdx + offset;
1780
          if (targetIdx < otpDigits.length) setOtpDigit(targetIdx, ch);
1781
        });
1782
      }
Bogdan Timofte authored a day ago
1783
      syncOtpFields();
Xdev Host Manager authored 2 days ago
1784
      const next = Math.min((digits.length >= otpDigits.length ? digits.length : startIdx + digits.length), otpDigits.length - 1);
1785
      otpDigits[next].focus();
1786
      maybeSubmitOtp();
1787
    }
1788

            
Xdev Host Manager authored 2 days ago
1789
    function getOtp() { return otpDigits.map(i => i.value).join(''); }
Bogdan Timofte authored a day ago
1790
    function syncOtpFields() {
1791
      const otp = getOtp();
1792
      if (otpHidden) otpHidden.value = otp;
1793
      if (otpAutofill && otpAutofill.value !== otp) otpAutofill.value = otp;
1794
    }
Xdev Host Manager authored 2 days ago
1795
    function otpReady() { return otpDigits.every(i => /^\d$/.test(i.value)); }
Xdev Host Manager authored 2 days ago
1796
    function maybeSubmitOtp() { if (otpReady()) $('login-form').requestSubmit(); }
Bogdan Timofte authored a day ago
1797
    function clearOtp() {
1798
      otpDigits.forEach(i => { i.value = ''; i.classList.remove('filled'); });
1799
      if (otpAutofill) otpAutofill.value = '';
1800
      if (otpHidden) otpHidden.value = '';
1801
      otpDigits[0].focus();
1802
    }
1803

            
1804
    if (otpAutofill) {
1805
      const handleAutofill = () => fillOtp(otpAutofill.value, 0);
1806
      otpAutofill.addEventListener('input', handleAutofill);
1807
      otpAutofill.addEventListener('change', handleAutofill);
1808
    }
Xdev Host Manager authored 2 days ago
1809

            
1810
    $('login-form').addEventListener('submit', async (event) => {
1811
      event.preventDefault();
Xdev Host Manager authored 2 days ago
1812
      if (!otpReady()) return;
1813
      $('login-form').classList.add('busy');
Xdev Host Manager authored 2 days ago
1814
      $('login-error').textContent = '';
Xdev Host Manager authored 2 days ago
1815
      try {
Xdev Host Manager authored 2 days ago
1816
        await api('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ otp: getOtp() }) });
Xdev Host Manager authored 2 days ago
1817
        await refresh();
Xdev Host Manager authored 2 days ago
1818
      } catch (e) {
1819
        showLogin(e.message === 'invalid_otp' ? 'Cod incorect.' : e.message);
1820
      } finally {
Xdev Host Manager authored 2 days ago
1821
        $('login-form').classList.remove('busy');
Xdev Host Manager authored 2 days ago
1822
      }
Xdev Host Manager authored 2 days ago
1823
    });
1824

            
1825
    $('logout').addEventListener('click', async () => {
1826
      await api('/api/logout', { method: 'POST' }).catch(() => {});
Xdev Host Manager authored 2 days ago
1827
      clearOtp();
1828
      showLogin();
Xdev Host Manager authored 2 days ago
1829
    });
1830

            
Xdev Host Manager authored 2 days ago
1831
    $('refresh').addEventListener('click', () => refresh().catch(e => msg(e.message)));
1832
    $('filter').addEventListener('input', renderHosts);
1833

            
Xdev Host Manager authored 2 days ago
1834
    $('host-form').addEventListener('submit', async (event) => {
1835
      event.preventDefault();
1836
      try {
1837
        await api('/api/hosts/upsert', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formObject(event.target)) });
1838
        msg('host saved');
1839
        await refresh();
1840
      } catch (e) { msg(e.message); }
1841
    });
1842

            
1843
    $('delete-host').addEventListener('click', async () => {
1844
      const id = $('host-form').elements.id.value;
1845
      if (!id || !confirm(`Delete ${id}?`)) return;
1846
      try {
1847
        await api('/api/hosts/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) });
1848
        $('host-form').reset();
1849
        msg('host deleted');
1850
        await refresh();
1851
      } catch (e) { msg(e.message); }
1852
    });
1853

            
1854
    $('write-tsv').addEventListener('click', async () => {
1855
      if (!confirm('Write config/local-hosts.tsv from hosts.yaml?')) return;
1856
      try {
1857
        await api('/api/render/local-hosts-tsv', { method: 'POST' });
1858
        msg('local-hosts.tsv written');
1859
      } catch (e) { msg(e.message); }
1860
    });
1861

            
Xdev Host Manager authored 2 days ago
1862
    refresh().catch(() => showLogin());
Xdev Host Manager authored 2 days ago
1863
  </script>
1864
</body>
1865
</html>
1866
HTML
Bogdan Timofte authored a day ago
1867
    $html =~ s/__HOST_MANAGER_BUILD_TITLE__/$build_title/g;
1868
    $html =~ s/__HOST_MANAGER_BUILD__/$build/g;
1869
    return $html;
Xdev Host Manager authored 2 days ago
1870
}