LocalAuthority / scripts / host_manager.pl
Newer Older
a081702 12 hours ago History
2112 lines | 79.817kb
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

            
Bogdan Timofte authored 12 hours ago
113
    if ($method eq 'GET' && app_page_path($path)) {
Xdev Host Manager authored 2 days ago
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
    }
Bogdan Timofte authored 12 hours ago
166
    if ($method eq 'GET' && $path =~ m{\A/download/ca/cert/([A-Za-z0-9_.-]+)\.crt\z}) {
167
        my $name = $1;
168
        return send_file($client, ca_issued_cert_path($name), 'application/x-pem-file; charset=utf-8', "$name.crt");
169
    }
Xdev Host Manager authored 2 days ago
170

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

            
197
    return send_json($client, 404, { error => 'not_found' });
198
}
199

            
Bogdan Timofte authored 12 hours ago
200
sub app_page_path {
201
    my ($path) = @_;
202
    return $path =~ m{\A/(?:|overview|hosts|dns|work-orders|ca)\z};
203
}
204

            
Xdev Host Manager authored 2 days ago
205
sub load_registry {
206
    return parse_hosts_yaml(read_file($opt{data}));
207
}
208

            
209
sub save_registry {
210
    my ($registry) = @_;
211
    $registry->{updated_at} = iso_now();
212
    backup_file($opt{data});
213
    write_file($opt{data}, render_hosts_yaml($registry));
214
}
215

            
Xdev Host Manager authored 2 days ago
216
sub load_work_orders {
217
    return { version => 1, work_orders => [] } unless -f $opt{work_orders};
218
    return parse_work_orders_yaml(read_file($opt{work_orders}));
219
}
220

            
221
sub save_work_orders {
222
    my ($orders) = @_;
223
    backup_file($opt{work_orders});
224
    write_file($opt{work_orders}, render_work_orders_yaml($orders));
225
}
226

            
227
sub work_orders_payload {
228
    my ($orders) = @_;
229
    my $pending = 0;
230
    for my $wo (@{ $orders->{work_orders} || [] }) {
231
        $pending++ if ($wo->{status} || 'pending') eq 'pending';
232
    }
233
    return {
234
        version => $orders->{version},
235
        work_orders => $orders->{work_orders} || [],
236
        counts => {
237
            work_orders => scalar @{ $orders->{work_orders} || [] },
238
            pending => $pending,
239
        },
240
    };
241
}
242

            
243
sub confirm_work_order {
244
    my ($client, $payload) = @_;
245
    my $id = clean_scalar($payload->{id} || '');
246
    return send_json($client, 400, { error => 'invalid_work_order_id' }) unless $id =~ /\AWO-[A-Za-z0-9_.-]+\z/;
247
    return send_json($client, 400, { error => 'confirmation_required' }) unless clean_scalar($payload->{confirm} || '') eq $id;
248

            
249
    my $orders = load_work_orders();
250
    my $work_order;
251
    for my $wo (@{ $orders->{work_orders} || [] }) {
252
        if (($wo->{id} || '') eq $id) {
253
            $work_order = $wo;
254
            last;
255
        }
256
    }
257
    return send_json($client, 404, { error => 'work_order_not_found' }) unless $work_order;
258
    return send_json($client, 409, { error => 'work_order_not_pending' }) unless ($work_order->{status} || 'pending') eq 'pending';
Xdev Host Manager authored 2 days ago
259
    my $incomplete = incomplete_work_order_items($work_order);
260
    return send_json($client, 409, {
261
        error => 'work_order_incomplete',
262
        incomplete => $incomplete,
263
    }) if @$incomplete;
Xdev Host Manager authored 2 days ago
264

            
265
    my $registry = load_registry();
266
    my $results = apply_work_order($registry, $work_order);
267
    $work_order->{status} = 'confirmed';
268
    $work_order->{confirmed_at} = iso_now();
269
    $work_order->{result} = scalar(@$results) . ' action(s) applied';
270

            
271
    save_registry($registry);
272
    save_work_orders($orders);
273
    backup_file($opt{local_hosts_tsv});
274
    write_file($opt{local_hosts_tsv}, render_local_hosts_tsv($registry));
275

            
276
    return send_json($client, 200, {
277
        ok => json_bool(1),
278
        work_order => $work_order,
279
        results => $results,
280
        local_hosts_tsv => $opt{local_hosts_tsv},
281
    });
282
}
283

            
Xdev Host Manager authored 2 days ago
284
sub update_work_order_checklist {
285
    my ($client, $payload) = @_;
286
    my $id = clean_scalar($payload->{id} || '');
287
    my $item_id = clean_scalar($payload->{item_id} || '');
288
    my $status = clean_scalar($payload->{status} || '');
289
    my $notes = clean_scalar($payload->{notes} || '');
290
    return send_json($client, 400, { error => 'invalid_work_order_id' }) unless $id =~ /\AWO-[A-Za-z0-9_.-]+\z/;
291
    return send_json($client, 400, { error => 'invalid_checklist_item' }) unless $item_id =~ /\A[A-Za-z0-9_.-]+\z/;
292
    return send_json($client, 400, { error => 'invalid_checklist_status' }) unless $status =~ /\A(?:pending|done|blocked)\z/;
293

            
294
    my $orders = load_work_orders();
295
    my $work_order;
296
    for my $wo (@{ $orders->{work_orders} || [] }) {
297
        if (($wo->{id} || '') eq $id) {
298
            $work_order = $wo;
299
            last;
300
        }
301
    }
302
    return send_json($client, 404, { error => 'work_order_not_found' }) unless $work_order;
303
    return send_json($client, 409, { error => 'work_order_not_pending' }) unless ($work_order->{status} || 'pending') eq 'pending';
304

            
305
    my $item;
306
    for my $candidate (@{ $work_order->{checklist} || [] }) {
307
        if (($candidate->{id} || '') eq $item_id) {
308
            $item = $candidate;
309
            last;
310
        }
311
    }
312
    return send_json($client, 404, { error => 'checklist_item_not_found' }) unless $item;
313

            
314
    $item->{status} = $status;
315
    $item->{updated_at} = iso_now();
316
    $item->{notes} = $notes if length $notes;
317
    save_work_orders($orders);
318
    return send_json($client, 200, { ok => json_bool(1), work_order => $work_order });
319
}
320

            
321
sub incomplete_work_order_items {
322
    my ($work_order) = @_;
323
    my @incomplete;
324
    for my $item (@{ $work_order->{checklist} || [] }) {
325
        push @incomplete, $item unless ($item->{status} || 'pending') eq 'done';
326
    }
327
    return \@incomplete;
328
}
329

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

            
Xdev Host Manager authored 2 days ago
359
sub registry_payload {
360
    my ($registry) = @_;
361
    my $problems = analyze_hosts($registry->{hosts});
Xdev Host Manager authored 2 days ago
362
    my @hosts = map { host_payload($_) } @{ $registry->{hosts} };
Xdev Host Manager authored 2 days ago
363
    return {
364
        version => $registry->{version},
365
        updated_at => $registry->{updated_at},
366
        policy => $registry->{policy},
Xdev Host Manager authored 2 days ago
367
        hosts => \@hosts,
Xdev Host Manager authored 2 days ago
368
        problems => $problems,
369
        counts => {
370
            hosts => scalar @{ $registry->{hosts} },
371
            problems => scalar @$problems,
372
        },
373
    };
374
}
375

            
376
sub upsert_host {
377
    my ($client, $payload) = @_;
378
    my $id = clean_id($payload->{id} || '');
379
    return send_json($client, 400, { error => 'invalid_id' }) unless $id;
380

            
381
    my $hosts_ip = clean_scalar($payload->{hosts_ip} || '');
382
    my $dns_ip = clean_scalar($payload->{dns_ip} || '');
383
    return send_json($client, 400, { error => 'missing_ip' }) unless $hosts_ip && $dns_ip;
384

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

            
388
    my $registry = load_registry();
389
    my %host = (
390
        id => $id,
391
        status => clean_scalar($payload->{status} || 'active'),
392
        hosts_ip => $hosts_ip,
393
        dns_ip => $dns_ip,
394
        names => \@names,
395
        roles => [ clean_list($payload->{roles}) ],
396
        sources => [ clean_list($payload->{sources}) ],
397
        monitoring => clean_scalar($payload->{monitoring} || 'pending'),
398
        notes => clean_scalar($payload->{notes} || ''),
399
    );
400

            
401
    my $replaced = 0;
402
    for my $i (0 .. $#{ $registry->{hosts} }) {
403
        if ($registry->{hosts}->[$i]{id} eq $id) {
404
            $registry->{hosts}->[$i] = \%host;
405
            $replaced = 1;
406
            last;
407
        }
408
    }
409
    push @{ $registry->{hosts} }, \%host unless $replaced;
410
    save_registry($registry);
411
    return send_json($client, 200, { ok => json_bool(1), host => \%host });
412
}
413

            
414
sub delete_host {
415
    my ($client, $id) = @_;
416
    $id = clean_id($id);
417
    return send_json($client, 400, { error => 'invalid_id' }) unless $id;
418

            
419
    my $registry = load_registry();
420
    my @kept = grep { $_->{id} ne $id } @{ $registry->{hosts} };
421
    return send_json($client, 404, { error => 'not_found' }) if @kept == @{ $registry->{hosts} };
422
    $registry->{hosts} = \@kept;
423
    save_registry($registry);
424
    return send_json($client, 200, { ok => json_bool(1) });
425
}
426

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

            
Xdev Host Manager authored 2 days ago
454
sub host_payload {
455
    my ($host) = @_;
456
    my %copy = %$host;
457
    $copy{names} = [ effective_names($host) ];
458
    $copy{declared_names} = [ @{ $host->{names} || [] } ];
459
    $copy{derived_names} = [ derived_names($host) ];
460
    return \%copy;
461
}
462

            
463
sub effective_names {
464
    my ($host) = @_;
465
    my @names = @{ $host->{names} || [] };
466
    push @names, derived_names($host);
467
    return unique_preserve(@names);
468
}
469

            
470
sub derived_names {
471
    my ($host) = @_;
472
    my @derived;
473
    for my $name (@{ $host->{names} || [] }) {
474
        next unless $name =~ /^(.+)\.madagascar\.xdev\.ro$/;
475
        push @derived, $1 if length $1;
476
    }
477
    return unique_preserve(@derived);
478
}
479

            
480
sub remove_derived_names {
481
    my @names = @_;
482
    my %derived;
483
    for my $name (@names) {
484
        next unless $name =~ /^(.+)\.madagascar\.xdev\.ro$/;
485
        $derived{$1} = 1;
486
    }
487
    return grep { !$derived{$_} } @names;
488
}
489

            
490
sub unique_preserve {
491
    my @values = @_;
492
    my %seen;
493
    return grep { !$seen{$_}++ } @values;
494
}
495

            
Xdev Host Manager authored 2 days ago
496
sub problem {
497
    my ($host, $code, $message) = @_;
498
    return { host_id => $host->{id}, code => $code, message => $message };
499
}
500

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

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

            
Xdev Host Manager authored 2 days ago
549
sub ca_script_path {
550
    return "$project_dir/scripts/ca_manager.sh";
551
}
552

            
553
sub ca_dir {
554
    return $ENV{HOST_MANAGER_CA_DIR} || "$project_dir/var/ca";
555
}
556

            
557
sub ca_cert_path {
558
    return ca_dir() . "/certs/ca.cert.pem";
559
}
560

            
Bogdan Timofte authored 12 hours ago
561
sub ca_issued_cert_path {
562
    my ($name) = @_;
563
    die "unsafe certificate name\n" unless $name =~ /\A[A-Za-z0-9_.-]+\z/;
564
    return ca_dir() . "/issued/$name.cert.pem";
565
}
566

            
Xdev Host Manager authored 2 days ago
567
sub ca_manager_json {
568
    my ($command) = @_;
569
    my $script = ca_script_path();
570
    die "CA manager script is missing\n" unless -x $script;
571
    local $ENV{HOST_MANAGER_CA_DIR} = ca_dir();
572
    open my $fh, '-|', $script, $command or die "Cannot run CA manager\n";
573
    local $/;
574
    my $out = <$fh>;
575
    close $fh or die "CA manager failed\n";
576
    return $out || '{}';
577
}
578

            
Xdev Host Manager authored 2 days ago
579
sub parse_hosts_yaml {
580
    my ($text) = @_;
581
    my %registry = (
582
        version => 1,
583
        updated_at => '',
584
        policy => {},
585
        hosts => [],
586
    );
587
    my ($section, $current, $list_key);
588
    for my $line (split /\n/, $text) {
589
        next if $line =~ /^\s*$/ || $line =~ /^\s*#/;
590
        if ($line =~ /^version:\s*(\d+)/) {
591
            $registry{version} = int($1);
592
        } elsif ($line =~ /^updated_at:\s*(.+)$/) {
593
            $registry{updated_at} = yaml_unquote($1);
594
        } elsif ($line =~ /^policy:\s*$/) {
595
            $section = 'policy';
596
        } elsif ($line =~ /^hosts:\s*$/) {
597
            $section = 'hosts';
598
        } elsif (($section || '') eq 'policy' && $line =~ /^  ([A-Za-z0-9_]+):\s*(.+)$/) {
599
            $registry{policy}{$1} = yaml_unquote($2);
600
        } elsif (($section || '') eq 'hosts' && $line =~ /^  - id:\s*(.+)$/) {
601
            $current = {
602
                id => yaml_unquote($1),
603
                status => 'active',
604
                hosts_ip => '',
605
                dns_ip => '',
606
                names => [],
607
                roles => [],
608
                sources => [],
609
                monitoring => 'pending',
610
                notes => '',
611
            };
612
            push @{ $registry{hosts} }, $current;
613
            $list_key = undef;
614
        } elsif ($current && $line =~ /^    ([A-Za-z0-9_]+):\s*$/) {
615
            $list_key = $1;
616
            $current->{$list_key} ||= [];
617
        } elsif ($current && defined $list_key && $line =~ /^      -\s*(.+)$/) {
618
            push @{ $current->{$list_key} }, yaml_unquote($1);
619
        } elsif ($current && $line =~ /^    ([A-Za-z0-9_]+):\s*(.*)$/) {
620
            $current->{$1} = yaml_unquote($2);
621
            $list_key = undef;
622
        }
623
    }
624
    return \%registry;
625
}
626

            
627
sub render_hosts_yaml {
628
    my ($registry) = @_;
629
    my $out = "version: " . int($registry->{version} || 1) . "\n";
630
    $out .= "updated_at: " . yq($registry->{updated_at} || iso_now()) . "\n";
631
    $out .= "policy:\n";
632
    for my $key (sort keys %{ $registry->{policy} || {} }) {
633
        $out .= "  $key: " . yq($registry->{policy}{$key}) . "\n";
634
    }
635
    $out .= "hosts:\n";
636
    for my $host (sort { $a->{id} cmp $b->{id} } @{ $registry->{hosts} || [] }) {
637
        $out .= "  - id: " . yq($host->{id}) . "\n";
638
        for my $key (qw(status hosts_ip dns_ip)) {
639
            $out .= "    $key: " . yq($host->{$key} || '') . "\n";
640
        }
641
        for my $key (qw(names roles sources)) {
642
            $out .= "    $key:\n";
643
            for my $value (@{ $host->{$key} || [] }) {
644
                $out .= "      - " . yq($value) . "\n";
645
            }
646
        }
647
        $out .= "    monitoring: " . yq($host->{monitoring} || 'pending') . "\n";
648
        $out .= "    notes: " . yq($host->{notes} || '') . "\n";
649
    }
650
    return $out;
651
}
652

            
Xdev Host Manager authored 2 days ago
653
sub parse_work_orders_yaml {
654
    my ($text) = @_;
655
    my %orders = (
656
        version => 1,
657
        work_orders => [],
658
    );
Xdev Host Manager authored 2 days ago
659
    my ($section, $current, $list_section, $current_action, $current_item);
Xdev Host Manager authored 2 days ago
660
    for my $line (split /\n/, $text) {
661
        next if $line =~ /^\s*$/ || $line =~ /^\s*#/;
662
        if ($line =~ /^version:\s*(\d+)/) {
663
            $orders{version} = int($1);
664
        } elsif ($line =~ /^work_orders:\s*$/) {
665
            $section = 'work_orders';
666
        } elsif (($section || '') eq 'work_orders' && $line =~ /^  - id:\s*(.+)$/) {
667
            $current = {
668
                id => yaml_unquote($1),
669
                status => 'pending',
Xdev Host Manager authored 2 days ago
670
                checklist => [],
Xdev Host Manager authored 2 days ago
671
                actions => [],
672
            };
673
            push @{ $orders{work_orders} }, $current;
Xdev Host Manager authored 2 days ago
674
            $list_section = '';
Xdev Host Manager authored 2 days ago
675
            $current_action = undef;
Xdev Host Manager authored 2 days ago
676
            $current_item = undef;
677
        } elsif ($current && $line =~ /^    checklist:\s*$/) {
678
            $list_section = 'checklist';
679
            $current->{checklist} ||= [];
680
        } elsif ($current && $list_section eq 'checklist' && $line =~ /^      - id:\s*(.+)$/) {
681
            $current_item = { id => yaml_unquote($1), status => 'pending' };
682
            push @{ $current->{checklist} }, $current_item;
683
            $current_action = undef;
684
        } elsif ($current_item && $list_section eq 'checklist' && $line =~ /^        ([A-Za-z0-9_]+):\s*(.*)$/) {
685
            $current_item->{$1} = yaml_unquote($2);
Xdev Host Manager authored 2 days ago
686
        } elsif ($current && $line =~ /^    actions:\s*$/) {
Xdev Host Manager authored 2 days ago
687
            $list_section = 'actions';
Xdev Host Manager authored 2 days ago
688
            $current->{actions} ||= [];
Xdev Host Manager authored 2 days ago
689
        } elsif ($current && $list_section eq 'actions' && $line =~ /^      - type:\s*(.+)$/) {
Xdev Host Manager authored 2 days ago
690
            $current_action = { type => yaml_unquote($1) };
691
            push @{ $current->{actions} }, $current_action;
Xdev Host Manager authored 2 days ago
692
            $current_item = undef;
693
        } elsif ($current_action && $list_section eq 'actions' && $line =~ /^        ([A-Za-z0-9_]+):\s*(.*)$/) {
Xdev Host Manager authored 2 days ago
694
            $current_action->{$1} = yaml_unquote($2);
695
        } elsif ($current && $line =~ /^    ([A-Za-z0-9_]+):\s*(.*)$/) {
696
            $current->{$1} = yaml_unquote($2);
Xdev Host Manager authored 2 days ago
697
            $list_section = '';
Xdev Host Manager authored 2 days ago
698
            $current_action = undef;
Xdev Host Manager authored 2 days ago
699
            $current_item = undef;
Xdev Host Manager authored 2 days ago
700
        }
701
    }
702
    return \%orders;
703
}
704

            
705
sub render_work_orders_yaml {
706
    my ($orders) = @_;
707
    my $out = "version: " . int($orders->{version} || 1) . "\n";
708
    $out .= "work_orders:\n";
709
    for my $wo (@{ $orders->{work_orders} || [] }) {
710
        $out .= "  - id: " . yq($wo->{id}) . "\n";
711
        for my $key (qw(status title reason created_at confirmed_at result)) {
712
            next unless exists $wo->{$key} && length($wo->{$key} || '');
713
            $out .= "    $key: " . yq($wo->{$key}) . "\n";
714
        }
Xdev Host Manager authored 2 days ago
715
        $out .= "    checklist:\n";
716
        for my $item (@{ $wo->{checklist} || [] }) {
717
            $out .= "      - id: " . yq($item->{id}) . "\n";
718
            for my $key (qw(text status owner notes updated_at)) {
719
                next unless exists $item->{$key} && length($item->{$key} || '');
720
                $out .= "        $key: " . yq($item->{$key}) . "\n";
721
            }
722
        }
Xdev Host Manager authored 2 days ago
723
        $out .= "    actions:\n";
724
        for my $action (@{ $wo->{actions} || [] }) {
725
            $out .= "      - type: " . yq($action->{type}) . "\n";
726
            for my $key (qw(host_id name)) {
727
                next unless exists $action->{$key} && length($action->{$key} || '');
728
                $out .= "        $key: " . yq($action->{$key}) . "\n";
729
            }
730
        }
731
    }
732
    return $out;
733
}
734

            
Xdev Host Manager authored 2 days ago
735
sub request_payload {
736
    my ($headers, $body) = @_;
737
    my $type = $headers->{'content-type'} || '';
738
    if ($type =~ m{application/json}) {
739
        return json_decode($body || '{}');
740
    }
741
    return { parse_params($body || '') };
742
}
743

            
744
sub json_bool {
745
    my ($value) = @_;
746
    return bless \(my $bool = $value ? 1 : 0), 'HostManager::JSONBool';
747
}
748

            
749
sub json_encode {
750
    my ($value) = @_;
751
    if (!defined $value) {
752
        return 'null';
753
    }
754
    my $ref = ref($value);
755
    if (!$ref) {
756
        return $value if $value =~ /\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?\z/;
757
        return json_string($value);
758
    }
759
    if ($ref eq 'HostManager::JSONBool') {
760
        return $$value ? 'true' : 'false';
761
    }
762
    if ($ref eq 'ARRAY') {
763
        return '[' . join(',', map { json_encode($_) } @$value) . ']';
764
    }
765
    if ($ref eq 'HASH') {
766
        return '{' . join(',', map { json_string($_) . ':' . json_encode($value->{$_}) } sort keys %$value) . '}';
767
    }
768
    return json_string("$value");
769
}
770

            
771
sub json_string {
772
    my ($value) = @_;
773
    $value = '' unless defined $value;
774
    $value =~ s/\\/\\\\/g;
775
    $value =~ s/"/\\"/g;
776
    $value =~ s/\n/\\n/g;
777
    $value =~ s/\r/\\r/g;
778
    $value =~ s/\t/\\t/g;
779
    $value =~ s/([\x00-\x1f])/sprintf("\\u%04x", ord($1))/eg;
780
    return qq("$value");
781
}
782

            
783
sub json_decode {
784
    my ($text) = @_;
785
    my $i = 0;
786
    my $len = length($text);
787
    my ($parse_value, $parse_string, $parse_array, $parse_object, $parse_number, $skip_ws);
788

            
789
    $skip_ws = sub {
790
        $i++ while $i < $len && substr($text, $i, 1) =~ /\s/;
791
    };
792

            
793
    $parse_string = sub {
794
        die "Expected JSON string\n" unless substr($text, $i, 1) eq '"';
795
        $i++;
796
        my $out = '';
797
        while ($i < $len) {
798
            my $ch = substr($text, $i++, 1);
799
            return $out if $ch eq '"';
800
            if ($ch eq "\\") {
801
                die "Bad JSON escape\n" if $i >= $len;
802
                my $esc = substr($text, $i++, 1);
803
                if ($esc eq '"' || $esc eq "\\" || $esc eq '/') {
804
                    $out .= $esc;
805
                } elsif ($esc eq 'b') {
806
                    $out .= "\b";
807
                } elsif ($esc eq 'f') {
808
                    $out .= "\f";
809
                } elsif ($esc eq 'n') {
810
                    $out .= "\n";
811
                } elsif ($esc eq 'r') {
812
                    $out .= "\r";
813
                } elsif ($esc eq 't') {
814
                    $out .= "\t";
815
                } elsif ($esc eq 'u') {
816
                    my $hex = substr($text, $i, 4);
817
                    die "Bad JSON unicode escape\n" unless $hex =~ /\A[0-9A-Fa-f]{4}\z/;
818
                    $out .= chr(hex($hex));
819
                    $i += 4;
820
                } else {
821
                    die "Bad JSON escape\n";
822
                }
823
            } else {
824
                $out .= $ch;
825
            }
826
        }
827
        die "Unterminated JSON string\n";
828
    };
829

            
830
    $parse_number = sub {
831
        my $start = $i;
832
        $i++ if substr($text, $i, 1) eq '-';
833
        $i++ while $i < $len && substr($text, $i, 1) =~ /[0-9]/;
834
        if ($i < $len && substr($text, $i, 1) eq '.') {
835
            $i++;
836
            $i++ while $i < $len && substr($text, $i, 1) =~ /[0-9]/;
837
        }
838
        if ($i < $len && substr($text, $i, 1) =~ /[eE]/) {
839
            $i++;
840
            $i++ if $i < $len && substr($text, $i, 1) =~ /[+-]/;
841
            $i++ while $i < $len && substr($text, $i, 1) =~ /[0-9]/;
842
        }
843
        return 0 + substr($text, $start, $i - $start);
844
    };
845

            
846
    $parse_array = sub {
847
        die "Expected JSON array\n" unless substr($text, $i, 1) eq '[';
848
        $i++;
849
        my @out;
850
        $skip_ws->();
851
        if ($i < $len && substr($text, $i, 1) eq ']') {
852
            $i++;
853
            return \@out;
854
        }
855
        while (1) {
856
            push @out, $parse_value->();
857
            $skip_ws->();
858
            my $ch = substr($text, $i++, 1);
859
            last if $ch eq ']';
860
            die "Expected JSON array comma\n" unless $ch eq ',';
861
        }
862
        return \@out;
863
    };
864

            
865
    $parse_object = sub {
866
        die "Expected JSON object\n" unless substr($text, $i, 1) eq '{';
867
        $i++;
868
        my %out;
869
        $skip_ws->();
870
        if ($i < $len && substr($text, $i, 1) eq '}') {
871
            $i++;
872
            return \%out;
873
        }
874
        while (1) {
875
            $skip_ws->();
876
            my $key = $parse_string->();
877
            $skip_ws->();
878
            die "Expected JSON object colon\n" unless substr($text, $i++, 1) eq ':';
879
            $out{$key} = $parse_value->();
880
            $skip_ws->();
881
            my $ch = substr($text, $i++, 1);
882
            last if $ch eq '}';
883
            die "Expected JSON object comma\n" unless $ch eq ',';
884
        }
885
        return \%out;
886
    };
887

            
888
    $parse_value = sub {
889
        $skip_ws->();
890
        die "Unexpected end of JSON\n" if $i >= $len;
891
        my $ch = substr($text, $i, 1);
892
        return $parse_string->() if $ch eq '"';
893
        return $parse_object->() if $ch eq '{';
894
        return $parse_array->() if $ch eq '[';
895
        if (substr($text, $i, 4) eq 'true') {
896
            $i += 4;
897
            return json_bool(1);
898
        }
899
        if (substr($text, $i, 5) eq 'false') {
900
            $i += 5;
901
            return json_bool(0);
902
        }
903
        if (substr($text, $i, 4) eq 'null') {
904
            $i += 4;
905
            return undef;
906
        }
907
        return $parse_number->() if $ch =~ /[-0-9]/;
908
        die "Unexpected JSON token\n";
909
    };
910

            
911
    my $value = $parse_value->();
912
    $skip_ws->();
913
    die "Trailing JSON content\n" if $i != $len;
914
    return $value;
915
}
916

            
917
sub parse_params {
918
    my ($text) = @_;
919
    my %out;
920
    for my $pair (split /&/, $text) {
921
        next unless length $pair;
922
        my ($k, $v) = split /=/, $pair, 2;
923
        $out{url_decode($k)} = url_decode($v || '');
924
    }
925
    return %out;
926
}
927

            
928
sub clean_id {
929
    my ($value) = @_;
930
    $value = lc clean_scalar($value);
931
    $value =~ s/[^a-z0-9_.-]+/-/g;
932
    $value =~ s/^-+|-+$//g;
933
    return $value;
934
}
935

            
936
sub clean_scalar {
937
    my ($value) = @_;
938
    $value = '' unless defined $value;
939
    $value =~ s/[\r\n\t]+/ /g;
940
    $value =~ s/^\s+|\s+$//g;
941
    return $value;
942
}
943

            
944
sub clean_list {
945
    my ($value) = @_;
946
    return () unless defined $value;
947
    my @items = ref($value) eq 'ARRAY' ? @$value : split /[\s,]+/, $value;
948
    my @clean;
949
    for my $item (@items) {
950
        $item = clean_scalar($item);
951
        push @clean, $item if length $item;
952
    }
953
    return @clean;
954
}
955

            
956
sub yq {
957
    my ($value) = @_;
958
    $value = '' unless defined $value;
959
    $value =~ s/\\/\\\\/g;
960
    $value =~ s/"/\\"/g;
961
    return qq("$value");
962
}
963

            
964
sub yaml_unquote {
965
    my ($value) = @_;
966
    $value = '' unless defined $value;
967
    $value =~ s/^\s+|\s+$//g;
968
    if ($value =~ /^"(.*)"$/) {
969
        $value = $1;
970
        $value =~ s/\\"/"/g;
971
        $value =~ s/\\\\/\\/g;
972
    }
973
    return $value;
974
}
975

            
976
sub verify_totp {
977
    my ($secret, $otp) = @_;
978
    return 0 unless $secret && $otp =~ /^\d{6}$/;
979
    my $key = eval { base32_decode($secret) };
980
    return 0 if $@ || !length $key;
981
    my $counter = int(time() / 30);
982
    for my $offset (-1, 0, 1) {
983
        return 1 if totp_code($key, $counter + $offset) eq $otp;
984
    }
985
    return 0;
986
}
987

            
988
sub totp_code {
989
    my ($key, $counter) = @_;
990
    my $msg = pack('NN', int($counter / 4294967296), $counter & 0xffffffff);
991
    my $hash = hmac_sha1($msg, $key);
992
    my $offset = ord(substr($hash, -1)) & 0x0f;
993
    my $bin = unpack('N', substr($hash, $offset, 4)) & 0x7fffffff;
994
    return sprintf('%06d', $bin % 1_000_000);
995
}
996

            
997
sub base32_decode {
998
    my ($text) = @_;
999
    $text = uc($text || '');
1000
    $text =~ s/[^A-Z2-7]//g;
1001
    my %map;
1002
    my @chars = ('A'..'Z', '2'..'7');
1003
    @map{@chars} = (0..31);
1004
    my ($bits, $value, $out) = (0, 0, '');
1005
    for my $char (split //, $text) {
1006
        die "Invalid base32\n" unless exists $map{$char};
1007
        $value = ($value << 5) | $map{$char};
1008
        $bits += 5;
1009
        while ($bits >= 8) {
1010
            $bits -= 8;
1011
            $out .= chr(($value >> $bits) & 0xff);
1012
        }
1013
    }
1014
    return $out;
1015
}
1016

            
1017
sub create_session {
1018
    my $nonce = random_hex(24);
1019
    my $expires = int(time() + 8 * 3600);
1020
    my $sig = hmac_sha256_hex("$nonce:$expires", $session_secret);
1021
    my $token = "$nonce:$expires:$sig";
1022
    $sessions{$token} = $expires;
1023
    return $token;
1024
}
1025

            
1026
sub is_authenticated {
1027
    my ($headers) = @_;
1028
    my $token = cookie_value($headers->{'cookie'} || '', 'hm_session');
1029
    return 0 unless $token;
1030
    my ($nonce, $expires, $sig) = split /:/, $token;
1031
    return 0 unless $nonce && $expires && $sig;
1032
    return 0 if $expires < time();
1033
    return 0 unless hmac_sha256_hex("$nonce:$expires", $session_secret) eq $sig;
1034
    return exists $sessions{$token};
1035
}
1036

            
1037
sub expire_session {
1038
    my ($headers) = @_;
1039
    my $token = cookie_value($headers->{'cookie'} || '', 'hm_session');
1040
    delete $sessions{$token} if $token;
1041
}
1042

            
1043
sub cookie_value {
1044
    my ($cookie, $name) = @_;
1045
    for my $part (split /;\s*/, $cookie) {
1046
        my ($k, $v) = split /=/, $part, 2;
1047
        return $v if defined $k && $k eq $name;
1048
    }
1049
    return '';
1050
}
1051

            
1052
sub send_json {
1053
    my ($client, $status, $payload, $extra_headers) = @_;
1054
    return send_response($client, $status, json_encode($payload), 'application/json; charset=utf-8', $extra_headers);
1055
}
1056

            
Xdev Host Manager authored 2 days ago
1057
sub send_json_raw {
1058
    my ($client, $status, $json_body, $extra_headers) = @_;
1059
    return send_response($client, $status, $json_body, 'application/json; charset=utf-8', $extra_headers);
1060
}
1061

            
Xdev Host Manager authored 2 days ago
1062
sub send_html {
1063
    my ($client, $status, $html) = @_;
1064
    return send_response($client, $status, $html, 'text/html; charset=utf-8');
1065
}
1066

            
1067
sub send_text {
1068
    my ($client, $status, $text) = @_;
1069
    return send_response($client, $status, $text, 'text/plain; charset=utf-8');
1070
}
1071

            
1072
sub send_download {
1073
    my ($client, $status, $content, $type, $filename) = @_;
1074
    return send_response($client, $status, $content, $type, [ qq(Content-Disposition: attachment; filename="$filename") ]);
1075
}
1076

            
1077
sub send_file {
1078
    my ($client, $path, $type, $filename) = @_;
1079
    return send_json($client, 404, { error => 'missing_file' }) unless -f $path;
1080
    return send_download($client, 200, read_file($path), $type, $filename);
1081
}
1082

            
1083
sub send_response {
1084
    my ($client, $status, $body, $type, $extra_headers) = @_;
Xdev Host Manager authored 2 days ago
1085
    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
1086
    $body = '' unless defined $body;
1087
    print $client "HTTP/1.1 $status " . ($reason{$status} || 'OK') . "\r\n";
1088
    print $client "Content-Type: $type\r\n";
1089
    print $client "Content-Length: " . length($body) . "\r\n";
1090
    print $client "Cache-Control: no-store\r\n";
1091
    print $client "$_\r\n" for @{ $extra_headers || [] };
1092
    print $client "Connection: close\r\n\r\n";
1093
    print $client $body;
1094
}
1095

            
1096
sub read_file {
1097
    my ($path) = @_;
1098
    open my $fh, '<', $path or die "Cannot read $path: $!";
1099
    local $/;
1100
    return <$fh>;
1101
}
1102

            
1103
sub write_file {
1104
    my ($path, $content) = @_;
1105
    open my $fh, '>', $path or die "Cannot write $path: $!";
1106
    print {$fh} $content;
1107
    close $fh or die "Cannot close $path: $!";
1108
}
1109

            
1110
sub backup_file {
1111
    my ($path) = @_;
1112
    return unless -f $path;
1113
    my $backup_dir = "$project_dir/backups/host-manager";
1114
    make_path($backup_dir) unless -d $backup_dir;
1115
    my $name = $path;
1116
    $name =~ s{.*/}{};
1117
    my $stamp = strftime('%Y%m%d_%H%M%S', localtime);
1118
    write_file("$backup_dir/$name.$stamp.bak", read_file($path));
1119
}
1120

            
1121
sub url_decode {
1122
    my ($value) = @_;
1123
    $value = '' unless defined $value;
1124
    $value =~ tr/+/ /;
1125
    $value =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
1126
    return $value;
1127
}
1128

            
1129
sub random_hex {
1130
    my ($bytes) = @_;
1131
    if (open my $fh, '<:raw', '/dev/urandom') {
1132
        read($fh, my $raw, $bytes);
1133
        close $fh;
1134
        return unpack('H*', $raw);
1135
    }
1136
    return sha256_hex(rand() . time() . $$);
1137
}
1138

            
1139
sub iso_now {
1140
    return strftime('%Y-%m-%dT%H:%M:%SZ', gmtime);
1141
}
1142

            
Bogdan Timofte authored 18 hours ago
1143
sub build_info {
1144
    my %info = (
1145
        revision => '',
1146
        branch => '',
1147
        built_at => '',
1148
        deployed_at => '',
1149
        dirty => '',
1150
    );
1151

            
1152
    if ($ENV{HOST_MANAGER_BUILD}) {
1153
        $info{revision} = clean_scalar($ENV{HOST_MANAGER_BUILD});
1154
        return \%info;
1155
    }
1156

            
1157
    my $build_file = "$project_dir/BUILD";
1158
    if (-f $build_file) {
1159
        for my $line (split /\n/, read_file($build_file)) {
1160
            next unless $line =~ /\A([A-Za-z0-9_.-]+)=(.*)\z/;
1161
            $info{$1} = clean_scalar($2);
1162
        }
1163
        return \%info if $info{revision} || $info{built_at};
1164
    }
1165

            
1166
    my $revision = git_value('rev-parse --short=12 HEAD');
1167
    my $branch = git_value('rev-parse --abbrev-ref HEAD');
1168
    $info{revision} = $revision if $revision;
1169
    $info{branch} = $branch if $branch && $branch ne 'HEAD';
1170
    return \%info;
1171
}
1172

            
1173
sub git_value {
1174
    my ($args) = @_;
1175
    return '' unless -d "$project_dir/.git";
1176
    open my $fh, '-|', "git -C '$project_dir' $args 2>/dev/null" or return '';
1177
    my $value = <$fh> || '';
1178
    close $fh;
1179
    chomp $value;
1180
    return clean_scalar($value);
1181
}
1182

            
1183
sub build_label {
1184
    my $info = build_info();
1185
    my $revision = $info->{revision} || 'unknown';
1186
    my $branch = $info->{branch} || '';
1187
    $branch = '' if $branch eq 'HEAD';
1188
    my $label = $branch ? "$branch $revision" : $revision;
1189
    $label .= '+dirty' if ($info->{dirty} || '') eq '1';
1190
    return $label;
1191
}
1192

            
1193
sub build_title {
1194
    my $info = build_info();
1195
    my $label = build_label();
1196
    my $stamp = $info->{deployed_at} || $info->{built_at} || '';
1197
    return $stamp ? "$label deployed $stamp" : $label;
1198
}
1199

            
1200
sub html_escape {
1201
    my ($value) = @_;
1202
    $value = '' unless defined $value;
1203
    $value =~ s/&/&amp;/g;
1204
    $value =~ s/</&lt;/g;
1205
    $value =~ s/>/&gt;/g;
1206
    $value =~ s/"/&quot;/g;
1207
    $value =~ s/'/&#039;/g;
1208
    return $value;
1209
}
1210

            
Xdev Host Manager authored 2 days ago
1211
sub app_html {
Bogdan Timofte authored 18 hours ago
1212
    my $build = html_escape(build_label());
1213
    my $build_title = html_escape(build_title());
1214
    my $html = <<'HTML';
Xdev Host Manager authored 2 days ago
1215
<!doctype html>
1216
<html lang="ro">
1217
<head>
1218
  <meta charset="utf-8">
1219
  <meta name="viewport" content="width=device-width, initial-scale=1">
Bogdan Timofte authored 18 hours ago
1220
  <meta name="xdev-build" content="__HOST_MANAGER_BUILD_TITLE__">
Xdev Host Manager authored 2 days ago
1221
  <title>Madagascar Local Authority</title>
Xdev Host Manager authored 2 days ago
1222
  <style>
1223
    :root {
1224
      color-scheme: light;
1225
      --ink: #152033;
1226
      --muted: #647084;
1227
      --line: #d8dee8;
1228
      --soft: #f4f6f9;
1229
      --panel: #ffffff;
1230
      --accent: #1267d8;
1231
      --bad: #b42318;
1232
      --warn: #946200;
1233
      --ok: #137333;
1234
    }
1235
    * { box-sizing: border-box; }
1236
    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
1237

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

            
1342
    /* ── App shell (hidden until authenticated) ── */
1343
    #app { display: none; }
Bogdan Timofte authored 12 hours ago
1344
    header { display: grid; grid-template-columns: minmax(180px, auto) 1fr auto; align-items: center; gap: 16px; padding: 12px 18px; background: var(--panel); border-bottom: 1px solid var(--line); position: sticky; top: 0; z-index: 2; }
Xdev Host Manager authored 2 days ago
1345
    h1 { margin: 0; font-size: 17px; font-weight: 700; }
Bogdan Timofte authored 12 hours ago
1346
    nav { display: flex; align-items: center; gap: 4px; min-width: 0; overflow-x: auto; }
1347
    nav a { color: var(--muted); text-decoration: none; padding: 7px 10px; border-radius: 6px; white-space: nowrap; font-weight: 650; }
1348
    nav a:hover { color: var(--ink); background: var(--soft); }
1349
    nav a.active { color: var(--accent); background: #e8f0fe; }
1350
    .header-right { display: flex; align-items: center; justify-content: flex-end; gap: 10px; min-width: 0; }
1351
    #message { max-width: 260px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
Xdev Host Manager authored 2 days ago
1352
    main { padding: 16px; display: grid; gap: 16px; max-width: 1280px; margin: 0 auto; }
Bogdan Timofte authored 12 hours ago
1353
    .page { display: grid; gap: 16px; }
1354
    .page[hidden] { display: none; }
Xdev Host Manager authored 2 days ago
1355
    .toolbar, .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; }
1356
    .toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px; }
1357
    .panel { overflow: hidden; }
1358
    .panel-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-bottom: 1px solid var(--line); background: #fafbfc; }
1359
    .panel-head h2 { margin: 0; font-size: 14px; }
1360
    .stats { display: flex; gap: 8px; flex-wrap: wrap; }
1361
    .stat { padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--soft); font-size: 12px; color: var(--muted); }
1362
    button, input, select, textarea { font: inherit; }
1363
    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; }
1364
    button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
Xdev Host Manager authored 2 days ago
1365
    button:disabled { opacity: .45; cursor: not-allowed; }
Xdev Host Manager authored 2 days ago
1366
    button.danger { color: var(--bad); }
Xdev Host Manager authored 2 days ago
1367
    button:disabled, .linkbtn[aria-disabled="true"] { opacity: .55; cursor: not-allowed; pointer-events: none; }
Xdev Host Manager authored 2 days ago
1368
    input, select, textarea { width: 100%; border: 1px solid var(--line); border-radius: 6px; padding: 8px; background: #fff; color: var(--ink); }
1369
    textarea { min-height: 74px; resize: vertical; }
1370
    table { width: 100%; border-collapse: collapse; table-layout: fixed; }
1371
    th, td { padding: 9px 10px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; overflow-wrap: anywhere; }
1372
    th { color: var(--muted); font-size: 12px; font-weight: 700; background: #fafbfc; }
1373
    tr:hover td { background: #f8fafc; }
1374
    .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; }
1375
    .pill.ok { color: var(--ok); border-color: #b7dfc1; background: #edf8ef; }
1376
    .pill.warn { color: var(--warn); border-color: #f1d184; background: #fff7df; }
1377
    .pill.bad { color: var(--bad); border-color: #f0b8b3; background: #fff0ee; }
1378
    .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; padding: 14px; }
1379
    .span2 { grid-column: 1 / -1; }
1380
    label { display: grid; gap: 5px; color: var(--muted); font-size: 12px; font-weight: 650; }
1381
    .muted { color: var(--muted); }
Bogdan Timofte authored 12 hours ago
1382
    .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; font-size: 12px; }
1383
    .ca-detail { display: grid; gap: 6px; min-width: 0; }
1384
    .ca-fingerprint { overflow-wrap: anywhere; }
1385
    .ca-empty { padding: 12px 14px; }
Bogdan Timofte authored 18 hours ago
1386
    .build-badge {
1387
      position: fixed;
1388
      right: 10px;
1389
      bottom: 8px;
1390
      z-index: 5;
1391
      color: rgba(255,255,255,.46);
1392
      background: rgba(19,24,42,.28);
1393
      border: 1px solid rgba(255,255,255,.08);
1394
      border-radius: 4px;
1395
      padding: 2px 5px;
1396
      font-size: 10px;
1397
      line-height: 1.2;
1398
      pointer-events: none;
1399
      user-select: none;
1400
    }
1401
    body.is-app .build-badge {
1402
      color: rgba(100,112,132,.58);
1403
      background: rgba(255,255,255,.72);
1404
      border-color: rgba(216,222,232,.72);
1405
    }
Xdev Host Manager authored 2 days ago
1406
    .problems { padding: 10px 14px; display: grid; gap: 8px; }
1407
    .problem { border-left: 3px solid var(--warn); padding: 7px 9px; background: #fffaf0; }
Bogdan Timofte authored 18 hours ago
1408
    .work-order-card { display: grid; gap: 8px; min-width: 0; }
1409
    .work-order-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
1410
    .work-order-title { color: var(--ink); font-size: 14px; font-weight: 650; }
1411
    .work-order-checklist, .work-order-actions { display: grid; gap: 6px; min-width: 0; }
1412
    .work-order-actions { gap: 4px; }
1413
    .work-order-checkitem { display: flex; align-items: flex-start; gap: 8px; min-width: 0; color: var(--ink); font-size: 13px; font-weight: 400; }
1414
    .work-order-checkitem input[type="checkbox"] { width: auto; flex: 0 0 auto; margin: 2px 0 0; }
1415
    .work-order-checkitem span { min-width: 0; overflow-wrap: anywhere; }
Bogdan Timofte authored 12 hours ago
1416
    .host-tools { display: flex; align-items: center; justify-content: flex-end; gap: 8px; min-width: 0; }
1417
    .host-tools input { max-width: 240px; }
1418
    .modal-backdrop {
1419
      position: fixed;
1420
      inset: 0;
1421
      z-index: 10;
1422
      display: grid;
1423
      align-items: start;
1424
      justify-items: center;
1425
      padding: 72px 16px 24px;
1426
      background: rgba(21,32,51,.48);
1427
      overflow: auto;
1428
    }
1429
    .modal-backdrop[hidden] { display: none; }
1430
    .modal {
1431
      width: min(840px, 100%);
1432
      max-height: calc(100dvh - 96px);
1433
      overflow: auto;
1434
      background: var(--panel);
1435
      border: 1px solid var(--line);
1436
      border-radius: 8px;
1437
      box-shadow: 0 20px 60px rgba(21,32,51,.26);
1438
    }
1439
    .modal-head {
1440
      position: sticky;
1441
      top: 0;
1442
      z-index: 1;
1443
      display: flex;
1444
      align-items: center;
1445
      justify-content: space-between;
1446
      gap: 12px;
1447
      padding: 12px 14px;
1448
      border-bottom: 1px solid var(--line);
1449
      background: #fafbfc;
1450
    }
1451
    .modal-head h2 { margin: 0; font-size: 14px; }
1452
    .modal-close { min-width: 34px; justify-content: center; padding: 7px; }
1453
    .form-actions { display: flex; flex-wrap: wrap; gap: 8px; }
Xdev Host Manager authored 2 days ago
1454
    @media (max-width: 760px) {
Bogdan Timofte authored 12 hours ago
1455
      header { grid-template-columns: 1fr; align-items: stretch; gap: 10px; }
1456
      .header-right { justify-content: flex-start; flex-wrap: wrap; }
1457
      #message { max-width: 100%; }
1458
      .panel-head { align-items: stretch; flex-direction: column; }
1459
      .host-tools { justify-content: flex-start; flex-wrap: wrap; }
1460
      .host-tools input { max-width: none; }
1461
      .modal-backdrop { padding-top: 16px; }
1462
      .modal { max-height: calc(100dvh - 32px); }
Xdev Host Manager authored 2 days ago
1463
      .grid { grid-template-columns: 1fr; }
1464
      table { min-width: 760px; }
1465
      .table-wrap { overflow-x: auto; }
1466
    }
1467
  </style>
1468
</head>
Bogdan Timofte authored 18 hours ago
1469
<body class="is-login">
Xdev Host Manager authored 2 days ago
1470

            
Xdev Host Manager authored 2 days ago
1471
  <!-- ── Login screen ── -->
1472
  <div id="login-screen">
1473
    <div class="login-card">
1474
      <div class="brand">
1475
        <div class="icon">
Xdev Host Manager authored 2 days ago
1476
          <svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
1477
            <rect x="16" y="10" width="32" height="44" rx="4"/>
1478
            <rect x="21" y="16" width="22" height="8" rx="2"/>
1479
            <rect x="21" y="28" width="22" height="8" rx="2"/>
1480
            <rect x="21" y="40" width="22" height="8" rx="2"/>
1481
            <path d="M26 20h8M26 32h8M26 44h8"/>
1482
            <path d="M40 20h.01M40 32h.01M40 44h.01"/>
Xdev Host Manager authored 2 days ago
1483
          </svg>
1484
        </div>
Xdev Host Manager authored 2 days ago
1485
        <h1>Madagascar Local Authority</h1>
1486
        <p>Hosts, DNS &amp; Local CA</p>
Xdev Host Manager authored 2 days ago
1487
      </div>
Bogdan Timofte authored 19 hours ago
1488
      <form id="login-form" method="post" action="/api/login" autocomplete="on" novalidate>
1489
        <div class="pm-helper-fields" aria-hidden="true">
1490
          <input type="text" id="login-account" name="username" autocomplete="username" autocapitalize="off" spellcheck="false">
1491
          <input type="text" id="otp-autofill" name="code" inputmode="numeric" pattern="[0-9]*" autocomplete="one-time-code">
1492
          <input type="hidden" id="otp-hidden" name="otp">
1493
        </div>
Xdev Host Manager authored 2 days ago
1494
        <div class="otp-row">
Bogdan Timofte authored 19 hours ago
1495
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 1">
1496
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 2">
1497
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 3">
1498
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 4">
1499
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 5">
1500
          <input type="text" inputmode="numeric" pattern="[0-9]*" class="otp-digit" aria-label="Digit 6">
Xdev Host Manager authored 2 days ago
1501
        </div>
1502
      </form>
1503
      <div id="login-error"></div>
1504
    </div>
1505
  </div>
1506

            
1507
  <!-- ── App (shown after login) ── -->
1508
  <div id="app">
1509
    <header>
Xdev Host Manager authored 2 days ago
1510
      <h1>Madagascar Local Authority</h1>
Bogdan Timofte authored 12 hours ago
1511
      <nav aria-label="Sections">
1512
        <a href="/overview" data-page-link="overview">Overview</a>
1513
        <a href="/hosts" data-page-link="hosts">Hosts</a>
1514
        <a href="/dns" data-page-link="dns">DNS</a>
1515
        <a href="/work-orders" data-page-link="work-orders">Work Orders</a>
1516
        <a href="/ca" data-page-link="ca">Local CA</a>
1517
      </nav>
Xdev Host Manager authored 2 days ago
1518
      <div class="header-right">
1519
        <span class="muted" id="app-updated"></span>
Bogdan Timofte authored 12 hours ago
1520
        <span id="message" class="muted"></span>
1521
        <button id="refresh">Refresh</button>
Xdev Host Manager authored 2 days ago
1522
        <button type="button" id="logout">Logout</button>
Xdev Host Manager authored 2 days ago
1523
      </div>
Xdev Host Manager authored 2 days ago
1524
    </header>
1525
    <main>
Bogdan Timofte authored 12 hours ago
1526
      <section class="page" id="page-overview" data-page="overview">
1527
        <section class="panel">
1528
          <div class="panel-head">
1529
            <h2>Overview</h2>
1530
            <div class="stats" id="stats"></div>
1531
          </div>
1532
          <div class="problems" id="problems"></div>
1533
        </section>
Xdev Host Manager authored 2 days ago
1534
      </section>
1535

            
Bogdan Timofte authored 12 hours ago
1536
      <section class="page" id="page-hosts" data-page="hosts" hidden>
1537
        <section class="panel">
1538
          <div class="panel-head">
1539
            <h2>Hosts</h2>
1540
            <div class="host-tools">
1541
              <input id="filter" placeholder="filter">
1542
              <button type="button" id="new-host">New host</button>
1543
            </div>
1544
          </div>
1545
          <div class="table-wrap">
1546
            <table>
1547
              <thead>
1548
                <tr>
1549
                  <th style="width: 120px">ID</th>
1550
                  <th style="width: 130px">hosts_ip</th>
1551
                  <th style="width: 130px">dns_ip</th>
1552
                  <th>Names</th>
1553
                  <th style="width: 150px">Roles</th>
1554
                  <th style="width: 110px">Monitoring</th>
1555
                  <th style="width: 90px">Status</th>
1556
                </tr>
1557
              </thead>
1558
              <tbody id="hosts"></tbody>
1559
            </table>
1560
          </div>
1561
        </section>
Xdev Host Manager authored 2 days ago
1562
      </section>
Xdev Host Manager authored 2 days ago
1563

            
Bogdan Timofte authored 12 hours ago
1564
      <section class="page" id="page-dns" data-page="dns" hidden>
1565
        <section class="toolbar">
1566
          <a class="linkbtn" href="/download/hosts.yaml">hosts.yaml</a>
1567
          <a class="linkbtn" href="/download/local-hosts.tsv">local-hosts.tsv</a>
1568
          <a class="linkbtn" href="/download/monitoring.json">monitoring.json</a>
1569
          <button id="write-tsv">Write local-hosts.tsv</button>
1570
        </section>
Xdev Host Manager authored 2 days ago
1571
      </section>
1572

            
Bogdan Timofte authored 12 hours ago
1573
      <section class="page" id="page-work-orders" data-page="work-orders" hidden>
1574
        <section class="panel">
1575
          <div class="panel-head">
1576
            <h2>Work Orders</h2>
1577
            <div class="stats" id="wo-stats"></div>
1578
          </div>
1579
          <div class="problems" id="work-orders"></div>
1580
        </section>
Xdev Host Manager authored 2 days ago
1581
      </section>
1582

            
Bogdan Timofte authored 12 hours ago
1583
      <section class="page" id="page-ca" data-page="ca" hidden>
1584
        <section class="panel">
1585
          <div class="panel-head">
1586
            <h2>Local Certificate Authority</h2>
1587
            <a class="linkbtn" href="/download/ca.crt">ca.crt</a>
1588
          </div>
1589
          <div class="problems" id="ca-status"></div>
1590
        </section>
1591
        <section class="panel">
1592
          <div class="panel-head">
1593
            <h2>Issued Certificates</h2>
1594
            <div class="stats" id="ca-certs-summary"></div>
1595
          </div>
1596
          <div class="table-wrap">
1597
            <table>
1598
              <thead>
1599
                <tr>
1600
                  <th style="width: 150px">Name</th>
1601
                  <th>DNS names</th>
1602
                  <th style="width: 210px">Validity</th>
1603
                  <th style="width: 180px">Serial</th>
1604
                  <th>Fingerprint</th>
1605
                  <th style="width: 110px">Download</th>
1606
                </tr>
1607
              </thead>
1608
              <tbody id="ca-certs"></tbody>
1609
            </table>
1610
          </div>
1611
        </section>
Xdev Host Manager authored 2 days ago
1612
      </section>
Bogdan Timofte authored 12 hours ago
1613
    </main>
Xdev Host Manager authored 2 days ago
1614

            
Bogdan Timofte authored 12 hours ago
1615
    <div id="host-modal" class="modal-backdrop" hidden>
1616
      <section class="modal" role="dialog" aria-modal="true" aria-labelledby="host-modal-title">
1617
        <div class="modal-head">
1618
          <h2 id="host-modal-title">Edit host</h2>
1619
          <button type="button" id="close-host-modal" class="modal-close" aria-label="Close host editor">x</button>
Xdev Host Manager authored 2 days ago
1620
        </div>
1621
        <form id="host-form" class="grid">
1622
          <label>ID<input name="id" required></label>
1623
          <label>Status<select name="status"><option>active</option><option>planned</option><option>retired</option></select></label>
1624
          <label>hosts_ip<input name="hosts_ip" required></label>
1625
          <label>dns_ip<input name="dns_ip" required></label>
1626
          <label class="span2">Names<textarea name="names" required></textarea></label>
1627
          <label>Roles<input name="roles"></label>
1628
          <label>Sources<input name="sources"></label>
1629
          <label>Monitoring<select name="monitoring"><option>pending</option><option>enabled</option><option>disabled</option></select></label>
1630
          <label>Notes<input name="notes"></label>
Bogdan Timofte authored 12 hours ago
1631
          <div class="span2 form-actions">
Xdev Host Manager authored 2 days ago
1632
            <button class="primary" type="submit">Save host</button>
1633
            <button class="danger" type="button" id="delete-host">Delete host</button>
1634
          </div>
1635
        </form>
1636
      </section>
Bogdan Timofte authored 12 hours ago
1637
    </div>
Xdev Host Manager authored 2 days ago
1638
  </div>
1639

            
Bogdan Timofte authored 18 hours ago
1640
  <div class="build-badge" title="Running build __HOST_MANAGER_BUILD_TITLE__">build __HOST_MANAGER_BUILD__</div>
1641

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

            
1645
    const $ = (id) => document.getElementById(id);
1646
    const msg = (text) => { $('message').textContent = text || ''; };
Bogdan Timofte authored 12 hours ago
1647
    const PAGE_PATHS = {
1648
      '/': 'overview',
1649
      '/overview': 'overview',
1650
      '/hosts': 'hosts',
1651
      '/dns': 'dns',
1652
      '/work-orders': 'work-orders',
1653
      '/ca': 'ca',
1654
    };
Xdev Host Manager authored 2 days ago
1655

            
1656
    async function api(path, options = {}) {
1657
      const res = await fetch(path, options);
1658
      const body = await res.json();
1659
      if (!res.ok) throw new Error(body.error || res.statusText);
1660
      return body;
1661
    }
1662

            
Bogdan Timofte authored 12 hours ago
1663
    function currentPage() {
1664
      return PAGE_PATHS[window.location.pathname] || 'overview';
1665
    }
1666

            
1667
    function showPage(page, push = false) {
1668
      const target = page || 'overview';
1669
      document.querySelectorAll('[data-page]').forEach(section => {
1670
        section.hidden = section.dataset.page !== target;
1671
      });
1672
      document.querySelectorAll('[data-page-link]').forEach(link => {
1673
        link.classList.toggle('active', link.dataset.pageLink === target);
1674
        link.setAttribute('aria-current', link.dataset.pageLink === target ? 'page' : 'false');
1675
      });
1676
      if (push) {
1677
        const href = target === 'overview' ? '/overview' : '/' + target;
1678
        history.pushState({ page: target }, '', href);
1679
      }
1680
    }
1681

            
Xdev Host Manager authored 2 days ago
1682
    function showLogin(errorText) {
Bogdan Timofte authored 18 hours ago
1683
      document.body.classList.remove('is-app');
1684
      document.body.classList.add('is-login');
Xdev Host Manager authored 2 days ago
1685
      $('app').style.display = 'none';
1686
      $('login-screen').style.display = 'flex';
1687
      $('login-error').textContent = errorText || '';
Bogdan Timofte authored 19 hours ago
1688
      clearOtp();
Xdev Host Manager authored 2 days ago
1689
    }
1690

            
1691
    function showApp() {
Bogdan Timofte authored 18 hours ago
1692
      document.body.classList.remove('is-login');
1693
      document.body.classList.add('is-app');
Xdev Host Manager authored 2 days ago
1694
      $('login-screen').style.display = 'none';
1695
      $('app').style.display = 'block';
Bogdan Timofte authored 12 hours ago
1696
      showPage(currentPage());
Xdev Host Manager authored 2 days ago
1697
    }
1698

            
Xdev Host Manager authored 2 days ago
1699
    async function refresh() {
1700
      const session = await api('/api/session');
1701
      state.authenticated = session.authenticated;
Xdev Host Manager authored 2 days ago
1702
      if (!state.authenticated) { showLogin(); return; }
1703
      showApp();
Xdev Host Manager authored 2 days ago
1704
      const data = await api('/api/hosts');
1705
      state.hosts = data.hosts || [];
1706
      state.problems = data.problems || [];
1707
      render(data);
Xdev Host Manager authored 2 days ago
1708
      await renderCa();
Xdev Host Manager authored 2 days ago
1709
      await renderWorkOrders();
Xdev Host Manager authored 2 days ago
1710
    }
1711

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

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

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

            
1724
      renderHosts();
1725
    }
1726

            
Xdev Host Manager authored 2 days ago
1727
    async function renderCa() {
1728
      try {
1729
        const status = await api('/api/ca/status');
1730
        if (!status.initialized) {
1731
          $('ca-status').innerHTML = '<div class="problem"><strong>not initialized</strong> Run <code>sudo scripts/ca_manager.sh init</code> on jumper.</div>';
Bogdan Timofte authored 12 hours ago
1732
          $('ca-certs-summary').innerHTML = '';
1733
          $('ca-certs').innerHTML = '<tr><td colspan="6" class="muted">CA is not initialized.</td></tr>';
Xdev Host Manager authored 2 days ago
1734
          return;
1735
        }
1736
        const certs = await api('/api/ca/certificates');
Bogdan Timofte authored 12 hours ago
1737
        const caDays = daysUntil(status.not_after);
Xdev Host Manager authored 2 days ago
1738
        $('ca-status').innerHTML = `
Bogdan Timofte authored 12 hours ago
1739
          <div class="muted ca-detail">
Xdev Host Manager authored 2 days ago
1740
            <div><strong>${escapeHtml(status.subject || '')}</strong></div>
Bogdan Timofte authored 12 hours ago
1741
            <div>SHA256 <span class="mono ca-fingerprint">${escapeHtml(status.fingerprint_sha256 || '')}</span></div>
Xdev Host Manager authored 2 days ago
1742
            <div>valid ${escapeHtml(status.not_before || '')} - ${escapeHtml(status.not_after || '')}</div>
Bogdan Timofte authored 12 hours ago
1743
            <div>
1744
              <span class="pill ${certStatusClass(caDays)}">${escapeHtml(certStatusLabel(caDays))}</span>
1745
              <span>${certs.length} issued certificate(s)</span>
1746
            </div>
Xdev Host Manager authored 2 days ago
1747
          </div>`;
Bogdan Timofte authored 12 hours ago
1748
        $('ca-certs-summary').innerHTML = [
1749
          ['issued', certs.length],
1750
          ['expiring', certs.filter(cert => {
1751
            const days = daysUntil(cert.not_after);
1752
            return days !== null && days >= 0 && days <= 30;
1753
          }).length],
1754
          ['expired', certs.filter(cert => {
1755
            const days = daysUntil(cert.not_after);
1756
            return days !== null && days < 0;
1757
          }).length],
1758
        ].map(([k, v]) => `<span class="stat">${k}: ${escapeHtml(String(v))}</span>`).join('');
1759
        $('ca-certs').innerHTML = certs.length ? certs.map(cert => {
1760
          const days = daysUntil(cert.not_after);
1761
          const dnsNames = cert.dns_names || [];
1762
          const dnsHtml = dnsNames.length
1763
            ? dnsNames.map(name => `<span class="pill">${escapeHtml(name)}</span>`).join('')
1764
            : '<span class="muted">No DNS SANs reported.</span>';
1765
          return `<tr>
1766
            <td><strong>${escapeHtml(cert.name || '')}</strong></td>
1767
            <td>${dnsHtml}</td>
1768
            <td>
1769
              <div class="ca-detail">
1770
                <span class="pill ${certStatusClass(days)}">${escapeHtml(certStatusLabel(days))}</span>
1771
                <span class="muted">until ${escapeHtml(cert.not_after || '')}</span>
1772
              </div>
1773
            </td>
1774
            <td class="mono">${escapeHtml(cert.serial || '')}</td>
1775
            <td class="mono ca-fingerprint">${escapeHtml(cert.fingerprint_sha256 || '')}</td>
1776
            <td><a class="linkbtn" href="/download/ca/cert/${encodeURIComponent(cert.name || '')}.crt">crt</a></td>
1777
          </tr>`;
1778
        }).join('') : '<tr><td colspan="6" class="muted">No issued certificates.</td></tr>';
Xdev Host Manager authored 2 days ago
1779
      } catch (e) {
1780
        $('ca-status').innerHTML = `<div class="problem"><strong>CA status unavailable</strong> ${escapeHtml(e.message)}</div>`;
Bogdan Timofte authored 12 hours ago
1781
        $('ca-certs-summary').innerHTML = '';
1782
        $('ca-certs').innerHTML = '<tr><td colspan="6" class="muted">Certificate list unavailable.</td></tr>';
Xdev Host Manager authored 2 days ago
1783
      }
1784
    }
1785

            
Bogdan Timofte authored 12 hours ago
1786
    function daysUntil(dateText) {
1787
      const time = Date.parse(dateText || '');
1788
      if (!Number.isFinite(time)) return null;
1789
      return Math.ceil((time - Date.now()) / 86400000);
1790
    }
1791

            
1792
    function certStatusClass(days) {
1793
      if (days === null) return '';
1794
      if (days < 0) return 'bad';
1795
      if (days <= 30) return 'warn';
1796
      return 'ok';
1797
    }
1798

            
1799
    function certStatusLabel(days) {
1800
      if (days === null) return 'validity unknown';
1801
      if (days < 0) return 'expired';
1802
      if (days === 0) return 'expires today';
1803
      return `${days}d remaining`;
1804
    }
1805

            
Xdev Host Manager authored 2 days ago
1806
    async function renderWorkOrders() {
1807
      try {
1808
        const data = await api('/api/work-orders');
1809
        state.workOrders = data.work_orders || [];
1810
        $('wo-stats').innerHTML = [
1811
          ['pending', data.counts.pending],
1812
          ['total', data.counts.work_orders],
1813
        ].map(([k, v]) => `<span class="stat">${k}: ${escapeHtml(String(v))}</span>`).join('');
1814

            
1815
        if (!state.workOrders.length) {
1816
          $('work-orders').innerHTML = '<div class="muted" style="padding: 8px 0">No work orders.</div>';
1817
          return;
1818
        }
1819

            
1820
        $('work-orders').innerHTML = state.workOrders.map(wo => {
Xdev Host Manager authored 2 days ago
1821
          const checklist = wo.checklist || [];
1822
          const doneItems = checklist.filter(item => (item.status || 'pending') === 'done').length;
1823
          const checklistComplete = checklist.length === 0 || doneItems === checklist.length;
1824
          const checklistHtml = checklist.map(item => {
1825
            const checked = (item.status || 'pending') === 'done' ? 'checked' : '';
Bogdan Timofte authored 18 hours ago
1826
            return `<label class="work-order-checkitem">
Xdev Host Manager authored 2 days ago
1827
              <input type="checkbox" data-wo-checklist="${escapeHtml(wo.id)}" data-item-id="${escapeHtml(item.id || '')}" ${checked}>
1828
              <span><strong>${escapeHtml(item.id || '')}</strong> ${escapeHtml(item.text || '')}</span>
1829
            </label>`;
1830
          }).join('');
Xdev Host Manager authored 2 days ago
1831
          const actions = (wo.actions || []).map(a => {
1832
            const target = [a.host_id, a.name].filter(Boolean).join(' ');
1833
            return `<div><span class="pill">${escapeHtml(a.type || '')}</span> ${escapeHtml(target)}</div>`;
1834
          }).join('');
1835
          const statusClass = (wo.status || 'pending') === 'pending' ? 'warn' : 'ok';
1836
          const button = (wo.status || 'pending') === 'pending'
Xdev Host Manager authored 2 days ago
1837
            ? `<button type="button" class="primary" data-confirm-wo="${escapeHtml(wo.id)}" ${checklistComplete ? '' : 'disabled'}>Confirm</button>`
Xdev Host Manager authored 2 days ago
1838
            : '';
Bogdan Timofte authored 18 hours ago
1839
          return `<div class="problem work-order-card">
1840
            <div class="work-order-head">
Xdev Host Manager authored 2 days ago
1841
              <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
1842
              ${button}
1843
            </div>
Bogdan Timofte authored 18 hours ago
1844
            <div class="work-order-title">${escapeHtml(wo.title || '')}</div>
Xdev Host Manager authored 2 days ago
1845
            <div class="muted">${escapeHtml(wo.reason || '')}</div>
Bogdan Timofte authored 18 hours ago
1846
            <div class="work-order-checklist">${checklistHtml}</div>
1847
            <div class="work-order-actions">${actions}</div>
Xdev Host Manager authored 2 days ago
1848
            ${wo.confirmed_at ? `<div class="muted">confirmed ${escapeHtml(wo.confirmed_at)}</div>` : ''}
1849
          </div>`;
1850
        }).join('');
Xdev Host Manager authored 2 days ago
1851
        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
1852
        document.querySelectorAll('[data-confirm-wo]').forEach(button => button.addEventListener('click', () => confirmWorkOrder(button.dataset.confirmWo)));
1853
      } catch (e) {
1854
        $('work-orders').innerHTML = `<div class="problem"><strong>Work orders unavailable</strong> ${escapeHtml(e.message)}</div>`;
1855
      }
1856
    }
1857

            
Xdev Host Manager authored 2 days ago
1858
    async function updateWorkOrderChecklist(id, itemId, checked) {
1859
      try {
1860
        await api('/api/work-orders/checklist', {
1861
          method: 'POST',
1862
          headers: { 'Content-Type': 'application/json' },
1863
          body: JSON.stringify({ id, item_id: itemId, status: checked ? 'done' : 'pending' })
1864
        });
1865
        msg('work order updated');
1866
        await refresh();
1867
      } catch (e) { msg(e.message); await refresh(); }
1868
    }
1869

            
Xdev Host Manager authored 2 days ago
1870
    async function confirmWorkOrder(id) {
1871
      const typed = prompt(`Type ${id} to confirm this work order`);
1872
      if (typed !== id) return;
1873
      try {
1874
        await api('/api/work-orders/confirm', {
1875
          method: 'POST',
1876
          headers: { 'Content-Type': 'application/json' },
1877
          body: JSON.stringify({ id, confirm: typed })
1878
        });
1879
        msg('work order confirmed; local-hosts.tsv written');
1880
        await refresh();
1881
      } catch (e) { msg(e.message); }
1882
    }
1883

            
Xdev Host Manager authored 2 days ago
1884
    function renderHosts() {
1885
      const filter = $('filter').value.toLowerCase();
1886
      $('hosts').innerHTML = state.hosts
1887
        .filter(h => JSON.stringify(h).toLowerCase().includes(filter))
1888
        .map(h => {
1889
          const problems = state.problems.filter(p => p.host_id === h.id);
1890
          const cls = problems.length ? 'warn' : 'ok';
1891
          return `<tr data-id="${escapeHtml(h.id)}">
1892
            <td><button type="button" data-edit="${escapeHtml(h.id)}">${escapeHtml(h.id)}</button></td>
1893
            <td>${escapeHtml(h.hosts_ip || '')}</td>
1894
            <td>${escapeHtml(h.dns_ip || '')}</td>
1895
            <td>${(h.names || []).map(n => `<span class="pill">${escapeHtml(n)}</span>`).join('')}</td>
1896
            <td>${(h.roles || []).map(n => `<span class="pill">${escapeHtml(n)}</span>`).join('')}</td>
1897
            <td><span class="pill ${cls}">${escapeHtml(h.monitoring || '')}</span></td>
1898
            <td>${escapeHtml(h.status || '')}</td>
1899
          </tr>`;
1900
        }).join('');
1901
      document.querySelectorAll('[data-edit]').forEach(button => button.addEventListener('click', () => editHost(button.dataset.edit)));
1902
    }
1903

            
1904
    function editHost(id) {
1905
      const host = state.hosts.find(h => h.id === id);
1906
      if (!host) return;
1907
      const form = $('host-form');
1908
      for (const key of ['id', 'status', 'hosts_ip', 'dns_ip', 'monitoring', 'notes']) form.elements[key].value = host[key] || '';
1909
      form.elements.names.value = (host.names || []).join('\n');
1910
      form.elements.roles.value = (host.roles || []).join(' ');
1911
      form.elements.sources.value = (host.sources || []).join(' ');
Bogdan Timofte authored 12 hours ago
1912
      openHostModal('Edit host');
1913
    }
1914

            
1915
    function newHost() {
1916
      const form = $('host-form');
1917
      form.reset();
1918
      form.elements.status.value = 'active';
1919
      form.elements.monitoring.value = 'pending';
1920
      openHostModal('New host');
1921
    }
1922

            
1923
    function openHostModal(title) {
1924
      $('host-modal-title').textContent = title || 'Edit host';
1925
      $('host-modal').hidden = false;
1926
      document.body.style.overflow = 'hidden';
1927
      $('host-form').elements.id.focus();
1928
    }
1929

            
1930
    function closeHostModal() {
1931
      $('host-modal').hidden = true;
1932
      document.body.style.overflow = '';
Xdev Host Manager authored 2 days ago
1933
    }
1934

            
1935
    function formObject(form) {
1936
      return Object.fromEntries(new FormData(form).entries());
1937
    }
1938

            
1939
    function escapeHtml(value) {
Bogdan Timofte authored 12 hours ago
1940
      value = value == null ? '' : String(value);
Xdev Host Manager authored 2 days ago
1941
      return value.replace(/[&<>"']/g, ch => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[ch]));
1942
    }
1943

            
Bogdan Timofte authored 19 hours ago
1944
    const ACCOUNT_STORAGE_KEY = 'mla_last_account';
1945

            
Xdev Host Manager authored 2 days ago
1946
    // OTP digit boxes — auto-advance, backspace, paste
1947
    const otpDigits = Array.from(document.querySelectorAll('.otp-digit'));
Bogdan Timofte authored 19 hours ago
1948
    const otpAutofill = $('otp-autofill');
1949
    const otpHidden = $('otp-hidden');
1950
    const loginAccount = $('login-account');
1951

            
1952
    if (loginAccount) {
1953
      const rememberedAccount = localStorage.getItem(ACCOUNT_STORAGE_KEY);
1954
      if (rememberedAccount && !loginAccount.value) loginAccount.value = rememberedAccount;
1955
      loginAccount.addEventListener('input', () => {
1956
        const value = (loginAccount.value || '').trim();
1957
        if (value) localStorage.setItem(ACCOUNT_STORAGE_KEY, value);
1958
      });
1959
    }
1960

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

            
1963
    otpDigits.forEach((input, idx) => {
1964
      input.addEventListener('keydown', (e) => {
1965
        if (e.key === 'Backspace') {
Bogdan Timofte authored 19 hours ago
1966
          if (input.value) setOtpDigit(idx, '');
1967
          else if (idx > 0) { setOtpDigit(idx - 1, ''); otpDigits[idx - 1].focus(); }
1968
          syncOtpFields();
Xdev Host Manager authored 2 days ago
1969
          e.preventDefault();
1970
        }
1971
      });
Xdev Host Manager authored 2 days ago
1972
      input.addEventListener('input', () => {
1973
        const digits = input.value.replace(/\D/g, '');
1974
        if (digits.length > 1) {
1975
          fillOtp(digits, digits.length >= otpDigits.length ? 0 : idx);
1976
          return;
1977
        }
1978
        setOtpDigit(idx, digits);
Bogdan Timofte authored 19 hours ago
1979
        syncOtpFields();
Xdev Host Manager authored 2 days ago
1980
        if (digits && idx < otpDigits.length - 1) otpDigits[idx + 1].focus();
1981
        maybeSubmitOtp();
Xdev Host Manager authored 2 days ago
1982
      });
1983
      input.addEventListener('paste', (e) => {
1984
        const text = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '');
1985
        e.preventDefault();
Xdev Host Manager authored 2 days ago
1986
        fillOtp(text, text.length >= otpDigits.length ? 0 : idx);
Xdev Host Manager authored 2 days ago
1987
      });
1988
    });
1989

            
Xdev Host Manager authored 2 days ago
1990
    function setOtpDigit(idx, value) {
1991
      const digit = (value || '').replace(/\D/g, '').slice(0, 1);
1992
      otpDigits[idx].value = digit;
1993
      otpDigits[idx].classList.toggle('filled', !!digit);
1994
    }
1995

            
1996
    function fillOtp(text, startIdx = 0) {
1997
      const digits = (text || '').replace(/\D/g, '').slice(0, otpDigits.length);
1998
      if (!digits) return;
1999
      if (digits.length >= otpDigits.length) {
2000
        otpDigits.forEach((_, i) => setOtpDigit(i, digits[i] || ''));
2001
      } else {
2002
        digits.split('').forEach((ch, offset) => {
2003
          const targetIdx = startIdx + offset;
2004
          if (targetIdx < otpDigits.length) setOtpDigit(targetIdx, ch);
2005
        });
2006
      }
Bogdan Timofte authored 19 hours ago
2007
      syncOtpFields();
Xdev Host Manager authored 2 days ago
2008
      const next = Math.min((digits.length >= otpDigits.length ? digits.length : startIdx + digits.length), otpDigits.length - 1);
2009
      otpDigits[next].focus();
2010
      maybeSubmitOtp();
2011
    }
2012

            
Xdev Host Manager authored 2 days ago
2013
    function getOtp() { return otpDigits.map(i => i.value).join(''); }
Bogdan Timofte authored 19 hours ago
2014
    function syncOtpFields() {
2015
      const otp = getOtp();
2016
      if (otpHidden) otpHidden.value = otp;
2017
      if (otpAutofill && otpAutofill.value !== otp) otpAutofill.value = otp;
2018
    }
Xdev Host Manager authored 2 days ago
2019
    function otpReady() { return otpDigits.every(i => /^\d$/.test(i.value)); }
Xdev Host Manager authored 2 days ago
2020
    function maybeSubmitOtp() { if (otpReady()) $('login-form').requestSubmit(); }
Bogdan Timofte authored 19 hours ago
2021
    function clearOtp() {
2022
      otpDigits.forEach(i => { i.value = ''; i.classList.remove('filled'); });
2023
      if (otpAutofill) otpAutofill.value = '';
2024
      if (otpHidden) otpHidden.value = '';
2025
      otpDigits[0].focus();
2026
    }
2027

            
2028
    if (otpAutofill) {
2029
      const handleAutofill = () => fillOtp(otpAutofill.value, 0);
2030
      otpAutofill.addEventListener('input', handleAutofill);
2031
      otpAutofill.addEventListener('change', handleAutofill);
2032
    }
Xdev Host Manager authored 2 days ago
2033

            
Bogdan Timofte authored 12 hours ago
2034
    document.querySelectorAll('[data-page-link]').forEach(link => {
2035
      link.addEventListener('click', (event) => {
2036
        event.preventDefault();
2037
        showPage(link.dataset.pageLink, true);
2038
      });
2039
    });
2040

            
2041
    window.addEventListener('popstate', () => showPage(currentPage()));
2042

            
Xdev Host Manager authored 2 days ago
2043
    $('login-form').addEventListener('submit', async (event) => {
2044
      event.preventDefault();
Xdev Host Manager authored 2 days ago
2045
      if (!otpReady()) return;
2046
      $('login-form').classList.add('busy');
Xdev Host Manager authored 2 days ago
2047
      $('login-error').textContent = '';
Xdev Host Manager authored 2 days ago
2048
      try {
Xdev Host Manager authored 2 days ago
2049
        await api('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ otp: getOtp() }) });
Xdev Host Manager authored 2 days ago
2050
        await refresh();
Xdev Host Manager authored 2 days ago
2051
      } catch (e) {
2052
        showLogin(e.message === 'invalid_otp' ? 'Cod incorect.' : e.message);
2053
      } finally {
Xdev Host Manager authored 2 days ago
2054
        $('login-form').classList.remove('busy');
Xdev Host Manager authored 2 days ago
2055
      }
Xdev Host Manager authored 2 days ago
2056
    });
2057

            
2058
    $('logout').addEventListener('click', async () => {
2059
      await api('/api/logout', { method: 'POST' }).catch(() => {});
Bogdan Timofte authored 12 hours ago
2060
      window.location.replace('/?logged_out=' + Date.now());
Xdev Host Manager authored 2 days ago
2061
    });
2062

            
Xdev Host Manager authored 2 days ago
2063
    $('refresh').addEventListener('click', () => refresh().catch(e => msg(e.message)));
2064
    $('filter').addEventListener('input', renderHosts);
Bogdan Timofte authored 12 hours ago
2065
    $('new-host').addEventListener('click', newHost);
2066
    $('close-host-modal').addEventListener('click', closeHostModal);
2067
    $('host-modal').addEventListener('click', (event) => {
2068
      if (event.target === $('host-modal')) closeHostModal();
2069
    });
2070
    window.addEventListener('keydown', (event) => {
2071
      if (event.key === 'Escape' && !$('host-modal').hidden) closeHostModal();
2072
    });
Xdev Host Manager authored 2 days ago
2073

            
Xdev Host Manager authored 2 days ago
2074
    $('host-form').addEventListener('submit', async (event) => {
2075
      event.preventDefault();
2076
      try {
2077
        await api('/api/hosts/upsert', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formObject(event.target)) });
Bogdan Timofte authored 12 hours ago
2078
        closeHostModal();
Xdev Host Manager authored 2 days ago
2079
        msg('host saved');
2080
        await refresh();
2081
      } catch (e) { msg(e.message); }
2082
    });
2083

            
2084
    $('delete-host').addEventListener('click', async () => {
2085
      const id = $('host-form').elements.id.value;
2086
      if (!id || !confirm(`Delete ${id}?`)) return;
2087
      try {
2088
        await api('/api/hosts/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) });
2089
        $('host-form').reset();
Bogdan Timofte authored 12 hours ago
2090
        closeHostModal();
Xdev Host Manager authored 2 days ago
2091
        msg('host deleted');
2092
        await refresh();
2093
      } catch (e) { msg(e.message); }
2094
    });
2095

            
2096
    $('write-tsv').addEventListener('click', async () => {
2097
      if (!confirm('Write config/local-hosts.tsv from hosts.yaml?')) return;
2098
      try {
2099
        await api('/api/render/local-hosts-tsv', { method: 'POST' });
2100
        msg('local-hosts.tsv written');
2101
      } catch (e) { msg(e.message); }
2102
    });
2103

            
Xdev Host Manager authored 2 days ago
2104
    refresh().catch(() => showLogin());
Xdev Host Manager authored 2 days ago
2105
  </script>
2106
</body>
2107
</html>
2108
HTML
Bogdan Timofte authored 18 hours ago
2109
    $html =~ s/__HOST_MANAGER_BUILD_TITLE__/$build_title/g;
2110
    $html =~ s/__HOST_MANAGER_BUILD__/$build/g;
2111
    return $html;
Xdev Host Manager authored 2 days ago
2112
}