Compare commits
18
Commits
58c37bf81b
...
6a3e0a29a4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a3e0a29a4 | ||
|
|
c19c11e6eb | ||
|
|
85f6d47024 | ||
|
|
4175608772 | ||
|
|
24060b2c5a | ||
|
|
cefbac625c | ||
|
|
73efb206ac | ||
|
|
7fea321376 | ||
|
|
b583e9803f | ||
|
|
92ac1eeb62 | ||
|
|
242a587340 | ||
|
|
7a8e683d99 | ||
|
|
3e447fd024 | ||
|
|
6953f5e972 | ||
|
|
55526263a0 | ||
|
|
4bb7400b8e | ||
|
|
79afcc2e16 | ||
|
|
8708bd9498 |
@@ -60,3 +60,13 @@ jobs:
|
||||
# Root context: admin depends on the shared module.
|
||||
docker build -t "$IMAGE" -f admin/Dockerfile .
|
||||
docker push "$IMAGE"
|
||||
|
||||
- name: Build and push adminsite image
|
||||
run: |
|
||||
IMAGE="${{ vars.DOCKER_HOST }}/${{ github.repository_owner }}/vantage/adminsite:latest"
|
||||
docker build \
|
||||
--build-arg NEXT_PUBLIC_ADMIN_API_URL="${{ vars.ADMIN_API_URL }}" \
|
||||
--build-arg NEXT_PUBLIC_ADMIN_ENV="${{ vars.ADMIN_ENV }}" \
|
||||
-t "$IMAGE" \
|
||||
-f adminsite/Dockerfile adminsite/
|
||||
docker push "$IMAGE"
|
||||
|
||||
@@ -37,6 +37,24 @@ func ownedInstance(c *gin.Context, instanceID string) (*models.Instance, bool) {
|
||||
return &inst, true
|
||||
}
|
||||
|
||||
// getMe reports who the caller is, for route guards in the UI.
|
||||
//
|
||||
// It is deliberately outside RequireCustomer/RequireStaff: the UI needs a
|
||||
// truthful 401 to redirect on, not an error page. It reveals nothing a caller
|
||||
// does not already possess, because it only ever describes their own cookie.
|
||||
func getMe(c *gin.Context) {
|
||||
s := auth.Load(c)
|
||||
if s == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "not signed in"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"kind": s.Kind,
|
||||
"email": s.Email,
|
||||
"account_id": s.AccountID,
|
||||
})
|
||||
}
|
||||
|
||||
func getAccount(c *gin.Context) {
|
||||
s := auth.Current(c)
|
||||
ctx := c.Request.Context()
|
||||
@@ -58,7 +76,13 @@ func getAccount(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"account": acct, "instances": instances})
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"account": acct,
|
||||
"instances": instances,
|
||||
// Sent rather than mirrored in the UI: a hardcoded 3 in TypeScript is a
|
||||
// second source of truth for a rule the backend enforces.
|
||||
"max_relinks": models.MaxRelinksPerTerm,
|
||||
})
|
||||
}
|
||||
|
||||
func linkInstance(c *gin.Context) {
|
||||
@@ -122,7 +146,15 @@ func getInstanceLicense(c *gin.Context) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "no licence issued yet"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, lic)
|
||||
// The owner gets the blob itself: it is signed public data bound to their
|
||||
// own instance, and the download endpoint hands over the same bytes. The
|
||||
// struct tag hides it, so the fields are listed explicitly.
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"license_id": lic.LicenseID, "instance_id": lic.InstanceID, "tier": lic.Tier,
|
||||
"deployment": lic.Deployment, "limits": lic.Limits, "features": lic.Features,
|
||||
"issued_at": lic.IssuedAt, "expires_at": lic.ExpiresAt, "reason": lic.Reason,
|
||||
"issued_by": lic.IssuedBy, "blob": lic.Blob,
|
||||
})
|
||||
}
|
||||
|
||||
func downloadInstanceLicense(c *gin.Context) {
|
||||
|
||||
@@ -30,6 +30,8 @@ func Routes(cfg config.Config) http.Handler {
|
||||
r.POST("/auth/login", auth.HandleCloudLogin) // falls through to customer login
|
||||
r.POST("/auth/logout", auth.HandleLogout)
|
||||
r.GET("/auth/verify", auth.HandleVerify)
|
||||
r.GET("/auth/me", getMe)
|
||||
r.POST("/auth/signup", auth.HandleSignup)
|
||||
|
||||
cust := r.Group("/api")
|
||||
cust.Use(auth.RequireCustomer())
|
||||
@@ -50,6 +52,8 @@ func Routes(cfg config.Config) http.Handler {
|
||||
staff.GET("/accounts/:id", staffGetAccount)
|
||||
staff.GET("/instances", staffListInstances)
|
||||
staff.POST("/instances", staffCreateInstance)
|
||||
staff.GET("/instances/:id", staffGetInstance)
|
||||
staff.GET("/subscriptions", staffListSubscriptions)
|
||||
staff.POST("/instances/:id/issue", staffIssue)
|
||||
staff.POST("/instances/:id/relink", staffRelink)
|
||||
staff.GET("/licenses", staffListLicenses)
|
||||
|
||||
+114
-5
@@ -21,10 +21,19 @@ import (
|
||||
func staffListAccounts(c *gin.Context) {
|
||||
filter := bson.M{}
|
||||
if q := c.Query("q"); q != "" {
|
||||
filter["$or"] = []bson.M{
|
||||
or := []bson.M{
|
||||
{"name": bson.M{"$regex": q, "$options": "i"}},
|
||||
{"billing_email": bson.M{"$regex": q, "$options": "i"}},
|
||||
{"paddle_customer_id": q},
|
||||
}
|
||||
// A support email often contains an instance UUID and nothing else, so
|
||||
// resolve that to its owning account rather than returning nothing.
|
||||
var inst models.Instance
|
||||
if err := db.Admin("admin_instances").FindOne(c.Request.Context(),
|
||||
bson.M{"instance_id": q}).Decode(&inst); err == nil {
|
||||
or = append(or, bson.M{"account_id": inst.AccountID})
|
||||
}
|
||||
filter["$or"] = or
|
||||
}
|
||||
cur, err := db.Admin("accounts").Find(c.Request.Context(), filter,
|
||||
options.Find().SetLimit(200).SetSort(bson.D{{Key: "created_at", Value: -1}}))
|
||||
@@ -70,12 +79,33 @@ func staffGetAccount(c *gin.Context) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
cur, _ := db.Admin("admin_instances").Find(ctx, bson.M{"account_id": acct.AccountID})
|
||||
instances := []models.Instance{}
|
||||
if cur != nil {
|
||||
if cur, err := db.Admin("admin_instances").Find(ctx, bson.M{"account_id": acct.AccountID}); err == nil {
|
||||
_ = cur.All(ctx, &instances)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"account": acct, "instances": instances})
|
||||
subs := []models.Subscription{}
|
||||
if cur, err := db.Admin("subscriptions").Find(ctx, bson.M{"account_id": acct.AccountID}); err == nil {
|
||||
_ = cur.All(ctx, &subs)
|
||||
}
|
||||
users := []models.CustomerUser{}
|
||||
if cur, err := db.Admin("customer_users").Find(ctx, bson.M{"account_id": acct.AccountID}); err == nil {
|
||||
_ = cur.All(ctx, &users)
|
||||
}
|
||||
entries := []models.AuditEntry{}
|
||||
if cur, err := db.Admin("admin_audit").Find(ctx, bson.M{"account_id": acct.AccountID},
|
||||
options.Find().SetLimit(100).SetSort(bson.D{{Key: "created_at", Value: -1}})); err == nil {
|
||||
_ = cur.All(ctx, &entries)
|
||||
}
|
||||
|
||||
// CustomerUser's password hash and both verify-token fields are json:"-",
|
||||
// so no secret leaves here.
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"account": acct,
|
||||
"instances": instances,
|
||||
"subscriptions": subs,
|
||||
"users": users,
|
||||
"audit": entries,
|
||||
})
|
||||
}
|
||||
|
||||
func staffListInstances(c *gin.Context) {
|
||||
@@ -185,6 +215,81 @@ func staffCreateInstance(c *gin.Context) {
|
||||
c.JSON(http.StatusCreated, inst)
|
||||
}
|
||||
|
||||
// staffGetInstance is the "why did this stop working" screen's data: one
|
||||
// instance, its account, its whole licence history newest first, and whether
|
||||
// the control plane currently holds what we think it holds.
|
||||
func staffGetInstance(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
var inst models.Instance
|
||||
if err := db.Admin("admin_instances").FindOne(ctx,
|
||||
bson.M{"instance_id": c.Param("id")}).Decode(&inst); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var acct models.Account
|
||||
_ = db.Admin("accounts").FindOne(ctx, bson.M{"account_id": inst.AccountID}).Decode(&acct)
|
||||
|
||||
lics := []models.License{}
|
||||
if cur, err := db.Admin("licenses").Find(ctx, bson.M{"instance_id": inst.InstanceID},
|
||||
options.Find().SetSort(bson.D{{Key: "issued_at", Value: -1}})); err == nil {
|
||||
_ = cur.All(ctx, &lics)
|
||||
}
|
||||
|
||||
// Injection state is only meaningful for cloud. For self-hosted the
|
||||
// customer holds the blob and there is nothing for us to have written.
|
||||
injection := gin.H{"applicable": inst.Deployment == license.DeploymentCloud}
|
||||
if inst.Deployment == license.DeploymentCloud {
|
||||
var remote sharedmodels.Instance
|
||||
err := db.Control("instances").FindOne(ctx,
|
||||
bson.M{"instance_id": inst.InstanceID}).Decode(&remote)
|
||||
switch {
|
||||
case err != nil:
|
||||
injection["state"] = "missing"
|
||||
case inst.CurrentLicense == "":
|
||||
injection["state"] = "none_issued"
|
||||
default:
|
||||
var current models.License
|
||||
if db.Admin("licenses").FindOne(ctx,
|
||||
bson.M{"license_id": inst.CurrentLicense}).Decode(¤t) == nil &&
|
||||
remote.LicenseBlob == current.Blob {
|
||||
injection["state"] = "current"
|
||||
} else {
|
||||
injection["state"] = "stale"
|
||||
}
|
||||
}
|
||||
injection["failed_at"] = inst.InjectFailedAt
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"instance": inst, "account": acct, "licenses": lics, "injection": injection,
|
||||
})
|
||||
}
|
||||
|
||||
// staffListSubscriptions backs the past-due queue on the dashboard.
|
||||
func staffListSubscriptions(c *gin.Context) {
|
||||
filter := bson.M{}
|
||||
if v := c.Query("status"); v != "" {
|
||||
filter["status"] = v
|
||||
}
|
||||
if v := c.Query("account_id"); v != "" {
|
||||
filter["account_id"] = v
|
||||
}
|
||||
cur, err := db.Admin("subscriptions").Find(c.Request.Context(), filter,
|
||||
options.Find().SetLimit(500))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
subs := []models.Subscription{}
|
||||
if err := cur.All(c.Request.Context(), &subs); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, subs)
|
||||
}
|
||||
|
||||
func staffIssue(c *gin.Context) {
|
||||
var body struct {
|
||||
Tier string `json:"tier"`
|
||||
@@ -309,7 +414,11 @@ func staffUpdatePlan(c *gin.Context) {
|
||||
}
|
||||
|
||||
func staffAudit(c *gin.Context) {
|
||||
cur, err := db.Admin("admin_audit").Find(c.Request.Context(), bson.M{},
|
||||
filter := bson.M{}
|
||||
if v := c.Query("account_id"); v != "" {
|
||||
filter["account_id"] = v
|
||||
}
|
||||
cur, err := db.Admin("admin_audit").Find(c.Request.Context(), filter,
|
||||
options.Find().SetLimit(500).SetSort(bson.D{{Key: "created_at", Value: -1}}))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
|
||||
@@ -55,7 +55,83 @@ func CreateCustomerUser(ctx context.Context, accountID, email, password string)
|
||||
if _, err := db.Admin("customer_users").InsertOne(ctx, u); err != nil {
|
||||
return err
|
||||
}
|
||||
return mail.SendVerification(u.Email, token)
|
||||
|
||||
if err := mail.SendVerification(u.Email, token); err != nil {
|
||||
// Undo the insert. A row whose verification link was never delivered is
|
||||
// worse than no row: it can never be signed in to, and it holds the
|
||||
// unique index on email, so the customer cannot sign up again with the
|
||||
// address they just used.
|
||||
_, _ = db.Admin("customer_users").DeleteOne(ctx, bson.M{"user_id": u.UserID})
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// HandleSignup creates a self-hosted customer: an account, an unverified user,
|
||||
// and a verification email.
|
||||
//
|
||||
// Nothing is usable until the emailed link is opened, the same rule sitesvc
|
||||
// already proves — so an address nobody controls cannot occupy an email or
|
||||
// produce an account that can sign in.
|
||||
func HandleSignup(c *gin.Context) {
|
||||
var body struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Website string `json:"website"` // honeypot; real users never fill it
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "name, email and password are required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Honeypot: answer exactly as success so a bot learns nothing.
|
||||
if strings.TrimSpace(body.Website) != "" {
|
||||
c.JSON(http.StatusCreated, gin.H{"pending": true})
|
||||
return
|
||||
}
|
||||
|
||||
email := strings.ToLower(strings.TrimSpace(body.Email))
|
||||
ctx := c.Request.Context()
|
||||
|
||||
if email == "" || len(body.Password) < 12 || strings.TrimSpace(body.Name) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "name, email and a password of at least 12 characters are required"})
|
||||
return
|
||||
}
|
||||
if !allowAttempt("signup:"+email, c.ClientIP()) {
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many attempts, try again later"})
|
||||
return
|
||||
}
|
||||
|
||||
if n, _ := db.Admin("customer_users").CountDocuments(ctx, bson.M{"email": email}); n > 0 {
|
||||
// Same response as success. Telling a stranger the address is taken
|
||||
// confirms who has an account here.
|
||||
c.JSON(http.StatusCreated, gin.H{"pending": true})
|
||||
return
|
||||
}
|
||||
|
||||
acct := models.Account{
|
||||
AccountID: uuid.NewString(),
|
||||
Name: strings.TrimSpace(body.Name),
|
||||
BillingEmail: email,
|
||||
Status: models.AccountActive,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if _, err := db.Admin("accounts").InsertOne(ctx, acct); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "could not create the account"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := CreateCustomerUser(ctx, acct.AccountID, email, body.Password); err != nil {
|
||||
// Roll the account back rather than strand one with no owner.
|
||||
_, _ = db.Admin("accounts").DeleteOne(ctx, bson.M{"account_id": acct.AccountID})
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "could not send the verification email"})
|
||||
return
|
||||
}
|
||||
|
||||
audit.Write(ctx, models.AuditEntry{
|
||||
Actor: email, Action: "customer.signup", AccountID: acct.AccountID, IP: c.ClientIP()})
|
||||
c.JSON(http.StatusCreated, gin.H{"pending": true})
|
||||
}
|
||||
|
||||
// HandleVerify consumes a verification token.
|
||||
|
||||
@@ -8,7 +8,9 @@ import (
|
||||
|
||||
const ctxSession = "admin_session_obj"
|
||||
|
||||
func load(c *gin.Context) *Session {
|
||||
// Load returns the caller's session, or nil. Exported because the session probe
|
||||
// in api/ needs to read a session without requiring one.
|
||||
func Load(c *gin.Context) *Session {
|
||||
id, err := c.Cookie(CookieName)
|
||||
if err != nil || id == "" {
|
||||
return nil
|
||||
@@ -32,7 +34,7 @@ func Current(c *gin.Context) *Session {
|
||||
|
||||
func RequireStaff() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
s := load(c)
|
||||
s := Load(c)
|
||||
if s == nil || s.Kind != KindStaff {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "sign in required"})
|
||||
return
|
||||
@@ -47,7 +49,7 @@ func RequireStaff() gin.HandlerFunc {
|
||||
// remembering to filter.
|
||||
func RequireCustomer() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
s := load(c)
|
||||
s := Load(c)
|
||||
if s == nil || s.Kind != KindCustomer || s.AccountID == "" {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "sign in required"})
|
||||
return
|
||||
|
||||
@@ -61,10 +61,10 @@ func Load() (Config, error) {
|
||||
// and must leave the username empty.
|
||||
RedisUsername: os.Getenv("REDIS_USERNAME"),
|
||||
RedisPassword: os.Getenv("REDIS_PASSWORD"),
|
||||
SigningKey: os.Getenv("LICENSE_SIGNING_KEY"),
|
||||
PublicURL: strings.TrimSuffix(os.Getenv("PUBLIC_URL"), "/"),
|
||||
TrustProxy: strings.EqualFold(os.Getenv("TRUST_PROXY"), "true"),
|
||||
Addr: ":" + envOr("PORT", "8083"),
|
||||
SigningKey: os.Getenv("LICENSE_SIGNING_KEY"),
|
||||
PublicURL: strings.TrimSuffix(os.Getenv("PUBLIC_URL"), "/"),
|
||||
TrustProxy: strings.EqualFold(os.Getenv("TRUST_PROXY"), "true"),
|
||||
Addr: ":" + envOr("PORT", "8083"),
|
||||
|
||||
SMTPHost: os.Getenv("SMTP_HOST"),
|
||||
SMTPPort: envOr("SMTP_PORT", "587"),
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
.next
|
||||
.env
|
||||
*.lic
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
.next
|
||||
next-env.d.ts
|
||||
.env
|
||||
*.lic
|
||||
@@ -0,0 +1,43 @@
|
||||
FROM node:26-alpine AS deps
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm install
|
||||
|
||||
FROM node:26-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
|
||||
# Baked in at build time and must be reachable from the BROWSER, and present in
|
||||
# admin's ADMIN_ORIGIN. Wrong here means every request fails at runtime.
|
||||
ARG NEXT_PUBLIC_ADMIN_API_URL=http://localhost:8083
|
||||
ENV NEXT_PUBLIC_ADMIN_API_URL=$NEXT_PUBLIC_ADMIN_API_URL
|
||||
ARG NEXT_PUBLIC_ADMIN_ENV=production
|
||||
ENV NEXT_PUBLIC_ADMIN_ENV=$NEXT_PUBLIC_ADMIN_ENV
|
||||
|
||||
RUN npm run build
|
||||
|
||||
FROM node:26-alpine AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
RUN addgroup --system --gid 1001 nodejs && \
|
||||
adduser --system --uid 1001 nextjs
|
||||
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
|
||||
USER nextjs
|
||||
|
||||
EXPOSE 3000
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { API_BASE, NotConnected, api } from "@/lib/api";
|
||||
import { NotConnectedPanel } from "@/components/NotConnected";
|
||||
import { formatDate } from "@/lib/format";
|
||||
|
||||
export default function BillingPage() {
|
||||
const { data, error, isLoading } = useQuery({
|
||||
queryKey: ["subscriptions"],
|
||||
queryFn: api.subscriptions,
|
||||
});
|
||||
|
||||
if (error instanceof NotConnected) return <NotConnectedPanel url={API_BASE} />;
|
||||
if (isLoading) return <p className="text-ink-3">Loading…</p>;
|
||||
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<h1 className="text-3xl">Billing</h1>
|
||||
|
||||
{!data || data.length === 0 ? (
|
||||
<p className="text-ink-2">
|
||||
You have no subscriptions. Cloud instances and self-hosted licences are both
|
||||
bought from the pricing page.
|
||||
</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded border border-rule bg-panel">
|
||||
<table className="w-full border-collapse text-left">
|
||||
<thead>
|
||||
<tr className="border-b border-rule bg-panel-2 font-mono text-[0.72rem] uppercase tracking-[0.08em] text-ink-3">
|
||||
<th className="px-4 py-2.5">Plan</th>
|
||||
<th className="px-4 py-2.5">Term</th>
|
||||
<th className="px-4 py-2.5">Status</th>
|
||||
<th className="px-4 py-2.5">Renews</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.map((s) => (
|
||||
<tr
|
||||
key={s.subscription_id}
|
||||
className="border-b border-rule-soft last:border-0"
|
||||
>
|
||||
<td className="px-4 py-3">{s.tier.replace("_", " ")}</td>
|
||||
<td className="px-4 py-3">{s.term}</td>
|
||||
<td className="px-4 py-3">{s.status}</td>
|
||||
<td className="px-4 py-3 font-mono tabular-nums">
|
||||
{formatDate(s.current_period_end)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="max-w-xl text-[0.82rem] text-ink-3">
|
||||
To change a card, download an invoice or cancel, email support and we will send you
|
||||
a billing link. Self-service billing arrives with card payments.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { API_BASE, ApiError, NotConnected, api } from "@/lib/api";
|
||||
import { NotConnectedPanel } from "@/components/NotConnected";
|
||||
import { LicenceDelivery } from "@/components/LicenceDelivery";
|
||||
import { RelinkPanel } from "@/components/RelinkPanel";
|
||||
import { StatePill } from "@/components/StatePill";
|
||||
import { formatDate, licenceState, limitLabel } from "@/lib/format";
|
||||
|
||||
export default function InstancePage() {
|
||||
const id = String(useParams().id);
|
||||
const router = useRouter();
|
||||
const qc = useQueryClient();
|
||||
const [relinkError, setRelinkError] = useState<string | undefined>();
|
||||
|
||||
const account = useQuery({ queryKey: ["account"], queryFn: api.account });
|
||||
const licence = useQuery({
|
||||
queryKey: ["license", id],
|
||||
queryFn: () => api.license(id),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const relink = useMutation({
|
||||
mutationFn: (newId: string) => api.relink(id, newId),
|
||||
onSuccess: (lic) => {
|
||||
qc.invalidateQueries({ queryKey: ["account"] });
|
||||
router.replace(`/instances/${lic.instance_id}`);
|
||||
},
|
||||
onError: (err) =>
|
||||
setRelinkError(err instanceof ApiError ? err.message : "Relink failed. Try again."),
|
||||
});
|
||||
|
||||
if (account.error instanceof NotConnected) return <NotConnectedPanel url={API_BASE} />;
|
||||
|
||||
const instance = account.data?.instances.find((i) => i.instance_id === id);
|
||||
if (account.isLoading) return <p className="text-ink-3">Loading…</p>;
|
||||
if (!instance) {
|
||||
// Says "not on your account" rather than "does not exist": the backend
|
||||
// answers 404 for another account's instance, and confirming existence
|
||||
// here would undo that.
|
||||
return <p className="text-ink-2">That instance is not on your account.</p>;
|
||||
}
|
||||
|
||||
const lic = licence.data;
|
||||
const state = licenceState(lic?.expires_at, Boolean(lic));
|
||||
|
||||
return (
|
||||
<div className="grid gap-8">
|
||||
<header className="grid gap-3">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-3xl">{instance.name}</h1>
|
||||
<StatePill state={state} />
|
||||
</div>
|
||||
<p className="font-mono text-[0.82rem] tabular-nums text-ink-3">
|
||||
{instance.instance_id}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{lic ? (
|
||||
<>
|
||||
<dl className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Fact label="Tier" value={lic.tier.replace("_", " ")} />
|
||||
<Fact label="Expires" value={formatDate(lic.expires_at)} />
|
||||
<Fact label="Servers" value={limitLabel(lic.limits.max_servers)} />
|
||||
<Fact label="Features" value={lic.features.join(", ") || "none"} />
|
||||
</dl>
|
||||
|
||||
{instance.deployment === "self_hosted" && (
|
||||
<>
|
||||
<LicenceDelivery
|
||||
instanceId={instance.instance_id}
|
||||
blob={lic.blob ?? ""}
|
||||
downloadUrl={api.licenseBlobUrl(instance.instance_id)}
|
||||
/>
|
||||
<RelinkPanel
|
||||
instanceId={instance.instance_id}
|
||||
used={instance.relink_count}
|
||||
max={account.data?.max_relinks ?? 3}
|
||||
error={relinkError}
|
||||
onRelink={(newId) => relink.mutate(newId)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="text-ink-2">No licence has been issued for this instance yet.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Fact({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="grid gap-1">
|
||||
<dt className="font-mono text-[0.72rem] uppercase tracking-[0.1em] text-ink-3">
|
||||
{label}
|
||||
</dt>
|
||||
<dd className="font-mono tabular-nums">{value}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { ApiError, NotConnected, api } from "@/lib/api";
|
||||
import { Button } from "@/components/Button";
|
||||
import { Field } from "@/components/Field";
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function LinkForm({ onLinked }: { onLinked: (instanceId: string) => void }) {
|
||||
const [id, setId] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [error, setError] = useState<string | undefined>();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const value = id.trim();
|
||||
|
||||
// Checked here so a typo costs nothing and the message is instant.
|
||||
if (!UUID_RE.test(value)) {
|
||||
setError(
|
||||
"That does not look like an instance ID. It should look like the example below.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(true);
|
||||
setError(undefined);
|
||||
try {
|
||||
const inst = await api.link(value, name.trim());
|
||||
onLinked(inst.instance_id);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof NotConnected
|
||||
? "The licensing service is not reachable from this page."
|
||||
: err instanceof ApiError
|
||||
? err.message
|
||||
: "Could not link that instance. Try again.",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="grid gap-4" noValidate>
|
||||
<Field
|
||||
label="Instance ID"
|
||||
value={id}
|
||||
onChange={(e) => setId(e.target.value)}
|
||||
error={error}
|
||||
hint={
|
||||
<>
|
||||
Find this on your install’s <code>Settings → Licence</code> page, or on
|
||||
the setup screen just after you first sign in. It looks like{" "}
|
||||
<code>6a0fe3f0-49d2-4aa1-967c-a3094b200b5d</code>.
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Field
|
||||
label="Name it (optional)"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
hint="So you can tell it apart from your other installs."
|
||||
/>
|
||||
<Button type="submit" disabled={busy} className="justify-self-start">
|
||||
{busy ? "Linking…" : "Link and issue licence"}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { LinkForm } from "./LinkForm";
|
||||
|
||||
export default function LinkPage() {
|
||||
const router = useRouter();
|
||||
const qc = useQueryClient();
|
||||
|
||||
return (
|
||||
<div className="grid max-w-2xl gap-6">
|
||||
<header className="grid gap-2">
|
||||
<h1 className="text-3xl">Link an install</h1>
|
||||
<p className="text-ink-2">
|
||||
Every licence is tied to one install, so we need its ID before we can issue
|
||||
yours. Paste it below and your licence is ready on the next screen.
|
||||
</p>
|
||||
</header>
|
||||
<LinkForm
|
||||
onLinked={(instanceId) => {
|
||||
qc.invalidateQueries({ queryKey: ["account"] });
|
||||
// Straight to the download, not back to a list: the licence is
|
||||
// the thing they came for.
|
||||
router.push(`/instances/${instanceId}`);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { RequireKind } from "@/lib/session";
|
||||
|
||||
export default function CustomerLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<RequireKind kind="customer">
|
||||
<nav className="border-b border-rule-soft bg-panel-2">
|
||||
<div className="mx-auto flex max-w-rail flex-wrap gap-5 px-5 py-2.5 font-mono text-[0.72rem] uppercase tracking-[0.06em]">
|
||||
<Link href="/" className="text-accent">
|
||||
Overview
|
||||
</Link>
|
||||
<Link href="/instances/link" className="text-ink-3">
|
||||
Link an install
|
||||
</Link>
|
||||
<Link href="/billing" className="text-ink-3">
|
||||
Billing
|
||||
</Link>
|
||||
</div>
|
||||
</nav>
|
||||
<main className="mx-auto max-w-rail px-5 py-8">{children}</main>
|
||||
</RequireKind>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useQueries, useQuery } from "@tanstack/react-query";
|
||||
import Link from "next/link";
|
||||
import { API_BASE, NotConnected, api, type License } from "@/lib/api";
|
||||
import { NotConnectedPanel } from "@/components/NotConnected";
|
||||
import { InstanceCard } from "@/components/InstanceCard";
|
||||
|
||||
export default function OverviewPage() {
|
||||
const { data, error, isLoading } = useQuery({ queryKey: ["account"], queryFn: api.account });
|
||||
|
||||
const licences = useQueries({
|
||||
queries: (data?.instances ?? [])
|
||||
.filter((i) => i.current_license)
|
||||
.map((i) => ({
|
||||
queryKey: ["license", i.instance_id],
|
||||
queryFn: () => api.license(i.instance_id),
|
||||
})),
|
||||
});
|
||||
|
||||
if (error instanceof NotConnected) return <NotConnectedPanel url={API_BASE} />;
|
||||
if (isLoading || !data) return <p className="text-ink-3">Loading your account…</p>;
|
||||
|
||||
const byInstance = new Map<string, License>();
|
||||
licences.forEach((q) => {
|
||||
if (q.data) byInstance.set(q.data.instance_id, q.data);
|
||||
});
|
||||
|
||||
const unlinked = data.instances.filter((i) => i.status === "awaiting_link");
|
||||
|
||||
return (
|
||||
<div className="grid gap-8">
|
||||
<header className="grid gap-2">
|
||||
<h1 className="text-3xl">{data.account.name}</h1>
|
||||
<p className="text-ink-2">{data.account.billing_email}</p>
|
||||
</header>
|
||||
|
||||
{unlinked.length > 0 && (
|
||||
<div className="rounded border border-accent bg-accent-wash p-4">
|
||||
<h2 className="text-xl">Finish setting up your licence</h2>
|
||||
<p className="mt-1 text-[0.82rem] text-ink-2">
|
||||
{unlinked.length === 1
|
||||
? "One purchase is"
|
||||
: `${unlinked.length} purchases are`}{" "}
|
||||
not attached to an install yet, so no licence has been issued for{" "}
|
||||
{unlinked.length === 1 ? "it" : "them"}.
|
||||
</p>
|
||||
<Link
|
||||
href="/instances/link"
|
||||
className="mt-2 inline-block text-[0.82rem] font-semibold text-accent underline"
|
||||
>
|
||||
Link an install
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data.instances.length === 0 ? (
|
||||
<div className="grid max-w-xl gap-3 rounded border border-rule bg-panel p-5">
|
||||
<h2 className="text-xl">No instances yet</h2>
|
||||
<p className="text-ink-2">
|
||||
There are two ways to run Vantage. Buy a cloud instance and we host it, and
|
||||
your licence is applied automatically. Or buy a self-hosted licence, install
|
||||
Vantage on your own server, and link it here to get your licence file.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{data.instances.map((i) => (
|
||||
<InstanceCard
|
||||
key={i.instance_id}
|
||||
instance={i}
|
||||
license={byInstance.get(i.instance_id)}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import { Field } from "@/components/Field";
|
||||
import { formatDate } from "@/lib/format";
|
||||
|
||||
export function AccountSearch() {
|
||||
const [q, setQ] = useState("");
|
||||
const { data, isFetching } = useQuery({
|
||||
queryKey: ["staff-accounts", q],
|
||||
queryFn: () => api.staff.accounts(q || undefined),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<Field
|
||||
label="Search"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
hint="Name, email, Paddle customer ID, or an instance UUID."
|
||||
/>
|
||||
<div className="overflow-x-auto rounded border border-rule bg-panel">
|
||||
<table className="w-full border-collapse text-left">
|
||||
<thead>
|
||||
<tr className="border-b border-rule bg-panel-2 font-mono text-[0.72rem] uppercase tracking-[0.08em] text-ink-3">
|
||||
<th className="px-4 py-2.5">Account</th>
|
||||
<th className="px-4 py-2.5">Billing email</th>
|
||||
<th className="px-4 py-2.5">Status</th>
|
||||
<th className="px-4 py-2.5">Created</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(data ?? []).map((a) => (
|
||||
<tr
|
||||
key={a.account_id}
|
||||
className="border-b border-rule-soft last:border-0"
|
||||
>
|
||||
<td className="px-4 py-3">
|
||||
<Link
|
||||
href={`/staff/accounts/${a.account_id}`}
|
||||
className="text-accent underline"
|
||||
>
|
||||
{a.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-[0.82rem]">
|
||||
{a.billing_email}
|
||||
</td>
|
||||
<td className="px-4 py-3">{a.status}</td>
|
||||
<td className="px-4 py-3 font-mono tabular-nums">
|
||||
{formatDate(a.created_at)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{!isFetching && (data ?? []).length === 0 && (
|
||||
<p className="px-4 py-6 text-ink-3">
|
||||
No account matches that. Try the instance UUID from the customer’s
|
||||
email.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { api } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/format";
|
||||
|
||||
export default function AccountDetailPage() {
|
||||
const id = String(useParams().id);
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["staff-account", id],
|
||||
queryFn: () => api.staff.account(id),
|
||||
});
|
||||
|
||||
if (isLoading || !data) return <p className="text-ink-3">Loading…</p>;
|
||||
|
||||
return (
|
||||
<div className="grid gap-8">
|
||||
<header className="grid gap-1">
|
||||
<h1 className="text-3xl">{data.account.name}</h1>
|
||||
<p className="font-mono text-[0.82rem] text-ink-3">
|
||||
{data.account.billing_email} · {data.account.account_id}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<Panel title="Instances">
|
||||
<ul className="grid gap-2">
|
||||
{data.instances.map((i) => (
|
||||
<li key={i.instance_id} className="flex flex-wrap justify-between gap-2">
|
||||
<Link
|
||||
href={`/staff/instances/${i.instance_id}`}
|
||||
className="text-accent underline"
|
||||
>
|
||||
{i.name || i.instance_id}
|
||||
</Link>
|
||||
<span className="font-mono text-[0.82rem] text-ink-3">
|
||||
{i.deployment} · {i.tier ?? "no tier"} · {i.status}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{data.instances.length === 0 && <li className="text-ink-3">None.</li>}
|
||||
</ul>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Subscriptions">
|
||||
<ul className="grid gap-2">
|
||||
{data.subscriptions.map((s) => (
|
||||
<li key={s.subscription_id} className="flex flex-wrap justify-between gap-2">
|
||||
<span>
|
||||
{s.tier.replace("_", " ")} · {s.term}
|
||||
</span>
|
||||
<span className="font-mono text-[0.82rem] text-ink-3">
|
||||
{s.status} · renews {formatDate(s.current_period_end)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{data.subscriptions.length === 0 && <li className="text-ink-3">None.</li>}
|
||||
</ul>
|
||||
</Panel>
|
||||
|
||||
<Panel title="People">
|
||||
<ul className="grid gap-2">
|
||||
{data.users.map((u) => (
|
||||
<li key={u.user_id} className="flex flex-wrap justify-between gap-2">
|
||||
<span className="font-mono text-[0.82rem]">{u.email}</span>
|
||||
<span className="font-mono text-[0.82rem] text-ink-3">
|
||||
{u.verified_at
|
||||
? `verified ${formatDate(u.verified_at)}`
|
||||
: "not verified"}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{data.users.length === 0 && (
|
||||
<li className="text-ink-3">
|
||||
None — this is a cloud account, so its people sign in with their
|
||||
control-plane details.
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Audit">
|
||||
<ul className="grid gap-1 font-mono text-[0.82rem]">
|
||||
{data.audit.map((e, n) => (
|
||||
<li key={n} className="flex flex-wrap justify-between gap-2 text-ink-2">
|
||||
<span>
|
||||
{e.action} · {e.actor}
|
||||
</span>
|
||||
<span className="tabular-nums text-ink-3">
|
||||
{formatDate(e.created_at)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{data.audit.length === 0 && <li className="text-ink-3">Nothing yet.</li>}
|
||||
</ul>
|
||||
</Panel>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Panel({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<section className="grid gap-3 rounded border border-rule bg-panel p-5">
|
||||
<h2 className="text-xl">{title}</h2>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { AccountSearch } from "./AccountSearch";
|
||||
|
||||
export default function AccountsPage() {
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<h1 className="text-3xl">Accounts</h1>
|
||||
<AccountSearch />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import { formatDate, formatStamp } from "@/lib/format";
|
||||
import { Field } from "@/components/Field";
|
||||
|
||||
export default function AuditPage() {
|
||||
const [filter, setFilter] = useState("");
|
||||
const { data } = useQuery({ queryKey: ["staff-audit"], queryFn: () => api.staff.audit() });
|
||||
|
||||
const rows = (data ?? []).filter((e) =>
|
||||
filter
|
||||
? `${e.action} ${e.actor} ${e.target ?? ""}`.toLowerCase().includes(filter.toLowerCase())
|
||||
: true,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<h1 className="text-3xl">Audit</h1>
|
||||
<Field
|
||||
label="Filter"
|
||||
value={filter}
|
||||
onChange={(e) => setFilter(e.target.value)}
|
||||
hint="Action, actor or target."
|
||||
/>
|
||||
<ul className="grid gap-2 rounded border border-rule bg-panel p-5 font-mono text-[0.82rem]">
|
||||
{rows.map((e, n) => (
|
||||
<li
|
||||
key={n}
|
||||
className="grid gap-1 border-b border-rule-soft pb-2 last:border-0 sm:grid-cols-[11rem_1fr]"
|
||||
>
|
||||
<span className="tabular-nums text-ink-3">
|
||||
{formatDate(e.created_at)} {formatStamp(e.created_at)}
|
||||
</span>
|
||||
<span className="text-ink-2">
|
||||
<b className="text-ink">{e.action}</b> · {e.actor}
|
||||
{e.target && ` · ${e.target}`}
|
||||
{e.detail && ` · ${e.detail}`}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{rows.length === 0 && <li className="text-ink-3">Nothing matches that.</li>}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { ApiError, api, type Tier } from "@/lib/api";
|
||||
import { Button } from "@/components/Button";
|
||||
import { Field } from "@/components/Field";
|
||||
|
||||
export function IssuePanel({
|
||||
instanceId,
|
||||
deployment,
|
||||
}: {
|
||||
instanceId: string;
|
||||
deployment: string;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [tier, setTier] = useState<Tier>(deployment === "cloud" ? "professional" : "self_hosted");
|
||||
const [term, setTerm] = useState("annual");
|
||||
const [newId, setNewId] = useState("");
|
||||
const [error, setError] = useState<string | undefined>();
|
||||
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ["staff-instance", instanceId] });
|
||||
|
||||
const issue = useMutation({
|
||||
mutationFn: () => api.staff.issue(instanceId, { tier, term, reason: "manual" }),
|
||||
onSuccess: invalidate,
|
||||
onError: (e) => setError(e instanceof ApiError ? e.message : "Issue failed."),
|
||||
});
|
||||
|
||||
const relink = useMutation({
|
||||
mutationFn: () => api.staff.relink(instanceId, newId.trim()),
|
||||
onSuccess: invalidate,
|
||||
onError: (e) => setError(e instanceof ApiError ? e.message : "Relink failed."),
|
||||
});
|
||||
|
||||
return (
|
||||
<section className="grid gap-4 border-t border-rule-soft pt-5">
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<label className="grid gap-1.5">
|
||||
<span className="font-mono text-[0.72rem] uppercase tracking-[0.1em] text-ink-3">
|
||||
Tier
|
||||
</span>
|
||||
<select
|
||||
value={tier}
|
||||
onChange={(e) => setTier(e.target.value as Tier)}
|
||||
className="rounded border border-rule bg-panel-2 px-2.5 py-2"
|
||||
>
|
||||
<option value="free">Free</option>
|
||||
<option value="professional">Professional</option>
|
||||
<option value="self_hosted">Self Hosted</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1.5">
|
||||
<span className="font-mono text-[0.72rem] uppercase tracking-[0.1em] text-ink-3">
|
||||
Term
|
||||
</span>
|
||||
<select
|
||||
value={term}
|
||||
onChange={(e) => setTerm(e.target.value)}
|
||||
className="rounded border border-rule bg-panel-2 px-2.5 py-2"
|
||||
>
|
||||
<option value="annual">Annual</option>
|
||||
<option value="monthly">Monthly</option>
|
||||
</select>
|
||||
</label>
|
||||
<Button type="button" onClick={() => issue.mutate()} disabled={issue.isPending}>
|
||||
{issue.isPending ? "Issuing…" : "Issue licence"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<Field
|
||||
label="Relink to instance ID"
|
||||
value={newId}
|
||||
onChange={(e) => setNewId(e.target.value)}
|
||||
hint="Staff relinks are not capped — the customer cap exists to put you in the loop."
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="line"
|
||||
onClick={() => relink.mutate()}
|
||||
disabled={!newId.trim()}
|
||||
>
|
||||
Relink
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-[0.82rem] text-expired">{error}</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import clsx from "clsx";
|
||||
import { api, type InjectionState } from "@/lib/api";
|
||||
import { Ledger } from "@/components/Ledger";
|
||||
import { IssuePanel } from "./IssuePanel";
|
||||
|
||||
const INJECTION: Record<InjectionState, { label: string; tone: string }> = {
|
||||
current: { label: "Control plane holds the current licence", tone: "text-valid" },
|
||||
stale: {
|
||||
label: "Control plane holds an older blob — the reconciler will repair it",
|
||||
tone: "text-warn",
|
||||
},
|
||||
missing: { label: "No matching instance in the control plane", tone: "text-expired" },
|
||||
none_issued: { label: "Nothing issued yet, so nothing to inject", tone: "text-ink-3" },
|
||||
};
|
||||
|
||||
export default function StaffInstancePage() {
|
||||
const id = String(useParams().id);
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["staff-instance", id],
|
||||
queryFn: () => api.staff.instance(id),
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
|
||||
if (isLoading || !data) return <p className="text-ink-3">Loading…</p>;
|
||||
|
||||
const inj = data.injection.state ? INJECTION[data.injection.state] : undefined;
|
||||
|
||||
return (
|
||||
<div className="grid gap-8">
|
||||
<header className="grid gap-2">
|
||||
<h1 className="text-3xl">{data.instance.name || data.instance.instance_id}</h1>
|
||||
<p className="font-mono text-[0.82rem] tabular-nums text-ink-3">
|
||||
{data.instance.instance_id}
|
||||
</p>
|
||||
<p className="text-[0.82rem]">
|
||||
<Link
|
||||
href={`/staff/accounts/${data.account.account_id}`}
|
||||
className="text-accent underline"
|
||||
>
|
||||
{data.account.name || data.account.account_id}
|
||||
</Link>
|
||||
<span className="text-ink-3">
|
||||
{" "}
|
||||
· {data.instance.deployment} · {data.instance.status}
|
||||
{data.instance.relink_count > 0 &&
|
||||
` · ${data.instance.relink_count} relinks this term`}
|
||||
</span>
|
||||
</p>
|
||||
{data.injection.applicable && inj && (
|
||||
<p className={clsx("font-mono text-[0.72rem]", inj.tone)}>{inj.label}</p>
|
||||
)}
|
||||
</header>
|
||||
|
||||
<section className="grid gap-3 rounded border border-rule bg-panel p-5">
|
||||
<h2 className="text-xl">Licence history</h2>
|
||||
<Ledger licenses={data.licenses} />
|
||||
<IssuePanel
|
||||
instanceId={data.instance.instance_id}
|
||||
deployment={data.instance.deployment}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { RequireKind } from "@/lib/session";
|
||||
|
||||
const LINKS = [
|
||||
["/staff", "Operations"],
|
||||
["/staff/accounts", "Accounts"],
|
||||
["/staff/licenses", "Licences"],
|
||||
["/staff/plans", "Plans"],
|
||||
["/staff/audit", "Audit"],
|
||||
] as const;
|
||||
|
||||
export default function StaffLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<RequireKind kind="staff">
|
||||
<nav className="border-b border-rule-soft bg-panel-2">
|
||||
<div className="mx-auto flex max-w-rail flex-wrap gap-5 px-5 py-2.5 font-mono text-[0.72rem] uppercase tracking-[0.06em]">
|
||||
{LINKS.map(([href, label]) => (
|
||||
<Link key={href} href={href} className="text-ink-3 hover:text-accent">
|
||||
{label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
<main className="mx-auto max-w-rail px-5 py-8">{children}</main>
|
||||
</RequireKind>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { api, type Tier } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/format";
|
||||
|
||||
export default function LicensesPage() {
|
||||
const [tier, setTier] = useState<"" | Tier>("");
|
||||
const [reason, setReason] = useState("");
|
||||
const { data } = useQuery({ queryKey: ["staff-licenses"], queryFn: () => api.staff.licenses() });
|
||||
|
||||
// Filtered here rather than server-side: the endpoint caps at 500 rows and
|
||||
// staff are narrowing a list they can already see.
|
||||
const rows = (data ?? []).filter(
|
||||
(l) => (!tier || l.tier === tier) && (!reason || l.reason === reason),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<h1 className="text-3xl">Licences</h1>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<select
|
||||
value={tier}
|
||||
onChange={(e) => setTier(e.target.value as Tier | "")}
|
||||
className="rounded border border-rule bg-panel-2 px-2.5 py-2"
|
||||
aria-label="Filter by tier"
|
||||
>
|
||||
<option value="">All tiers</option>
|
||||
<option value="free">Free</option>
|
||||
<option value="professional">Professional</option>
|
||||
<option value="self_hosted">Self Hosted</option>
|
||||
</select>
|
||||
<select
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
className="rounded border border-rule bg-panel-2 px-2.5 py-2"
|
||||
aria-label="Filter by reason"
|
||||
>
|
||||
<option value="">All reasons</option>
|
||||
<option value="new">New</option>
|
||||
<option value="renewal">Renewal</option>
|
||||
<option value="tier_change">Tier change</option>
|
||||
<option value="relink">Relink</option>
|
||||
<option value="manual">Manual</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="overflow-x-auto rounded border border-rule bg-panel">
|
||||
<table className="w-full border-collapse text-left">
|
||||
<thead>
|
||||
<tr className="border-b border-rule bg-panel-2 font-mono text-[0.72rem] uppercase tracking-[0.08em] text-ink-3">
|
||||
<th className="px-4 py-2.5">Issued</th>
|
||||
<th className="px-4 py-2.5">Instance</th>
|
||||
<th className="px-4 py-2.5">Tier</th>
|
||||
<th className="px-4 py-2.5">Reason</th>
|
||||
<th className="px-4 py-2.5">Expires</th>
|
||||
<th className="px-4 py-2.5">State</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((l) => (
|
||||
<tr
|
||||
key={l.license_id}
|
||||
className="border-b border-rule-soft last:border-0"
|
||||
>
|
||||
<td className="px-4 py-3 font-mono tabular-nums">
|
||||
{formatDate(l.issued_at)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Link
|
||||
href={`/staff/instances/${l.instance_id}`}
|
||||
className="font-mono text-[0.82rem] text-accent underline"
|
||||
>
|
||||
{l.instance_id.slice(0, 8)}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-4 py-3">{l.tier.replace("_", " ")}</td>
|
||||
<td className="px-4 py-3">{l.reason.replace("_", " ")}</td>
|
||||
<td className="px-4 py-3 font-mono tabular-nums">
|
||||
{formatDate(l.expires_at)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-ink-3">
|
||||
{l.superseded_by ? "superseded" : "current"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{rows.length === 0 && (
|
||||
<p className="px-4 py-6 text-ink-3">No licences match those filters.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { API_BASE, NotConnected, api } from "@/lib/api";
|
||||
import { NotConnectedPanel } from "@/components/NotConnected";
|
||||
import { Queue } from "@/components/Queue";
|
||||
import { daysRemaining } from "@/lib/format";
|
||||
|
||||
const HOURS_48 = 48 * 3600_000;
|
||||
|
||||
export default function StaffDashboard() {
|
||||
const injection = useQuery({ queryKey: ["injection"], queryFn: api.staff.injectionHealth });
|
||||
const expiring = useQuery({
|
||||
queryKey: ["instances", "expiring"],
|
||||
queryFn: () => api.staff.instances({ expiring: "true" }),
|
||||
});
|
||||
const pastDue = useQuery({
|
||||
queryKey: ["subs", "past_due"],
|
||||
queryFn: () => api.staff.subscriptions("past_due"),
|
||||
});
|
||||
const unlinked = useQuery({
|
||||
queryKey: ["instances", "awaiting_link"],
|
||||
queryFn: () => api.staff.instances({ status: "awaiting_link" }),
|
||||
});
|
||||
|
||||
if (injection.error instanceof NotConnected) return <NotConnectedPanel url={API_BASE} />;
|
||||
|
||||
const stale = (unlinked.data ?? []).filter(
|
||||
(i) => Date.now() - new Date(i.created_at).getTime() > HOURS_48,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<h1 className="text-3xl">Operations</h1>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Queue
|
||||
title="Failed injections"
|
||||
tone="expired"
|
||||
count={injection.data?.count ?? 0}
|
||||
items={(injection.data?.failed ?? []).slice(0, 4).map((i) => ({
|
||||
label: i.name || i.instance_id,
|
||||
href: `/staff/instances/${i.instance_id}`,
|
||||
meta: i.inject_failed_at
|
||||
? new Date(i.inject_failed_at).toISOString().slice(11, 16)
|
||||
: "",
|
||||
}))}
|
||||
/>
|
||||
<Queue
|
||||
title="Expiring ≤ 14 days"
|
||||
tone="warn"
|
||||
count={expiring.data?.length ?? 0}
|
||||
items={(expiring.data ?? []).slice(0, 4).map((i) => ({
|
||||
label: i.name || i.instance_id,
|
||||
href: `/staff/instances/${i.instance_id}`,
|
||||
meta: i.tier ?? "",
|
||||
}))}
|
||||
/>
|
||||
<Queue
|
||||
title="Past due"
|
||||
tone="expired"
|
||||
count={pastDue.data?.length ?? 0}
|
||||
items={(pastDue.data ?? []).slice(0, 4).map((s) => ({
|
||||
label: s.instance_id || s.account_id,
|
||||
href: `/staff/accounts/${s.account_id}`,
|
||||
meta: `${daysRemaining(s.current_period_end)}d`,
|
||||
}))}
|
||||
/>
|
||||
<Queue
|
||||
title="Unlinked > 48h"
|
||||
tone="accent"
|
||||
count={stale.length}
|
||||
items={stale.slice(0, 4).map((i) => ({
|
||||
label: i.name || i.instance_id,
|
||||
href: `/staff/accounts/${i.account_id}`,
|
||||
meta: `${Math.floor((Date.now() - new Date(i.created_at).getTime()) / 86_400_000)}d`,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { api, type Plan } from "@/lib/api";
|
||||
import { Button } from "@/components/Button";
|
||||
import { ConfirmPlanChange } from "@/components/ConfirmPlanChange";
|
||||
import { limitLabel } from "@/lib/format";
|
||||
|
||||
export default function PlansPage() {
|
||||
const qc = useQueryClient();
|
||||
const plans = useQuery({ queryKey: ["plans"], queryFn: api.staff.plans });
|
||||
const licenses = useQuery({ queryKey: ["staff-licenses"], queryFn: () => api.staff.licenses() });
|
||||
const [draft, setDraft] = useState<Plan | null>(null);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (p: Plan) =>
|
||||
api.staff.updatePlan(p.tier, {
|
||||
name: p.name,
|
||||
limits: p.limits,
|
||||
features: p.features,
|
||||
paddle_product_id: p.paddle_product_id,
|
||||
paddle_price_ids: p.paddle_price_ids,
|
||||
active: p.active,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["plans"] });
|
||||
setDraft(null);
|
||||
},
|
||||
});
|
||||
|
||||
const original = plans.data?.find((p) => p.tier === draft?.tier);
|
||||
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<h1 className="text-3xl">Plans</h1>
|
||||
|
||||
{draft && original && (
|
||||
<ConfirmPlanChange
|
||||
plan={original}
|
||||
next={draft}
|
||||
issuedCount={(licenses.data ?? []).filter((l) => l.tier === draft.tier).length}
|
||||
onConfirm={() => save.mutate(draft)}
|
||||
onCancel={() => setDraft(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
{(plans.data ?? []).map((p) => (
|
||||
<section
|
||||
key={p.tier}
|
||||
className="grid gap-3 rounded border border-rule bg-panel p-5"
|
||||
>
|
||||
<h2 className="text-xl">{p.name}</h2>
|
||||
<dl className="grid gap-1 font-mono text-[0.82rem] tabular-nums text-ink-2">
|
||||
<div className="flex justify-between gap-2">
|
||||
<dt>servers</dt>
|
||||
<dd>{limitLabel(p.limits.max_servers)}</dd>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<dt>secret groups</dt>
|
||||
<dd>{limitLabel(p.limits.max_secret_groups)}</dd>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<dt>channels</dt>
|
||||
<dd>{limitLabel(p.limits.max_channels)}</dd>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<dt>features</dt>
|
||||
<dd>{p.features.join(", ") || "none"}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
{/* Guard rail two: deployment is shown, never edited. */}
|
||||
<p className="flex items-center gap-2 rounded border border-rule bg-panel-2 px-2.5 py-2 text-[0.82rem] text-ink-3">
|
||||
<span aria-hidden="true">🔒</span>
|
||||
<span>
|
||||
Deployment is fixed at{" "}
|
||||
<b className="font-mono">{p.deployment}</b>. Moving a tier between
|
||||
cloud and self-hosted is a code change, not a form field.
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="line"
|
||||
onClick={() =>
|
||||
setDraft({ ...p, limits: { ...p.limits, max_servers: 7 } })
|
||||
}
|
||||
>
|
||||
Cap servers at 7
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="line"
|
||||
onClick={() =>
|
||||
setDraft({
|
||||
...p,
|
||||
features: p.features.filter((f) => f !== "oidc"),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remove OIDC
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* ==========================================================================
|
||||
Vantage admin console design tokens.
|
||||
|
||||
Lines 8-97 below are site/app/globals.css's token blocks, copied verbatim:
|
||||
the marketing site and this console are one visual system. Change them in
|
||||
both apps in the same commit — nothing enforces the match automatically.
|
||||
|
||||
Light is the default because web/ is locked to dark, and telling the two
|
||||
apart at a glance is what stops a Reissue landing in the wrong tab. In dark
|
||||
mode the accent lifts to #5b9be8, which is nearer web/'s indigo, so the
|
||||
distinction leans on the ground rather than the hue.
|
||||
========================================================================== */
|
||||
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
|
||||
--ground: #eaedf3;
|
||||
--panel: #ffffff;
|
||||
--panel-2: #f4f6fa;
|
||||
--ink: #0a1b33;
|
||||
--ink-2: #41556f;
|
||||
--ink-3: #6c7f96;
|
||||
--rule: #cdd6e2;
|
||||
--rule-soft: #e0e6ef;
|
||||
--accent: #0b2a58;
|
||||
--accent-ink: #ffffff;
|
||||
--up: #2f8a60;
|
||||
--down: #c6462f;
|
||||
--pend: #b0801f;
|
||||
--shadow: 0 1px 0 rgba(10, 27, 51, 0.05), 0 18px 40px -26px rgba(10, 27, 51, 0.45);
|
||||
--logo: #0b2a58;
|
||||
|
||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
--mono: ui-monospace, "Cascadia Mono", "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
|
||||
|
||||
--s--1: clamp(0.76rem, 0.74rem + 0.1vw, 0.81rem);
|
||||
--s-0: clamp(1rem, 0.97rem + 0.14vw, 1.05rem);
|
||||
--s-1: clamp(1.16rem, 1.09rem + 0.32vw, 1.36rem);
|
||||
--s-2: clamp(1.5rem, 1.34rem + 0.74vw, 2rem);
|
||||
--s-3: clamp(2rem, 1.66rem + 1.6vw, 3.1rem);
|
||||
--s-4: clamp(2.6rem, 1.9rem + 3.3vw, 4.9rem);
|
||||
|
||||
--rail: 1200px;
|
||||
}
|
||||
|
||||
/* Dark tokens are defined once and applied through three selectors: the OS
|
||||
preference, and both explicit values of data-theme so the in-page toggle
|
||||
wins in either direction. */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--ground: #071628;
|
||||
--panel: #0d2138;
|
||||
--panel-2: #102842;
|
||||
--ink: #e4ecf6;
|
||||
--ink-2: #9fb3ca;
|
||||
--ink-3: #71879f;
|
||||
--rule: #1e3855;
|
||||
--rule-soft: #172c44;
|
||||
--accent: #5b9be8;
|
||||
--accent-ink: #04101f;
|
||||
--up: #4fb484;
|
||||
--down: #e2705a;
|
||||
--pend: #d6a63f;
|
||||
--shadow: 0 1px 0 rgba(0, 0, 0, 0.35), 0 20px 44px -26px rgba(0, 0, 0, 0.85);
|
||||
--logo: #7fb2f0;
|
||||
}
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
--ground: #071628;
|
||||
--panel: #0d2138;
|
||||
--panel-2: #102842;
|
||||
--ink: #e4ecf6;
|
||||
--ink-2: #9fb3ca;
|
||||
--ink-3: #71879f;
|
||||
--rule: #1e3855;
|
||||
--rule-soft: #172c44;
|
||||
--accent: #5b9be8;
|
||||
--accent-ink: #04101f;
|
||||
--up: #4fb484;
|
||||
--down: #e2705a;
|
||||
--pend: #d6a63f;
|
||||
--shadow: 0 1px 0 rgba(0, 0, 0, 0.35), 0 20px 44px -26px rgba(0, 0, 0, 0.85);
|
||||
--logo: #7fb2f0;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] {
|
||||
--ground: #eaedf3;
|
||||
--panel: #ffffff;
|
||||
--panel-2: #f4f6fa;
|
||||
--ink: #0a1b33;
|
||||
--ink-2: #41556f;
|
||||
--ink-3: #6c7f96;
|
||||
--rule: #cdd6e2;
|
||||
--rule-soft: #e0e6ef;
|
||||
--accent: #0b2a58;
|
||||
--accent-ink: #ffffff;
|
||||
--up: #2f8a60;
|
||||
--down: #c6462f;
|
||||
--pend: #b0801f;
|
||||
--shadow: 0 1px 0 rgba(10, 27, 51, 0.05), 0 18px 40px -26px rgba(10, 27, 51, 0.45);
|
||||
--logo: #0b2a58;
|
||||
}
|
||||
|
||||
/* Not in site/: the hatched sandbox badge and hover washes need a tinted fill,
|
||||
and deriving it at each use would drift. */
|
||||
:root {
|
||||
--accent-wash: rgba(11, 42, 88, 0.07);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--accent-wash: rgba(91, 155, 232, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
--accent-wash: rgba(91, 155, 232, 0.1);
|
||||
}
|
||||
|
||||
:root[data-theme="light"] {
|
||||
--accent-wash: rgba(11, 42, 88, 0.07);
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--ground);
|
||||
color: var(--ink);
|
||||
font-family: var(--sans);
|
||||
font-size: var(--s-0);
|
||||
line-height: 1.6;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
/* site/'s heading treatment, which is what replaces a display face. */
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-weight: 800;
|
||||
line-height: 1.03;
|
||||
letter-spacing: -0.03em;
|
||||
text-wrap: balance;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: var(--mono);
|
||||
font-size: 0.92em;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 3px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.001ms !important;
|
||||
transition-duration: 0.001ms !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Metadata } from "next";
|
||||
import "./globals.css";
|
||||
import { Providers } from "@/components/Providers";
|
||||
import { EnvBadge } from "@/components/EnvBadge";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Vantage Licensing",
|
||||
description: "Licences, instances and billing for Vantage.",
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>
|
||||
<header className="border-b border-rule bg-panel">
|
||||
<div className="mx-auto flex max-w-rail flex-wrap items-center justify-between gap-4 px-5 py-4">
|
||||
<span className="flex items-baseline gap-2 text-[1.16rem] font-extrabold tracking-[-0.02em]">
|
||||
Vantage
|
||||
<span className="font-mono text-[0.72rem] font-normal uppercase tracking-[0.14em] text-ink-3">
|
||||
Licensing
|
||||
</span>
|
||||
</span>
|
||||
<EnvBadge />
|
||||
</div>
|
||||
</header>
|
||||
<Providers>{children}</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { API_BASE, ApiError, NotConnected, api } from "@/lib/api";
|
||||
import { NotConnectedPanel } from "@/components/NotConnected";
|
||||
import { Button } from "@/components/Button";
|
||||
import { Field } from "@/components/Field";
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [staff, setStaff] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [offline, setOffline] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const s = staff
|
||||
? await api.staffLogin(email, password)
|
||||
: await api.login(email, password);
|
||||
router.replace(s.kind === "staff" ? "/staff" : "/");
|
||||
} catch (err) {
|
||||
if (err instanceof NotConnected) setOffline(true);
|
||||
else if (err instanceof ApiError) setError(err.message);
|
||||
else setError("Sign in failed. Try again.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (offline)
|
||||
return (
|
||||
<Main>
|
||||
<NotConnectedPanel url={API_BASE} />
|
||||
</Main>
|
||||
);
|
||||
|
||||
return (
|
||||
<Main>
|
||||
<h1 className="text-3xl">Sign in</h1>
|
||||
<form onSubmit={submit} className="mt-6 grid gap-4">
|
||||
<Field
|
||||
label="Email"
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
<Field
|
||||
label="Password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
error={error ?? undefined}
|
||||
/>
|
||||
<label className="flex items-center gap-2 text-[0.82rem] text-ink-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={staff}
|
||||
onChange={(e) => setStaff(e.target.checked)}
|
||||
/>
|
||||
I work at Vantage
|
||||
</label>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button type="submit" disabled={busy}>
|
||||
{busy ? "Signing in…" : "Sign in"}
|
||||
</Button>
|
||||
<Link href="/signup" className="text-[0.82rem] text-accent underline">
|
||||
Create an account for a self-hosted licence
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
</Main>
|
||||
);
|
||||
}
|
||||
|
||||
function Main({ children }: { children: React.ReactNode }) {
|
||||
return <main className="mx-auto max-w-rail px-5 py-12">{children}</main>;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<main className="mx-auto max-w-rail px-5 py-12">
|
||||
<h1 className="text-3xl">Nothing here</h1>
|
||||
<p className="mt-2 text-ink-2">
|
||||
That page does not exist, or it belongs to an account you are not signed in to.
|
||||
</p>
|
||||
<Link href="/" className="mt-4 inline-block text-accent underline">
|
||||
Back to your account
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { ApiError, NotConnected, api } from "@/lib/api";
|
||||
import { Button } from "@/components/Button";
|
||||
import { Field } from "@/components/Field";
|
||||
|
||||
export default function SignupPage() {
|
||||
const [form, setForm] = useState({ name: "", email: "", password: "", website: "" });
|
||||
const [state, setState] = useState<"idle" | "busy" | "sent">("idle");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setState("busy");
|
||||
setError(null);
|
||||
try {
|
||||
await api.signup(form);
|
||||
setState("sent");
|
||||
} catch (err) {
|
||||
setState("idle");
|
||||
setError(
|
||||
err instanceof NotConnected
|
||||
? "The licensing service is not reachable from this page."
|
||||
: err instanceof ApiError
|
||||
? err.message
|
||||
: "Could not create the account. Try again.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-rail px-5 py-12">
|
||||
{state === "sent" ? (
|
||||
<div className="grid max-w-xl gap-3">
|
||||
<h1 className="text-3xl">Check your email</h1>
|
||||
<p className="text-ink-2">
|
||||
We sent a link to {form.email}. Open it to finish setting up your account —
|
||||
it expires in 24 hours. Nothing is created until you do.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<h1 className="text-3xl">Create an account</h1>
|
||||
<p className="mt-2 max-w-xl text-ink-2">
|
||||
For self-hosted licences. If you run on our cloud, sign in with the same
|
||||
details you use for your Vantage instance.
|
||||
</p>
|
||||
<form onSubmit={submit} className="mt-6 grid gap-4">
|
||||
<Field
|
||||
label="Organisation"
|
||||
required
|
||||
value={form.name}
|
||||
onChange={(e) => setForm({ ...form, name: e.target.value })}
|
||||
/>
|
||||
<Field
|
||||
label="Email"
|
||||
type="email"
|
||||
required
|
||||
value={form.email}
|
||||
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||
/>
|
||||
<Field
|
||||
label="Password"
|
||||
type="password"
|
||||
required
|
||||
minLength={12}
|
||||
hint="At least 12 characters."
|
||||
value={form.password}
|
||||
onChange={(e) => setForm({ ...form, password: e.target.value })}
|
||||
error={error ?? undefined}
|
||||
/>
|
||||
{/* Honeypot: off-screen, unlabelled for humans, irresistible to bots. */}
|
||||
<input
|
||||
type="text"
|
||||
name="website"
|
||||
tabIndex={-1}
|
||||
autoComplete="off"
|
||||
aria-hidden="true"
|
||||
value={form.website}
|
||||
onChange={(e) => setForm({ ...form, website: e.target.value })}
|
||||
className="absolute left-[-9999px] h-0 w-0"
|
||||
/>
|
||||
<Button type="submit" disabled={state === "busy"}>
|
||||
{state === "busy" ? "Creating…" : "Create account"}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Suspense } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
function Verify() {
|
||||
const token = useSearchParams().get("token") ?? "";
|
||||
const { data, error, isLoading } = useQuery({
|
||||
queryKey: ["verify", token],
|
||||
queryFn: () => api.verify(token),
|
||||
enabled: token !== "",
|
||||
retry: false,
|
||||
});
|
||||
|
||||
if (!token)
|
||||
return (
|
||||
<Message
|
||||
title="That link is incomplete"
|
||||
body="It is missing its token. Use the link in the email exactly as sent."
|
||||
/>
|
||||
);
|
||||
if (isLoading) return <Message title="Verifying…" body="One moment." />;
|
||||
if (error || !data?.verified)
|
||||
return (
|
||||
<Message
|
||||
title="That link is invalid or has expired"
|
||||
body="Links last 24 hours and can only be used once. Sign up again to get a fresh one."
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="grid max-w-xl gap-3">
|
||||
<h1 className="text-3xl">Email verified</h1>
|
||||
<p className="text-ink-2">Your account is ready.</p>
|
||||
<Link href="/login" className="justify-self-start text-accent underline">
|
||||
Sign in
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Message({ title, body }: { title: string; body: string }) {
|
||||
return (
|
||||
<div className="grid max-w-xl gap-3">
|
||||
<h1 className="text-3xl">{title}</h1>
|
||||
<p className="text-ink-2">{body}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function VerifyPage() {
|
||||
return (
|
||||
<main className="mx-auto max-w-rail px-5 py-12">
|
||||
<Suspense fallback={null}>
|
||||
<Verify />
|
||||
</Suspense>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import clsx from "clsx";
|
||||
|
||||
type Props = React.ButtonHTMLAttributes<HTMLButtonElement> & { variant?: "solid" | "line" };
|
||||
|
||||
/*
|
||||
* Matches site/'s .btn--solid and .btn--line exactly, including the neutral
|
||||
* border on the secondary variant. site/ does not have an accent-outlined
|
||||
* button and this app should not invent one.
|
||||
*/
|
||||
export function Button({ variant = "solid", className, ...rest }: Props) {
|
||||
return (
|
||||
<button
|
||||
{...rest}
|
||||
className={clsx(
|
||||
"inline-flex items-center gap-2 rounded border px-4 py-2.5 text-[0.94rem] font-semibold",
|
||||
"transition-[filter,border-color] duration-150 hover:brightness-110",
|
||||
variant === "solid"
|
||||
? "border-accent bg-accent text-accent-ink"
|
||||
: "border-rule bg-panel text-ink hover:border-ink-3",
|
||||
rest.disabled && "cursor-not-allowed border-rule bg-panel text-ink-3 hover:brightness-100",
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { Plan } from "@/lib/api";
|
||||
import { limitLabel } from "@/lib/format";
|
||||
import { Button } from "./Button";
|
||||
|
||||
/*
|
||||
* Editing a plan changes what every future customer gets, so the confirmation
|
||||
* names each field rather than asking "are you sure". Existing licences
|
||||
* snapshotted their plan at issue time and are genuinely unaffected — saying so
|
||||
* is what stops a well-meaning edit being followed by a panicked reissue.
|
||||
*/
|
||||
export function ConfirmPlanChange({
|
||||
plan,
|
||||
next,
|
||||
issuedCount,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: {
|
||||
plan: Plan;
|
||||
next: Plan;
|
||||
issuedCount: number;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const rows: { field: string; was: string; now: string }[] = [];
|
||||
if (plan.limits.max_servers !== next.limits.max_servers)
|
||||
rows.push({
|
||||
field: "max_servers",
|
||||
was: limitLabel(plan.limits.max_servers),
|
||||
now: limitLabel(next.limits.max_servers),
|
||||
});
|
||||
if (plan.limits.max_secret_groups !== next.limits.max_secret_groups)
|
||||
rows.push({
|
||||
field: "max_secret_groups",
|
||||
was: limitLabel(plan.limits.max_secret_groups),
|
||||
now: limitLabel(next.limits.max_secret_groups),
|
||||
});
|
||||
if (plan.limits.max_channels !== next.limits.max_channels)
|
||||
rows.push({
|
||||
field: "max_channels",
|
||||
was: limitLabel(plan.limits.max_channels),
|
||||
now: limitLabel(next.limits.max_channels),
|
||||
});
|
||||
if (plan.features.join(",") !== next.features.join(","))
|
||||
rows.push({
|
||||
field: "features",
|
||||
was: plan.features.join(", ") || "none",
|
||||
now: next.features.join(", ") || "none",
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="grid max-w-xl gap-3 rounded border border-warn bg-panel p-5">
|
||||
<h2 className="text-xl">Change what {plan.name} grants?</h2>
|
||||
<ul className="grid gap-1 font-mono text-[0.82rem]">
|
||||
{rows.map((r) => (
|
||||
<li key={r.field} className="flex flex-wrap gap-2">
|
||||
<span className="text-ink-3">{r.field}</span>
|
||||
<span className="text-ink-3 line-through">{r.was}</span>
|
||||
<span className="font-semibold text-ink">→ {r.now}</span>
|
||||
</li>
|
||||
))}
|
||||
{rows.length === 0 && <li className="text-ink-3">Nothing would change.</li>}
|
||||
</ul>
|
||||
<p className="text-[0.82rem] text-ink-3">
|
||||
This applies to licences issued from now on. The {issuedCount} licences already
|
||||
issued keep what they were signed with until each is reissued.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button type="button" onClick={onConfirm}>
|
||||
Change plan
|
||||
</Button>
|
||||
<Button type="button" variant="line" onClick={onCancel}>
|
||||
Keep as is
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Sandbox is hatched as well as coloured, so it survives a colourblind reader
|
||||
* and a glance. It sits in the same place on every screen: issuing against the
|
||||
* wrong environment should feel wrong before you click.
|
||||
*/
|
||||
const ENV = process.env.NEXT_PUBLIC_ADMIN_ENV === "sandbox" ? "sandbox" : "production";
|
||||
|
||||
export function EnvBadge() {
|
||||
const sandbox = ENV === "sandbox";
|
||||
return (
|
||||
<span
|
||||
className={
|
||||
sandbox
|
||||
? "inline-flex items-center gap-2 rounded-sm border border-warn px-2 py-1 font-mono text-[0.72rem] uppercase tracking-[0.1em] text-ink [background-image:repeating-linear-gradient(-45deg,var(--accent-wash)_0_6px,transparent_6px_12px)]"
|
||||
: "inline-flex items-center gap-2 rounded-sm bg-accent px-2 py-1 font-mono text-[0.72rem] uppercase tracking-[0.1em] text-accent-ink"
|
||||
}
|
||||
>
|
||||
<i className="h-1.5 w-1.5 shrink-0 rounded-full bg-current" />
|
||||
{sandbox ? "Sandbox" : "Production"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export function Field({
|
||||
label,
|
||||
hint,
|
||||
error,
|
||||
...input
|
||||
}: React.InputHTMLAttributes<HTMLInputElement> & {
|
||||
label: string;
|
||||
hint?: React.ReactNode;
|
||||
error?: string;
|
||||
}) {
|
||||
return (
|
||||
<label className="grid max-w-md gap-1.5">
|
||||
<span className="font-mono text-[0.72rem] uppercase tracking-[0.1em] text-ink-3">
|
||||
{label}
|
||||
</span>
|
||||
<input
|
||||
{...input}
|
||||
className="rounded border border-rule bg-panel-2 px-2.5 py-2 font-mono text-ink"
|
||||
/>
|
||||
{error ? (
|
||||
<span className="text-[0.82rem] text-expired">{error}</span>
|
||||
) : hint ? (
|
||||
<span className="text-[0.82rem] text-ink-3">{hint}</span>
|
||||
) : null}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import Link from "next/link";
|
||||
import clsx from "clsx";
|
||||
import type { Instance, License } from "@/lib/api";
|
||||
import { daysRemaining, formatDate, licenceState } from "@/lib/format";
|
||||
import { StatePill } from "./StatePill";
|
||||
|
||||
const STRIPE = {
|
||||
valid: "before:bg-valid",
|
||||
warn: "before:bg-warn",
|
||||
expired: "before:bg-expired",
|
||||
none: "before:bg-accent",
|
||||
} as const;
|
||||
|
||||
export function InstanceCard({ instance, license }: { instance: Instance; license?: License }) {
|
||||
const state = licenceState(license?.expires_at, Boolean(license));
|
||||
const days = license ? daysRemaining(license.expires_at) : 0;
|
||||
const cloud = instance.deployment === "cloud";
|
||||
|
||||
return (
|
||||
<article
|
||||
className={clsx(
|
||||
"relative grid gap-3 rounded border border-rule bg-panel p-4 pl-5",
|
||||
"before:absolute before:inset-y-0 before:left-0 before:w-1 before:content-['']",
|
||||
STRIPE[state],
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="text-lg">{instance.name || "Unnamed instance"}</h3>
|
||||
<p className="font-mono text-[0.72rem] uppercase tracking-[0.1em] text-ink-3">
|
||||
{cloud ? "Cloud" : "Self-hosted"}
|
||||
{instance.tier ? ` · ${instance.tier.replace("_", " ")}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
<StatePill state={state} />
|
||||
</div>
|
||||
|
||||
{state === "expired" && (
|
||||
<p className="text-[0.82rem] text-ink-2">
|
||||
Servers and monitors are still running, and your agents keep their keys. Changes
|
||||
are disabled until you renew.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{state === "none" && (
|
||||
<p className="text-[0.82rem] text-ink-2">
|
||||
You have paid for this but it is not attached to an install yet, so no licence
|
||||
has been issued. Linking takes a minute.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{license && state !== "expired" && (
|
||||
<div className="grid gap-1 font-mono text-[0.82rem] tabular-nums text-ink-2">
|
||||
<span>{days} days remaining</span>
|
||||
<div className="h-[3px] overflow-hidden rounded-sm bg-rule-soft">
|
||||
<div
|
||||
className={clsx("h-full", state === "warn" ? "bg-warn" : "bg-valid")}
|
||||
style={{ width: `${Math.max(2, Math.min(100, (days / 365) * 100))}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span>Renews {formatDate(license.expires_at)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{state === "none" ? (
|
||||
<Link
|
||||
href="/instances/link"
|
||||
className="justify-self-start text-[0.82rem] font-semibold text-accent underline"
|
||||
>
|
||||
Link an install
|
||||
</Link>
|
||||
) : cloud && instance.slug ? (
|
||||
<a
|
||||
href={`https://${instance.slug}.vantage.hostxtra.co.uk`}
|
||||
className="justify-self-start text-[0.82rem] font-semibold text-accent underline"
|
||||
>
|
||||
Open {instance.slug}.vantage.hostxtra.co.uk
|
||||
</a>
|
||||
) : (
|
||||
<Link
|
||||
href={`/instances/${instance.instance_id}`}
|
||||
className="justify-self-start text-[0.82rem] font-semibold text-accent underline"
|
||||
>
|
||||
{state === "expired" ? "Renew and download" : "Licence and download"}
|
||||
</Link>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import clsx from "clsx";
|
||||
import type { License } from "@/lib/api";
|
||||
import { formatDate, formatStamp, limitLabel } from "@/lib/format";
|
||||
|
||||
const REASON: Record<License["reason"], string> = {
|
||||
new: "New",
|
||||
renewal: "Renewal",
|
||||
tier_change: "Tier change",
|
||||
relink: "Relink",
|
||||
manual: "Manual",
|
||||
};
|
||||
|
||||
/*
|
||||
* Licences are append-only: a renewal supersedes its predecessor rather than
|
||||
* replacing it. So this is a ledger, not a table. Superseded rows stay visible
|
||||
* and are overprinted the way a cancelled instrument is — hiding them would
|
||||
* destroy the only record of why an instance stopped working on a given date.
|
||||
*/
|
||||
export function Ledger({ licenses }: { licenses: License[] }) {
|
||||
if (licenses.length === 0) {
|
||||
return (
|
||||
<p className="text-ink-2">
|
||||
No licence has ever been issued for this instance, so it is read-only.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="grid">
|
||||
{licenses.map((l) => {
|
||||
const dead = Boolean(l.superseded_by);
|
||||
return (
|
||||
<li
|
||||
key={l.license_id}
|
||||
className={clsx(
|
||||
"grid gap-4 border-b border-rule-soft py-4 last:border-0 sm:grid-cols-[9.5rem_1fr]",
|
||||
dead && "text-ink-3",
|
||||
)}
|
||||
>
|
||||
<div className="font-mono text-[0.72rem] tabular-nums text-ink-3">
|
||||
<b
|
||||
className={clsx(
|
||||
"block text-[0.82rem] font-semibold",
|
||||
dead ? "text-ink-3" : "text-ink",
|
||||
)}
|
||||
>
|
||||
{formatDate(l.issued_at)}
|
||||
</b>
|
||||
{formatStamp(l.issued_at)}
|
||||
</div>
|
||||
<div className="grid justify-items-start gap-1.5">
|
||||
{dead && (
|
||||
<span className="-rotate-2 rounded-sm border-2 border-archival px-1.5 py-0.5 font-mono text-[0.72rem] uppercase tracking-[0.18em] text-archival opacity-75">
|
||||
Superseded
|
||||
</span>
|
||||
)}
|
||||
<p className="flex flex-wrap items-center gap-2 font-semibold">
|
||||
{l.tier.replace("_", " ")}
|
||||
<span className="rounded-sm border border-rule px-1.5 py-0.5 font-mono text-[0.72rem] font-normal uppercase tracking-[0.09em] text-accent">
|
||||
{REASON[l.reason]}
|
||||
</span>
|
||||
</p>
|
||||
<p className="font-mono text-[0.72rem] tabular-nums text-ink-3">
|
||||
{l.license_id.slice(0, 8)} · expires {formatDate(l.expires_at)} ·{" "}
|
||||
{limitLabel(l.limits.max_servers)} servers · issued by {l.issued_by}
|
||||
{l.superseded_by && (
|
||||
<>
|
||||
{" "}
|
||||
· replaced by{" "}
|
||||
<span className="text-accent underline">
|
||||
{l.superseded_by.slice(0, 8)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "./Button";
|
||||
|
||||
/*
|
||||
* A licence blob is signed public data, not a secret — it is useless on any
|
||||
* instance other than the one it names. So it is safe to show inline, and
|
||||
* showing it is what stops a blocked download from blocking a paying customer.
|
||||
*/
|
||||
export function LicenceDelivery({
|
||||
instanceId,
|
||||
blob,
|
||||
downloadUrl,
|
||||
}: {
|
||||
instanceId: string;
|
||||
blob: string;
|
||||
downloadUrl: string;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
async function copy() {
|
||||
await navigator.clipboard.writeText(blob);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
|
||||
const steps = [
|
||||
<>
|
||||
Open <code className="rounded-sm bg-accent-wash px-1">Settings → Licence</code> on your
|
||||
install.
|
||||
</>,
|
||||
<>Paste the licence into the box and save.</>,
|
||||
<>
|
||||
The page reports <code className="rounded-sm bg-accent-wash px-1">Valid</code> straight
|
||||
away — no restart.
|
||||
</>,
|
||||
];
|
||||
|
||||
return (
|
||||
<section className="grid gap-3">
|
||||
<h2 className="text-xl">Your licence</h2>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<a
|
||||
href={downloadUrl}
|
||||
download={`vantage-${instanceId}.lic`}
|
||||
className="inline-flex items-center gap-2 rounded border border-accent bg-accent px-4 py-2.5 text-[0.94rem] font-semibold text-accent-ink"
|
||||
>
|
||||
Download licence
|
||||
</a>
|
||||
<Button variant="line" type="button" onClick={copy}>
|
||||
{copied ? "Copied" : "Copy to clipboard"}
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="overflow-x-auto rounded border border-dashed border-rule bg-panel-2 p-3 font-mono text-[0.72rem] text-ink-2">
|
||||
{blob}
|
||||
</pre>
|
||||
<ol className="grid gap-2">
|
||||
{steps.map((body, i) => (
|
||||
<li
|
||||
key={i}
|
||||
className="grid grid-cols-[1.6rem_1fr] gap-3 text-[0.82rem] text-ink-2"
|
||||
>
|
||||
<span className="h-6 rounded-sm border border-rule text-center font-mono text-[0.72rem] leading-6 text-accent">
|
||||
{i + 1}
|
||||
</span>
|
||||
<span>{body}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* The deployment failure this repo makes most often, made legible. It names the
|
||||
* variable, the value baked in, and both reasons it fails — unreachable from
|
||||
* the browser, or missing from admin's ADMIN_ORIGIN.
|
||||
*/
|
||||
export function NotConnectedPanel({ url }: { url: string }) {
|
||||
return (
|
||||
<div className="grid max-w-2xl gap-3 rounded border border-expired bg-panel p-5">
|
||||
<h2 className="text-xl text-expired">Not connected to the licensing service</h2>
|
||||
{url ? (
|
||||
<p className="text-ink-2">
|
||||
This build points at <code className="text-ink">ADMIN_API_URL</code> ={" "}
|
||||
<code className="text-ink">{url}</code>, which did not respond.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-ink-2">
|
||||
<code className="text-ink">ADMIN_API_URL</code> was not set when this app was
|
||||
built, so there is nowhere to send requests.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-[0.82rem] text-ink-3">
|
||||
The value is baked in when the image is built and has to be reachable from your
|
||||
browser, not just from the server. It also has to appear in the licensing
|
||||
service’s <code>ADMIN_ORIGIN</code>, or the browser blocks every request.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { queryClient } from "@/lib/query-client";
|
||||
|
||||
export function Providers({ children }: { children: React.ReactNode }) {
|
||||
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import Link from "next/link";
|
||||
import clsx from "clsx";
|
||||
|
||||
const TONE = {
|
||||
expired: "border-l-expired text-expired",
|
||||
warn: "border-l-warn text-warn",
|
||||
accent: "border-l-accent text-accent",
|
||||
} as const;
|
||||
|
||||
export function Queue({
|
||||
title,
|
||||
count,
|
||||
tone,
|
||||
items,
|
||||
}: {
|
||||
title: string;
|
||||
count: number;
|
||||
tone: keyof typeof TONE;
|
||||
items: { label: string; href: string; meta: string }[];
|
||||
}) {
|
||||
return (
|
||||
<section
|
||||
className={clsx(
|
||||
"grid gap-2 rounded border border-l-4 border-rule bg-panel p-4",
|
||||
TONE[tone],
|
||||
)}
|
||||
>
|
||||
<h2 className="font-mono text-[0.72rem] font-normal uppercase tracking-[0.1em] text-ink-3">
|
||||
{title}
|
||||
</h2>
|
||||
<p className="text-3xl font-extrabold leading-none tabular-nums tracking-[-0.03em]">
|
||||
{count}
|
||||
</p>
|
||||
{items.length === 0 ? (
|
||||
<p className="text-[0.72rem] text-ink-3">Nothing to do here.</p>
|
||||
) : (
|
||||
<ul className="grid gap-1">
|
||||
{items.map((i) => (
|
||||
<li
|
||||
key={i.href}
|
||||
className="flex justify-between gap-2 font-mono text-[0.72rem] text-ink-2"
|
||||
>
|
||||
<Link href={i.href} className="text-accent underline">
|
||||
{i.label}
|
||||
</Link>
|
||||
<span className="tabular-nums">{i.meta}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "./Button";
|
||||
import { Field } from "./Field";
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function RelinkPanel({
|
||||
used,
|
||||
max,
|
||||
onRelink,
|
||||
error,
|
||||
}: {
|
||||
instanceId: string;
|
||||
used: number;
|
||||
max: number;
|
||||
onRelink: (newId: string) => void;
|
||||
error?: string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [value, setValue] = useState("");
|
||||
const remaining = Math.max(0, max - used);
|
||||
const exhausted = remaining === 0;
|
||||
|
||||
return (
|
||||
<section className="grid gap-3 border-t border-rule-soft pt-5">
|
||||
<h2 className="text-xl">Moved to a new server?</h2>
|
||||
<p className="text-[0.82rem] text-ink-2">
|
||||
Relinking issues a replacement licence for the new install, covering the rest of
|
||||
your current term.
|
||||
</p>
|
||||
{open && !exhausted && (
|
||||
<Field
|
||||
label="New instance ID"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
error={error}
|
||||
hint="From Settings → Licence on the new install."
|
||||
/>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="line"
|
||||
disabled={exhausted || (open && !UUID_RE.test(value.trim()))}
|
||||
onClick={() => (open ? onRelink(value.trim()) : setOpen(true))}
|
||||
>
|
||||
Relink to a new install
|
||||
</Button>
|
||||
<span className="text-[0.82rem] text-ink-3">
|
||||
{exhausted
|
||||
? "You have used every relink for this term — contact support and we will sort it out."
|
||||
: `${remaining} of ${max} relinks left this term`}
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import clsx from "clsx";
|
||||
import type { LicenceState } from "@/lib/format";
|
||||
|
||||
const LABEL: Record<LicenceState, string> = {
|
||||
valid: "Valid",
|
||||
warn: "Expiring",
|
||||
expired: "Expired",
|
||||
none: "Awaiting link",
|
||||
};
|
||||
|
||||
/*
|
||||
* State reads three ways: this pill's colour, the pill's SHAPE, and the label.
|
||||
* Colour alone would fail a colourblind reader on the one screen where getting
|
||||
* it wrong costs money.
|
||||
*/
|
||||
const SHAPE: Record<LicenceState, string> = {
|
||||
valid: "rounded-full",
|
||||
warn: "[clip-path:polygon(50%_0,100%_100%,0_100%)]",
|
||||
expired: "[clip-path:polygon(20%_0,80%_0,100%_20%,100%_80%,80%_100%,20%_100%,0_80%,0_20%)]",
|
||||
none: "rounded-none",
|
||||
};
|
||||
|
||||
const TONE: Record<LicenceState, string> = {
|
||||
valid: "border-valid text-valid",
|
||||
warn: "border-warn text-warn",
|
||||
expired: "border-expired text-expired",
|
||||
none: "border-accent text-accent",
|
||||
};
|
||||
|
||||
export function StatePill({ state }: { state: LicenceState }) {
|
||||
return (
|
||||
<span
|
||||
className={clsx(
|
||||
"inline-flex shrink-0 items-center gap-1.5 rounded-sm border bg-panel px-2 py-0.5 font-mono text-[0.72rem] uppercase tracking-[0.08em]",
|
||||
TONE[state],
|
||||
)}
|
||||
>
|
||||
<i className={clsx("h-1.5 w-1.5 shrink-0 bg-current", SHAPE[state])} />
|
||||
{LABEL[state]}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
/*
|
||||
* The typed client for the licensing service.
|
||||
*
|
||||
* The browser calls admin directly, so every request carries credentials and
|
||||
* every failure mode is one of three: the API is unreachable (NotConnected),
|
||||
* the caller is not signed in (ApiError 401, which layouts redirect on), or the
|
||||
* request was refused (ApiError with the backend's own message, which is
|
||||
* customer-facing and should be shown verbatim).
|
||||
*/
|
||||
|
||||
export const API_BASE = (process.env.NEXT_PUBLIC_ADMIN_API_URL ?? "").replace(/\/$/, "");
|
||||
|
||||
export class NotConnected extends Error {
|
||||
constructor() {
|
||||
super("not connected");
|
||||
this.name = "NotConnected";
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function req<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
if (!API_BASE) throw new NotConnected();
|
||||
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${API_BASE}${path}`, {
|
||||
...init,
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },
|
||||
});
|
||||
} catch {
|
||||
// Network-level failure, DNS, or a CORS preflight the browser refused.
|
||||
throw new NotConnected();
|
||||
}
|
||||
|
||||
if (res.status === 204) return undefined as T;
|
||||
|
||||
const body = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
throw new ApiError(res.status, body?.error ?? `request failed (${res.status})`);
|
||||
}
|
||||
return body as T;
|
||||
}
|
||||
|
||||
const post = <T,>(path: string, payload?: unknown) =>
|
||||
req<T>(path, { method: "POST", body: payload ? JSON.stringify(payload) : undefined });
|
||||
|
||||
// --- types ---------------------------------------------------------------
|
||||
|
||||
export type Deployment = "cloud" | "self_hosted";
|
||||
export type Tier = "free" | "professional" | "self_hosted";
|
||||
export type InstanceStatus = "awaiting_link" | "active" | "lapsed" | "cancelled";
|
||||
|
||||
export interface Session {
|
||||
kind: "staff" | "customer";
|
||||
email: string;
|
||||
account_id?: string;
|
||||
}
|
||||
|
||||
export interface Limits {
|
||||
max_servers: number;
|
||||
max_secret_groups: number;
|
||||
max_channels: number;
|
||||
}
|
||||
|
||||
export interface Account {
|
||||
account_id: string;
|
||||
name: string;
|
||||
billing_email: string;
|
||||
paddle_customer_id?: string;
|
||||
status: "active" | "suspended";
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Instance {
|
||||
instance_id: string;
|
||||
account_id: string;
|
||||
name: string;
|
||||
slug?: string;
|
||||
deployment: Deployment;
|
||||
tier?: Tier;
|
||||
status: InstanceStatus;
|
||||
current_license?: string;
|
||||
relink_count: number;
|
||||
inject_failed_at?: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface License {
|
||||
license_id: string;
|
||||
instance_id: string;
|
||||
account_id: string;
|
||||
tier: Tier;
|
||||
deployment: Deployment;
|
||||
limits: Limits;
|
||||
features: string[];
|
||||
issued_at: string;
|
||||
expires_at: string;
|
||||
superseded_by?: string;
|
||||
issued_by: string;
|
||||
reason: "new" | "renewal" | "tier_change" | "relink" | "manual";
|
||||
}
|
||||
|
||||
export interface Subscription {
|
||||
subscription_id: string;
|
||||
account_id: string;
|
||||
instance_id?: string;
|
||||
tier: Tier;
|
||||
term: string;
|
||||
status: string;
|
||||
current_period_end: string;
|
||||
}
|
||||
|
||||
export interface Plan {
|
||||
tier: Tier;
|
||||
name: string;
|
||||
deployment: Deployment;
|
||||
limits: Limits;
|
||||
features: string[];
|
||||
paddle_product_id?: string;
|
||||
paddle_price_ids?: Record<string, string>;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface CustomerUser {
|
||||
user_id: string;
|
||||
account_id: string;
|
||||
email: string;
|
||||
verified_at?: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AuditEntry {
|
||||
actor: string;
|
||||
action: string;
|
||||
account_id?: string;
|
||||
target?: string;
|
||||
detail?: string;
|
||||
ip?: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AccountResponse {
|
||||
account: Account;
|
||||
instances: Instance[];
|
||||
max_relinks: number;
|
||||
}
|
||||
|
||||
export interface StaffAccountResponse {
|
||||
account: Account;
|
||||
instances: Instance[];
|
||||
subscriptions: Subscription[];
|
||||
users: CustomerUser[];
|
||||
audit: AuditEntry[];
|
||||
}
|
||||
|
||||
export type InjectionState = "current" | "stale" | "missing" | "none_issued";
|
||||
|
||||
export interface StaffInstanceResponse {
|
||||
instance: Instance;
|
||||
account: Account;
|
||||
licenses: License[];
|
||||
injection: { applicable: boolean; state?: InjectionState; failed_at?: string | null };
|
||||
}
|
||||
|
||||
// --- calls ---------------------------------------------------------------
|
||||
|
||||
export const api = {
|
||||
me: () => req<Session>("/auth/me"),
|
||||
login: (email: string, password: string) => post<Session>("/auth/login", { email, password }),
|
||||
staffLogin: (email: string, password: string) =>
|
||||
post<Session>("/auth/staff/login", { email, password }),
|
||||
logout: () => post<{ ok: boolean }>("/auth/logout"),
|
||||
signup: (payload: { name: string; email: string; password: string; website?: string }) =>
|
||||
post<{ pending: boolean }>("/auth/signup", payload),
|
||||
verify: (token: string) =>
|
||||
req<{ verified: boolean }>(`/auth/verify?token=${encodeURIComponent(token)}`),
|
||||
|
||||
account: () => req<AccountResponse>("/api/account"),
|
||||
link: (instance_id: string, name: string) =>
|
||||
post<Instance>("/api/instances/link", { instance_id, name }),
|
||||
relink: (id: string, instance_id: string) =>
|
||||
post<License>(`/api/instances/${id}/relink`, { instance_id }),
|
||||
license: (id: string) => req<License & { blob?: string }>(`/api/instances/${id}/license`),
|
||||
licenseBlobUrl: (id: string) => `${API_BASE}/api/instances/${id}/license/download`,
|
||||
subscriptions: () => req<Subscription[]>("/api/subscriptions"),
|
||||
|
||||
staff: {
|
||||
accounts: (q?: string) =>
|
||||
req<Account[]>(`/api/staff/accounts${q ? `?q=${encodeURIComponent(q)}` : ""}`),
|
||||
account: (id: string) => req<StaffAccountResponse>(`/api/staff/accounts/${id}`),
|
||||
instances: (params?: Record<string, string>) =>
|
||||
req<Instance[]>(
|
||||
`/api/staff/instances${params ? `?${new URLSearchParams(params)}` : ""}`,
|
||||
),
|
||||
instance: (id: string) => req<StaffInstanceResponse>(`/api/staff/instances/${id}`),
|
||||
issue: (id: string, payload: { tier: Tier; term?: string; reason?: string }) =>
|
||||
post<License>(`/api/staff/instances/${id}/issue`, payload),
|
||||
relink: (id: string, instance_id: string) =>
|
||||
post<License>(`/api/staff/instances/${id}/relink`, { instance_id }),
|
||||
licenses: (params?: Record<string, string>) =>
|
||||
req<License[]>(`/api/staff/licenses${params ? `?${new URLSearchParams(params)}` : ""}`),
|
||||
plans: () => req<Plan[]>("/api/staff/plans"),
|
||||
updatePlan: (tier: Tier, plan: Omit<Plan, "tier" | "deployment">) =>
|
||||
req<{ updated: boolean }>(`/api/staff/plans/${tier}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(plan),
|
||||
}),
|
||||
audit: (accountId?: string) =>
|
||||
req<AuditEntry[]>(`/api/staff/audit${accountId ? `?account_id=${accountId}` : ""}`),
|
||||
injectionHealth: () =>
|
||||
req<{ failed: Instance[]; count: number }>("/api/staff/health/injection"),
|
||||
subscriptions: (status?: string) =>
|
||||
req<Subscription[]>(`/api/staff/subscriptions${status ? `?status=${status}` : ""}`),
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
export type LicenceState = "valid" | "warn" | "expired" | "none";
|
||||
|
||||
/** Amber inside 14 days, matching the window staff chase renewals on. */
|
||||
export const EXPIRY_WARNING_DAYS = 14;
|
||||
|
||||
export function daysRemaining(iso: string): number {
|
||||
const ms = new Date(iso).getTime() - Date.now();
|
||||
return Math.ceil(ms / 86_400_000);
|
||||
}
|
||||
|
||||
export function licenceState(expiresAt: string | undefined, hasLicence: boolean): LicenceState {
|
||||
if (!hasLicence || !expiresAt) return "none";
|
||||
const days = daysRemaining(expiresAt);
|
||||
if (days <= 0) return "expired";
|
||||
if (days <= EXPIRY_WARNING_DAYS) return "warn";
|
||||
return "valid";
|
||||
}
|
||||
|
||||
export function formatDate(iso: string): string {
|
||||
return new Date(iso).toLocaleDateString("en-GB", {
|
||||
day: "numeric",
|
||||
month: "short",
|
||||
year: "numeric",
|
||||
});
|
||||
}
|
||||
|
||||
export function formatStamp(iso: string): string {
|
||||
return `${new Date(iso).toISOString().slice(11, 19)} UTC`;
|
||||
}
|
||||
|
||||
export function limitLabel(n: number): string {
|
||||
return n === -1 ? "unlimited" : String(n);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { ApiError, NotConnected } from "./api";
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
// Retrying a 401 or a missing API URL just delays the redirect and
|
||||
// the not-connected panel.
|
||||
retry: (count, error) =>
|
||||
error instanceof NotConnected || error instanceof ApiError ? false : count < 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { API_BASE, ApiError, NotConnected, api, type Session } from "./api";
|
||||
import { NotConnectedPanel } from "@/components/NotConnected";
|
||||
|
||||
export function useSession() {
|
||||
const { data, error, isLoading } = useQuery<Session>({
|
||||
queryKey: ["me"],
|
||||
queryFn: api.me,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
return { session: data, error, isLoading };
|
||||
}
|
||||
|
||||
/*
|
||||
* The route-group guard. This is UX, not security: admin enforces the same
|
||||
* boundary with RequireStaff/RequireCustomer and returns 404 rather than 403
|
||||
* for another account's data. A customer hitting a staff route is redirected
|
||||
* rather than shown a refusal, because there is nothing to tell them about.
|
||||
*/
|
||||
export function RequireKind({
|
||||
kind,
|
||||
children,
|
||||
}: {
|
||||
kind: Session["kind"];
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const { session, error, isLoading } = useSession();
|
||||
|
||||
useEffect(() => {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
router.replace("/login");
|
||||
return;
|
||||
}
|
||||
if (session && session.kind !== kind) {
|
||||
router.replace(session.kind === "staff" ? "/staff" : "/");
|
||||
}
|
||||
}, [error, session, kind, router]);
|
||||
|
||||
if (error instanceof NotConnected) return <NotConnectedPanel url={API_BASE} />;
|
||||
if (isLoading || !session || session.kind !== kind) return null;
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
/*
|
||||
* Unlike web/, this app does NOT proxy /api through a rewrite. The browser
|
||||
* calls admin directly, so NEXT_PUBLIC_ADMIN_API_URL must be reachable from the
|
||||
* browser and must appear in admin's ADMIN_ORIGIN. lib/api.ts renders an
|
||||
* explicit not-connected state when it is not.
|
||||
*/
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
Generated
+6868
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "vantage-adminsite",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "16.2.9",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"@tanstack/react-query": "^5.51.1",
|
||||
"clsx": "^2.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.11",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"eslint": "^9.0.0",
|
||||
"eslint-config-next": "16.2.9",
|
||||
"postcss": "^8.4.39",
|
||||
"tailwindcss": "^3.4.6",
|
||||
"typescript": "^5.5.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { Config } from "tailwindcss";
|
||||
|
||||
/*
|
||||
* Tokens are shared with site/ — same names, same values, copied verbatim into
|
||||
* app/globals.css. Nothing here may hold a hex value: if a colour needs to
|
||||
* change it changes in globals.css, in both apps, in one commit.
|
||||
*
|
||||
* The semantic three are aliased rather than renamed. site/ calls them up,
|
||||
* down and pend because it shows monitor state; this app calls them valid,
|
||||
* expired and warn because it shows licence state. Same colours, honest names
|
||||
* on both sides.
|
||||
*/
|
||||
const config: Config = {
|
||||
content: ["./app/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}"],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
ground: "var(--ground)",
|
||||
panel: "var(--panel)",
|
||||
"panel-2": "var(--panel-2)",
|
||||
ink: "var(--ink)",
|
||||
"ink-2": "var(--ink-2)",
|
||||
"ink-3": "var(--ink-3)",
|
||||
rule: "var(--rule)",
|
||||
"rule-soft": "var(--rule-soft)",
|
||||
accent: "var(--accent)",
|
||||
"accent-ink": "var(--accent-ink)",
|
||||
"accent-wash": "var(--accent-wash)",
|
||||
valid: "var(--up)",
|
||||
warn: "var(--pend)",
|
||||
expired: "var(--down)",
|
||||
archival: "var(--ink-3)",
|
||||
},
|
||||
fontFamily: {
|
||||
sans: ["ui-sans-serif", "system-ui", "-apple-system", "Segoe UI", "Roboto", "Helvetica Neue", "Arial", "sans-serif"],
|
||||
mono: ["ui-monospace", "Cascadia Mono", "SF Mono", "JetBrains Mono", "Menlo", "Consolas", "monospace"],
|
||||
},
|
||||
// site/ uses 4px on panels and buttons, 2px on focus rings.
|
||||
borderRadius: { DEFAULT: "4px" },
|
||||
maxWidth: { rail: "1200px" },
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -81,6 +81,25 @@ vantage/
|
||||
│ ├── models/ # mirrors server org/user + pending signup
|
||||
│ ├── provision/ # slug rules mirrored from the control plane
|
||||
│ └── store/ # mongo: pending signups, org/user creation
|
||||
├── admin/ # licensing authority: the only signer
|
||||
│ ├── cmd/main.go # boot: two Mongo connections, reconciler, HTTP
|
||||
│ ├── cmd/adminctl/ # staff-add; deliberately has no HTTP surface
|
||||
│ └── internal/
|
||||
│ ├── api/ # customer + staff handlers, route table
|
||||
│ ├── auth/ # staff, cloud-owner and self-hosted sessions
|
||||
│ ├── inject/ # the ONE write path into the control plane
|
||||
│ ├── licensing/ # Issue, LinkInstance, Relink
|
||||
│ ├── mail/ # verification and licence delivery
|
||||
│ └── models/ # accounts, instances, licences, plans
|
||||
├── adminsite/ # staff + customer console (vantage-hq)
|
||||
│ ├── app/(customer)/ # overview, instance, link, billing
|
||||
│ ├── app/(staff)/staff/ # operations, accounts, licences, plans, audit
|
||||
│ ├── components/ # InstanceCard, Ledger, Queue, EnvBadge
|
||||
│ └── lib/ # api client, session guards, formatters
|
||||
├── shared/ # imported by server, sitesvc and admin
|
||||
│ ├── license/ # payload, sign, verify, trusted keys, plans
|
||||
│ ├── models/ # Instance, User, Settings
|
||||
│ └── cmd/lkctl/ # issue and inspect licences by hand
|
||||
├── proto/vantage/v1/vantage.proto
|
||||
├── installer/ # Windows: setup.ps1, nssm.exe, WiX .wxs
|
||||
├── deploy/ # docker-compose.yml, agent.service
|
||||
@@ -127,7 +146,9 @@ Agents report CPU/memory/swap/partitions/kernel — metrics every 30s, full stat
|
||||
|
||||
### Marketing site and sitesvc
|
||||
|
||||
`site/` is a separate Next.js app built exactly like `web/` — `output: "standalone"`, run by Node in a `node:26-alpine` image, listening on `3000` and published as `3001`. Both of its forms post to `sitesvc`; the control plane is not involved and has no public signup endpoint.
|
||||
`site/` is a separate Next.js app built exactly like `web/` — `output: "standalone"`, run by Node in a `node:26-alpine` image, listening on `3000` and published as `3003`. Both of its forms post to `sitesvc`; the control plane is not involved and has no public signup endpoint.
|
||||
|
||||
`adminsite/` is built the same way and published as `3004`, served at **`vantage-hq.hostxtra.co.uk`** — deliberately *outside* `*.vantage.hostxtra.co.uk`, because that namespace is per-tenant instance subdomains and `APP_ROOT_LABEL` resolves an org from the label before `vantage`. It shares `site/`'s design tokens verbatim (see Frontend below) and, unlike `web/`, does **not** proxy through a Next rewrite: the browser calls `admin` directly, so `ADMIN_API_URL` must be browser-reachable and listed in admin's `ADMIN_ORIGIN`. Authenticated requests work cross-origin only because both hosts share the registrable domain `hostxtra.co.uk`, which keeps `admin_session`'s `SameSite=Lax` cookie in play.
|
||||
|
||||
`sitesvc/` (port `8082`) owns both flows end to end:
|
||||
|
||||
@@ -245,6 +266,39 @@ org GET,POST /org/users · PUT /org/users/:id/role · DELETE /org/users
|
||||
|
||||
---
|
||||
|
||||
## Admin REST API (`admin`, :8083)
|
||||
|
||||
A separate service with its own session cookie (`admin_session`) and its own database. Unauthenticated:
|
||||
|
||||
```
|
||||
GET /healthz
|
||||
GET /auth/me # who am I; 401 drives the UI's redirects
|
||||
POST /auth/staff/login /auth/login /auth/logout
|
||||
POST /auth/signup # self-hosted only; honeypot + rate limited
|
||||
GET /auth/verify?token=…
|
||||
```
|
||||
|
||||
Customer-session (`/api`), every instance resolved through `ownedInstance`:
|
||||
|
||||
```
|
||||
GET /account # account, instances, max_relinks
|
||||
POST /instances/link · /instances/:id/relink
|
||||
GET /instances/:id/license · /instances/:id/license/download
|
||||
GET /subscriptions
|
||||
```
|
||||
|
||||
Staff-session (`/api/staff`):
|
||||
|
||||
```
|
||||
GET,POST /accounts · GET /accounts/:id # search by name, email, Paddle ID or instance UUID
|
||||
GET,POST /instances · GET /instances/:id # instance + account + licence history + injection state
|
||||
POST /instances/:id/issue · /instances/:id/relink
|
||||
GET /licenses · /subscriptions · /audit · /plans · PUT /plans/:tier
|
||||
GET /health/injection
|
||||
```
|
||||
|
||||
**Customer endpoints answer 404, never 403, for another account's resource** — a 403 confirms the resource exists. Route-group guards in `adminsite/` mirror this, but the backend is the layer that matters.
|
||||
|
||||
## MongoDB Collections
|
||||
|
||||
`servers` · `keys` · `assignments` · `orgs` · `users` · `org_oidc` · `settings` · `secrets` · `workflows` · `workflow_steps` · `workflow_runs` · `monitors` · `incidents` · `monitor_rollups` · `notification_channels` · `console_sessions` · `audit_logs` · `migrations`
|
||||
@@ -358,7 +412,9 @@ Windows: MSI built by CI (WiX), or `installer/setup.ps1` registering the agent a
|
||||
| `SITE_ORIGIN` | yes in practice | comma-separated allowed origins; unset refuses every cross-origin browser request |
|
||||
| `TRUST_PROXY` | no | only `true` behind a proxy that overwrites `X-Forwarded-For`, or clients spoof past the rate limiter |
|
||||
|
||||
`deploy/docker-compose.yml` runs four services: `redis`, `guacd`, `server` (8080 + 9090), `web` (3000). MongoDB is external. `deploy/docker-compose.site.yml` adds the public marketing site on `3001` and is only used on vantage.hostxtra.co.uk.
|
||||
`deploy/docker-compose.yml` runs four services: `redis`, `guacd`, `server` (8080 + 9090), `web` (3000). MongoDB is external. `deploy/docker-compose.site.yml` adds four more — `site` (3003), `sitesvc` (8082), `admin` (8083) and `adminsite` (3004) — and is only used on vantage.hostxtra.co.uk.
|
||||
|
||||
`LICENSE_SIGNING_KEY` appears in **exactly one service in exactly one compose file**: `admin` in `docker-compose.site.yml`. It must never be added to `server`, and the self-hosted `docker-compose.yml` must never mention `admin` or `adminsite` at all. Admin uses an external Redis via `REDIS_ADDR`/`REDIS_USERNAME`/`REDIS_PASSWORD`; the base compose hardcodes `redis:6379` for `server`, so those variables reach admin only.
|
||||
|
||||
---
|
||||
|
||||
@@ -380,6 +436,18 @@ Windows: MSI built by CI (WiX), or `installer/setup.ps1` registering the agent a
|
||||
|
||||
Next.js 16 (App Router) + React 18, Tailwind 3, TanStack Query. Guacamole client bundled locally in `web/lib/guacamole-common.js`.
|
||||
|
||||
There are **three separate visual identities**, and the split is deliberate:
|
||||
|
||||
| App | Ground | Accent | Themes |
|
||||
| --- | --- | --- | --- |
|
||||
| `web/` | `#0f1117` | indigo `#6366f1` | dark only, locked |
|
||||
| `site/` | token-based | brand navy `#0b2a58` / `#5b9be8` | light + dark |
|
||||
| `adminsite/` | **the same tokens as `site/`** | brand navy | light + dark, light default |
|
||||
|
||||
`adminsite/app/globals.css` holds `site/app/globals.css`'s token blocks **copied verbatim** — same names, same values. **Change them in both files in the same commit; nothing enforces the match automatically**, the same shape of hazard as sitesvc's mirrored slug rules. Tailwind in `adminsite/` maps `var(--…)` references only, so no component may carry a hex value. `site/` names the semantic three `--up`/`--pend`/`--down` for monitor state; `adminsite/` aliases them to `valid`/`warn`/`expired` for licence state — same colours.
|
||||
|
||||
`adminsite/` defaults to **light** on purpose: `web/` is locked to dark, and a staff member with both open should never mistake one for the other before clicking Reissue. In dark mode the shared accent lifts to `#5b9be8`, closer to web/'s indigo, so that distinction rests on the ground — do not make dark the default. Licence state never reads by colour alone: every pill carries a distinct shape and a text label.
|
||||
|
||||
| Route | Purpose |
|
||||
| --------------------------------------------------------------- | ----------------------------------------------------------------------- |
|
||||
| `/setup` | First-run bootstrap: create the first org and owner |
|
||||
@@ -411,7 +479,7 @@ GOOS=linux GOARCH=amd64 go build \
|
||||
|
||||
### `server-deploy.yml` — triggered on every push to `main`
|
||||
|
||||
Builds and pushes four images to the Gitea container registry: `server`, `web`, `site` and `sitesvc`.
|
||||
Builds and pushes six images to the Gitea container registry: `server`, `web`, `site`, `sitesvc`, `admin` and `adminsite`.
|
||||
|
||||
Note that despite the name, **this workflow does not deploy** — it only builds and pushes. There is no SSH step and no path filter; every push to `main` rebuilds all three images. Rolling them out is a separate manual step on the host:
|
||||
|
||||
@@ -439,6 +507,8 @@ git push origin main # server + web deploy
|
||||
| `API_URL` | Variable | baked into the `web` image at build time |
|
||||
| `SITE_API_URL` | Variable | **browser-reachable** sitesvc URL, baked into the `site` image. Required — if empty, both forms report "not connected" and submit nowhere. Must also be in sitesvc's `SITE_ORIGIN`. |
|
||||
| `SITE_CONTACT_EMAIL` | Variable | optional; address shown when a form is misconfigured |
|
||||
| `ADMIN_API_URL` | Variable | **browser-reachable** admin URL, baked into the `adminsite` image. Same footgun as `SITE_API_URL`: wrong here and every request fails at runtime with the not-connected panel. Must also be in admin's `ADMIN_ORIGIN`. |
|
||||
| `ADMIN_ENV` | Variable | `production` or `sandbox`; drives the persistent environment badge. Anything but `sandbox` reads as production. |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ services:
|
||||
image: gitea.hostxtra.co.uk/mrhid6/vantage/site:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- 3002:3000
|
||||
- 3003:3000
|
||||
depends_on:
|
||||
- sitesvc
|
||||
sitesvc:
|
||||
@@ -33,9 +33,9 @@ services:
|
||||
PORT: "8083"
|
||||
ADMIN_MONGO_URI: ${ADMIN_MONGO_URI:-}
|
||||
CONTROL_MONGO_URI: ${MONGO_URI:-}
|
||||
REDIS_ADDR: ${ADMIN_REDIS_ADDR:-10.10.10.2:6379}
|
||||
REDIS_USERNAME: ${ADMIN_REDIS_USERNAME:-}
|
||||
REDIS_PASSWORD: ${ADMIN_REDIS_PASSWORD:-}
|
||||
REDIS_ADDR: ${REDIS_ADDR:-10.10.10.2:6379}
|
||||
REDIS_USERNAME: ${REDIS_USERNAME:-}
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD:-}
|
||||
LICENSE_SIGNING_KEY: ${LICENSE_SIGNING_KEY:-}
|
||||
PUBLIC_URL: ${ADMIN_PUBLIC_URL:-}
|
||||
ADMIN_ORIGIN: ${ADMIN_ORIGIN:-}
|
||||
@@ -45,4 +45,17 @@ services:
|
||||
SMTP_USERNAME: ${SMTP_USERNAME:-}
|
||||
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
|
||||
SMTP_FROM: ${SMTP_FROM:-}
|
||||
|
||||
# The staff and customer console, served at vantage-hq.hostxtra.co.uk.
|
||||
# ADMIN_API_URL is baked into the image at build time, not read here, so
|
||||
# changing it needs a rebuild rather than a restart — and it must appear in
|
||||
# admin's ADMIN_ORIGIN above or the browser blocks every request.
|
||||
adminsite:
|
||||
image: gitea.hostxtra.co.uk/mrhid6/vantage/adminsite:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
# 3000 is web, 3003 is the marketing site; this takes 3004.
|
||||
- 3004:3000
|
||||
depends_on:
|
||||
- admin
|
||||
networks: {}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user