Compare commits

...

10 Commits

Author SHA1 Message Date
9f364d2854
fix: signer
All checks were successful
continuous-integration/drone Build is passing
2024-12-29 19:27:29 +00:00
e9d88279cf
fix: build 2024-12-29 19:25:14 +00:00
f4227fa121
feat: edit ssh key 2024-12-29 19:15:04 +00:00
1510b16ceb
feat: show more VM info 2024-12-29 16:11:05 +00:00
fead7f1bff
fix: icons 2024-11-29 17:38:04 +00:00
658e4aa5f2
feat: start/stop vm 2024-11-29 17:34:02 +00:00
fc1962defc
feat: signup 2024-11-29 10:47:40 +00:00
12c3ddc31d
fix: expired link 2024-11-27 14:39:57 +00:00
e4f6863e21
feat: add nginx conf 2024-11-26 19:17:48 +00:00
8ee0748740
fix: undo const 2024-11-26 19:15:50 +00:00
31 changed files with 945 additions and 252 deletions

1
.env Normal file
View File

@ -0,0 +1 @@
VITE_API_URL="https://api.lnvps.net"

1
.env.development Normal file
View File

@ -0,0 +1 @@
VITE_API_URL="http://localhost:8000"

View File

@ -5,4 +5,5 @@ RUN yarn && yarn build
FROM nginx as runner
WORKDIR /usr/share/nginx/html
COPY --from=builder /src/dist .
COPY --from=builder /src/dist .
COPY nginx.conf /etc/nginx/conf.d/default.conf

10
nginx.conf Normal file
View File

@ -0,0 +1,10 @@
server {
listen 80 default_server;
server_name _;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html =404;
}
}

View File

@ -12,8 +12,12 @@
"dependencies": {
"@scure/base": "^1.2.1",
"@snort/shared": "^1.0.17",
"@snort/system": "^1.5.7",
"@snort/system-react": "^1.5.7",
"@snort/system": "^1.6.1",
"@snort/system-react": "^1.6.1",
"@xterm/addon-attach": "^0.11.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"classnames": "^2.5.1",
"qr-code-styling": "^1.8.4",
"react": "^18.3.1",

View File

@ -16,5 +16,10 @@
<path d="M24 0V24H0V0H24Z" fill="white" fill-opacity="0.01"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.0589 19.2443C12.8824 20.0009 15.764 19.0421 17.5934 16.9994C18.146 16.3822 19.0943 16.33 19.7115 16.8826C20.3286 17.4353 20.3808 18.3836 19.8282 19.0008C17.2737 21.8532 13.2404 23.2026 9.28249 22.1421C3.6811 20.6412 0.35698 14.8837 1.85787 9.2823C3.35876 3.68091 9.1163 0.356795 14.7177 1.85768C18.9224 2.98433 21.8407 6.50832 22.4032 10.5596C22.4653 11.0066 22.4987 11.4603 22.502 11.9179C22.5117 13.2319 21.0529 13.9572 20.01 13.2545L17.3364 11.4531C15.8701 10.4651 16.8533 8.17943 18.579 8.56459L18.6789 8.58688C17.7458 6.76269 16.0738 5.32688 13.9412 4.75546C9.94024 3.6834 5.82771 6.05777 4.75565 10.0588C3.68358 14.0598 6.05795 18.1723 10.0589 19.2443Z" fill="#F7F9FC"/>
</svg>
<svg id="pencil" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M24 0V24H0V0H24Z" fill="white" fill-opacity="0.01"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M20.1315 3.16087C18.9599 1.9893 17.0604 1.9893 15.8888 3.16087L15.1817 3.86798L20.1315 8.81773L20.8386 8.11062C22.0101 6.93905 22.0101 5.03955 20.8386 3.86798L20.1315 3.16087ZM18.7172 10.2319L13.7675 5.28219L4.6765 14.3732C4.47771 14.572 4.33879 14.8226 4.27557 15.0966L3.24752 19.5515C3.08116 20.2723 3.72726 20.9182 4.44797 20.7519L8.90288 19.7239C9.17681 19.6606 9.42746 19.5217 9.62625 19.3229L18.7172 10.2319Z" fill="#F7F9FC"/>
</svg>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

View File

@ -73,6 +73,7 @@ export interface VmInstance {
disk_size: number;
disk_id: number;
status?: VmStatus;
mac_address: string;
template?: VmTemplate;
image?: VmOsImage;
@ -102,11 +103,15 @@ export interface VmPayment {
is_paid: boolean;
}
export interface PathVm {
ssh_key_id?: number;
}
export class LNVpsApi {
constructor(
readonly url: string,
readonly publisher: EventPublisher | undefined,
) { }
) {}
async listVms() {
const { data } = await this.#handleResponse<ApiResponse<Array<VmInstance>>>(
@ -122,6 +127,27 @@ export class LNVpsApi {
return data;
}
async patchVm(id: number, req: PathVm) {
const { data } = await this.#handleResponse<ApiResponse<void>>(
await this.#req(`/api/v1/vm/${id}`, "PATCH", req),
);
return data;
}
async startVm(id: number) {
const { data } = await this.#handleResponse<ApiResponse<VmInstance>>(
await this.#req(`/api/v1/vm/${id}/start`, "PATCH"),
);
return data;
}
async stopVm(id: number) {
const { data } = await this.#handleResponse<ApiResponse<VmInstance>>(
await this.#req(`/api/v1/vm/${id}/stop`, "PATCH"),
);
return data;
}
async listOffers() {
const { data } = await this.#handleResponse<ApiResponse<Array<VmTemplate>>>(
await this.#req("/api/v1/vm/templates", "GET"),
@ -178,6 +204,24 @@ export class LNVpsApi {
return data;
}
async connect_terminal(id: number) {
const u = `${this.url}/api/v1/console/${id}`;
const auth = await this.#auth_event(u, "GET");
const ws = new WebSocket(
`${u}?auth=${base64.encode(
new TextEncoder().encode(JSON.stringify(auth)),
)}`,
);
return await new Promise<WebSocket>((resolve, reject) => {
ws.onopen = () => {
resolve(ws);
};
ws.onerror = (e) => {
reject(e);
};
});
}
async #handleResponse<T extends ApiResponseBase>(rsp: Response) {
if (rsp.ok) {
return (await rsp.json()) as T;
@ -192,21 +236,29 @@ export class LNVpsApi {
}
}
async #req(path: string, method: "GET" | "POST" | "DELETE", body?: object) {
const auth = async (url: string, method: string) => {
const auth = await this.publisher?.generic((eb) => {
return eb
.kind(EventKind.HttpAuthentication)
.tag(["u", url])
.tag(["method", method]);
});
if (auth) {
return `Nostr ${base64.encode(
new TextEncoder().encode(JSON.stringify(auth)),
)}`;
}
};
async #auth_event(url: string, method: string) {
return await this.publisher?.generic((eb) => {
return eb
.kind(EventKind.HttpAuthentication)
.tag(["u", url])
.tag(["method", method]);
});
}
async #auth(url: string, method: string) {
const auth = await this.#auth_event(url, method);
if (auth) {
return `Nostr ${base64.encode(
new TextEncoder().encode(JSON.stringify(auth)),
)}`;
}
}
async #req(
path: string,
method: "GET" | "POST" | "DELETE" | "PUT" | "PATCH",
body?: object,
) {
const u = `${this.url}${path}`;
return await fetch(u, {
method,
@ -214,7 +266,7 @@ export class LNVpsApi {
headers: {
accept: "application/json",
"content-type": "application/json",
authorization: (await auth(u, method)) ?? "",
authorization: (await this.#auth(u, method)) ?? "",
},
});
}

71
src/blossom.ts Normal file
View File

@ -0,0 +1,71 @@
import { base64, bytesToString } from "@scure/base";
import { throwIfOffline, unixNow } from "@snort/shared";
import { EventKind, EventPublisher } from "@snort/system";
export interface BlobDescriptor {
url?: string;
sha256: string;
size: number;
type?: string;
uploaded?: number;
}
export class Blossom {
constructor(
readonly url: string,
readonly publisher: EventPublisher,
) {
this.url = new URL(this.url).toString();
}
async upload(file: File) {
const hash = await window.crypto.subtle.digest(
"SHA-256",
await file.arrayBuffer(),
);
const tags = [["x", bytesToString("hex", new Uint8Array(hash))]];
const rsp = await this.#req("/upload", "PUT", file, tags);
if (rsp.ok) {
return (await rsp.json()) as BlobDescriptor;
} else {
const text = await rsp.text();
throw new Error(text);
}
}
async #req(
path: string,
method: "GET" | "POST" | "DELETE" | "PUT",
body?: BodyInit,
tags?: Array<Array<string>>,
) {
throwIfOffline();
const url = `${this.url}upload`;
const now = unixNow();
const auth = async (url: string, method: string) => {
const auth = await this.publisher.generic((eb) => {
eb.kind(24_242 as EventKind)
.tag(["u", url])
.tag(["method", method])
.tag(["t", path.slice(1)])
.tag(["expiration", (now + 10).toString()]);
tags?.forEach((t) => eb.tag(t));
return eb;
});
return `Nostr ${base64.encode(
new TextEncoder().encode(JSON.stringify(auth)),
)}`;
};
return await fetch(url, {
method,
body,
headers: {
accept: "application/json",
authorization: await auth(url, method),
},
});
}
}

View File

@ -1,18 +1,28 @@
import classNames from "classnames";
import { forwardRef, HTMLProps } from "react";
import { forwardRef, HTMLProps, useState } from "react";
import Spinner from "./spinner";
export type AsyncButtonProps = {
onClick?: (e: React.MouseEvent) => Promise<void> | void;
} & Omit<HTMLProps<HTMLButtonElement>, "type" | "ref" | "onClick">;
const AsyncButton = forwardRef<HTMLButtonElement, AsyncButtonProps>(
function AsyncButton({ className, ...props }, ref) {
function AsyncButton({ className, onClick, ...props }, ref) {
const [loading, setLoading] = useState(false);
const hasBg = className?.includes("bg-");
return (
<button
ref={ref}
onClick={async (e) => {
setLoading(true);
try {
await onClick?.(e);
} finally {
setLoading(false);
}
}}
className={classNames(
"py-1 px-2 rounded-xl font-medium",
"py-1 px-2 rounded-xl font-medium relative",
{
"bg-neutral-800 cursor-not-allowed text-neutral-500":
!hasBg && props.disabled === true,
@ -22,7 +32,17 @@ const AsyncButton = forwardRef<HTMLButtonElement, AsyncButtonProps>(
)}
{...props}
>
{props.children}
<span
style={{ visibility: loading ? "hidden" : "visible" }}
className="whitespace-nowrap items-center justify-center"
>
{props.children}
</span>
{loading && (
<span className="absolute w-full h-full top-0 left-0 flex items-center justify-center">
<Spinner />
</span>
)}
</button>
);
},

View File

@ -1,7 +1,6 @@
import classNames from "classnames";
import { MouseEventHandler } from "react";
import Icons from "../icons.svg?url";
type Props = {
name: string;
size?: number;
@ -11,13 +10,13 @@ type Props = {
export function Icon(props: Props) {
const size = props.size || 20;
const href = `${Icons}#${props.name}`;
const href = `/icons.svg#${props.name}`;
return (
<svg
width={size}
height={size}
className={props.className}
className={classNames(props.className, "cursor-pointer")}
onClick={props.onClick}
>
<use href={href} />

View File

@ -1,27 +1,24 @@
import { SnortContext } from "@snort/system-react";
import { useContext } from "react";
import { AsyncButton } from "./button";
import { loginNip7 } from "../login";
import useLogin from "../hooks/login";
import Profile from "./profile";
import { NostrLink } from "@snort/system";
import { Link } from "react-router-dom";
import { Link, useNavigate } from "react-router-dom";
export default function LoginButton() {
const system = useContext(SnortContext);
const login = useLogin();
const navigate = useNavigate();
return !login ? (
<AsyncButton
onClick={async () => {
await loginNip7(system);
navigate("/login");
}}
>
Sign In
</AsyncButton>
) : (
<Link to="/account">
<Profile link={NostrLink.publicKey(login.pubkey)} />
<Profile link={NostrLink.publicKey(login.publicKey)} />
</Link>
);
}

View File

@ -51,7 +51,7 @@ export default function Modal(props: ModalProps) {
className={
props.bodyClassName ??
classNames(
"relative bg-layer-1 p-8 transition max-xl:rounded-t-3xl xl:rounded-3xl max-xl:mt-auto xl:my-auto max-lg:w-full",
"relative bg-neutral-700 p-8 transition max-xl:rounded-t-3xl xl:rounded-3xl max-xl:mt-auto xl:my-auto max-lg:w-full",
{
"max-xl:-translate-y-[calc(100vh-100dvh)]": props.ready ?? true,
"max-xl:translate-y-[50vh]": !(props.ready ?? true),

View File

@ -4,6 +4,7 @@ import { useUserProfile } from "@snort/system-react";
export default function Profile({ link }: { link: NostrLink }) {
const profile = useUserProfile(link.id);
const name = profile?.display_name ?? profile?.name ?? "";
return (
<div className="flex gap-2 items-center">
<img
@ -11,9 +12,7 @@ export default function Profile({ link }: { link: NostrLink }) {
className="w-12 h-12 rounded-full bg-neutral-800 object-cover object-center"
/>
<div>
{profile?.display_name ??
profile?.name ??
hexToBech32("npub", link.id).slice(0, 12)}
{name.length > 0 ? name : hexToBech32("npub", link.id).slice(0, 12)}
</div>
</div>
);

View File

@ -0,0 +1,33 @@
.spinner_V8m1 {
transform-origin: center;
animation: spinner_zKoa 2s linear infinite;
}
.spinner_V8m1 circle {
stroke-linecap: round;
animation: spinner_YpZS 1.5s ease-in-out infinite;
}
@keyframes spinner_zKoa {
100% {
transform: rotate(360deg);
}
}
@keyframes spinner_YpZS {
0% {
stroke-dasharray: 0 150;
stroke-dashoffset: 0;
}
47.5% {
stroke-dasharray: 42 150;
stroke-dashoffset: -16;
}
95%,
100% {
stroke-dasharray: 42 150;
stroke-dashoffset: -59;
}
}

View File

@ -0,0 +1,23 @@
import "./spinner.css";
export interface IconProps {
className?: string;
width?: number;
height?: number;
}
const Spinner = (props: IconProps) => (
<svg
width="20"
height="20"
stroke="currentColor"
viewBox="0 0 20 20"
{...props}
>
<g className="spinner_V8m1">
<circle cx="10" cy="10" r="7.5" fill="none" strokeWidth="3"></circle>
</g>
</svg>
);
export default Spinner;

View File

@ -0,0 +1,97 @@
import { useEffect, useState } from "react";
import { UserSshKey } from "../api";
import useLogin from "../hooks/login";
import { AsyncButton } from "./button";
export default function SSHKeySelector({
selectedKey,
setSelectedKey,
}: {
selectedKey: UserSshKey["id"];
setSelectedKey: (k: UserSshKey["id"]) => void;
}) {
const login = useLogin();
const [newKey, setNewKey] = useState("");
const [newKeyError, setNewKeyError] = useState("");
const [newKeyName, setNewKeyName] = useState("");
const [showAddKey, setShowAddKey] = useState(false);
const [sshKeys, setSshKeys] = useState<Array<UserSshKey>>([]);
async function addNewKey() {
if (!login?.api) return;
setNewKeyError("");
try {
const nk = await login?.api.addSshKey(newKeyName, newKey);
setNewKey("");
setNewKeyName("");
setSelectedKey(nk.id);
setShowAddKey(false);
login?.api.listSshKeys().then((a) => setSshKeys(a));
} catch (e) {
if (e instanceof Error) {
setNewKeyError(e.message);
}
}
}
useEffect(() => {
if (!login?.api) return;
login?.api.listSshKeys().then((a) => {
setSshKeys(a);
if (a.length > 0) {
setSelectedKey(a[0].id);
} else {
setShowAddKey(true);
}
});
}, []);
return (
<div className="flex flex-col gap-2">
{sshKeys.length > 0 && (
<>
<b>Select SSH Key:</b>
<select
className="bg-neutral-900 p-2 rounded-xl"
value={selectedKey}
onChange={(e) => setSelectedKey(Number(e.target.value))}
>
{sshKeys.map((a) => (
<option value={a.id}>{a.name}</option>
))}
</select>
</>
)}
{!showAddKey && sshKeys.length > 0 && (
<AsyncButton onClick={() => setShowAddKey(true)}>
Add new SSH key
</AsyncButton>
)}
{(showAddKey || sshKeys.length === 0) && (
<>
<b>Add SSH Key:</b>
<textarea
rows={5}
placeholder="ssh-[rsa|ed25519] AA== id"
value={newKey}
onChange={(e) => setNewKey(e.target.value)}
/>
<input
type="text"
placeholder="Key name"
value={newKeyName}
onChange={(e) => setNewKeyName(e.target.value)}
/>
<AsyncButton
disabled={newKey.length < 10 || newKeyName.length < 2}
onClick={addNewKey}
>
Add Key
</AsyncButton>
{newKeyError && <b className="text-red-500">{newKeyError}</b>}
</>
)}
</div>
);
}

View File

@ -1,25 +1,43 @@
import { VmInstance } from "../api";
import useLogin from "../hooks/login";
import { Icon } from "./icon";
import { AsyncButton } from "./button";
export default function VmActions({ vm }: { vm: VmInstance }) {
export default function VmActions({
vm,
onReload,
}: {
vm: VmInstance;
onReload?: () => void;
}) {
const login = useLogin();
const state = vm.status?.state;
if (!state) return;
if (!login?.api) return;
return (
<div className="flex flex-col gap-1">
<div className="flex gap-2">
<Icon
name={state === "running" ? "stop" : "start"}
className="bg-neutral-700 p-2 rounded-lg hover:bg-neutral-600"
size={40}
onClick={e => {
<AsyncButton
onClick={async (e) => {
e.stopPropagation();
if (state === "running") {
await login?.api.stopVm(vm.id);
} else {
await login?.api.startVm(vm.id);
}
onReload?.();
}}
/>
<Icon
className="bg-neutral-700 hover:bg-neutral-600"
>
<Icon name={state === "running" ? "stop" : "start"} size={30} />
</AsyncButton>
{/*<Icon
name="delete"
className="bg-neutral-700 p-2 rounded-lg hover:bg-neutral-600"
size={40}
onClick={e => {
onClick={(e) => {
e.stopPropagation();
}}
/>
@ -27,10 +45,10 @@ export default function VmActions({ vm }: { vm: VmInstance }) {
name="refresh-1"
className="bg-neutral-700 p-2 rounded-lg hover:bg-neutral-600"
size={40}
onClick={e => {
onClick={(e) => {
e.stopPropagation();
}}
/>
/>*/}
</div>
</div>
);

View File

@ -4,16 +4,28 @@ import OsImageName from "./os-image-name";
import VpsResources from "./vps-resources";
import VmActions from "./vps-actions";
export default function VpsInstanceRow({ vm, actions }: { vm: VmInstance, actions?: boolean }) {
export default function VpsInstanceRow({
vm,
actions,
onReload,
}: {
vm: VmInstance;
actions?: boolean;
onReload?: () => void;
}) {
const expires = new Date(vm.expires);
const isExpired = expires <= new Date();
const navigate = useNavigate();
return (
<div className="flex justify-between items-center rounded-xl bg-neutral-900 px-3 py-2 cursor-pointer hover:bg-neutral-800"
onClick={() => navigate("/vm", {
state: vm
})}>
<div
className="flex justify-between items-center rounded-xl bg-neutral-900 px-3 py-2 cursor-pointer hover:bg-neutral-800"
onClick={() =>
navigate("/vm", {
state: vm,
})
}
>
<div className="flex flex-col gap-2">
<div>
<span className="text-sm text-neutral-400">#{vm.id}</span>
@ -26,7 +38,7 @@ export default function VpsInstanceRow({ vm, actions }: { vm: VmInstance, action
</div>
<VpsResources vm={vm} />
</div>
{(actions ?? true) && <div className="flex gap-2 items-center">
<div className="flex gap-2 items-center">
{isExpired && (
<>
<Link to="/vm/renew" className="text-red-500 text-sm" state={vm}>
@ -34,8 +46,10 @@ export default function VpsInstanceRow({ vm, actions }: { vm: VmInstance, action
</Link>
</>
)}
{!isExpired && <VmActions vm={vm} />}
</div>}
{!isExpired && (actions ?? true) && (
<VmActions vm={vm} onReload={onReload} />
)}
</div>
</div>
);
}

View File

@ -2,8 +2,6 @@ import { useEffect } from "react";
import { LNVpsApi, VmPayment } from "../api";
import QrCode from "./qr";
import useLogin from "../hooks/login";
import { ApiUrl } from "../const";
import { EventPublisher } from "@snort/system";
export default function VpsPayment({
payment,
@ -29,13 +27,10 @@ export default function VpsPayment({
}
useEffect(() => {
if (!login?.signer) return;
const api = new LNVpsApi(
ApiUrl,
new EventPublisher(login.signer, login.pubkey),
);
if (!login?.api) return;
const tx = setInterval(async () => {
if (await checkPayment(api)) {
if (await checkPayment(login.api)) {
clearInterval(tx);
}
}, 2_000);

View File

@ -12,8 +12,7 @@ export const GB = KB * 1000;
export const TB = GB * 1000;
export const PB = TB * 1000;
export const ApiUrl = "http://localhost:8000";
//export const ApiUrl = "https://api.lnvps.net";
export const ApiUrl = import.meta.env.VITE_API_URL;
export const NostrProfile = new NostrLink(
NostrPrefix.Profile,

View File

@ -1,9 +1,21 @@
import { useSyncExternalStore } from "react";
import { Login } from "../login";
import { useContext, useSyncExternalStore } from "react";
import { LoginState } from "../login";
import { SnortContext } from "@snort/system-react";
import { LNVpsApi } from "../api";
import { ApiUrl } from "../const";
export default function useLogin() {
return useSyncExternalStore(
(c) => Login.hook(c),
() => Login.snapshot(),
const session = useSyncExternalStore(
(c) => LoginState.hook(c),
() => LoginState.snapshot(),
);
const system = useContext(SnortContext);
return session
? {
type: session.type,
publicKey: session.publicKey,
system,
api: new LNVpsApi(ApiUrl, LoginState.getSigner()),
}
: undefined;
}

View File

@ -35,3 +35,9 @@ a:hover {
hr {
@apply border-neutral-800;
}
input,
textarea,
select {
@apply border-none rounded-xl bg-neutral-900 p-2;
}

View File

@ -1,38 +1,112 @@
import { ExternalStore } from "@snort/shared";
import {
EventSigner,
EventPublisher,
Nip46Signer,
Nip7Signer,
SystemInterface,
UserState,
PrivateKeySigner,
} from "@snort/system";
class LoginShell extends ExternalStore<UserState<void> | undefined> {
#state?: UserState<void>;
export interface LoginSession {
type: "nip7" | "nsec" | "nip46";
publicKey: string;
privateKey?: string;
bunker?: string;
}
class LoginStore extends ExternalStore<LoginSession | undefined> {
#session?: LoginSession;
#signer?: EventPublisher;
async login(signer: EventSigner, system: SystemInterface) {
if (this.#state !== undefined) {
throw new Error("Already logged in");
constructor() {
super();
const s = window.localStorage.getItem("session");
if (s) {
this.#session = JSON.parse(s);
// patch session
if (this.#session) {
this.#session.type ??= "nip7";
}
}
const pubkey = await signer.getPubKey();
this.#state = new UserState<void>(pubkey);
await this.#state.init(signer, system);
this.#state.on("change", () => this.notifyChange());
this.notifyChange();
}
takeSnapshot() {
return this.#state;
return this.#session ? { ...this.#session } : undefined;
}
logout() {
this.#session = undefined;
this.#signer = undefined;
this.#save();
}
login(pubkey: string, type: LoginSession["type"] = "nip7") {
this.#session = {
type: type ?? "nip7",
publicKey: pubkey,
};
this.#save();
}
loginPrivateKey(key: string) {
const s = new PrivateKeySigner(key);
this.#session = {
type: "nsec",
publicKey: s.getPubKey(),
privateKey: key,
};
this.#save();
}
loginBunker(url: string, localKey: string, remotePubkey: string) {
this.#session = {
type: "nip46",
publicKey: remotePubkey,
privateKey: localKey,
bunker: url,
};
this.#save();
}
getSigner() {
if (!this.#signer && this.#session) {
switch (this.#session.type) {
case "nsec":
this.#signer = new EventPublisher(
new PrivateKeySigner(this.#session.privateKey!),
this.#session.publicKey,
);
break;
case "nip46":
this.#signer = new EventPublisher(
new Nip46Signer(
this.#session.bunker!,
new PrivateKeySigner(this.#session.privateKey!),
),
this.#session.publicKey,
);
break;
case "nip7":
this.#signer = new EventPublisher(
new Nip7Signer(),
this.#session.publicKey,
);
break;
}
}
if (this.#signer) {
return this.#signer;
}
throw "Signer not setup!";
}
#save() {
if (this.#session) {
window.localStorage.setItem("session", JSON.stringify(this.#session));
} else {
window.localStorage.removeItem("session");
}
this.notifyChange();
}
}
export const Login = new LoginShell();
export async function loginNip7(system: SystemInterface) {
const signer = new Nip7Signer();
const pubkey = await signer.getPubKey();
if (pubkey) {
await Login.login(signer, system);
} else {
throw new Error("No nostr extension found");
}
}
export const LoginState = new LoginStore();

View File

@ -9,6 +9,7 @@ import HomePage from "./pages/home.tsx";
import OrderPage from "./pages/order.tsx";
import VmPage from "./pages/vm.tsx";
import AccountPage from "./pages/account.tsx";
import SignUpPage from "./pages/sign-up.tsx";
const system = new NostrSystem({
automaticOutboxModel: false,
@ -29,6 +30,10 @@ const router = createBrowserRouter([
path: "/",
element: <HomePage />,
},
{
path: "/login",
element: <SignUpPage />,
},
{
path: "/account",
element: <AccountPage />,

View File

@ -1,21 +1,22 @@
import { useEffect, useState } from "react";
import { LNVpsApi, VmInstance } from "../api";
import { VmInstance } from "../api";
import useLogin from "../hooks/login";
import { EventPublisher } from "@snort/system";
import { ApiUrl } from "../const";
import VpsInstanceRow from "../components/vps-instance";
export default function AccountPage() {
const login = useLogin();
const [vms, setVms] = useState<Array<VmInstance>>([]);
async function loadVms() {
if (!login?.api) return;
const vms = await login?.api.listVms();
setVms(vms);
}
useEffect(() => {
if (!login?.signer) return;
const api = new LNVpsApi(
ApiUrl,
new EventPublisher(login.signer, login.pubkey),
);
api.listVms().then(setVms);
loadVms();
const t = setInterval(() => loadVms(), 5_000);
return () => clearInterval(t);
}, [login]);
return (
@ -23,7 +24,7 @@ export default function AccountPage() {
<h3>My Resources</h3>
<div className="flex flex-col gap-2">
{vms.map((a) => (
<VpsInstanceRow key={a.id} vm={a} actions={false} />
<VpsInstanceRow key={a.id} vm={a} onReload={loadVms} />
))}
</div>
</>

View File

@ -34,7 +34,7 @@ export default function HomePage() {
<a target="_blank" href="http://speedtest.v0l.io">
Speedtest
</a>{" "}
| <a href="/public/lnvps.asc">PGP</a>
| <a href="/lnvps.asc">PGP</a>
</div>
</div>
</div>

View File

@ -1,79 +1,35 @@
import { useLocation, useNavigate } from "react-router-dom";
import { LNVpsApi, UserSshKey, VmOsImage, VmTemplate } from "../api";
import { VmOsImage, VmTemplate } from "../api";
import { useEffect, useState } from "react";
import CostLabel from "../components/cost";
import { ApiUrl } from "../const";
import { EventPublisher } from "@snort/system";
import useLogin from "../hooks/login";
import { AsyncButton } from "../components/button";
import classNames from "classnames";
import VpsResources from "../components/vps-resources";
import OsImageName from "../components/os-image-name";
import SSHKeySelector from "../components/ssh-keys";
export default function OrderPage() {
const { state } = useLocation();
const login = useLogin();
const navigate = useNavigate();
const template = state as VmTemplate | undefined;
const [newKey, setNewKey] = useState("");
const [newKeyError, setNewKeyError] = useState("");
const [newKeyName, setNewKeyName] = useState("");
const [useImage, setUseImage] = useState(-1);
const [useSshKey, setUseSshKey] = useState(-1);
const [showAddKey, setShowAddKey] = useState(false);
const [images, setImages] = useState<Array<VmOsImage>>([]);
const [sshKeys, setSshKeys] = useState<Array<UserSshKey>>([]);
const [orderError, setOrderError] = useState("");
useEffect(() => {
if (!login?.signer) return;
const api = new LNVpsApi(
ApiUrl,
new EventPublisher(login.signer, login.pubkey),
);
api.listOsImages().then((a) => setImages(a));
api.listSshKeys().then((a) => {
setSshKeys(a);
if (a.length > 0) {
setUseSshKey(a[0].id);
} else {
setShowAddKey(true);
}
});
if (!login?.api) return;
login.api.listOsImages().then((a) => setImages(a));
}, [login]);
async function addNewKey() {
if (!login?.signer) return;
setNewKeyError("");
const api = new LNVpsApi(
ApiUrl,
new EventPublisher(login.signer, login.pubkey),
);
try {
const nk = await api.addSshKey(newKeyName, newKey);
setNewKey("");
setNewKeyName("");
setUseSshKey(nk.id);
setShowAddKey(false);
api.listSshKeys().then((a) => setSshKeys(a));
} catch (e) {
if (e instanceof Error) {
setNewKeyError(e.message);
}
}
}
async function createOrder() {
if (!login?.signer || !template) return;
const api = new LNVpsApi(
ApiUrl,
new EventPublisher(login.signer, login.pubkey),
);
if (!login?.api || !template) return;
setOrderError("");
try {
const newVm = await api.orderVm(template.id, useImage, useSshKey);
const newVm = await login.api.orderVm(template.id, useImage, useSshKey);
navigate("/vm/renew", {
state: newVm,
});
@ -122,53 +78,7 @@ export default function OrderPage() {
))}
</div>
<hr />
<div className="flex flex-col gap-2">
{sshKeys.length > 0 && (
<>
<b>Select SSH Key:</b>
<select
className="bg-neutral-900 p-2 rounded-xl"
value={useSshKey}
onChange={(e) => setUseSshKey(Number(e.target.value))}
>
{sshKeys.map((a) => (
<option value={a.id}>{a.name}</option>
))}
</select>
</>
)}
{!showAddKey && sshKeys.length > 0 && (
<AsyncButton onClick={() => setShowAddKey(true)}>
Add new SSH key
</AsyncButton>
)}
{(showAddKey || sshKeys.length === 0) && (
<>
<b>Add SSH Key:</b>
<textarea
className="border-none rounded-xl bg-neutral-900 p-2"
rows={5}
placeholder="ssh-[rsa|ed25519] AA== id"
value={newKey}
onChange={(e) => setNewKey(e.target.value)}
/>
<input
type="text"
className="border-none rounded-xl bg-neutral-900 p-2"
placeholder="Key name"
value={newKeyName}
onChange={(e) => setNewKeyName(e.target.value)}
/>
<AsyncButton
disabled={newKey.length < 10 || newKeyName.length < 2}
onClick={addNewKey}
>
Add Key
</AsyncButton>
{newKeyError && <b className="text-red-500">{newKeyError}</b>}
</>
)}
</div>
<SSHKeySelector selectedKey={useSshKey} setSelectedKey={setUseSshKey} />
<AsyncButton
disabled={useSshKey === -1 || useImage === -1}
onClick={createOrder}

174
src/pages/sign-up.tsx Normal file
View File

@ -0,0 +1,174 @@
import {
EventPublisher,
Nip46Signer,
Nip7Signer,
PrivateKeySigner,
} from "@snort/system";
import { AsyncButton } from "../components/button";
import { useContext, useState } from "react";
import { bech32ToHex, hexToBech32 } from "@snort/shared";
import { openFile } from "../utils";
import { SnortContext } from "@snort/system-react";
import { Blossom } from "../blossom";
import { useNavigate } from "react-router-dom";
import { LoginState } from "../login";
export default function SignUpPage() {
const [name, setName] = useState("");
const [keyIn, setKeyIn] = useState("");
const [error, setError] = useState("");
const [file, setFile] = useState<File>();
const [key, setKey] = useState<PrivateKeySigner>();
const system = useContext(SnortContext);
const navigate = useNavigate();
async function uploadImage() {
const f = await openFile();
setFile(f);
}
async function spawnAccount() {
if (!key) return;
setError("");
const pub = new EventPublisher(key, key.getPubKey());
let pic = undefined;
if (file) {
// upload picture
const b = new Blossom("https://nostr.download", pub);
const up = await b.upload(file);
if (up.url) {
pic = up.url;
} else {
setError("Upload filed");
return;
}
}
const ev = await pub.metadata({
name: name,
picture: pic,
});
system.BroadcastEvent(ev);
LoginState.loginPrivateKey(key.privateKey);
navigate("/");
}
async function loginKey() {
setError("");
try {
if (keyIn.startsWith("nsec1")) {
LoginState.loginPrivateKey(bech32ToHex(keyIn));
navigate("/");
} else if (keyIn.startsWith("bunker://")) {
const signer = new Nip46Signer(keyIn);
await signer.init();
const pubkey = await signer.getPubKey();
LoginState.loginBunker(keyIn, signer.privateKey!, pubkey);
navigate("/");
}
} catch (e) {
if (e instanceof Error) {
setError(e.message);
}
}
}
return (
<div className="flex flex-col gap-4">
{error && <b className="text-red-500">{error}</b>}
<h1>Login</h1>
<input
type="text"
placeholder="nsec/bunker"
value={keyIn}
onChange={(e) => setKeyIn(e.target.value)}
/>
<AsyncButton
onClick={loginKey}
disabled={!keyIn.startsWith("nsec") && !keyIn.startsWith("bunker://")}
>
Login
</AsyncButton>
{window.nostr && (
<div className="flex flex-col gap-4">
Browser Extension:
<AsyncButton
onClick={async () => {
const pk = await new Nip7Signer().getPubKey();
LoginState.login(pk);
navigate("/");
}}
>
Nostr Extension
</AsyncButton>
</div>
)}
<div className="flex gap-4 items-center my-6">
<div className="text-xl">OR</div>
<div className="h-[1px] bg-neutral-800 w-full"></div>
</div>
<h1>Create Account</h1>
<p>
LNVPS uses nostr accounts,{" "}
<a
href="https://nostr.how/en/what-is-nostr"
target="_blank"
className="underline"
>
what is nostr?
</a>
</p>
<div className="flex flex-col gap-2">
<div>Avatar</div>
<div
className="w-40 h-40 bg-neutral-900 rounded-xl relative cursor-pointer overflow-hidden"
onClick={uploadImage}
>
<div className="absolute bg-black/50 w-full h-full hover:opacity-90 opacity-0 flex items-center justify-center">
Upload
</div>
{file && (
<img
src={URL.createObjectURL(file)}
className="w-full h-full object-cover"
/>
)}
</div>
</div>
<div className="flex flex-col gap-2">
<div>Name</div>
<div>
<input
type="text"
placeholder="Display name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
</div>
<AsyncButton
onClick={async () => {
setKey(PrivateKeySigner.random());
}}
>
Create Account
</AsyncButton>
{key && (
<>
<div className="flex flex-col gap-2">
<h3>Your new key:</h3>
<div className="font-monospace select-all">
{hexToBech32("nsec", key.privateKey)}
</div>
<b>Please save this key, it CANNOT be recovered</b>
</div>
<AsyncButton onClick={spawnAccount}>Login</AsyncButton>
</>
)}
</div>
);
}

View File

@ -1,13 +1,21 @@
import "@xterm/xterm/css/xterm.css";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { LNVpsApi, VmInstance, VmPayment } from "../api";
import { VmInstance, VmPayment } from "../api";
import VpsInstanceRow from "../components/vps-instance";
import useLogin from "../hooks/login";
import { ApiUrl } from "../const";
import { EventPublisher } from "@snort/system";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import VpsPayment from "../components/vps-payment";
import CostLabel from "../components/cost";
import { AsyncButton } from "../components/button";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import { toEui64 } from "../utils";
import { Icon } from "../components/icon";
import Modal from "../components/modal";
import SSHKeySelector from "../components/ssh-keys";
const fit = new FitAddon();
export default function VmPage() {
const { state } = useLocation() as { state?: VmInstance };
@ -15,20 +23,46 @@ export default function VmPage() {
const login = useLogin();
const navigate = useNavigate();
const [payment, setPayment] = useState<VmPayment>();
const [term] = useState<Terminal>();
const termRef = useRef<HTMLDivElement | null>(null);
const [editKey, setEditKey] = useState(false);
const [key, setKey] = useState(state?.ssh_key_id ?? -1);
const renew = useCallback(
async function () {
if (!login?.signer || !state) return;
const api = new LNVpsApi(
ApiUrl,
new EventPublisher(login.signer, login.pubkey),
);
const p = await api.renewVm(state.id);
if (!login?.api || !state) return;
const p = await login?.api.renewVm(state.id);
setPayment(p);
},
[login, state],
[login?.api, state],
);
/*async function openTerminal() {
if (!login?.api || !state) return;
const ws = await login.api.connect_terminal(state.id);
const te = new Terminal();
const webgl = new WebglAddon();
webgl.onContextLoss(() => {
webgl.dispose();
});
te.loadAddon(webgl);
te.loadAddon(fit);
te.onResize(({ cols, rows }) => {
ws.send(`${cols}:${rows}`);
});
const attach = new AttachAddon(ws);
te.loadAddon(attach);
setTerm(te);
}*/
useEffect(() => {
if (term && termRef.current) {
term.open(termRef.current);
term.focus();
fit.fit();
}
}, [termRef, term, fit]);
useEffect(() => {
switch (action) {
case "renew":
@ -41,24 +75,51 @@ export default function VmPage() {
}
return (
<div className="flex flex-col gap-4">
<VpsInstanceRow vm={state} actions={false} />
{action === undefined && <>
<div className="text-xl">Renewal</div>
<div className="flex justify-between items-center">
<div>{new Date(state.expires).toDateString()}</div>
{state.template?.cost_plan && <div><CostLabel cost={state.template?.cost_plan} /></div>}
</div>
<AsyncButton onClick={() => navigate("/vm/renew", { state })}>
Extend Now
</AsyncButton>
<div className="text-xl">Network</div>
<div className="flex gap-4">
{(state.ip_assignments?.length ?? 0) === 0 && <div className="text-sm text-red-500">No IP's assigned</div>}
{state.ip_assignments?.map(a => <div key={a.id} className="text-sm bg-neutral-900 px-3 py-1 rounded-lg">
{a.ip.split("/")[0]}
</div>)}
</div>
</>}
<VpsInstanceRow vm={state} actions={true} />
{action === undefined && (
<>
<div className="flex gap-4 items-center">
<div className="text-xl">Network:</div>
{(state.ip_assignments?.length ?? 0) === 0 && (
<div className="text-sm text-red-500">No IP's assigned</div>
)}
{state.ip_assignments?.map((a) => (
<div
key={a.id}
className="text-sm bg-neutral-900 px-3 py-1 rounded-lg"
>
{a.ip.split("/")[0]}
</div>
))}
<div className="text-sm bg-neutral-900 px-3 py-1 rounded-lg">
{toEui64("2a13:2c0::", state.mac_address)}
</div>
</div>
<div className="flex gap-4 items-center">
<div className="text-xl">SSH Key:</div>
<div className="text-sm bg-neutral-900 px-3 py-1 rounded-lg">
{state.ssh_key?.name}
</div>
<Icon name="pencil" onClick={() => setEditKey(true)} />
</div>
<hr />
<div className="text-xl">Renewal</div>
<div className="flex justify-between items-center">
<div>{new Date(state.expires).toDateString()}</div>
{state.template?.cost_plan && (
<div>
<CostLabel cost={state.template?.cost_plan} />
</div>
)}
</div>
<AsyncButton onClick={() => navigate("/vm/renew", { state })}>
Extend Now
</AsyncButton>
{/*
{!term && <AsyncButton onClick={openTerminal}>Connect Terminal</AsyncButton>}
{term && <div className="border p-2" ref={termRef}></div>}*/}
</>
)}
{action === "renew" && (
<>
<h3>Renew VPS</h3>
@ -66,12 +127,8 @@ export default function VmPage() {
<VpsPayment
payment={payment}
onPaid={async () => {
if (!login?.signer || !state) return;
const api = new LNVpsApi(
ApiUrl,
new EventPublisher(login.signer, login.pubkey),
);
const newState = await api.getVm(state.id);
if (!login?.api || !state) return;
const newState = await login?.api.getVm(state.id);
navigate("/vm", {
state: newState,
});
@ -81,6 +138,30 @@ export default function VmPage() {
)}
</>
)}
{editKey && (
<Modal id="edit-ssh-key" onClose={() => setEditKey(false)}>
<SSHKeySelector selectedKey={key} setSelectedKey={setKey} />
<div className="flex flex-col gap-4 mt-8">
<small>After selecting a new key, please restart the VM.</small>
<AsyncButton
onClick={async () => {
if (!login?.api) return;
await login.api.patchVm(state.id, {
ssh_key_id: key,
});
const ns = await login.api.getVm(state?.id);
navigate(".", {
state: ns,
replace: true,
});
setEditKey(false);
}}
>
Save
</AsyncButton>
</div>
</Modal>
)}
</div>
);
}

53
src/utils.ts Normal file
View File

@ -0,0 +1,53 @@
import { base16 } from "@scure/base";
export async function openFile(): Promise<File | undefined> {
return new Promise((resolve) => {
const elm = document.createElement("input");
let lock = false;
elm.type = "file";
const handleInput = (e: Event) => {
lock = true;
const elm = e.target as HTMLInputElement;
if ((elm.files?.length ?? 0) > 0) {
resolve(elm.files![0]);
} else {
resolve(undefined);
}
};
elm.onchange = (e) => handleInput(e);
elm.click();
window.addEventListener(
"focus",
() => {
setTimeout(() => {
if (!lock) {
resolve(undefined);
}
}, 300);
},
{ once: true },
);
});
}
export function toEui64(prefix: string, mac: string) {
const macData = base16.decode(mac.replace(/:/g, "").toUpperCase());
const macExtended = new Uint8Array([
...macData.subarray(0, 3),
0xff,
0xfe,
...macData.subarray(3, 6),
]);
macExtended[0] |= 0x02;
return (
prefix +
base16.encode(macExtended.subarray(0, 2)) +
":" +
base16.encode(macExtended.subarray(2, 4)) +
":" +
base16.encode(macExtended.subarray(4, 6)) +
":" +
base16.encode(macExtended.subarray(6, 8))
).toLowerCase();
}

View File

@ -758,20 +758,20 @@ __metadata:
languageName: node
linkType: hard
"@snort/system-react@npm:^1.5.7":
version: 1.5.7
resolution: "@snort/system-react@npm:1.5.7"
"@snort/system-react@npm:^1.6.1":
version: 1.6.1
resolution: "@snort/system-react@npm:1.6.1"
dependencies:
"@snort/shared": "npm:^1.0.17"
"@snort/system": "npm:^1.5.7"
"@snort/system": "npm:^1.6.1"
react: "npm:^18.2.0"
checksum: 10c0/b8261d72bef88fc6baa91f3f3765a7e65e7775e0f87142079ec425fdc3639871da068b2bfc9c4a2c0f15a20c7c76ffe84d9bc8cbc1e6ef5a76989cd78d3f7049
checksum: 10c0/fe3180c1f4341df4fd585c4031ef632a7d59c7637c6aed16ea254a1c22a66e288516d96939c0080efd0fb73940531855a59a24fae5f82c326f6544362eb0394c
languageName: node
linkType: hard
"@snort/system@npm:^1.5.7":
version: 1.5.7
resolution: "@snort/system@npm:1.5.7"
"@snort/system@npm:^1.6.1":
version: 1.6.1
resolution: "@snort/system@npm:1.6.1"
dependencies:
"@noble/ciphers": "npm:^0.6.0"
"@noble/curves": "npm:^1.4.0"
@ -786,7 +786,7 @@ __metadata:
nostr-social-graph: "npm:^1.0.3"
uuid: "npm:^9.0.0"
ws: "npm:^8.14.0"
checksum: 10c0/9b1d6e36dfc3c0845754d4f2c10eb39665a2c4c4c61a07635e0b792a352f8566dbd79561561568c182272cd92b0d2c421ef137775b16872b7e28fa39366e2094
checksum: 10c0/5da01450970f4a51df98369c4cdd2b8886add3480e7962d11ed17498cf7db421bcd5e585abe532ff754efc0bf26b5734b9b24005f958802357ec390ccb74d281
languageName: node
linkType: hard
@ -1046,6 +1046,40 @@ __metadata:
languageName: node
linkType: hard
"@xterm/addon-attach@npm:^0.11.0":
version: 0.11.0
resolution: "@xterm/addon-attach@npm:0.11.0"
peerDependencies:
"@xterm/xterm": ^5.0.0
checksum: 10c0/7646e4a4ec1588f922bfed81e0361db435e4db73656847eda1f5724f7580a522b0ad9b636c76ddb3fad785feb4c594cc813b7e7a990d780d2d7aa78c69ad092f
languageName: node
linkType: hard
"@xterm/addon-fit@npm:^0.10.0":
version: 0.10.0
resolution: "@xterm/addon-fit@npm:0.10.0"
peerDependencies:
"@xterm/xterm": ^5.0.0
checksum: 10c0/76926120fc940376afef2cb68b15aec2a99fc628b6e3cc84f2bcb1682ca9b87f982b3c10ff206faf4ebc5b410467b81a7b5e83be37b4ac386586f472e4fa1c61
languageName: node
linkType: hard
"@xterm/addon-webgl@npm:^0.18.0":
version: 0.18.0
resolution: "@xterm/addon-webgl@npm:0.18.0"
peerDependencies:
"@xterm/xterm": ^5.0.0
checksum: 10c0/682a3f5f128ee09a0cf1b41cbb7b2f925a5e43056e12ba0c523b93a1f5f188045caef9e31f32db933b8a7a1b12d8f9babaddfa11e6f11df0c7b265009103476c
languageName: node
linkType: hard
"@xterm/xterm@npm:^5.5.0":
version: 5.5.0
resolution: "@xterm/xterm@npm:5.5.0"
checksum: 10c0/358801feece58617d777b2783bec68dac1f52f736da3b0317f71a34f4e25431fb0b1920244f678b8d673f797145b4858c2a5ccb463a4a6df7c10c9093f1c9267
languageName: node
linkType: hard
"abbrev@npm:^2.0.0":
version: 2.0.0
resolution: "abbrev@npm:2.0.0"
@ -2345,11 +2379,15 @@ __metadata:
"@eslint/js": "npm:^9.8.0"
"@scure/base": "npm:^1.2.1"
"@snort/shared": "npm:^1.0.17"
"@snort/system": "npm:^1.5.7"
"@snort/system-react": "npm:^1.5.7"
"@snort/system": "npm:^1.6.1"
"@snort/system-react": "npm:^1.6.1"
"@types/react": "npm:^18.3.3"
"@types/react-dom": "npm:^18.3.0"
"@vitejs/plugin-react": "npm:^4.3.1"
"@xterm/addon-attach": "npm:^0.11.0"
"@xterm/addon-fit": "npm:^0.10.0"
"@xterm/addon-webgl": "npm:^0.18.0"
"@xterm/xterm": "npm:^5.5.0"
autoprefixer: "npm:^10.4.20"
classnames: "npm:^2.5.1"
eslint: "npm:^9.8.0"