diff options
Diffstat (limited to 'web/ui/src')
29 files changed, 2912 insertions, 0 deletions
diff --git a/web/ui/src/app.css b/web/ui/src/app.css new file mode 100644 index 0000000..db2f519 --- /dev/null +++ b/web/ui/src/app.css @@ -0,0 +1,1170 @@ +/* ---------------------------------------------------------------- + Tidy Index — dashboard styles + + Shares the exact design tokens from the landing page. Adds + dashboard-specific components (tabs, cards, badges, toasts, + form inputs, danger variants). +---------------------------------------------------------------- */ + +/* ---------- self-hosted webfonts ---------- */ + +@font-face { + font-family: 'Fraunces'; + font-style: normal; + font-weight: 300 600; + font-display: swap; + src: url('/fonts/fraunces-latin.woff2') format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} + +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 400 600; + font-display: swap; + src: url('/fonts/inter-latin.woff2') format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} + +@font-face { + font-family: 'JetBrains Mono'; + font-style: normal; + font-weight: 400 500; + font-display: swap; + src: url('/fonts/jetbrains-mono-latin.woff2') format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2212, U+2215, U+FEFF, U+FFFD; +} + +:root { + --c-bg: #ffffff; + --c-bg-soft: #f7f9fc; + --c-bg-tint: #eef4fb; + + --c-rule: #e3ecf5; + --c-rule-strong: #cbd6e6; + + --c-ink: #0b1f3a; + --c-ink-soft: #3b4f6b; + --c-ink-mute: #6b7c93; + + --c-blue: #2563eb; + --c-blue-deep: #1d4ed8; + --c-blue-soft: #dbeafe; + --c-blue-tint: #eef4ff; + + --c-danger: #dc2626; + --c-danger-deep: #b91c1c; + --c-danger-soft: #fee2e2; + --c-danger-tint: #fef2f2; + + --c-success: #059669; + --c-success-soft: #d1fae5; + + --c-warn: #b45309; + --c-warn-soft: #fef3c7; + + --shadow-sm: 0 1px 2px rgba(15, 38, 73, 0.04); + --shadow-md: 0 8px 28px -10px rgba(37, 99, 235, 0.18), + 0 2px 6px rgba(15, 38, 73, 0.05); + --shadow-lg: 0 24px 60px -20px rgba(37, 99, 235, 0.25), + 0 6px 16px rgba(15, 38, 73, 0.06); + + --radius-sm: 6px; + --radius-md: 12px; + --radius-lg: 18px; + + --font-serif: 'Fraunces', 'Iowan Old Style', Georgia, 'Times New Roman', serif; + --font-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', + Helvetica, Arial, sans-serif; + --font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, + Consolas, monospace; + + --max-w: 960px; + --max-w-wide: 1080px; + --gutter: clamp(20px, 4vw, 40px); +} + +* { box-sizing: border-box; } + +html { -webkit-text-size-adjust: 100%; } + +body { + margin: 0; + font-family: var(--font-sans); + font-size: 16px; + line-height: 1.6; + color: var(--c-ink); + background: var(--c-bg); + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; +} + +a { + color: var(--c-blue); + text-decoration: none; + transition: color 160ms ease; +} +a:hover { color: var(--c-blue-deep); } + +img, svg { display: block; max-width: 100%; } + +::selection { + background: var(--c-blue-soft); + color: var(--c-ink); +} + +/* ---------- layout ---------- */ + +.container { + width: 100%; + max-width: var(--max-w); + margin: 0 auto; + padding: 0 var(--gutter); +} + +/* ---------- typographic primitives (match landing) ---------- */ + +.serif { + font-family: var(--font-serif); + font-variation-settings: 'opsz' 144, 'SOFT' 30; + font-weight: 400; + letter-spacing: -0.018em; + color: var(--c-ink); +} + +.serif-italic { + font-style: italic; + font-variation-settings: 'opsz' 144, 'SOFT' 100; +} + +.section-marker { + margin: 0 0 18px; + font-family: var(--font-mono); + font-size: 12px; + font-weight: 500; + letter-spacing: 0.04em; + color: var(--c-blue); + text-transform: lowercase; +} + +.page-title { + margin: 0 0 8px; + font-family: var(--font-serif); + font-variation-settings: 'opsz' 144, 'SOFT' 30; + font-weight: 400; + font-size: clamp(32px, 4.6vw, 44px); + line-height: 1.1; + letter-spacing: -0.02em; + color: var(--c-ink); +} + +.page-subtitle { + margin: 0 0 32px; + font-size: 16px; + color: var(--c-ink-soft); + max-width: 60ch; +} + +/* ---------- dashboard app shell ---------- */ + +.app-header { + position: sticky; + top: 0; + z-index: 40; + background: rgba(255, 255, 255, 0.85); + backdrop-filter: saturate(180%) blur(14px); + -webkit-backdrop-filter: saturate(180%) blur(14px); + border-bottom: 1px solid var(--c-rule); +} + +.app-header-inner { + display: flex; + align-items: center; + justify-content: space-between; + height: 66px; +} + +.brand { + display: inline-flex; + align-items: center; + gap: 12px; + font-family: var(--font-serif); + font-variation-settings: 'opsz' 24; + font-weight: 500; + font-size: 19px; + letter-spacing: -0.005em; + color: var(--c-ink); +} +.brand:hover { color: var(--c-blue); } + +.brand-mark { + display: inline-flex; + align-items: center; + justify-content: center; + width: 30px; + height: 30px; + color: var(--c-blue); +} +.brand-mark svg { width: 22px; height: 22px; } + +.app-header-meta { + display: flex; + align-items: center; + gap: 22px; + font-family: var(--font-mono); + font-size: 12px; + color: var(--c-ink-mute); +} + +.app-header-meta .plan-chip { + padding: 5px 10px; + border: 1px solid var(--c-rule); + border-radius: 999px; + color: var(--c-ink-soft); + text-transform: lowercase; + letter-spacing: 0.04em; +} + +.app-header-meta .plan-chip strong { + color: var(--c-blue); + font-weight: 500; +} + +.app-header-meta .pending-chip { + padding: 5px 10px; + border: 1px solid #fde68a; + background: var(--c-warn-soft); + border-radius: 999px; + color: var(--c-warn); + letter-spacing: 0.02em; + font-family: var(--font-mono); + font-size: 11px; +} + +.app-header-meta a { + color: var(--c-ink-soft); + border-bottom: 1px solid transparent; +} +.app-header-meta a:hover { + color: var(--c-blue); + border-color: var(--c-blue); +} + +/* ---------- tab nav ---------- */ + +.tabs { + border-bottom: 1px solid var(--c-rule); + margin-bottom: 48px; +} + +.tabs-inner { + display: flex; + gap: 4px; + overflow-x: auto; + -ms-overflow-style: none; + scrollbar-width: none; +} +.tabs-inner::-webkit-scrollbar { display: none; } + +.tab { + position: relative; + display: inline-flex; + align-items: center; + gap: 8px; + padding: 18px 18px 16px; + font-family: var(--font-sans); + font-size: 14px; + font-weight: 500; + color: var(--c-ink-mute); + border-bottom: 2px solid transparent; + margin-bottom: -1px; + white-space: nowrap; + transition: color 160ms ease, border-color 160ms ease; +} + +.tab:hover { color: var(--c-ink-soft); } + +.tab.active { + color: var(--c-ink); + border-bottom-color: var(--c-blue); +} + +.tab-num { + font-family: var(--font-mono); + font-size: 11px; + color: var(--c-blue); + font-weight: 500; +} + +/* ---------- main content ---------- */ + +main.app-main { + padding: 56px 0 120px; + min-height: calc(100vh - 66px - 64px); +} + +.entry-main { + padding: 0; + min-height: 100vh; + display: flex; + align-items: center; + justify-content: center; +} + +/* ---------- cards ---------- */ + +.card { + background: #fff; + border: 1px solid var(--c-rule); + border-radius: var(--radius-md); + padding: 26px 28px; + box-shadow: var(--shadow-sm); + transition: border-color 180ms ease, box-shadow 180ms ease; +} + +.card + .card { margin-top: 14px; } + +.card.card-feature { + border-color: var(--c-blue-soft); + background: linear-gradient(180deg, #ffffff 0%, var(--c-blue-tint) 140%); + box-shadow: var(--shadow-md); +} + +.card.card-accent { + border-left: 3px solid var(--c-blue); +} + +.card-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + margin-bottom: 10px; +} + +.card-title { + margin: 0; + font-family: var(--font-serif); + font-variation-settings: 'opsz' 36, 'SOFT' 30; + font-weight: 500; + font-size: 19px; + line-height: 1.2; + letter-spacing: -0.005em; + color: var(--c-ink); +} + +.card-sub { + margin: 0; + font-size: 14px; + color: var(--c-ink-mute); + line-height: 1.55; +} + +.card-body { font-size: 15px; color: var(--c-ink-soft); } + +.card-footer { + margin-top: 18px; + padding-top: 16px; + border-top: 1px solid var(--c-rule); + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + font-family: var(--font-mono); + font-size: 12px; + color: var(--c-ink-mute); +} + +/* ---------- buttons ---------- */ + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + font-family: var(--font-sans); + font-size: 14px; + font-weight: 500; + padding: 10px 18px; + border-radius: 999px; + border: 1px solid transparent; + cursor: pointer; + transition: all 180ms ease; + letter-spacing: -0.005em; + text-decoration: none; + background: transparent; + color: inherit; +} + +.btn svg { width: 15px; height: 15px; } + +.btn-primary { + background: var(--c-ink); + color: #fff; + box-shadow: 0 6px 18px -8px rgba(11, 31, 58, 0.5); +} +.btn-primary:hover { + background: var(--c-blue); + color: #fff; + transform: translateY(-1px); + box-shadow: 0 10px 22px -8px rgba(37, 99, 235, 0.5); +} + +.btn-accent { + background: var(--c-blue); + color: #fff; + box-shadow: 0 6px 18px -8px rgba(37, 99, 235, 0.5); +} +.btn-accent:hover { + background: var(--c-blue-deep); + color: #fff; + transform: translateY(-1px); +} + +.btn-ghost { + background: transparent; + color: var(--c-ink); + border-color: var(--c-rule); +} +.btn-ghost:hover { + background: var(--c-bg-soft); + border-color: var(--c-blue-soft); + color: var(--c-blue-deep); +} + +.btn-danger { + background: transparent; + color: var(--c-danger); + border-color: var(--c-danger-soft); +} +.btn-danger:hover { + background: var(--c-danger-tint); + border-color: var(--c-danger); + color: var(--c-danger-deep); +} + +.btn-sm { + padding: 7px 14px; + font-size: 13px; +} +.btn-lg { + padding: 14px 26px; + font-size: 15px; +} + +.btn-link { + display: inline-flex; + align-items: center; + gap: 6px; + font-family: var(--font-sans); + font-size: 14px; + font-weight: 500; + color: var(--c-ink-soft); + border: 0; + background: transparent; + cursor: pointer; + padding: 4px 0; + border-bottom: 1px solid var(--c-rule-strong); +} +.btn-link:hover { + color: var(--c-blue); + border-color: var(--c-blue); +} + +/* ---------- form inputs ---------- */ + +.field { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 18px; +} + +.field-label { + font-family: var(--font-mono); + font-size: 11px; + letter-spacing: 0.06em; + text-transform: lowercase; + color: var(--c-ink-mute); +} + +.input, .select, .textarea { + width: 100%; + font-family: var(--font-sans); + font-size: 15px; + line-height: 1.5; + color: var(--c-ink); + background: #fff; + border: 1px solid var(--c-rule); + border-radius: var(--radius-sm); + padding: 11px 14px; + transition: border-color 160ms ease, box-shadow 160ms ease; +} +.input:focus, .select:focus, .textarea:focus { + outline: none; + border-color: var(--c-blue); + box-shadow: 0 0 0 3px var(--c-blue-tint); +} + +.input.mono { + font-family: var(--font-mono); + font-size: 13px; +} + +.input.input-lg { + padding: 14px 18px; + font-size: 16px; +} + +.help { + font-size: 13px; + color: var(--c-ink-mute); + line-height: 1.5; +} + +/* ---------- chips / scope toggles ---------- */ + +.chip-grid { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.chip { + font-family: var(--font-mono); + font-size: 12px; + padding: 7px 13px; + border-radius: 999px; + border: 1px solid var(--c-rule); + background: #fff; + color: var(--c-ink-soft); + cursor: pointer; + transition: all 140ms ease; + user-select: none; +} +.chip:hover { + border-color: var(--c-blue-soft); + color: var(--c-ink); +} +.chip.active { + background: var(--c-blue-tint); + border-color: var(--c-blue); + color: var(--c-blue-deep); +} + +.chip-all { + font-weight: 500; +} + +/* ---------- badges ---------- */ + +.badge { + display: inline-flex; + align-items: center; + gap: 6px; + font-family: var(--font-mono); + font-size: 10px; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; + padding: 4px 9px; + border-radius: 999px; + background: var(--c-blue-tint); + color: var(--c-blue-deep); + border: 1px solid var(--c-blue-soft); +} + +.badge-success { + background: var(--c-success-soft); + color: var(--c-success); + border-color: #a7f3d0; +} + +.badge-muted { + background: var(--c-bg-soft); + color: var(--c-ink-mute); + border-color: var(--c-rule); +} + +.badge-danger { + background: var(--c-danger-soft); + color: var(--c-danger-deep); + border-color: #fecaca; +} + +.badge-warn { + background: var(--c-warn-soft); + color: var(--c-warn); + border-color: #fde68a; +} + +/* ---------- banner ---------- */ + +.banner { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + padding: 14px 20px; + background: var(--c-warn-soft); + border: 1px solid #fde68a; + border-radius: var(--radius-sm); + font-size: 14px; + color: var(--c-warn); + margin-bottom: 28px; +} +.banner strong { color: #78350f; font-weight: 500; } + +/* ---------- toasts ---------- */ + +.toast-container { + position: fixed; + top: 24px; + left: 50%; + transform: translateX(-50%); + z-index: 100; + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + pointer-events: none; +} + +.toast { + pointer-events: auto; + display: inline-flex; + align-items: center; + gap: 10px; + background: #fff; + border: 1px solid var(--c-rule-strong); + border-radius: 999px; + padding: 11px 22px; + font-family: var(--font-sans); + font-size: 14px; + color: var(--c-ink); + box-shadow: var(--shadow-md); + animation: toast-in 220ms ease-out; +} + +.toast.toast-success { + border-color: #a7f3d0; + background: linear-gradient(180deg, #ffffff 0%, var(--c-success-soft) 180%); +} +.toast.toast-success .toast-dot { background: var(--c-success); } + +.toast.toast-error { + border-color: #fecaca; + background: linear-gradient(180deg, #ffffff 0%, var(--c-danger-soft) 180%); +} +.toast.toast-error .toast-dot { background: var(--c-danger); } + +.toast-dot { + display: inline-block; + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--c-blue); +} + +@keyframes toast-in { + from { opacity: 0; transform: translateY(-8px); } + to { opacity: 1; transform: translateY(0); } +} + +/* ---------- key reveal banner ---------- */ + +.key-reveal { + background: linear-gradient(180deg, #ffffff 0%, var(--c-blue-tint) 140%); + border: 1px solid var(--c-blue-soft); + border-left: 3px solid var(--c-blue); + border-radius: var(--radius-md); + padding: 22px 26px; + margin-bottom: 24px; + box-shadow: var(--shadow-md); +} + +.key-reveal-head { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 14px; +} + +.key-reveal-head strong { + font-family: var(--font-serif); + font-variation-settings: 'opsz' 36, 'SOFT' 30; + font-size: 17px; + font-weight: 500; + color: var(--c-ink); +} + +.key-reveal-value { + display: flex; + align-items: center; + gap: 10px; + padding: 14px 18px; + background: #fff; + border: 1px solid var(--c-rule); + border-radius: var(--radius-sm); + font-family: var(--font-mono); + font-size: 13px; + color: var(--c-ink); + word-break: break-all; +} + +.key-reveal-warn { + margin: 14px 0 0; + font-size: 13px; + color: var(--c-warn); +} + +/* ---------- key list ---------- */ + +.key-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + flex-wrap: wrap; +} + +.key-row-main { + flex: 1; + min-width: 240px; + display: flex; + flex-direction: column; + gap: 6px; +} + +.key-name { + font-family: var(--font-serif); + font-variation-settings: 'opsz' 36, 'SOFT' 30; + font-weight: 500; + font-size: 18px; + color: var(--c-ink); + display: flex; + align-items: center; + gap: 10px; +} + +.key-mask { + font-family: var(--font-mono); + font-size: 13px; + color: var(--c-ink-soft); + letter-spacing: 0.02em; +} + +.key-meta { + display: flex; + flex-wrap: wrap; + gap: 14px; + font-family: var(--font-mono); + font-size: 11px; + color: var(--c-ink-mute); + margin-top: 6px; +} + +.key-meta .meta-label { + color: var(--c-blue); + text-transform: lowercase; + margin-right: 4px; +} + +.scope-summary { + font-family: var(--font-mono); + font-size: 11px; + color: var(--c-ink-mute); +} + +.scope-summary code { + background: var(--c-bg-soft); + padding: 2px 6px; + border-radius: 4px; + margin-right: 4px; +} + +/* ---------- plan grid ---------- */ + +.plan-grid { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 18px; + margin-top: 8px; +} + +.plan-card { + position: relative; + background: #fff; + border: 1px solid var(--c-rule); + border-radius: var(--radius-md); + padding: 28px 28px 24px; + box-shadow: var(--shadow-sm); + transition: border-color 200ms ease, box-shadow 200ms ease, transform 200ms ease; + display: flex; + flex-direction: column; +} +.plan-card:hover { + border-color: var(--c-blue-soft); + box-shadow: var(--shadow-md); + transform: translateY(-1px); +} + +.plan-card.current { + border-color: var(--c-blue); + box-shadow: 0 10px 30px -12px rgba(37, 99, 235, 0.25); + background: linear-gradient(180deg, #ffffff 0%, var(--c-blue-tint) 160%); +} + +.plan-card .badge { + position: absolute; + top: 20px; + right: 20px; +} + +.plan-name { + font-family: var(--font-serif); + font-variation-settings: 'opsz' 36, 'SOFT' 30; + font-weight: 500; + font-size: 22px; + color: var(--c-ink); + margin: 0 0 4px; +} + +.plan-price { + font-family: var(--font-serif); + font-variation-settings: 'opsz' 144, 'SOFT' 30; + font-size: 42px; + font-weight: 400; + line-height: 1; + color: var(--c-ink); + margin: 8px 0 14px; +} +.plan-price small { + font-family: var(--font-sans); + font-size: 14px; + font-weight: 400; + color: var(--c-ink-mute); +} + +.plan-features { + list-style: none; + padding: 0; + margin: 0 0 22px; + display: flex; + flex-direction: column; + gap: 8px; +} +.plan-features li { + font-size: 14px; + color: var(--c-ink-soft); + display: flex; + align-items: center; + gap: 8px; +} +.plan-features li::before { + content: "·"; + color: var(--c-blue); + font-weight: 700; + font-size: 20px; + line-height: 1; + margin-top: 2px; +} + +.plan-cta { + margin-top: auto; +} + +/* ---------- usage ---------- */ + +.usage-summary { + display: grid; + grid-template-columns: 1fr auto; + gap: 24px; + align-items: center; + margin-bottom: 14px; +} + +.usage-count { + font-family: var(--font-serif); + font-variation-settings: 'opsz' 144, 'SOFT' 30; + font-size: 44px; + line-height: 1; + font-weight: 400; + color: var(--c-ink); +} +.usage-count small { + font-family: var(--font-sans); + font-size: 14px; + font-weight: 400; + color: var(--c-ink-mute); +} + +.usage-bar { + width: 100%; + height: 6px; + background: var(--c-bg-soft); + border: 1px solid var(--c-rule); + border-radius: 999px; + overflow: hidden; + margin-top: 18px; +} + +.usage-bar-fill { + height: 100%; + background: linear-gradient(90deg, var(--c-blue) 0%, #60a5fa 100%); + border-radius: 999px; + transition: width 300ms ease; +} + +.usage-table { + width: 100%; + border-collapse: collapse; + font-size: 14px; + margin-top: 12px; +} + +.usage-table th { + text-align: left; + font-family: var(--font-mono); + font-size: 11px; + letter-spacing: 0.06em; + text-transform: lowercase; + color: var(--c-ink-mute); + padding: 12px 0; + border-bottom: 1px solid var(--c-rule); + font-weight: 500; +} + +.usage-table td { + padding: 14px 0; + border-bottom: 1px solid var(--c-rule); + color: var(--c-ink-soft); +} +.usage-table tr:last-child td { border-bottom: 0; } +.usage-table td:first-child { + font-family: var(--font-mono); + font-size: 13px; + color: var(--c-ink); +} +.usage-table td.num { + text-align: right; + font-variant-numeric: tabular-nums; + color: var(--c-ink); +} + +/* ---------- entry / landing page of dashboard ---------- */ + +.entry-card { + width: 100%; + max-width: 440px; + background: #fff; + border: 1px solid var(--c-rule); + border-radius: var(--radius-lg); + padding: 48px 44px 40px; + box-shadow: var(--shadow-md); + text-align: left; +} + +.entry-brand { + font-family: var(--font-mono); + font-size: 12px; + letter-spacing: 0.22em; + color: var(--c-blue); + margin-bottom: 16px; +} + +.entry-tagline { + font-family: var(--font-serif); + font-variation-settings: 'opsz' 144, 'SOFT' 30; + font-weight: 400; + font-size: 28px; + line-height: 1.15; + letter-spacing: -0.015em; + color: var(--c-ink); + margin: 0 0 32px; +} + +.entry-tagline em { + font-style: italic; + font-variation-settings: 'opsz' 144, 'SOFT' 100; + color: var(--c-blue); +} + +.entry-divider { + display: flex; + align-items: center; + gap: 10px; + margin: 24px 0; + font-family: var(--font-mono); + font-size: 11px; + color: var(--c-ink-mute); + text-transform: lowercase; + letter-spacing: 0.06em; +} +.entry-divider::before, +.entry-divider::after { + content: ""; + flex: 1; + height: 1px; + background: var(--c-rule); +} + +.entry-magic-note { + margin: 16px 0 0; + padding: 14px 16px; + background: var(--c-blue-tint); + border: 1px solid var(--c-blue-soft); + border-radius: var(--radius-sm); + font-family: var(--font-mono); + font-size: 11px; + color: var(--c-ink-soft); + word-break: break-all; +} +.entry-magic-note strong { + display: block; + color: var(--c-blue); + text-transform: lowercase; + letter-spacing: 0.06em; + margin-bottom: 6px; + font-weight: 500; +} +.entry-magic-note a { color: var(--c-blue-deep); } + +/* ---------- footer ---------- */ + +.app-footer { + border-top: 1px solid var(--c-rule); + background: var(--c-bg); + padding: 28px 0; + margin-top: auto; +} + +.app-footer-inner { + display: flex; + align-items: center; + justify-content: center; + gap: 18px; + flex-wrap: wrap; + font-family: var(--font-mono); + font-size: 12px; + color: var(--c-ink-mute); +} + +.app-footer-line { + margin: 0; + letter-spacing: 0.02em; +} + +.app-footer-line a { + color: var(--c-ink-soft); + border-bottom: 1px solid var(--c-rule-strong); + padding-bottom: 1px; + transition: color 160ms ease, border-color 160ms ease; +} +.app-footer-line a:hover { + color: var(--c-blue); + border-color: var(--c-blue); +} + +/* ---------- inline flex helpers ---------- */ + +.row { display: flex; align-items: center; gap: 12px; } +.row-between { display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.row-wrap { flex-wrap: wrap; } +.col { display: flex; flex-direction: column; gap: 12px; } + +.stack-sm > * + * { margin-top: 8px; } +.stack > * + * { margin-top: 14px; } +.stack-lg > * + * { margin-top: 22px; } + +.mt-0 { margin-top: 0; } +.mt-8 { margin-top: 8px; } +.mt-16 { margin-top: 16px; } +.mt-24 { margin-top: 24px; } +.mt-40 { margin-top: 40px; } + +.mb-0 { margin-bottom: 0; } +.mb-8 { margin-bottom: 8px; } +.mb-16 { margin-bottom: 16px; } +.mb-24 { margin-bottom: 24px; } + +.text-mute { color: var(--c-ink-mute); } +.text-soft { color: var(--c-ink-soft); } +.text-mono { font-family: var(--font-mono); font-size: 13px; } + +/* ---------- code blocks ---------- */ + +code, pre { + font-family: var(--font-mono); +} + +.code-block { + background: var(--c-bg-soft); + border: 1px solid var(--c-rule); + border-radius: var(--radius-sm); + padding: 14px 18px; + font-family: var(--font-mono); + font-size: 12.5px; + line-height: 1.6; + color: var(--c-ink); + overflow-x: auto; + white-space: pre; + margin: 0; +} + +/* ---------- empty state ---------- */ + +.empty-state { + text-align: center; + padding: 56px 24px; + border: 1px dashed var(--c-rule-strong); + border-radius: var(--radius-md); + color: var(--c-ink-mute); +} +.empty-state p { margin: 0 0 8px; font-size: 15px; } +.empty-state p.empty-title { + font-family: var(--font-serif); + font-variation-settings: 'opsz' 36, 'SOFT' 30; + font-weight: 500; + font-size: 18px; + color: var(--c-ink-soft); +} + +/* ---------- danger zone ---------- */ + +.danger-zone { + margin-top: 40px; + border: 1px solid var(--c-danger-soft); + background: var(--c-danger-tint); + border-radius: var(--radius-md); + padding: 22px 26px; +} +.danger-zone-title { + font-family: var(--font-mono); + font-size: 11px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--c-danger); + margin: 0 0 8px; +} +.danger-zone-body { + font-size: 14px; + color: var(--c-ink-soft); + margin: 0 0 16px; +} + +/* ---------- responsive ---------- */ + +@media (max-width: 760px) { + .plan-grid { grid-template-columns: 1fr; } + .usage-summary { grid-template-columns: 1fr; } + .app-header-meta .plan-chip { display: none; } + main.app-main { padding: 40px 0 80px; } + .tabs { margin-bottom: 32px; } + .card { padding: 22px 20px; } + .entry-card { padding: 36px 28px 32px; } +} + +@media (prefers-reduced-motion: reduce) { + * { transition: none !important; animation: none !important; } +} diff --git a/web/ui/src/app.d.ts b/web/ui/src/app.d.ts new file mode 100644 index 0000000..f609a0b --- /dev/null +++ b/web/ui/src/app.d.ts @@ -0,0 +1,16 @@ +// See https://kit.svelte.dev/docs/types#app + +import type { Account } from '$lib/server/db'; + +declare global { + namespace App { + interface Locals { + account: Account | null; + } + // interface PageData {} + // interface PageState {} + // interface Platform {} + } +} + +export {}; diff --git a/web/ui/src/app.html b/web/ui/src/app.html new file mode 100644 index 0000000..beb1a42 --- /dev/null +++ b/web/ui/src/app.html @@ -0,0 +1,42 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <meta name="description" content="Tidy Index — dashboard" /> + <link rel="icon" type="image/svg+xml" href="%sveltekit.assets%/favicon.svg" /> + + <!-- Preload the three self-hosted webfonts so the browser fetches + them in parallel with the CSS, not after it. --> + <link rel="preload" href="%sveltekit.assets%/fonts/fraunces-latin.woff2" as="font" type="font/woff2" crossorigin /> + <link rel="preload" href="%sveltekit.assets%/fonts/inter-latin.woff2" as="font" type="font/woff2" crossorigin /> + <link rel="preload" href="%sveltekit.assets%/fonts/jetbrains-mono-latin.woff2" as="font" type="font/woff2" crossorigin /> + + <!-- Prevent FOUT: hide the body until webfonts are loaded, with a + 1500ms safety timeout so the page never stays blank forever. --> + <style>html.fonts-pending body { visibility: hidden; }</style> + <script> + (function () { + var d = document; + d.documentElement.classList.add('fonts-pending'); + var done = false; + function reveal() { + if (done) return; + done = true; + d.documentElement.classList.remove('fonts-pending'); + } + if (d.fonts && d.fonts.ready && typeof d.fonts.ready.then === 'function') { + d.fonts.ready.then(reveal); + } else { + reveal(); + } + setTimeout(reveal, 1500); + })(); + </script> + + %sveltekit.head% + </head> + <body data-sveltekit-preload-data="hover"> + <div style="display: contents">%sveltekit.body%</div> + </body> +</html> diff --git a/web/ui/src/hooks.server.ts b/web/ui/src/hooks.server.ts new file mode 100644 index 0000000..1204a94 --- /dev/null +++ b/web/ui/src/hooks.server.ts @@ -0,0 +1,16 @@ +import { redirect, type Handle } from '@sveltejs/kit'; + +import { getAccountFromCookies } from '$lib/server/auth'; + +export const handle: Handle = async ({ event, resolve }) => { + event.locals.account = getAccountFromCookies(event.cookies); + + const path = event.url.pathname; + + // /dashboard/* requires a session. Bounce to the entry page if missing. + if (path.startsWith('/dashboard') && !event.locals.account) { + throw redirect(303, '/'); + } + + return resolve(event); +}; diff --git a/web/ui/src/lib/components/BrandMark.svelte b/web/ui/src/lib/components/BrandMark.svelte new file mode 100644 index 0000000..0feab32 --- /dev/null +++ b/web/ui/src/lib/components/BrandMark.svelte @@ -0,0 +1,7 @@ +<span class="brand-mark" aria-hidden="true"> + <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"> + <rect x="4" y="6" width="24" height="3" rx="1.5" fill="currentColor" /> + <rect x="4" y="14" width="18" height="3" rx="1.5" fill="currentColor" opacity="0.7" /> + <rect x="4" y="22" width="12" height="3" rx="1.5" fill="currentColor" opacity="0.4" /> + </svg> +</span> diff --git a/web/ui/src/lib/components/Footer.svelte b/web/ui/src/lib/components/Footer.svelte new file mode 100644 index 0000000..8042f64 --- /dev/null +++ b/web/ui/src/lib/components/Footer.svelte @@ -0,0 +1,8 @@ +<footer class="app-footer"> + <div class="container app-footer-inner"> + <p class="app-footer-line"> + Need something — email us at + <a href="mailto:contact@tidyindex.com">contact@tidyindex.com</a> + </p> + </div> +</footer> diff --git a/web/ui/src/lib/components/Toasts.svelte b/web/ui/src/lib/components/Toasts.svelte new file mode 100644 index 0000000..3d66b3f --- /dev/null +++ b/web/ui/src/lib/components/Toasts.svelte @@ -0,0 +1,12 @@ +<script lang="ts"> + import { toasts } from '$lib/stores/toasts'; +</script> + +<div class="toast-container" aria-live="polite" aria-atomic="true"> + {#each $toasts as t (t.id)} + <div class="toast toast-{t.kind}"> + <span class="toast-dot"></span> + <span>{t.message}</span> + </div> + {/each} +</div> diff --git a/web/ui/src/lib/datasets.ts b/web/ui/src/lib/datasets.ts new file mode 100644 index 0000000..83c2e4e --- /dev/null +++ b/web/ui/src/lib/datasets.ts @@ -0,0 +1,46 @@ +/** + * The shared list of dataset slugs a user can scope an API key to. + * Used by the create-key form, the key scope display, and the usage + * breakdown. The order here is the order they show up in the UI. + */ +export const DATASETS = [ + 'irs-990', + 'irs-990pf', + 'sec-edgar', + 'sec-13f', + 'sec-form4', + 'fec-contributions', + 'lobbying-federal', + 'usaspending', + 'pacer', + 'state-corps', + 'ucc-filings', + 'fda-faers', + 'osha', + 'nih-reporter', + 'cfpb-complaints' +] as const; + +export type DatasetSlug = (typeof DATASETS)[number]; + +/** Friendly short label for a dataset slug. */ +export function datasetLabel(slug: string): string { + switch (slug) { + case 'irs-990': return 'IRS 990'; + case 'irs-990pf': return 'IRS 990-PF'; + case 'sec-edgar': return 'SEC EDGAR'; + case 'sec-13f': return 'SEC 13-F'; + case 'sec-form4': return 'SEC Form 4'; + case 'fec-contributions': return 'FEC contributions'; + case 'lobbying-federal': return 'Federal lobbying'; + case 'usaspending': return 'USAspending'; + case 'pacer': return 'PACER'; + case 'state-corps': return 'State incorporation'; + case 'ucc-filings': return 'UCC filings'; + case 'fda-faers': return 'FDA FAERS'; + case 'osha': return 'OSHA inspections'; + case 'nih-reporter': return 'NIH RePORTER'; + case 'cfpb-complaints': return 'CFPB complaints'; + default: return slug; + } +} diff --git a/web/ui/src/lib/keys.ts b/web/ui/src/lib/keys.ts new file mode 100644 index 0000000..5fddedc --- /dev/null +++ b/web/ui/src/lib/keys.ts @@ -0,0 +1,24 @@ +import { DATASETS } from './datasets'; + +/** Display mask: prefix + bullets. We don't store the full key, so we + * cannot show any trailing characters from it after creation. */ +export function maskKey(prefix: string): string { + return `${prefix}${'\u2022'.repeat(24)}`; +} + +/** Validate + normalize a scope list from user input. Used server-side + * when persisting a new key; kept in the client-safe module so the + * create-key form can mirror its logic if it wants. */ +export function normalizeScopes(input: string[]): string[] { + if (!input || input.length === 0) return ['*']; + if (input.includes('*')) return ['*']; + const allowed = new Set<string>(DATASETS); + const out = input.filter((s) => allowed.has(s)); + return out.length === 0 ? ['*'] : out; +} + +export function scopeSummary(scopes: string[]): string { + if (scopes.length === 1 && scopes[0] === '*') return 'all datasets'; + if (scopes.length <= 3) return scopes.join(', '); + return `${scopes.slice(0, 2).join(', ')} +${scopes.length - 2} more`; +} diff --git a/web/ui/src/lib/plans.ts b/web/ui/src/lib/plans.ts new file mode 100644 index 0000000..bf6c474 --- /dev/null +++ b/web/ui/src/lib/plans.ts @@ -0,0 +1,82 @@ +export type PlanId = 'free' | 'dev' | 'pro' | 'enterprise'; + +export interface Plan { + id: PlanId; + name: string; + price: number | null; // null = custom / contact us + priceLabel: string; + period: string; + requestsPerMonth: number; // Infinity for enterprise + maxKeys: number; // Infinity for enterprise + features: string[]; + cta: string; +} + +export const PLANS: Record<PlanId, Plan> = { + free: { + id: 'free', + name: 'Free', + price: 0, + priceLabel: '$0', + period: 'forever', + requestsPerMonth: 1_000, + maxKeys: 1, + features: [ + '1,000 requests per month', + '1 API key', + 'JSON + JSONL access', + 'Community support' + ], + cta: 'Switch to Free' + }, + dev: { + id: 'dev', + name: 'Developer', + price: 100, + priceLabel: '$100', + period: '/ month', + requestsPerMonth: 50_000, + maxKeys: 5, + features: [ + '50,000 requests per month', + '5 API keys', + 'All response shapes', + 'Email support' + ], + cta: 'Switch to Developer' + }, + pro: { + id: 'pro', + name: 'Professional', + price: 1000, + priceLabel: '$1,000', + period: '/ month', + requestsPerMonth: 500_000, + maxKeys: 20, + features: [ + '500,000 requests per month', + '20 API keys', + 'Priority support', + 'SLA on uptime' + ], + cta: 'Switch to Pro' + }, + enterprise: { + id: 'enterprise', + name: 'Enterprise', + price: null, + priceLabel: 'Custom', + period: '', + requestsPerMonth: Number.POSITIVE_INFINITY, + maxKeys: Number.POSITIVE_INFINITY, + features: [ + 'Unlimited requests', + 'Unlimited keys', + 'Dedicated support', + 'Custom datasets and SLAs' + ], + cta: 'Contact us' + } +}; + +export const PLAN_ORDER: PlanId[] = ['free', 'dev', 'pro', 'enterprise']; diff --git a/web/ui/src/lib/server/auth.ts b/web/ui/src/lib/server/auth.ts new file mode 100644 index 0000000..6f202d3 --- /dev/null +++ b/web/ui/src/lib/server/auth.ts @@ -0,0 +1,153 @@ +import jwt from 'jsonwebtoken'; +import { randomBytes } from 'node:crypto'; +import { dev } from '$app/environment'; +import { env } from '$env/dynamic/private'; +import type { Cookies } from '@sveltejs/kit'; + +import { db, queries, newId, now, type Account } from './db'; + +function getJwtSecret(): string { + const secret = env.JWT_SECRET; + if (!secret) { + throw new Error( + 'JWT_SECRET env variable is required. Copy .env.example to .env ' + + 'and generate one with `openssl rand -base64 48`.' + ); + } + return secret; +} + +const COOKIE_NAME = 'ti_sess'; +const COOKIE_MAX_AGE = 60 * 60 * 24 * 365; // 1 year + +interface SessionPayload { + sub: string; // account id +} + +export function createSession(cookies: Cookies, accountId: string): void { + const token = jwt.sign( + { sub: accountId } satisfies SessionPayload, + getJwtSecret(), + { algorithm: 'HS256' } + ); + cookies.set(COOKIE_NAME, token, { + path: '/', + httpOnly: true, + sameSite: 'lax', + secure: !dev, + maxAge: COOKIE_MAX_AGE + }); +} + +export function clearSession(cookies: Cookies): void { + cookies.delete(COOKIE_NAME, { path: '/' }); +} + +export function getAccountFromCookies(cookies: Cookies): Account | null { + const raw = cookies.get(COOKIE_NAME); + if (!raw) return null; + try { + const decoded = jwt.verify(raw, getJwtSecret(), { + algorithms: ['HS256'] + }) as SessionPayload; + if (!decoded.sub) return null; + const account = queries.accountById.get(decoded.sub); + return account ?? null; + } catch { + return null; + } +} + +// -------- account helpers -------- + +/** Create a brand-new anonymous account (no email). */ +export function createAnonymousAccount(): Account { + const id = newId(); + const ts = now(); + queries.insertAccount.run(id, null, 'free', ts); + return { id, email: null, pending_email: null, plan: 'free', created_at: ts }; +} + +/** Find an account by email or create a new one with that email. */ +export function getOrCreateAccountByEmail(email: string): Account { + const existing = queries.accountByEmail.get(email); + if (existing) return existing; + const id = newId(); + const ts = now(); + queries.insertAccount.run(id, email, 'free', ts); + return { id, email, pending_email: null, plan: 'free', created_at: ts }; +} + +// -------- magic links -------- + +export interface MagicLink { + token: string; + expires_at: number; + url: string; +} + +export function generateMagicLink( + accountId: string, + baseUrl: string +): MagicLink { + const token = randomBytes(24).toString('base64url'); + const id = newId(); + const ts = now(); + const expires = ts + 15 * 60 * 1000; // 15 minutes + queries.insertMagicLink.run(id, accountId, token, expires, ts); + const url = `${baseUrl.replace(/\/$/, '')}/auth/callback?token=${token}`; + return { token, expires_at: expires, url }; +} + +export function consumeMagicLink(token: string): Account | null { + const row = queries.magicLinkByToken.get(token); + if (!row) return null; + if (row.used === 1) return null; + if (row.expires_at < now()) return null; + queries.markMagicLinkUsed.run(row.id); + const account = queries.accountById.get(row.account_id); + return account ?? null; +} + +// -------- email attach / merge -------- + +/** + * Attach an email to an existing (anonymous) account. If another account + * already uses that email, merge this account into the other one — all + * API keys move over, the anonymous account is deleted, and the caller + * receives the surviving account id (which may be different from the + * one passed in). + */ +export function attachEmailToAccount( + accountId: string, + email: string +): { accountId: string; merged: boolean } { + const normalized = email.trim().toLowerCase(); + if (!normalized) throw new Error('Email is empty'); + + const current = queries.accountById.get(accountId); + if (!current) throw new Error('Account not found'); + + const existing = queries.accountByEmail.get(normalized); + + // Same account already has this email — no-op. + if (existing && existing.id === current.id) { + return { accountId: current.id, merged: false }; + } + + // No other account has this email — just attach it. + if (!existing) { + queries.updateAccountEmail.run(normalized, current.id); + return { accountId: current.id, merged: false }; + } + + // Another account already owns the email. Merge current into existing: + // move all keys over, then delete the current account. + const merge = db.transaction(() => { + queries.reassignKeys.run(existing.id, current.id); + queries.deleteAccount.run(current.id); + }); + merge(); + + return { accountId: existing.id, merged: true }; +} diff --git a/web/ui/src/lib/server/db.ts b/web/ui/src/lib/server/db.ts new file mode 100644 index 0000000..ee5736d --- /dev/null +++ b/web/ui/src/lib/server/db.ts @@ -0,0 +1,233 @@ +import Database from 'better-sqlite3'; +import { mkdirSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { env } from '$env/dynamic/private'; + +import type { PlanId } from '$lib/plans'; + +const DB_PATH = resolve(env.DATABASE_PATH || './data/dashboard.db'); + +// Make sure the data/ directory exists before better-sqlite3 tries to open. +mkdirSync(dirname(DB_PATH), { recursive: true }); + +export const db = new Database(DB_PATH); +db.pragma('journal_mode = WAL'); +db.pragma('foreign_keys = ON'); + +// -------- schema -------- + +db.exec(` + CREATE TABLE IF NOT EXISTS accounts ( + id TEXT PRIMARY KEY, + email TEXT UNIQUE, + pending_email TEXT, + plan TEXT NOT NULL DEFAULT 'free', + created_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS api_keys ( + id TEXT PRIMARY KEY, + account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + key_hash TEXT NOT NULL UNIQUE, + key_prefix TEXT NOT NULL, + name TEXT NOT NULL, + scopes TEXT NOT NULL DEFAULT '["*"]', + active INTEGER NOT NULL DEFAULT 1, + created_at INTEGER NOT NULL, + last_used_at INTEGER + ); + CREATE INDEX IF NOT EXISTS idx_api_keys_account ON api_keys(account_id); + + CREATE TABLE IF NOT EXISTS magic_links ( + id TEXT PRIMARY KEY, + account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + token TEXT NOT NULL UNIQUE, + expires_at INTEGER NOT NULL, + used INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_magic_links_token ON magic_links(token); + + CREATE TABLE IF NOT EXISTS usage_events ( + id TEXT PRIMARY KEY, + api_key_id TEXT NOT NULL REFERENCES api_keys(id) ON DELETE CASCADE, + dataset TEXT NOT NULL, + timestamp INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_usage_key ON usage_events(api_key_id); + CREATE INDEX IF NOT EXISTS idx_usage_timestamp ON usage_events(timestamp); + CREATE INDEX IF NOT EXISTS idx_usage_dataset ON usage_events(dataset); +`); + +// Idempotent migration: pre-existing dashboard.db files won't have +// pending_email yet. SQLite has no IF NOT EXISTS for ALTER, so check +// PRAGMA table_info first. +{ + const cols = db + .prepare(`PRAGMA table_info(accounts)`) + .all() as Array<{ name: string }>; + if (!cols.some((c) => c.name === 'pending_email')) { + db.exec(`ALTER TABLE accounts ADD COLUMN pending_email TEXT`); + } +} + +// -------- types -------- + +export interface Account { + id: string; + email: string | null; + /** Email the user is mid-verifying. Cleared on completion or cancel. */ + pending_email: string | null; + plan: PlanId; + created_at: number; +} + +export interface ApiKeyRow { + id: string; + account_id: string; + key_hash: string; + key_prefix: string; + name: string; + scopes: string; // JSON string on disk + active: number; // 0 / 1 + created_at: number; + last_used_at: number | null; +} + +export interface ApiKey { + id: string; + account_id: string; + key_prefix: string; + name: string; + scopes: string[]; // decoded + active: boolean; + created_at: number; + last_used_at: number | null; +} + +export function rowToKey(row: ApiKeyRow): ApiKey { + return { + id: row.id, + account_id: row.account_id, + key_prefix: row.key_prefix, + name: row.name, + scopes: JSON.parse(row.scopes), + active: row.active === 1, + created_at: row.created_at, + last_used_at: row.last_used_at + }; +} + +// -------- helpers -------- + +export function now(): number { + return Date.now(); +} + +export function newId(): string { + return randomUUID(); +} + +// -------- prepared statements -------- + +const stmts = { + accountById: db.prepare<string, Account>( + `SELECT id, email, pending_email, plan, created_at FROM accounts WHERE id = ?` + ), + accountByEmail: db.prepare<string, Account>( + `SELECT id, email, pending_email, plan, created_at FROM accounts WHERE email = ?` + ), + insertAccount: db.prepare( + `INSERT INTO accounts (id, email, plan, created_at) VALUES (?, ?, ?, ?)` + ), + updateAccountEmail: db.prepare( + `UPDATE accounts SET email = ? WHERE id = ?` + ), + setPendingEmail: db.prepare( + `UPDATE accounts SET pending_email = ? WHERE id = ?` + ), + clearPendingEmail: db.prepare( + `UPDATE accounts SET pending_email = NULL WHERE id = ?` + ), + promotePendingEmail: db.prepare( + `UPDATE accounts SET email = pending_email, pending_email = NULL WHERE id = ?` + ), + updateAccountPlan: db.prepare( + `UPDATE accounts SET plan = ? WHERE id = ?` + ), + deleteAccount: db.prepare( + `DELETE FROM accounts WHERE id = ?` + ), + reassignKeys: db.prepare( + `UPDATE api_keys SET account_id = ? WHERE account_id = ?` + ), + reassignUsage: db.prepare( + `UPDATE usage_events SET api_key_id = api_key_id WHERE api_key_id IN + (SELECT id FROM api_keys WHERE account_id = ?)` + ), + keysForAccount: db.prepare<string, ApiKeyRow>( + `SELECT * FROM api_keys WHERE account_id = ? ORDER BY created_at DESC` + ), + keyById: db.prepare<[string, string], ApiKeyRow>( + `SELECT * FROM api_keys WHERE id = ? AND account_id = ?` + ), + insertKey: db.prepare( + `INSERT INTO api_keys + (id, account_id, key_hash, key_prefix, name, scopes, active, created_at) + VALUES (?, ?, ?, ?, ?, ?, 1, ?)` + ), + revokeKey: db.prepare( + `UPDATE api_keys SET active = 0 WHERE id = ? AND account_id = ?` + ), + countActiveKeys: db.prepare<string, { c: number }>( + `SELECT COUNT(*) AS c FROM api_keys WHERE account_id = ? AND active = 1` + ), + insertMagicLink: db.prepare( + `INSERT INTO magic_links (id, account_id, token, expires_at, used, created_at) + VALUES (?, ?, ?, ?, 0, ?)` + ), + magicLinkByToken: db.prepare< + string, + { id: string; account_id: string; expires_at: number; used: number } + >( + `SELECT id, account_id, expires_at, used FROM magic_links WHERE token = ?` + ), + markMagicLinkUsed: db.prepare( + `UPDATE magic_links SET used = 1 WHERE id = ?` + ), + insertUsageEvent: db.prepare( + `INSERT INTO usage_events (id, api_key_id, dataset, timestamp) + VALUES (?, ?, ?, ?)` + ), + usageCountSince: db.prepare<[string, number], { c: number }>( + `SELECT COUNT(*) AS c FROM usage_events e + JOIN api_keys k ON k.id = e.api_key_id + WHERE k.account_id = ? AND e.timestamp >= ?` + ), + usageByDataset: db.prepare< + [string, number], + { dataset: string; c: number } + >( + `SELECT e.dataset AS dataset, COUNT(*) AS c + FROM usage_events e + JOIN api_keys k ON k.id = e.api_key_id + WHERE k.account_id = ? AND e.timestamp >= ? + GROUP BY e.dataset + ORDER BY c DESC` + ), + usageByKey: db.prepare< + [number, string], + { key_id: string; name: string; c: number } + >( + `SELECT k.id AS key_id, k.name AS name, COUNT(e.id) AS c + FROM api_keys k + LEFT JOIN usage_events e + ON e.api_key_id = k.id AND e.timestamp >= ? + WHERE k.account_id = ? + GROUP BY k.id + ORDER BY c DESC` + ) +}; + +export const queries = stmts; diff --git a/web/ui/src/lib/server/keys.ts b/web/ui/src/lib/server/keys.ts new file mode 100644 index 0000000..350839b --- /dev/null +++ b/web/ui/src/lib/server/keys.ts @@ -0,0 +1,79 @@ +import { createHash, randomBytes } from 'node:crypto'; + +import { queries, newId, now, rowToKey, type ApiKey } from './db'; +import { normalizeScopes } from '$lib/keys'; + +const ALPHABET = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + +/** + * Generate a new API key string (not yet persisted). + * Format: "ti_" + 32 random alphanumeric characters. + */ +export function mintKey(): { key: string; hash: string; prefix: string } { + const bytes = randomBytes(32); + let random = ''; + for (let i = 0; i < 32; i++) { + random += ALPHABET[bytes[i] % ALPHABET.length]; + } + const key = `ti_${random}`; + const hash = createHash('sha256').update(key).digest('hex'); + const prefix = key.slice(0, 8); // "ti_" + 5 chars + return { key, hash, prefix }; +} + +// -------- persistence -------- + +export interface CreateKeyInput { + accountId: string; + name: string; + scopes: string[]; +} + +export interface CreatedKey extends ApiKey { + /** The full plaintext key. Only returned on creation — never stored. */ + plaintext: string; +} + +export function createKey(input: CreateKeyInput): CreatedKey { + const { key, hash, prefix } = mintKey(); + const id = newId(); + const ts = now(); + const name = input.name.trim() || 'Untitled key'; + const scopes = normalizeScopes(input.scopes); + queries.insertKey.run( + id, + input.accountId, + hash, + prefix, + name, + JSON.stringify(scopes), + ts + ); + return { + id, + account_id: input.accountId, + key_prefix: prefix, + name, + scopes, + active: true, + created_at: ts, + last_used_at: null, + plaintext: key + }; +} + +export function listKeys(accountId: string): ApiKey[] { + return queries.keysForAccount.all(accountId).map(rowToKey); +} + +export function revokeKey(accountId: string, keyId: string): boolean { + const row = queries.keyById.get(keyId, accountId); + if (!row) return false; + queries.revokeKey.run(keyId, accountId); + return true; +} + +export function countActiveKeys(accountId: string): number { + return queries.countActiveKeys.get(accountId)?.c ?? 0; +} diff --git a/web/ui/src/lib/server/usage.ts b/web/ui/src/lib/server/usage.ts new file mode 100644 index 0000000..721cc3c --- /dev/null +++ b/web/ui/src/lib/server/usage.ts @@ -0,0 +1,33 @@ +import { queries } from './db'; + +export function startOfCurrentMonth(): number { + const d = new Date(); + d.setUTCDate(1); + d.setUTCHours(0, 0, 0, 0); + return d.getTime(); +} + +export function usageCountThisMonth(accountId: string): number { + return queries.usageCountSince.get(accountId, startOfCurrentMonth())?.c ?? 0; +} + +export function usageByDataset( + accountId: string +): Array<{ dataset: string; count: number }> { + const rows = queries.usageByDataset.all(accountId, startOfCurrentMonth()); + return rows.map((r: { dataset: string; c: number }) => ({ + dataset: r.dataset, + count: r.c + })); +} + +export function usageByKey( + accountId: string +): Array<{ keyId: string; name: string; count: number }> { + const rows = queries.usageByKey.all(startOfCurrentMonth(), accountId); + return rows.map((r: { key_id: string; name: string; c: number }) => ({ + keyId: r.key_id, + name: r.name, + count: r.c + })); +} diff --git a/web/ui/src/lib/stores/toasts.ts b/web/ui/src/lib/stores/toasts.ts new file mode 100644 index 0000000..27dd8c4 --- /dev/null +++ b/web/ui/src/lib/stores/toasts.ts @@ -0,0 +1,21 @@ +import { writable } from 'svelte/store'; + +export type ToastKind = 'info' | 'success' | 'error'; + +export interface Toast { + id: number; + kind: ToastKind; + message: string; +} + +let nextId = 1; + +export const toasts = writable<Toast[]>([]); + +export function pushToast(message: string, kind: ToastKind = 'info'): void { + const id = nextId++; + toasts.update((list) => [...list, { id, kind, message }]); + setTimeout(() => { + toasts.update((list) => list.filter((t) => t.id !== id)); + }, 2500); +} diff --git a/web/ui/src/routes/+layout.server.ts b/web/ui/src/routes/+layout.server.ts new file mode 100644 index 0000000..37c08a0 --- /dev/null +++ b/web/ui/src/routes/+layout.server.ts @@ -0,0 +1,7 @@ +import type { LayoutServerLoad } from './$types'; + +export const load: LayoutServerLoad = async ({ locals }) => { + return { + account: locals.account + }; +}; diff --git a/web/ui/src/routes/+layout.svelte b/web/ui/src/routes/+layout.svelte new file mode 100644 index 0000000..ddd7c4c --- /dev/null +++ b/web/ui/src/routes/+layout.svelte @@ -0,0 +1,9 @@ +<script lang="ts"> + import '../app.css'; + import Toasts from '$lib/components/Toasts.svelte'; + + let { children } = $props(); +</script> + +<Toasts /> +{@render children()} diff --git a/web/ui/src/routes/+page.server.ts b/web/ui/src/routes/+page.server.ts new file mode 100644 index 0000000..2daf03d --- /dev/null +++ b/web/ui/src/routes/+page.server.ts @@ -0,0 +1,20 @@ +import { redirect } from '@sveltejs/kit'; + +import { createAnonymousAccount, createSession } from '$lib/server/auth'; +import type { PageServerLoad } from './$types'; + +/** + * The root route is just a bouncer: if you already have a session, + * go to the dashboard; if not, we mint an anonymous account on the + * spot, set a session cookie, and go to the dashboard. + * + * There is intentionally no sign-in page. Users can add an email on + * the Account tab later if they want a way to recover their keys. + */ +export const load: PageServerLoad = async ({ locals, cookies }) => { + if (!locals.account) { + const account = createAnonymousAccount(); + createSession(cookies, account.id); + } + throw redirect(303, '/dashboard'); +}; diff --git a/web/ui/src/routes/auth/callback/+server.ts b/web/ui/src/routes/auth/callback/+server.ts new file mode 100644 index 0000000..da8181b --- /dev/null +++ b/web/ui/src/routes/auth/callback/+server.ts @@ -0,0 +1,14 @@ +import { redirect, type RequestHandler } from '@sveltejs/kit'; + +import { consumeMagicLink, createSession } from '$lib/server/auth'; + +export const GET: RequestHandler = async ({ url, cookies }) => { + const token = url.searchParams.get('token'); + if (!token) throw redirect(303, '/?error=missing-token'); + + const account = consumeMagicLink(token); + if (!account) throw redirect(303, '/?error=invalid-token'); + + createSession(cookies, account.id); + throw redirect(303, '/dashboard'); +}; diff --git a/web/ui/src/routes/auth/logout/+server.ts b/web/ui/src/routes/auth/logout/+server.ts new file mode 100644 index 0000000..b17d1d5 --- /dev/null +++ b/web/ui/src/routes/auth/logout/+server.ts @@ -0,0 +1,13 @@ +import { redirect, type RequestHandler } from '@sveltejs/kit'; + +import { clearSession } from '$lib/server/auth'; + +export const POST: RequestHandler = async ({ cookies }) => { + clearSession(cookies); + throw redirect(303, '/'); +}; + +export const GET: RequestHandler = async ({ cookies }) => { + clearSession(cookies); + throw redirect(303, '/'); +}; diff --git a/web/ui/src/routes/dashboard/+layout.server.ts b/web/ui/src/routes/dashboard/+layout.server.ts new file mode 100644 index 0000000..8eebc76 --- /dev/null +++ b/web/ui/src/routes/dashboard/+layout.server.ts @@ -0,0 +1,12 @@ +import { redirect } from '@sveltejs/kit'; + +import type { LayoutServerLoad } from './$types'; + +export const load: LayoutServerLoad = async ({ locals }) => { + if (!locals.account) { + throw redirect(303, '/'); + } + return { + account: locals.account + }; +}; diff --git a/web/ui/src/routes/dashboard/+layout.svelte b/web/ui/src/routes/dashboard/+layout.svelte new file mode 100644 index 0000000..9137c75 --- /dev/null +++ b/web/ui/src/routes/dashboard/+layout.svelte @@ -0,0 +1,90 @@ +<script lang="ts"> + import { page } from '$app/stores'; + import BrandMark from '$lib/components/BrandMark.svelte'; + import Footer from '$lib/components/Footer.svelte'; + import { PLANS } from '$lib/plans'; + + let { data, children } = $props(); + + const tabs = [ + { id: '01', slug: 'keys', label: 'Keys' }, + { id: '02', slug: 'usage', label: 'Usage' }, + { id: '03', slug: 'account', label: 'Account' } + ]; + + let currentPath = $derived($page.url.pathname); + let account = $derived(data.account); + let planInfo = $derived(account ? PLANS[account.plan] : PLANS.free); +</script> + +<svelte:head> + <title>Tidy Index — Dashboard</title> +</svelte:head> + +<header class="app-header"> + <div class="container app-header-inner"> + <a href="/dashboard/keys" class="brand" aria-label="Tidy Index dashboard home"> + <BrandMark /> + <span>Tidy Index</span> + </a> + + <div class="app-header-meta"> + <span class="plan-chip"> + plan: <strong>{planInfo.name.toLowerCase()}</strong> + </span> + {#if account?.email} + <span title={account.email}>{account.email}</span> + {:else if account?.pending_email} + <span class="pending-chip" title="Sign-in link sent — awaiting verification"> + pending · {account.pending_email} + </span> + {:else} + <span class="text-mute">anonymous</span> + {/if} + </div> + </div> +</header> + +<div class="container"> + {#if !account?.email && !account?.pending_email} + <div class="banner"> + <span> + You're using an anonymous session. + <strong>Sign in with an email so you don't lose access to your keys.</strong> + </span> + <a href="/dashboard/account?focus=email" class="btn btn-sm btn-ghost">Sign in</a> + </div> + {:else if account?.pending_email && !account?.email} + <div class="banner"> + <span> + We sent a sign-in link to <strong>{account.pending_email}</strong>. + Check your inbox to finish signing in. + </span> + <a href="/dashboard/account" class="btn btn-sm btn-ghost">Manage</a> + </div> + {/if} + + <nav class="tabs" aria-label="Dashboard sections"> + <div class="tabs-inner"> + {#each tabs as tab} + {@const active = currentPath.startsWith(`/dashboard/${tab.slug}`)} + <a + href="/dashboard/{tab.slug}" + class="tab {active ? 'active' : ''}" + aria-current={active ? 'page' : undefined} + > + <span class="tab-num">§ {tab.id}</span> + <span>{tab.label}</span> + </a> + {/each} + </div> + </nav> +</div> + +<main class="app-main"> + <div class="container"> + {@render children()} + </div> +</main> + +<Footer /> diff --git a/web/ui/src/routes/dashboard/+page.server.ts b/web/ui/src/routes/dashboard/+page.server.ts new file mode 100644 index 0000000..32e2307 --- /dev/null +++ b/web/ui/src/routes/dashboard/+page.server.ts @@ -0,0 +1,7 @@ +import { redirect } from '@sveltejs/kit'; + +import type { PageServerLoad } from './$types'; + +export const load: PageServerLoad = async () => { + throw redirect(303, '/dashboard/keys'); +}; diff --git a/web/ui/src/routes/dashboard/account/+page.server.ts b/web/ui/src/routes/dashboard/account/+page.server.ts new file mode 100644 index 0000000..5581b52 --- /dev/null +++ b/web/ui/src/routes/dashboard/account/+page.server.ts @@ -0,0 +1,107 @@ +import { fail, redirect, type Actions } from '@sveltejs/kit'; + +import { queries } from '$lib/server/db'; +import { + attachEmailToAccount, + clearSession, + createSession +} from '$lib/server/auth'; +import { PLANS, PLAN_ORDER, type PlanId } from '$lib/plans'; +import type { PageServerLoad } from './$types'; + +export const load: PageServerLoad = async ({ locals }) => { + const account = locals.account!; + const keys = queries.keysForAccount.all(account.id); + return { + account, + keyCount: keys.length, + plans: PLAN_ORDER.map((id) => PLANS[id]), + currentPlan: account.plan + }; +}; + +export const actions: Actions = { + /** + * Anonymous → pending. The user has typed an email; we save it as + * pending_email and (eventually) send a magic link. Email sending is + * not wired up yet — the UI just transitions to the pending state. + */ + requestSignInLink: async ({ request, locals }) => { + const account = locals.account!; + const form = await request.formData(); + const email = ((form.get('email') ?? '') as string).trim().toLowerCase(); + + if (!email || !email.includes('@') || email.length > 254) { + return fail(400, { error: 'Enter a valid email address.' }); + } + + queries.setPendingEmail.run(email, account.id); + return { linkSent: true, email }; + }, + + /** Pending → anonymous. User abandons the verification. */ + cancelPendingSignIn: async ({ locals }) => { + const account = locals.account!; + queries.clearPendingEmail.run(account.id); + return { cancelled: true }; + }, + + /** + * Pending → signed in. Dev-only shortcut so the signed-in UI is + * reachable without a working magic-link verification flow. Will be + * removed once /auth/callback promotes pending_email itself. + * + * Goes through attachEmailToAccount so we get the same conflict + * handling as real verification: if another account already owns the + * email, current account merges into it (keys move over, current is + * deleted, session cookie reissued). + */ + markVerified: async ({ locals, cookies }) => { + const account = locals.account!; + if (!account.pending_email) { + return fail(400, { error: 'No pending email to verify.' }); + } + try { + const result = attachEmailToAccount(account.id, account.pending_email); + if (result.accountId === account.id) { + // Email attached cleanly to this account — clear pending state. + queries.clearPendingEmail.run(account.id); + } else { + // Merged into a pre-existing account that already owned this + // email. The current account is gone; reissue the cookie so + // subsequent requests load the surviving account. + createSession(cookies, result.accountId); + } + return { verified: true, merged: result.accountId !== account.id }; + } catch (e) { + return fail(400, { + error: e instanceof Error ? e.message : 'Could not verify.' + }); + } + }, + + switchPlan: async ({ request, locals }) => { + const account = locals.account!; + const form = await request.formData(); + const planId = ((form.get('plan') ?? '') as string) as PlanId; + + if (!PLAN_ORDER.includes(planId)) { + return fail(400, { error: 'Unknown plan' }); + } + if (planId === 'enterprise') { + return fail(400, { + error: 'Enterprise is contact-only. Email contact@tidyindex.com.' + }); + } + + queries.updateAccountPlan.run(planId, account.id); + return { switchedTo: planId }; + }, + + deleteAccount: async ({ locals, cookies }) => { + const account = locals.account!; + queries.deleteAccount.run(account.id); + clearSession(cookies); + throw redirect(303, '/'); + } +}; diff --git a/web/ui/src/routes/dashboard/account/+page.svelte b/web/ui/src/routes/dashboard/account/+page.svelte new file mode 100644 index 0000000..287c210 --- /dev/null +++ b/web/ui/src/routes/dashboard/account/+page.svelte @@ -0,0 +1,238 @@ +<script lang="ts"> + import { tick } from 'svelte'; + import { enhance } from '$app/forms'; + import { afterNavigate, invalidateAll } from '$app/navigation'; + import { pushToast } from '$lib/stores/toasts'; + import { PLANS } from '$lib/plans'; + import type { PageData, ActionData } from './$types'; + + let { data, form }: { data: PageData; form: ActionData } = $props(); + + let confirmDelete = $state(false); + + // When arriving via "Sign in" (which links to .../account?focus=email), + // drop the cursor straight into the email field. preventScroll keeps the + // page from jumping when focus() is called. + afterNavigate(async (nav) => { + if (nav.to?.url.searchParams.get('focus') !== 'email') return; + await tick(); + document.getElementById('email')?.focus({ preventScroll: true }); + }); + + $effect(() => { + if (!form) return; + if ('linkSent' in form && form.linkSent) { + pushToast(`Sign-in link sent to ${form.email}`, 'success'); + invalidateAll(); + } else if ('cancelled' in form && form.cancelled) { + pushToast('Sign-in cancelled', 'success'); + invalidateAll(); + } else if ('verified' in form && form.verified) { + pushToast('Signed in', 'success'); + invalidateAll(); + } else if ('switchedTo' in form && form.switchedTo) { + pushToast(`Switched to ${PLANS[form.switchedTo].name}`, 'success'); + invalidateAll(); + } else if ('error' in form && form.error) { + pushToast(form.error, 'error'); + } + }); +</script> + +<p class="section-marker">§ 03 · account</p> +<h1 class="page-title">Account.</h1> +<p class="page-subtitle"> + {#if data.account.email} + Manage your sign-in and review what we know about you. + {:else if data.account.pending_email} + Finish signing in to lock your keys to this email. + {:else} + Sign in with email so your keys follow you across browsers. + {/if} +</p> + +<div class="card"> + <div class="card-head"> + <h2 class="card-title">Sign in</h2> + </div> + + {#if data.account.email} + <!-- Signed in --> + <p class="card-sub"> + Signed in as <strong>{data.account.email}</strong>. + </p> + <form method="POST" action="/auth/logout" class="mt-16"> + <button type="submit" class="btn btn-ghost btn-sm">Sign out</button> + </form> + {:else if data.account.pending_email} + <!-- Pending verification --> + <p class="card-sub"> + We sent a sign-in link to + <strong>{data.account.pending_email}</strong>. Click it from your inbox + to finish signing in. + </p> + <div class="row mt-16"> + <form method="POST" action="?/requestSignInLink" use:enhance> + <input type="hidden" name="email" value={data.account.pending_email} /> + <button type="submit" class="btn btn-ghost btn-sm">Resend link</button> + </form> + <form method="POST" action="?/cancelPendingSignIn" use:enhance> + <button type="submit" class="btn btn-ghost btn-sm">Cancel</button> + </form> + <form method="POST" action="?/markVerified" use:enhance> + <button type="submit" class="btn btn-accent btn-sm" title="Dev shortcut: skips real verification"> + (dev) Mark verified + </button> + </form> + </div> + {:else} + <!-- Anonymous --> + <p class="card-sub"> + You're using an anonymous session. Sign in with an email so you don't + lose access to your keys if you clear cookies or switch browsers. + </p> + <form method="POST" action="?/requestSignInLink" use:enhance class="mt-16"> + <div class="field"> + <label class="field-label" for="email">email address</label> + <input + id="email" + name="email" + type="email" + class="input" + placeholder="you@company.com" + required + /> + </div> + <button type="submit" class="btn btn-accent btn-sm"> + Send sign-in link + </button> + </form> + {/if} +</div> + +<div class="card mt-24"> + <div class="card-head"> + <h2 class="card-title">Plan</h2> + </div> + <p class="card-sub"> + Usage resets on the first of every month. You can change plans any time, and + we prorate mid-cycle. (Billing is stubbed in this demo — switching plans just + updates the dashboard.) + </p> + + <div class="plan-grid mt-16"> + {#each data.plans as plan} + {@const isCurrent = plan.id === data.currentPlan} + <div class="plan-card {isCurrent ? 'current' : ''}"> + {#if isCurrent} + <span class="badge">Current</span> + {/if} + + <p class="plan-name">{plan.name}</p> + <p class="plan-price"> + {plan.priceLabel} + {#if plan.period}<small> {plan.period}</small>{/if} + </p> + + <ul class="plan-features"> + {#each plan.features as f} + <li>{f}</li> + {/each} + </ul> + + <div class="plan-cta"> + {#if plan.id === 'enterprise'} + <a + href="mailto:contact@tidyindex.com?subject=Enterprise%20inquiry" + class="btn btn-ghost" + style="width: 100%;" + > + Contact us + </a> + {:else if isCurrent} + <button class="btn btn-ghost" style="width: 100%;" disabled> + Current plan + </button> + {:else} + <form method="POST" action="?/switchPlan" use:enhance> + <input type="hidden" name="plan" value={plan.id} /> + <button + class="btn {plan.id === 'pro' ? 'btn-accent' : 'btn-ghost'}" + style="width: 100%;" + type="submit" + > + {plan.cta} + </button> + </form> + {/if} + </div> + </div> + {/each} + </div> + + <p class="help mt-24"> + Need something not listed here — custom datasets, on-prem deployment, higher + rate limits? Reply to any email from us, or reach out at + <a href="mailto:contact@tidyindex.com">contact@tidyindex.com</a>. + </p> +</div> + +<div class="card mt-24"> + <div class="card-head"> + <h2 class="card-title">What we know about you</h2> + </div> + <dl class="usage-table" style="display:block;"> + <div class="row-between" style="padding:10px 0; border-bottom:1px solid var(--c-rule);"> + <dt class="text-mono text-mute">account id</dt> + <dd class="text-mono" style="margin:0;">{data.account.id}</dd> + </div> + <div class="row-between" style="padding:10px 0; border-bottom:1px solid var(--c-rule);"> + <dt class="text-mono text-mute">plan</dt> + <dd class="text-mono" style="margin:0;">{data.account.plan}</dd> + </div> + <div class="row-between" style="padding:10px 0; border-bottom:1px solid var(--c-rule);"> + <dt class="text-mono text-mute">created</dt> + <dd class="text-mono" style="margin:0;"> + {new Date(data.account.created_at).toLocaleDateString('en-US', { + month: 'short', + day: 'numeric', + year: 'numeric' + })} + </dd> + </div> + <div class="row-between" style="padding:10px 0;"> + <dt class="text-mono text-mute">keys on file</dt> + <dd class="text-mono" style="margin:0;">{data.keyCount}</dd> + </div> + </dl> +</div> + +<div class="danger-zone"> + <p class="danger-zone-title">Danger zone</p> + <p class="danger-zone-body"> + Deleting your account will revoke every key and permanently erase your + usage history. This cannot be undone. + </p> + {#if confirmDelete} + <div class="row"> + <form method="POST" action="?/deleteAccount" use:enhance> + <button type="submit" class="btn btn-danger btn-sm"> + Yes, delete everything + </button> + </form> + <button + class="btn btn-ghost btn-sm" + onclick={() => (confirmDelete = false)} + > + Cancel + </button> + </div> + {:else} + <button + class="btn btn-danger btn-sm" + onclick={() => (confirmDelete = true)} + > + Delete account + </button> + {/if} +</div> diff --git a/web/ui/src/routes/dashboard/keys/+page.server.ts b/web/ui/src/routes/dashboard/keys/+page.server.ts new file mode 100644 index 0000000..5491283 --- /dev/null +++ b/web/ui/src/routes/dashboard/keys/+page.server.ts @@ -0,0 +1,68 @@ +import { fail, type Actions } from '@sveltejs/kit'; + +import { + createKey, + listKeys, + revokeKey, + countActiveKeys +} from '$lib/server/keys'; +import { PLANS } from '$lib/plans'; +import type { PageServerLoad } from './$types'; + +export const load: PageServerLoad = async ({ locals }) => { + const account = locals.account!; + const keys = listKeys(account.id); + return { + keys, + activeCount: countActiveKeys(account.id), + plan: PLANS[account.plan] + }; +}; + +export const actions: Actions = { + create: async ({ request, locals }) => { + const account = locals.account!; + const form = await request.formData(); + const name = ((form.get('name') ?? '') as string).trim(); + const scopes = form.getAll('scopes').map((s) => s.toString()); + + if (!name) { + return fail(400, { error: 'Give the key a name so you can recognize it later.' }); + } + + const plan = PLANS[account.plan]; + const active = countActiveKeys(account.id); + if (Number.isFinite(plan.maxKeys) && active >= plan.maxKeys) { + return fail(403, { + error: `Your ${plan.name} plan allows ${plan.maxKeys} active key${ + plan.maxKeys === 1 ? '' : 's' + }. Revoke one or upgrade your plan first.` + }); + } + + const created = createKey({ + accountId: account.id, + name, + scopes + }); + + return { + created: { + id: created.id, + plaintext: created.plaintext, + name: created.name + } + }; + }, + + revoke: async ({ request, locals }) => { + const account = locals.account!; + const form = await request.formData(); + const id = (form.get('id') ?? '').toString(); + if (!id) return fail(400, { error: 'Missing key id.' }); + + const ok = revokeKey(account.id, id); + if (!ok) return fail(404, { error: 'Key not found.' }); + return { revokedId: id }; + } +}; diff --git a/web/ui/src/routes/dashboard/keys/+page.svelte b/web/ui/src/routes/dashboard/keys/+page.svelte new file mode 100644 index 0000000..b0a066f --- /dev/null +++ b/web/ui/src/routes/dashboard/keys/+page.svelte @@ -0,0 +1,220 @@ +<script lang="ts"> + import { enhance } from '$app/forms'; + import { DATASETS } from '$lib/datasets'; + import { maskKey, scopeSummary } from '$lib/keys'; + import { pushToast } from '$lib/stores/toasts'; + import type { PageData, ActionData } from './$types'; + + let { data, form }: { data: PageData; form: ActionData } = $props(); + + let showCreate = $state(false); + let name = $state(''); + let selected = $state<Set<string>>(new Set()); + let allScopes = $state(true); + + function toggleChip(slug: string) { + if (allScopes) { + allScopes = false; + selected = new Set([slug]); + return; + } + const next = new Set(selected); + if (next.has(slug)) next.delete(slug); + else next.add(slug); + if (next.size === 0) { + allScopes = true; + selected = new Set(); + } else { + selected = next; + } + } + + function selectAll() { + allScopes = true; + selected = new Set(); + } + + function fmtDate(ts: number): string { + return new Date(ts).toLocaleDateString('en-US', { + month: 'short', + day: 'numeric', + year: 'numeric' + }); + } + + async function copy(text: string) { + try { + await navigator.clipboard.writeText(text); + pushToast('Copied to clipboard', 'success'); + } catch { + pushToast("Couldn't copy — select it manually", 'error'); + } + } + + // When a new key is returned in `form`, show toast + scroll to top. + $effect(() => { + if (form && 'created' in form && form.created) { + pushToast(`Key "${form.created.name}" created`, 'success'); + showCreate = false; + name = ''; + selected = new Set(); + allScopes = true; + } else if (form && 'revokedId' in form && form.revokedId) { + pushToast('Key revoked', 'success'); + } else if (form && 'error' in form && form.error) { + pushToast(form.error, 'error'); + } + }); +</script> + +<p class="section-marker">§ 01 · api keys</p> +<div class="row-between mb-24"> + <div> + <h1 class="page-title">Your API keys.</h1> + <p class="page-subtitle"> + {data.activeCount} active, {data.keys.length - data.activeCount} revoked. Your + {data.plan.name} plan allows + {Number.isFinite(data.plan.maxKeys) ? data.plan.maxKeys : 'unlimited'} + active key{data.plan.maxKeys === 1 ? '' : 's'}. + </p> + </div> + {#if !showCreate} + <button class="btn btn-primary" onclick={() => (showCreate = true)}> + + New key + </button> + {/if} +</div> + +{#if form && 'created' in form && form.created} + <div class="key-reveal"> + <div class="key-reveal-head"> + <span class="badge">New key</span> + <strong>Copy this key now — it won't be shown again.</strong> + </div> + <div class="key-reveal-value"> + <span style="flex: 1;">{form.created.plaintext}</span> + <button class="btn btn-sm btn-ghost" onclick={() => copy(form.created!.plaintext)}> + Copy + </button> + </div> + <p class="key-reveal-warn"> + Store it somewhere safe. Once you leave this page we only keep the hash. + </p> + </div> +{/if} + +{#if showCreate} + <form + method="POST" + action="?/create" + class="card card-accent mb-24" + use:enhance + > + <div class="card-head"> + <h2 class="card-title">New key</h2> + <button type="button" class="btn btn-sm btn-ghost" onclick={() => (showCreate = false)}> + Cancel + </button> + </div> + + <div class="field"> + <label class="field-label" for="name">name</label> + <input + id="name" + name="name" + class="input" + placeholder="e.g. production ingest" + bind:value={name} + required + /> + <p class="help">Just for you — how you'll recognize this key in the list.</p> + </div> + + <div class="field"> + <span class="field-label">dataset scope</span> + <div class="chip-grid"> + <button + type="button" + class="chip chip-all {allScopes ? 'active' : ''}" + onclick={selectAll} + > + all datasets + </button> + {#each DATASETS as slug} + <button + type="button" + class="chip {selected.has(slug) ? 'active' : ''}" + onclick={() => toggleChip(slug)} + > + {slug} + </button> + {/each} + </div> + <p class="help"> + {#if allScopes} + This key will work against every dataset in the catalog. + {:else} + This key will only work against the {selected.size} selected dataset{selected.size === 1 ? '' : 's'}. + {/if} + </p> + </div> + + {#if allScopes} + <input type="hidden" name="scopes" value="*" /> + {:else} + {#each [...selected] as slug} + <input type="hidden" name="scopes" value={slug} /> + {/each} + {/if} + + <div class="row mt-16"> + <button type="submit" class="btn btn-accent">Create key</button> + <button type="button" class="btn btn-ghost" onclick={() => (showCreate = false)}> + Cancel + </button> + </div> + </form> +{/if} + +{#if data.keys.length === 0} + <div class="empty-state"> + <p class="empty-title">No keys yet.</p> + <p>Click "+ New key" to create your first one.</p> + </div> +{:else} + {#each data.keys as key (key.id)} + <div class="card"> + <div class="key-row"> + <div class="key-row-main"> + <div class="key-name"> + {key.name} + {#if key.active} + <span class="badge badge-success">Active</span> + {:else} + <span class="badge badge-muted">Revoked</span> + {/if} + </div> + <div class="key-mask">{maskKey(key.key_prefix)}</div> + <div class="scope-summary"> + scope: <code>{scopeSummary(key.scopes)}</code> + </div> + <div class="key-meta"> + <span><span class="meta-label">created</span> {fmtDate(key.created_at)}</span> + {#if key.last_used_at} + <span><span class="meta-label">last used</span> {fmtDate(key.last_used_at)}</span> + {:else} + <span><span class="meta-label">last used</span> never</span> + {/if} + </div> + </div> + + {#if key.active} + <form method="POST" action="?/revoke" use:enhance> + <input type="hidden" name="id" value={key.id} /> + <button class="btn btn-sm btn-danger" type="submit">Revoke</button> + </form> + {/if} + </div> + </div> + {/each} +{/if} diff --git a/web/ui/src/routes/dashboard/usage/+page.server.ts b/web/ui/src/routes/dashboard/usage/+page.server.ts new file mode 100644 index 0000000..34ff002 --- /dev/null +++ b/web/ui/src/routes/dashboard/usage/+page.server.ts @@ -0,0 +1,13 @@ +import { PLANS } from '$lib/plans'; +import { usageByDataset, usageByKey, usageCountThisMonth } from '$lib/server/usage'; +import type { PageServerLoad } from './$types'; + +export const load: PageServerLoad = async ({ locals }) => { + const account = locals.account!; + return { + plan: PLANS[account.plan], + total: usageCountThisMonth(account.id), + byDataset: usageByDataset(account.id), + byKey: usageByKey(account.id) + }; +}; diff --git a/web/ui/src/routes/dashboard/usage/+page.svelte b/web/ui/src/routes/dashboard/usage/+page.svelte new file mode 100644 index 0000000..883460c --- /dev/null +++ b/web/ui/src/routes/dashboard/usage/+page.svelte @@ -0,0 +1,152 @@ +<script lang="ts"> + import { pushToast } from '$lib/stores/toasts'; + import type { PageData } from './$types'; + + let { data }: { data: PageData } = $props(); + + const monthName = new Date().toLocaleDateString('en-US', { + month: 'long', + year: 'numeric' + }); + + function fmt(n: number): string { + return n.toLocaleString('en-US'); + } + + const curlExample = `curl https://api.tidyindex.com/v1/datasets/irs-990/records/20-0049703 \\ + -H "Authorization: Bearer YOUR_API_KEY"`; + + async function copyCurl() { + try { + await navigator.clipboard.writeText(curlExample); + pushToast('Copied', 'success'); + } catch { + pushToast("Couldn't copy", 'error'); + } + } + + let pct = $derived.by(() => { + if (!Number.isFinite(data.plan.requestsPerMonth)) return 0; + const p = (data.total / data.plan.requestsPerMonth) * 100; + return Math.min(100, Math.max(0, p)); + }); + + let limitLabel = $derived( + Number.isFinite(data.plan.requestsPerMonth) + ? fmt(data.plan.requestsPerMonth) + : 'unlimited' + ); +</script> + +<p class="section-marker">§ 02 · usage</p> +<h1 class="page-title">This month.</h1> +<p class="page-subtitle"> + Requests counted against your plan limit for {monthName}. +</p> + +<div class="card"> + <div class="usage-summary"> + <div> + <p class="text-mono text-mute" style="margin:0 0 6px;"> + requests / {limitLabel} + </p> + <p class="usage-count"> + {fmt(data.total)} + {#if Number.isFinite(data.plan.requestsPerMonth)} + <small> of {limitLabel}</small> + {/if} + </p> + </div> + <div> + <span class="badge">{data.plan.name.toLowerCase()} plan</span> + </div> + </div> + {#if Number.isFinite(data.plan.requestsPerMonth)} + <div class="usage-bar" aria-label="Usage bar"> + <div class="usage-bar-fill" style="width: {pct}%"></div> + </div> + {/if} +</div> + +<div class="card mt-24"> + <div class="card-head"> + <h2 class="card-title">By dataset</h2> + <p class="card-sub">Which datasets drew the most traffic.</p> + </div> + {#if data.byDataset.length === 0} + <div class="empty-state"> + <p class="empty-title">No requests yet this month.</p> + <p>Usage data will show up here once your keys start making calls.</p> + </div> + {:else} + <table class="usage-table"> + <thead> + <tr> + <th>dataset</th> + <th style="text-align:right;">requests</th> + <th style="text-align:right; width: 140px;">share</th> + </tr> + </thead> + <tbody> + {#each data.byDataset as row} + <tr> + <td>{row.dataset}</td> + <td class="num">{fmt(row.count)}</td> + <td class="num"> + {data.total > 0 + ? ((row.count / data.total) * 100).toFixed(1) + : '0.0'}% + </td> + </tr> + {/each} + </tbody> + </table> + {/if} +</div> + +<div class="card mt-24"> + <div class="card-head"> + <h2 class="card-title">By key</h2> + <p class="card-sub">Traffic attributed to each of your keys.</p> + </div> + {#if data.byKey.length === 0} + <div class="empty-state"> + <p class="empty-title">No keys yet.</p> + <p>Create one on the Keys tab.</p> + </div> + {:else} + <table class="usage-table"> + <thead> + <tr> + <th>key</th> + <th style="text-align:right;">requests</th> + </tr> + </thead> + <tbody> + {#each data.byKey as row} + <tr> + <td>{row.name}</td> + <td class="num">{fmt(row.count)}</td> + </tr> + {/each} + </tbody> + </table> + {/if} +</div> + +<div class="card mt-24"> + <div class="card-head"> + <h2 class="card-title">API base URL</h2> + </div> + <p class="card-sub">All endpoints live under this host.</p> + <pre class="code-block mt-16">https://api.tidyindex.com/v1</pre> +</div> + +<div class="card mt-24"> + <div class="card-head"> + <h2 class="card-title">Quick start</h2> + <button class="btn btn-sm btn-ghost" onclick={copyCurl}>Copy curl</button> + </div> + <p class="card-sub">Fetch one record from the IRS 990 dataset.</p> + <pre class="code-block mt-16">{curlExample}</pre> +</div> |
