🎉 Init

This commit is contained in:
2026-07-19 16:43:30 +02:00
commit 3e380643d7
61 changed files with 4644 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
{"sessionId":"433ed9bc-2980-474e-b7f0-4dce7d8f063f","pid":59345,"procStart":"541074","acquiredAt":1784461527697}
+14
View File
@@ -0,0 +1,14 @@
# Maven
target/
# Node
node_modules/
dist/
# IDE
.idea/
*.iml
.vscode/
# OS
.DS_Store
+9
View File
@@ -0,0 +1,9 @@
services:
postgres:
image: postgres:16
environment:
POSTGRES_DB: postgres
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- "32876:5432"
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+17
View File
@@ -0,0 +1,17 @@
FROM node:24-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
+5
View File
@@ -0,0 +1,5 @@
# Vue 3 + TypeScript + Vite
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lockaway</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+18
View File
@@ -0,0 +1,18 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://backend/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+1954
View File
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@fontsource-variable/big-shoulders-display": "^5.3.0",
"@fontsource-variable/mulish": "^5.2.8",
"@fontsource/ibm-plex-mono": "^5.3.0",
"@tailwindcss/vite": "^4.3.3",
"@vueuse/core": "^14.3.0",
"axios": "^1.18.1",
"material-symbols": "^0.45.8",
"tailwindcss": "^4.3.3",
"vue": "^3.5.39"
},
"devDependencies": {
"@types/node": "^24.13.2",
"@vitejs/plugin-vue": "^6.0.7",
"@vue/tsconfig": "^0.9.1",
"typescript": "~6.0.2",
"vite": "^8.1.1",
"vue-tsc": "^3.3.5"
}
}
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
DEV_TAG=3
IMAGE="harbor.dinauer.dev/lockaway/frontend:dev-${DEV_TAG}"
echo "==> Building Docker image ${IMAGE}"
docker build --no-cache -t "${IMAGE}" .
echo "==> Pushing image to Harbor"
if [[ -n "${HARBOR_USERNAME:-}" && -n "${HARBOR_PASSWORD:-}" ]]; then
echo "${HARBOR_PASSWORD}" | docker login harbor.dinauer.dev -u "${HARBOR_USERNAME}" --password-stdin
docker push "${IMAGE}"
docker logout harbor.dinauer.dev
else
docker push "${IMAGE}"
fi
echo "==> Removing local image"
docker image rm --force "${IMAGE}"
echo "==> Done: ${IMAGE}"
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

+43
View File
@@ -0,0 +1,43 @@
<script setup lang="ts">
import HeaderComponent from './components/HeaderComponent.vue'
import SearchInput from './components/SearchInput.vue'
import SecretList from './components/SecretList.vue'
import MasterPasswordGate from './components/MasterPasswordGate.vue'
import CreateSecretPopup from './components/CreateSecretPopup.vue'
import { usePopup } from './components/popup/Popup'
import { useSecrets } from './composables/useSecrets'
import { useMasterPassword } from './composables/useMasterPassword'
const { masterPassword, isRestoring } = useMasterPassword()
const { secrets, searchText, load } = useSecrets()
function openCreateSecretPopup() {
usePopup().open(CreateSecretPopup, { onCreated: load })
}
</script>
<template>
<template v-if="!isRestoring">
<MasterPasswordGate v-if="!masterPassword" />
<template v-else>
<HeaderComponent @imported="load" />
<main class="mx-auto max-w-5xl space-y-5 p-6">
<div class="flex gap-2">
<SearchInput v-model="searchText" />
<button
type="button"
class="flex h-10 shrink-0 items-center gap-1.5 rounded bg-brass px-4 text-sm font-bold tracking-[0.08em] text-ink transition-colors hover:bg-brass-bright active:scale-[0.98] tracking-normal"
@click="openCreateSecretPopup"
>
<span class="material-symbols-outlined text-[1em] leading-none" style="font-variation-settings: 'FILL' 0, 'wght' 500, 'GRAD' 0, 'opsz' 20">
add
</span>
NEW ENTRY
</button>
</div>
<SecretList :secrets="secrets" @deleted="load" @updated="load" />
</main>
</template>
</template>
<component :is="usePopup().get()" />
</template>
+5
View File
@@ -0,0 +1,5 @@
import axios from 'axios'
export const apiClient = axios.create({
baseURL: '/api',
})
+13
View File
@@ -0,0 +1,13 @@
import axios from 'axios'
const ERROR_MESSAGES: Record<string, string> = {
secret_conflict: 'Ein Secret mit diesem Namen existiert bereits in einem der ausgewählten Namespaces.',
}
export function extractErrorMessage(error: unknown): string {
if (axios.isAxiosError(error) && typeof error.response?.data?.error === 'string') {
const key = error.response.data.error
return ERROR_MESSAGES[key] ?? key
}
return 'Etwas ist schiefgelaufen.'
}
+5
View File
@@ -0,0 +1,5 @@
import { apiClient } from './client'
export function exportSecrets(): Promise<Blob> {
return apiClient.get('/_export', { responseType: 'blob' }).then((response) => response.data)
}
+5
View File
@@ -0,0 +1,5 @@
import { apiClient } from './client'
export function importSecrets(secrets: unknown): Promise<void> {
return apiClient.post('/_import', secrets).then(() => undefined)
}
+47
View File
@@ -0,0 +1,47 @@
import { apiClient } from './client'
import type { Secret } from '../types/Secret'
interface SecretResponse {
id: string
name: string
namespaces: string[]
contentHash: string
entries: Record<string, string>
type: string
}
function toSecret(response: SecretResponse): Secret {
return {
id: response.id,
name: response.name,
namespaces: response.namespaces,
contentHash: response.contentHash,
entries: Object.entries(response.entries).map(([key, value]) => ({ key, value })),
type: response.type,
}
}
export function getSecrets(searchText?: string): Promise<Secret[]> {
return apiClient
.get<SecretResponse[]>('/secrets', { params: { searchText } })
.then((response) => response.data.map(toSecret))
}
export interface SecretCreatePayload {
name: string
namespaces: string[]
entries: Record<string, string>
type: string
}
export function createSecret(payload: SecretCreatePayload): Promise<void> {
return apiClient.post('/secrets', payload).then(() => undefined)
}
export function updateSecret(id: string, payload: SecretCreatePayload): Promise<void> {
return apiClient.put(`/secrets/${id}`, payload).then(() => undefined)
}
export function deleteSecret(id: string): Promise<void> {
return apiClient.delete(`/secrets/${id}`).then(() => undefined)
}
+11
View File
@@ -0,0 +1,11 @@
import { apiClient } from './client'
export function getVerificationValue(): Promise<string | null> {
return apiClient
.get<{ value: string } | ''>('/verification', { validateStatus: (status) => status === 200 || status === 204 })
.then((response) => (response.status === 204 ? null : (response.data as { value: string }).value))
}
export function setVerificationValue(value: string): Promise<void> {
return apiClient.post('/verification', { value }).then(() => undefined)
}
@@ -0,0 +1,69 @@
<script setup lang="ts">
import { ref } from 'vue'
import PopupTemplate from './popup/PopupTemplate.vue'
import SecretForm from './SecretForm.vue'
import { usePopup } from './popup/Popup'
import { useMasterPassword } from '../composables/useMasterPassword'
import { encryptValue } from '../crypto/secretCrypto'
import { createSecret } from '../api/secrets'
import { extractErrorMessage } from '../api/errors'
const { onCreated } = usePopup().data<{ onCreated: () => void }>()
const { derivedKey } = useMasterPassword()
const name = ref('')
const namespaces = ref<string[]>([])
const entries = ref([{ key: '', value: '' }])
const type = ref('Opaque')
const isSubmitting = ref(false)
const errorMessage = ref('')
function submit() {
const key = derivedKey.value
if (!key) {
return
}
isSubmitting.value = true
errorMessage.value = ''
Promise.all(
entries.value
.filter((entry) => entry.key)
.map((entry) => encryptValue(key, entry.value).then((encrypted) => [entry.key, encrypted] as const)),
)
.then((encryptedPairs) =>
createSecret({
name: name.value,
namespaces: namespaces.value,
entries: Object.fromEntries(encryptedPairs),
type: type.value,
}),
)
.then(() => {
onCreated()
usePopup().close()
})
.catch((error) => {
errorMessage.value = extractErrorMessage(error)
})
.finally(() => {
isSubmitting.value = false
})
}
</script>
<template>
<PopupTemplate heading="Secret erstellen">
<SecretForm
v-model:name="name"
v-model:namespaces="namespaces"
v-model:entries="entries"
v-model:type="type"
submit-label="Erstellen"
:submitting="isSubmitting"
:error-message="errorMessage"
@submit="submit"
/>
</PopupTemplate>
</template>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import PopupTemplate from './popup/PopupTemplate.vue'
import { usePopup } from './popup/Popup'
import { deleteSecret } from '../api/secrets'
import type { Secret } from '../types/Secret'
const { secret, onDeleted } = usePopup().data<{ secret: Secret; onDeleted: () => void }>()
function confirmDelete() {
deleteSecret(secret.id).then(() => {
onDeleted()
usePopup().close()
})
}
</script>
<template>
<PopupTemplate heading="Secret löschen" size="sm">
<p class="text-sm text-paper-dim">
Soll <span class="font-mono text-paper">{{ secret.name }}</span> wirklich gelöscht werden?
</p>
<div class="mt-4 flex justify-end gap-2">
<button
type="button"
class="rounded px-4 py-2 text-sm font-semibold text-paper-dim transition-colors hover:bg-panel-2 hover:text-paper"
@click="usePopup().close()"
>
Abbrechen
</button>
<button
type="button"
class="rounded bg-rust px-4 py-2 text-sm font-bold tracking-[0.08em] text-paper transition-colors hover:brightness-110 active:scale-[0.98]"
@click="confirmDelete"
>
LÖSCHEN
</button>
</div>
</PopupTemplate>
</template>
@@ -0,0 +1,87 @@
<script setup lang="ts">
import { ref } from 'vue'
import PopupTemplate from './popup/PopupTemplate.vue'
import SecretForm from './SecretForm.vue'
import { usePopup } from './popup/Popup'
import { useMasterPassword } from '../composables/useMasterPassword'
import { decryptValue, encryptValue } from '../crypto/secretCrypto'
import { updateSecret } from '../api/secrets'
import { extractErrorMessage } from '../api/errors'
import type { Secret } from '../types/Secret'
const { secret, onUpdated } = usePopup().data<{ secret: Secret; onUpdated: () => void }>()
const { derivedKey } = useMasterPassword()
const name = ref(secret.name)
const namespaces = ref<string[]>([...secret.namespaces])
const entries = ref<{ key: string; value: string }[]>([])
const type = ref(secret.type)
const isLoading = ref(true)
const isSubmitting = ref(false)
const errorMessage = ref('')
const decryptionKey = derivedKey.value
if (decryptionKey) {
Promise.all(
secret.entries.map((entry) =>
decryptValue(decryptionKey, entry.value)
.then((value) => ({ key: entry.key, value }))
.catch(() => ({ key: entry.key, value: '' })),
),
).then((decrypted) => {
entries.value = decrypted
isLoading.value = false
})
}
function submit() {
const encryptionKey = derivedKey.value
if (!encryptionKey) {
return
}
isSubmitting.value = true
errorMessage.value = ''
Promise.all(
entries.value
.filter((entry) => entry.key)
.map((entry) => encryptValue(encryptionKey, entry.value).then((encrypted) => [entry.key, encrypted] as const)),
)
.then((encryptedPairs) =>
updateSecret(secret.id, {
name: name.value,
namespaces: namespaces.value,
entries: Object.fromEntries(encryptedPairs),
type: type.value,
}),
)
.then(() => {
onUpdated()
usePopup().close()
})
.catch((error) => {
errorMessage.value = extractErrorMessage(error)
})
.finally(() => {
isSubmitting.value = false
})
}
</script>
<template>
<PopupTemplate heading="Secret bearbeiten">
<div v-if="isLoading" class="text-sm text-paper-dim">Entschlüssele…</div>
<SecretForm
v-else
v-model:name="name"
v-model:namespaces="namespaces"
v-model:entries="entries"
v-model:type="type"
submit-label="Speichern"
:submitting="isSubmitting"
:error-message="errorMessage"
@submit="submit"
/>
</PopupTemplate>
</template>
@@ -0,0 +1,76 @@
<script setup lang="ts">
import { useMasterPassword } from '../composables/useMasterPassword'
import { exportSecrets } from '../api/export'
import { usePopup } from './popup/Popup'
import ImportSecretsPopup from './ImportSecretsPopup.vue'
const emit = defineEmits<{ imported: [] }>()
const { lock } = useMasterPassword()
function exportFilename() {
const now = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`
const time = `${pad(now.getHours())}-${pad(now.getMinutes())}`
return `${date}_${time}_lockaway-export.json`
}
function download() {
exportSecrets().then((blob) => {
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = exportFilename()
link.click()
URL.revokeObjectURL(url)
})
}
function openImportPopup() {
usePopup().open(ImportSecretsPopup, { onImported: () => emit('imported') })
}
</script>
<template>
<header class="sticky top-0 z-30 flex items-center justify-between gap-3 border-b border-hairline bg-panel px-5 py-3">
<div class="flex items-center gap-2.5">
<span class="material-symbols-outlined text-[1.35rem] leading-none text-brass" style="font-variation-settings: 'FILL' 1, 'wght' 400, 'GRAD' 0, 'opsz' 24">
lock
</span>
<span class="font-display text-[1.7rem] font-semibold leading-none tracking-wide text-paper">Lockaway</span>
</div>
<div class="flex items-center gap-1.5">
<button
type="button"
class="flex items-center gap-1.5 rounded px-3 py-1.5 text-sm font-semibold text-paper-dim transition-colors hover:bg-panel-2 hover:text-paper"
@click="openImportPopup"
>
<span class="material-symbols-outlined text-[1em] leading-none" style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20">
upload
</span>
Import
</button>
<button
type="button"
class="flex items-center gap-1.5 rounded px-3 py-1.5 text-sm font-semibold text-paper-dim transition-colors hover:bg-panel-2 hover:text-paper"
@click="download"
>
<span class="material-symbols-outlined text-[1em] leading-none" style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20">
download
</span>
Export
</button>
<button
type="button"
class="flex items-center gap-1.5 rounded px-3 py-1.5 text-sm font-semibold text-paper-dim transition-colors hover:bg-panel-2 hover:text-paper"
@click="lock"
>
<span class="material-symbols-outlined text-[1em] leading-none" style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20">
logout
</span>
Logout
</button>
</div>
</header>
</template>
@@ -0,0 +1,73 @@
<script setup lang="ts">
import { ref } from 'vue'
import PopupTemplate from './popup/PopupTemplate.vue'
import { usePopup } from './popup/Popup'
import { importSecrets } from '../api/import'
import { extractErrorMessage } from '../api/errors'
const { onImported } = usePopup().data<{ onImported: () => void }>()
const file = ref<File | null>(null)
const errorMessage = ref('')
const isSubmitting = ref(false)
function onFileSelected(event: Event) {
file.value = (event.target as HTMLInputElement).files?.[0] ?? null
errorMessage.value = ''
}
function submit() {
if (!file.value) {
errorMessage.value = 'Bitte eine Datei auswählen.'
return
}
isSubmitting.value = true
errorMessage.value = ''
file.value
.text()
.then((text) => importSecrets(JSON.parse(text)))
.then(() => {
onImported()
usePopup().close()
})
.catch((error) => {
errorMessage.value = extractErrorMessage(error)
})
.finally(() => {
isSubmitting.value = false
})
}
</script>
<template>
<PopupTemplate heading="Secrets importieren" size="sm">
<div class="space-y-3">
<input
type="file"
accept="application/json"
class="w-full rounded border border-hairline bg-ink px-3 py-2 text-sm text-paper-dim file:mr-3 file:rounded file:border-0 file:bg-panel-2 file:px-3 file:py-1.5 file:text-sm file:font-semibold file:text-paper"
@change="onFileSelected"
/>
<p v-if="errorMessage" class="text-sm text-rust">{{ errorMessage }}</p>
</div>
<div class="mt-4 flex justify-end gap-2">
<button
type="button"
class="rounded px-4 py-2 text-sm font-semibold text-paper-dim transition-colors hover:bg-panel-2 hover:text-paper"
@click="usePopup().close()"
>
Abbrechen
</button>
<button
type="button"
:disabled="isSubmitting"
class="rounded bg-brass px-4 py-2 text-sm font-bold tracking-[0.08em] text-ink transition-colors hover:bg-brass-bright disabled:opacity-50"
@click="submit"
>
IMPORT
</button>
</div>
</PopupTemplate>
</template>
@@ -0,0 +1,174 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useMasterPassword } from '../composables/useMasterPassword'
import { useVerification } from '../composables/useVerification'
const { unlock } = useMasterPassword()
const { needsSetup, setup, verify } = useVerification()
const password = ref('')
const repeatPassword = ref('')
const errorMessage = ref('')
const isSubmitting = ref(false)
function submitSetup() {
errorMessage.value = ''
if (password.value.length < 8) {
errorMessage.value = 'Master Password muss mindestens 8 Zeichen lang sein.'
return
}
if (password.value !== repeatPassword.value) {
errorMessage.value = 'Die Passwörter stimmen nicht überein.'
return
}
isSubmitting.value = true
setup(password.value)
.then(() => unlock(password.value))
.catch(() => {
errorMessage.value = 'Einrichtung fehlgeschlagen.'
})
.finally(() => {
isSubmitting.value = false
})
}
function submitUnlock() {
errorMessage.value = ''
isSubmitting.value = true
verify(password.value)
.then((isValid) => {
if (!isValid) {
errorMessage.value = 'Falsches Master Password.'
return undefined
}
return unlock(password.value)
})
.finally(() => {
isSubmitting.value = false
})
}
</script>
<template>
<div class="flex min-h-screen items-center justify-center p-4">
<div class="flex w-full max-w-sm flex-col items-center space-y-6">
<div class="dial">
<div class="dial__ticks" />
<div class="dial__face">
<span class="material-symbols-outlined text-[1.75rem] leading-none text-brass" style="font-variation-settings: 'FILL' 1, 'wght' 400, 'GRAD' 0, 'opsz' 24">
lock
</span>
</div>
</div>
<div class="text-center">
<h1 class="font-display text-3xl font-semibold leading-none tracking-wide text-paper">Lockaway</h1>
<p v-if="needsSetup === null" class="mt-2 text-sm text-paper-dim">Prüfe Tresor-Status…</p>
<p v-else-if="needsSetup" class="mt-2 text-sm text-paper-dim">Noch kein Master Password gesetzt — richte den Tresor ein.</p>
<p v-else class="mt-2 text-sm text-paper-dim">Master Password eingeben, um den Tresor zu öffnen.</p>
</div>
<form
v-if="needsSetup === true"
@submit.prevent="submitSetup"
class="w-full space-y-3 rounded border border-hairline bg-panel p-5"
>
<input
v-model="password"
type="password"
placeholder="Master Password"
autocomplete="new-password"
autofocus
class="w-full rounded border border-hairline bg-ink px-3 py-2.5 font-mono text-sm text-paper outline-none transition-colors placeholder:text-paper-dim/60 focus:border-brass/60"
/>
<input
v-model="repeatPassword"
type="password"
placeholder="Master Password wiederholen"
autocomplete="new-password"
class="w-full rounded border border-hairline bg-ink px-3 py-2.5 font-mono text-sm text-paper outline-none transition-colors placeholder:text-paper-dim/60 focus:border-brass/60"
/>
<p v-if="errorMessage" class="text-sm text-rust">{{ errorMessage }}</p>
<button
type="submit"
:disabled="isSubmitting"
class="flex w-full items-center justify-center gap-2 rounded bg-brass py-2.5 text-sm font-bold tracking-[0.08em] text-ink transition-colors hover:bg-brass-bright disabled:opacity-50"
>
TRESOR EINRICHTEN
</button>
</form>
<form
v-else-if="needsSetup === false"
@submit.prevent="submitUnlock"
class="w-full space-y-3 rounded border border-hairline bg-panel p-5"
>
<input
v-model="password"
type="password"
placeholder="Master Password"
autocomplete="current-password"
autofocus
class="w-full rounded border border-hairline bg-ink px-3 py-2.5 font-mono text-sm text-paper outline-none transition-colors placeholder:text-paper-dim/60 focus:border-brass/60"
/>
<p v-if="errorMessage" class="text-sm text-rust">{{ errorMessage }}</p>
<button
type="submit"
:disabled="isSubmitting"
class="flex w-full items-center justify-center gap-2 rounded bg-brass py-2.5 text-sm font-bold tracking-[0.08em] text-ink transition-colors hover:bg-brass-bright disabled:opacity-50"
>
ENTSPERREN
</button>
</form>
</div>
</div>
</template>
<style scoped>
.dial {
position: relative;
width: 6.5rem;
height: 6.5rem;
}
.dial__ticks {
position: absolute;
inset: 0;
border-radius: 9999px;
background: repeating-conic-gradient(var(--color-brass) 0deg 2deg, transparent 2deg 18deg);
-webkit-mask-image: radial-gradient(closest-side, transparent 74%, black 78%, black 92%, transparent 96%);
mask-image: radial-gradient(closest-side, transparent 74%, black 78%, black 92%, transparent 96%);
animation: settle 0.7s cubic-bezier(0.16, 1, 0.3, 1) both;
}
.dial__face {
position: absolute;
inset: 0.85rem;
display: flex;
align-items: center;
justify-content: center;
border-radius: 9999px;
background: var(--color-panel);
border: 1px solid var(--color-hairline);
}
@keyframes settle {
from {
transform: rotate(-45deg);
opacity: 0;
}
to {
transform: rotate(0deg);
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.dial__ticks {
animation: none;
}
}
</style>
@@ -0,0 +1,52 @@
<script setup lang="ts">
import { ref } from 'vue'
const model = defineModel<string[]>({ required: true })
const input = ref('')
function addNamespace() {
const value = input.value.trim()
if (value && !model.value.includes(value)) {
model.value.push(value)
}
input.value = ''
}
function removeNamespace(namespace: string) {
model.value = model.value.filter((n) => n !== namespace)
}
</script>
<template>
<div>
<div v-if="model.length" class="mb-2 flex flex-wrap gap-1.5">
<span
v-for="namespace in model"
:key="namespace"
class="flex items-center gap-1 rounded border border-hairline py-1 pl-2 pr-1 font-mono text-xs text-paper-dim"
>
{{ namespace }}
<button
type="button"
class="flex h-3 w-3 items-center justify-center rounded-full text-paper-dim hover:text-rust"
@click="removeNamespace(namespace)"
>
<span
class="material-symbols-outlined text-[1em] leading-none"
style="font-variation-settings: 'FILL' 0, 'wght' 300, 'GRAD' 0, 'opsz' 20"
>
close
</span>
</button>
</span>
</div>
<input
v-model="input"
type="text"
placeholder="Namespace eingeben und Enter drücken"
class="w-full rounded border border-hairline bg-ink px-3 py-2 font-mono text-sm text-paper outline-none transition-colors placeholder:text-paper-dim/60 focus:border-brass/60"
@keydown.enter.prevent="addNamespace"
@blur="addNamespace"
/>
</div>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
const model = defineModel<string>({ required: true })
</script>
<template>
<div class="relative flex-1">
<span
class="material-symbols-outlined pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[18px] text-paper-dim"
style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20"
>
search
</span>
<input
v-model="model"
type="text"
placeholder="Suche nach Name, Namespace oder Key…"
class="h-10 w-full rounded border border-hairline bg-panel pl-9 pr-3 font-mono text-sm text-paper outline-none transition-colors placeholder:text-paper-dim/70 focus:border-brass/60"
/>
</div>
</template>
+161
View File
@@ -0,0 +1,161 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { useClipboard } from '@vueuse/core'
import type { Secret } from '../types/Secret'
import { useMasterPassword } from '../composables/useMasterPassword'
import { decryptValue } from '../crypto/secretCrypto'
import { usePopup } from './popup/Popup'
import DeleteSecretPopup from './DeleteSecretPopup.vue'
import EditSecretPopup from './EditSecretPopup.vue'
const props = defineProps<{ secret: Secret }>()
const emit = defineEmits<{ deleted: []; updated: [] }>()
const { derivedKey } = useMasterPassword()
const { copy, copied } = useClipboard()
const decryptedValues = ref<Record<string, string>>({})
const revealed = ref<Record<string, boolean>>({})
const copiedKey = ref<string | null>(null)
function toggleReveal(key: string) {
revealed.value[key] = !revealed.value[key]
}
function copyValue(key: string) {
const value = decryptedValues.value[key]
if (value === undefined) {
return
}
copiedKey.value = key
copy(value)
}
function openDeletePopup() {
usePopup().open(DeleteSecretPopup, { secret: props.secret, onDeleted: () => emit('deleted') })
}
function openEditPopup() {
usePopup().open(EditSecretPopup, { secret: props.secret, onUpdated: () => emit('updated') })
}
watch(
() => props.secret,
(secret) => {
const key = derivedKey.value
if (!key) {
return
}
Promise.all(
secret.entries.map((entry) =>
decryptValue(key, entry.value)
.then((value) => [entry.key, value] as const)
.catch(() => [entry.key, '⚠️ falsches Master Password'] as const),
),
).then((pairs) => {
decryptedValues.value = Object.fromEntries(pairs)
})
},
{ immediate: true },
)
</script>
<template>
<details class="group rounded border border-hairline bg-panel transition-colors open:border-brass/40">
<summary class="flex cursor-pointer list-none items-center gap-3 px-4 py-3">
<span
class="material-symbols-outlined shrink-0 text-paper-dim transition-transform group-open:rotate-90"
style="font-variation-settings: 'FILL' 0, 'wght' 500, 'GRAD' 0, 'opsz' 20"
>
chevron_right
</span>
<div class="flex min-w-0 flex-1 items-center gap-2">
<h2 class="shrink truncate font-display text-lg font-bold leading-none tracking-widest text-paper">
{{ secret.name.toUpperCase() }}
</h2>
<span
v-if="secret.type !== 'Opaque'"
class="hidden shrink-0 rounded border border-verdigris/40 px-1.5 py-0.5 font-mono text-[11px] text-verdigris sm:inline"
:title="`Secret-Type: ${secret.type}`"
>
{{ secret.type }}
</span>
<span
class="hidden shrink-0 font-mono text-[13px] tracking-wide text-brass/70 sm:inline"
title="Secret-ID (gekürzt)"
>
#{{ secret.id.slice(0, 8) }}
</span>
</div>
<div class="flex shrink-0 items-center gap-1.5">
<span
v-for="namespace in secret.namespaces"
:key="namespace"
class="rounded border border-hairline px-2 py-0.5 font-mono text-sm text-paper-dim"
>
{{ namespace }}
</span>
<button
type="button"
class="flex h-8 w-8 shrink-0 items-center justify-center rounded text-paper-dim transition-colors hover:bg-panel-2 hover:text-paper"
@click.stop.prevent="openEditPopup"
>
<span class="material-symbols-outlined text-[1em] leading-none" style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20">
edit
</span>
</button>
<button
type="button"
class="flex h-8 w-8 shrink-0 items-center justify-center rounded text-paper-dim transition-colors hover:bg-panel-2 hover:text-rust"
@click.stop.prevent="openDeletePopup"
>
<span class="material-symbols-outlined text-[1em] leading-none" style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20">
delete
</span>
</button>
</div>
</summary>
<div class="space-y-2 border-t border-hairline px-4 py-3">
<div v-for="entry in secret.entries" :key="entry.key" class="flex items-baseline gap-2">
<span class="shrink-0 font-mono text-[14px] uppercase tracking-wide text-verdigris">{{ entry.key }}</span>
<span class="leader" />
<button
type="button"
class="flex max-w-xs shrink-0 items-center gap-1.5 font-mono text-[14px] text-paper transition-colors hover:text-brass"
@click="toggleReveal(entry.key)"
>
<span class="truncate">{{ revealed[entry.key] ? (decryptedValues[entry.key] ?? '…') : entry.value }}</span>
<span
class="material-symbols-outlined shrink-0 text-[1em] leading-none text-paper-dim"
style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20"
>
{{ revealed[entry.key] ? 'visibility_off' : 'visibility' }}
</span>
</button>
<button
type="button"
class="flex h-6 w-6 shrink-0 self-center items-center justify-center rounded text-paper-dim transition-colors hover:bg-panel-2 hover:text-brass"
title="In Zwischenablage kopieren"
@click="copyValue(entry.key)"
>
<span
class="material-symbols-outlined text-[1em] leading-none"
:class="copied && copiedKey === entry.key ? 'text-verdigris' : ''"
style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20"
>
{{ copied && copiedKey === entry.key ? 'check' : 'content_copy' }}
</span>
</button>
</div>
</div>
</details>
</template>
<style scoped>
.leader {
flex: 1 1 auto;
border-bottom: 1px dotted var(--color-hairline);
margin-bottom: 0.3rem;
min-width: 1rem;
}
</style>
+106
View File
@@ -0,0 +1,106 @@
<script setup lang="ts">
import NamespacePicker from './NamespacePicker.vue'
const name = defineModel<string>('name', { required: true })
const namespaces = defineModel<string[]>('namespaces', { required: true })
const entries = defineModel<{ key: string; value: string }[]>('entries', { required: true })
const type = defineModel<string>('type', { required: true })
const SECRET_TYPES = [
'Opaque',
'kubernetes.io/tls',
'kubernetes.io/dockerconfigjson',
'kubernetes.io/basic-auth',
'kubernetes.io/ssh-auth',
]
defineProps<{ submitLabel: string; submitting: boolean; errorMessage?: string | null }>()
const emit = defineEmits<{ submit: [] }>()
function addEntry() {
entries.value.push({ key: '', value: '' })
}
function removeEntry(index: number) {
entries.value.splice(index, 1)
}
</script>
<template>
<form class="space-y-4" @submit.prevent="emit('submit')">
<div>
<label class="mb-2 block font-sans text-xs font-bold tracking-[0.15em] text-paper-dim">NAME</label>
<input
v-model="name"
type="text"
required
class="w-full rounded border border-hairline bg-ink px-3 py-2 font-mono text-sm text-paper outline-none transition-colors focus:border-brass/60"
/>
</div>
<div>
<label class="mb-2 block font-sans text-xs font-bold tracking-[0.15em] text-paper-dim">NAMESPACES</label>
<NamespacePicker v-model="namespaces" />
</div>
<div>
<label class="mb-2 block font-sans text-xs font-bold tracking-[0.15em] text-paper-dim">TYPE</label>
<select
v-model="type"
class="w-full rounded border border-hairline bg-ink px-3 py-2 font-mono text-sm text-paper outline-none transition-colors focus:border-brass/60"
>
<option v-for="secretType in SECRET_TYPES" :key="secretType" :value="secretType">{{ secretType }}</option>
</select>
</div>
<div>
<label class="mb-2 block font-sans text-xs font-bold tracking-[0.15em] text-paper-dim">ENTRIES</label>
<div class="space-y-2">
<div v-for="(entry, index) in entries" :key="index" class="flex items-start gap-2">
<input
v-model="entry.key"
type="text"
placeholder="Key"
class="w-1/3 rounded border border-hairline bg-ink px-3 py-2 font-mono text-sm text-paper outline-none transition-colors placeholder:text-paper-dim/60 focus:border-brass/60"
@keydown.enter.prevent
/>
<textarea
v-model="entry.value"
placeholder="Value"
rows="1"
class="flex-1 resize-y rounded border border-hairline bg-ink px-3 py-2 font-mono text-sm text-paper outline-none transition-colors placeholder:text-paper-dim/60 focus:border-brass/60"
/>
<button
type="button"
class="flex h-9 w-9 shrink-0 items-center justify-center rounded text-paper-dim transition-colors hover:bg-panel-2 hover:text-rust"
@click="removeEntry(index)"
>
<span class="material-symbols-outlined text-[1em] leading-none" style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20">
close
</span>
</button>
</div>
</div>
<button
type="button"
class="mt-2 flex items-center gap-1 text-xs font-semibold text-verdigris transition-colors hover:text-brass"
@click="addEntry"
>
<span class="material-symbols-outlined text-[1em] leading-none" style="font-variation-settings: 'FILL' 0, 'wght' 500, 'GRAD' 0, 'opsz' 20">
add
</span>
Entry hinzufügen
</button>
</div>
<p v-if="errorMessage" class="text-sm text-rust">{{ errorMessage }}</p>
<button
type="submit"
:disabled="submitting"
class="w-full rounded bg-brass py-2.5 text-sm font-bold tracking-[0.08em] text-ink transition-colors hover:bg-brass-bright active:scale-[0.98] disabled:opacity-50 disabled:active:scale-100"
>
{{ submitLabel.toUpperCase() }}
</button>
</form>
</template>
+25
View File
@@ -0,0 +1,25 @@
<script setup lang="ts">
import type { Secret } from '../types/Secret'
import SecretCard from './SecretCard.vue'
defineProps<{ secrets: Secret[] }>()
const emit = defineEmits<{ deleted: []; updated: [] }>()
</script>
<template>
<div v-if="secrets.length" class="space-y-2">
<SecretCard
v-for="secret in secrets"
:key="secret.id"
:secret="secret"
@deleted="emit('deleted')"
@updated="emit('updated')"
/>
</div>
<div v-else class="flex flex-col items-center gap-2 rounded border border-dashed border-hairline py-16 text-paper-dim">
<span class="material-symbols-outlined text-[32px]" style="font-variation-settings: 'FILL' 0, 'wght' 300, 'GRAD' 0, 'opsz' 40">
search_off
</span>
<p class="text-sm font-bold tracking-[0.1em]">DER TRESOR IST LEER</p>
</div>
</template>
+29
View File
@@ -0,0 +1,29 @@
import { shallowRef, type Component } from 'vue'
const component = shallowRef<Component | undefined>(undefined)
let payload: unknown = undefined
function disableScrolling() {
document.body.style.overflow = 'hidden'
}
function enableScrolling() {
document.body.style.overflow = 'visible'
}
export function usePopup() {
return {
get: () => component.value,
data: <T>() => payload as T,
open(newComponent: Component, newPayload?: unknown) {
component.value = newComponent
payload = newPayload
disableScrolling()
},
close() {
component.value = undefined
payload = undefined
enableScrolling()
},
}
}
@@ -0,0 +1,65 @@
<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
import { usePopup } from './Popup'
defineProps<{
heading: string
size?: 'sm' | 'md'
}>()
function onKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
usePopup().close()
}
}
onMounted(() => document.addEventListener('keydown', onKeydown))
onUnmounted(() => document.removeEventListener('keydown', onKeydown))
</script>
<template>
<Transition
enter-active-class="transition duration-150 ease-out"
enter-from-class="opacity-0"
enter-to-class="opacity-100"
leave-active-class="transition duration-100 ease-in"
leave-from-class="opacity-100"
leave-to-class="opacity-0"
appear
>
<div
class="fixed inset-0 z-50 flex items-center justify-center bg-ink/80 p-4"
@click="usePopup().close()"
>
<Transition
enter-active-class="transition duration-150 ease-out"
enter-from-class="opacity-0 scale-95"
enter-to-class="opacity-100 scale-100"
leave-active-class="transition duration-100 ease-in"
leave-from-class="opacity-100 scale-100"
leave-to-class="opacity-0 scale-95"
appear
>
<div
class="w-full rounded border border-hairline bg-panel p-5"
:class="size === 'sm' ? 'max-w-sm' : 'max-w-3xl'"
@click.stop
>
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-bold tracking-[0.04em] text-paper">{{ heading.toUpperCase() }}</h2>
<button
type="button"
class="flex h-7 w-7 items-center justify-center rounded text-paper-dim transition-colors hover:bg-panel-2 hover:text-paper"
@click="usePopup().close()"
>
<span class="material-symbols-outlined text-[1em] leading-none" style="font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20">
close
</span>
</button>
</div>
<slot />
</div>
</Transition>
</div>
</Transition>
</template>
@@ -0,0 +1,55 @@
import { ref, watch } from 'vue'
import { useIdle } from '@vueuse/core'
import { deriveKey } from '../crypto/secretCrypto'
const STORAGE_KEY = 'lockaway_master_password'
const IDLE_TIMEOUT_MS = 5 * 60 * 1000
const masterPassword = ref<string | null>(null)
const derivedKey = ref<CryptoKey | null>(null)
const isRestoring = ref(true)
const { idle } = useIdle(IDLE_TIMEOUT_MS)
watch(idle, (isIdle) => {
if (isIdle && masterPassword.value) {
lock()
}
})
function setUnlocked(password: string): Promise<void> {
return deriveKey(password).then((key) => {
derivedKey.value = key
masterPassword.value = password
})
}
function lock() {
masterPassword.value = null
derivedKey.value = null
sessionStorage.removeItem(STORAGE_KEY)
}
function restore() {
const password = sessionStorage.getItem(STORAGE_KEY)
if (password) {
setUnlocked(password).then(() => {
isRestoring.value = false
})
} else {
isRestoring.value = false
}
}
restore()
export function useMasterPassword() {
function unlock(password: string): Promise<void> {
return setUnlocked(password).then(() => {
sessionStorage.setItem(STORAGE_KEY, password)
})
}
return { masterPassword, derivedKey, isRestoring, unlock, lock }
}
+24
View File
@@ -0,0 +1,24 @@
import { onMounted, ref, watch } from 'vue'
import { getSecrets } from '../api/secrets'
import type { Secret } from '../types/Secret'
export function useSecrets() {
const secrets = ref<Secret[]>([])
const searchText = ref('')
function load() {
getSecrets(searchText.value).then((result) => {
secrets.value = result
})
}
let debounceTimeout: ReturnType<typeof setTimeout>
watch(searchText, () => {
clearTimeout(debounceTimeout)
debounceTimeout = setTimeout(load, 250)
})
onMounted(load)
return { secrets, searchText, load }
}
@@ -0,0 +1,44 @@
import { ref } from 'vue'
import { getVerificationValue, setVerificationValue } from '../api/verification'
import { decryptValue, deriveKey, encryptValue } from '../crypto/secretCrypto'
const VERIFICATION_PLAINTEXT = 'lockaway-verification-v1'
const needsSetup = ref<boolean | null>(null)
const storedValue = ref<string | null>(null)
function load(): Promise<void> {
return getVerificationValue().then((value) => {
storedValue.value = value
needsSetup.value = value === null
})
}
load()
export function useVerification() {
function setup(password: string): Promise<void> {
return deriveKey(password)
.then((key) => encryptValue(key, VERIFICATION_PLAINTEXT))
.then((encrypted) =>
setVerificationValue(encrypted).then(() => {
storedValue.value = encrypted
needsSetup.value = false
}),
)
}
function verify(password: string): Promise<boolean> {
const value = storedValue.value
if (!value) {
return Promise.resolve(false)
}
return deriveKey(password)
.then((key) => decryptValue(key, value))
.then((plaintext) => plaintext === VERIFICATION_PLAINTEXT)
.catch(() => false)
}
return { needsSetup, setup, verify }
}
+40
View File
@@ -0,0 +1,40 @@
const HKDF_INFO = 'lockaway-secret-encryption-v1'
function hmacSha256(keyBytes: Uint8Array, data: Uint8Array): Promise<Uint8Array> {
return crypto.subtle
.importKey('raw', keyBytes as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
.then((key) => crypto.subtle.sign('HMAC', key, data as BufferSource))
.then((signature) => new Uint8Array(signature))
}
export function deriveKey(masterPassword: string): Promise<CryptoKey> {
const encoder = new TextEncoder()
const salt = new Uint8Array(32)
return hmacSha256(salt, encoder.encode(masterPassword))
.then((prk) => hmacSha256(prk, new Uint8Array([...encoder.encode(HKDF_INFO), 1])))
.then((okm) => crypto.subtle.importKey('raw', okm.slice(0, 32), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']))
}
export function decryptValue(key: CryptoKey, base64: string): Promise<string> {
const raw = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))
const iv = raw.slice(0, 12)
const ciphertext = raw.slice(12)
return crypto.subtle
.decrypt({ name: 'AES-GCM', iv, tagLength: 128 }, key, ciphertext)
.then((plaintext) => new TextDecoder().decode(plaintext))
}
export function encryptValue(key: CryptoKey, value: string): Promise<string> {
const iv = crypto.getRandomValues(new Uint8Array(12))
return crypto.subtle
.encrypt({ name: 'AES-GCM', iv, tagLength: 128 }, key, new TextEncoder().encode(value))
.then((ciphertext) => {
const raw = new Uint8Array(iv.length + ciphertext.byteLength)
raw.set(iv, 0)
raw.set(new Uint8Array(ciphertext), iv.length)
return btoa(String.fromCharCode(...raw))
})
}
+1
View File
@@ -0,0 +1 @@
declare module '@fontsource-variable/big-shoulders-display/wght'
+11
View File
@@ -0,0 +1,11 @@
import { createApp } from 'vue'
import '@fontsource-variable/mulish/index.css'
import '@fontsource-variable/big-shoulders-display/wght'
import '@fontsource/ibm-plex-mono/400.css'
import '@fontsource/ibm-plex-mono/500.css'
import '@fontsource/ibm-plex-mono/600.css'
import 'material-symbols/outlined.css'
import './style.css'
import App from './App.vue'
createApp(App).mount('#app')
+42
View File
@@ -0,0 +1,42 @@
@import "tailwindcss";
@theme {
--font-sans: 'Mulish Variable', sans-serif;
--font-display: 'Big Shoulders Display Variable', sans-serif;
--font-mono: 'IBM Plex Mono', monospace;
--color-ink: #12151a;
--color-panel: #1a1e25;
--color-panel-2: #22262e;
--color-hairline: #333944;
--color-paper: #e9e4d8;
--color-paper-dim: #c5ab87;
--color-brass: #c6a15b;
--color-brass-bright: #e0c07e;
--color-rust: #b5533c;
--color-verdigris: #6e9b8c;
}
@layer base {
html {
font-size: 16px;
color-scheme: dark;
}
body {
@apply font-sans text-[color:var(--color-paper)];
font-weight: 500;
min-height: 100vh;
background: var(--color-ink);
}
::selection {
background: var(--color-brass);
color: var(--color-ink);
}
:focus-visible {
outline: 1.5px solid color-mix(in srgb, var(--color-brass) 55%, transparent);
outline-offset: 2px;
}
}
+4
View File
@@ -0,0 +1,4 @@
export interface Entry {
key: string
value: string
}
+10
View File
@@ -0,0 +1,10 @@
import type { Entry } from './Entry'
export interface Secret {
id: string
name: string
namespaces: string[]
contentHash: string
entries: Entry[]
type: string
}
+15
View File
@@ -0,0 +1,15 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+19
View File
@@ -0,0 +1,19 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import tailwindcss from '@tailwindcss/vite'
const backendUrl = process.env.BACKEND_URL ?? 'http://localhost:8080'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue(), tailwindcss()],
server: {
proxy: {
'/api': {
target: backendUrl,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
})
+4
View File
@@ -0,0 +1,4 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
distributionSha256Sum=5af3b743dd8b876b5c45da33b676251e5f1687712644abb4ee519ca56e1d89ce
Vendored Executable
+295
View File
@@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
+189
View File
@@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
DEV_TAG=2
IMAGE="harbor.dinauer.dev/lockaway/reconciler:dev-${DEV_TAG}"
echo "==> Building Quarkus application"
./mvnw clean package
echo "==> Building Docker image ${IMAGE}"
docker build --no-cache -t "${IMAGE}" -f src/main/docker/Dockerfile.jvm .
echo "==> Pushing image to Harbor"
if [[ -n "${HARBOR_USERNAME:-}" && -n "${HARBOR_PASSWORD:-}" ]]; then
echo "${HARBOR_PASSWORD}" | docker login harbor.dinauer.dev -u "${HARBOR_USERNAME}" --password-stdin
docker push "${IMAGE}"
docker logout harbor.dinauer.dev
else
docker push "${IMAGE}"
fi
echo "==> Removing local image"
docker image rm --force "${IMAGE}"
echo "==> Done: ${IMAGE}"
+108
View File
@@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>dev.dinauer.lockaway</groupId>
<artifactId>reconciler</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<compiler-plugin.version>3.15.0</compiler-plugin.version>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id>
<quarkus.platform.group-id>io.quarkus.platform</quarkus.platform.group-id>
<quarkus.platform.version>3.37.3</quarkus.platform.version>
<skipITs>true</skipITs>
<surefire-plugin.version>3.5.6</surefire-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>${quarkus.platform.artifact-id}</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-kubernetes-client</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-scheduler</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-arc</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.platform.version}</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>build</goal>
<goal>generate-code</goal>
<goal>generate-code-tests</goal>
<goal>native-image-agent</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<properties>
<skipITs>false</skipITs>
<quarkus.native.enabled>true</quarkus.native.enabled>
</properties>
</profile>
</profiles>
</project>
+100
View File
@@ -0,0 +1,100 @@
####
# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode
#
# Before building the container image run:
#
# ./mvnw package
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/reconciler-jvm .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/reconciler-jvm
#
# If you want to include the debug port into your docker image
# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005.
# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005
# when running the container
#
# Then run the container using :
#
# docker run -i --rm -p 8080:8080 quarkus/reconciler-jvm
#
# This image uses the `run-java.sh` script to run the application.
# This scripts computes the command line to execute your Java application, and
# includes memory/GC tuning.
# You can configure the behavior using the following environment properties:
# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") - Be aware that this will override
# the default JVM options, use `JAVA_OPTS_APPEND` to append options
# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options
# in JAVA_OPTS (example: "-Dsome.property=foo")
# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is
# used to calculate a default maximal heap memory based on a containers restriction.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio
# of the container available memory as set here. The default is `50` which means 50%
# of the available memory is used as an upper boundary. You can skip this mechanism by
# setting this value to `0` in which case no `-Xmx` option is added.
# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This
# is used to calculate a default initial heap memory based on the maximum heap memory.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio
# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx`
# is used as the initial heap size. You can skip this mechanism by setting this value
# to `0` in which case no `-Xms` option is added (example: "25")
# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS.
# This is used to calculate the maximum value of the initial heap memory. If used in
# a container without any memory constraints for the container then this option has
# no effect. If there is a memory constraint then `-Xms` is limited to the value set
# here. The default is 4096MB which means the calculated value of `-Xms` never will
# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096")
# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output
# when things are happening. This option, if set to true, will set
# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true").
# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example:
# true").
# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787").
# - CONTAINER_CORE_LIMIT: A calculated core limit as described in
# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2")
# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024").
# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion.
# (example: "20")
# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking.
# (example: "40")
# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection.
# (example: "4")
# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus
# previous GC times. (example: "90")
# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20")
# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100")
# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should
# contain the necessary JRE command-line options to specify the required GC, which
# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC).
# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080")
# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080")
# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be
# accessed directly. (example: "foo.example.com,bar.example.com")
#
# You can find more information about the UBI base runtime images and their configuration here:
# https://rh-openjdk.github.io/redhat-openjdk-containers/
###
FROM registry.access.redhat.com/ubi8/openjdk-21:1.23
ENV LANGUAGE='en_US:en'
# We make four distinct layers so if there are application changes the library layers can be re-used
COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/
COPY --chown=185 target/quarkus-app/*.jar /deployments/
COPY --chown=185 target/quarkus-app/app/ /deployments/app/
COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/
EXPOSE 8080
USER 185
ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
ENV JAVA_APP_JAR="/deployments/quarkus-run.jar"
ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ]
@@ -0,0 +1,17 @@
package dev.dinauer.lockaway.reconciler;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.util.List;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
@RegisterRestClient(configKey = "backend-api")
@Path("/secrets")
public interface BackendClient
{
@GET
@Produces(MediaType.APPLICATION_JSON)
List<LockawaySecret> get();
}
@@ -0,0 +1,17 @@
package dev.dinauer.lockaway.reconciler;
import io.fabric8.kubernetes.client.KubernetesClient;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@ApplicationScoped
public class KubernetesNamespaceService
{
@Inject
KubernetesClient kubernetesClient;
public boolean exists(String name)
{
return kubernetesClient.namespaces().withName(name).get() != null;
}
}
@@ -0,0 +1,107 @@
package dev.dinauer.lockaway.reconciler;
import dev.dinauer.lockaway.reconciler.crypto.DecryptionService;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
@ApplicationScoped
public class KubernetesSecretService
{
public static final String LABEL_SECRET_NAME = "lockaway.dev/secret-name";
private static final String ANNOTATION_CONTENT_HASH = "lockaway.dev/content-hash";
private static final String FIELD_MANAGER = "lockaway-reconciler";
@Inject
KubernetesClient kubernetesClient;
@Inject
DecryptionService decryptionService;
public List<Secret> get()
{
return kubernetesClient.secrets().inAnyNamespace().withLabel(LABEL_SECRET_NAME).list().getItems();
}
public void apply(LockawayNamespaceSecret lockawayNamespaceSecret, String contentHash) throws UnmanagedSecretException
{
LockawaySecret lockawaySecret = lockawayNamespaceSecret.lockawaySecret();
String namespace = lockawayNamespaceSecret.namespace();
String name = lockawaySecret.name();
String type = lockawaySecret.type();
Map<String, String> stringData = lockawaySecret.entries()
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> decryptionService.decrypt(e.getValue())));
Secret existing = kubernetesClient.secrets().inNamespace(namespace).withName(name).get();
if (Objects.nonNull(existing))
{
if (isUnmanaged(existing))
{
throw new UnmanagedSecretException(namespace, name);
}
if (isDifferentType(existing, lockawayNamespaceSecret))
{
kubernetesClient.secrets().inNamespace(namespace).withName(name).delete();
}
}
Secret desired = new SecretBuilder()
.withNewMetadata()
.withName(name)
.withNamespace(namespace)
.addToLabels(LABEL_SECRET_NAME, name)
.addToAnnotations(ANNOTATION_CONTENT_HASH, contentHash)
.endMetadata()
.withType(type)
.withStringData(stringData)
.build();
kubernetesClient.secrets().inNamespace(namespace).resource(desired)
.fieldManager(FIELD_MANAGER)
.forceConflicts()
.serverSideApply();
}
public void remove(String namespace, String name) throws UnmanagedSecretException
{
Secret existing = kubernetesClient.secrets().inNamespace(namespace).withName(name).get();
if (Objects.nonNull(existing))
{
if (isUnmanaged(existing))
{
throw new UnmanagedSecretException(namespace, name);
}
kubernetesClient.secrets().inNamespace(namespace).withName(name).delete();
}
}
private boolean isUnmanaged(Secret secret)
{
if (Objects.isNull(secret.getMetadata().getLabels()))
{
return true;
}
return !secret.getMetadata().getLabels().containsKey(LABEL_SECRET_NAME);
}
private boolean isDifferentType(Secret existing, LockawayNamespaceSecret desired)
{
return !existing.getType().equalsIgnoreCase(desired.lockawaySecret().type());
}
public boolean contentHashMatches(Secret existing, String contentHash)
{
return existing.getMetadata().getAnnotations() != null && contentHash.equals(existing.getMetadata().getAnnotations().get(ANNOTATION_CONTENT_HASH));
}
}
@@ -0,0 +1,5 @@
package dev.dinauer.lockaway.reconciler;
public record LockawayNamespaceSecret(String namespace, LockawaySecret lockawaySecret)
{
}
@@ -0,0 +1,8 @@
package dev.dinauer.lockaway.reconciler;
import java.util.List;
import java.util.Map;
public record LockawaySecret(String name, List<String> namespaces, String contentHash, Map<String, String> entries, String type)
{
}
@@ -0,0 +1,145 @@
package dev.dinauer.lockaway.reconciler;
import io.fabric8.kubernetes.api.model.Secret;
import io.quarkus.scheduler.Scheduled;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.*;
import java.util.stream.Collectors;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ApplicationScoped
public class Reconciler
{
private static final Logger LOG = LoggerFactory.getLogger(Reconciler.class);
@Inject
@RestClient
BackendClient backendClient;
@Inject
KubernetesSecretService kubernetesSecretService;
@Inject
KubernetesNamespaceService kubernetesNamespaceService;
@Scheduled(every = "60s")
void reconcile()
{
List<LockawayNamespaceSecret> desired = resolve(backendClient.get());
List<Secret> existing = kubernetesSecretService.get();
create(desired, existing);
update(desired, existing);
prune(desired, existing);
}
private void create(List<LockawayNamespaceSecret> desired, List<Secret> existing)
{
Set<SecretKey> existingKeys = existing.stream().map(Reconciler::keyOf).collect(Collectors.toSet());
for (LockawayNamespaceSecret lockawayNamespaceSecret : desired)
{
if (!existingKeys.contains(keyOf(lockawayNamespaceSecret)))
{
if (kubernetesNamespaceService.exists(lockawayNamespaceSecret.namespace()))
{
try
{
kubernetesSecretService.apply(lockawayNamespaceSecret, lockawayNamespaceSecret.lockawaySecret().contentHash());
LOG.info("[CREATE] {}/{}", lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name());
}
catch (Exception e)
{
LOG.error("Failed to create secret {}/{}: {}", lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name(), e.getMessage());
}
}
}
}
}
private void update(List<LockawayNamespaceSecret> desired, List<Secret> existing)
{
Map<SecretKey, Secret> existingByKey = existing.stream().collect(Collectors.toMap(Reconciler::keyOf, s -> s));
for (LockawayNamespaceSecret lockawayNamespaceSecret : desired)
{
Secret current = existingByKey.get(keyOf(lockawayNamespaceSecret));
if (current != null)
{
String contentHash = lockawayNamespaceSecret.lockawaySecret().contentHash();
if (!kubernetesSecretService.contentHashMatches(current, contentHash))
{
if (kubernetesNamespaceService.exists(lockawayNamespaceSecret.namespace()))
{
try
{
kubernetesSecretService.apply(lockawayNamespaceSecret, contentHash);
LOG.info("[UPDATE] {}/{}", lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name());
}
catch (Exception e)
{
LOG.error("Failed to update secret {}/{}: {}", lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name(), e.getMessage());
}
}
}
}
}
}
private void prune(List<LockawayNamespaceSecret> desired, List<Secret> existing)
{
Set<SecretKey> desiredKeys = desired.stream().map(Reconciler::keyOf).collect(Collectors.toSet());
for (Secret secret : existing)
{
if (!desiredKeys.contains(keyOf(secret)))
{
if (kubernetesNamespaceService.exists(secret.getMetadata().getNamespace()))
{
try
{
kubernetesSecretService.remove(secret.getMetadata().getNamespace(), secret.getMetadata().getName());
LOG.info("[REMOVE] {}/{}", secret.getMetadata().getNamespace(), secret.getMetadata().getName());
}
catch (Exception e)
{
LOG.error("Failed to remove secret {}/{}: {}", secret.getMetadata().getNamespace(), secret.getMetadata().getName(), e.getMessage());
}
}
}
}
}
private List<LockawayNamespaceSecret> resolve(List<LockawaySecret> lockawaySecrets)
{
List<LockawayNamespaceSecret> lockawayNamespaceSecrets = new ArrayList<>();
for (LockawaySecret lockawaySecret : lockawaySecrets)
{
for (String namespace : lockawaySecret.namespaces())
{
lockawayNamespaceSecrets.add(new LockawayNamespaceSecret(namespace, lockawaySecret));
}
}
return lockawayNamespaceSecrets;
}
private static SecretKey keyOf(LockawayNamespaceSecret lockawayNamespaceSecret)
{
return new SecretKey(lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name());
}
private static SecretKey keyOf(Secret secret)
{
return new SecretKey(secret.getMetadata().getNamespace(),
secret.getMetadata().getLabels().get(KubernetesSecretService.LABEL_SECRET_NAME));
}
private record SecretKey(String namespace, String name)
{
}
}
@@ -0,0 +1,9 @@
package dev.dinauer.lockaway.reconciler;
public class UnmanagedSecretException extends Exception
{
public UnmanagedSecretException(String namespace, String name)
{
super(String.format("Found unmanaged secret %s/%s", namespace, name));
}
}
@@ -0,0 +1,41 @@
package dev.dinauer.lockaway.reconciler.crypto;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
@ApplicationScoped
public class DecryptionService
{
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final int IV_LENGTH_BYTES = 12;
private static final int TAG_LENGTH_BITS = 128;
@Inject
MasterKeyProvider masterKeyProvider;
public String decrypt(String encoded)
{
try
{
byte[] data = Base64.getDecoder().decode(encoded);
byte[] iv = Arrays.copyOfRange(data, 0, IV_LENGTH_BYTES);
byte[] ciphertext = Arrays.copyOfRange(data, IV_LENGTH_BYTES, data.length);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, masterKeyProvider.getKey(), new GCMParameterSpec(TAG_LENGTH_BITS, iv));
byte[] plaintext = cipher.doFinal(ciphertext);
return new String(plaintext, StandardCharsets.UTF_8);
}
catch (GeneralSecurityException e)
{
throw new IllegalStateException("Failed to decrypt value", e);
}
}
}
@@ -0,0 +1,61 @@
package dev.dinauer.lockaway.reconciler.crypto;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.eclipse.microprofile.config.inject.ConfigProperty;
@ApplicationScoped
public class MasterKeyProvider
{
private static final String HKDF_INFO = "lockaway-secret-encryption-v1";
private static final String HMAC_ALGORITHM = "HmacSHA256";
private static final int KEY_LENGTH_BYTES = 32;
private final SecretKeySpec derivedKey;
@Inject
public MasterKeyProvider(@ConfigProperty(name = "lockaway.master.key") String masterKey)
{
this.derivedKey = deriveKey(masterKey.getBytes(StandardCharsets.UTF_8));
}
public SecretKeySpec getKey()
{
return derivedKey;
}
private SecretKeySpec deriveKey(byte[] masterKeyBytes)
{
try
{
byte[] salt = new byte[32];
byte[] prk = hmac(salt, masterKeyBytes);
byte[] okm = hmac(prk, concat(HKDF_INFO.getBytes(StandardCharsets.UTF_8), new byte[] { 1 }));
return new SecretKeySpec(Arrays.copyOf(okm, KEY_LENGTH_BYTES), "AES");
}
catch (GeneralSecurityException e)
{
throw new IllegalStateException("Failed to derive encryption key.", e);
}
}
private byte[] hmac(byte[] key, byte[] data) throws GeneralSecurityException
{
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
mac.init(new SecretKeySpec(key, HMAC_ALGORITHM));
return mac.doFinal(data);
}
private byte[] concat(byte[] a, byte[] b)
{
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
}
@@ -0,0 +1,2 @@
%dev.quarkus.rest-client.backend-api.url=http://localhost:8080
%dev.lockaway.master.key=testtest