From 93825ebc64102cca6d50a40b44619cee051be7a0 Mon Sep 17 00:00:00 2001 From: amania-jailbreak Date: Wed, 5 Aug 2026 10:09:58 +0900 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=9B=9E=E3=82=B3=E3=83=9F=E3=83=83?= =?UTF-8?q?=E3=83=88:=20AltStore=20PAL=E5=90=91=E3=81=91ADP=E3=83=9B?= =?UTF-8?q?=E3=82=B9=E3=83=86=E3=82=A3=E3=83=B3=E3=82=B0SaaS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fastify API・Node Worker・PostgreSQL・S3互換ストレージ構成 - ADP ZIPのマルチパートアップロードとManifest検証(パストラバーサル・ZIP爆弾等を拒否) - manifest.json/signatureは再シリアライズせず元バイト列を保持 - Cloudflare風の運用向け管理ダッシュボード(shadcn/Radix・日本語UI・4ルート) 概要/Sources/アプリ/リリース + ルートランディングページ - 汎用OIDC SSO・Workspace単位の認可・demo mode - 匿名配布: /sources/{slug}/source.json, /artifacts/{releaseId}/manifest.json - Docker Compose対応 --- .env.example | 32 + .gitignore | 45 + .openai/hosting.json | 4 + README.md | 56 + app/chatgpt-auth.ts | 86 + app/dashboard/apps/page.tsx | 6 + app/dashboard/layout.tsx | 8 + app/dashboard/page.tsx | 6 + app/dashboard/releases/page.tsx | 6 + app/dashboard/settings/page.tsx | 7 + app/dashboard/sources/page.tsx | 6 + app/globals.css | 136 + app/layout.tsx | 16 + app/lib/dashboard.ts | 105 + app/page.tsx | 53 + app/sources/[slug]/PublicSourceView.tsx | 45 + app/sources/[slug]/page.tsx | 6 + apps/api/src/auth.ts | 126 + apps/api/src/config.ts | 49 + apps/api/src/manifest.ts | 183 + apps/api/src/migrate.ts | 11 + apps/api/src/processor.ts | 66 + apps/api/src/runtime.ts | 9 + apps/api/src/schema.ts | 115 + apps/api/src/server.ts | 301 + apps/api/src/storage.ts | 191 + apps/api/src/store.ts | 492 + apps/api/tsconfig.json | 8 + apps/worker/src/worker.ts | 30 + apps/worker/tsconfig.json | 8 + build/sites-vite-plugin.ts | 45 + components/altdock/admin-shell.tsx | 99 + components/altdock/dashboard-provider.tsx | 166 + components/altdock/dashboard-view.tsx | 159 + components/ui/badge.tsx | 7 + components/ui/button.tsx | 9 + components/ui/command.tsx | 28 + components/ui/dialog.tsx | 33 + components/ui/dropdown-menu.tsx | 19 + components/ui/tabs.tsx | 18 + components/ui/utils.ts | 7 + docker-compose.yml | 105 + eslint.config.mjs | 18 + next.config.ts | 7 + package-lock.json | 12538 ++++++++++++++++++++ package.json | 70 + packages/core/src/index.ts | 2 + packages/core/src/source.ts | 102 + packages/core/src/types.ts | 121 + postcss.config.mjs | 7 + public/favicon.svg | 4 + public/file.svg | 1 + public/globe.svg | 1 + public/window.svg | 1 + tests/api.test.mjs | 92 + tests/source.test.mjs | 54 + tsconfig.json | 34 + vite.config.ts | 59 + worker/index.ts | 47 + 59 files changed, 16065 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 .openai/hosting.json create mode 100644 README.md create mode 100644 app/chatgpt-auth.ts create mode 100644 app/dashboard/apps/page.tsx create mode 100644 app/dashboard/layout.tsx create mode 100644 app/dashboard/page.tsx create mode 100644 app/dashboard/releases/page.tsx create mode 100644 app/dashboard/settings/page.tsx create mode 100644 app/dashboard/sources/page.tsx create mode 100644 app/globals.css create mode 100644 app/layout.tsx create mode 100644 app/lib/dashboard.ts create mode 100644 app/page.tsx create mode 100644 app/sources/[slug]/PublicSourceView.tsx create mode 100644 app/sources/[slug]/page.tsx create mode 100644 apps/api/src/auth.ts create mode 100644 apps/api/src/config.ts create mode 100644 apps/api/src/manifest.ts create mode 100644 apps/api/src/migrate.ts create mode 100644 apps/api/src/processor.ts create mode 100644 apps/api/src/runtime.ts create mode 100644 apps/api/src/schema.ts create mode 100644 apps/api/src/server.ts create mode 100644 apps/api/src/storage.ts create mode 100644 apps/api/src/store.ts create mode 100644 apps/api/tsconfig.json create mode 100644 apps/worker/src/worker.ts create mode 100644 apps/worker/tsconfig.json create mode 100644 build/sites-vite-plugin.ts create mode 100644 components/altdock/admin-shell.tsx create mode 100644 components/altdock/dashboard-provider.tsx create mode 100644 components/altdock/dashboard-view.tsx create mode 100644 components/ui/badge.tsx create mode 100644 components/ui/button.tsx create mode 100644 components/ui/command.tsx create mode 100644 components/ui/dialog.tsx create mode 100644 components/ui/dropdown-menu.tsx create mode 100644 components/ui/tabs.tsx create mode 100644 components/ui/utils.ts create mode 100644 docker-compose.yml create mode 100644 eslint.config.mjs create mode 100644 next.config.ts create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 packages/core/src/index.ts create mode 100644 packages/core/src/source.ts create mode 100644 packages/core/src/types.ts create mode 100644 postcss.config.mjs create mode 100644 public/favicon.svg create mode 100644 public/file.svg create mode 100644 public/globe.svg create mode 100644 public/window.svg create mode 100644 tests/api.test.mjs create mode 100644 tests/source.test.mjs create mode 100644 tsconfig.json create mode 100644 vite.config.ts create mode 100644 worker/index.ts diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..372846a --- /dev/null +++ b/.env.example @@ -0,0 +1,32 @@ +NODE_ENV=development +PORT=4000 +PUBLIC_BASE_URL=http://localhost:4000 +WEB_ORIGIN=http://localhost:3000 +NEXT_PUBLIC_API_BASE_URL=http://localhost:4000 +NEXT_PUBLIC_AUTH_MODE=demo + +# Use PostgreSQL + MinIO in Docker Compose. Leave DATABASE_URL empty for memory mode. +DATABASE_URL=postgres://altdock:altdock@localhost:5432/altdock +STORAGE_MODE=s3 +S3_ENDPOINT=http://localhost:9000 +S3_REGION=us-east-1 +S3_BUCKET=altdock +S3_ACCESS_KEY_ID=minioadmin +S3_SECRET_ACCESS_KEY=minioadmin +S3_FORCE_PATH_STYLE=true + +# demo works without an identity provider; production should use generic OIDC. +AUTH_MODE=demo +SESSION_SECRET=replace-with-at-least-32-random-characters +OIDC_ISSUER_URL= +OIDC_CLIENT_ID= +OIDC_CLIENT_SECRET= +OIDC_REDIRECT_URI=http://localhost:4000/auth/callback + +MAX_UPLOAD_BYTES=5368709120 +MAX_ARCHIVE_ENTRIES=2048 +MAX_EXPANDED_BYTES=8589934592 +MAX_SOURCES_PER_WORKSPACE=3 +MAX_APPS_PER_SOURCE=20 +MAX_STORAGE_BYTES=21474836480 +PROCESS_INLINE=true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a663647 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/.vinext/ +/out/ + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* +!.env.example + +# vercel +.vercel + +# typescript +next-env.d.ts +/dist/ +*.tsbuildinfo +/.wrangler/ +/outputs/ +/work/ +/.data/ diff --git a/.openai/hosting.json b/.openai/hosting.json new file mode 100644 index 0000000..47c28cb --- /dev/null +++ b/.openai/hosting.json @@ -0,0 +1,4 @@ +{ + "d1": null, + "r2": null +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..6a746c2 --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +# AltDock + +AltDock is a self-hostable, multi-tenant hosting service for AltStore PAL +Alternative Distribution Packages (ADPs). Upload the original ADP ZIP, validate +its manifest and asset set, then publish a PAL-compatible Source JSON URL. + +## Run locally without Docker + +```bash +npm install +cp .env.example .env +npm run dev:api +``` + +With no `DATABASE_URL`, the API uses an in-memory store and local files under +`.data/storage`. Open the web app in another terminal: + +```bash +npm run dev +``` + +The dashboard is at `http://localhost:3000` and the API is at +`http://localhost:4000`. + +## Run the full stack + +```bash +docker compose up +``` + +This starts PostgreSQL, MinIO, the API, the ADP worker, and the web app. The +MinIO console is available at `http://localhost:9001` with the credentials in +`docker-compose.yml`. + +## Production identity + +Set `AUTH_MODE=oidc` and configure `OIDC_ISSUER_URL`, `OIDC_CLIENT_ID`, +`OIDC_CLIENT_SECRET`, `OIDC_REDIRECT_URI`, and a random `SESSION_SECRET`. The +demo mode is intentionally enabled by default for local development only. + +## ADP workflow + +1. Submit the app for Notarization and download the completed ADP ZIP. +2. Upload the original ZIP to AltDock; do not prettify or rewrite its files. +3. Review the parsed bundle ID, Apple Item ID, version, build, and asset paths. +4. Publish the release and copy the Source URL into AltStore PAL. + +Published artifacts are served at `/artifacts/{releaseId}/{relativePath}` and +the Source JSON is served at `/sources/{slug}/source.json`. + +## Checks + +```bash +npm run lint +npm test +``` diff --git a/app/chatgpt-auth.ts b/app/chatgpt-auth.ts new file mode 100644 index 0000000..8d1fb35 --- /dev/null +++ b/app/chatgpt-auth.ts @@ -0,0 +1,86 @@ +import { headers } from "next/headers"; +import { redirect } from "next/navigation"; + +export type ChatGPTUser = { + displayName: string; + email: string; + fullName: string | null; +}; + +const USER_EMAIL_HEADER = "oai-authenticated-user-email"; +const USER_FULL_NAME_HEADER = "oai-authenticated-user-full-name"; +const USER_FULL_NAME_ENCODING_HEADER = + "oai-authenticated-user-full-name-encoding"; +const PERCENT_ENCODED_UTF8 = "percent-encoded-utf-8"; +const SIGN_IN_PATH = "/signin-with-chatgpt"; +const SIGN_OUT_PATH = "/signout-with-chatgpt"; +const CALLBACK_PATH = "/callback"; + +export async function getChatGPTUser(): Promise { + const requestHeaders = await headers(); + const email = requestHeaders.get(USER_EMAIL_HEADER); + if (!email) return null; + + const encodedFullName = requestHeaders.get(USER_FULL_NAME_HEADER); + const fullName = + encodedFullName && + requestHeaders.get(USER_FULL_NAME_ENCODING_HEADER) === PERCENT_ENCODED_UTF8 + ? safeDecodeURIComponent(encodedFullName) + : null; + + return { + displayName: fullName ?? email, + email, + fullName, + }; +} + +export async function requireChatGPTUser( + returnTo: string, +): Promise { + const user = await getChatGPTUser(); + if (user) return user; + + redirect(chatGPTSignInPath(returnTo)); +} + +export function chatGPTSignInPath(returnTo: string): string { + const safeReturnTo = safeRelativeReturnPath(returnTo); + return `${SIGN_IN_PATH}?return_to=${encodeURIComponent(safeReturnTo)}`; +} + +export function chatGPTSignOutPath(returnTo = "/"): string { + const safeReturnTo = safeRelativeReturnPath(returnTo); + return `${SIGN_OUT_PATH}?return_to=${encodeURIComponent(safeReturnTo)}`; +} + +function safeRelativeReturnPath(value: string): string { + if (!value.startsWith("/") || value.startsWith("//")) return "/"; + + let url: URL; + try { + url = new URL(value, "https://app.local"); + } catch { + return "/"; + } + if (url.origin !== "https://app.local") return "/"; + if (isReservedAuthPath(url.pathname)) return "/"; + + return `${url.pathname}${url.search}${url.hash}`; +} + +function isReservedAuthPath(pathname: string): boolean { + return ( + pathname === SIGN_IN_PATH || + pathname === SIGN_OUT_PATH || + pathname === CALLBACK_PATH + ); +} + +function safeDecodeURIComponent(value: string): string | null { + try { + return decodeURIComponent(value); + } catch { + return null; + } +} diff --git a/app/dashboard/apps/page.tsx b/app/dashboard/apps/page.tsx new file mode 100644 index 0000000..a45e389 --- /dev/null +++ b/app/dashboard/apps/page.tsx @@ -0,0 +1,6 @@ +import { DashboardView } from "@/components/altdock/dashboard-view"; + +export default function AppsPage() { + return ; +} + diff --git a/app/dashboard/layout.tsx b/app/dashboard/layout.tsx new file mode 100644 index 0000000..e34b00d --- /dev/null +++ b/app/dashboard/layout.tsx @@ -0,0 +1,8 @@ +import type { ReactNode } from "react"; +import { DashboardProvider } from "@/components/altdock/dashboard-provider"; +import { AdminShell } from "@/components/altdock/admin-shell"; + +export default function DashboardLayout({ children }: { children: ReactNode }) { + return {children}; +} + diff --git a/app/dashboard/page.tsx b/app/dashboard/page.tsx new file mode 100644 index 0000000..3369433 --- /dev/null +++ b/app/dashboard/page.tsx @@ -0,0 +1,6 @@ +import { DashboardView } from "@/components/altdock/dashboard-view"; + +export default function DashboardPage() { + return ; +} + diff --git a/app/dashboard/releases/page.tsx b/app/dashboard/releases/page.tsx new file mode 100644 index 0000000..2e18b6b --- /dev/null +++ b/app/dashboard/releases/page.tsx @@ -0,0 +1,6 @@ +import { DashboardView } from "@/components/altdock/dashboard-view"; + +export default function ReleasesPage() { + return ; +} + diff --git a/app/dashboard/settings/page.tsx b/app/dashboard/settings/page.tsx new file mode 100644 index 0000000..a8666c4 --- /dev/null +++ b/app/dashboard/settings/page.tsx @@ -0,0 +1,7 @@ +import Link from "next/link"; +import { ArrowUpRight, KeyRound, ShieldCheck, SlidersHorizontal } from "lucide-react"; + +export default function SettingsPage() { + return <>
WORKSPACE SETTINGS

設定

認証と配布上限は環境設定で管理します。

設定画面は準備中です

SSO、ストレージ、アップロード上限は現在の環境変数と管理者設定で制御されています。

認証OIDC / demo mode
配布Workspace単位の認可
PALドキュメントを開く
; +} + diff --git a/app/dashboard/sources/page.tsx b/app/dashboard/sources/page.tsx new file mode 100644 index 0000000..3b54801 --- /dev/null +++ b/app/dashboard/sources/page.tsx @@ -0,0 +1,6 @@ +import { DashboardView } from "@/components/altdock/dashboard-view"; + +export default function SourcesPage() { + return ; +} + diff --git a/app/globals.css b/app/globals.css new file mode 100644 index 0000000..06ac125 --- /dev/null +++ b/app/globals.css @@ -0,0 +1,136 @@ +@import "tailwindcss"; + +:root { --ink: #172321; --muted: #73817c; --cream: #f7f7f2; --paper: #ffffff; --line: #e6e9e4; --coral: #e9694b; --blue: #5d8cc5; --green: #78a483; } +* { box-sizing: border-box; } +html { background: var(--cream); } +body { margin: 0; background: var(--cream); color: var(--ink); font-family: var(--font-geist-sans), Arial, Helvetica, sans-serif; } +button, input, textarea, select { font: inherit; } +button, a { -webkit-tap-highlight-color: transparent; } +button { cursor: pointer; } +.app-shell { display: flex; min-height: 100vh; } +.sidebar { position: sticky; top: 0; display: flex; width: 248px; min-height: 100vh; flex: 0 0 248px; flex-direction: column; padding: 30px 18px 20px; border-right: 1px solid var(--line); background: #f4f5ef; } +.brand-lockup { display: flex; align-items: center; gap: 9px; padding: 0 13px; color: #162321; font-size: 18px; font-weight: 760; letter-spacing: -.04em; } +.brand-mark { display: inline-flex; width: 27px; height: 27px; align-items: center; justify-content: center; border-radius: 9px; color: #fff; background: var(--ink); font-size: 14px; font-weight: 800; transform: rotate(-7deg); } +.brand-version { margin-left: 2px; color: var(--coral); font-size: 8px; font-weight: 800; letter-spacing: .14em; } +.sidebar-caption, .section-kicker, .panel-eyebrow, .stat-label { color: #9aa39c; font-size: 9px; font-weight: 800; letter-spacing: .16em; } +.sidebar-caption { margin: 65px 13px 17px; } +.sidebar-nav { display: flex; flex-direction: column; gap: 5px; } +.nav-item { display: flex; align-items: center; gap: 13px; width: 100%; padding: 12px 13px; border: 0; border-radius: 10px; color: #74807b; background: transparent; text-align: left; font-size: 13px; font-weight: 590; transition: .18s ease; } +.nav-item span { width: 17px; color: #98a49e; font-size: 16px; text-align: center; } +.nav-item:hover { color: var(--ink); background: #e9ece5; } +.nav-item.active { color: #26322f; background: #e6e9e1; box-shadow: inset 3px 0 0 var(--coral); } +.nav-item.active span { color: var(--coral); } +.sidebar-bottom { margin-top: auto; } +.storage-card { padding: 15px 13px; border: 1px solid #e0e5dd; border-radius: 11px; background: rgba(255,255,255,.4); } +.storage-head { display: flex; justify-content: space-between; margin-bottom: 10px; color: #69756e; font-size: 10px; font-weight: 650; } +.progress-track { height: 5px; overflow: hidden; border-radius: 9px; background: #dee4dc; } +.progress-track span { display: block; height: 100%; border-radius: inherit; background: var(--coral); } +.storage-card small { display: block; margin-top: 9px; color: #a1aaa3; font-size: 10px; } +.profile { display: flex; align-items: center; gap: 9px; margin-top: 22px; padding: 12px 9px 0; border-top: 1px solid var(--line); } +.profile-avatar { display: inline-flex; width: 28px; height: 28px; align-items: center; justify-content: center; border-radius: 50%; color: #fff; background: #2b4a43; font-size: 11px; font-weight: 750; } +.profile strong, .profile small { display: block; } +.profile strong { color: #45534e; font-size: 11px; } +.profile small { margin-top: 2px; color: #98a39d; font-size: 9px; } +.profile-more { margin-left: auto; color: #a8b1aa; letter-spacing: 2px; } +.main-column { min-width: 0; flex: 1; } +.topbar { display: flex; height: 72px; align-items: center; justify-content: space-between; padding: 0 clamp(24px, 5vw, 72px); border-bottom: 1px solid var(--line); background: rgba(247,247,242,.76); } +.breadcrumbs { display: flex; gap: 10px; align-items: center; color: #a0aaa3; font-size: 11px; } +.breadcrumbs b { color: #c1c8c1; font-weight: 400; }.breadcrumbs strong { color: #50605a; font-weight: 650; } +.topbar-actions { display: flex; gap: 11px; align-items: center; color: #96a29b; font-size: 10px; }.topbar-actions a { color: #678579; text-decoration: none; }.online-dot { width: 6px; height: 6px; border-radius: 50%; background: #7fae8d; box-shadow: 0 0 0 4px #e0ebe0; } +.page-content { max-width: 1250px; margin: 0 auto; padding: 58px clamp(24px, 5vw, 72px) 42px; } +.hero-row { display: flex; min-height: 205px; align-items: center; justify-content: space-between; }.eyebrow { margin-bottom: 15px; color: var(--coral); font-size: 9px; font-weight: 850; letter-spacing: .18em; }.hero-row h1 { margin: 0; color: var(--ink); font-size: clamp(36px, 4.4vw, 59px); font-weight: 500; letter-spacing: -.075em; line-height: .96; }.hero-row h1 em { color: var(--coral); font-style: normal; }.hero-copy { max-width: 470px; margin: 19px 0 0; color: #7c8982; font-size: 13px; line-height: 1.7; } +.hero-orbit { position: relative; width: 215px; height: 190px; margin-right: clamp(8px, 4vw, 64px); }.orbit { position: absolute; border: 1px solid #d8ded6; border-radius: 50%; transform: rotate(-25deg); }.orbit-one { inset: 11px 0 17px 22px; }.orbit-two { inset: 0 21px 25px 1px; border-color: #ebc9bf; transform: rotate(42deg); }.orbit-core { position: absolute; top: 66px; left: 83px; display: flex; width: 63px; height: 63px; align-items: center; justify-content: center; border-radius: 20px; color: #fff; background: var(--coral); box-shadow: 12px 15px 35px #d7b7ac; font-size: 28px; font-weight: 700; transform: rotate(-7deg); }.orbit-label { position: absolute; right: -2px; bottom: 15px; color: #a0aaa3; font-size: 8px; font-weight: 800; letter-spacing: .12em; line-height: 1.5; } +.notice { display: flex; gap: 10px; align-items: center; margin: 8px 0 21px; padding: 11px 13px; border: 1px solid #dfe9df; border-radius: 9px; color: #587263; background: #f1f8f0; font-size: 11px; }.notice.error { border-color: #f0d2c9; color: #a25849; background: #fff4ef; }.notice.info { border-color: #d5e2f0; color: #547395; background: #f2f7fc; }.notice > span { font-size: 14px; font-weight: 800; }.notice button { margin-left: auto; border: 0; color: inherit; background: transparent; font-size: 17px; } +.stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 13px; margin: 28px 0 46px; }.stat-card { position: relative; min-height: 125px; padding: 21px 22px; overflow: hidden; border: 1px solid var(--line); border-radius: 13px; background: rgba(255,255,255,.65); }.stat-card strong { display: block; margin-top: 14px; color: #273632; font-size: 27px; font-weight: 550; letter-spacing: -.06em; }.stat-card small { color: #9ca7a0; font-size: 10px; }.stat-icon { position: absolute; top: 17px; right: 19px; font-size: 24px; opacity: .85; }.stat-icon.coral { color: var(--coral); }.stat-icon.blue { color: var(--blue); }.stat-icon.green { color: var(--green); } +.section-header { display: flex; align-items: end; justify-content: space-between; margin-bottom: 16px; }.section-header h2 { margin: 6px 0 0; color: #35443e; font-size: 21px; font-weight: 600; letter-spacing: -.045em; }.section-kicker { color: #a3ada6; }.button { display: inline-flex; min-height: 36px; align-items: center; justify-content: center; gap: 6px; padding: 0 14px; border: 1px solid transparent; border-radius: 8px; font-size: 11px; font-weight: 680; transition: .18s ease; }.button:disabled { cursor: wait; opacity: .55; }.button.primary { color: #fff; background: var(--ink); box-shadow: 0 4px 9px #18362d14; }.button.primary:hover { background: #2f4841; transform: translateY(-1px); }.button.secondary { color: #2e4c42; background: #eef3ed; border-color: #dbe7dc; }.button.ghost { color: #687b72; background: transparent; border-color: #dce3dc; }.button.ghost:hover { color: var(--ink); background: #fff; }.button.tiny { min-height: 28px; padding: 0 10px; border-radius: 6px; font-size: 10px; } +.workspace-grid { display: grid; grid-template-columns: minmax(0, 1fr) 285px; gap: 15px; }.panel { border: 1px solid var(--line); border-radius: 13px; background: rgba(255,255,255,.72); }.source-panel { min-height: 330px; padding: 24px 26px; }.panel-heading { display: flex; align-items: start; justify-content: space-between; gap: 16px; }.panel-heading h3 { margin: 7px 0 4px; color: #30423b; font-size: 19px; font-weight: 620; letter-spacing: -.045em; }.panel-heading p { margin: 0; color: #96a19b; font-size: 11px; }.visibility-pill { display: inline-flex; gap: 6px; align-items: center; padding: 6px 9px; border-radius: 5px; color: #6e8074; background: #edf4ed; font-size: 9px; font-weight: 750; }.visibility-pill span { width: 5px; height: 5px; border-radius: 50%; background: #8cb092; }.visibility-pill.draft { color: #8b8172; background: #f6f1ea; }.visibility-pill.draft span { background: #d0a565; }.visibility-pill.public { color: #9b5948; background: #fff1eb; }.visibility-pill.public span { background: var(--coral); } +.source-url-row { display: flex; gap: 9px; margin: 27px 0 16px; }.source-url { display: flex; min-width: 0; flex: 1; align-items: center; gap: 9px; padding: 0 12px; overflow: hidden; border: 1px solid #e2e8e2; border-radius: 7px; color: #7b8b82; background: #f8faf7; font-family: var(--font-geist-mono), monospace; font-size: 10px; white-space: nowrap; }.source-url span:last-child { overflow: hidden; text-overflow: ellipsis; }.url-lock { color: var(--coral); font-size: 13px; }.app-list { display: flex; flex-direction: column; }.app-row { display: flex; min-height: 67px; align-items: center; gap: 12px; border-top: 1px solid #edf0eb; }.app-icon { display: inline-flex; width: 34px; height: 34px; flex: 0 0 34px; align-items: center; justify-content: center; border-radius: 10px; color: #fff; font-size: 13px; font-weight: 750; }.app-info { min-width: 0; flex: 1; }.app-info strong, .app-info small { display: block; }.app-info strong { overflow: hidden; color: #405049; font-size: 12px; font-weight: 680; text-overflow: ellipsis; white-space: nowrap; }.app-info small { margin-top: 3px; overflow: hidden; color: #9aa69f; font-family: var(--font-geist-mono), monospace; font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }.app-release-meta { display: flex; min-width: 130px; flex-direction: column; align-items: end; gap: 5px; color: #89968e; font-family: var(--font-geist-mono), monospace; font-size: 9px; }.release-status { display: inline-flex; width: fit-content; padding: 4px 7px; border-radius: 4px; font-family: var(--font-geist-sans), Arial, sans-serif; font-size: 9px; font-weight: 740; }.release-status.published { color: #67816d; background: #edf5ee; }.release-status.ready { color: #9a6f42; background: #fff5e7; }.release-status.processing { color: #5379a0; background: #edf5fd; }.release-status.rejected { color: #a35e51; background: #fff0ec; }.release-status.archived, .release-status.uploaded { color: #88948d; background: #f0f2ef; }.row-chevron { color: #b5bdb7; font-size: 20px; } +.empty-state { display: flex; min-height: 195px; align-items: center; justify-content: center; flex-direction: column; padding: 25px; text-align: center; }.empty-icon { display: flex; width: 40px; height: 40px; align-items: center; justify-content: center; margin-bottom: 12px; border-radius: 13px; color: var(--coral); background: #fff0eb; font-size: 20px; }.empty-state strong { color: #607069; font-size: 12px; }.empty-state p { max-width: 360px; margin: 7px 0 15px; color: #a0aaa4; font-size: 10px; line-height: 1.6; } +.right-rail { display: flex; flex-direction: column; gap: 15px; }.quick-panel { padding: 20px 18px 11px; }.quick-action { display: flex; width: 100%; align-items: center; gap: 10px; margin-top: 15px; padding: 0 0 13px; border: 0; border-bottom: 1px solid #edf0eb; color: #5b6e65; background: transparent; text-align: left; }.quick-action:last-child { border-bottom: 0; }.quick-action > span:nth-child(2) { flex: 1; }.quick-action strong, .quick-action small { display: block; }.quick-action strong { color: #5a6d64; font-size: 10px; font-weight: 700; }.quick-action small { margin-top: 4px; color: #a0aaa5; font-size: 9px; }.quick-action b { color: #b7c1ba; font-size: 17px; font-weight: 400; }.quick-icon { display: inline-flex; width: 31px; height: 31px; align-items: center; justify-content: center; border-radius: 9px; font-size: 15px; }.coral-bg { color: #d6674a; background: #fff0eb; }.blue-bg { color: #648db7; background: #eff5fc; }.green-bg { color: #71947a; background: #edf5ee; }.callout { display: flex; gap: 12px; padding: 18px 17px; border-radius: 13px; color: #fff; background: #27463d; }.callout-orb { display: flex; width: 28px; height: 28px; flex: 0 0 28px; align-items: center; justify-content: center; border: 1px solid #87a59a; border-radius: 50%; color: #e8bd8f; font-size: 12px; }.callout strong { display: block; font-size: 12px; line-height: 1.3; }.callout p { margin: 9px 0 0; color: #b7cbc1; font-size: 9px; line-height: 1.55; } +.release-header { margin-top: 47px; }.release-table { overflow: hidden; }.release-table-head, .release-table-row { display: grid; grid-template-columns: minmax(180px, 1.5fr) 120px 80px 110px 70px; gap: 15px; align-items: center; padding: 0 23px; }.release-table-head { min-height: 38px; border-bottom: 1px solid var(--line); color: #a1aaa4; font-size: 8px; font-weight: 800; letter-spacing: .13em; }.release-table-row { min-height: 67px; border-bottom: 1px solid #edf0eb; }.release-table-row:last-child { border-bottom: 0; }.release-name { display: flex; align-items: center; gap: 10px; }.release-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--coral); box-shadow: 0 0 0 4px #ffebe4; }.release-name strong, .release-name small { display: block; }.release-name strong { color: #5c6e65; font-size: 11px; }.release-name small, .release-size, .release-date { margin-top: 3px; color: #9ca7a0; font-family: var(--font-geist-mono), monospace; font-size: 9px; }.release-table-row > .release-status { justify-self: start; }.release-table-row > .row-chevron { justify-self: end; }.table-empty { padding: 27px; color: #a1aaa4; text-align: center; font-size: 11px; }.footer-note { display: flex; gap: 17px; align-items: center; margin-top: 22px; color: #a3aca6; font-size: 9px; }.footer-note span:first-child { color: #76877d; font-weight: 700; }.footer-note a { margin-left: auto; color: #728b7e; text-decoration: none; } +.modal-backdrop { position: fixed; z-index: 50; inset: 0; display: flex; align-items: center; justify-content: center; padding: 20px; background: #1f332e55; backdrop-filter: blur(6px); }.modal { position: relative; width: min(100%, 495px); padding: 30px; border: 1px solid #e0e6df; border-radius: 17px; background: #fff; box-shadow: 0 25px 80px #1e352e2e; }.modal-close { position: absolute; top: 15px; right: 16px; border: 0; color: #a4aea8; background: transparent; font-size: 23px; }.modal h2 { margin: 7px 0 7px; color: #30423b; font-size: 25px; letter-spacing: -.06em; }.modal > p { margin: 0 0 24px; color: #8d9b93; font-size: 11px; line-height: 1.55; }.modal label { display: block; margin-top: 15px; color: #728078; font-size: 10px; font-weight: 700; }.modal input, .modal textarea, .modal select { display: block; width: 100%; margin-top: 7px; padding: 10px 11px; border: 1px solid #dfe6de; border-radius: 7px; outline: none; color: #455750; background: #fbfcfa; font-size: 11px; }.modal input:focus, .modal textarea:focus, .modal select:focus { border-color: #a9c4b0; box-shadow: 0 0 0 3px #e6f1e7; }.modal textarea { resize: vertical; }.modal-actions { display: flex; justify-content: end; gap: 9px; margin-top: 25px; }.dropzone { position: relative; margin: 20px 0 14px; }.dropzone input { position: absolute; z-index: 1; inset: 0; width: 100%; height: 100%; cursor: pointer; opacity: 0; }.dropzone label { display: flex; min-height: 145px; align-items: center; justify-content: center; flex-direction: column; gap: 7px; margin: 0; border: 1px dashed #b9cdc0; border-radius: 11px; color: #72847a; background: #f6faf5; text-align: center; }.dropzone label:hover { border-color: var(--coral); background: #fff9f5; }.drop-icon { display: flex; width: 38px; height: 38px; align-items: center; justify-content: center; border-radius: 12px; color: var(--coral); background: #fff0eb; font-size: 18px; }.dropzone strong { color: #5f7368; font-size: 12px; }.dropzone small { color: #a1ada5; font-size: 9px; }.upload-hint { display: flex; gap: 9px; padding: 11px; border-radius: 8px; color: #758982; background: #f2f7f1; }.upload-hint span { display: flex; width: 16px; height: 16px; flex: 0 0 16px; align-items: center; justify-content: center; border-radius: 50%; color: #fff; background: #86a990; font-size: 9px; font-weight: 800; }.upload-hint p { margin: 0; font-size: 9px; line-height: 1.55; }.loading-bar { position: fixed; z-index: 60; top: 0; left: 0; width: 35%; height: 3px; background: var(--coral); animation: load 1.1s infinite ease-in-out; } +@keyframes load { 0% { transform: translateX(-100%); } 100% { transform: translateX(310%); } } +.public-source-page { min-height: 100vh; padding: 0 clamp(20px, 7vw, 100px) 40px; color: var(--ink); background: radial-gradient(circle at 82% 0%, color-mix(in srgb, var(--source-tint) 12%, transparent), transparent 30%), var(--cream); } +.public-source-header { display: flex; max-width: 1040px; height: 76px; align-items: center; justify-content: space-between; margin: 0 auto; border-bottom: 1px solid var(--line); }.public-brand { display: flex; gap: 9px; align-items: center; color: var(--ink); font-size: 17px; font-weight: 760; letter-spacing: -.05em; text-decoration: none; }.public-badge { color: #9ca8a1; font-size: 9px; font-weight: 800; letter-spacing: .15em; } +.public-source-hero { display: flex; max-width: 1040px; align-items: center; gap: 20px; margin: 75px auto 0; }.public-source-hero > div:nth-child(2) { flex: 1; }.public-source-avatar { display: flex; width: 82px; height: 82px; align-items: center; justify-content: center; overflow: hidden; border-radius: 25px; color: #fff; background: var(--source-tint); box-shadow: 14px 15px 35px color-mix(in srgb, var(--source-tint) 25%, transparent); font-size: 34px; font-weight: 700; }.public-source-avatar img, .public-app-icon img { width: 100%; height: 100%; object-fit: cover; }.public-source-hero h1 { margin: 8px 0 4px; color: #32433c; font-size: clamp(34px, 5vw, 58px); font-weight: 560; letter-spacing: -.075em; }.public-source-hero p { margin: 0; color: #8a9890; font-size: 13px; }.public-source-description { max-width: 660px; margin: 27px auto 0; color: #6f8077; font-size: 13px; line-height: 1.75; }.public-app-grid { display: grid; max-width: 1040px; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; margin: 47px auto 0; }.public-app-card { padding: 23px; border: 1px solid var(--line); border-radius: 15px; background: rgba(255,255,255,.78); }.public-app-card-top { display: flex; align-items: start; justify-content: space-between; }.public-app-icon { display: flex; width: 49px; height: 49px; align-items: center; justify-content: center; overflow: hidden; border-radius: 15px; color: #fff; font-size: 21px; font-weight: 700; }.public-category { padding: 5px 8px; border-radius: 4px; color: #8a968f; background: #f0f3ee; font-size: 8px; font-weight: 800; letter-spacing: .08em; text-transform: uppercase; }.public-app-card h2 { margin: 19px 0 4px; color: #4b5c54; font-size: 19px; letter-spacing: -.05em; }.public-developer { margin: 0; overflow: hidden; color: #a1aba5; font-family: var(--font-geist-mono), monospace; font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }.public-app-description { min-height: 43px; margin: 18px 0; color: #829087; font-size: 11px; line-height: 1.55; }.public-release { display: flex; align-items: center; justify-content: space-between; padding-top: 15px; border-top: 1px solid #edf0eb; color: #a1aaa4; font-size: 9px; }.public-release strong { color: #657970; font-family: var(--font-geist-mono), monospace; font-size: 10px; }.public-release small { color: #a0aba4; font-size: 8px; font-weight: 400; }.public-no-apps { grid-column: 1 / -1; padding: 45px; border: 1px dashed #cad6cc; border-radius: 15px; color: #7d8f85; background: #f8fbf7; text-align: center; }.public-no-apps p { margin: 7px 0 0; color: #a3afa6; font-size: 11px; }.public-source-footer { display: flex; max-width: 1040px; justify-content: space-between; margin: 55px auto 0; padding-top: 17px; border-top: 1px solid var(--line); color: #a1aaa4; font-size: 9px; }.public-source-footer span:first-child { color: #74877c; font-weight: 700; }.public-source-error, .public-source-loading { display: flex; min-height: 100vh; align-items: center; justify-content: center; flex-direction: column; gap: 11px; color: #7f9086; background: var(--cream); text-align: center; }.public-source-error h1 { margin: 12px 0 0; color: var(--ink); font-size: 30px; letter-spacing: -.06em; }.public-source-error p { margin: 0; font-size: 12px; }.public-source-error a { color: var(--coral); font-size: 11px; font-weight: 700; text-decoration: none; } +@media (max-width: 960px) { .sidebar { width: 205px; flex-basis: 205px; }.workspace-grid { grid-template-columns: 1fr; }.right-rail { display: grid; grid-template-columns: 1fr 1fr; }.hero-orbit { margin-right: 0; transform: scale(.8); }.release-table-head, .release-table-row { grid-template-columns: minmax(180px, 1.5fr) 105px 70px 90px 65px; padding-inline: 15px; } } +.visibility-pill select { max-width: 18px; padding: 0; border: 0; outline: 0; color: inherit; background: transparent; font-size: 9px; } +.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.field-help { color: #a3aea6; font-size: 9px; font-weight: 400; } +@media (max-width: 720px) { .app-shell { display: block; }.sidebar { position: static; display: block; width: 100%; min-height: auto; padding: 17px 18px; border-right: 0; border-bottom: 1px solid var(--line); }.sidebar-caption, .sidebar-bottom { display: none; }.sidebar-nav { display: none; }.topbar { height: 54px; padding: 0 20px; }.topbar-actions { font-size: 0; }.topbar-actions a { font-size: 10px; }.page-content { padding: 34px 20px 28px; }.hero-row { min-height: 0; }.hero-row h1 { font-size: 43px; }.hero-copy { font-size: 12px; }.hero-orbit { display: none; }.stats-grid { gap: 8px; margin: 30px 0 38px; }.stat-card { min-height: 104px; padding: 15px 13px; }.stat-card strong { margin-top: 10px; font-size: 20px; }.stat-card small { font-size: 8px; }.stat-icon { top: 13px; right: 12px; font-size: 18px; }.section-header h2 { font-size: 18px; }.button { padding-inline: 11px; font-size: 10px; }.source-panel { padding: 18px 15px; }.source-url-row { flex-direction: column; }.source-url { min-height: 36px; }.app-release-meta { min-width: auto; }.app-release-meta > span:first-child { display: none; }.right-rail { display: flex; }.release-table { overflow-x: auto; }.release-table-head, .release-table-row { min-width: 575px; }.footer-note { flex-wrap: wrap; }.footer-note a { margin-left: 0; }.modal { padding: 25px 20px; }.public-source-header { height: 63px; }.public-badge { font-size: 7px; }.public-source-hero { align-items: start; flex-wrap: wrap; margin-top: 43px; }.public-source-hero > div:nth-child(2) { min-width: calc(100% - 102px); }.public-source-hero h1 { font-size: 36px; }.public-source-hero .button { margin-left: 102px; }.public-source-footer { flex-direction: column; gap: 7px; } } + +/* AltDock control-plane UI: compact, neutral, and operational rather than promotional. */ +:root { --admin-bg: #f5f6f8; --admin-panel: #ffffff; --admin-line: #e4e7eb; --admin-line-strong: #d5d9df; --admin-text: #20252b; --admin-muted: #68717d; --admin-subtle: #8c96a3; --admin-orange: #e56d4d; --admin-blue: #4d7fae; --admin-green: #31845e; --admin-yellow: #a87424; --admin-red: #c9554d; } +.sr-only { position: absolute !important; width: 1px !important; height: 1px !important; padding: 0 !important; overflow: hidden !important; clip: rect(0, 0, 0, 0) !important; white-space: nowrap !important; border: 0 !important; } +.admin-shell { display: flex; min-height: 100vh; color: var(--admin-text); background: var(--admin-bg); } +.admin-sidebar { position: sticky; z-index: 20; top: 0; display: flex; width: 240px; height: 100vh; flex: 0 0 240px; flex-direction: column; border-right: 1px solid var(--admin-line); background: #fafbfc; transition: width .18s ease, flex-basis .18s ease; } +.admin-sidebar.is-collapsed { width: 68px; flex-basis: 68px; } +.admin-sidebar-inner { display: flex; height: 100%; flex-direction: column; padding: 16px 12px 14px; } +.admin-brand { display: flex; width: 100%; height: 36px; align-items: center; gap: 9px; padding: 0 9px; border: 0; color: var(--admin-text); background: transparent; text-align: left; } +.admin-brand-mark { display: inline-flex; width: 27px; height: 27px; align-items: center; justify-content: center; border-radius: 6px; color: #fff; background: #20252b; font-size: 14px; font-weight: 800; } +.admin-brand-name { font-size: 16px; font-weight: 720; letter-spacing: -.035em; } +.admin-brand-beta { margin-left: auto; color: var(--admin-orange); font-size: 8px; font-weight: 800; letter-spacing: .12em; } +.admin-workspace-switcher { display: flex; min-width: 0; align-items: center; gap: 9px; margin: 24px 3px 21px; padding: 9px 8px; border: 1px solid var(--admin-line); border-radius: 7px; background: #fff; text-align: left; } +.admin-workspace-avatar { display: inline-flex; width: 25px; height: 25px; flex: 0 0 25px; align-items: center; justify-content: center; border-radius: 5px; color: #fff; background: #4c6a84; font-size: 11px; font-weight: 750; } +.admin-workspace-copy { min-width: 0; flex: 1; }.admin-workspace-copy small, .admin-workspace-copy strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.admin-workspace-copy small { color: var(--admin-subtle); font-size: 8px; font-weight: 750; letter-spacing: .11em; }.admin-workspace-copy strong { margin-top: 2px; color: var(--admin-text); font-size: 11px; font-weight: 650; } +.admin-nav-label { margin: 0 9px 8px; color: var(--admin-subtle); font-size: 9px; font-weight: 800; letter-spacing: .14em; text-transform: uppercase; }.admin-nav-label-secondary { margin-top: 23px; }.admin-nav { display: flex; flex-direction: column; gap: 2px; }.admin-nav-item { display: flex; min-height: 35px; align-items: center; gap: 10px; padding: 0 10px; border-radius: 6px; color: #66717e; font-size: 12px; font-weight: 560; text-decoration: none; }.admin-nav-item:hover { color: var(--admin-text); background: #eef0f3; }.admin-nav-item.active { color: #26313b; background: #e9edf1; box-shadow: inset 2px 0 0 var(--admin-orange); font-weight: 680; }.admin-nav-item.active svg { color: var(--admin-orange); }.admin-nav-external { margin-left: auto; color: var(--admin-subtle); }.admin-sidebar.is-collapsed .admin-nav-item { justify-content: center; padding: 0; }.admin-sidebar.is-collapsed .admin-nav-item svg { flex: 0 0 auto; }.admin-sidebar-spacer { flex: 1; } +.admin-storage-card { margin: 0 2px 13px; padding: 12px 10px; border: 1px solid var(--admin-line); border-radius: 7px; background: #fff; }.admin-storage-row { display: flex; justify-content: space-between; gap: 8px; color: var(--admin-muted); font-size: 10px; }.admin-storage-row strong { color: var(--admin-text); font-family: var(--font-geist-mono), monospace; font-size: 9px; font-weight: 600; }.admin-storage-card small { display: block; margin-top: 9px; color: var(--admin-subtle); font-size: 9px; }.admin-progress { height: 5px; overflow: hidden; border-radius: 99px; background: #edf0f2; }.admin-progress span { display: block; height: 100%; min-width: 1px; border-radius: inherit; background: var(--admin-orange); transition: width .2s ease; }.admin-storage-card .admin-progress { margin-top: 10px; } +.admin-user-card { display: flex; align-items: center; gap: 8px; padding: 13px 7px 2px; border-top: 1px solid var(--admin-line); }.admin-user-avatar { display: inline-flex; width: 27px; height: 27px; align-items: center; justify-content: center; border-radius: 50%; color: #fff; background: #4b6378; font-size: 10px; font-weight: 750; }.admin-user-card > span:nth-child(2) { min-width: 0; flex: 1; }.admin-user-card strong, .admin-user-card small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.admin-user-card strong { color: var(--admin-text); font-size: 10px; font-weight: 650; }.admin-user-card small { margin-top: 2px; color: var(--admin-subtle); font-family: var(--font-geist-mono), monospace; font-size: 8px; }.admin-user-menu { color: var(--admin-subtle); letter-spacing: 2px; } +.admin-collapse-toggle { position: fixed; z-index: 22; bottom: 18px; left: 222px; display: inline-flex; width: 26px; height: 26px; align-items: center; justify-content: center; border: 1px solid var(--admin-line-strong); border-radius: 50%; color: var(--admin-muted); background: #fff; box-shadow: 0 2px 7px #16202b12; transition: left .18s ease; }.admin-sidebar.is-collapsed ~ .admin-collapse-toggle { left: 54px; }.admin-collapse-toggle:hover { color: var(--admin-text); } +.admin-main-column { min-width: 0; flex: 1; }.admin-topbar { position: sticky; z-index: 10; top: 0; display: flex; height: 57px; align-items: center; justify-content: space-between; padding: 0 clamp(22px, 4vw, 58px); border-bottom: 1px solid var(--admin-line); background: #ffffffeb; backdrop-filter: blur(10px); }.admin-topbar-left, .admin-topbar-actions, .admin-breadcrumb, .admin-search-trigger, .admin-topbar-action { display: flex; align-items: center; }.admin-topbar-left { min-width: 0; }.admin-breadcrumb { gap: 9px; color: var(--admin-subtle); font-size: 11px; }.admin-breadcrumb strong { color: var(--admin-text); font-weight: 650; }.admin-topbar-actions { gap: 14px; }.admin-search-trigger { gap: 8px; min-width: 176px; height: 31px; padding: 0 9px; border: 1px solid var(--admin-line); border-radius: 6px; color: var(--admin-subtle); background: #fbfcfd; font-size: 10px; text-align: left; }.admin-search-trigger:hover { border-color: var(--admin-line-strong); color: var(--admin-muted); }.admin-search-trigger kbd { margin-left: auto; padding: 2px 5px; border: 1px solid var(--admin-line); border-radius: 4px; color: var(--admin-subtle); background: #fff; font-family: var(--font-geist-mono), monospace; font-size: 9px; }.admin-topbar-action { gap: 6px; color: var(--admin-text); font-size: 10px; font-weight: 650; text-decoration: none; }.admin-topbar-action:hover, .admin-auth-link:hover { color: var(--admin-orange); }.admin-status-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--admin-green); box-shadow: 0 0 0 3px #e2f1e9; }.admin-auth-link { color: var(--admin-muted); font-size: 10px; text-decoration: none; }.mobile-menu-button { display: none; } +.admin-content { width: min(100%, 1440px); margin: 0 auto; padding: 34px clamp(22px, 4vw, 58px) 64px; }.admin-page-heading { display: flex; align-items: end; justify-content: space-between; gap: 20px; margin-bottom: 27px; }.admin-eyebrow, .dialog-kicker { color: var(--admin-orange); font-size: 9px; font-weight: 800; letter-spacing: .14em; }.admin-page-heading h1 { margin: 6px 0 5px; color: var(--admin-text); font-size: 28px; font-weight: 650; letter-spacing: -.045em; }.admin-page-heading p { margin: 0; color: var(--admin-muted); font-size: 12px; line-height: 1.55; }.admin-page-actions { display: flex; align-items: center; gap: 8px; }.admin-link { display: inline-flex; align-items: center; gap: 5px; color: var(--admin-muted); font-size: 10px; font-weight: 650; text-decoration: none; }.admin-link:hover { color: var(--admin-orange); } +.ui-button { display: inline-flex; min-height: 33px; align-items: center; justify-content: center; gap: 7px; padding: 0 12px; border: 1px solid transparent; border-radius: 6px; color: #fff; background: #252c34; font-size: 11px; font-weight: 650; line-height: 1; transition: border-color .15s ease, background .15s ease, color .15s ease; }.ui-button:hover { background: #111820; }.ui-button:disabled { cursor: wait; opacity: .5; }.ui-button-sm { min-height: 29px; padding: 0 9px; font-size: 10px; }.ui-button-icon { width: 31px; min-height: 31px; padding: 0; }.ui-button-primary { color: #fff; background: var(--admin-orange); }.ui-button-primary:hover { background: #ce5d42; }.ui-button-secondary { color: #27323c; border-color: var(--admin-line-strong); background: #fff; }.ui-button-secondary:hover, .ui-button-outline:hover { background: #f0f2f4; }.ui-button-outline { color: var(--admin-text); border-color: var(--admin-line-strong); background: #fff; }.ui-button-ghost { color: var(--admin-muted); background: transparent; }.ui-button-ghost:hover { color: var(--admin-text); background: #eef0f2; }.ui-button-danger { color: #fff; background: var(--admin-red); } +.admin-metric-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 11px; margin-bottom: 15px; }.admin-metric-card { min-height: 114px; padding: 16px 17px; border: 1px solid var(--admin-line); border-radius: 8px; background: var(--admin-panel); }.admin-metric-top { display: flex; align-items: center; justify-content: space-between; color: var(--admin-subtle); font-size: 9px; font-weight: 800; letter-spacing: .12em; }.admin-metric-top svg { color: var(--admin-muted); }.metric-orange .admin-metric-top svg { color: var(--admin-orange); }.metric-blue .admin-metric-top svg { color: var(--admin-blue); }.metric-green .admin-metric-top svg { color: var(--admin-green); }.admin-metric-card strong { display: block; margin-top: 16px; color: var(--admin-text); font-family: var(--font-geist-mono), monospace; font-size: 25px; font-weight: 600; letter-spacing: -.07em; }.admin-metric-card small { display: block; margin-top: 6px; color: var(--admin-subtle); font-size: 10px; } +.admin-overview-grid { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(280px, .75fr); gap: 15px; margin-bottom: 15px; }.admin-section-card { min-width: 0; margin-bottom: 15px; border: 1px solid var(--admin-line); border-radius: 8px; background: var(--admin-panel); }.admin-overview-grid .admin-section-card { margin-bottom: 0; }.admin-section-card-header { display: flex; align-items: start; justify-content: space-between; gap: 16px; padding: 18px 19px 14px; }.admin-section-card-header h2 { margin: 0; color: var(--admin-text); font-size: 13px; font-weight: 680; letter-spacing: -.015em; }.admin-section-card-header p { margin: 5px 0 0; color: var(--admin-subtle); font-size: 10px; }.health-list { display: grid; grid-template-columns: repeat(4, 1fr); gap: 9px; padding: 3px 19px 18px; }.health-list > div { padding: 11px 10px; border: 1px solid var(--admin-line); border-radius: 6px; background: #fbfcfd; }.health-label { display: flex; align-items: center; gap: 6px; color: var(--admin-muted); font-size: 10px; white-space: nowrap; }.health-list strong { display: block; margin-top: 10px; color: var(--admin-text); font-family: var(--font-geist-mono), monospace; font-size: 18px; font-weight: 600; }.health-dot, .admin-status-dot-small { display: inline-block; width: 6px; height: 6px; flex: 0 0 6px; border-radius: 50%; }.health-dot.success, .ui-badge-success .admin-status-dot-small { background: var(--admin-green); }.health-dot.info, .ui-badge-info .admin-status-dot-small { background: var(--admin-blue); }.health-dot.warning, .ui-badge-warning .admin-status-dot-small { background: var(--admin-yellow); }.health-dot.danger, .ui-badge-danger .admin-status-dot-small { background: var(--admin-red); }.ui-badge-neutral .admin-status-dot-small { background: #98a1aa; }.quota-summary { padding: 0 19px 18px; }.quota-summary > div:first-child { display: flex; justify-content: space-between; margin-bottom: 7px; color: var(--admin-muted); font-size: 10px; }.quota-summary strong { color: var(--admin-text); font-family: var(--font-geist-mono), monospace; font-weight: 600; } +.admin-action-row { display: flex; width: 100%; align-items: center; gap: 10px; padding: 12px 19px; border: 0; border-top: 1px solid var(--admin-line); color: var(--admin-muted); background: transparent; text-align: left; text-decoration: none; }.admin-action-row:hover { background: #fafbfc; }.admin-action-row > span:nth-child(2) { min-width: 0; flex: 1; }.admin-action-row strong, .admin-action-row small { display: block; }.admin-action-row strong { color: var(--admin-text); font-size: 11px; font-weight: 650; }.admin-action-row small { margin-top: 4px; color: var(--admin-subtle); font-size: 9px; }.admin-action-icon { display: inline-flex; width: 29px; height: 29px; flex: 0 0 29px; align-items: center; justify-content: center; border-radius: 6px; }.admin-action-icon.orange { color: var(--admin-orange); background: #fff1ed; }.admin-action-icon.blue { color: var(--admin-blue); background: #edf4fa; }.admin-action-icon.neutral { color: var(--admin-muted); background: #f0f2f4; } +.admin-table-wrap { width: 100%; overflow-x: auto; }.admin-table { width: 100%; border-collapse: collapse; text-align: left; }.admin-table th { height: 37px; padding: 0 19px; border-top: 1px solid var(--admin-line); border-bottom: 1px solid var(--admin-line); color: var(--admin-subtle); font-size: 9px; font-weight: 800; letter-spacing: .09em; white-space: nowrap; }.admin-table td { height: 59px; padding: 8px 19px; border-bottom: 1px solid #edf0f2; color: var(--admin-muted); font-size: 11px; vertical-align: middle; white-space: nowrap; }.admin-table tbody tr:last-child td { border-bottom: 0; }.admin-table tbody tr:hover td { background: #fbfcfd; }.admin-clickable-row { cursor: pointer; }.table-primary-link { display: inline-flex; min-width: 185px; align-items: center; gap: 9px; border: 0; color: var(--admin-text); background: transparent; text-align: left; text-decoration: none; }.table-primary-link strong, .table-primary-link small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.table-primary-link strong { color: var(--admin-text); font-size: 11px; font-weight: 650; }.table-primary-link small { max-width: 250px; margin-top: 3px; color: var(--admin-subtle); font-family: var(--font-geist-mono), monospace; font-size: 9px; }.table-avatar { display: inline-flex; width: 30px; height: 30px; flex: 0 0 30px; align-items: center; justify-content: center; border-radius: 6px; color: #fff; font-size: 12px; font-weight: 750; }.table-avatar-small { width: 26px; height: 26px; flex-basis: 26px; border-radius: 5px; font-size: 10px; }.table-chevron { color: #aab2bb; }.table-actions { display: flex; justify-content: end; gap: 2px; }.admin-table code, .table-code { color: #596773; font-family: var(--font-geist-mono), monospace; font-size: 9px; }.table-subline { display: block; margin-top: 4px; color: var(--admin-subtle); font-family: var(--font-geist-mono), monospace; font-size: 8px; }.version-cell strong, .version-cell small { display: block; }.version-cell strong { color: var(--admin-text); font-family: var(--font-geist-mono), monospace; font-size: 10px; font-weight: 600; }.version-cell small { margin-top: 3px; color: var(--admin-subtle); font-family: var(--font-geist-mono), monospace; font-size: 9px; }.category-label { padding: 4px 7px; border-radius: 4px; color: var(--admin-muted); background: #f1f3f5; font-size: 9px; } +.ui-badge { display: inline-flex; min-height: 22px; align-items: center; gap: 6px; padding: 0 7px; border-radius: 4px; font-size: 9px; font-weight: 680; white-space: nowrap; }.ui-badge-neutral { color: #66717d; background: #eef0f2; }.ui-badge-info { color: #47739b; background: #edf4fa; }.ui-badge-warning { color: #956c2a; background: #fbf3e3; }.ui-badge-danger { color: #a34d47; background: #fceeed; }.ui-badge-success { color: #397a5b; background: #eaf5ee; } +.admin-toolbar { display: flex; align-items: center; gap: 9px; padding: 13px 19px; border-top: 1px solid var(--admin-line); }.admin-search-field, .admin-filter-field { display: flex; height: 32px; align-items: center; gap: 7px; padding: 0 9px; border: 1px solid var(--admin-line); border-radius: 5px; color: var(--admin-subtle); background: #fbfcfd; }.admin-search-field { min-width: 280px; flex: 1; max-width: 440px; }.admin-search-field input { width: 100%; border: 0; outline: 0; color: var(--admin-text); background: transparent; font-size: 10px; }.admin-search-field input::placeholder { color: var(--admin-subtle); }.admin-filter-field select { border: 0; outline: 0; color: var(--admin-muted); background: transparent; font-size: 10px; }.admin-toolbar-note { display: inline-flex; align-items: center; gap: 6px; margin-left: auto; color: var(--admin-subtle); font-size: 9px; }.admin-table-empty { padding: 28px 19px; color: var(--admin-subtle); text-align: center; font-size: 11px; }.admin-empty-state { display: flex; min-height: 170px; align-items: center; justify-content: center; flex-direction: column; padding: 20px; text-align: center; }.admin-empty-icon { display: inline-flex; width: 38px; height: 38px; align-items: center; justify-content: center; margin-bottom: 10px; border-radius: 7px; color: var(--admin-orange); background: #fff1ed; }.admin-empty-state strong { color: var(--admin-text); font-size: 12px; }.admin-empty-state p { max-width: 340px; margin: 6px 0 13px; color: var(--admin-subtle); font-size: 10px; line-height: 1.5; } +.admin-loading-state, .admin-error-state { display: flex; min-height: 55vh; align-items: center; justify-content: center; flex-direction: column; text-align: center; }.admin-loading-state strong, .admin-error-state strong { margin-top: 12px; color: var(--admin-text); font-size: 13px; }.admin-loading-state p, .admin-error-state p { margin: 6px 0 0; color: var(--admin-subtle); font-size: 11px; }.admin-error-state { color: var(--admin-red); }.admin-spinner { display: inline-block; width: 20px; height: 20px; border: 2px solid #dfe3e7; border-top-color: var(--admin-orange); border-radius: 50%; animation: admin-spin .8s linear infinite; }.admin-loading-inline { display: flex; align-items: center; gap: 8px; padding: 30px; color: var(--admin-subtle); font-size: 11px; }.admin-loading-inline .admin-spinner { width: 15px; height: 15px; }@keyframes admin-spin { to { transform: rotate(360deg); } } +.ui-dialog-overlay { position: fixed; z-index: 50; inset: 0; background: #19212b66; backdrop-filter: blur(2px); }.ui-dialog-content { position: fixed; z-index: 51; top: 50%; left: 50%; width: min(100% - 32px, 520px); max-height: calc(100vh - 32px); overflow-y: auto; padding: 24px; border: 1px solid var(--admin-line-strong); border-radius: 9px; outline: 0; background: #fff; box-shadow: 0 20px 70px #17202c2b; transform: translate(-50%, -50%); }.ui-dialog-content.wide-dialog { width: min(100% - 32px, 680px); }.ui-dialog-header { padding-right: 18px; }.ui-dialog-title { margin: 6px 0 5px; color: var(--admin-text); font-size: 19px; font-weight: 680; letter-spacing: -.035em; }.ui-dialog-description { margin: 0; color: var(--admin-muted); font-size: 11px; line-height: 1.55; }.ui-dialog-close { position: absolute; top: 14px; right: 14px; display: inline-flex; width: 28px; height: 28px; align-items: center; justify-content: center; border: 0; border-radius: 5px; color: var(--admin-subtle); background: transparent; }.ui-dialog-close:hover { color: var(--admin-text); background: #f0f2f4; }.ui-dialog-form { margin-top: 21px; }.ui-dialog-footer { display: flex; justify-content: flex-end; gap: 7px; margin-top: 23px; }.admin-field { display: block; margin-top: 13px; color: var(--admin-muted); font-size: 10px; font-weight: 680; }.admin-field:first-child { margin-top: 0; }.admin-field input, .admin-field textarea, .admin-field select { display: block; width: 100%; margin-top: 6px; padding: 9px 10px; border: 1px solid var(--admin-line-strong); border-radius: 5px; outline: 0; color: var(--admin-text); background: #fbfcfd; font-size: 11px; }.admin-field input:focus, .admin-field textarea:focus, .admin-field select:focus { border-color: var(--admin-orange); box-shadow: 0 0 0 3px #e56d4d1c; }.admin-field input[readonly] { color: var(--admin-subtle); background: #f4f5f6; }.admin-field textarea { resize: vertical; }.admin-field-hint { margin-left: 5px; color: var(--admin-subtle); font-size: 9px; font-weight: 400; }.admin-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }.admin-info-callout { display: flex; gap: 8px; margin-top: 14px; padding: 10px; border: 1px solid #dfe8f0; border-radius: 5px; color: #58738b; background: #f5f9fc; font-size: 10px; line-height: 1.5; }.admin-info-callout svg { flex: 0 0 auto; color: var(--admin-blue); }.admin-form-error { margin-top: 13px; padding: 10px; border: 1px solid #f2d3cf; border-radius: 5px; color: var(--admin-red); background: #fff5f3; font-size: 10px; line-height: 1.45; }.admin-dropzone { position: relative; margin-top: 16px; }.admin-dropzone input { position: absolute; z-index: 1; inset: 0; width: 100%; height: 100%; cursor: pointer; opacity: 0; }.admin-dropzone label { display: flex; min-height: 145px; align-items: center; justify-content: center; flex-direction: column; gap: 7px; border: 1px dashed #b8c2cc; border-radius: 7px; color: var(--admin-muted); background: #fbfcfd; text-align: center; }.admin-dropzone label:hover { border-color: var(--admin-orange); background: #fffaf8; }.admin-dropzone-icon { display: inline-flex; width: 38px; height: 38px; align-items: center; justify-content: center; border-radius: 7px; color: var(--admin-orange); background: #fff1ed; }.admin-dropzone strong { color: var(--admin-text); font-size: 12px; }.admin-dropzone small { color: var(--admin-subtle); font-size: 9px; }.admin-title-muted { color: var(--admin-subtle); font-family: var(--font-geist-mono), monospace; font-size: 13px; font-weight: 500; }.release-detail-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin-top: 20px; }.release-detail-grid > div, .json-summary-grid > div { min-width: 0; padding: 11px; border: 1px solid var(--admin-line); border-radius: 5px; background: #fbfcfd; }.release-detail-grid span, .json-summary-grid span { display: block; color: var(--admin-subtle); font-size: 9px; }.release-detail-grid strong, .release-detail-grid code, .json-summary-grid strong, .json-summary-grid code { display: block; margin-top: 6px; overflow: hidden; color: var(--admin-text); font-family: var(--font-geist-mono), monospace; font-size: 10px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }.asset-path-panel { margin-top: 15px; padding: 14px; border: 1px solid var(--admin-line); border-radius: 6px; }.asset-path-panel h3 { margin: 0; color: var(--admin-text); font-size: 11px; }.asset-path-panel p { margin: 5px 0 10px; color: var(--admin-subtle); font-size: 9px; }.asset-path-panel ul { max-height: 145px; margin: 0; padding: 0 0 0 16px; overflow-y: auto; }.asset-path-panel li { padding: 4px 0; color: var(--admin-muted); }.asset-path-panel code { color: #596773; font-family: var(--font-geist-mono), monospace; font-size: 9px; }.json-summary-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-top: 15px; }.json-preview { max-height: 390px; margin: 15px 0 0; padding: 13px; overflow: auto; border: 1px solid var(--admin-line); border-radius: 5px; color: #465462; background: #f7f8fa; font-family: var(--font-geist-mono), monospace; font-size: 9px; line-height: 1.55; }.ui-tabs-list { display: flex; gap: 4px; margin-top: 17px; border-bottom: 1px solid var(--admin-line); }.ui-tabs-trigger { padding: 8px 10px; border: 0; border-bottom: 2px solid transparent; color: var(--admin-subtle); background: transparent; font-size: 10px; }.ui-tabs-trigger[data-state="active"] { border-bottom-color: var(--admin-orange); color: var(--admin-text); font-weight: 680; }.ui-tabs-content { outline: 0; }.ui-tabs-content:focus-visible { box-shadow: 0 0 0 3px #e56d4d1c; } +.ui-dialog-content.command-dialog { width: min(100% - 32px, 510px); padding: 0; overflow: hidden; }.ui-command { color: var(--admin-text); background: #fff; }.ui-command-input { display: flex; width: 100%; height: 48px; padding: 0 16px; border: 0; border-bottom: 1px solid var(--admin-line); outline: 0; color: var(--admin-text); background: transparent; font-size: 12px; }.ui-command-list { max-height: 310px; padding: 7px; overflow-y: auto; }.ui-command-empty { padding: 24px; color: var(--admin-subtle); text-align: center; font-size: 11px; }.ui-command-group [cmdk-group-heading] { padding: 8px 9px 5px; color: var(--admin-subtle); font-size: 9px; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; }.ui-command-item { display: flex; align-items: center; gap: 9px; min-height: 35px; padding: 0 9px; border-radius: 5px; color: var(--admin-muted); font-size: 11px; cursor: pointer; }.ui-command-item[data-selected="true"] { color: var(--admin-text); background: #f0f2f4; }.command-shortcut { margin-left: auto; color: var(--admin-subtle); font-family: var(--font-geist-mono), monospace; font-size: 9px; }.ui-dropdown-content { z-index: 60; min-width: 170px; padding: 5px; border: 1px solid var(--admin-line); border-radius: 6px; background: #fff; box-shadow: 0 8px 30px #17202c18; }.ui-dropdown-item { display: flex; min-height: 30px; align-items: center; padding: 0 8px; border-radius: 4px; color: var(--admin-muted); font-size: 10px; outline: 0; }.ui-dropdown-item[data-highlighted] { color: var(--admin-text); background: #f0f2f4; }.ui-dropdown-separator { height: 1px; margin: 5px 0; background: var(--admin-line); } +.admin-toast-viewport { position: fixed; z-index: 100; right: 18px; bottom: 18px; display: flex; width: 360px; max-width: calc(100vw - 36px); flex-direction: column; gap: 8px; outline: 0; }.admin-toast { position: relative; display: grid; grid-template-columns: 1fr auto; gap: 3px 12px; padding: 13px 14px; border: 1px solid var(--admin-line-strong); border-left: 3px solid var(--admin-green); border-radius: 7px; color: var(--admin-text); background: #fff; box-shadow: 0 10px 32px #17202c22; }.admin-toast.toast-error { border-left-color: var(--admin-red); }.admin-toast.toast-info { border-left-color: var(--admin-blue); }.admin-toast [data-radix-toast-title] { font-size: 11px; font-weight: 720; }.admin-toast [data-radix-toast-description] { color: var(--admin-muted); font-size: 10px; line-height: 1.45; }.admin-toast button { grid-column: 2; grid-row: 1 / span 2; align-self: center; border: 0; color: var(--admin-subtle); background: transparent; font-size: 16px; } +.mobile-nav-dialog { top: 0; left: 0; width: min(290px, calc(100vw - 44px)); height: 100vh; max-height: none; padding: 0; border: 0; border-radius: 0 9px 9px 0; transform: none; }.mobile-nav-dialog .admin-sidebar-inner { padding: 16px 12px; }.mobile-nav-close { position: absolute; z-index: 2; top: 16px; right: 13px; display: inline-flex; width: 28px; height: 28px; align-items: center; justify-content: center; border: 0; border-radius: 5px; color: var(--admin-subtle); background: #f1f3f5; } +.settings-placeholder { max-width: 620px; padding: 34px; text-align: center; }.settings-placeholder-icon { display: inline-flex; width: 42px; height: 42px; align-items: center; justify-content: center; border-radius: 8px; color: var(--admin-orange); background: #fff1ed; }.settings-placeholder h2 { margin: 14px 0 7px; color: var(--admin-text); font-size: 16px; }.settings-placeholder > p { max-width: 420px; margin: 0 auto 22px; color: var(--admin-muted); font-size: 11px; line-height: 1.6; }.settings-placeholder-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 9px; margin-bottom: 20px; }.settings-placeholder-grid > div { display: flex; align-items: center; gap: 8px; padding: 12px; border: 1px solid var(--admin-line); border-radius: 6px; text-align: left; }.settings-placeholder-grid svg { color: var(--admin-blue); }.settings-placeholder-grid strong, .settings-placeholder-grid span { display: block; }.settings-placeholder-grid strong { color: var(--admin-text); font-size: 10px; }.settings-placeholder-grid span { margin-top: 3px; color: var(--admin-subtle); font-size: 9px; } +@media (max-width: 1050px) { .admin-sidebar { width: 210px; flex-basis: 210px; }.admin-sidebar.is-collapsed { width: 64px; flex-basis: 64px; }.admin-collapse-toggle { left: 192px; }.admin-sidebar.is-collapsed ~ .admin-collapse-toggle { left: 50px; }.admin-metric-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }.admin-overview-grid { grid-template-columns: 1fr; }.admin-overview-grid .admin-section-card { margin-bottom: 0; }.admin-topbar { padding-inline: 24px; }.admin-content { padding-inline: 24px; } } +@media (max-width: 760px) { .admin-sidebar, .admin-collapse-toggle { display: none; }.admin-topbar { height: 53px; padding: 0 15px; }.mobile-menu-button { display: inline-flex; margin-right: 5px; }.admin-topbar-actions { gap: 8px; }.admin-search-trigger { min-width: 31px; width: 31px; justify-content: center; padding: 0; }.admin-search-trigger span, .admin-search-trigger kbd, .admin-topbar-action span, .admin-auth-link { display: none; }.admin-topbar-action { width: 31px; height: 31px; justify-content: center; padding: 0; border: 1px solid var(--admin-line-strong); border-radius: 6px; }.admin-content { padding: 24px 15px 45px; }.admin-page-heading { align-items: start; flex-direction: column; gap: 15px; margin-bottom: 22px; }.admin-page-heading h1 { font-size: 24px; }.admin-page-actions { width: 100%; }.admin-page-actions .ui-button { flex: 1; }.admin-metric-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }.admin-metric-card { min-height: 102px; padding: 13px; }.admin-metric-card strong { margin-top: 13px; font-size: 21px; }.admin-section-card-header { padding-inline: 14px; }.health-list { grid-template-columns: repeat(2, 1fr); padding-inline: 14px; }.quota-summary { padding-inline: 14px; }.admin-table th, .admin-table td { padding-inline: 13px; }.admin-toolbar { flex-wrap: wrap; padding-inline: 13px; }.admin-search-field { min-width: 100%; max-width: none; }.admin-toolbar-note { margin-left: 0; }.admin-form-grid, .release-detail-grid, .json-summary-grid, .settings-placeholder-grid { grid-template-columns: 1fr; }.ui-dialog-content { width: min(100% - 22px, 520px); padding: 20px 17px; }.ui-dialog-content.wide-dialog { width: min(100% - 22px, 680px); }.admin-toast-viewport { right: 11px; bottom: 11px; max-width: calc(100vw - 22px); }.admin-toast { width: 100%; } } + +/* Root landing page: same neutral/operational language as the dashboard, standalone. */ +.landing { min-height: 100vh; color: var(--admin-text); background: var(--admin-bg); } +.landing-header { display: flex; align-items: center; justify-content: space-between; max-width: 1080px; margin: 0 auto; height: 64px; padding: 0 24px; } +.landing-brand { display: flex; align-items: center; gap: 9px; color: var(--admin-text); font-size: 16px; font-weight: 720; letter-spacing: -.035em; text-decoration: none; } +.landing-beta { margin-left: 4px; color: var(--admin-orange); font-size: 8px; font-weight: 800; letter-spacing: .12em; } +.landing-nav { display: flex; align-items: center; gap: 22px; } +.landing-nav a { color: var(--admin-muted); font-size: 11px; font-weight: 560; text-decoration: none; } +.landing-nav a:hover { color: var(--admin-text); } +.landing-signin { display: inline-flex; align-items: center; gap: 6px; min-height: 33px; padding: 0 13px; border-radius: 6px; color: #fff !important; background: var(--admin-orange); font-size: 11px; font-weight: 660; } +.landing-signin:hover { background: #ce5d42; } +.landing-hero { display: grid; grid-template-columns: 1.15fr .85fr; gap: 48px; align-items: center; max-width: 1080px; margin: 18px auto 0; padding: 70px 24px 84px; } +.landing-eyebrow { color: var(--admin-orange); font-size: 10px; font-weight: 800; letter-spacing: .14em; } +.landing-hero h1 { margin: 16px 0 0; color: var(--admin-text); font-size: clamp(30px, 4vw, 46px); font-weight: 640; letter-spacing: -.05em; line-height: 1.06; } +.landing-hero p { max-width: 540px; margin: 20px 0 0; color: var(--admin-muted); font-size: 14px; line-height: 1.7; } +.landing-hero-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 28px; } +.landing-hero-actions .ui-button { min-height: 38px; font-size: 12px; } +.landing-hero-meta { display: inline-flex; align-items: center; gap: 7px; margin-top: 22px; color: var(--admin-subtle); font-size: 10px; } +.landing-hero-meta svg { color: var(--admin-green); } +.landing-hero-meta code { color: var(--admin-muted); font-family: var(--font-geist-mono), monospace; font-size: 9px; } +.landing-hero-card { display: flex; flex-direction: column; gap: 0; padding: 22px; border: 1px solid var(--admin-line); border-radius: 10px; background: var(--admin-panel); box-shadow: 0 18px 50px #17202c0d; } +.landing-flow-step { display: flex; align-items: center; gap: 12px; padding: 14px 6px; color: var(--admin-muted); font-size: 12px; font-weight: 560; } +.landing-flow-step span:nth-child(2) { display: inline-flex; align-items: center; gap: 8px; } +.landing-flow-step svg { color: var(--admin-subtle); } +.landing-flow-step.done { color: var(--admin-text); } +.landing-flow-step.done svg { color: var(--admin-orange); } +.landing-flow-num { display: inline-flex; width: 22px; height: 22px; flex: 0 0 22px; align-items: center; justify-content: center; border: 1px solid var(--admin-line-strong); border-radius: 50%; color: var(--admin-subtle); font-family: var(--font-geist-mono), monospace; font-size: 10px; font-weight: 700; } +.landing-flow-step.done .landing-flow-num { border-color: var(--admin-orange); color: #fff; background: var(--admin-orange); } +.landing-flow-arrow { width: 1px; height: 18px; margin: 0 0 0 11px; background: var(--admin-line-strong); } +.landing-features { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; max-width: 1080px; margin: 0 auto; padding: 0 24px 80px; } +.landing-feature { min-height: 150px; padding: 22px; border: 1px solid var(--admin-line); border-radius: 9px; background: var(--admin-panel); } +.landing-feature svg { color: var(--admin-orange); } +.landing-feature h2 { margin: 14px 0 7px; color: var(--admin-text); font-size: 14px; font-weight: 660; } +.landing-feature p { margin: 0; color: var(--admin-muted); font-size: 12px; line-height: 1.6; } +.landing-footer { display: flex; align-items: center; justify-content: space-between; max-width: 1080px; margin: 0 auto; padding: 22px 24px 40px; border-top: 1px solid var(--admin-line); color: var(--admin-subtle); font-size: 10px; } +.landing-footer-links { display: flex; gap: 18px; } +.landing-footer-links a { color: var(--admin-muted); text-decoration: none; } +.landing-footer-links a:hover { color: var(--admin-text); } +@media (max-width: 880px) { .landing-hero { grid-template-columns: 1fr; gap: 32px; padding-top: 44px; padding-bottom: 52px; }.landing-features { grid-template-columns: 1fr; }.landing-header { height: 56px; }.landing-nav { gap: 14px; }.landing-nav a:first-child, .landing-nav a:nth-child(2) { display: none; } } +@media (max-width: 560px) { .landing-hero-actions { flex-direction: column; align-items: stretch; }.landing-hero-actions .ui-button { justify-content: center; }.landing-footer { flex-direction: column; gap: 12px; align-items: start; } } diff --git a/app/layout.tsx b/app/layout.tsx new file mode 100644 index 0000000..65560c3 --- /dev/null +++ b/app/layout.tsx @@ -0,0 +1,16 @@ +import type { Metadata } from "next"; +import { Geist, Geist_Mono } from "next/font/google"; +import "./globals.css"; + +const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"] }); +const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"] }); + +export const metadata: Metadata = { + title: "AltDock — Workspace dashboard", + description: "Manage AltStore PAL Sources, apps, and notarized ADP releases.", + icons: { icon: "/favicon.svg", shortcut: "/favicon.svg" }, +}; + +export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) { + return {children}; +} diff --git a/app/lib/dashboard.ts b/app/lib/dashboard.ts new file mode 100644 index 0000000..fe5ae45 --- /dev/null +++ b/app/lib/dashboard.ts @@ -0,0 +1,105 @@ +import type { AppRecord, ReleaseRecord, SourceRecord } from "@/packages/core/src/index"; + +export type DashboardSource = { + source: SourceRecord; + apps: AppRecord[]; + releases: ReleaseRecord[]; +}; + +export type DashboardData = { + workspace: { + name: string; + slug: string; + }; + sources: DashboardSource[]; + usage: { + storageBytes: number; + sourceCount: number; + }; + limits: { + maxSources: number; + maxAppsPerSource: number; + maxStorageBytes: number; + maxUploadBytes: number; + }; +}; + +export type Notice = { + tone: "success" | "error" | "info"; + text: string; +}; + +export type Visibility = SourceRecord["visibility"]; + +export const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:4000"; +export const AUTH_MODE = process.env.NEXT_PUBLIC_AUTH_MODE || "demo"; +export const DEMO_HEADERS = { "x-demo-user": "demo@altdock.local" }; + +export async function api(path: string, init: RequestInit = {}) { + const headers = new Headers(init.headers); + headers.set("accept", "application/json"); + if (init.body) headers.set("content-type", "application/json"); + Object.entries(DEMO_HEADERS).forEach(([key, value]) => headers.set(key, value)); + const response = await fetch(`${API_BASE}${path}`, { ...init, headers, credentials: "include" }); + const body = (await response.json().catch(() => ({}))) as T & { error?: string; detail?: string }; + if (!response.ok) throw new Error(body.detail || body.error || `Request failed (${response.status})`); + return body; +} + +export function formatBytes(value: number) { + if (!value) return "0 B"; + const units = ["B", "KB", "MB", "GB"]; + const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1); + return `${(value / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${units[index]}`; +} + +export function formatDate(value: string) { + return new Intl.DateTimeFormat("ja-JP", { year: "numeric", month: "short", day: "numeric" }).format(new Date(value)); +} + +export function formatDateTime(value: string) { + return new Intl.DateTimeFormat("ja-JP", { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }).format(new Date(value)); +} + +export function statusLabel(status: ReleaseRecord["status"]) { + return { + uploaded: "アップロード済み", + processing: "処理中", + ready: "公開準備完了", + rejected: "要修正", + published: "公開中", + archived: "アーカイブ", + }[status]; +} + +export function statusTone(status: ReleaseRecord["status"]) { + return { + uploaded: "neutral", + processing: "info", + ready: "warning", + rejected: "danger", + published: "success", + archived: "neutral", + }[status] as "neutral" | "info" | "warning" | "danger" | "success"; +} + +export function visibilityLabel(visibility: Visibility) { + return { draft: "下書き", unlisted: "限定公開", public: "公開" }[visibility]; +} + +export function visibilityTone(visibility: Visibility) { + return { draft: "neutral", unlisted: "warning", public: "success" }[visibility] as "neutral" | "warning" | "success"; +} + +export function flattenSources(dashboard: DashboardData) { + return dashboard.sources; +} + +export function flattenApps(dashboard: DashboardData) { + return dashboard.sources.flatMap((entry) => entry.apps.map((app) => ({ app, source: entry.source, releases: entry.releases.filter((release) => release.appId === app.id) }))); +} + +export function flattenReleases(dashboard: DashboardData) { + return dashboard.sources.flatMap((entry) => entry.releases.map((release) => ({ release, source: entry.source, app: entry.apps.find((app) => app.id === release.appId) }))); +} + diff --git a/app/page.tsx b/app/page.tsx new file mode 100644 index 0000000..80dbbde --- /dev/null +++ b/app/page.tsx @@ -0,0 +1,53 @@ +"use client"; + +import Link from "next/link"; +import { ArrowRight, Boxes, FileArchive, Gauge, KeyRound, ShieldCheck, UploadCloud } from "lucide-react"; +import { AUTH_MODE, API_BASE } from "@/app/lib/dashboard"; + +export default function Home() { + return
+
+ AAltDockBETA + +
+ +
+
+
ALTSTORE PAL · ADP HOSTING
+

Notarization済みのADPを、
そのままPALへ届ける。

+

Appleの検証チェーンを壊さず、ADP ZIPをアップロードするだけでAltStore PAL互換のSourceを公開できるホスティング基盤です。Manifestとsignatureは再シリアライズせず、元のバイト列を保持します。

+
+ ダッシュボードを開く + 配布要件を見る +
+
Demo mode で起動中 · API {API_BASE}
+
+ +
+ +
+

元のパッケージを保持

ADPの階層・ハッシュ・manifest.json・signatureを一切書き換えません。Appleの検証チェーンがそのまま通ります。

+

検証を自動化

パストラバーサル、シンボリックリンク、ZIP爆弾、欠落・余分なファイルをWorkerで検査し、問題があれば拒否します。

+

Workspace単位の認可

汎用OIDC SSOでユーザーを識別し、WorkspaceごとにSource・アプリ・ファイルを分離します。

+
+ + +
; +} diff --git a/app/sources/[slug]/PublicSourceView.tsx b/app/sources/[slug]/PublicSourceView.tsx new file mode 100644 index 0000000..647ddfc --- /dev/null +++ b/app/sources/[slug]/PublicSourceView.tsx @@ -0,0 +1,45 @@ +"use client"; + +import { useEffect, useState } from "react"; +import Link from "next/link"; + +type SourceDocument = { + name: string; + subtitle?: string; + description?: string; + iconURL?: string; + tintColor?: string; + apps: Array<{ name: string; bundleIdentifier: string; developerName: string; subtitle?: string; localizedDescription: string; iconURL?: string; category: string; versions: Array<{ version: string; buildVersion: string; date: string; downloadURL: string; size: number }> }>; +}; + +const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:4000"; + +function formatBytes(value: number) { + if (!value) return "0 B"; + const units = ["B", "KB", "MB", "GB"]; + const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1); + return `${(value / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${units[index]}`; +} + +export default function PublicSourceView({ slug }: { slug: string }) { + const [document, setDocument] = useState(null); + const [error, setError] = useState(false); + + useEffect(() => { + fetch(`${API_BASE}/sources/${slug}/source.json`) + .then((response) => response.ok ? response.json() : Promise.reject(new Error("not found"))) + .then(setDocument) + .catch(() => setError(true)); + }, [slug]); + + if (error) return
A

Source not found

This Source is still a draft or the URL is incorrect.

Open AltDock
; + if (!document) return
A

Loading Source…

; + + return
+
AAltDockALTSTORE PAL SOURCE
+
{document.iconURL ? : document.name.slice(0, 1)}
SOURCE / {slug}

{document.name}

{document.subtitle}

+ {document.description &&

{document.description}

} +
{document.apps.length ? document.apps.map((app) => { const release = app.versions[0]; return
{app.iconURL ? : app.name.slice(0, 1)}{app.category}

{app.name}

{app.developerName} · {app.bundleIdentifier}

{app.localizedDescription || app.subtitle || "A PAL-ready iOS app."}

{release ?
Latest releasev{release.version} build {release.buildVersion}{formatBytes(release.size)}
:
No published release yet
}
; }) :
No published apps yet.

Come back when the developer ships their first release.

}
+
Powered by AltDockSource JSON is available for AltStore PAL.
+
; +} diff --git a/app/sources/[slug]/page.tsx b/app/sources/[slug]/page.tsx new file mode 100644 index 0000000..f21cd9e --- /dev/null +++ b/app/sources/[slug]/page.tsx @@ -0,0 +1,6 @@ +import PublicSourceView from "./PublicSourceView"; + +export default async function PublicSourcePage({ params }: { params: Promise<{ slug: string }> }) { + const { slug } = await params; + return ; +} diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts new file mode 100644 index 0000000..e1aecde --- /dev/null +++ b/apps/api/src/auth.ts @@ -0,0 +1,126 @@ +import { createHash, randomBytes } from "node:crypto"; +import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; +import { createRemoteJWKSet, jwtVerify, SignJWT } from "jose"; +import type { Identity } from "../../../packages/core/src/index"; +import type { AppConfig } from "./config"; + +const stateCookie = "altdock_oidc_state"; +const verifierCookie = "altdock_oidc_verifier"; +const nonceCookie = "altdock_oidc_nonce"; +const sessionCookie = "altdock_session"; + +function base64Url(value: Buffer) { + return value.toString("base64url"); +} + +function pkceChallenge(verifier: string) { + return createHash("sha256").update(verifier).digest("base64url"); +} + +export async function createSession(identity: Identity, appConfig: AppConfig) { + return new SignJWT({ ...identity }) + .setProtectedHeader({ alg: "HS256" }) + .setIssuedAt() + .setExpirationTime("7d") + .sign(new TextEncoder().encode(appConfig.SESSION_SECRET)); +} + +export async function readSession(token: string | undefined, appConfig: AppConfig): Promise { + if (!token) return null; + try { + const result = await jwtVerify(token, new TextEncoder().encode(appConfig.SESSION_SECRET), { algorithms: ["HS256"] }); + const payload = result.payload; + if (typeof payload.subject !== "string" || typeof payload.email !== "string" || typeof payload.displayName !== "string") return null; + return { subject: payload.subject, email: payload.email, displayName: payload.displayName }; + } catch { + return null; + } +} + +export async function getIdentity(request: FastifyRequest, appConfig: AppConfig): Promise { + if (appConfig.AUTH_MODE === "demo") { + const email = String(request.headers["x-demo-user"] || "demo@altdock.local"); + return { subject: `demo:${email}`, email, displayName: email.split("@")[0] || "Demo Developer" }; + } + return readSession(request.cookies[sessionCookie], appConfig); +} + +function setSession(reply: FastifyReply, token: string) { + reply.setCookie(sessionCookie, token, { + httpOnly: true, + sameSite: "lax", + secure: process.env.NODE_ENV === "production", + path: "/", + maxAge: 60 * 60 * 24 * 7, + }); +} + +async function oidcDiscovery(appConfig: AppConfig) { + if (!appConfig.OIDC_ISSUER_URL) throw new Error("OIDC_ISSUER_URL_REQUIRED"); + const response = await fetch(`${appConfig.OIDC_ISSUER_URL.replace(/\/$/, "")}/.well-known/openid-configuration`); + if (!response.ok) throw new Error(`OIDC_DISCOVERY_FAILED:${response.status}`); + return response.json() as Promise<{ authorization_endpoint: string; token_endpoint: string; jwks_uri: string; issuer: string }>; +} + +export async function registerAuthRoutes(app: FastifyInstance, appConfig: AppConfig) { + app.get("/auth/login", async (_request, reply) => { + if (appConfig.AUTH_MODE === "demo") return reply.redirect(appConfig.WEB_ORIGIN); + if (!appConfig.OIDC_CLIENT_ID || !appConfig.OIDC_REDIRECT_URI) throw new Error("OIDC_CONFIGURATION_REQUIRED"); + const provider = await oidcDiscovery(appConfig); + const state = base64Url(randomBytes(24)); + const verifier = base64Url(randomBytes(32)); + const nonce = base64Url(randomBytes(24)); + const params = new URLSearchParams({ + client_id: appConfig.OIDC_CLIENT_ID, + redirect_uri: appConfig.OIDC_REDIRECT_URI, + response_type: "code", + scope: "openid profile email", + state, + nonce, + code_challenge: pkceChallenge(verifier), + code_challenge_method: "S256", + }); + reply.setCookie(stateCookie, state, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/auth" }); + reply.setCookie(verifierCookie, verifier, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/auth" }); + reply.setCookie(nonceCookie, nonce, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/auth" }); + return reply.redirect(`${provider.authorization_endpoint}?${params.toString()}`); + }); + + app.get("/auth/callback", async (request, reply) => { + if (appConfig.AUTH_MODE === "demo") return reply.redirect(appConfig.WEB_ORIGIN); + if (!appConfig.OIDC_CLIENT_ID || !appConfig.OIDC_REDIRECT_URI || !appConfig.OIDC_CLIENT_SECRET) throw new Error("OIDC_CONFIGURATION_REQUIRED"); + const query = request.query as { code?: string; state?: string; error?: string }; + if (query.error) return reply.code(400).send({ error: "OIDC_LOGIN_FAILED", detail: query.error }); + if (!query.code || query.state !== request.cookies[stateCookie]) return reply.code(400).send({ error: "OIDC_STATE_INVALID" }); + const verifier = request.cookies[verifierCookie]; + const nonce = request.cookies[nonceCookie]; + if (!verifier || !nonce) return reply.code(400).send({ error: "OIDC_VERIFIER_MISSING" }); + const provider = await oidcDiscovery(appConfig); + const tokenResponse = await fetch(provider.token_endpoint, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ grant_type: "authorization_code", code: query.code, redirect_uri: appConfig.OIDC_REDIRECT_URI, client_id: appConfig.OIDC_CLIENT_ID, client_secret: appConfig.OIDC_CLIENT_SECRET, code_verifier: verifier }), + }); + if (!tokenResponse.ok) return reply.code(400).send({ error: "OIDC_TOKEN_EXCHANGE_FAILED" }); + const tokens = await tokenResponse.json() as { id_token?: string; access_token?: string }; + if (!tokens.id_token) return reply.code(400).send({ error: "OIDC_ID_TOKEN_MISSING" }); + const jwks = createRemoteJWKSet(new URL(provider.jwks_uri)); + const verified = await jwtVerify(tokens.id_token, jwks, { issuer: provider.issuer, audience: appConfig.OIDC_CLIENT_ID }); + const claims = verified.payload; + if (claims.nonce !== nonce) return reply.code(400).send({ error: "OIDC_NONCE_INVALID" }); + const subject = String(claims.sub || ""); + if (!subject) return reply.code(400).send({ error: "OIDC_SUBJECT_MISSING" }); + const email = String(claims.email || `${subject}@oidc.local`); + const displayName = String(claims.name || claims.preferred_username || email.split("@")[0] || "Developer"); + setSession(reply, await createSession({ subject, email, displayName }, appConfig)); + reply.clearCookie(stateCookie, { path: "/auth" }); + reply.clearCookie(verifierCookie, { path: "/auth" }); + reply.clearCookie(nonceCookie, { path: "/auth" }); + return reply.redirect(appConfig.WEB_ORIGIN); + }); + + app.get("/auth/logout", async (_request, reply) => { + reply.clearCookie(sessionCookie, { path: "/" }); + return reply.redirect(appConfig.WEB_ORIGIN); + }); +} diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts new file mode 100644 index 0000000..5c7b1f6 --- /dev/null +++ b/apps/api/src/config.ts @@ -0,0 +1,49 @@ +import { z } from "zod"; + +const booleanFromEnv = z.preprocess((value) => { + if (typeof value !== "string") return value; + return ["1", "true", "yes", "on"].includes(value.toLowerCase()); +}, z.boolean()); + +const numberFromEnv = z.preprocess( + (value) => (typeof value === "string" ? Number(value) : value), + z.number().finite(), +); + +const schema = z.object({ + NODE_ENV: z.enum(["development", "test", "production"]).default("development"), + HOST: z.string().default("0.0.0.0"), + PORT: numberFromEnv.default(4000), + PUBLIC_BASE_URL: z.string().url().default("http://localhost:4000"), + WEB_ORIGIN: z.string().url().default("http://localhost:3000"), + DATABASE_URL: z.string().optional(), + STORAGE_MODE: z.enum(["local", "s3"]).default("local"), + LOCAL_STORAGE_DIR: z.string().default(".data/storage"), + S3_ENDPOINT: z.string().url().optional(), + S3_REGION: z.string().default("auto"), + S3_BUCKET: z.string().default("altdock"), + S3_ACCESS_KEY_ID: z.string().optional(), + S3_SECRET_ACCESS_KEY: z.string().optional(), + S3_FORCE_PATH_STYLE: booleanFromEnv.default(true), + AUTH_MODE: z.enum(["demo", "oidc"]).default("demo"), + SESSION_SECRET: z.string().min(32).default("altdock-local-session-secret-change-me-123456"), + OIDC_ISSUER_URL: z.string().url().optional(), + OIDC_CLIENT_ID: z.string().optional(), + OIDC_CLIENT_SECRET: z.string().optional(), + OIDC_REDIRECT_URI: z.string().url().optional(), + MAX_UPLOAD_BYTES: numberFromEnv.default(5 * 1024 * 1024 * 1024), + MAX_ARCHIVE_ENTRIES: numberFromEnv.default(2048), + MAX_EXPANDED_BYTES: numberFromEnv.default(8 * 1024 * 1024 * 1024), + MAX_SOURCES_PER_WORKSPACE: numberFromEnv.default(3), + MAX_APPS_PER_SOURCE: numberFromEnv.default(20), + MAX_STORAGE_BYTES: numberFromEnv.default(20 * 1024 * 1024 * 1024), + PROCESS_INLINE: booleanFromEnv.default(true), +}); + +export type AppConfig = z.infer; + +export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig { + return schema.parse(env); +} + +export const config = loadConfig(); diff --git a/apps/api/src/manifest.ts b/apps/api/src/manifest.ts new file mode 100644 index 0000000..4b74417 --- /dev/null +++ b/apps/api/src/manifest.ts @@ -0,0 +1,183 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { createHash } from "node:crypto"; +import { posix } from "node:path"; +import { Transform } from "node:stream"; +import unzipper from "unzipper"; +import type { ManifestSummary, ReleaseAsset } from "../../../packages/core/src/index"; +import type { StorageAdapter } from "./storage"; + +interface ZipEntryLike { + path: string; + type: string; + uncompressedSize?: number; + buffer(): Promise; + stream(): NodeJS.ReadableStream; +} + +export interface AdpInspection { + manifestBytes: Buffer; + signatureBytes: Buffer; + manifest: Record; + summary: ManifestSummary; + expectedPaths: string[]; + entries: Map; + archiveSizeBytes: number; +} + +function safeZipPath(value: string) { + const normalized = value.replaceAll("\\", "/"); + if (!normalized || normalized.startsWith("/") || normalized.includes("\0")) { + throw new Error("ADP_PATH_INVALID"); + } + const clean = posix.normalize(normalized); + if (clean === "." || clean.startsWith("../") || clean.includes("/../") || clean === "..") { + throw new Error("ADP_PATH_TRAVERSAL"); + } + return clean; +} + +function collectAssetPaths(value: unknown, output: Set) { + if (!value || typeof value !== "object") return; + if (Array.isArray(value)) { + for (const item of value) collectAssetPaths(item, output); + return; + } + for (const [key, child] of Object.entries(value)) { + if (["assetPath", "sourcePath", "deltaPath"].includes(key) && typeof child === "string") { + output.add(safeZipPath(child)); + } + collectAssetPaths(child, output); + } +} + +function stringRecord(value: unknown) { + if (!value || typeof value !== "object" || Array.isArray(value)) return {}; + return Object.fromEntries(Object.entries(value).filter(([, item]) => typeof item === "string")) as Record; +} + +function summaryFromManifest(manifest: Record): ManifestSummary { + const variantPaths = new Set(); + const deltaPaths = new Set(); + collectAssetPaths(manifest.variants, variantPaths); + collectAssetPaths(manifest.deltas, deltaPaths); + return { + distributionPackageRevision: typeof manifest.distributionPackageRevision === "number" ? manifest.distributionPackageRevision : undefined, + appleItemId: String(manifest.appleItemId || ""), + bundleId: String(manifest.bundleId || ""), + shortVersionString: String(manifest.shortVersionString || ""), + bundleVersion: String(manifest.bundleVersion || ""), + appleVersionId: manifest.appleVersionId ? String(manifest.appleVersionId) : undefined, + platforms: Array.isArray(manifest.platforms) ? manifest.platforms.map(String) : [], + minimumSystemVersions: stringRecord(manifest.minimumSystemVersions), + variantPaths: [...variantPaths], + deltaPaths: [...deltaPaths], + }; +} + +export async function inspectAdpArchive( + archivePath: string, + maxEntries: number, + maxExpandedBytes: number, +): Promise { + const directory = await unzipper.Open.file(archivePath); + if (directory.files.length > maxEntries) throw new Error("ADP_TOO_MANY_FILES"); + const entries = new Map(); + let expandedBytes = 0; + for (const rawEntry of directory.files as unknown as ZipEntryLike[]) { + const path = safeZipPath(rawEntry.path); + if (rawEntry.type !== "File" && rawEntry.type !== "Directory") throw new Error("ADP_LINK_ENTRY"); + if (rawEntry.type === "Directory" || path.endsWith("/")) continue; + expandedBytes += Number(rawEntry.uncompressedSize || 0); + if (expandedBytes > maxExpandedBytes) throw new Error("ADP_EXPANDED_SIZE_LIMIT"); + if (entries.has(path)) throw new Error("ADP_DUPLICATE_PATH"); + entries.set(path, rawEntry); + } + + const manifestEntry = entries.get("manifest.json"); + const signatureEntry = entries.get("signature"); + if (!manifestEntry || !signatureEntry) throw new Error("ADP_REQUIRED_FILE_MISSING"); + const manifestBytes = await manifestEntry.buffer(); + let manifest: Record; + try { + manifest = JSON.parse(manifestBytes.toString("utf8")); + } catch { + throw new Error("ADP_MANIFEST_INVALID_JSON"); + } + const assetPaths = new Set(); + collectAssetPaths(manifest.variants, assetPaths); + collectAssetPaths(manifest.deltas, assetPaths); + const expectedPaths = ["manifest.json", "signature", ...assetPaths].sort(); + const actualPaths = [...entries.keys()].sort(); + if (expectedPaths.join("\n") !== actualPaths.join("\n")) { + const missing = expectedPaths.filter((path) => !entries.has(path)); + const extra = actualPaths.filter((path) => !expectedPaths.includes(path)); + const reason = missing.length ? `missing:${missing.join(",")}` : `extra:${extra.join(",")}`; + throw new Error(`ADP_FILE_SET_MISMATCH:${reason}`); + } + const summary = summaryFromManifest(manifest); + if (!summary.appleItemId || !summary.bundleId || !summary.shortVersionString || !summary.bundleVersion) { + throw new Error("ADP_MANIFEST_METADATA_MISSING"); + } + return { + manifestBytes, + signatureBytes: await signatureEntry.buffer(), + manifest, + summary, + expectedPaths, + entries, + archiveSizeBytes: 0, + }; +} + +function contentTypeFor(path: string) { + if (path === "manifest.json") return "application/json; charset=utf-8"; + if (path.endsWith(".ipa")) return "application/octet-stream"; + return "application/octet-stream"; +} + +class HashTransform extends Transform { + readonly hash = createHash("sha256"); + sizeBytes = 0; + + _transform(chunk: Buffer, _encoding: BufferEncoding, callback: (error?: Error | null, data?: Buffer) => void) { + this.hash.update(chunk); + this.sizeBytes += chunk.length; + callback(null, chunk); + } +} + +export async function storeAdpAssets( + archivePath: string, + releaseId: string, + inspection: AdpInspection, + storage: StorageAdapter, +): Promise<{ assets: ReleaseAsset[]; totalBytes: number }> { + const assets: ReleaseAsset[] = []; + const freshDirectory = await unzipper.Open.file(archivePath); + const freshEntries = new Map(); + for (const rawEntry of freshDirectory.files as unknown as ZipEntryLike[]) { + if (rawEntry.type !== "File" && rawEntry.type !== "Directory") throw new Error("ADP_LINK_ENTRY"); + if (rawEntry.type === "Directory" || rawEntry.path.endsWith("/")) continue; + freshEntries.set(safeZipPath(rawEntry.path), rawEntry); + } + + for (const path of inspection.expectedPaths) { + const entry = freshEntries.get(path); + if (!entry) throw new Error("ADP_REQUIRED_FILE_MISSING"); + const objectKey = `artifacts/${releaseId}/${path}`; + if (path === "manifest.json") { + await storage.writeObject(objectKey, inspection.manifestBytes, "application/json; charset=utf-8"); + assets.push({ releaseId, path, objectKey, sizeBytes: inspection.manifestBytes.length, sha256: createHash("sha256").update(inspection.manifestBytes).digest("hex"), contentType: contentTypeFor(path) }); + continue; + } + if (path === "signature") { + await storage.writeObject(objectKey, inspection.signatureBytes, "application/octet-stream"); + assets.push({ releaseId, path, objectKey, sizeBytes: inspection.signatureBytes.length, sha256: createHash("sha256").update(inspection.signatureBytes).digest("hex"), contentType: contentTypeFor(path) }); + continue; + } + const transform = new HashTransform(); + await storage.writeStream(objectKey, transform, contentTypeFor(path), Number(entry.uncompressedSize || 0), entry.stream()); + assets.push({ releaseId, path, objectKey, sizeBytes: transform.sizeBytes, sha256: transform.hash.digest("hex"), contentType: contentTypeFor(path) }); + } + return { assets, totalBytes: assets.reduce((sum, asset) => sum + asset.sizeBytes, 0) }; +} diff --git a/apps/api/src/migrate.ts b/apps/api/src/migrate.ts new file mode 100644 index 0000000..602b54d --- /dev/null +++ b/apps/api/src/migrate.ts @@ -0,0 +1,11 @@ +import { loadConfig } from "./config"; +import { createRuntime } from "./runtime"; + +const appConfig = loadConfig(); +if (!appConfig.DATABASE_URL) { + console.log("DATABASE_URL is not configured; memory mode does not need a migration."); + process.exit(0); +} +const runtime = await createRuntime(appConfig); +await runtime.pool?.end(); +console.log("AltDock database schema is ready."); diff --git a/apps/api/src/processor.ts b/apps/api/src/processor.ts new file mode 100644 index 0000000..833835f --- /dev/null +++ b/apps/api/src/processor.ts @@ -0,0 +1,66 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import type { AppMetadata } from "../../../packages/core/src/index"; +import { inspectAdpArchive, storeAdpAssets } from "./manifest"; +import type { AppConfig } from "./config"; +import type { Store } from "./store"; +import type { StorageAdapter } from "./storage"; + +export async function processUpload(uploadId: string, store: Store, storage: StorageAdapter, appConfig: AppConfig) { + const upload = await store.getUpload(uploadId); + if (!upload) throw new Error("UPLOAD_NOT_FOUND"); + await store.updateUpload(uploadId, { status: "processing", errorCode: undefined, errorMessage: undefined }); + const workDir = await mkdtemp(join(tmpdir(), "altdock-upload-")); + const archivePath = join(workDir, "package.zip"); + try { + await storage.downloadToFile(upload.objectKey, archivePath); + const inspection = await inspectAdpArchive(archivePath, appConfig.MAX_ARCHIVE_ENTRIES, appConfig.MAX_EXPANDED_BYTES); + const source = await store.getSource(upload.sourceId); + if (!source) throw new Error("SOURCE_NOT_FOUND"); + const existingApp = upload.appId ? await store.getApp(upload.appId) : null; + const metadata: Partial = existingApp || { + name: source.name, + developerName: "AltDock Developer", + localizedDescription: `Release ${inspection.summary.shortVersionString} (${inspection.summary.bundleVersion})`, + subtitle: "", + tintColor: source.tintColor, + category: "other", + screenshots: [], + appPermissions: { entitlements: [], privacy: {} }, + }; + const app = await store.upsertApp(upload.sourceId, { + bundleIdentifier: inspection.summary.bundleId, + marketplaceID: inspection.summary.appleItemId, + metadata, + }); + await store.updateUpload(uploadId, { appId: app.id }); + const releaseId = randomUUID(); + const release = await store.createRelease({ + id: releaseId, + appId: app.id, + uploadId, + version: inspection.summary.shortVersionString, + buildVersion: inspection.summary.bundleVersion, + appleItemId: inspection.summary.appleItemId, + date: new Date().toISOString(), + localizedDescription: metadata.localizedDescription || "", + minOSVersion: inspection.summary.minimumSystemVersions.ios, + sizeBytes: 0, + manifest: inspection.summary, + }); + const result = await storeAdpAssets(archivePath, release.id, inspection, storage); + await store.addReleaseAssets(result.assets); + const completed = await store.updateRelease(release.id, { sizeBytes: result.totalBytes, status: "ready" }); + await store.updateUpload(uploadId, { status: "completed", receivedSize: upload.receivedSize || upload.expectedSize }); + return completed; + } catch (error) { + const message = error instanceof Error ? error.message : "ADP_PROCESSING_FAILED"; + console.error(`[altdock] upload ${uploadId} failed: ${message}`); + await store.updateUpload(uploadId, { status: "failed", errorCode: message.split(":")[0], errorMessage: message }); + throw error; + } finally { + await rm(workDir, { recursive: true, force: true }); + } +} diff --git a/apps/api/src/runtime.ts b/apps/api/src/runtime.ts new file mode 100644 index 0000000..b53960d --- /dev/null +++ b/apps/api/src/runtime.ts @@ -0,0 +1,9 @@ +import type { AppConfig } from "./config"; +import { createStore } from "./store"; +import { createStorage } from "./storage"; + +export async function createRuntime(appConfig: AppConfig) { + const { store, pool } = await createStore(appConfig); + await store.init(); + return { store, storage: createStorage(appConfig), pool }; +} diff --git a/apps/api/src/schema.ts b/apps/api/src/schema.ts new file mode 100644 index 0000000..c0e6103 --- /dev/null +++ b/apps/api/src/schema.ts @@ -0,0 +1,115 @@ +export const schemaSql = ` +CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + subject TEXT NOT NULL UNIQUE, + email TEXT NOT NULL, + display_name TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS workspaces ( + id TEXT PRIMARY KEY, + owner_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + slug TEXT NOT NULL UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS sources ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE, + slug TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + subtitle TEXT NOT NULL DEFAULT '', + description TEXT NOT NULL DEFAULT '', + icon_url TEXT, + header_url TEXT, + website TEXT, + tint_color TEXT NOT NULL DEFAULT '#E9694B', + visibility TEXT NOT NULL DEFAULT 'draft' CHECK (visibility IN ('draft', 'unlisted', 'public')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS apps ( + id TEXT PRIMARY KEY, + source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE, + name TEXT NOT NULL, + bundle_identifier TEXT NOT NULL, + marketplace_id TEXT NOT NULL, + developer_name TEXT NOT NULL, + subtitle TEXT NOT NULL DEFAULT '', + localized_description TEXT NOT NULL DEFAULT '', + icon_url TEXT, + tint_color TEXT NOT NULL DEFAULT '#E9694B', + category TEXT NOT NULL DEFAULT 'other', + screenshots JSONB NOT NULL DEFAULT '[]'::jsonb, + app_permissions JSONB NOT NULL DEFAULT '{"entitlements":[],"privacy":{}}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE(source_id, bundle_identifier) +); + +CREATE TABLE IF NOT EXISTS uploads ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE, + source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE, + app_id TEXT REFERENCES apps(id) ON DELETE SET NULL, + object_key TEXT NOT NULL UNIQUE, + multipart_upload_id TEXT, + original_filename TEXT NOT NULL, + expected_size BIGINT NOT NULL, + received_size BIGINT NOT NULL DEFAULT 0, + status TEXT NOT NULL DEFAULT 'created', + error_code TEXT, + error_message TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS releases ( + id TEXT PRIMARY KEY, + app_id TEXT NOT NULL REFERENCES apps(id) ON DELETE CASCADE, + upload_id TEXT NOT NULL REFERENCES uploads(id) ON DELETE CASCADE, + version TEXT NOT NULL, + build_version TEXT NOT NULL, + apple_item_id TEXT NOT NULL, + date TIMESTAMPTZ NOT NULL, + localized_description TEXT NOT NULL DEFAULT '', + min_os_version TEXT, + size_bytes BIGINT NOT NULL DEFAULT 0, + status TEXT NOT NULL DEFAULT 'processing', + error_code TEXT, + error_message TEXT, + manifest JSONB NOT NULL, + published_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE(app_id, version, build_version) +); + +CREATE TABLE IF NOT EXISTS release_assets ( + id TEXT PRIMARY KEY, + release_id TEXT NOT NULL REFERENCES releases(id) ON DELETE CASCADE, + path TEXT NOT NULL, + object_key TEXT NOT NULL UNIQUE, + size_bytes BIGINT NOT NULL, + sha256 TEXT NOT NULL, + content_type TEXT NOT NULL, + UNIQUE(release_id, path) +); + +CREATE TABLE IF NOT EXISTS audit_events ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE, + action TEXT NOT NULL, + entity_type TEXT NOT NULL, + entity_id TEXT NOT NULL, + payload JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS sources_workspace_idx ON sources(workspace_id); +ALTER TABLE uploads ADD COLUMN IF NOT EXISTS multipart_upload_id TEXT; +CREATE INDEX IF NOT EXISTS apps_source_idx ON apps(source_id); +CREATE INDEX IF NOT EXISTS releases_app_idx ON releases(app_id); +CREATE INDEX IF NOT EXISTS uploads_queue_idx ON uploads(status, created_at); +`; diff --git a/apps/api/src/server.ts b/apps/api/src/server.ts new file mode 100644 index 0000000..45aa2c0 --- /dev/null +++ b/apps/api/src/server.ts @@ -0,0 +1,301 @@ +import { randomUUID } from "node:crypto"; +import { posix } from "node:path"; +import { Readable } from "node:stream"; +import Fastify, { type FastifyReply, type FastifyRequest } from "fastify"; +import cookie from "@fastify/cookie"; +import cors from "@fastify/cors"; +import { z } from "zod"; +import { buildSourceDocument } from "../../../packages/core/src/index"; +import type { Identity } from "../../../packages/core/src/index"; +import { loadConfig } from "./config"; +import { getIdentity, registerAuthRoutes } from "./auth"; +import { processUpload } from "./processor"; +import { createRuntime } from "./runtime"; + +const sourceInput = z.object({ + name: z.string().trim().min(1).max(80), + subtitle: z.string().max(160).default(""), + description: z.string().max(4000).default(""), + visibility: z.enum(["draft", "unlisted", "public"]).default("draft"), + iconURL: z.string().url().optional(), + headerURL: z.string().url().optional(), + website: z.string().url().optional(), + tintColor: z.string().regex(/^#?[0-9a-f]{6}$/i).default("#E9694B"), +}); + +const uploadInput = z.object({ + sourceId: z.string().min(1), + appId: z.string().optional(), + filename: z.string().trim().min(1).max(180), + sizeBytes: z.number().int().positive(), +}); + +const appInput = z.object({ + sourceId: z.string().min(1), + name: z.string().trim().min(1).max(80).optional(), + developerName: z.string().max(120).optional(), + subtitle: z.string().max(160).optional(), + localizedDescription: z.string().max(4000).optional(), + iconURL: z.string().url().optional(), + tintColor: z.string().regex(/^#?[0-9a-f]{6}$/i).optional(), + category: z.string().max(32).optional(), + screenshots: z.array(z.object({ imageURL: z.string().url(), width: z.number().int().positive().optional(), height: z.number().int().positive().optional() })).max(12).optional(), + appPermissions: z.object({ entitlements: z.array(z.string()).max(200), privacy: z.record(z.string(), z.string()).default({}) }).optional(), +}); + +const multipartPartsInput = z.object({ + parts: z.array(z.object({ partNumber: z.number().int().positive(), etag: z.string().min(1) })).max(10000).optional(), +}).default({}); + +function safePath(value: string) { + const decoded = decodeURIComponent(value).replaceAll("\\", "/"); + const normalized = posix.normalize(decoded); + if (!normalized || normalized.startsWith("/") || normalized === "." || normalized.startsWith("../") || normalized.includes("/../")) return null; + return normalized; +} + +function errorMessage(error: unknown) { + return error instanceof Error ? error.message : "UNKNOWN_ERROR"; +} + +async function requireIdentity(request: FastifyRequest, reply: FastifyReply, appConfig: ReturnType) { + const identity = await getIdentity(request, appConfig); + if (!identity) { + await reply.code(401).send({ error: "AUTHENTICATION_REQUIRED" }); + return null; + } + return identity; +} + +async function requireOwnedSource(id: string, identity: Identity, runtime: Awaited>, appConfig: ReturnType) { + const workspace = await runtime.store.getWorkspace(identity); + const source = await runtime.store.getSource(id, workspace.id); + if (!source) throw new Error("SOURCE_NOT_FOUND"); + const usage = await runtime.store.getUsage(workspace.id); + return { workspace, source, usage, appConfig }; +} + +export async function createServer() { + const appConfig = loadConfig(); + const runtime = await createRuntime(appConfig); + const app = Fastify({ logger: appConfig.NODE_ENV !== "test", bodyLimit: appConfig.MAX_UPLOAD_BYTES }); + app.addContentTypeParser(["application/zip", "application/octet-stream"], { parseAs: "buffer" }, (_request, payload, done) => done(null, payload)); + await app.register(cookie); + // The control plane (web :3000) and API (:4000) are cross-origin, so allow + // the write methods the dashboard uses; @fastify/cors otherwise defaults to + // GET/HEAD/POST and blocks PATCH/PUT in the browser. + await app.register(cors, { origin: true, credentials: true, methods: ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] }); + await registerAuthRoutes(app, appConfig); + + app.get("/healthz", async () => ({ ok: true, service: "altdock-api", storageMode: appConfig.STORAGE_MODE })); + + app.get("/api/v1/me", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const workspace = await runtime.store.getWorkspace(identity); + return { identity, workspace }; + }); + + app.get("/api/v1/dashboard", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const workspace = await runtime.store.getWorkspace(identity); + let sources = await runtime.store.listSources(workspace.id); + if (appConfig.AUTH_MODE === "demo" && sources.length === 0) { + await runtime.store.createSource(workspace.id, { name: "Demo Source", subtitle: "A PAL-ready app shelf", description: "Upload a notarized ADP ZIP to publish your first app.", visibility: "draft", tintColor: "#E9694B" }); + sources = await runtime.store.listSources(workspace.id); + } + const enriched = await Promise.all(sources.map(async (source) => ({ source, apps: await runtime.store.listApps(source.id), releases: await runtime.store.listReleasesForSource(source.id) }))); + return { workspace, sources: enriched, usage: await runtime.store.getUsage(workspace.id), limits: { maxSources: appConfig.MAX_SOURCES_PER_WORKSPACE, maxAppsPerSource: appConfig.MAX_APPS_PER_SOURCE, maxStorageBytes: appConfig.MAX_STORAGE_BYTES, maxUploadBytes: appConfig.MAX_UPLOAD_BYTES } }; + }); + + app.post("/api/v1/sources", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const input = sourceInput.parse(request.body); + const workspace = await runtime.store.getWorkspace(identity); + const existing = await runtime.store.listSources(workspace.id); + if (existing.length >= appConfig.MAX_SOURCES_PER_WORKSPACE) return reply.code(409).send({ error: "SOURCE_QUOTA_REACHED" }); + const source = await runtime.store.createSource(workspace.id, input); + return reply.code(201).send({ source }); + }); + + app.patch("/api/v1/sources/:id", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const input = sourceInput.partial().parse(request.body); + const sourceId = (request.params as { id: string }).id; + const workspace = await runtime.store.getWorkspace(identity); + const source = await runtime.store.updateSource(sourceId, workspace.id, input); + if (!source) return reply.code(404).send({ error: "SOURCE_NOT_FOUND" }); + return { source }; + }); + + app.post("/api/v1/apps", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const input = appInput.parse(request.body); + const { source } = await requireOwnedSource(input.sourceId, identity, runtime, appConfig); + const apps = await runtime.store.listApps(source.id); + if (apps.length >= appConfig.MAX_APPS_PER_SOURCE) return reply.code(409).send({ error: "APP_QUOTA_REACHED" }); + if (!input.name) return reply.code(400).send({ error: "APP_NAME_REQUIRED_FOR_MANUAL_APP" }); + const appRecord = await runtime.store.upsertApp(source.id, { bundleIdentifier: `manual.${source.slug}.${Date.now()}`, marketplaceID: "", metadata: input }); + return reply.code(201).send({ app: appRecord }); + }); + + app.patch("/api/v1/apps/:id", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const input = appInput.omit({ sourceId: true }).partial().parse(request.body); + const appId = (request.params as { id: string }).id; + const appRecord = await runtime.store.getApp(appId); + if (!appRecord) return reply.code(404).send({ error: "APP_NOT_FOUND" }); + await requireOwnedSource(appRecord.sourceId, identity, runtime, appConfig); + const updated = await runtime.store.updateApp(appId, input); + return { app: updated }; + }); + + app.post("/api/v1/uploads", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const input = uploadInput.parse(request.body); + if (input.sizeBytes > appConfig.MAX_UPLOAD_BYTES) return reply.code(413).send({ error: "UPLOAD_SIZE_LIMIT", limitBytes: appConfig.MAX_UPLOAD_BYTES }); + const { workspace, source } = await requireOwnedSource(input.sourceId, identity, runtime, appConfig); + const usage = await runtime.store.getUsage(workspace.id); + if (usage.storageBytes + input.sizeBytes > appConfig.MAX_STORAGE_BYTES) return reply.code(413).send({ error: "STORAGE_QUOTA_REACHED" }); + if (input.appId) { + const appRecord = await runtime.store.getApp(input.appId); + if (!appRecord || appRecord.sourceId !== source.id) return reply.code(400).send({ error: "APP_NOT_IN_SOURCE" }); + } + const uploadId = randomUUID(); + const safeFilename = input.filename.replace(/[^a-zA-Z0-9._-]/g, "-"); + const objectKey = `uploads/${workspace.id}/${uploadId}/${safeFilename}`; + const uploadPlan = await runtime.storage.createUploadPlan(objectKey, "application/zip", input.sizeBytes); + const upload = await runtime.store.createUpload({ id: uploadId, workspaceId: workspace.id, sourceId: source.id, appId: input.appId, objectKey, multipartUploadId: uploadPlan.mode === "multipart" ? uploadPlan.uploadId : undefined, originalFilename: input.filename, expectedSize: input.sizeBytes }); + if (uploadPlan.mode === "single" && uploadPlan.uploadUrl.startsWith("/")) uploadPlan.uploadUrl = `${appConfig.PUBLIC_BASE_URL}${uploadPlan.uploadUrl}`; + return reply.code(201).send({ upload, uploadPlan, mode: appConfig.STORAGE_MODE }); + }); + + app.put("/api/v1/uploads/content/:encodedKey", async (request, reply) => { + if (appConfig.STORAGE_MODE !== "local") return reply.code(404).send({ error: "DIRECT_UPLOAD_USES_STORAGE_URL" }); + const key = decodeURIComponent((request.params as { encodedKey: string }).encodedKey); + if (!key.startsWith("uploads/") || key.includes("..")) return reply.code(400).send({ error: "UPLOAD_KEY_INVALID" }); + const uploadId = key.split("/")[2]; + const upload = await runtime.store.getUpload(uploadId); + if (!upload || upload.objectKey !== key) return reply.code(404).send({ error: "UPLOAD_NOT_FOUND" }); + const body = Buffer.isBuffer(request.body) ? Readable.from(request.body) : request.body as NodeJS.ReadableStream; + const receivedSize = await runtime.storage.writeUploadFromStream(key, body); + if (receivedSize !== upload.expectedSize) return reply.code(400).send({ error: "UPLOAD_SIZE_MISMATCH", expectedSize: upload.expectedSize, receivedSize }); + await runtime.store.updateUpload(upload.id, { receivedSize, status: "uploaded" }); + return { ok: true, receivedSize }; + }); + + app.post("/api/v1/uploads/:id/complete", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const uploadId = (request.params as { id: string }).id; + const workspace = await runtime.store.getWorkspace(identity); + const upload = await runtime.store.getUpload(uploadId, workspace.id); + if (!upload) return reply.code(404).send({ error: "UPLOAD_NOT_FOUND" }); + const completeInput = multipartPartsInput.parse(request.body); + if (upload.multipartUploadId) await runtime.storage.completeMultipartUpload(upload.objectKey, upload.multipartUploadId, completeInput.parts); + const head = await runtime.storage.headObject(upload.objectKey); + if (!head || head.sizeBytes !== upload.expectedSize) return reply.code(400).send({ error: "UPLOAD_INCOMPLETE", expectedSize: upload.expectedSize, receivedSize: head?.sizeBytes || 0 }); + await runtime.store.updateUpload(upload.id, { receivedSize: head.sizeBytes, status: "queued" }); + if (appConfig.PROCESS_INLINE) { + try { + await processUpload(upload.id, runtime.store, runtime.storage, appConfig); + } catch { + // The failed upload and user-facing error are stored by the processor. + } + } + return reply.code(202).send({ upload: await runtime.store.getUpload(upload.id), release: (await runtime.store.listReleasesForSource(upload.sourceId)).find((release) => release.uploadId === upload.id) || null }); + }); + + app.get("/api/v1/uploads/:id", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const workspace = await runtime.store.getWorkspace(identity); + const upload = await runtime.store.getUpload((request.params as { id: string }).id, workspace.id); + if (!upload) return reply.code(404).send({ error: "UPLOAD_NOT_FOUND" }); + const release = (await runtime.store.listReleasesForSource(upload.sourceId)).find((item) => item.uploadId === upload.id) || null; + return { upload, release }; + }); + + app.get("/api/v1/releases/:id", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const release = await runtime.store.getRelease((request.params as { id: string }).id); + if (!release) return reply.code(404).send({ error: "RELEASE_NOT_FOUND" }); + const appRecord = await runtime.store.getApp(release.appId); + if (!appRecord) return reply.code(404).send({ error: "APP_NOT_FOUND" }); + await requireOwnedSource(appRecord.sourceId, identity, runtime, appConfig); + return { release, assets: await runtime.store.listReleaseAssets(release.id) }; + }); + + app.post("/api/v1/releases/:id/publish", async (request, reply) => { + const identity = await requireIdentity(request, reply, appConfig); + if (!identity) return; + const release = await runtime.store.getRelease((request.params as { id: string }).id); + if (!release) return reply.code(404).send({ error: "RELEASE_NOT_FOUND" }); + const appRecord = await runtime.store.getApp(release.appId); + if (!appRecord) return reply.code(404).send({ error: "APP_NOT_FOUND" }); + await requireOwnedSource(appRecord.sourceId, identity, runtime, appConfig); + if (release.status !== "ready" && release.status !== "published") return reply.code(409).send({ error: "RELEASE_NOT_READY", status: release.status, detail: release.errorMessage }); + const updated = await runtime.store.updateRelease(release.id, { status: "published", publishedAt: new Date().toISOString() }); + return { release: updated }; + }); + + app.get("/sources/:slug/source.json", async (request, reply) => { + const source = await runtime.store.getSourceBySlug((request.params as { slug: string }).slug); + if (!source || source.visibility === "draft") return reply.code(404).send({ error: "SOURCE_NOT_FOUND" }); + const apps = await runtime.store.listApps(source.id); + const releases = await runtime.store.listReleasesForSource(source.id); + const document = buildSourceDocument(source, apps, releases, appConfig.PUBLIC_BASE_URL); + return reply.header("cache-control", "public, max-age=60, must-revalidate").header("access-control-allow-origin", "*").type("application/json").send(document); + }); + + app.get("/sources/:slug", async (request, reply) => { + const source = await runtime.store.getSourceBySlug((request.params as { slug: string }).slug); + if (!source || source.visibility === "draft") return reply.code(404).send({ error: "SOURCE_NOT_FOUND" }); + return { source, apps: await runtime.store.listApps(source.id), releases: (await runtime.store.listReleasesForSource(source.id)).filter((release) => release.status === "published") }; + }); + + app.route({ method: ["GET", "HEAD"], url: "/artifacts/:releaseId/*", handler: async (request, reply) => { + const params = request.params as { releaseId: string; "*": string }; + const release = await runtime.store.getRelease(params.releaseId); + if (!release || release.status !== "published") return reply.code(404).send({ error: "ARTIFACT_NOT_FOUND" }); + const appRecord = await runtime.store.getApp(release.appId); + if (!appRecord) return reply.code(404).send({ error: "ARTIFACT_NOT_FOUND" }); + const source = await runtime.store.getSource(appRecord.sourceId); + if (!source || source.visibility === "draft") return reply.code(404).send({ error: "ARTIFACT_NOT_FOUND" }); + const assetPath = safePath(params["*"]); + if (!assetPath) return reply.code(400).send({ error: "ASSET_PATH_INVALID" }); + const asset = await runtime.store.getReleaseAsset(release.id, assetPath); + if (!asset) return reply.code(404).send({ error: "ASSET_NOT_FOUND" }); + reply.header("content-type", asset.contentType).header("content-length", String(asset.sizeBytes)).header("cache-control", "public, max-age=31536000, immutable").header("etag", `\"${asset.sha256}\"`).header("accept-ranges", "bytes").header("access-control-allow-origin", "*"); + if (request.method === "HEAD") return reply.code(200).send(); + const object = await runtime.storage.getObject(asset.objectKey); + if (!object) return reply.code(404).send({ error: "ASSET_NOT_FOUND" }); + return reply.send(object.body); + }}); + + app.setErrorHandler((error, request, reply) => { + const message = errorMessage(error); + request.log.error({ err: error }, "request failed"); + const status = error instanceof z.ZodError ? 400 : (error as { statusCode?: number }).statusCode || (message.includes("_NOT_FOUND") ? 404 : 500); + return reply.code(status).send({ error: status === 500 ? "INTERNAL_ERROR" : message, detail: status === 500 ? undefined : message }); + }); + return { app, runtime, appConfig }; +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const { app, runtime, appConfig } = await createServer(); + await app.listen({ host: appConfig.HOST, port: appConfig.PORT }); + const shutdown = async () => { + await app.close(); + await runtime.pool?.end(); + }; + process.once("SIGINT", shutdown); + process.once("SIGTERM", shutdown); +} diff --git a/apps/api/src/storage.ts b/apps/api/src/storage.ts new file mode 100644 index 0000000..4726009 --- /dev/null +++ b/apps/api/src/storage.ts @@ -0,0 +1,191 @@ +import { createReadStream, createWriteStream } from "node:fs"; +import { mkdir, stat, writeFile } from "node:fs/promises"; +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { dirname, normalize, relative, resolve } from "node:path"; +import { pipeline } from "node:stream/promises"; +import { Readable } from "node:stream"; +import { + CompleteMultipartUploadCommand, + CreateMultipartUploadCommand, + GetObjectCommand, + HeadObjectCommand, + PutObjectCommand, + S3Client, + UploadPartCommand, +} from "@aws-sdk/client-s3"; +import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; +import type { AppConfig } from "./config"; + +export interface StoredObject { + body: Readable; + sizeBytes: number; + contentType: string; +} + +export type UploadPlan = + | { mode: "single"; uploadUrl: string } + | { mode: "multipart"; uploadId: string; partSizeBytes: number; parts: Array<{ partNumber: number; uploadUrl: string }> }; + +export interface StorageAdapter { + createUploadPlan(key: string, contentType: string, sizeBytes: number): Promise; + completeMultipartUpload(key: string, uploadId: string | undefined, parts: Array<{ partNumber: number; etag: string }> | undefined): Promise; + writeUploadFromStream(key: string, stream: NodeJS.ReadableStream): Promise; + writeObject(key: string, body: Buffer, contentType: string): Promise; + writeStream(key: string, transform: NodeJS.ReadWriteStream, contentType: string, sizeBytes: number, source: NodeJS.ReadableStream): Promise; + downloadToFile(key: string, filePath: string): Promise; + getObject(key: string): Promise; + headObject(key: string): Promise<{ sizeBytes: number; contentType: string } | null>; +} + +function contentTypeForPath(path: string) { + if (path.endsWith(".json")) return "application/json; charset=utf-8"; + if (path.endsWith(".ipa")) return "application/octet-stream"; + return "application/octet-stream"; +} + +export class LocalStorage implements StorageAdapter { + private readonly root: string; + + constructor(root: string) { + this.root = resolve(root); + } + + private pathFor(key: string) { + const candidate = resolve(this.root, normalize(key)); + const relativePath = relative(this.root, candidate); + if (!relativePath || relativePath.startsWith("..") || relativePath.includes("..")) { + throw new Error("STORAGE_PATH_INVALID"); + } + return candidate; + } + + async createUploadPlan(key: string) { + return { mode: "single" as const, uploadUrl: `/api/v1/uploads/content/${encodeURIComponent(key)}` }; + } + + async completeMultipartUpload() { + return; + } + + async writeUploadFromStream(key: string, stream: NodeJS.ReadableStream) { + const filePath = this.pathFor(key); + await mkdir(dirname(filePath), { recursive: true }); + await pipeline(stream, createWriteStream(filePath, { flags: "w" })); + return Number((await stat(filePath)).size); + } + + async writeObject(key: string, body: Buffer) { + const filePath = this.pathFor(key); + await mkdir(dirname(filePath), { recursive: true }); + await writeFile(filePath, body); + } + + async writeStream(key: string, transform: NodeJS.ReadWriteStream, _contentType: string, _sizeBytes: number, source: NodeJS.ReadableStream) { + const filePath = this.pathFor(key); + await mkdir(dirname(filePath), { recursive: true }); + await pipeline(source, transform, createWriteStream(filePath, { flags: "w" })); + } + + async downloadToFile(key: string, filePath: string) { + await mkdir(dirname(filePath), { recursive: true }); + await pipeline(createReadStream(this.pathFor(key)), createWriteStream(filePath, { flags: "w" })); + } + + async getObject(key: string) { + const filePath = this.pathFor(key); + try { + const fileStat = await stat(filePath); + return { body: createReadStream(filePath), sizeBytes: Number(fileStat.size), contentType: contentTypeForPath(key) }; + } catch { + return null; + } + } + + async headObject(key: string) { + try { + const fileStat = await stat(this.pathFor(key)); + return { sizeBytes: Number(fileStat.size), contentType: contentTypeForPath(key) }; + } catch { + return null; + } + } +} + +export class S3Storage implements StorageAdapter { + private readonly client: S3Client; + + constructor(private readonly appConfig: AppConfig) { + this.client = new S3Client({ + region: appConfig.S3_REGION, + endpoint: appConfig.S3_ENDPOINT, + forcePathStyle: appConfig.S3_FORCE_PATH_STYLE, + credentials: + appConfig.S3_ACCESS_KEY_ID && appConfig.S3_SECRET_ACCESS_KEY + ? { accessKeyId: appConfig.S3_ACCESS_KEY_ID, secretAccessKey: appConfig.S3_SECRET_ACCESS_KEY } + : undefined, + }); + } + + async createUploadPlan(key: string, contentType: string, sizeBytes: number) { + const partSizeBytes = 16 * 1024 * 1024; + const partCount = Math.ceil(sizeBytes / partSizeBytes); + if (partCount > 10000) throw new Error("UPLOAD_PART_COUNT_LIMIT"); + const multipart = await this.client.send(new CreateMultipartUploadCommand({ Bucket: this.appConfig.S3_BUCKET, Key: key, ContentType: contentType })); + if (!multipart.UploadId) throw new Error("MULTIPART_UPLOAD_ID_MISSING"); + const parts = await Promise.all(Array.from({ length: partCount }, async (_, index) => ({ partNumber: index + 1, uploadUrl: await getSignedUrl(this.client, new UploadPartCommand({ Bucket: this.appConfig.S3_BUCKET, Key: key, UploadId: multipart.UploadId, PartNumber: index + 1 }), { expiresIn: 900 }) }))); + return { mode: "multipart" as const, uploadId: multipart.UploadId, partSizeBytes, parts }; + } + + async completeMultipartUpload(key: string, uploadId: string | undefined, parts: Array<{ partNumber: number; etag: string }> | undefined) { + if (!uploadId || !parts?.length) throw new Error("MULTIPART_PARTS_REQUIRED"); + await this.client.send(new CompleteMultipartUploadCommand({ Bucket: this.appConfig.S3_BUCKET, Key: key, UploadId: uploadId, MultipartUpload: { Parts: parts.sort((a, b) => a.partNumber - b.partNumber).map((part) => ({ PartNumber: part.partNumber, ETag: part.etag })) } })); + } + + async writeUploadFromStream(key: string, stream: NodeJS.ReadableStream) { + await this.client.send(new PutObjectCommand({ Bucket: this.appConfig.S3_BUCKET, Key: key, Body: stream as any })); + const metadata = await this.headObject(key); + return metadata?.sizeBytes || 0; + } + + async writeObject(key: string, body: Buffer, contentType: string) { + await this.client.send(new PutObjectCommand({ Bucket: this.appConfig.S3_BUCKET, Key: key, Body: body, ContentType: contentType })); + } + + async writeStream(key: string, transform: NodeJS.ReadWriteStream, contentType: string, sizeBytes: number, source: NodeJS.ReadableStream) { + const upload = this.client.send(new PutObjectCommand({ Bucket: this.appConfig.S3_BUCKET, Key: key, Body: transform as any, ContentType: contentType, ContentLength: sizeBytes || undefined })); + await pipeline(source, transform); + await upload; + } + + async downloadToFile(key: string, filePath: string) { + const response = await this.client.send(new GetObjectCommand({ Bucket: this.appConfig.S3_BUCKET, Key: key })); + if (!response.Body) throw new Error("STORAGE_OBJECT_EMPTY"); + await mkdir(dirname(filePath), { recursive: true }); + const body = response.Body instanceof Readable ? response.Body : Readable.fromWeb(response.Body as any); + await pipeline(body, createWriteStream(filePath, { flags: "w" })); + } + + async getObject(key: string) { + try { + const response = await this.client.send(new GetObjectCommand({ Bucket: this.appConfig.S3_BUCKET, Key: key })); + if (!response.Body) return null; + const body = response.Body instanceof Readable ? response.Body : Readable.fromWeb(response.Body as any); + return { body, sizeBytes: Number(response.ContentLength || 0), contentType: response.ContentType || contentTypeForPath(key) }; + } catch { + return null; + } + } + + async headObject(key: string) { + try { + const response = await this.client.send(new HeadObjectCommand({ Bucket: this.appConfig.S3_BUCKET, Key: key })); + return { sizeBytes: Number(response.ContentLength || 0), contentType: response.ContentType || contentTypeForPath(key) }; + } catch { + return null; + } + } +} + +export function createStorage(appConfig: AppConfig): StorageAdapter { + return appConfig.STORAGE_MODE === "s3" ? new S3Storage(appConfig) : new LocalStorage(appConfig.LOCAL_STORAGE_DIR); +} diff --git a/apps/api/src/store.ts b/apps/api/src/store.ts new file mode 100644 index 0000000..abc1b3d --- /dev/null +++ b/apps/api/src/store.ts @@ -0,0 +1,492 @@ +import { randomUUID } from "node:crypto"; +import { Pool } from "pg"; +/* eslint-disable @typescript-eslint/no-explicit-any */ +import type { + AppMetadata, + AppRecord, + Identity, + ReleaseAsset, + ReleaseRecord, + SourceRecord, + UploadRecord, + WorkspaceRecord, +} from "../../../packages/core/src/index"; +import { schemaSql } from "./schema"; +import type { AppConfig } from "./config"; + +export interface Store { + init(): Promise; + getWorkspace(identity: Identity): Promise; + listSources(workspaceId: string): Promise; + getSource(id: string, workspaceId?: string): Promise; + getSourceBySlug(slug: string): Promise; + createSource( + workspaceId: string, + input: Pick & + Partial>, + ): Promise; + updateSource( + id: string, + workspaceId: string, + patch: Partial>, + ): Promise; + listApps(sourceId: string): Promise; + getApp(id: string): Promise; + upsertApp( + sourceId: string, + input: { + bundleIdentifier: string; + marketplaceID: string; + metadata: Partial; + }, + ): Promise; + updateApp( + id: string, + patch: Partial, + ): Promise; + createUpload(input: Omit): Promise; + getUpload(id: string, workspaceId?: string): Promise; + updateUpload(id: string, patch: Partial): Promise; + createRelease(input: Omit): Promise; + getRelease(id: string): Promise; + updateRelease(id: string, patch: Partial): Promise; + listReleasesForSource(sourceId: string): Promise; + addReleaseAssets(assets: ReleaseAsset[]): Promise; + listReleaseAssets(releaseId: string): Promise; + getReleaseAsset(releaseId: string, path: string): Promise; + getUsage(workspaceId: string): Promise<{ storageBytes: number; sourceCount: number }>; + listQueuedUploads(limit: number): Promise; +} + +function now() { + return new Date().toISOString(); +} + +function slugify(value: string) { + const result = value + .toLowerCase() + .trim() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, "") + .slice(0, 48); + return result || `source-${randomUUID().slice(0, 8)}`; +} + +function defaultMetadata(metadata: Partial): AppMetadata { + return { + name: metadata.name || "Untitled App", + developerName: metadata.developerName || "AltDock Developer", + subtitle: metadata.subtitle || "", + localizedDescription: metadata.localizedDescription || "", + iconURL: metadata.iconURL, + tintColor: metadata.tintColor || "#E9694B", + category: metadata.category || "other", + screenshots: metadata.screenshots || [], + appPermissions: metadata.appPermissions || { entitlements: [], privacy: {} }, + }; +} + +export class MemoryStore implements Store { + private readonly workspaces = new Map(); + private readonly workspaceBySubject = new Map(); + private readonly sources = new Map(); + private readonly apps = new Map(); + private readonly uploads = new Map(); + private readonly releases = new Map(); + private readonly assets = new Map(); + + async init() {} + + async getWorkspace(identity: Identity) { + const existingId = this.workspaceBySubject.get(identity.subject); + if (existingId) return this.workspaces.get(existingId)!; + const id = randomUUID(); + const workspace: WorkspaceRecord = { + id, + name: `${identity.displayName || "Developer"}'s Workspace`, + slug: slugify(identity.displayName || identity.email), + ownerSubject: identity.subject, + ownerEmail: identity.email, + createdAt: now(), + }; + this.workspaces.set(id, workspace); + this.workspaceBySubject.set(identity.subject, id); + return workspace; + } + + async listSources(workspaceId: string) { + return [...this.sources.values()] + .filter((source) => source.workspaceId === workspaceId) + .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + } + + async getSource(id: string, workspaceId?: string) { + const source = this.sources.get(id); + return source && (!workspaceId || source.workspaceId === workspaceId) ? source : null; + } + + async getSourceBySlug(slug: string) { + return [...this.sources.values()].find((source) => source.slug === slug) || null; + } + + async createSource(workspaceId: string, input: Pick & Partial>) { + const createdAt = now(); + const source: SourceRecord = { + id: randomUUID(), + workspaceId, + slug: `${slugify(input.name)}-${randomUUID().slice(0, 6)}`, + name: input.name, + subtitle: input.subtitle || "", + description: input.description || "", + iconURL: input.iconURL, + headerURL: input.headerURL, + website: input.website, + tintColor: input.tintColor || "#E9694B", + visibility: input.visibility, + createdAt, + updatedAt: createdAt, + }; + this.sources.set(source.id, source); + return source; + } + + async updateSource(id: string, workspaceId: string, patch: Partial>) { + const source = await this.getSource(id, workspaceId); + if (!source) return null; + Object.assign(source, patch, { updatedAt: now() }); + return source; + } + + async listApps(sourceId: string) { + return [...this.apps.values()].filter((app) => app.sourceId === sourceId); + } + + async getApp(id: string) { + return this.apps.get(id) || null; + } + + async upsertApp(sourceId: string, input: { bundleIdentifier: string; marketplaceID: string; metadata: Partial }) { + const existing = [...this.apps.values()].find((app) => app.sourceId === sourceId && app.bundleIdentifier === input.bundleIdentifier); + const metadata = defaultMetadata(input.metadata); + if (existing) { + Object.assign(existing, metadata, { marketplaceID: input.marketplaceID || existing.marketplaceID, updatedAt: now() }); + return existing; + } + const app: AppRecord = { + id: randomUUID(), + sourceId, + bundleIdentifier: input.bundleIdentifier, + marketplaceID: input.marketplaceID, + ...metadata, + createdAt: now(), + updatedAt: now(), + }; + this.apps.set(app.id, app); + return app; + } + + async updateApp(id: string, patch: Partial) { + const app = this.apps.get(id); + if (!app) return null; + Object.assign(app, patch, { updatedAt: now() }); + return app; + } + + async createUpload(input: Omit) { + const upload: UploadRecord = { ...input, status: "created", receivedSize: 0, createdAt: now() }; + this.uploads.set(upload.id, upload); + return upload; + } + + async getUpload(id: string, workspaceId?: string) { + const upload = this.uploads.get(id); + return upload && (!workspaceId || upload.workspaceId === workspaceId) ? upload : null; + } + + async updateUpload(id: string, patch: Partial) { + const upload = this.uploads.get(id); + if (!upload) return null; + Object.assign(upload, patch); + return upload; + } + + async createRelease(input: Omit) { + const release: ReleaseRecord = { ...input, status: "processing", createdAt: now() }; + this.releases.set(release.id, release); + return release; + } + + async getRelease(id: string) { + return this.releases.get(id) || null; + } + + async updateRelease(id: string, patch: Partial) { + const release = this.releases.get(id); + if (!release) return null; + Object.assign(release, patch); + return release; + } + + async listReleasesForSource(sourceId: string) { + const appIds = new Set((await this.listApps(sourceId)).map((app) => app.id)); + return [...this.releases.values()].filter((release) => appIds.has(release.appId)); + } + + async addReleaseAssets(assets: ReleaseAsset[]) { + for (const asset of assets) this.assets.set(`${asset.releaseId}:${asset.path}`, asset); + } + + async listReleaseAssets(releaseId: string) { + return [...this.assets.values()].filter((asset) => asset.releaseId === releaseId); + } + + async getReleaseAsset(releaseId: string, path: string) { + return this.assets.get(`${releaseId}:${path}`) || null; + } + + async getUsage(workspaceId: string) { + const sourceCount = (await this.listSources(workspaceId)).length; + const sourceIds = new Set((await this.listSources(workspaceId)).map((source) => source.id)); + const appIds = new Set([...this.apps.values()].filter((app) => sourceIds.has(app.sourceId)).map((app) => app.id)); + const releaseIds = new Set([...this.releases.values()].filter((release) => appIds.has(release.appId)).map((release) => release.id)); + const storageBytes = [...this.assets.values()].filter((asset) => releaseIds.has(asset.releaseId)).reduce((sum, asset) => sum + asset.sizeBytes, 0); + return { storageBytes, sourceCount }; + } + + async listQueuedUploads(limit: number) { + return [...this.uploads.values()].filter((upload) => upload.status === "queued").slice(0, limit); + } +} + +type Queryable = Pick; + +function mapSource(row: any): SourceRecord { + return { + id: row.id, + workspaceId: row.workspace_id, + slug: row.slug, + name: row.name, + subtitle: row.subtitle, + description: row.description, + iconURL: row.icon_url || undefined, + headerURL: row.header_url || undefined, + website: row.website || undefined, + tintColor: row.tint_color, + visibility: row.visibility, + createdAt: new Date(row.created_at).toISOString(), + updatedAt: new Date(row.updated_at).toISOString(), + }; +} + +function mapApp(row: any): AppRecord { + return { + id: row.id, + sourceId: row.source_id, + name: row.name, + bundleIdentifier: row.bundle_identifier, + marketplaceID: row.marketplace_id, + developerName: row.developer_name, + subtitle: row.subtitle, + localizedDescription: row.localized_description, + iconURL: row.icon_url || undefined, + tintColor: row.tint_color, + category: row.category, + screenshots: row.screenshots || [], + appPermissions: row.app_permissions || { entitlements: [], privacy: {} }, + createdAt: new Date(row.created_at).toISOString(), + updatedAt: new Date(row.updated_at).toISOString(), + }; +} + +function mapUpload(row: any): UploadRecord { + return { + id: row.id, + workspaceId: row.workspace_id, + sourceId: row.source_id, + appId: row.app_id || undefined, + objectKey: row.object_key, + multipartUploadId: row.multipart_upload_id || undefined, + originalFilename: row.original_filename, + expectedSize: Number(row.expected_size), + receivedSize: Number(row.received_size), + status: row.status, + errorCode: row.error_code || undefined, + errorMessage: row.error_message || undefined, + createdAt: new Date(row.created_at).toISOString(), + }; +} + +function mapRelease(row: any): ReleaseRecord { + return { + id: row.id, + appId: row.app_id, + uploadId: row.upload_id, + version: row.version, + buildVersion: row.build_version, + appleItemId: row.apple_item_id, + date: new Date(row.date).toISOString(), + localizedDescription: row.localized_description, + minOSVersion: row.min_os_version || undefined, + sizeBytes: Number(row.size_bytes), + status: row.status, + errorCode: row.error_code || undefined, + errorMessage: row.error_message || undefined, + manifest: row.manifest, + createdAt: new Date(row.created_at).toISOString(), + publishedAt: row.published_at ? new Date(row.published_at).toISOString() : undefined, + }; +} + +export class PostgresStore implements Store { + constructor(private readonly pool: Queryable) {} + + async init() { + await this.pool.query(schemaSql); + } + + async getWorkspace(identity: Identity) { + const user = await this.pool.query( + `INSERT INTO users (id, subject, email, display_name) + VALUES ($1, $2, $3, $4) + ON CONFLICT (subject) DO UPDATE SET email = EXCLUDED.email, display_name = EXCLUDED.display_name + RETURNING *`, + [randomUUID(), identity.subject, identity.email, identity.displayName], + ); + const userRow = user.rows[0]; + const workspace = await this.pool.query( + `INSERT INTO workspaces (id, owner_user_id, name, slug) + VALUES ($1, $2, $3, $4) + ON CONFLICT (slug) DO UPDATE SET name = EXCLUDED.name + RETURNING *`, + [randomUUID(), userRow.id, `${identity.displayName || "Developer"}'s Workspace`, `${slugify(identity.displayName || identity.email)}-${userRow.id.slice(0, 6)}`], + ); + const row = workspace.rows[0]; + return { id: row.id, name: row.name, slug: row.slug, ownerSubject: identity.subject, ownerEmail: identity.email, createdAt: new Date(row.created_at).toISOString() }; + } + + async listSources(workspaceId: string) { + const result = await this.pool.query(`SELECT * FROM sources WHERE workspace_id = $1 ORDER BY updated_at DESC`, [workspaceId]); + return result.rows.map(mapSource); + } + + async getSource(id: string, workspaceId?: string) { + const result = await this.pool.query(`SELECT * FROM sources WHERE id = $1 ${workspaceId ? "AND workspace_id = $2" : ""}`, workspaceId ? [id, workspaceId] : [id]); + return result.rows[0] ? mapSource(result.rows[0]) : null; + } + + async getSourceBySlug(slug: string) { + const result = await this.pool.query(`SELECT * FROM sources WHERE slug = $1`, [slug]); + return result.rows[0] ? mapSource(result.rows[0]) : null; + } + + async createSource(workspaceId: string, input: Pick & Partial>) { + const result = await this.pool.query(`INSERT INTO sources (id, workspace_id, slug, name, subtitle, description, icon_url, header_url, website, tint_color, visibility) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING *`, [randomUUID(), workspaceId, `${slugify(input.name)}-${randomUUID().slice(0, 6)}`, input.name, input.subtitle || "", input.description || "", input.iconURL || null, input.headerURL || null, input.website || null, input.tintColor || "#E9694B", input.visibility]); + return mapSource(result.rows[0]); + } + + async updateSource(id: string, workspaceId: string, patch: Partial>) { + const source = await this.getSource(id, workspaceId); + if (!source) return null; + const next = { ...source, ...patch }; + const result = await this.pool.query(`UPDATE sources SET name=$1, subtitle=$2, description=$3, icon_url=$4, header_url=$5, website=$6, tint_color=$7, visibility=$8, updated_at=NOW() WHERE id=$9 AND workspace_id=$10 RETURNING *`, [next.name, next.subtitle, next.description, next.iconURL || null, next.headerURL || null, next.website || null, next.tintColor, next.visibility, id, workspaceId]); + return result.rows[0] ? mapSource(result.rows[0]) : null; + } + + async listApps(sourceId: string) { + const result = await this.pool.query(`SELECT * FROM apps WHERE source_id = $1 ORDER BY created_at ASC`, [sourceId]); + return result.rows.map(mapApp); + } + + async getApp(id: string) { + const result = await this.pool.query(`SELECT * FROM apps WHERE id = $1`, [id]); + return result.rows[0] ? mapApp(result.rows[0]) : null; + } + + async upsertApp(sourceId: string, input: { bundleIdentifier: string; marketplaceID: string; metadata: Partial }) { + const metadata = defaultMetadata(input.metadata); + const result = await this.pool.query(`INSERT INTO apps (id, source_id, name, bundle_identifier, marketplace_id, developer_name, subtitle, localized_description, icon_url, tint_color, category, screenshots, app_permissions) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT (source_id, bundle_identifier) DO UPDATE SET marketplace_id=EXCLUDED.marketplace_id, name=EXCLUDED.name, developer_name=EXCLUDED.developer_name, subtitle=EXCLUDED.subtitle, localized_description=EXCLUDED.localized_description, icon_url=EXCLUDED.icon_url, tint_color=EXCLUDED.tint_color, category=EXCLUDED.category, screenshots=EXCLUDED.screenshots, app_permissions=EXCLUDED.app_permissions, updated_at=NOW() RETURNING *`, [randomUUID(), sourceId, metadata.name, input.bundleIdentifier, input.marketplaceID, metadata.developerName, metadata.subtitle, metadata.localizedDescription, metadata.iconURL || null, metadata.tintColor, metadata.category, JSON.stringify(metadata.screenshots), JSON.stringify(metadata.appPermissions)]); + return mapApp(result.rows[0]); + } + + async updateApp(id: string, patch: Partial) { + const app = await this.getApp(id); + if (!app) return null; + const next = { ...app, ...patch }; + const result = await this.pool.query(`UPDATE apps SET name=$1, developer_name=$2, subtitle=$3, localized_description=$4, icon_url=$5, tint_color=$6, category=$7, screenshots=$8, app_permissions=$9, updated_at=NOW() WHERE id=$10 RETURNING *`, [next.name, next.developerName, next.subtitle, next.localizedDescription, next.iconURL || null, next.tintColor, next.category, JSON.stringify(next.screenshots), JSON.stringify(next.appPermissions), id]); + return result.rows[0] ? mapApp(result.rows[0]) : null; + } + + async createUpload(input: Omit) { + const result = await this.pool.query(`INSERT INTO uploads (id, workspace_id, source_id, app_id, object_key, multipart_upload_id, original_filename, expected_size) VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *`, [input.id, input.workspaceId, input.sourceId, input.appId || null, input.objectKey, input.multipartUploadId || null, input.originalFilename, input.expectedSize]); + return mapUpload(result.rows[0]); + } + + async getUpload(id: string, workspaceId?: string) { + const result = await this.pool.query(`SELECT * FROM uploads WHERE id=$1 ${workspaceId ? "AND workspace_id=$2" : ""}`, workspaceId ? [id, workspaceId] : [id]); + return result.rows[0] ? mapUpload(result.rows[0]) : null; + } + + async updateUpload(id: string, patch: Partial) { + const current = await this.getUpload(id); + if (!current) return null; + const next = { ...current, ...patch }; + const result = await this.pool.query(`UPDATE uploads SET app_id=$1, multipart_upload_id=$2, received_size=$3, status=$4, error_code=$5, error_message=$6 WHERE id=$7 RETURNING *`, [next.appId || null, next.multipartUploadId || null, next.receivedSize, next.status, next.errorCode || null, next.errorMessage || null, id]); + return result.rows[0] ? mapUpload(result.rows[0]) : null; + } + + async createRelease(input: Omit) { + const result = await this.pool.query(`INSERT INTO releases (id, app_id, upload_id, version, build_version, apple_item_id, date, localized_description, min_os_version, size_bytes, status, manifest) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'processing',$11) RETURNING *`, [input.id, input.appId, input.uploadId, input.version, input.buildVersion, input.appleItemId, input.date, input.localizedDescription, input.minOSVersion || null, input.sizeBytes, JSON.stringify(input.manifest)]); + return mapRelease(result.rows[0]); + } + + async getRelease(id: string) { + const result = await this.pool.query(`SELECT * FROM releases WHERE id=$1`, [id]); + return result.rows[0] ? mapRelease(result.rows[0]) : null; + } + + async updateRelease(id: string, patch: Partial) { + const current = await this.getRelease(id); + if (!current) return null; + const next = { ...current, ...patch }; + const result = await this.pool.query(`UPDATE releases SET status=$1, error_code=$2, error_message=$3, size_bytes=$4, localized_description=$5, published_at=$6 WHERE id=$7 RETURNING *`, [next.status, next.errorCode || null, next.errorMessage || null, next.sizeBytes, next.localizedDescription, next.publishedAt || null, id]); + return result.rows[0] ? mapRelease(result.rows[0]) : null; + } + + async listReleasesForSource(sourceId: string) { + const result = await this.pool.query(`SELECT releases.* FROM releases JOIN apps ON apps.id = releases.app_id WHERE apps.source_id=$1 ORDER BY releases.date DESC, releases.build_version DESC`, [sourceId]); + return result.rows.map(mapRelease); + } + + async addReleaseAssets(assets: ReleaseAsset[]) { + for (const asset of assets) { + await this.pool.query(`INSERT INTO release_assets (id, release_id, path, object_key, size_bytes, sha256, content_type) VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT (release_id, path) DO UPDATE SET object_key=EXCLUDED.object_key, size_bytes=EXCLUDED.size_bytes, sha256=EXCLUDED.sha256, content_type=EXCLUDED.content_type`, [randomUUID(), asset.releaseId, asset.path, asset.objectKey, asset.sizeBytes, asset.sha256, asset.contentType]); + } + } + + async listReleaseAssets(releaseId: string) { + const result = await this.pool.query(`SELECT release_id, path, object_key, size_bytes, sha256, content_type FROM release_assets WHERE release_id=$1 ORDER BY path`, [releaseId]); + return result.rows.map((row) => ({ releaseId: row.release_id, path: row.path, objectKey: row.object_key, sizeBytes: Number(row.size_bytes), sha256: row.sha256, contentType: row.content_type })); + } + + async getReleaseAsset(releaseId: string, path: string) { + const result = await this.pool.query(`SELECT release_id, path, object_key, size_bytes, sha256, content_type FROM release_assets WHERE release_id=$1 AND path=$2`, [releaseId, path]); + const row = result.rows[0]; + return row ? { releaseId: row.release_id, path: row.path, objectKey: row.object_key, sizeBytes: Number(row.size_bytes), sha256: row.sha256, contentType: row.content_type } : null; + } + + async getUsage(workspaceId: string) { + const result = await this.pool.query(`SELECT COUNT(DISTINCT s.id)::int AS source_count, COALESCE(SUM(u.received_size),0)::bigint AS storage_bytes FROM sources s LEFT JOIN uploads u ON u.workspace_id=s.workspace_id WHERE s.workspace_id=$1`, [workspaceId]); + return { storageBytes: Number(result.rows[0]?.storage_bytes || 0), sourceCount: Number(result.rows[0]?.source_count || 0) }; + } + + async listQueuedUploads(limit: number) { + const result = await this.pool.query(`SELECT * FROM uploads WHERE status='queued' ORDER BY created_at LIMIT $1`, [limit]); + return result.rows.map(mapUpload); + } +} + +export async function createStore(appConfig: AppConfig): Promise<{ store: Store; pool?: Pool }> { + if (!appConfig.DATABASE_URL) return { store: new MemoryStore() }; + const pool = new Pool({ connectionString: appConfig.DATABASE_URL }); + return { store: new PostgresStore(pool), pool }; +} diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 0000000..2447b21 --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/apps/worker/src/worker.ts b/apps/worker/src/worker.ts new file mode 100644 index 0000000..794a6fe --- /dev/null +++ b/apps/worker/src/worker.ts @@ -0,0 +1,30 @@ +import { loadConfig } from "../../api/src/config"; +import { processUpload } from "../../api/src/processor"; +import { createRuntime } from "../../api/src/runtime"; + +const appConfig = loadConfig(); +const runtime = await createRuntime(appConfig); + +async function tick() { + const uploads = await runtime.store.listQueuedUploads(2); + for (const upload of uploads) { + try { + await processUpload(upload.id, runtime.store, runtime.storage, appConfig); + console.log(`[worker] processed ${upload.id}`); + } catch (error) { + console.error(`[worker] failed ${upload.id}`, error); + } + } +} + +console.log(`AltDock worker listening for queued uploads (${appConfig.STORAGE_MODE} storage).`); +await tick(); +const interval = setInterval(() => void tick(), 2500); + +const shutdown = async () => { + clearInterval(interval); + await runtime.pool?.end(); + process.exit(0); +}; +process.once("SIGINT", shutdown); +process.once("SIGTERM", shutdown); diff --git a/apps/worker/tsconfig.json b/apps/worker/tsconfig.json new file mode 100644 index 0000000..2447b21 --- /dev/null +++ b/apps/worker/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/build/sites-vite-plugin.ts b/build/sites-vite-plugin.ts new file mode 100644 index 0000000..26563fd --- /dev/null +++ b/build/sites-vite-plugin.ts @@ -0,0 +1,45 @@ +import { access, cp, mkdir, rm } from "node:fs/promises"; +import { resolve } from "node:path"; +import type { Plugin } from "vite"; + +async function exists(path: string): Promise { + try { + await access(path); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return false; + } + throw error; + } +} + +// Packages Sites metadata and migrations after Vite finishes compiling. +export function sites(): Plugin { + let root = process.cwd(); + + return { + name: "sites", + apply: "build", + configResolved(config) { + root = config.root; + }, + async closeBundle() { + const outputDirectory = resolve(root, "dist", ".openai"); + const hostingConfig = resolve(root, ".openai", "hosting.json"); + const drizzleSource = resolve(root, "drizzle"); + + await rm(outputDirectory, { recursive: true, force: true }); + await mkdir(outputDirectory, { recursive: true }); + + if (await exists(hostingConfig)) { + await cp(hostingConfig, resolve(outputDirectory, "hosting.json")); + } + if (await exists(drizzleSource)) { + await cp(drizzleSource, resolve(outputDirectory, "drizzle"), { + recursive: true, + }); + } + }, + }; +} diff --git a/components/altdock/admin-shell.tsx b/components/altdock/admin-shell.tsx new file mode 100644 index 0000000..618305b --- /dev/null +++ b/components/altdock/admin-shell.tsx @@ -0,0 +1,99 @@ +"use client"; + +import * as Toast from "@radix-ui/react-toast"; +import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"; +import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"; +import { Button } from "@/components/ui/button"; +import { usePathname, useRouter } from "next/navigation"; +import Link from "next/link"; +import { useEffect, useMemo, useState, type ComponentType, type PropsWithChildren } from "react"; +import { AppWindow, BookOpen, Boxes, ChevronDown, ExternalLink, FileArchive, Gauge, Menu, PanelLeftClose, PanelLeftOpen, Plus, Search, Settings2, UploadCloud, X } from "lucide-react"; +import { API_BASE, AUTH_MODE, formatBytes } from "@/app/lib/dashboard"; +import { useDashboard } from "./dashboard-provider"; + +type NavItem = { href: string; label: string; icon: ComponentType<{ size?: number; strokeWidth?: number }> }; + +const primaryNav: NavItem[] = [ + { href: "/dashboard", label: "概要", icon: Gauge }, + { href: "/dashboard/sources", label: "Sources", icon: Boxes }, + { href: "/dashboard/apps", label: "アプリ", icon: AppWindow }, + { href: "/dashboard/releases", label: "リリース", icon: FileArchive }, +]; + +const secondaryNav: NavItem[] = [ + { href: "https://faq.altstore.io/developers/distribute-with-altstore-pal", label: "PALドキュメント", icon: BookOpen }, + { href: "/dashboard/settings", label: "設定", icon: Settings2 }, +]; + +function isActive(pathname: string, href: string) { + if (href === "/dashboard") return pathname === "/dashboard"; + return pathname.startsWith(href); +} + +function SideNavigation({ collapsed, onNavigate }: { collapsed?: boolean; onNavigate?: () => void }) { + const pathname = usePathname(); + const router = useRouter(); + const { dashboard } = useDashboard(); + + const renderItem = (item: NavItem) => { + const external = item.href.startsWith("http"); + const Icon = item.icon; + const className = `admin-nav-item${isActive(pathname, item.href) ? " active" : ""}`; + const content = <>{item.label}{external && }; + if (external) return {content}; + return {content}; + }; + + const storagePercent = dashboard ? Math.min(100, (dashboard.usage.storageBytes / Math.max(1, dashboard.limits.maxStorageBytes)) * 100) : 0; + + return
+ + {!collapsed &&
{dashboard?.workspace.name.slice(0, 1).toUpperCase() || "D"}WORKSPACE{dashboard?.workspace.name || "Developer Workspace"}
} +
管理
+ +
その他
+ +
+ {!collapsed &&
保存容量{formatBytes(dashboard?.usage.storageBytes || 0)} / {formatBytes(dashboard?.limits.maxStorageBytes || 0)}
Free workspace plan
} + {!collapsed &&
DDemo Developerdemo@altdock.local···
} +
; +} + +function CommandPalette({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) { + const router = useRouter(); + const commands = useMemo(() => primaryNav.map((item) => ({ ...item, action: () => router.push(item.href) })), [router]); + return 画面を検索移動先を検索できます。該当する画面がありません。 { commands[0].action(); onOpenChange(false); }}>概要G O { commands[1].action(); onOpenChange(false); }}>SourcesG S { commands[2].action(); onOpenChange(false); }}>アプリG A { commands[3].action(); onOpenChange(false); }}>リリースG R { router.push("/dashboard/releases?upload=1"); onOpenChange(false); }}>ADPをアップロード; +} + +export function AdminShell({ children }: PropsWithChildren) { + const [collapsed, setCollapsed] = useState(false); + const [mobileOpen, setMobileOpen] = useState(false); + const [commandOpen, setCommandOpen] = useState(false); + const pathname = usePathname(); + const { notice, dismissNotice, dashboard } = useDashboard(); + + useEffect(() => { + const handleShortcut = (event: KeyboardEvent) => { + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") { event.preventDefault(); setCommandOpen(true); } + }; + window.addEventListener("keydown", handleShortcut); + return () => window.removeEventListener("keydown", handleShortcut); + }, []); + + const pageLabel = pathname === "/dashboard" ? "概要" : pathname.includes("/sources") ? "Sources" : pathname.includes("/apps") ? "アプリ" : pathname.includes("/releases") ? "リリース" : "設定"; + + return +
+ + 管理画面ナビゲーション管理画面の移動先を選択します。 setMobileOpen(false)} /> +
+
Workspace/{pageLabel}
新しいリリース{AUTH_MODE === "oidc" ? SSOでログイン : API status}
+
{children}
+
+ +
+ {notice && { if (!open) dismissNotice(); }} className={`admin-toast toast-${notice.tone}`}>{notice.tone === "error" ? "処理に失敗しました" : notice.tone === "info" ? "処理中" : "完了"}{notice.text}×} + + +
; +} diff --git a/components/altdock/dashboard-provider.tsx b/components/altdock/dashboard-provider.tsx new file mode 100644 index 0000000..ed77839 --- /dev/null +++ b/components/altdock/dashboard-provider.tsx @@ -0,0 +1,166 @@ +"use client"; + +import { createContext, useCallback, useContext, useEffect, useMemo, useState, type PropsWithChildren } from "react"; +import type { AppRecord, ReleaseRecord, SourceRecord } from "@/packages/core/src/index"; +import { API_BASE, api, type DashboardData, type Notice, type Visibility } from "@/app/lib/dashboard"; + +type SourceInput = Pick & Partial>; + +type UploadPlan = + | { mode: "single"; uploadUrl: string } + | { mode: "multipart"; uploadId: string; partSizeBytes: number; parts: Array<{ partNumber: number; uploadUrl: string }> }; + +type AppPatch = Partial>; + +type DashboardContextValue = { + dashboard: DashboardData | null; + loading: boolean; + busy: boolean; + notice: Notice | null; + refresh: () => Promise; + dismissNotice: () => void; + createSource: (input: SourceInput) => Promise; + updateSource: (id: string, input: Partial) => Promise; + changeVisibility: (id: string, visibility: Visibility) => Promise; + uploadRelease: (sourceId: string, file: File, appId?: string) => Promise; + saveApp: (id: string, patch: AppPatch) => Promise; + publishRelease: (id: string) => Promise; + copySourceUrl: (source: SourceRecord) => Promise; +}; + +const DashboardContext = createContext(null); + +function messageFor(error: unknown, fallback: string) { + return error instanceof Error ? error.message : fallback; +} + +export function DashboardProvider({ children }: PropsWithChildren) { + const [dashboard, setDashboard] = useState(null); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [notice, setNotice] = useState(null); + + const refresh = useCallback(async () => { + setLoading(true); + try { + setDashboard(await api("/api/v1/dashboard")); + } catch (error) { + setNotice({ tone: "error", text: `APIに接続できません。${messageFor(error, "APIを起動してください。")}` }); + } finally { + setLoading(false); + } + }, []); + + // The provider owns the external dashboard request and refreshes it on mount. + // eslint-disable-next-line react-hooks/set-state-in-effect + useEffect(() => { void refresh(); }, [refresh]); + + const withBusy = useCallback(async (work: () => Promise, success: string, failure: string) => { + setBusy(true); + try { + await work(); + setNotice({ tone: "success", text: success }); + await refresh(); + } catch (error) { + setNotice({ tone: "error", text: messageFor(error, failure) }); + throw error; + } finally { + setBusy(false); + } + }, [refresh]); + + const createSource = useCallback(async (input: SourceInput) => { + await withBusy( + async () => { await api("/api/v1/sources", { method: "POST", body: JSON.stringify(input) }); }, + "Sourceを作成しました。", + "Sourceを作成できませんでした。", + ); + }, [withBusy]); + + const updateSource = useCallback(async (id: string, input: Partial) => { + await withBusy( + async () => { await api(`/api/v1/sources/${id}`, { method: "PATCH", body: JSON.stringify(input) }); }, + "Sourceを更新しました。", + "Sourceを更新できませんでした。", + ); + }, [withBusy]); + + const changeVisibility = useCallback(async (id: string, visibility: Visibility) => { + await withBusy( + async () => { await api(`/api/v1/sources/${id}`, { method: "PATCH", body: JSON.stringify({ visibility }) }); }, + "Sourceの公開状態を更新しました。", + "公開状態を変更できませんでした。", + ); + }, [withBusy]); + + const uploadRelease = useCallback(async (sourceId: string, file: File, appId?: string) => { + setBusy(true); + setNotice({ tone: "info", text: "ADPをアップロードし、Manifestとアセットを検証しています。" }); + try { + const init = await api<{ upload: { id: string }; uploadPlan: UploadPlan }>("/api/v1/uploads", { method: "POST", body: JSON.stringify({ sourceId, appId, filename: file.name, sizeBytes: file.size }) }); + const uploadedParts: Array<{ partNumber: number; etag: string }> = []; + if (init.uploadPlan.mode === "multipart") { + for (const part of init.uploadPlan.parts) { + const start = (part.partNumber - 1) * init.uploadPlan.partSizeBytes; + const response = await fetch(part.uploadUrl, { method: "PUT", body: file.slice(start, Math.min(file.size, start + init.uploadPlan.partSizeBytes)) }); + if (!response.ok) throw new Error(`ADPパート${part.partNumber}の転送に失敗しました。`); + const etag = response.headers.get("etag"); + if (!etag) throw new Error(`ADPパート${part.partNumber}のETagを取得できませんでした。`); + uploadedParts.push({ partNumber: part.partNumber, etag }); + } + } else { + const response = await fetch(init.uploadPlan.uploadUrl, { method: "PUT", headers: { "content-type": "application/zip" }, body: file }); + if (!response.ok) throw new Error("ADPファイルの転送に失敗しました。"); + } + + let complete = await api<{ release?: ReleaseRecord }>(`/api/v1/uploads/${init.upload.id}/complete`, { method: "POST", body: JSON.stringify({ parts: uploadedParts.length ? uploadedParts : undefined }) }); + if (!complete.release) { + for (let attempt = 0; attempt < 20; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1200)); + const status = await api<{ release?: ReleaseRecord }>(`/api/v1/uploads/${init.upload.id}`); + if (status.release) { complete = status; break; } + } + } + setNotice({ tone: complete.release?.status === "ready" ? "success" : "info", text: complete.release ? `v${complete.release.version}(build ${complete.release.buildVersion})の検証が完了しました。` : "アップロードをキューに追加しました。処理完了後に更新してください。" }); + await refresh(); + return complete.release || null; + } catch (error) { + setNotice({ tone: "error", text: messageFor(error, "ADPを処理できませんでした。") }); + throw error; + } finally { + setBusy(false); + } + }, [refresh]); + + const saveApp = useCallback(async (id: string, patch: AppPatch) => { + await withBusy( + async () => { await api(`/api/v1/apps/${id}`, { method: "PATCH", body: JSON.stringify(patch) }); }, + "アプリのSourceメタデータを更新しました。", + "アプリ情報を更新できませんでした。", + ); + }, [withBusy]); + + const publishRelease = useCallback(async (id: string) => { + await withBusy( + async () => { await api(`/api/v1/releases/${id}/publish`, { method: "POST", body: "{}" }); }, + "リリースを公開しました。", + "リリースを公開できませんでした。", + ); + }, [withBusy]); + + const copySourceUrl = useCallback(async (source: SourceRecord) => { + const url = `${API_BASE.replace(/\/$/, "")}/sources/${source.slug}/source.json`; + await navigator.clipboard?.writeText(url); + setNotice({ tone: "success", text: "Source URLをコピーしました。AltStore PALのSource追加画面に貼り付けられます。" }); + }, []); + + const value = useMemo(() => ({ dashboard, loading, busy, notice, refresh, dismissNotice: () => setNotice(null), createSource, updateSource, changeVisibility, uploadRelease, saveApp, publishRelease, copySourceUrl }), [dashboard, loading, busy, notice, refresh, createSource, updateSource, changeVisibility, uploadRelease, saveApp, publishRelease, copySourceUrl]); + + return {children}; +} + +export function useDashboard() { + const context = useContext(DashboardContext); + if (!context) throw new Error("useDashboard must be used inside DashboardProvider"); + return context; +} diff --git a/components/altdock/dashboard-view.tsx b/components/altdock/dashboard-view.tsx new file mode 100644 index 0000000..9298a45 --- /dev/null +++ b/components/altdock/dashboard-view.tsx @@ -0,0 +1,159 @@ +"use client"; + +import { useEffect, useState, type FormEvent, type ReactNode } from "react"; +import { useRouter, useSearchParams } from "next/navigation"; +import { Activity, ArrowUpRight, ChevronRight, Clipboard, Code2, Copy, Database, ExternalLink, Filter, HardDrive, Pencil, Plus, RefreshCw, Search, ShieldCheck, UploadCloud, XCircle, type LucideIcon } from "lucide-react"; +import type { AppRecord, ReleaseRecord, SourceRecord } from "@/packages/core/src/index"; +import { API_BASE, flattenApps, flattenReleases, formatBytes, formatDate, formatDateTime, statusLabel, statusTone, visibilityLabel, visibilityTone, type DashboardData, type DashboardSource, type Visibility } from "@/app/lib/dashboard"; +import { useDashboard } from "./dashboard-provider"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogForm, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; + +type ViewName = "overview" | "sources" | "apps" | "releases"; + +function PageHeading({ eyebrow, title, description, actions }: { eyebrow?: string; title: string; description: string; actions?: ReactNode }) { + return
{eyebrow || "ALTDock WORKSPACE"}

{title}

{description}

{actions}
; +} + +function MetricCard({ label, value, detail, icon: Icon, tone = "neutral" }: { label: string; value: string | number; detail: string; icon: LucideIcon; tone?: "neutral" | "orange" | "blue" | "green" }) { + return
{label}
{value}{detail}
; +} + +function SectionCard({ title, description, action, children, className = "" }: { title: string; description?: string; action?: ReactNode; children: ReactNode; className?: string }) { + return

{title}

{description &&

{description}

}
{action}
{children}
; +} + +function EmptyState({ icon: Icon, title, description, action }: { icon: LucideIcon; title: string; description: string; action?: ReactNode }) { + return
{title}

{description}

{action}
; +} + +function LoadingState() { + return
Workspaceを読み込んでいます

APIから最新の配布状況を取得中です。

; +} + +function InlineStatus({ status }: { status: ReleaseRecord["status"] }) { + return {statusLabel(status)}; +} + +function InlineVisibility({ visibility }: { visibility: Visibility }) { + return {visibilityLabel(visibility)}; +} + +function SourceDialog({ open, onOpenChange, source, busy, onSubmit }: { open: boolean; onOpenChange: (open: boolean) => void; source?: SourceRecord; busy: boolean; onSubmit: (input: { name: string; subtitle: string; description: string; visibility: Visibility }) => Promise }) { + const [form, setForm] = useState({ name: source?.name || "", subtitle: source?.subtitle || "", description: source?.description || "", visibility: source?.visibility || "draft" as Visibility }); + const submit = async (event: FormEvent) => { event.preventDefault(); await onSubmit(form); onOpenChange(false); }; + return
{source ? "SOURCE SETTINGS" : "NEW SOURCE"}
{source ? "Sourceを編集" : "Sourceを作成"}AltStore PALに表示する配布面の基本情報を設定します。