agnes-the-ai-analyst/app/web/templates/admin_tokens.html
ZdenekSrotyr 1b0329e8c5
UI design system unification — one stylesheet, canonical primitives, nav fix (#284)
* docs(plan): design-system unification plan (post-review revisions)

Plan covers consolidating two CSS files into one, introducing
canonical primitives (.btn family, .search-input, .filter-bar,
.page-header, .data-table, .empty-state, .toast, .stat-card,
.tab-strip), unifying the top-nav Admin trigger with sibling
links, and migrating 41 templates that today carry inline
<style> blocks.

Post-review revisions: nav fix moved to first commit (user
complaint lands first); sticky-header and dark-mode skeleton
tasks dropped (defer to follow-up PRs); contract test class
detection tokenizes class="..." attributes properly; baseline
screenshot loop added to Task 0; vendor-token grep widened.

* fix(nav): unify Admin trigger with sibling nav links

The top-nav Admin entry is a <button class="app-nav-link
app-nav-menu-trigger">, siblings are <a class="app-nav-link">.
.app-nav-menu-trigger used to override .app-nav-link with
"color: inherit; font: inherit", resetting font-size from 13px
back to body default and color from --text-secondary to body
color. Active state diverged too: .is-active on links used
--primary blue, [aria-expanded=true] on the button used
--border-light grey.

Fix: expand .app-nav-link so it covers <button>-element resets
(font-family: inherit, border: 0, background: transparent,
cursor: pointer, display: inline-flex for chevron alignment).
Add [aria-expanded="true"] as another active-state selector
so the dropdown's open state highlights identically to .is-active
on links. Delete the now-redundant .app-nav-menu-trigger rules
that stripped button chrome.

Extract the inline <script> from _app_header.html into a new
app/web/static/app.js (loaded by base.html only — base_login.html
has no nav). Sets up window.appUI.wireDropdown for both the user
menu and the Admin dropdown via DOMContentLoaded.

* style(css): consolidate style.css into style-custom.css + add cache-bust

One stylesheet for the whole web UI:
- style.css (1086 lines, legacy Google-inspired tokens + components)
  absorbed into style-custom.css under a labeled block, placed after
  the modern :root + body so style-custom's component rules continue
  to override the legacy ones (preserves the original cascade order
  that came from loading style.css first).
- style.css deleted; <link> dropped from base.html + base_login.html.
- static_url() now appends ?v=<mtime> to /static/<path>. Cheap
  per-request os.stat — auto-invalidates browser + proxy caches on
  redeploy without operator intervention. Mtime survives across
  uvicorn restarts as long as the file content is unchanged.

Legacy classes (.btn, .card, .login-*, .badge, .code-block, .flash,
.form-group, .username-box, .btn-copy, .auth-tabs, .divider, etc.)
still render — they live in style-custom.css now. Login pages,
error page, password setup, and the dashboard's Claude Code Setup
card all kept working in browser smoke.

* test(design): contract test for design-system invariants

7 structural invariants enforced from this commit onwards:
- style.css must stay deleted
- no template links style.css via static_url
- exactly one bare :root block in style-custom.css
- canonical primitives declared (.btn, .btn-primary, .search-input,
  .filter-bar, .page-header, .data-table, .empty-state, .toast, …)
- no deprecated class names in templates (.users-table, .gp-table,
  .marketplaces-table, .audit-table, .users-search, .marketplaces-search,
  .modal-btn, .btn-primary-v2, …)
- app.js loaded by base.html, NOT by base_login.html
- 3 helper-level unit tests for the class-attribute tokenizer
  (multi-line attrs, Jinja-conditional fragments, false-positive prose)

Two of the assertions intentionally start FAILING after this commit
(missing primitives + legacy class refs in 7 admin templates) and
will turn green as Tasks 4–7 add primitives and Tasks 8–15 migrate
the templates.

* feat(css): canonical button family + legacy token aliases

Adds at top of :root: legacy token aliases (--bg, --card-bg, --text,
--text-light, --secondary, --radius) pointing at modern equivalents.
Absorbed style.css rules referenced these names; without aliases
they fell back to 'unset'. Aliases live until Task 16 alongside
their absorbed rules.

Appends canonical .btn variants at end of file (last cascade):
  .btn-primary + .btn-primary-v2 + .modal-btn.primary (alias group)
  .btn-secondary + .btn-secondary-v2 + .modal-btn:not(.primary):not(.danger)
  .btn-ghost + .btn-ghost-v2
  .btn-danger + .modal-btn.danger
  .btn-lg
  .btn:disabled + .btn:focus-visible (focus ring via --focus-ring)

Existing absorbed .btn, .btn-primary, .btn-secondary, .btn-sm rules
remain — the canonical block adds the missing variants + selector-list
aliases so .modal-btn and v2 markup keep rendering until migration
tasks swap them out.

Contract test: .btn-danger now declared (one less missing primitive).
Browser smoke: /admin/tokens hero + filter pills + empty state render
correctly with the absorbed style.css rules now backed by real tokens.

* feat(css): form-control primitives — .search-input + .filter-bar + .filter-pill + .form-input

Canonical filter bar shape: 36px-height inputs (matches button height
for vertical rhythm), 28px pills with .is-active state, consistent
focus ring via --focus-ring token.

Selector-list aliases for legacy per-page classes:
- .users-search / .marketplaces-search / .kb-search → .search-input
- .filters-card → .filter-bar
- .pill[aria-pressed="true"] also matches the .filter-pill active state

.form-input added as a sibling of .search-input for forms — same
baseline height + radius + focus treatment, with textarea.form-input
auto-sizing to min 96px and using the mono font (matches CSV/SQL
pasted-snippet patterns on /admin/agent-prompt + /admin/workspace-prompt).

Contract test: .search-input + .filter-bar + .filter-pill now declared.

* feat(css): .page-header primitive + variants + .tab-strip

Canonical page-header pattern with title (22px) + optional subtitle +
optional eyebrow + right-aligned actions slot. Two modifiers:
- .page-header--hero: gradient background (primary→primary-dark),
  28px white title, semi-transparent subtitle/eyebrow. For
  /marketplace, /store, /profile-style pages that already use this
  layout via per-page inline <style>. Migration tasks delete the
  duplicated rules.
- .page-header--compact: 18px title for dense admin index pages.

.tab-strip + .tab-strip__item — the secondary tab row pattern used by
/marketplace?tab=flea and similar. .is-active / [aria-selected=true]
both flip the active treatment (primary color + bottom border).

Contract test: .page-header / __title / __subtitle / __actions all
now declared (4 fewer missing primitives).

* feat(css+js): .data-table + .empty-state + .toast + .stat-card primitives

Last primitive batch. All 8 canonical-primitives invariants in
test_design_system_contract.py now green; only the template-migration
test fails (expected — Tasks 8–15).

.data-table (+ --compact modifier): selector-list aliases for legacy
per-page table classes (.users-table, .gp-table, .marketplaces-table,
.audit-table) so existing markup keeps rendering until migration.
Compact modifier shrinks padding + font for dense lists (audit log).

.empty-state with __icon / __title / __description / __actions —
replaces the ad-hoc 'no results' rendering scattered across pages
(corporate_memory, admin_users, admin_marketplaces, etc.).

.toast / .toast-container — paired with window.appToast({kind, msg,
timeout}) appended to app.js. Bottom-right stacked, click-to-dismiss,
auto-dismiss after 4s by default. Kind 'success' / 'warning' / 'error'
/ 'info' shows a 3px colored left border.

.stat-card (+ --accent variant) + .stat-row grid — for the dashboard
metric tile row.

* style(templates): migrate 8 templates off deprecated class names

Mechanical class-attribute rewrite via tokenizer (preserves Jinja
conditionals + multi-line attrs):

  modal-btn primary    -> btn btn-primary
  modal-btn danger     -> btn btn-danger
  modal-btn            -> btn btn-secondary
  users-table          -> data-table
  gp-table             -> data-table
  marketplaces-table   -> data-table
  audit-table          -> data-table
  users-search         -> search-input
  marketplaces-search  -> search-input

8 templates touched: admin_groups, admin_marketplaces, admin_tokens,
admin_users, admin_welcome, admin_workspace_prompt, my_tokens,
corporate_memory_admin. 43 lines updated total.

Inline <style> blocks in these templates still define rules for the
old class names — those rules no longer match anything and become
dead code, removed in Task 16's alias cleanup along with the
selector-list aliases in style-custom.css.

Contract test (tests/test_design_system_contract.py) now fully green:
9/9 invariants enforced from this commit onward.

* feat(css): extend .data-table selector list to 13 more bespoke -table classes

Visual unification of remaining tables across the codebase without
per-template edits. The .data-table baseline rules (uppercase header
tracking, 12px padding, hover state, border-radius) now apply to:

  .ad-table / .ea-table / .md-table / .members-table /
  .obs-table / .overview-stats-table / .registry-table /
  .sample-table / .sched-table / .sess-table / .sub-table /
  .subs-table / .ud-table

These class names live in 12 templates (activity_center, admin_access,
admin_group_detail, admin_scheduler_runs, admin_sessions,
admin_store_submissions, admin_tables, admin_usage, admin_user_detail,
catalog, me_debug, profile_sessions) that have their own per-page
<style> blocks. Per-page rules with higher specificity still win for
their custom needs (column widths, etc.) — this commit only sets a
shared baseline so every table renders with the same chrome.

Contract test stays green: 9/9 invariants enforced.

* style(css): remove now-unused legacy class aliases

Phase A renamed 8 templates off these names; no markup references
them any more, so the selector-list memberships are dead weight.
Removed from style-custom.css:

  .btn-primary-v2 / .btn-secondary-v2 / .btn-ghost-v2
  .modal-btn / .modal-btn.primary / .modal-btn.danger /
  .modal-btn:not(.primary):not(.danger)
  .users-search / .marketplaces-search / .kb-search
  .users-table / .gp-table / .marketplaces-table / .audit-table
  .filters-card

37 lines smaller. Contract test catches any reintroduction.

KEPT aliases (still in untouched template markup):
- .pill (marketplace_plugin_detail.html, marketplace.html — these
  pages weren't part of Phase A's deprecated-class sweep; their
  own .pill CSS rules still apply)
- All .data-table family extensions (.ad-table, .ea-table, .md-table,
  .members-table, .obs-table, .overview-stats-table, .registry-table,
  .sample-table, .sched-table, .sess-table, .sub-table, .subs-table,
  .ud-table) — these still render data tables in 12 templates;
  selector-list aliasing keeps them visually unified with .data-table
  baseline.
- Legacy token aliases (--bg / --text / --text-light / --secondary /
  --card-bg / --radius) — still resolve absorbed style.css rules.

Templates' inline <style> blocks still contain dead rules for the
renamed classes (.users-search, .modal-btn, etc.); harmless but
bloat. Optional follow-up: a separate sweep can drop those.

* docs(changelog): design-system unification under [Unreleased]

* feat(css): unify page-shell width — .container baseline 1280px + modifiers

Inventory found 30+ unique max-width values across templates (280px
login → 1600px admin/tables). The legacy .container default was 800px,
which made every admin page set its own wider inline override —
30+ ad-hoc widths drifted as a result.

Canonical: .container max-width = var(--width-app) (1280px). Pages
that need a different shape opt in via modifiers:

  .container--narrow → var(--width-narrow)  (800px) — long-form text,
                                                     setup wizards
  .container--wide   → var(--width-wide)    (1400px) — admin lists,
                                                     marketplace grids
  .container--full   → max-width: none — hero / landing

Pages that already set a NARROWER inline max-width (setup, login flows
inside .login-card, etc.) still render at their narrower size — the
inline override beats the new canonical 1280px. The visible change
hits the ~20 admin pages currently rendering at 800px via the legacy
default, which jump to 1280px and pick up consistent breathing room.

Spacing also normalized: padding 24px 20px → var(--space-6) var(--space-5).

* fix(home+catalog): gut dashboard sections + remove confusing toggle + fix table count

Dashboard /home cleanup:
- Remove 'Your Data' card — Data Packages is already a top-nav entry,
  so duplicating data sources on the landing page just adds noise.
- Remove 'Account' card — group memberships + scripts + last sync
  belong on /profile, not on the welcome screen.
- Remove entire right-column (Corporate Memory + Activity Center
  widgets) — both surfaces have dedicated admin pages reachable from
  the Admin dropdown.
- Keep stats row (Tables/Columns/Rows/Data Size/Unstructured),
  env-setup-CTA, and Notifications card.

/catalog cleanup:
- Strip the 'Always included' badge + the locked toggle-switch from
  Core Business Data and Business Metrics cards. The toggle was
  always 'checked disabled' — it visually looked like a switch but
  could not be toggled, which was confusing. The 'Always included'
  copy itself was redundant once the toggle was gone. Agnes Internal
  already rendered without these, so the three cards are now visually
  consistent.

Catalog data_stats fix:
- 'total_tables' was len(sync_state) — counted only tables that had
  ever synced, so a 30-row table_registry with 0 ever synced rendered
  as '0 tables'. Switched to len(tables) — the registered
  business-data table list — so the count reflects what's actually
  available, not what's been touched.

* fix(home): real stat numbers + drop unstructured tile + cleanup dead CSS

Dashboard stats were hardcoded zeros (columns: 0, size_display:
'0 MB', unstructured_display: '0 MB') and the table counter pulled
from sync_state (synced) instead of table_registry (registered).
On a fresh deployment with 30 registered tables and 0 ever synced,
the page rendered '0 / 0 / 0 / 0 MB / 0 MB' — useless.

Now:
- Tables: COUNT(*) FROM table_registry WHERE source_type != 'internal'.
  Matches the /catalog Core Business Data counter.
- Columns: SUM(sync_state.columns). Zero only when nothing's synced yet.
- Rows: unchanged (SUM(sync_state.rows), already correct).
- Data Size: SUM(sync_state.file_size_bytes), human-formatted via
  inline _fmt_bytes helper (KB/MB/GB).
- Unstructured: tile dropped — was always '0 MB' and had no source.
- last_updated: now derived from sync_state max(last_sync), wasn't set
  before so the 'Synced …' tag never rendered.

Dashboard.html cleanup: ~725 lines of orphan inline <style> removed —
.section-title, .data-source*, .toggle-switch*, .catalog-cta*,
.memory-card / .memory-stat / .memory-description / .memory-footer
/ .btn-memory, .activity-card / .activity-stat / .activity-text
/ .btn-activity, .account-grid / .account-row / .account-scripts
/ .badge-role / .badge-group / .cron-line, .badge-included /
.badge-beta / .badge-demo. All matched markup deleted in the
previous commit; the CSS was dead code until now.

* ui(catalog): rename page heading 'Data Catalog' → 'Data Packages'

The top-nav entry says 'Data Packages' but the page itself said
'Data Catalog' — confusing two-name product. Aligns the heading and
<title> with the nav label. Subtitle trimmed too: 'manage your
subscriptions' was a vestige of the toggle UI that just got removed,
replaced with a one-liner describing what the page is for.

Two other 'Data Catalog' strings stay: they live inside the table-
profiler overlay JS and refer to an EXTERNAL catalog system (e.g.
OpenMetadata / Atlan) that an operator may link to per table — that
is a generic term for any external data-catalog product, not our
page name.

* fix(nav): dropdown clicks always work + mutual-exclusion close

Two bugs in the wireDropdown helper:

1. Clicking trigger B while trigger A's menu was open left both open.
   e.stopPropagation() in trigger.click prevented the document-click
   handler from firing, so trigger A's open menu had no way to learn
   that something else was clicked. Net effect: state diverged across
   the two dropdowns the more you clicked.

2. The target-vs-trigger equality check (e.target !== trigger) was
   strict. Clicking the chevron <svg> inside the button reports the
   svg or its <path> child as e.target — not the button — so removing
   stopPropagation alone would trip the close branch in the same
   click that just opened the panel.

Fix both at once: drop e.stopPropagation() AND switch the doc-handler
guard to trigger.contains(e.target). Now any click outside both the
trigger subtree and the panel subtree closes; any click on another
trigger closes via the OTHER dropdown's doc handler; clicks inside
the trigger (button OR svg child) are fully ignored by the doc
handler and only the trigger's own toggle handler fires.

* feat(ui): canonical blue-gradient hero on every admin page

The UI had a per-page hero pattern on ~10 onboarding/marketing pages
(admin_tokens / profile / install / setup_advanced / marketplace /
my_tokens / store_upload / home_*), each with its own ad-hoc CSS
(.tokens-hero, .profile-hero, .install-hero, .upload-hero, …). The
admin section's index + detail pages had plain H1/H2 with their own
.users-title / .gp-title / .obs-title / .cfg-title / … inline styling.
Net effect: half the app felt like a product, half felt like a
spreadsheet.

Now:
- .page-header--hero CSS upgraded to match the look analysts already
  liked from admin_tokens: 28px/32px/24px padding, 14px radius, soft
  primary-tinted box-shadow (0 4px 16px rgba(0,115,209,0.2)), 28px
  semibold title, optional uppercase eyebrow + 13.5px subtitle.
  Narrow-viewport breakpoint included.
- New _page_hero.html partial wraps the boilerplate. Usage:
    {% set page_hero_eyebrow  = "Users & Access" %}
    {% set page_hero_title    = "Users" %}
    {% set page_hero_subtitle = "…" %}
    {% include "_page_hero.html" %}
- 15 admin templates migrated to it: admin_users / admin_groups /
  admin_marketplaces / admin_access / admin_sessions /
  admin_session_detail / admin_store_submissions /
  admin_scheduler_runs / admin_usage / admin_user_detail /
  admin_welcome / admin_workspace_prompt / admin_server_config /
  activity_center / admin/news_editor. Each gets a grouped eyebrow
  (Users & Access / Data / Agent Experience / Activity Center /
  Server) matching the Admin dropdown sections so the page identity
  is unambiguous at a glance.

Legacy *-title H2/H1 + adjacent subtitle paragraphs deleted; their
per-page CSS rules are dead now (harmless, retire in a follow-up
sweep alongside other inline-style cleanup the reviewers flagged).

admin_tables.html intentionally NOT migrated — it's a standalone
HTML page that doesn't extend base.html; a separate refactor.

Test: test_admin_users_page_renders_for_admin assertion updated
from .users-title to .page-header__title + .page-header--hero (the
canonical pair). All other web/template tests stay green.

* refactor(ui): dedup _humanbytes, drop 267 lines of dead inline CSS

(1) _humanbytes consolidation:
- Add TB branch + optional precision param (default 2 preserves existing
  Store detail callers; dashboard uses precision=1 for headline tiles).
- Delete inline _fmt_bytes from dashboard handler — was a copy of
  _humanbytes with different rounding. One canonical helper now.

(2) Dead inline-CSS sweep across 17 migrated templates:
- Conservative regex: a CSS rule is deleted only when its primary class
  matches one of the known-dead names AND that name is NOT referenced
  from any class= attribute in the same file's markup.
- Per-file 'in-use' guard saved several false positives that the deny
  list would have nuked (e.g. .users-toolbar, .gp-search, .obs-subtitle,
  .marketplaces-toolbar are still in use; only .users-table, .users-search,
  .users-title, .modal-btn, etc. that have NO markup left went away).
- Removed: -267 lines across admin_users (-42), admin_marketplaces (-45),
  admin_groups (-31), my_tokens (-38), admin_tokens (-29), admin_access
  (-9), admin_user_detail (-6), admin_welcome (-8), admin_workspace_prompt
  (-8), admin_server_config (-2), admin_sessions (-1), admin_session_detail
  (-1), admin_usage (-1), admin_store_submissions (-3), admin_scheduler_runs
  (-3), activity_center (-4), corporate_memory_admin (-36).

Contract test stays green (9/9); all web/template/render/user_management
tests pass.

* feat(ui): canonical hero on /catalog (Data Packages)

Same .page-header--hero treatment as the admin pages — Data eyebrow,
Data Packages title, Browse-the-data-sources subtitle. Removes the
ad-hoc .page-title block (h1 / p / wrapper-div) and its CSS rules
(now dead, 3 rule blocks deleted).

* fix(nav): load app.js from _app_header.html — works on standalone pages

The previous nav-fix commit moved the inline dropdown script from
_app_header.html into app/web/static/app.js + added <script src=…>
to base.html. That broke EVERY page that includes _app_header.html
WITHOUT extending base.html (catalog, corporate_memory*,
admin_tables, install). They got the nav markup but no JS → both
Admin and AD dropdowns dead on those pages.

Fix: emit the <script src=app.js defer> directly inside the
_app_header.html partial. Any page that includes the header now
gets the script automatically — base.html-extenders AND standalone
HTML pages alike. base.html's duplicate <script> line removed.

Also fixes the wide-hero on /catalog: .page-header--hero now sets
its own max-width: var(--width-app) (1280px) so standalone pages
without a .container parent don't render the gradient edge-to-edge.
catalog's .source-cards bumped from 900px → 1280px to match the
hero, otherwise the page reads two-tier (wide blue band, narrow
content) which the user flagged.

Verified locally via agent-browser: Admin + AD dropdowns now click
through on /catalog, /admin/tables, /corporate-memory.

* docs(plan): standalone pages → base.html framework migration plan

Plan + Plan-agent review (8 must-fix items applied) for converting
the 5 templates that ship their own <html><head><body> scaffold
(catalog, install, corporate_memory, corporate_memory_admin,
admin_tables) to extend base.html. Root cause of yesterday's
'dropdown dead on /catalog' regression: shared infrastructure in
base.html doesn't propagate to standalones.

* feat(base): body_attrs block + migrate install.html to extend base

base.html: new {% block body_attrs %}{% endblock %} slot so pages
that need <body> attributes (admin_tables has data-source-type)
can carry them through extends.

install.html: convert from standalone <html><head><body> scaffold
to {% extends "base.html" %} with title / body_attrs / head_extra
/ layout / scripts blocks. Drops:
- <!DOCTYPE>, <html>, </html>, <head>, </head>
- <meta charset>, <meta viewport>
- Duplicate <link rel="stylesheet" href="...style-custom.css">
  (base.html already provides one)
- <body> opening + closing tags
- Leading _app_header.html include + _version_badge.html include
  (base.html handles both)

Preserves per-page CSS (in head_extra), per-page JS (in scripts),
the Inter font preconnect (kept inline; not hoisted to base in
this PR — separate decision).

Pilots the migration recipe before the 4 larger pages.

* refactor(memory): extend base.html

Same recipe as install.html. corporate_memory.html now inherits
<html>/<head>/<body> + nav + app.js script tag from base.html.
Page-specific CSS and JS preserved in head_extra + scripts blocks.

* refactor(memory-admin): extend base.html

Same recipe as install/corporate_memory. Curation page now in the
shared rendering pipeline.

* refactor(catalog): extend base.html

catalog.html had the most complexity: 7 head-level assets (chart.js,
Prism, prism-sql, metric_modal.css link + 2 preconnects + Inter
stylesheet), 5 body-level <script> blocks including a <script type=
"module"> for the metric modal, 2 duplicate style-custom.css links
in <head>. The migration script preserved all of them — head-level
externals hoisted to {% block head_extra %} in source order, body
scripts relocated to {% block scripts %} in source order (so chart.js
loads before the IIFE that builds Chart instances), duplicate
style-custom.css links dropped (base.html provides one).

* refactor(admin-tables): extend base.html + carry data-source-type

The biggest of the 5 standalones at 3563 lines. <body data-source-
type="{{ data_source_type }}"> attribute carried through via the
new {% block body_attrs %} slot (admin_tables JS reads
document.body.dataset.sourceType to switch between keboola and
bigquery rendering paths).

* release: 0.54.10 — UI design system unification + homepage status frame + initial workspace override + store guardrails

Co-Authored-By: zdenek.srotyr <zdenek.srotyr@keboola.com>

* refactor(web): migrate remaining templates to canonical design primitives

- admin_group_detail: .data-table, .btn family, appToast(), remove duplicate table/button/toast CSS
- admin_store_submission_detail: .data-table, .btn family, appToast(), remove duplicate btn/toast CSS
- profile_sessions: .data-table, _page_hero.html, remove duplicate table/title CSS
- me_debug: .data-table, .btn family, remove duplicate table/button CSS
- marketplace: .btn-primary/.btn-secondary, remove duplicate button CSS
- store_edit: remove duplicate .btn-primary/.btn-link CSS, canonical button classes
- store_upload: remove duplicate .btn-primary/.btn-secondary/.btn-link CSS

Co-Authored-By: zdenek.srotyr <zdenek.srotyr@keboola.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-05-14 13:28:03 +02:00

1173 lines
42 KiB
HTML

{% extends "base.html" %}
{% block title %}Access tokens — {{ config.INSTANCE_NAME }}{% endblock %}
{% block content %}
<style>
/* ─────────────────────────────────────────────────────────────────────────
/admin/tokens — ALL tokens across users for incident response + offboarding.
Admin-only. Card-stack layout with owner column, stat chip strip, owner
search + sort-by-owner chip, confirm-with-owner revoke modal. No "new
token" button here — admins use /tokens for their own.
───────────────────────────────────────────────────────────────────────── */
body > .container { max-width: 1280px; }
.tokens-page {
max-width: 1280px;
margin: 0 auto;
padding: 28px 8px 48px;
box-sizing: border-box;
font-family: var(--font-primary, 'Inter', system-ui, -apple-system, BlinkMacSystemFont, sans-serif);
}
@media (max-width: 720px) {
.tokens-page { padding: 20px 0 32px; }
}
/* ── Hero ──────────────────────────────────────────────────────────────── */
.tokens-hero {
background: linear-gradient(135deg, #0073D1 0%, #0056A3 100%);
border-radius: 14px;
padding: 28px 32px 24px;
margin-bottom: 20px;
box-shadow: 0 4px 16px rgba(0, 115, 209, 0.2);
color: #fff;
position: relative;
}
.tokens-hero .hero-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.tokens-hero .hero-text { min-width: 0; }
.tokens-hero .hero-eyebrow {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.8px;
color: rgba(255, 255, 255, 0.75);
margin-bottom: 8px;
}
.tokens-hero .tokens-title {
font-size: 28px;
font-weight: 600;
letter-spacing: -0.01em;
margin: 0 0 6px;
color: #fff;
}
.tokens-hero .tokens-subtitle {
font-size: 14px;
font-weight: 400;
color: rgba(255, 255, 255, 0.9);
margin: 0;
line-height: 1.5;
}
.tokens-counts {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-top: 20px;
}
.tokens-counts .count-chip {
background: rgba(255, 255, 255, 0.12);
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 10px;
padding: 12px 14px;
display: flex;
align-items: center;
gap: 10px;
backdrop-filter: saturate(140%) blur(2px);
}
.tokens-counts .count-chip .dot {
width: 10px; height: 10px; border-radius: 50%;
flex-shrink: 0;
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.15);
}
.tokens-counts .count-chip.active .dot { background: #16a34a; }
.tokens-counts .count-chip.expiring .dot { background: #ea580c; }
.tokens-counts .count-chip.expired .dot { background: #dc2626; }
.tokens-counts .count-chip.revoked .dot { background: #6b7280; }
.tokens-counts .count-chip .count-value {
font-size: 24px;
font-weight: 600;
line-height: 1;
color: #fff;
letter-spacing: -0.01em;
}
.tokens-counts .count-chip .count-label {
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.4px;
color: rgba(255, 255, 255, 0.85);
margin-top: 2px;
}
.tokens-counts .count-chip .count-text {
display: flex;
flex-direction: column;
}
/* ── Toolbar ───────────────────────────────────────────────────────────── */
.toolbar {
margin-bottom: 14px;
display: flex;
flex-direction: column;
gap: 10px;
}
.chip-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
}
.chip-row .chip-group-label {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.4px;
color: var(--text-secondary, #6b7280);
margin-right: 4px;
}
.chip-group {
display: inline-flex;
flex-wrap: wrap;
gap: 6px;
}
.chip-btn {
font-family: var(--font-primary, inherit);
font-size: 12px;
font-weight: 500;
height: 30px;
padding: 0 12px;
border-radius: 999px;
border: 1px solid var(--border, #e5e7eb);
background: var(--surface, #fff);
color: var(--text-secondary, #6b7280);
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
transition: all 0.12s ease;
line-height: 1;
white-space: nowrap;
}
.chip-btn:hover {
border-color: #cbd5e1;
color: var(--text-primary, #111827);
}
.chip-btn[aria-pressed="true"] {
background: rgba(0, 115, 209, 0.10);
border-color: #0073D1;
color: #0073D1;
font-weight: 600;
}
.chip-btn:focus-visible {
outline: 2px solid #0073D1;
outline-offset: 2px;
}
.chip-btn .chip-dot {
width: 7px; height: 7px; border-radius: 50%;
flex-shrink: 0;
}
.chip-btn[data-val="active"] .chip-dot { background: #16a34a; }
.chip-btn[data-val="expiring"] .chip-dot { background: #ea580c; }
.chip-btn[data-val="expired"] .chip-dot { background: #dc2626; }
.chip-btn[data-val="revoked"] .chip-dot { background: #6b7280; }
.chip-btn .chip-arrow {
width: 10px; height: 10px;
opacity: 0;
}
.chip-btn[data-sort-dir="asc"] .chip-arrow,
.chip-btn[data-sort-dir="desc"] .chip-arrow { opacity: 1; }
.chip-btn[data-sort-dir="asc"] .chip-arrow { transform: rotate(180deg); }
.search-row {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.search-wrap {
position: relative;
flex: 1 1 280px;
min-width: 220px;
}
.search-wrap svg {
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
width: 14px; height: 14px;
color: var(--text-secondary, #9ca3af);
pointer-events: none;
}
.search-wrap input[type="search"] {
width: 100%;
height: 38px;
padding: 0 12px 0 36px;
border: 1px solid var(--border, #e5e7eb);
border-radius: 8px;
font-size: 13px;
font-family: var(--font-primary, inherit);
background: var(--surface, #fff);
color: var(--text-primary, #111827);
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
.search-wrap input[type="search"]::placeholder { color: #9ca3af; }
.search-wrap input[type="search"]:hover { border-color: #cbd5e1; }
.search-wrap input[type="search"]:focus {
outline: none;
border-color: #0073D1;
box-shadow: 0 0 0 3px rgba(0, 115, 209, 0.15);
}
.clear-link {
font-family: var(--font-primary, inherit);
background: none;
border: none;
padding: 8px 4px;
font-size: 13px;
font-weight: 500;
color: var(--text-secondary, #6b7280);
cursor: pointer;
text-decoration: none;
margin-left: auto;
}
.clear-link:hover { color: #0073D1; text-decoration: underline; }
.clear-link:focus-visible {
outline: 2px solid #0073D1;
outline-offset: 2px;
border-radius: 4px;
}
/* Hidden legacy select controls — kept for test backcompat. */
.sr-only {
position: absolute !important;
width: 1px; height: 1px;
padding: 0; margin: -1px;
overflow: hidden; clip: rect(0,0,0,0);
white-space: nowrap; border: 0;
}
/* ── Card list ─────────────────────────────────────────────────────────── */
.tokens-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 10px;
}
.token-card {
background: var(--surface, #fff);
border: 1px solid var(--border, #e5e7eb);
border-radius: 12px;
padding: 16px 20px;
display: flex;
align-items: center;
gap: 20px;
transition: box-shadow 0.15s ease, border-color 0.15s ease, transform 0.15s ease;
}
.token-card:hover {
box-shadow: 0 4px 16px rgba(15, 23, 42, 0.06);
border-color: #cbd5e1;
}
.token-card.is-revoked,
.token-card.is-expired {
background: #fafbfc;
}
.token-card.is-revoked .token-name,
.token-card.is-revoked .owner-email {
text-decoration: line-through;
color: var(--text-secondary, #6b7280);
}
.token-main {
flex: 1 1 auto;
min-width: 0;
display: flex;
align-items: center;
gap: 12px;
}
.avatar-sm {
width: 32px; height: 32px;
border-radius: 50%;
background: #0073D1;
color: #fff;
font-size: 12px;
font-weight: 600;
letter-spacing: 0.3px;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
text-transform: uppercase;
}
.token-text { min-width: 0; }
.token-name {
display: block;
font-size: 15px;
font-weight: 600;
color: var(--text-primary, #1A253C);
line-height: 1.3;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 380px;
}
.token-meta {
display: block;
font-size: 13px;
color: var(--text-secondary, #6b7280);
line-height: 1.4;
margin-top: 2px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 420px;
}
.owner-email { color: inherit; }
.chip-mono {
display: inline-block;
padding: 1px 6px;
background: var(--border-light, #f3f4f6);
border-radius: 4px;
font-family: var(--font-mono, ui-monospace, "SF Mono", Menlo, monospace);
font-size: 11.5px;
color: var(--text-secondary, #6b7280);
letter-spacing: 0.2px;
margin: 0 2px;
}
.token-usage {
flex: 0 0 200px;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.token-usage .usage-main {
font-size: 13px;
font-weight: 500;
color: var(--text-primary, #1A253C);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.token-usage .usage-sub {
font-size: 11.5px;
color: var(--text-secondary, #6b7280);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.token-usage.soon .usage-main { color: #c2410c; }
.token-usage.expired .usage-main{ color: #b91c1c; }
.token-usage.strike .usage-main { text-decoration: line-through; color: #9ca3af; font-weight: 400; }
.token-aside {
display: flex;
align-items: center;
gap: 12px;
flex-shrink: 0;
}
/* ── Status pill ───────────────────────────────────────────────────────── */
.status-pill {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-radius: 999px;
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.3px;
white-space: nowrap;
}
.status-pill .pill-dot {
width: 7px; height: 7px; border-radius: 50%;
flex-shrink: 0;
}
.status-pill.status-active { background: rgba(22, 163, 74, 0.12); color: #15803d; }
.status-pill.status-active .pill-dot { background: #16a34a; }
.status-pill.status-expiring { background: rgba(234, 88, 12, 0.12); color: #c2410c; }
.status-pill.status-expiring .pill-dot { background: #ea580c; }
.status-pill.status-expired { background: rgba(220, 38, 38, 0.12); color: #b91c1c; }
.status-pill.status-expired .pill-dot { background: #dc2626; }
.status-pill.status-revoked { background: rgba(107, 114, 128, 0.12); color: #4b5563; }
.status-pill.status-revoked .pill-dot { background: #6b7280; }
/* ── Revoke button ─────────────────────────────────────────────────────── */
.revoke-btn {
display: inline-flex;
align-items: center;
gap: 6px;
height: 32px;
padding: 0 14px;
border-radius: 8px;
font-family: var(--font-primary, inherit);
font-size: 13px;
font-weight: 500;
cursor: pointer;
background: transparent;
color: #dc2626;
border: 1px solid rgba(220, 38, 38, 0.35);
transition: all 0.12s ease;
line-height: 1;
}
.revoke-btn:hover:not([disabled]) {
background: #dc2626;
color: #fff;
border-color: #dc2626;
}
.revoke-btn:focus-visible {
outline: 2px solid #0073D1;
outline-offset: 2px;
}
.revoke-btn[disabled] {
opacity: 0.4;
cursor: not-allowed;
border-color: var(--border, #e5e7eb);
color: var(--text-secondary, #9ca3af);
}
.revoke-btn svg { display: block; }
.token-card:hover .revoke-btn:not([disabled]) {
border-color: #dc2626;
}
/* ── Empty / loading ───────────────────────────────────────────────────── */
.tokens-empty, .tokens-loading {
text-align: center;
padding: 48px 24px;
color: var(--text-secondary, #6b7280);
font-size: 14px;
background: var(--surface, #fff);
border: 1px solid var(--border, #e5e7eb);
border-radius: 12px;
}
.tokens-empty .empty-icon {
margin: 0 auto 14px;
width: 56px; height: 56px;
color: #d1d5db;
}
.tokens-empty .empty-title {
font-size: 15px;
font-weight: 600;
color: var(--text-primary, #1A253C);
margin: 0 0 4px;
}
.tokens-empty .empty-body {
font-size: 13px;
margin: 0 0 16px;
}
.tokens-empty .empty-clear {
padding: 8px 16px;
border-radius: 8px;
font-size: 13px;
font-weight: 500;
font-family: var(--font-primary, inherit);
border: 1px solid var(--border, #e5e7eb);
background: var(--surface, #fff);
color: var(--text-primary, #1A253C);
cursor: pointer;
transition: all 0.15s ease;
}
.tokens-empty .empty-clear:hover {
border-color: #0073D1;
color: #0073D1;
background: rgba(0, 115, 209, 0.04);
}
/* ── Modal ─────────────────────────────────────────────────────────────── */
.modal-backdrop {
position: fixed; inset: 0;
background: rgba(15, 23, 42, 0.55);
backdrop-filter: blur(2px);
display: none;
align-items: center;
justify-content: center;
z-index: 1000;
padding: 16px;
}
.modal-backdrop.is-open { display: flex; }
.modal-card {
background: var(--surface, #fff);
border-radius: 16px;
padding: 32px;
width: 100%;
max-width: 480px;
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.28);
animation: modal-in 0.18s ease-out;
}
@keyframes modal-in {
from { opacity: 0; transform: translateY(8px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.modal-card h3 {
margin: 0 0 10px;
font-size: 20px;
font-weight: 700;
color: var(--text-primary, #1A253C);
letter-spacing: -0.01em;
}
.modal-card p.sub {
margin: 0 0 18px;
font-size: 13.5px;
color: var(--text-secondary, #6b7280);
line-height: 1.55;
}
.modal-meta {
margin: 14px 0 4px;
padding: 14px 16px;
background: var(--background, #F5F7FA);
border: 1px solid var(--border-light, #f3f4f6);
border-radius: 10px;
display: grid;
grid-template-columns: max-content 1fr;
gap: 6px 14px;
font-size: 13px;
}
.modal-meta .mk {
color: var(--text-secondary, #6b7280);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.4px;
font-weight: 600;
align-self: center;
}
.modal-meta .mv {
color: var(--text-primary, #1A253C);
font-weight: 500;
word-break: break-all;
}
.modal-meta .mv.mono {
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 12px;
font-weight: 400;
}
.modal-actions {
display: flex;
gap: 10px;
justify-content: flex-end;
margin-top: 24px;
}
/* ── Toast ─────────────────────────────────────────────────────────────── */
.toast-stack {
position: fixed; bottom: 24px; right: 24px; z-index: 2000;
display: flex; flex-direction: column; gap: 8px; pointer-events: none;
}
.toast {
background: #111827;
color: #fff;
padding: 11px 18px;
border-radius: 10px;
font-size: 13px;
font-weight: 500;
box-shadow: 0 12px 36px rgba(0, 0, 0, 0.28);
opacity: 0;
transform: translateY(8px);
transition: opacity 0.2s, transform 0.2s;
pointer-events: auto;
max-width: 400px;
}
.toast.show { opacity: 1; transform: translateY(0); }
.toast.success { background: #047857; }
.toast.error { background: #b91c1c; }
/* ── Responsive ────────────────────────────────────────────────────────── */
@media (max-width: 720px) {
.tokens-page { padding: 20px 16px 32px; }
.tokens-hero { padding: 24px 20px 20px; }
.tokens-hero .tokens-title { font-size: 22px; }
.tokens-hero .hero-top { flex-direction: column; align-items: stretch; }
.token-card {
flex-direction: column;
align-items: stretch;
gap: 14px;
}
.token-main { width: 100%; }
.token-name { max-width: none; white-space: normal; }
.token-meta { max-width: none; white-space: normal; }
.token-usage {
flex: 1 1 auto;
width: 100%;
padding-left: 44px; /* align under avatar */
}
.token-aside {
width: 100%;
justify-content: space-between;
padding-left: 44px;
}
}
@media (max-width: 480px) {
.tokens-counts { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
</style>
<div class="tokens-page" data-is-admin="true" data-view="admin">
<!-- ═════════ HERO ═════════ -->
<section class="tokens-hero" aria-labelledby="tokens-title">
<div class="hero-top">
<div class="hero-text">
<div class="hero-eyebrow">Administration</div>
<h2 class="tokens-title" id="tokens-title">Access tokens</h2>
<p class="tokens-subtitle">
Personal access tokens across all users &mdash; for incident response and offboarding.
</p>
</div>
</div>
<div class="tokens-counts" id="tokens-counts" aria-live="polite" aria-label="Token counts summary">
<div class="count-chip active">
<span class="dot" aria-hidden="true"></span>
<div class="count-text">
<span class="count-value" id="count-active">0</span>
<span class="count-label">Active</span>
</div>
</div>
<div class="count-chip expiring" title="Active tokens expiring in the next 7 days">
<span class="dot" aria-hidden="true"></span>
<div class="count-text">
<span class="count-value" id="count-expiring">0</span>
<span class="count-label">Expiring soon</span>
</div>
</div>
<div class="count-chip expired">
<span class="dot" aria-hidden="true"></span>
<div class="count-text">
<span class="count-value" id="count-expired">0</span>
<span class="count-label">Expired</span>
</div>
</div>
<div class="count-chip revoked">
<span class="dot" aria-hidden="true"></span>
<div class="count-text">
<span class="count-value" id="count-revoked">0</span>
<span class="count-label">Revoked</span>
</div>
</div>
</div>
</section>
<!-- ═════════ TOOLBAR ═════════ -->
<section class="toolbar" aria-label="Filter and sort tokens">
<div class="chip-row">
<span class="chip-group-label" id="status-group-label">Status</span>
<div class="chip-group" role="radiogroup" aria-labelledby="status-group-label" id="flt-status-group">
<button type="button" class="chip-btn" role="radio" data-val="all" aria-pressed="true" aria-checked="true">All</button>
<button type="button" class="chip-btn" role="radio" data-val="active" aria-pressed="false" aria-checked="false"><span class="chip-dot" aria-hidden="true"></span>Active</button>
<button type="button" class="chip-btn" role="radio" data-val="expiring" aria-pressed="false" aria-checked="false"><span class="chip-dot" aria-hidden="true"></span>Expiring</button>
<button type="button" class="chip-btn" role="radio" data-val="expired" aria-pressed="false" aria-checked="false"><span class="chip-dot" aria-hidden="true"></span>Expired</button>
<button type="button" class="chip-btn" role="radio" data-val="revoked" aria-pressed="false" aria-checked="false"><span class="chip-dot" aria-hidden="true"></span>Revoked</button>
</div>
<!-- Hidden legacy select — kept so test assertion id="flt-status" stays valid -->
<select id="flt-status" class="sr-only" tabindex="-1" aria-hidden="true">
<option value="all" selected>All</option>
<option value="active">Active</option>
<option value="expiring">Expiring</option>
<option value="expired">Expired</option>
<option value="revoked">Revoked</option>
</select>
</div>
<div class="chip-row">
<span class="chip-group-label" id="sort-group-label">Sort by</span>
<div class="chip-group" role="group" aria-labelledby="sort-group-label" id="sort-group">
<button type="button" class="chip-btn" data-sort-key="created_at" data-sort-dir="desc" aria-pressed="true">
Created<svg class="chip-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg>
</button>
<button type="button" class="chip-btn" data-sort-key="last_used_at" aria-pressed="false">
Last used<svg class="chip-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg>
</button>
<button type="button" class="chip-btn" data-sort-key="expires_at" aria-pressed="false">
Expires<svg class="chip-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg>
</button>
<button type="button" class="chip-btn" data-sort-key="user_email" aria-pressed="false">
Owner<svg class="chip-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg>
</button>
</div>
<!-- Hidden legacy select — kept so test assertion id="flt-last-used" stays valid -->
<select id="flt-last-used" class="sr-only" tabindex="-1" aria-hidden="true">
<option value="any" selected>Any time</option>
<option value="never">Never used</option>
<option value="7d">&lt; 7 days ago</option>
<option value="30d">&lt; 30 days ago</option>
<option value="gt30d">&gt; 30 days ago</option>
<option value="gt90d">&gt; 90 days ago</option>
</select>
</div>
<div class="search-row">
<div class="search-wrap">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="11" cy="11" r="7"></circle>
<path d="m21 21-4.3-4.3"></path>
</svg>
<input id="flt-user" type="search" placeholder="Search by owner email&hellip;" autocomplete="off" aria-label="Filter by user email">
</div>
<button type="button" class="clear-link" id="clear-filters-toolbar">Clear filters</button>
</div>
</section>
<!-- ═════════ LIST ═════════ -->
<div id="tokens-loading" class="tokens-loading">Loading tokens&hellip;</div>
<ul class="tokens-list" id="tokens-list" role="list" aria-labelledby="tokens-title"></ul>
<div id="tokens-empty" class="tokens-empty" style="display:none;">
<svg class="empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="8" cy="15" r="4"></circle>
<line x1="10.85" y1="12.15" x2="19" y2="4"></line>
<line x1="18" y1="5" x2="20" y2="7"></line>
<line x1="15" y1="8" x2="17" y2="10"></line>
</svg>
<p class="empty-title">No tokens match these filters.</p>
<p class="empty-body">Adjust the filters or clear them to see everything.</p>
<button type="button" class="empty-clear" id="clear-filters-btn">Clear filters</button>
</div>
</div>
<!-- ═════════ REVOKE MODAL ═════════ -->
<div class="modal-backdrop" id="confirm-modal" role="dialog" aria-modal="true" aria-labelledby="confirm-title">
<div class="modal-card">
<h3 id="confirm-title">Revoke this token?</h3>
<p class="sub" id="confirm-text">
This cannot be undone and will immediately sign out any session using this token.
</p>
<div class="modal-meta" id="confirm-meta" aria-hidden="true"></div>
<div class="modal-actions">
<button class="btn btn-secondary" id="confirm-cancel-btn" data-close-modal="confirm-modal">Cancel</button>
<button class="btn btn-danger" id="confirm-ok-btn">Revoke token</button>
</div>
</div>
</div>
<div class="toast-stack" id="toast-stack" aria-live="polite"></div>
<script>
// Admin tokens — list of ALL tokens for incident response / offboarding.
const API_LIST = "/auth/admin/tokens";
const API_REVOKE = (id) => `/auth/admin/tokens/${encodeURIComponent(id)}`;
const SEVEN_DAYS = 7 * 86_400_000;
// ── Helpers ────────────────────────────────────────────────────────────────
function esc(s) {
const d = document.createElement("div");
d.textContent = s == null ? "" : String(s);
return d.innerHTML;
}
function fmtAbs(s) { return s ? String(s).replace("T", " ").slice(0, 19) : "—"; }
function parseDate(s) {
if (!s) return null;
const str = String(s).replace(" ", "T");
const d = new Date(str);
return isNaN(d.getTime()) ? null : d;
}
function relTime(s) {
const d = parseDate(s);
if (!d) return "—";
const diff = Date.now() - d.getTime();
const abs = Math.abs(diff);
const sign = diff < 0 ? "in " : "";
const suf = diff >= 0 ? " ago" : "";
const min = 60_000, hr = 3_600_000, day = 86_400_000;
if (abs < min) return sign + "just now";
if (abs < hr) return sign + Math.floor(abs / min) + "m" + suf;
if (abs < day) return sign + Math.floor(abs / hr) + "h" + suf;
const days = Math.floor(abs / day);
if (days === 1) return sign + "1 day" + suf;
if (days < 60) return sign + days + " days" + suf;
const months = Math.floor(days / 30);
if (months < 24) return sign + months + "mo" + suf;
return sign + Math.floor(days / 365) + "y" + suf;
}
function initialsFor(email) {
if (!email) return "??";
const clean = String(email).trim();
if (clean.includes("@")) {
const local = clean.split("@")[0];
if (local.includes(".")) {
const parts = local.split(".").filter(Boolean);
return (parts[0][0] + (parts[1] ? parts[1][0] : parts[0][1] || "")).toUpperCase();
}
return (local[0] + (local[1] || "")).toUpperCase();
}
return clean.slice(0, 2).toUpperCase();
}
function computeStatus(t, now) {
if (t.revoked_at) return "revoked";
const exp = parseDate(t.expires_at);
if (exp && exp.getTime() < now) return "expired";
if (exp && (exp.getTime() - now) < SEVEN_DAYS) return "expiring";
return "active";
}
function statusPill(status) {
const map = {
active: { cls: "status-active", label: "active", aria: "active token" },
expiring: { cls: "status-expiring", label: "expiring", aria: "token expiring soon" },
expired: { cls: "status-expired", label: "expired", aria: "expired token" },
revoked: { cls: "status-revoked", label: "revoked", aria: "revoked token" },
};
const info = map[status] || map.revoked;
return `<span class="status-pill ${info.cls}" aria-label="${info.aria}"><span class="pill-dot" aria-hidden="true"></span>${info.label}</span>`;
}
function statusTooltip(t, status) {
if (status === "revoked") return t.revoked_at ? "Revoked " + relTime(t.revoked_at) : "Revoked";
if (status === "expired") return t.expires_at ? "Expired " + relTime(t.expires_at) : "Expired";
if (status === "expiring") return t.expires_at ? "Expires " + relTime(t.expires_at) : "Expiring soon";
return t.expires_at ? "Active, expires " + relTime(t.expires_at) : "Active";
}
// ── Toast ──────────────────────────────────────────────────────────────────
function toast(msg, kind = "") {
const el = document.createElement("div");
el.className = "toast " + kind;
el.textContent = msg;
document.getElementById("toast-stack").appendChild(el);
requestAnimationFrame(() => el.classList.add("show"));
setTimeout(() => { el.classList.remove("show"); setTimeout(() => el.remove(), 250); }, 3500);
}
// ── Modal ──────────────────────────────────────────────────────────────────
let _modalPrevFocus = null;
function openModal(id) {
const m = document.getElementById(id);
_modalPrevFocus = document.activeElement;
m.classList.add("is-open");
const cancel = m.querySelector("#confirm-cancel-btn");
if (cancel) setTimeout(() => cancel.focus(), 10);
}
function closeModal(id) {
const m = document.getElementById(id);
m.classList.remove("is-open");
if (_modalPrevFocus && typeof _modalPrevFocus.focus === "function") {
try { _modalPrevFocus.focus(); } catch (_) {}
}
_modalPrevFocus = null;
}
document.querySelectorAll("[data-close-modal]").forEach(el =>
el.addEventListener("click", () => closeModal(el.dataset.closeModal)));
document.querySelectorAll(".modal-backdrop").forEach(el => {
el.addEventListener("click", e => { if (e.target === el) closeModal(el.id); });
});
document.addEventListener("keydown", e => {
if (e.key === "Escape") {
document.querySelectorAll(".modal-backdrop.is-open").forEach(m => closeModal(m.id));
}
if (e.key === "Tab") {
const open = document.querySelector(".modal-backdrop.is-open");
if (!open) return;
const focusables = open.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
if (!focusables.length) return;
const first = focusables[0];
const last = focusables[focusables.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault(); last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault(); first.focus();
}
}
});
function confirmModal({ title, sub, meta, okLabel = "Revoke token" }) {
document.getElementById("confirm-title").textContent = title;
document.getElementById("confirm-text").textContent = sub;
const metaEl = document.getElementById("confirm-meta");
if (meta && Object.keys(meta).length) {
let html = "";
for (const [k, v] of Object.entries(meta)) {
const isMono = k === "Prefix";
html += `<span class="mk">${esc(k)}</span><span class="mv${isMono ? " mono" : ""}">${esc(v)}</span>`;
}
metaEl.innerHTML = html;
metaEl.style.display = "grid";
} else {
metaEl.style.display = "none";
}
const okBtn = document.getElementById("confirm-ok-btn");
okBtn.textContent = okLabel;
return new Promise(resolve => {
const ok = () => { closeModal("confirm-modal"); cleanup(); resolve(true); };
const cancel = () => { cleanup(); resolve(false); };
const onCancelClick = () => cancel();
const cancelBtn = document.getElementById("confirm-cancel-btn");
function cleanup() {
okBtn.removeEventListener("click", ok);
cancelBtn.removeEventListener("click", onCancelClick);
}
okBtn.addEventListener("click", ok, { once: true });
cancelBtn.addEventListener("click", onCancelClick, { once: true });
openModal("confirm-modal");
});
}
// ── State ──────────────────────────────────────────────────────────────────
let allTokens = [];
let filters = { status: "all", user: "" };
let sort = { key: "created_at", dir: "desc" };
function applyFilters(items) {
const now = Date.now();
return items.filter(t => {
const s = computeStatus(t, now);
if (filters.status !== "all" && s !== filters.status) return false;
if (filters.user) {
const q = filters.user.toLowerCase();
if (!(t.user_email || "").toLowerCase().includes(q)) return false;
}
return true;
});
}
function sortItems(items) {
const now = Date.now();
const { key, dir } = sort;
const mul = dir === "asc" ? 1 : -1;
return [...items].sort((a, b) => {
let va, vb;
if (key === "status") { va = computeStatus(a, now); vb = computeStatus(b, now); }
else { va = a[key] || ""; vb = b[key] || ""; }
if (va < vb) return -1 * mul;
if (va > vb) return 1 * mul;
return 0;
});
}
function updateCounts() {
const now = Date.now();
let active = 0, revoked = 0, expired = 0, expiring = 0;
for (const t of allTokens) {
const s = computeStatus(t, now);
if (s === "active") active++;
else if (s === "expiring") expiring++;
else if (s === "revoked") revoked++;
else if (s === "expired") expired++;
}
const byId = (id) => document.getElementById(id);
if (byId("count-active")) byId("count-active").textContent = active;
if (byId("count-revoked")) byId("count-revoked").textContent = revoked;
if (byId("count-expired")) byId("count-expired").textContent = expired;
if (byId("count-expiring")) byId("count-expiring").textContent = expiring;
}
// ── Card render ────────────────────────────────────────────────────────────
const TRASH_SVG = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"></path><path d="M10 11v6"></path><path d="M14 11v6"></path><path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"></path></svg>`;
function renderCard(t, now) {
const status = computeStatus(t, now);
const ownerEmail = t.user_email || t.user_id || "—";
const initials = initialsFor(ownerEmail);
const exp = parseDate(t.expires_at);
const lastUsedRel = t.last_used_at ? relTime(t.last_used_at) : "—";
const lastUsedIp = t.last_used_ip ? `from ${esc(t.last_used_ip)}` : (t.last_used_at ? "" : "never used");
const lastUsedTitle = t.last_used_at
? `${fmtAbs(t.last_used_at)}${t.last_used_ip ? " from " + t.last_used_ip : ""}`
: "never used";
let usageCls = "";
if (status === "revoked") usageCls = "";
const createdRel = relTime(t.created_at);
let expPart = "";
if (t.revoked_at) {
expPart = `<span style="color:#6b7280;">Revoked ${esc(relTime(t.revoked_at))}</span>`;
} else if (exp) {
const delta = exp.getTime() - now;
if (delta < 0) {
expPart = `<span style="color:#b91c1c;font-weight:500;">Expired ${esc(relTime(t.expires_at))}</span>`;
} else if (delta < SEVEN_DAYS) {
expPart = `<span style="color:#c2410c;font-weight:500;">Expires ${esc(relTime(t.expires_at))}</span>`;
} else {
expPart = `Expires ${esc(relTime(t.expires_at))}`;
}
} else {
expPart = "No expiry";
}
const card = document.createElement("li");
card.className = "token-card" + (status === "revoked" ? " is-revoked" : "") + (status === "expired" ? " is-expired" : "");
card.setAttribute("role", "listitem");
card.setAttribute("data-token-card", t.id);
card.setAttribute("data-status", status);
card.innerHTML = `
<div class="token-main">
<span class="avatar-sm" aria-hidden="true">${esc(initials)}</span>
<div class="token-text">
<span class="token-name" title="${esc(t.name)}">${esc(t.name)}</span>
<span class="token-meta">
<span class="owner-email">${esc(ownerEmail)}</span>
<span aria-hidden="true"> &middot; </span>
<span class="chip-mono">${esc(t.prefix)}&hellip;</span>
<span aria-hidden="true"> &middot; </span>
<span>Created ${esc(createdRel)}</span>
<span aria-hidden="true"> &middot; </span>
${expPart}
</span>
</div>
</div>
<div class="token-usage ${usageCls}" title="${esc(lastUsedTitle)}">
<span class="usage-main">Last used ${esc(lastUsedRel)}</span>
${lastUsedIp ? `<span class="usage-sub">${lastUsedIp}</span>` : ""}
</div>
<div class="token-aside">
<span title="${esc(statusTooltip(t, status))}">${statusPill(status)}</span>
<button type="button" class="revoke-btn" data-revoke
data-token-id="${esc(t.id)}"
data-token-name="${esc(t.name)}"
data-token-owner="${esc(ownerEmail)}"
data-token-prefix="${esc(t.prefix)}"
aria-label="Revoke token ${esc(t.name)} owned by ${esc(ownerEmail)}"
title="Revoke token"
${t.revoked_at ? "disabled" : ""}>
${TRASH_SVG}
<span>Revoke</span>
</button>
</div>`;
return card;
}
function renderList() {
const list = document.getElementById("tokens-list");
const loading = document.getElementById("tokens-loading");
const empty = document.getElementById("tokens-empty");
loading.style.display = "none";
const filtered = sortItems(applyFilters(allTokens));
list.innerHTML = "";
if (filtered.length === 0) {
empty.style.display = "block";
list.style.display = "none";
return;
}
empty.style.display = "none";
list.style.display = "flex";
const now = Date.now();
for (const t of filtered) list.appendChild(renderCard(t, now));
list.querySelectorAll("[data-revoke]").forEach(el => {
el.addEventListener("click", () => revokeToken({
id: el.dataset.tokenId,
name: el.dataset.tokenName,
owner: el.dataset.tokenOwner,
prefix: el.dataset.tokenPrefix,
}));
});
}
async function loadTokens() {
try {
const r = await fetch(API_LIST, { credentials: "include" });
if (!r.ok) throw new Error("HTTP " + r.status);
allTokens = await r.json();
updateCounts();
renderList();
} catch (e) {
document.getElementById("tokens-loading").textContent = "Failed to load tokens: " + e.message;
toast("Failed to load tokens", "error");
}
}
async function revokeToken({ id, name, owner, prefix }) {
const meta = {
"Name": name,
"Owner": owner,
"Prefix": (prefix || "") + "…",
};
const confirmed = await confirmModal({
title: "Revoke this token?",
sub: "This cannot be undone and will immediately sign out any session using this token.",
meta,
okLabel: "Revoke token",
});
if (!confirmed) return;
const r = await fetch(API_REVOKE(id), { method: "DELETE", credentials: "include" });
if (!r.ok) { toast("Failed: " + (await r.text()), "error"); return; }
toast("Token revoked", "success");
await loadTokens();
}
// ── Filter chips (status) ──────────────────────────────────────────────────
function setStatusFilter(val) {
filters.status = val;
document.querySelectorAll("#flt-status-group .chip-btn").forEach(b => {
const on = b.dataset.val === val;
b.setAttribute("aria-pressed", on ? "true" : "false");
b.setAttribute("aria-checked", on ? "true" : "false");
});
const sel = document.getElementById("flt-status");
if (sel) sel.value = val;
renderList();
}
document.querySelectorAll("#flt-status-group .chip-btn").forEach(btn => {
btn.addEventListener("click", () => setStatusFilter(btn.dataset.val));
});
document.getElementById("flt-status").addEventListener("change", e => setStatusFilter(e.target.value));
// ── Sort chips ─────────────────────────────────────────────────────────────
function setSort(key) {
if (sort.key === key) {
sort.dir = sort.dir === "asc" ? "desc" : "asc";
} else {
sort.key = key;
sort.dir = key === "user_email" ? "asc" : "desc";
}
document.querySelectorAll("#sort-group .chip-btn").forEach(b => {
if (b.dataset.sortKey === sort.key) {
b.setAttribute("aria-pressed", "true");
b.setAttribute("data-sort-dir", sort.dir);
} else {
b.setAttribute("aria-pressed", "false");
b.removeAttribute("data-sort-dir");
}
});
renderList();
}
document.querySelectorAll("#sort-group .chip-btn").forEach(btn => {
btn.addEventListener("click", () => setSort(btn.dataset.sortKey));
});
// ── Owner email search ─────────────────────────────────────────────────────
(function bindUserFilter() {
const el = document.getElementById("flt-user");
if (!el) return;
el.addEventListener("input", e => {
filters.user = e.target.value.trim(); renderList();
});
})();
function clearFilters() {
filters = { status: "all", user: "" };
setStatusFilter("all");
const uf = document.getElementById("flt-user");
if (uf) uf.value = "";
const lu = document.getElementById("flt-last-used");
if (lu) lu.value = "any";
renderList();
}
document.getElementById("clear-filters-btn").addEventListener("click", clearFilters);
document.getElementById("clear-filters-toolbar").addEventListener("click", clearFilters);
// Pre-fill user filter from ?user=... (deep-link from /admin/users)
(function initFromQuery() {
try {
const q = new URLSearchParams(window.location.search);
const u = q.get("user");
if (u) {
filters.user = u;
const el = document.getElementById("flt-user");
if (el) el.value = u;
}
} catch (_) {}
})();
loadTokens();
</script>
{% endblock %}