mirror of
https://github.com/h44z/wg-portal.git
synced 2026-11-20 12:43:26 +01:00
Feat/client side key generation (#764)
* feat: expose editable key capability to frontend Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> * feat: expose editable keys setting Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> * feat: add browser WireGuard key and config helpers Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> * feat: support browser-only key generation for self provisioning Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> * fix: hide server config actions without private key Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> * refactor: share browser WireGuard key helpers Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> * refactor: reuse WireGuard browser key helpers Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> * fix: address review feedback for client-side key generation - Make generated key fields read-only so the downloaded config always matches the registered public key - Drop unreachable error handling and defensive branches; mirror wg_peer.tpl in the config builder - Keep only the keypair helper shared with KeyGeneraterView - Restore trailing newlines and remove the duplicated help text - Document browser-side key generation and add EditableKeys to the v0 swagger spec Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> * test: cover EditableKeys setting and browser-generated peer keys Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> * improve ui, fix potential race condition --------- Signed-off-by: I.F. <131729144+FukumotoIkuma@users.noreply.github.com> Co-authored-by: Christoph <christoph.h@sprinternet.at>
This commit is contained in:
@@ -154,7 +154,7 @@ More advanced options are found in the subsequent `Advanced` section.
|
|||||||
### `editable_keys`
|
### `editable_keys`
|
||||||
- **Default:** `true`
|
- **Default:** `true`
|
||||||
- **Environment Variable:** `WG_PORTAL_CORE_EDITABLE_KEYS`
|
- **Environment Variable:** `WG_PORTAL_CORE_EDITABLE_KEYS`
|
||||||
- **Description:** Allow editing of WireGuard key-pairs directly in the UI.
|
- **Description:** Allow editing of WireGuard key-pairs directly in the UI. When enabled, users creating their own peers (self-provisioning) can also generate the key-pair in the browser: the private key is never sent to the server, and the WireGuard configuration file is downloaded once right after creation. It cannot be downloaded or shown again later.
|
||||||
|
|
||||||
### `create_default_peer` (deprecated)
|
### `create_default_peer` (deprecated)
|
||||||
- **Default:** `false`
|
- **Default:** `false`
|
||||||
|
|||||||
@@ -47,6 +47,8 @@ const selectedPeer = computed(() => {
|
|||||||
return p
|
return p
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const hasStoredPrivateKey = computed(() => !!selectedPeer.value?.PrivateKey)
|
||||||
|
|
||||||
const selectedStats = computed(() => {
|
const selectedStats = computed(() => {
|
||||||
let s = peers.Statistics(props.peerId)
|
let s = peers.Statistics(props.peerId)
|
||||||
|
|
||||||
@@ -85,8 +87,12 @@ const configStyle = ref("wgquick")
|
|||||||
|
|
||||||
watch(() => props.visible, async (newValue, oldValue) => {
|
watch(() => props.visible, async (newValue, oldValue) => {
|
||||||
if (oldValue === false && newValue === true) { // if modal is shown
|
if (oldValue === false && newValue === true) { // if modal is shown
|
||||||
await peers.LoadPeerConfig(selectedPeer.value.Identifier, configStyle.value)
|
if (hasStoredPrivateKey.value) {
|
||||||
configString.value = peers.configuration
|
await peers.LoadPeerConfig(selectedPeer.value.Identifier, configStyle.value)
|
||||||
|
configString.value = peers.configuration
|
||||||
|
} else {
|
||||||
|
configString.value = ""
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -132,7 +138,7 @@ function ConfigQrUrl() {
|
|||||||
<template>
|
<template>
|
||||||
<Modal :title="title" :visible="visible" @close="close">
|
<Modal :title="title" :visible="visible" @close="close">
|
||||||
<template #default>
|
<template #default>
|
||||||
<div class="d-flex justify-content-end align-items-center mb-1" v-if="selectedInterface.Mode !== 'client'">
|
<div class="d-flex justify-content-end align-items-center mb-1" v-if="selectedInterface.Mode !== 'client' && hasStoredPrivateKey">
|
||||||
<span class="me-2">{{ $t('modals.peer-view.style-label') }}: </span>
|
<span class="me-2">{{ $t('modals.peer-view.style-label') }}: </span>
|
||||||
<div class="btn-group btn-switch-group" role="group" aria-label="Configuration Style">
|
<div class="btn-group btn-switch-group" role="group" aria-label="Configuration Style">
|
||||||
<input type="radio" class="btn-check" name="configstyle" id="raw" value="raw" autocomplete="off" checked="" v-model="configStyle">
|
<input type="radio" class="btn-check" name="configstyle" id="raw" value="raw" autocomplete="off" checked="" v-model="configStyle">
|
||||||
@@ -174,7 +180,7 @@ function ConfigQrUrl() {
|
|||||||
selectedPeer.DisabledReason }}</li>
|
selectedPeer.DisabledReason }}</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4" v-if="selectedInterface.Mode !== 'client'">
|
<div class="col-md-4" v-if="selectedInterface.Mode !== 'client' && hasStoredPrivateKey">
|
||||||
<img class="config-qr-img" :src="ConfigQrUrl()" loading="lazy" alt="Configuration QR Code">
|
<img class="config-qr-img" :src="ConfigQrUrl()" loading="lazy" alt="Configuration QR Code">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -209,7 +215,7 @@ function ConfigQrUrl() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="selectedInterface.Mode !== 'client'" class="accordion-item">
|
<div v-if="selectedInterface.Mode !== 'client' && hasStoredPrivateKey" class="accordion-item">
|
||||||
<h2 class="accordion-header" id="headingConfig">
|
<h2 class="accordion-header" id="headingConfig">
|
||||||
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
|
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
|
||||||
data-bs-target="#collapseConfig" aria-expanded="false" aria-controls="collapseConfig">
|
data-bs-target="#collapseConfig" aria-expanded="false" aria-controls="collapseConfig">
|
||||||
@@ -227,9 +233,9 @@ function ConfigQrUrl() {
|
|||||||
</template>
|
</template>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<div class="flex-fill text-start">
|
<div class="flex-fill text-start">
|
||||||
<button v-if="selectedInterface.Mode !== 'client'" @click.prevent="download" type="button" class="btn btn-primary me-1">{{
|
<button v-if="selectedInterface.Mode !== 'client' && hasStoredPrivateKey" @click.prevent="download" type="button" class="btn btn-primary me-1">{{
|
||||||
$t('modals.peer-view.button-download') }}</button>
|
$t('modals.peer-view.button-download') }}</button>
|
||||||
<button v-if="selectedInterface.Mode !== 'client'" @click.prevent="email" type="button" class="btn btn-primary me-1">{{
|
<button v-if="selectedInterface.Mode !== 'client' && hasStoredPrivateKey" @click.prevent="email" type="button" class="btn btn-primary me-1">{{
|
||||||
$t('modals.peer-view.button-email') }}</button>
|
$t('modals.peer-view.button-email') }}</button>
|
||||||
</div>
|
</div>
|
||||||
<button @click.prevent="close" type="button" class="btn btn-secondary">{{ $t('general.close') }}</button>
|
<button @click.prevent="close" type="button" class="btn btn-secondary">{{ $t('general.close') }}</button>
|
||||||
|
|||||||
@@ -6,11 +6,14 @@ import { useI18n } from 'vue-i18n';
|
|||||||
import { notify } from "@kyvg/vue3-notification";
|
import { notify } from "@kyvg/vue3-notification";
|
||||||
import { freshPeer, freshInterface } from '@/helpers/models';
|
import { freshPeer, freshInterface } from '@/helpers/models';
|
||||||
import { profileStore } from "@/stores/profile";
|
import { profileStore } from "@/stores/profile";
|
||||||
|
import { settingsStore } from "@/stores/settings";
|
||||||
|
import { downloadWgQuickConfig, generateKeypair } from '@/helpers/wireguard';
|
||||||
|
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
|
|
||||||
const peers = peerStore()
|
const peers = peerStore()
|
||||||
const profile = profileStore()
|
const profile = profileStore()
|
||||||
|
const settings = settingsStore()
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
peerId: String,
|
peerId: String,
|
||||||
@@ -55,15 +58,29 @@ const title = computed(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const formData = ref(freshPeer())
|
const formData = ref(freshPeer())
|
||||||
|
const isPreparing = ref(false)
|
||||||
const isSaving = ref(false)
|
const isSaving = ref(false)
|
||||||
const isDeleting = ref(false)
|
const isDeleting = ref(false)
|
||||||
|
const isGeneratingKeys = ref(false)
|
||||||
|
const clientSideKeyGenerated = ref(false)
|
||||||
|
const isBusy = computed(() => isPreparing.value || isSaving.value || isGeneratingKeys.value)
|
||||||
|
|
||||||
// functions
|
// functions
|
||||||
|
|
||||||
watch(() => props.visible, async (newValue, oldValue) => {
|
watch(() => props.visible, async (newValue, oldValue) => {
|
||||||
if (oldValue === false && newValue === true) { // if modal is shown
|
if (oldValue === false && newValue === true) { // if modal is shown
|
||||||
|
clientSideKeyGenerated.value = false
|
||||||
|
|
||||||
if (!selectedPeer.value) {
|
if (!selectedPeer.value) {
|
||||||
await peers.PreparePeer(selectedInterface.value.Identifier)
|
const preparingForm = formData.value
|
||||||
|
isPreparing.value = true
|
||||||
|
try {
|
||||||
|
await peers.PreparePeer(selectedInterface.value.Identifier)
|
||||||
|
} finally {
|
||||||
|
if (formData.value === preparingForm) isPreparing.value = false
|
||||||
|
}
|
||||||
|
// A closed dialog must not populate a later editing session.
|
||||||
|
if (formData.value !== preparingForm) return
|
||||||
|
|
||||||
formData.value.Identifier = peers.Prepared.Identifier
|
formData.value.Identifier = peers.Prepared.Identifier
|
||||||
formData.value.DisplayName = peers.Prepared.DisplayName
|
formData.value.DisplayName = peers.Prepared.DisplayName
|
||||||
@@ -160,29 +177,57 @@ watch(() => formData.value.Disabled, async (newValue, oldValue) => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
function close() {
|
function close() {
|
||||||
|
if (isSaving.value || isGeneratingKeys.value) return
|
||||||
formData.value = freshPeer()
|
formData.value = freshPeer()
|
||||||
|
isPreparing.value = false
|
||||||
|
clientSideKeyGenerated.value = false
|
||||||
emit('close')
|
emit('close')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function generateClientSideKeyPair() {
|
||||||
|
if (isBusy.value) return
|
||||||
|
isGeneratingKeys.value = true
|
||||||
|
try {
|
||||||
|
const keypair = await generateKeypair()
|
||||||
|
formData.value.PrivateKey = keypair.privateKey
|
||||||
|
formData.value.PublicKey = keypair.publicKey
|
||||||
|
clientSideKeyGenerated.value = true
|
||||||
|
} catch (e) {
|
||||||
|
notify({
|
||||||
|
title: "Failed to generate key pair!",
|
||||||
|
text: e.toString(),
|
||||||
|
type: 'error',
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
isGeneratingKeys.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function save() {
|
async function save() {
|
||||||
if (isSaving.value) return
|
if (isBusy.value) return
|
||||||
isSaving.value = true
|
isSaving.value = true
|
||||||
try {
|
try {
|
||||||
if (props.peerId !== '#NEW#') {
|
if (props.peerId !== '#NEW#') {
|
||||||
await peers.UpdatePeer(selectedPeer.value.Identifier, formData.value)
|
await peers.UpdatePeer(selectedPeer.value.Identifier, formData.value)
|
||||||
|
} else if (clientSideKeyGenerated.value) {
|
||||||
|
const { PublicKey, PrivateKey } = formData.value
|
||||||
|
// The client private key must never leave the browser.
|
||||||
|
await peers.CreatePeer(selectedInterface.value.Identifier, { ...formData.value, PrivateKey: "" })
|
||||||
|
downloadWgQuickConfig(peers.Find(PublicKey), PrivateKey)
|
||||||
} else {
|
} else {
|
||||||
await peers.CreatePeer(selectedInterface.value.Identifier, formData.value)
|
await peers.CreatePeer(selectedInterface.value.Identifier, formData.value)
|
||||||
}
|
}
|
||||||
close()
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
notify({
|
notify({
|
||||||
title: "Failed to save peer!",
|
title: "Failed to save peer!",
|
||||||
text: e.toString(),
|
text: e.toString(),
|
||||||
type: 'error',
|
type: 'error',
|
||||||
})
|
})
|
||||||
|
return
|
||||||
} finally {
|
} finally {
|
||||||
isSaving.value = false
|
isSaving.value = false
|
||||||
}
|
}
|
||||||
|
close()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function del() {
|
async function del() {
|
||||||
@@ -218,15 +263,28 @@ async function del() {
|
|||||||
<fieldset>
|
<fieldset>
|
||||||
<legend class="mt-4">{{ $t('modals.peer-edit.header-crypto') }}</legend>
|
<legend class="mt-4">{{ $t('modals.peer-edit.header-crypto') }}</legend>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label class="form-label mt-4">{{ $t('modals.peer-edit.private-key.label') }}</label>
|
<label class="form-label mt-4" for="userPeerPrivateKey">{{ $t('modals.peer-edit.private-key.label') }}</label>
|
||||||
<input type="text" class="form-control" :placeholder="$t('modals.peer-edit.private-key.placeholder')" required
|
<span v-if="clientSideKeyGenerated" class="badge text-bg-success ms-2" role="status">
|
||||||
v-model="formData.PrivateKey">
|
<i class="fas fa-lock me-1" aria-hidden="true"></i>{{ $t('modals.peer-edit.private-key.local-label') }}
|
||||||
<small id="privateKeyHelp" class="form-text text-muted">{{ $t('modals.peer-edit.private-key.help') }}</small>
|
</span>
|
||||||
|
<div class="input-group">
|
||||||
|
<input id="userPeerPrivateKey" type="text" class="form-control" :class="{ 'border-success': clientSideKeyGenerated }"
|
||||||
|
:placeholder="$t('modals.peer-edit.private-key.placeholder')" required aria-describedby="privateKeyHelp"
|
||||||
|
v-model="formData.PrivateKey" :readonly="clientSideKeyGenerated">
|
||||||
|
<button v-if="props.peerId === '#NEW#' && settings.Setting('EditableKeys')" class="btn btn-outline-primary" type="button"
|
||||||
|
@click.prevent="generateClientSideKeyPair" :disabled="isBusy" :title="$t('keygen.abstract')">
|
||||||
|
<span v-if="isGeneratingKeys" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
|
||||||
|
{{ $t('keygen.button-generate') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<small id="privateKeyHelp" class="form-text" :class="clientSideKeyGenerated ? 'text-success' : 'text-muted'">
|
||||||
|
{{ $t(clientSideKeyGenerated ? 'modals.peer-edit.private-key.local-help' : 'modals.peer-edit.private-key.help') }}
|
||||||
|
</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label class="form-label mt-4">{{ $t('modals.peer-edit.public-key.label') }}</label>
|
<label class="form-label mt-4">{{ $t('modals.peer-edit.public-key.label') }}</label>
|
||||||
<input type="text" class="form-control" :placeholder="$t('modals.peer-edit.public-key.placeholder')" required
|
<input type="text" class="form-control" :placeholder="$t('modals.peer-edit.public-key.placeholder')" required
|
||||||
v-model="formData.PublicKey">
|
v-model="formData.PublicKey" :readonly="clientSideKeyGenerated">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label class="form-label mt-4">{{ $t('modals.peer-edit.preshared-key.label') }}</label>
|
<label class="form-label mt-4">{{ $t('modals.peer-edit.preshared-key.label') }}</label>
|
||||||
@@ -296,11 +354,11 @@ async function del() {
|
|||||||
{{ $t('general.delete') }}
|
{{ $t('general.delete') }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<button class="btn btn-primary me-1" type="button" @click.prevent="save" :disabled="isSaving">
|
<button class="btn btn-primary me-1" type="button" @click.prevent="save" :disabled="isBusy">
|
||||||
<span v-if="isSaving" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
|
<span v-if="isSaving" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
|
||||||
{{ $t('general.save') }}
|
{{ $t('general.save') }}
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-secondary" type="button" @click.prevent="close">{{ $t('general.close') }}</button>
|
<button class="btn btn-secondary" type="button" @click.prevent="close" :disabled="isSaving || isGeneratingKeys">{{ $t('general.close') }}</button>
|
||||||
</template>
|
</template>
|
||||||
</Modal>
|
</Modal>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
/**
|
||||||
|
* Convert a Base64URL-encoded string to standard Base64 with padding.
|
||||||
|
* @function b64urlToB64
|
||||||
|
* @param {string} input - The Base64URL string.
|
||||||
|
* @returns {string} The padded, standard Base64 string.
|
||||||
|
*/
|
||||||
|
function b64urlToB64(input) {
|
||||||
|
let b64 = input.replace(/-/g, '+').replace(/_/g, '/');
|
||||||
|
while (b64.length % 4) {
|
||||||
|
b64 += '=';
|
||||||
|
}
|
||||||
|
return b64;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate an X25519 keypair using the Web Crypto API and return Base64-encoded strings.
|
||||||
|
* @async
|
||||||
|
* @function generateKeypair
|
||||||
|
* @returns {Promise<{ publicKey: string, privateKey: string }>} Resolves with an object containing
|
||||||
|
* - publicKey: the Base64-encoded public key
|
||||||
|
* - privateKey: the Base64-encoded private key
|
||||||
|
*/
|
||||||
|
export async function generateKeypair() {
|
||||||
|
// 1. Generate an X25519 key pair
|
||||||
|
const keyPair = await crypto.subtle.generateKey(
|
||||||
|
{ name: 'X25519', namedCurve: 'X25519' },
|
||||||
|
true, // extractable
|
||||||
|
['deriveBits'] // allowed usage for ECDH
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2. Export keys as JWK to access raw key material
|
||||||
|
const pubJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
|
||||||
|
const privJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
|
||||||
|
|
||||||
|
// 3. Convert Base64URL to standard Base64 with padding
|
||||||
|
return {
|
||||||
|
publicKey: b64urlToB64(pubJwk.x),
|
||||||
|
privateKey: b64urlToB64(privJwk.d)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a wg-quick configuration for a peer, mirroring internal/app/configfile/tpl_files/wg_peer.tpl.
|
||||||
|
* @function buildWgQuickConfig
|
||||||
|
* @param {object} peer - The peer as returned by the API.
|
||||||
|
* @param {string} privateKey - The Base64-encoded private key that only exists in the browser.
|
||||||
|
* @returns {string} The wg-quick configuration.
|
||||||
|
*/
|
||||||
|
function buildWgQuickConfig(peer, privateKey) {
|
||||||
|
const lines = [
|
||||||
|
'[Interface]',
|
||||||
|
`PrivateKey = ${privateKey}`,
|
||||||
|
`Address = ${peer.Addresses.join(', ')}`,
|
||||||
|
]
|
||||||
|
|
||||||
|
if (peer.Dns.Value.length) {
|
||||||
|
lines.push(`DNS = ${[...peer.Dns.Value, ...peer.DnsSearch.Value].join(', ')}`)
|
||||||
|
}
|
||||||
|
if (peer.Mtu.Value !== 0) lines.push(`MTU = ${peer.Mtu.Value}`)
|
||||||
|
if (peer.RoutingTable.Value !== '') lines.push(`Table = ${peer.RoutingTable.Value}`)
|
||||||
|
if (peer.FirewallMark.Value !== 0) lines.push(`FwMark = ${peer.FirewallMark.Value}`)
|
||||||
|
if (peer.PreUp.Value) lines.push(`PreUp = ${peer.PreUp.Value}`)
|
||||||
|
if (peer.PostUp.Value) lines.push(`PostUp = ${peer.PostUp.Value}`)
|
||||||
|
if (peer.PreDown.Value) lines.push(`PreDown = ${peer.PreDown.Value}`)
|
||||||
|
if (peer.PostDown.Value) lines.push(`PostDown = ${peer.PostDown.Value}`)
|
||||||
|
|
||||||
|
lines.push(
|
||||||
|
'',
|
||||||
|
'[Peer]',
|
||||||
|
`PublicKey = ${peer.EndpointPublicKey.Value}`,
|
||||||
|
`Endpoint = ${peer.Endpoint.Value}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (peer.AllowedIPs.Value.length) lines.push(`AllowedIPs = ${peer.AllowedIPs.Value.join(', ')}`)
|
||||||
|
if (peer.PresharedKey) lines.push(`PresharedKey = ${peer.PresharedKey}`)
|
||||||
|
if (peer.PersistentKeepalive.Value !== 0 && peer.Mode === 'client') {
|
||||||
|
lines.push(`PersistentKeepalive = ${peer.PersistentKeepalive.Value}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines.join('\n') + '\n'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Download a wg-quick configuration for a peer whose private key only exists in the browser.
|
||||||
|
* @function downloadWgQuickConfig
|
||||||
|
* @param {object} peer - The peer as returned by the API.
|
||||||
|
* @param {string} privateKey - The Base64-encoded private key.
|
||||||
|
*/
|
||||||
|
export function downloadWgQuickConfig(peer, privateKey) {
|
||||||
|
let element = document.createElement('a')
|
||||||
|
element.setAttribute('href', 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(buildWgQuickConfig(peer, privateKey)))
|
||||||
|
element.setAttribute('download', peer.Filename)
|
||||||
|
|
||||||
|
element.style.display = 'none'
|
||||||
|
document.body.appendChild(element)
|
||||||
|
|
||||||
|
element.click()
|
||||||
|
document.body.removeChild(element)
|
||||||
|
}
|
||||||
@@ -587,6 +587,8 @@
|
|||||||
"private-key": {
|
"private-key": {
|
||||||
"label": "Privater Schlüssel",
|
"label": "Privater Schlüssel",
|
||||||
"placeholder": "Der private Schlüssel",
|
"placeholder": "Der private Schlüssel",
|
||||||
|
"local-label": "Lokal erzeugt",
|
||||||
|
"local-help": "Der private Schlüssel wurde in diesem Browser erzeugt und wird nicht an den Server gesendet. Die Konfiguration wird beim Speichern einmalig heruntergeladen.",
|
||||||
"help": "Der private Schlüssel wird sicher auf dem Server gespeichert. Wenn der Benutzer bereits eine Kopie besitzt, kann dieses Feld entfallen. Der Server funktioniert auch ausschließlich mit dem öffentlichen Schlüssel des Peers."
|
"help": "Der private Schlüssel wird sicher auf dem Server gespeichert. Wenn der Benutzer bereits eine Kopie besitzt, kann dieses Feld entfallen. Der Server funktioniert auch ausschließlich mit dem öffentlichen Schlüssel des Peers."
|
||||||
},
|
},
|
||||||
"public-key": {
|
"public-key": {
|
||||||
|
|||||||
@@ -587,6 +587,8 @@
|
|||||||
"private-key": {
|
"private-key": {
|
||||||
"label": "Private Key",
|
"label": "Private Key",
|
||||||
"placeholder": "The private key",
|
"placeholder": "The private key",
|
||||||
|
"local-label": "Generated locally",
|
||||||
|
"local-help": "The private key was generated in this browser and is not sent to the server. The configuration is downloaded once when you save.",
|
||||||
"help": "The private key is stored securely on the server. If the user already holds a copy, you may omit this field. The server still functions exclusively with the peer’s public key."
|
"help": "The private key is stored securely on the server. If the user already holds a copy, you may omit this field. The server still functions exclusively with the peer’s public key."
|
||||||
},
|
},
|
||||||
"public-key": {
|
"public-key": {
|
||||||
|
|||||||
@@ -1,38 +1,12 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
|
|
||||||
import {ref} from "vue";
|
import {ref} from "vue";
|
||||||
|
import { generateKeypair } from "@/helpers/wireguard";
|
||||||
|
|
||||||
const privateKey = ref("")
|
const privateKey = ref("")
|
||||||
const publicKey = ref("")
|
const publicKey = ref("")
|
||||||
const presharedKey = ref("")
|
const presharedKey = ref("")
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate an X25519 keypair using the Web Crypto API and return Base64-encoded strings.
|
|
||||||
* @async
|
|
||||||
* @function generateKeypair
|
|
||||||
* @returns {Promise<{ publicKey: string, privateKey: string }>} Resolves with an object containing
|
|
||||||
* - publicKey: the Base64-encoded public key
|
|
||||||
* - privateKey: the Base64-encoded private key
|
|
||||||
*/
|
|
||||||
async function generateKeypair() {
|
|
||||||
// 1. Generate an X25519 key pair
|
|
||||||
const keyPair = await crypto.subtle.generateKey(
|
|
||||||
{ name: 'X25519', namedCurve: 'X25519' },
|
|
||||||
true, // extractable
|
|
||||||
['deriveBits'] // allowed usage for ECDH
|
|
||||||
);
|
|
||||||
|
|
||||||
// 2. Export keys as JWK to access raw key material
|
|
||||||
const pubJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
|
|
||||||
const privJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
|
|
||||||
|
|
||||||
// 3. Convert Base64URL to standard Base64 with padding
|
|
||||||
return {
|
|
||||||
publicKey: b64urlToB64(pubJwk.x),
|
|
||||||
privateKey: b64urlToB64(privJwk.d)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate a 32-byte pre-shared key using crypto.getRandomValues.
|
* Generate a 32-byte pre-shared key using crypto.getRandomValues.
|
||||||
* @function generatePresharedKey
|
* @function generatePresharedKey
|
||||||
@@ -44,20 +18,6 @@ function generatePresharedKey() {
|
|||||||
return privateKey;
|
return privateKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a Base64URL-encoded string to standard Base64 with padding.
|
|
||||||
* @function b64urlToB64
|
|
||||||
* @param {string} input - The Base64URL string.
|
|
||||||
* @returns {string} The padded, standard Base64 string.
|
|
||||||
*/
|
|
||||||
function b64urlToB64(input) {
|
|
||||||
let b64 = input.replace(/-/g, '+').replace(/_/g, '/');
|
|
||||||
while (b64.length % 4) {
|
|
||||||
b64 += '=';
|
|
||||||
}
|
|
||||||
return b64;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert an ArrayBuffer or TypedArray buffer to a Base64-encoded string.
|
* Convert an ArrayBuffer or TypedArray buffer to a Base64-encoded string.
|
||||||
* @function arrayBufferToBase64
|
* @function arrayBufferToBase64
|
||||||
|
|||||||
@@ -2633,6 +2633,9 @@
|
|||||||
"$ref": "#/definitions/model.SettingsBackendNames"
|
"$ref": "#/definitions/model.SettingsBackendNames"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"EditableKeys": {
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
"LoginFormVisible": {
|
"LoginFormVisible": {
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -403,6 +403,8 @@ definitions:
|
|||||||
items:
|
items:
|
||||||
$ref: '#/definitions/model.SettingsBackendNames'
|
$ref: '#/definitions/model.SettingsBackendNames'
|
||||||
type: array
|
type: array
|
||||||
|
EditableKeys:
|
||||||
|
type: boolean
|
||||||
LoginFormVisible:
|
LoginFormVisible:
|
||||||
type: boolean
|
type: boolean
|
||||||
MailLinkOnly:
|
MailLinkOnly:
|
||||||
|
|||||||
@@ -141,6 +141,7 @@ func (e ConfigEndpoint) handleSettingsGet() http.HandlerFunc {
|
|||||||
MailLinkOnly: e.cfg.Mail.LinkOnly,
|
MailLinkOnly: e.cfg.Mail.LinkOnly,
|
||||||
PersistentConfigSupported: e.cfg.Advanced.ConfigStoragePath != "",
|
PersistentConfigSupported: e.cfg.Advanced.ConfigStoragePath != "",
|
||||||
SelfProvisioning: e.cfg.Core.SelfProvisioningAllowed,
|
SelfProvisioning: e.cfg.Core.SelfProvisioningAllowed,
|
||||||
|
EditableKeys: e.cfg.Core.EditableKeys,
|
||||||
ApiAdminOnly: e.cfg.Advanced.ApiAdminOnly,
|
ApiAdminOnly: e.cfg.Advanced.ApiAdminOnly,
|
||||||
WebAuthnEnabled: e.cfg.Auth.WebAuthn.Enabled,
|
WebAuthnEnabled: e.cfg.Auth.WebAuthn.Enabled,
|
||||||
MinPasswordLength: e.cfg.Auth.MinPasswordLength,
|
MinPasswordLength: e.cfg.Auth.MinPasswordLength,
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/app/api/v0/model"
|
||||||
|
"github.com/h44z/wg-portal/internal/config"
|
||||||
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
type testControllerManager struct{}
|
||||||
|
|
||||||
|
func (testControllerManager) GetControllerNames() []config.BackendBase {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getSettings(t *testing.T, cfg *config.Config, userId domain.UserIdentifier) model.Settings {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
ep := ConfigEndpoint{cfg: cfg, controllerMgr: testControllerManager{}}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/v0/config/settings", nil)
|
||||||
|
req = req.WithContext(domain.SetUserInfo(context.Background(), &domain.ContextUserInfo{Id: userId}))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
|
||||||
|
ep.handleSettingsGet().ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var settings model.Settings
|
||||||
|
if err := json.NewDecoder(rec.Body).Decode(&settings); err != nil {
|
||||||
|
t.Fatalf("failed to decode settings: %v", err)
|
||||||
|
}
|
||||||
|
return settings
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConfigEndpointSettingsExposesEditableKeys pins the EditableKeys flag that the frontend uses to offer
|
||||||
|
// browser-side key generation in frontend/src/components/UserPeerEditModal.vue.
|
||||||
|
func TestConfigEndpointSettingsExposesEditableKeys(t *testing.T) {
|
||||||
|
for _, editable := range []bool{true, false} {
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Core.EditableKeys = editable
|
||||||
|
|
||||||
|
if got := getSettings(t, cfg, "user@example.com").EditableKeys; got != editable {
|
||||||
|
t.Fatalf("expected EditableKeys=%v for logged-in users, got %v", editable, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigEndpointSettingsHidesEditableKeysFromAnonymousUsers(t *testing.T) {
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Core.EditableKeys = true
|
||||||
|
|
||||||
|
if getSettings(t, cfg, domain.CtxUnknownUserId).EditableKeys {
|
||||||
|
t.Fatalf("expected EditableKeys to be hidden from anonymous users")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ type Settings struct {
|
|||||||
MailLinkOnly bool `json:"MailLinkOnly"`
|
MailLinkOnly bool `json:"MailLinkOnly"`
|
||||||
PersistentConfigSupported bool `json:"PersistentConfigSupported"`
|
PersistentConfigSupported bool `json:"PersistentConfigSupported"`
|
||||||
SelfProvisioning bool `json:"SelfProvisioning"`
|
SelfProvisioning bool `json:"SelfProvisioning"`
|
||||||
|
EditableKeys bool `json:"EditableKeys"`
|
||||||
ApiAdminOnly bool `json:"ApiAdminOnly"`
|
ApiAdminOnly bool `json:"ApiAdminOnly"`
|
||||||
WebAuthnEnabled bool `json:"WebAuthnEnabled"`
|
WebAuthnEnabled bool `json:"WebAuthnEnabled"`
|
||||||
MinPasswordLength int `json:"MinPasswordLength"`
|
MinPasswordLength int `json:"MinPasswordLength"`
|
||||||
|
|||||||
@@ -212,6 +212,61 @@ func TestCreatePeer_SetsIdentifier_FromPublicKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestCreatePeer_KeepsBrowserGeneratedKeyWithoutPrivateKey covers the browser-side key generation flow of
|
||||||
|
// frontend/src/components/UserPeerEditModal.vue: the client only sends its public key, so the server must
|
||||||
|
// neither store a private key nor replace the key pair with a server-generated one.
|
||||||
|
func TestCreatePeer_KeepsBrowserGeneratedKeyWithoutPrivateKey(t *testing.T) {
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Core.SelfProvisioningAllowed = true
|
||||||
|
cfg.Core.EditableKeys = true
|
||||||
|
|
||||||
|
ctrlMgr := &ControllerManager{
|
||||||
|
controllers: map[domain.InterfaceBackend]backendInstance{
|
||||||
|
config.LocalBackendName: {Implementation: &mockController{}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
db := &mockDB{iface: &domain.Interface{Identifier: "wg0", Type: domain.InterfaceTypeServer}}
|
||||||
|
|
||||||
|
m := Manager{
|
||||||
|
cfg: cfg,
|
||||||
|
bus: &mockBus{},
|
||||||
|
db: db,
|
||||||
|
wg: ctrlMgr,
|
||||||
|
}
|
||||||
|
|
||||||
|
userId := domain.UserIdentifier("user@example.com")
|
||||||
|
ctx := domain.SetUserInfo(context.Background(), &domain.ContextUserInfo{Id: userId, IsAdmin: false})
|
||||||
|
|
||||||
|
pubKey := "BROWSER_GENERATED_PUBLIC_KEY"
|
||||||
|
|
||||||
|
input := &domain.Peer{
|
||||||
|
UserIdentifier: userId,
|
||||||
|
InterfaceIdentifier: domain.InterfaceIdentifier("wg0"),
|
||||||
|
Interface: domain.PeerInterfaceConfig{
|
||||||
|
KeyPair: domain.KeyPair{PublicKey: pubKey},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := m.CreatePeer(ctx, input)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreatePeer returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
saved := db.savedPeers[domain.PeerIdentifier(pubKey)]
|
||||||
|
if saved == nil {
|
||||||
|
t.Fatalf("expected peer with identifier %q to be saved in DB", pubKey)
|
||||||
|
}
|
||||||
|
for name, peer := range map[string]*domain.Peer{"returned": out, "saved": saved} {
|
||||||
|
if peer.Interface.PublicKey != pubKey {
|
||||||
|
t.Fatalf("expected %s peer to keep public key %q, got %q", name, pubKey, peer.Interface.PublicKey)
|
||||||
|
}
|
||||||
|
if peer.Interface.PrivateKey != "" {
|
||||||
|
t.Fatalf("expected %s peer to have no private key, got %q", name, peer.Interface.PrivateKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCreateDefaultPeer_RespectsInterfaceFlag(t *testing.T) {
|
func TestCreateDefaultPeer_RespectsInterfaceFlag(t *testing.T) {
|
||||||
// Arrange
|
// Arrange
|
||||||
cfg := &config.Config{}
|
cfg := &config.Config{}
|
||||||
|
|||||||
Reference in New Issue
Block a user