feat: show the version of Sonda

- GET /version (signed-in users only) answers the version and, when the binary knows it, the commit it was built from and whether the files had uncommitted changes
- the commit is read from the build info Go records in a git checkout, so no build flag is needed
- the side menu shows the version under the privacy line, and Settings has an About section with it
- the menu's own requests (friends, version) are not counted as requests of an admin page in the Shell tests
This commit is contained in:
tgiachi 2026-11-15 17:30:14 +01:00
commit 00e5254fde
18 changed files with 337 additions and 10 deletions

41
cmd/sondad/buildinfo.go Normal file
View file

@ -0,0 +1,41 @@
package main
import (
"runtime/debug"
httpapi "codeberg.org/squidd/sonda/internal/api/http"
)
// shortRevision is how many characters of the commit the app shows.
const shortRevision = 7
// revision reads the commit the binary was built from, and whether the files had changes that were not committed.
// Go records both in a build made inside a git checkout; a build without them (a copy of the sources, or
// -buildvcs=false) has no revision.
func revision(info *debug.BuildInfo) (rev string, modified bool) {
if info == nil {
return "", false
}
for _, s := range info.Settings {
switch s.Key {
case "vcs.revision":
rev = s.Value
if len(rev) > shortRevision {
rev = rev[:shortRevision]
}
case "vcs.modified":
modified = s.Value == "true"
}
}
if rev == "" {
modified = false
}
return rev, modified
}
// build says which Sonda this is, for the signed-in users to see.
func build() httpapi.Build {
info, _ := debug.ReadBuildInfo()
rev, modified := revision(info)
return httpapi.Build{Version: version, Revision: rev, Modified: modified}
}

View file

@ -0,0 +1,43 @@
package main
import (
"runtime/debug"
"testing"
)
func settings(kv ...string) *debug.BuildInfo {
b := &debug.BuildInfo{}
for i := 0; i+1 < len(kv); i += 2 {
b.Settings = append(b.Settings, debug.BuildSetting{Key: kv[i], Value: kv[i+1]})
}
return b
}
func TestRevisionIsTheShortCommit(t *testing.T) {
rev, modified := revision(settings("vcs", "git", "vcs.revision", "69c85a7e1d0f4b2c8a9e3f5d6b7a8c9d0e1f2a3b", "vcs.modified", "false"))
if rev != "69c85a7" || modified {
t.Errorf("got %q, %v", rev, modified)
}
}
func TestRevisionSaysWhenTheTreeWasChanged(t *testing.T) {
rev, modified := revision(settings("vcs.revision", "69c85a7e1d0f", "vcs.modified", "true"))
if rev != "69c85a7" || !modified {
t.Errorf("got %q, %v", rev, modified)
}
}
func TestRevisionIsEmptyWithoutVersionControlInfo(t *testing.T) {
if rev, modified := revision(settings()); rev != "" || modified {
t.Errorf("got %q, %v", rev, modified)
}
if rev, modified := revision(nil); rev != "" || modified {
t.Errorf("nil: got %q, %v", rev, modified)
}
}
func TestShortRevisionIsKeptWhole(t *testing.T) {
if rev, _ := revision(settings("vcs.revision", "abc")); rev != "abc" {
t.Errorf("got %q", rev)
}
}

View file

@ -299,6 +299,7 @@ func run() error {
router := httpapi.NewRouter(httpapi.Deps{
Logger: logger,
Build: build(),
Auth: auth.NewService(storage.NewUserRepo(db), storage.NewRefreshRepo(db), tokens, cfg.Auth.RefreshTTL()),
Tokens: tokens,
Listening: listening.NewService(storage.NewListeningRepo(db), cfg.Listening.MinListen()),

View file

@ -360,6 +360,9 @@ func TestResponsesMatchTheSpec(t *testing.T) {
c.expect(c.call("GET", "/auth/me", "", nil), 401, "me without token", "unauthorized")
c.expect(c.call("GET", "/auth/me", token, nil), 200, "me")
c.expect(c.call("GET", "/version", "", nil), 401, "version without token", "unauthorized")
c.expect(c.call("GET", "/version", token, nil), 200, "version")
renewed := c.expect(c.call("POST", "/auth/refresh", "", map[string]string{"refresh_token": refresh}), 200, "refresh")
c.expect(c.call("POST", "/auth/refresh", "", map[string]string{"refresh_token": refresh}), 401, "refresh replay", "invalid_refresh_token")
c.expect(c.call("POST", "/auth/refresh", "", "not an object"), 400, "refresh bad body", "invalid_input")

View file

@ -0,0 +1,33 @@
package httpapi
import "testing"
func TestVersionIsForSignedInUsers(t *testing.T) {
h := newTestAPIWith(t, func(d *Deps) { d.Build = Build{Version: "1.2.3", Revision: "abc1234", Modified: true} })
if r := do(t, h, "GET", "/api/v1/version", "", nil); r.Code != 401 {
t.Fatalf("without a token: %d, want 401", r.Code)
}
tok := registerAndLogin(t, h)
r := do(t, h, "GET", "/api/v1/version", tok, nil)
if r.Code != 200 {
t.Fatalf("version: %d %v", r.Code, r.Body)
}
if str(r.Body, "version") != "1.2.3" || str(r.Body, "revision") != "abc1234" || r.Body["modified"] != true {
t.Errorf("body = %v", r.Body)
}
}
func TestVersionWithoutARevisionHasNone(t *testing.T) {
h := newTestAPIWith(t, func(d *Deps) { d.Build = Build{Version: "1.2.3"} })
tok := registerAndLogin(t, h)
r := do(t, h, "GET", "/api/v1/version", tok, nil)
if r.Code != 200 || str(r.Body, "version") != "1.2.3" {
t.Fatalf("version: %d %v", r.Code, r.Body)
}
if _, ok := r.Body["revision"]; ok {
t.Errorf("revision should be left out: %v", r.Body)
}
if _, ok := r.Body["modified"]; ok {
t.Errorf("modified should be left out: %v", r.Body)
}
}

View file

@ -212,9 +212,18 @@ type libraryService interface {
Delete(ctx context.Context, id int64) error
}
// Build says which Sonda is running: its version, and the commit it was built from when that is known.
type Build struct {
Version string `json:"version"`
Revision string `json:"revision,omitempty"`
// Modified is true when the files had changes that were not committed.
Modified bool `json:"modified,omitempty"`
}
// Deps are the services the API needs.
type Deps struct {
Logger *zap.Logger
Build Build
Auth authService
Tokens tokenParser
Listening listenService
@ -306,6 +315,7 @@ func NewRouter(d Deps) *gin.Engine {
// Any signed-in user.
protected := v1.Group("", requireAuth(d.Tokens, d.Auth, false))
protected.GET("/auth/me", a.me)
protected.GET("/version", func(c *gin.Context) { c.JSON(http.StatusOK, d.Build) })
protected.POST("/auth/password", a.changePassword)
l := &listenHandlers{svc: d.Listening, announce: d.Mastodon}
protected.POST("/listens", l.record)

View file

@ -68,6 +68,35 @@ paths:
properties:
status: {type: string, enum: [ok]}
/version:
get:
tags: [System]
operationId: getVersion
summary: Which Sonda is running
description: |
The version, and the commit it was built from when the binary knows it. Only a signed-in
user can ask: the version of a server is not told to a stranger.
security: [{bearerAuth: []}]
responses:
'200':
description: The version of this server.
content:
application/json:
schema:
type: object
additionalProperties: false
required: [version]
properties:
version: {type: string, example: 0.1.0}
revision:
type: string
description: The first characters of the commit. Left out when the build did not record it.
example: 69c85a7
modified:
type: boolean
description: True when the files had changes that were not committed. Left out when false.
'401': {$ref: '#/components/responses/Unauthorized'}
/openapi.yaml:
get:
tags: [System]

View file

@ -21,6 +21,27 @@ export interface paths {
patch?: never;
trace?: never;
};
"/version": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Which Sonda is running
* @description The version, and the commit it was built from when the binary knows it. Only a signed-in
* user can ask: the version of a server is not told to a stranger.
*/
get: operations["getVersion"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/openapi.yaml": {
parameters: {
query?: never;
@ -4390,6 +4411,37 @@ export interface operations {
};
};
};
getVersion: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The version of this server. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @example 0.1.0 */
version: string;
/**
* @description The first characters of the commit. Left out when the build did not record it.
* @example 69c85a7
*/
revision?: string;
/** @description True when the files had changes that were not committed. Left out when false. */
modified?: boolean;
};
};
};
401: components["responses"]["Unauthorized"];
};
};
getOpenAPI: {
parameters: {
query?: never;

18
web/src/api/version.ts Normal file
View file

@ -0,0 +1,18 @@
import { useQuery } from '@tanstack/react-query'
import { api } from '@/api/client'
export interface Version {
version: string
revision?: string
modified?: boolean
}
/** Which Sonda the server is. It cannot change while the page is open, so it is read once. */
export function useVersion() {
return useQuery({
queryKey: ['/version'],
queryFn: () => api.get<Version>('/version'),
staleTime: Infinity,
retry: false,
})
}

View file

@ -0,0 +1,48 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import { beforeEach, expect, test, vi } from 'vitest'
import { initI18n } from '@/i18n'
import { apiError, mockFetch } from '@/test/mockFetch'
import VersionLabel from './VersionLabel'
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
})
function renderLabel() {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<VersionLabel />
</QueryClientProvider>,
)
}
test('it says the version and the commit the server was built from', async () => {
mockFetch({ 'GET /api/v1/version': () => ({ version: '0.1.0', revision: '69c85a7' }) })
renderLabel()
expect(await screen.findByText('Version 0.1.0 · 69c85a7')).toBeInTheDocument()
})
test('a build that did not record its commit shows only the version', async () => {
mockFetch({ 'GET /api/v1/version': () => ({ version: '0.1.0' }) })
renderLabel()
expect(await screen.findByText('Version 0.1.0')).toBeInTheDocument()
})
test('a build with changes that were not committed says so', async () => {
mockFetch({ 'GET /api/v1/version': () => ({ version: '0.1.0', revision: '69c85a7', modified: true }) })
renderLabel()
expect(await screen.findByText('Version 0.1.0 · 69c85a7 (changed)')).toBeInTheDocument()
})
test('it shows nothing when the version cannot be read', async () => {
const { calls } = mockFetch({ 'GET /api/v1/version': () => apiError(500, 'internal') })
const { container } = render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<VersionLabel />
</QueryClientProvider>,
)
await vi.waitFor(() => expect(calls).toHaveLength(1))
expect(container).toBeEmptyDOMElement()
})

View file

@ -0,0 +1,14 @@
import { useTranslation } from 'react-i18next'
import { useVersion } from '@/api/version'
/**
* The version of Sonda, with the commit it was built from when the server knows it. It shows nothing until the server
* has answered, and nothing when it cannot: the version is information, not something the page waits for.
*/
export default function VersionLabel({ className }: { className?: string }) {
const { t } = useTranslation()
const { data } = useVersion()
if (!data) return null
const key = !data.revision ? 'version.plain' : data.modified ? 'version.changed' : 'version.commit'
return <p className={className}>{t(key, { version: data.version, revision: data.revision })}</p>
}

View file

@ -25,8 +25,8 @@ async function renderAt(path: string) {
await screen.findByRole('main')
}
/** The menu asks which friends there are; the tests below are about what an admin page asks. */
const notFriends = (c: { url: URL }) => c.url.pathname !== '/api/v1/friends'
/** What the menu asks for on its own (the friends, to know whether to show Friends, and the version): the tests below are about what an admin page asks. */
const notTheMenu = (c: { url: URL }) => !['/api/v1/friends', '/api/v1/version'].includes(c.url.pathname)
function mainNav() {
return screen.getByRole('navigation', { name: 'Main' })
@ -98,7 +98,7 @@ test('someone who is not an admin who opens the jobs address gets a notice and n
await renderAt('/admin/jobs')
expect(await screen.findByText('Only admins can see this page.')).toBeInTheDocument()
await new Promise((r) => setTimeout(r, 30))
expect(calls.filter(notFriends)).toHaveLength(0)
expect(calls.filter(notTheMenu)).toHaveLength(0)
})
test('someone who is not an admin who opens the providers address gets a notice and no request', async () => {
@ -107,7 +107,7 @@ test('someone who is not an admin who opens the providers address gets a notice
await renderAt('/admin/providers')
expect(await screen.findByText('Only admins can see this page.')).toBeInTheDocument()
await new Promise((r) => setTimeout(r, 30))
expect(calls.filter(notFriends)).toHaveLength(0)
expect(calls.filter(notTheMenu)).toHaveLength(0)
})
test('someone who is not an admin who opens the users address gets a notice and no request', async () => {
@ -116,7 +116,7 @@ test('someone who is not an admin who opens the users address gets a notice and
await renderAt('/admin/users')
expect(await screen.findByText('Only admins can see this page.')).toBeInTheDocument()
await new Promise((r) => setTimeout(r, 30))
expect(calls.filter(notFriends)).toHaveLength(0)
expect(calls.filter(notTheMenu)).toHaveLength(0)
})
test('someone who is not an admin who opens the admin address gets a notice and no request', async () => {

View file

@ -15,7 +15,7 @@ beforeEach(async () => {
})
function renderSidebar(friends: { id: number; name: string }[] = [], path = '/albums') {
mockFetch({ 'GET /api/v1/friends': () => ({ friends }) })
mockFetch({ 'GET /api/v1/friends': () => ({ friends }), 'GET /api/v1/version': () => ({ version: '0.1.0', revision: '69c85a7' }) })
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<MemoryRouter initialEntries={[path]}>
@ -79,6 +79,13 @@ test('the choice is kept on this device and applies the next time', async () =>
expect(localStorage.getItem('sonda.sidebar')).toBe('open')
})
test('the menu says which version of Sonda this is, and folding it leaves the version out', async () => {
const nav = renderSidebar()
expect(await within(nav).findByText('Version 0.1.0 · 69c85a7')).toBeInTheDocument()
await userEvent.click(within(nav).getByRole('button', { name: 'Collapse menu' }))
expect(within(nav).queryByText(/Version 0.1.0/)).not.toBeInTheDocument()
})
test('every link has an icon, and the words stay: the icon is decoration, not the name', () => {
const nav = renderSidebar()
const links = within(nav).getAllByRole('link')

View file

@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next'
import { useFriends } from '@/api/friends'
import { useSession } from '@/auth/session'
import Logo from '@/components/Logo'
import VersionLabel from '@/components/VersionLabel'
import { cn } from '@/lib/utils'
interface Item {
@ -184,7 +185,12 @@ export default function Sidebar() {
))}
</ul>
</div>
{!collapsed && <p className="px-3 pt-7 text-[13px] leading-snug text-muted-foreground max-sm:hidden">{t('app.privacy')}</p>}
{!collapsed && (
<div className="px-3 pt-7 text-[13px] leading-snug text-muted-foreground max-sm:hidden">
<p>{t('app.privacy')}</p>
<VersionLabel className="mt-3" />
</div>
)}
</nav>
)
}

View file

@ -114,7 +114,8 @@
"passwordHint": "8 to 256 characters. Changing it signs you out everywhere.",
"passwordLength": "The new password needs 8 to 256 characters.",
"currentPasswordWrong": "The current password is wrong.",
"changePassword": "Change password"
"changePassword": "Change password",
"about": "About"
},
"admin": {
"title": "Admin",
@ -1081,5 +1082,10 @@
"later": "Later",
"install": "Install Sonda",
"installIntro": "Install Sonda on this device to open it like an app, from its own icon and in its own window."
},
"version": {
"plain": "Version {{version}}",
"commit": "Version {{version}} · {{revision}}",
"changed": "Version {{version}} · {{revision}} (changed)"
}
}

View file

@ -114,7 +114,8 @@
"passwordHint": "Da 8 a 256 caratteri. Cambiarla ti disconnette ovunque.",
"passwordLength": "La nuova password deve avere da 8 a 256 caratteri.",
"currentPasswordWrong": "La password attuale è sbagliata.",
"changePassword": "Cambia password"
"changePassword": "Cambia password",
"about": "Informazioni"
},
"admin": {
"title": "Admin",
@ -1081,5 +1082,10 @@
"later": "Più tardi",
"install": "Installa Sonda",
"installIntro": "Installa Sonda su questo dispositivo per aprirla come un'app, con la sua icona e nella sua finestra."
},
"version": {
"plain": "Versione {{version}}",
"commit": "Versione {{version}} · {{revision}}",
"changed": "Versione {{version}} · {{revision}} (modificata)"
}
}

View file

@ -26,7 +26,7 @@ function renderSettings() {
}
beforeEach(async () => {
mockFetch({ 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }), 'GET /api/v1/me/mastodon': () => ({ connected: false }) })
mockFetch({ 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }), 'GET /api/v1/me/mastodon': () => ({ connected: false }), 'GET /api/v1/version': () => ({ version: '0.1.0', revision: '69c85a7' }) })
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
initTheme()
@ -241,3 +241,8 @@ test('there is a place to connect a Mastodon account, off until it is connected'
const section = await screen.findByRole('region', { name: 'Mastodon' })
expect(await within(section).findByRole('button', { name: 'Connect' })).toBeInTheDocument()
})
test('the page says which version of Sonda this is', async () => {
renderSettings()
expect(await screen.findByText('Version 0.1.0 · 69c85a7')).toBeInTheDocument()
})

View file

@ -7,6 +7,7 @@ import ChoiceGroup from '@/components/ChoiceGroup'
import ListeningSwitch from '@/components/ListeningSwitch'
import MastodonBlock from '@/components/MastodonBlock'
import Section from '@/components/Section'
import VersionLabel from '@/components/VersionLabel'
import { useInstall } from '@/pwa/useInstall'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@ -194,6 +195,10 @@ export default function SettingsPage() {
<Section title={t('settings.password')}>
<ChangePassword />
</Section>
<Section title={t('settings.about')}>
<VersionLabel />
</Section>
</div>
)
}