From 00e5254fdeb5b5cfa174d95a13a929c3a8be25fd Mon Sep 17 00:00:00 2001 From: tgiachi Date: Sun, 15 Nov 2026 17:30:14 +0100 Subject: [PATCH] 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 --- cmd/sondad/buildinfo.go | 41 +++++++++++++++++ cmd/sondad/buildinfo_test.go | 43 ++++++++++++++++++ cmd/sondad/main.go | 1 + internal/api/http/contract_test.go | 3 ++ internal/api/http/handlers_version_test.go | 33 ++++++++++++++ internal/api/http/router.go | 10 +++++ internal/api/openapi/openapi.yaml | 29 ++++++++++++ web/src/api/schema.d.ts | 52 ++++++++++++++++++++++ web/src/api/version.ts | 18 ++++++++ web/src/components/VersionLabel.test.tsx | 48 ++++++++++++++++++++ web/src/components/VersionLabel.tsx | 14 ++++++ web/src/components/layout/Shell.test.tsx | 10 ++--- web/src/components/layout/Sidebar.test.tsx | 9 +++- web/src/components/layout/Sidebar.tsx | 8 +++- web/src/i18n/locales/en.json | 8 +++- web/src/i18n/locales/it.json | 8 +++- web/src/pages/SettingsPage.test.tsx | 7 ++- web/src/pages/SettingsPage.tsx | 5 +++ 18 files changed, 337 insertions(+), 10 deletions(-) create mode 100644 cmd/sondad/buildinfo.go create mode 100644 cmd/sondad/buildinfo_test.go create mode 100644 internal/api/http/handlers_version_test.go create mode 100644 web/src/api/version.ts create mode 100644 web/src/components/VersionLabel.test.tsx create mode 100644 web/src/components/VersionLabel.tsx diff --git a/cmd/sondad/buildinfo.go b/cmd/sondad/buildinfo.go new file mode 100644 index 0000000..8e2a7f9 --- /dev/null +++ b/cmd/sondad/buildinfo.go @@ -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} +} diff --git a/cmd/sondad/buildinfo_test.go b/cmd/sondad/buildinfo_test.go new file mode 100644 index 0000000..9c353ce --- /dev/null +++ b/cmd/sondad/buildinfo_test.go @@ -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) + } +} diff --git a/cmd/sondad/main.go b/cmd/sondad/main.go index b0f7090..94fa00a 100644 --- a/cmd/sondad/main.go +++ b/cmd/sondad/main.go @@ -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()), diff --git a/internal/api/http/contract_test.go b/internal/api/http/contract_test.go index 48fd986..c79a521 100644 --- a/internal/api/http/contract_test.go +++ b/internal/api/http/contract_test.go @@ -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") diff --git a/internal/api/http/handlers_version_test.go b/internal/api/http/handlers_version_test.go new file mode 100644 index 0000000..233c93d --- /dev/null +++ b/internal/api/http/handlers_version_test.go @@ -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) + } +} diff --git a/internal/api/http/router.go b/internal/api/http/router.go index d30d4c0..f12300e 100644 --- a/internal/api/http/router.go +++ b/internal/api/http/router.go @@ -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) diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml index d2ce831..31f8031 100644 --- a/internal/api/openapi/openapi.yaml +++ b/internal/api/openapi/openapi.yaml @@ -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] diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index c0db685..f484490 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -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; diff --git a/web/src/api/version.ts b/web/src/api/version.ts new file mode 100644 index 0000000..f889f5d --- /dev/null +++ b/web/src/api/version.ts @@ -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'), + staleTime: Infinity, + retry: false, + }) +} diff --git a/web/src/components/VersionLabel.test.tsx b/web/src/components/VersionLabel.test.tsx new file mode 100644 index 0000000..8a59f71 --- /dev/null +++ b/web/src/components/VersionLabel.test.tsx @@ -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( + + + , + ) +} + +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( + + + , + ) + await vi.waitFor(() => expect(calls).toHaveLength(1)) + expect(container).toBeEmptyDOMElement() +}) diff --git a/web/src/components/VersionLabel.tsx b/web/src/components/VersionLabel.tsx new file mode 100644 index 0000000..a4db827 --- /dev/null +++ b/web/src/components/VersionLabel.tsx @@ -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

{t(key, { version: data.version, revision: data.revision })}

+} diff --git a/web/src/components/layout/Shell.test.tsx b/web/src/components/layout/Shell.test.tsx index 09f6be1..a230c2b 100644 --- a/web/src/components/layout/Shell.test.tsx +++ b/web/src/components/layout/Shell.test.tsx @@ -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 () => { diff --git a/web/src/components/layout/Sidebar.test.tsx b/web/src/components/layout/Sidebar.test.tsx index 98eea66..0836f4a 100644 --- a/web/src/components/layout/Sidebar.test.tsx +++ b/web/src/components/layout/Sidebar.test.tsx @@ -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( @@ -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') diff --git a/web/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx index dde745d..e6c440c 100644 --- a/web/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -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() { ))} - {!collapsed &&

{t('app.privacy')}

} + {!collapsed && ( +
+

{t('app.privacy')}

+ +
+ )} ) } diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index fe7afad..8b54cea 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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)" } } diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index e30610f..3705d87 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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)" } } diff --git a/web/src/pages/SettingsPage.test.tsx b/web/src/pages/SettingsPage.test.tsx index 37699ae..edd47b8 100644 --- a/web/src/pages/SettingsPage.test.tsx +++ b/web/src/pages/SettingsPage.test.tsx @@ -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() +}) diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx index dc8097f..77382b9 100644 --- a/web/src/pages/SettingsPage.tsx +++ b/web/src/pages/SettingsPage.tsx @@ -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() {
+ +
+ +
) }