move ui to using trunk

cargo install trunk
This commit is contained in:
Mikaël Cluseau
2026-01-22 17:54:31 +01:00
parent 2af7ff85c1
commit 3085dac359
15 changed files with 109 additions and 155 deletions

131
ui/js/Cluster.js Normal file
View File

@ -0,0 +1,131 @@
const Cluster = {
components: { Downloads, GetCopy },
props: [ 'cluster', 'token', 'state' ],
data() {
return {
signReqValidity: "1d",
sshSignReq: {
PubKey: "",
Principal: "root",
},
sshUserCert: null,
kubeSignReq: {
CSR: "",
User: "",
Group: "system:masters",
},
kubeUserCert: null,
};
},
methods: {
sshCASign() {
event.preventDefault();
fetch(`/clusters/${this.cluster.Name}/ssh/user-ca/sign`, {
method: 'POST',
body: JSON.stringify({ ...this.sshSignReq, Validity: this.signReqValidity }),
headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
}).then((resp) => {
if (resp.ok) {
resp.blob().then((cert) => { this.sshUserCert = URL.createObjectURL(cert) })
} else {
resp.json().then((resp) => alert('failed to sign: '+resp.message))
}
})
.catch((e) => { alert('failed to sign: '+e); })
},
kubeCASign() {
event.preventDefault();
fetch(`/clusters/${this.cluster.Name}/kube/sign`, {
method: 'POST',
body: JSON.stringify({ ...this.kubeSignReq, Validity: this.signReqValidity }),
headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
}).then((resp) => {
if (resp.ok) {
resp.blob().then((cert) => { this.kubeUserCert = URL.createObjectURL(cert) })
} else {
resp.json().then((resp) => alert('failed to sign: '+resp.message))
}
})
.catch((e) => { alert('failed to sign: '+e); })
},
readFile(e, onload) {
const file = e.target.files[0];
if (!file) { return; }
const reader = new FileReader();
reader.onload = () => { onload(reader.result) };
reader.onerror = () => { alert("error reading file"); };
reader.readAsText(file);
},
loadPubKey(e) {
this.readFile(e, (v) => {
this.sshSignReq.PubKey = v;
});
},
loadCSR(e) {
this.readFile(e, (v) => {
this.kubeSignReq.CSR = v;
});
},
},
template: `
<h3>Access</h3>
<p>Allow cluster access from a public key</p>
<h4>Grant SSH access</h4>
<p>Validity: <input type="text" v-model="signReqValidity"/> <small>time range, ie: -5m:1w, 5m, 1M, 1y, 1d-1s, etc.</small></p>
<p>User: <input type="text" v-model="sshSignReq.Principal"/></p>
<p>Public key (OpenSSH format):<br/>
<span class="text-and-file"><textarea v-model="sshSignReq.PubKey" style="height:3lh"></textarea>
<input type="file" accept=".pub" @change="loadPubKey" /></span>
</p>
<p><button @click="sshCASign">Sign SSH access</button>
<template v-if="sshUserCert">
=&gt; <a :href="sshUserCert" download="ssh-cert.pub">Get certificate</a>
</template>
</p>
<h4>Grant Kubernetes API access</h4>
<p>Validity: <input type="text" v-model="signReqValidity"/> <small>time range, ie: -5m:1w, 5m, 1M, 1y, 1d-1s, etc.</small></p>
<p>User: <input type="text" v-model="kubeSignReq.User"/> (by default, from the CSR)</p>
<p>Group: <input type="text" v-model="kubeSignReq.Group"/></p>
<p>Certificate signing request (PEM format):<br/>
<span class="text-and-file"><textarea v-model="kubeSignReq.CSR" style="height:7lh;"></textarea>
<input type="file" accept=".csr" @change="loadCSR" /></span>
</p>
<p><button @click="kubeCASign">Sign Kubernetes API access</button>
<template v-if="kubeUserCert">
=&gt; <a :href="kubeUserCert" download="kube-cert.pub">Get certificate</a>
</template>
</p>
<h3>Tokens</h3>
<section class="links">
<GetCopy v-for="n in cluster.Tokens" :token="token" :name="n" :href="'/clusters/'+cluster.Name+'/tokens/'+n" />
</section>
<h3>Passwords</h3>
<section class="links">
<GetCopy v-for="n in cluster.Passwords" :token="token" :name="n" :href="'/clusters/'+cluster.Name+'/passwords/'+n" />
</section>
<h3>Downloads</h3>
<Downloads :token="token" :state="state" kind="cluster" :name="cluster.Name" />
<h3>CAs</h3>
<table><tr><th>Name</th><th>Certificate</th><th>Signed certificates</th></tr>
<tr v-for="ca in cluster.CAs">
<td>{{ ca.Name }}</td>
<td><GetCopy :token="token" name="cert" :href="'/clusters/'+cluster.Name+'/CAs/'+ca.Name+'/certificate'" /></td>
<td><template v-for="signed in ca.Signed">
{{" "}}
<GetCopy :token="token" :name="signed" :href="'/clusters/'+cluster.Name+'/CAs/'+ca.Name+'/signed?name='+signed" />
</template></td>
</tr></table>
`
}

70
ui/js/Downloads.js Normal file
View File

@ -0,0 +1,70 @@
const Downloads = {
props: [ 'kind', 'name', 'token', 'state' ],
data() {
return { createDisabled: false, selectedAssets: {} }
},
computed: {
availableAssets() {
return {
cluster: ['addons'],
host: [
"kernel",
"initrd",
"bootstrap.tar",
"boot.img.lz4",
"boot.img.gz",
"boot.qcow2",
"boot.vmdk",
"boot.img",
"boot.iso",
"boot.tar",
"boot-efi.tar",
"config",
"bootstrap-config",
"ipxe",
],
}[this.kind]
},
downloads() {
return Object.entries(this.state.Downloads)
.filter(e => { let d=e[1]; return d.Kind == this.kind && d.Name == this.name })
.map(e => {
const token= e[0];
return {
text: token.substring(0, 5) + '...',
url: '/public/downloads/'+token+"/",
}
})
},
assets() {
return this.availableAssets.filter(a => this.selectedAssets[a])
},
},
methods: {
createToken() {
event.preventDefault()
this.createDisabled = true
fetch('/authorize-download', {
method: 'POST',
body: JSON.stringify({Kind: this.kind, Name: this.name, Assets: this.assets}),
headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
}).then((resp) => resp.json())
.then((token) => { this.selectedAssets = {}; this.createDisabled = false })
.catch((e) => { alert('failed to create link'); this.createDisabled = false })
},
},
template: `
<h4>Available assets</h4>
<p class="downloads">
<template v-for="asset in availableAssets">
<label :class="{selected: selectedAssets[asset]}"><input type="checkbox" v-model="selectedAssets[asset]" />&nbsp;{{ asset }}</label>
{{" "}}
</template>
</p>
<p><button :disabled="createDisabled || assets.length==0" @click="createToken">Create link</button></p>
<template v-if="downloads.length">
<h4>Active links</h4>
<p class="download-links"><template v-for="d in downloads"><a :href="d.url" target="_blank">{{ d.text }}</a>{{" "}}</template></p>
</template>`
}

32
ui/js/GetCopy.js Normal file
View File

@ -0,0 +1,32 @@
const GetCopy = {
props: [ 'name', 'href', 'token' ],
data() { return {showCopied: false} },
template: `<span class="notif"><div v-if="showCopied">copied!</div><a :href="href" @click="fetchAndSave()">{{name}}</a>&nbsp;<a href="#" class="copy" @click="fetchAndCopy()">&#x1F5D0;</a></span>`,
methods: {
fetch() {
event.preventDefault()
return fetch(this.href, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + this.token },
})
},
handleFetchError(e) {
console.log("failed to get value:", e)
alert('failed to get value')
},
fetchAndSave() {
this.fetch().then(resp => resp.blob()).then((value) => {
window.open(URL.createObjectURL(value), "_blank")
}).catch(this.handleFetchError)
},
fetchAndCopy() {
this.fetch()
.then((resp) => resp.headers.get("content-type") == "application/json" ? resp.json() : resp.text())
.then((value) => {
window.navigator.clipboard.writeText(value)
this.showCopied = true
setTimeout(() => { this.showCopied = false }, 1000)
}).catch(this.handleFetchError)
},
},
}

14
ui/js/Host.js Normal file
View File

@ -0,0 +1,14 @@
const Host = {
components: { Downloads },
props: [ 'host', 'token', 'state' ],
template: `
<p>Cluster: {{ host.Cluster }}<template v-if="host.Template"> ({{ host.Template }})</template></p>
<p>IPs:
<code v-for="ip in host.IPs">
{{ ip }}{{" "}}
</code>
</p>
<h3>Downloads</h3>
<Downloads :token="token" :state="state" kind="host" :name="host.Name" />
`
}

262
ui/js/app.js Normal file
View File

@ -0,0 +1,262 @@
import { createApp } from './vue.esm-browser.js';
createApp({
components: { Cluster, Host },
data() {
return {
forms: {
store: {},
storeUpload: {},
delKey: {},
hostFromTemplate: {},
hostFromTemplateDel: "",
},
view: "",
viewFilter: "",
session: {},
error: null,
publicState: null,
serverVersion: null,
uiHash: null,
watchingState: false,
state: null,
}
},
mounted() {
this.session = JSON.parse(sessionStorage.state || "{}")
this.watchPublicState()
},
watch: {
session: {
deep: true,
handler(v) {
sessionStorage.state = JSON.stringify(v)
if (v.token && !this.watchingState) {
this.watchState()
this.watchingState = true
}
}
},
publicState: {
deep: true,
handler(v) {
if (v) {
this.serverVersion = v.ServerVersion
if (this.uiHash && v.UIHash != this.uiHash) {
console.log("reloading")
location.reload()
} else {
this.uiHash = v.UIHash
}
}
},
}
},
computed: {
views() {
var views = [{type: "actions", name: "admin", title: "Admin actions"}];
(this.state.Clusters||[]).forEach((c) => views.push({type: "cluster", name: c.Name, title: `Cluster ${c.Name}`}));
(this.state.Hosts ||[]).forEach((c) => views.push({type: "host", name: c.Name, title: `Host ${c.Name}`}));
return views.filter((v) => v.type != "host" || v.name.includes(this.viewFilter));
},
viewObj() {
if (this.view) {
if (this.view.type == "cluster") {
return this.state.Clusters.find((c) => c.Name == this.view.name);
}
if (this.view.type == "host") {
return this.state.Hosts.find((h) => h.Name == this.view.name);
}
}
return undefined;
},
hostsFromTemplate() {
return (this.state.Hosts||[]).filter((h) => h.Template);
},
},
methods: {
any(array) {
return array && array.length != 0;
},
copyText(text) {
event.preventDefault()
window.navigator.clipboard.writeText(text)
},
setToken() {
event.preventDefault()
this.session.token = this.forms.setToken
this.forms.setToken = null
},
uploadStore() {
event.preventDefault()
this.apiPost('/public/store.tar', this.$refs.storeUpload.files[0], (v) => {
this.forms.store = {}
}, "application/tar")
},
namedPassphrase(name, passphrase) {
return {Name: this.forms.store.name, Passphrase: btoa(this.forms.store.pass1)}
},
storeAddKey() {
this.apiPost('/store/add-key', this.namedPassphrase(), (v) => {
this.forms.store = {}
})
},
storeDelKey() {
event.preventDefault()
let name = this.forms.delKey.name
if (!confirm("Remove key named "+JSON.stringify(name)+"?")) {
return
}
this.apiPost('/store/delete-key', name , (v) => {
this.forms.delKey = {}
})
},
unlockStore() {
this.apiPost('/public/unlock-store', this.namedPassphrase(), (v) => {
this.forms.store = {}
if (v) {
this.session.token = v
if (!this.watchingState) {
this.watchState()
this.watchingState = true
}
}
})
},
uploadConfig() {
this.apiPost('/configs', this.$refs.configUpload.files[0], (v) => {}, "text/vnd.yaml")
},
hostFromTemplateAdd() {
let v = this.forms.hostFromTemplate;
this.apiPost('/hosts-from-template/'+v.name, v, (v) => { this.forms.hostFromTemplate = {} });
},
hostFromTemplateDel() {
event.preventDefault()
let v = this.forms.hostFromTemplateDel;
if (!confirm("delete host template instance "+v+"?")) {
return
}
this.apiDelete('/hosts-from-template/'+v, (v) => { this.forms.hostFromTemplateDel = "" });
},
apiPost(action, data, onload, contentType = 'application/json') {
event.preventDefault()
if (data === undefined) {
throw("action " + action + ": no data")
}
/* TODO
fetch(action, {
method: 'POST',
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((result) => onload)
// */
var xhr = new XMLHttpRequest()
xhr.responseType = 'json'
// TODO spinner, pending action notification, or something
xhr.onerror = () => {
// this.actionResults.splice(idx, 1, {...item, done: true, failed: true })
}
xhr.onload = (r) => {
if (xhr.status != 200) {
this.error = xhr.response
return
}
// this.actionResults.splice(idx, 1, {...item, done: true, resp: xhr.responseText})
this.error = null
if (onload) {
onload(xhr.response)
}
}
xhr.open("POST", action)
xhr.setRequestHeader('Accept', 'application/json')
xhr.setRequestHeader('Content-Type', contentType)
if (this.session.token) {
xhr.setRequestHeader('Authorization', 'Bearer '+this.session.token)
}
if (contentType == "application/json") {
xhr.send(JSON.stringify(data))
} else {
xhr.send(data)
}
},
apiDelete(action, data, onload) {
event.preventDefault()
var xhr = new XMLHttpRequest()
xhr.onload = (r) => {
if (xhr.status != 200) {
this.error = xhr.response
return
}
this.error = null
if (onload) {
onload(xhr.response)
}
}
xhr.open("DELETE", action)
xhr.setRequestHeader('Accept', 'application/json')
if (this.session.token) {
xhr.setRequestHeader('Authorization', 'Bearer '+this.session.token)
}
xhr.send()
},
download(url) {
event.target.target = '_blank'
event.target.href = this.downloadLink(url)
},
downloadLink(url) {
// TODO once-shot download link
return url + '?token=' + this.session.token
},
watchPublicState() {
this.watchStream('publicState', '/public-state')
},
watchState() {
this.watchStream('state', '/state', true)
},
watchStream(field, path, withToken) {
let evtSrc = new EventSource(path + (withToken ? '?token='+this.session.token : ''));
evtSrc.onmessage = (e) => {
let update = JSON.parse(e.data)
console.log("watch "+path+":", update)
if (update.err) {
console.log("watch error from server:", err)
}
if (update.set) {
this[field] = update.set
}
if (update.p) { // patch
new jsonpatch.JSONPatch(update.p, true).apply(this[field])
}
}
evtSrc.onerror = (e) => {
// console.log("event source " + path + " error:", e)
if (evtSrc) evtSrc.close()
this[field] = null
window.setTimeout(() => { this.watchStream(field, path, withToken) }, 1000)
}
},
}
}).mount('#app');

36
ui/js/jsonpatch.min.js vendored Normal file

File diff suppressed because one or more lines are too long

16172
ui/js/vue.esm-browser.js Normal file

File diff suppressed because it is too large Load Diff