Add GET /api/v1/me and /api/v1/home for the native app
Two reads behind the member gate, for the native session:
- me: the member (id, name, email, initials, owner), the Base (name,
slug, origin, time zone), the Appearance (system, light or dark) and
Equipo's origin, null with Ask off.
- home: greeting, lede, steps and every app in Home's order. Oficina
apps carry their icon's fingerprinted URL and bundle ID
works.oficina.<id>, and a URL scheme where their app opens by one
(Calls, Equipo); installed apps and Base's own pages carry the
catalogue's tint and line art, and own pages Base's web URLs.
Home and the API now build from one homeContent, so they can't disagree.
requireMember answers 401 {"code":"unauthenticated"} (no-store, no
redirect) to anything under /api/ and to any request asking for JSON or
an event stream, both with no session and with a session that names
nobody (unlinked, removed, or native past seven days). ask.js already
reads a non-OK answer as unavailable or "didn't send", as before.
make ci: 16 packages ran, 0 failed; test step 15.2s of 60s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+451
−37
internal/config/oficina.go+15 −0internal/web/api.go+148 −0internal/web/app.go+27 −7internal/web/home.go+51 −29internal/webtest/api_test.go+190 −0internal/webtest/native_test.go+13 −0internal/webtest/oficina_harness_test.go+7 −1
diff --git a/internal/config/oficina.go b/internal/config/oficina.go| index 12c10cc..1f85810 100644 |
| --- a/internal/config/oficina.go |
| +++ b/internal/config/oficina.go |
| @@ -20,6 +20,21 @@ var oficinaApps = []struct{ id, name string }{ |
| {"memoria", "Memoria"}, {"calls", "Calls"}, {"fichas", "Fichas"}, {"equipo", "Equipo"}, |
| } |
| +// BundleID is the app's native bundle ID on the Mac and iPhone: every |
| +// Oficina native app is works.oficina.<id> (ruled 2026-11-14). Base's own |
| +// native app opens the app by it when it is installed. |
| +func (o OficinaApp) BundleID() string { return "works.oficina." + o.ID } |
| + |
| +// oficinaSchemes are the URL schemes that open an Oficina app's native app |
| +// on the iPhone, for the apps whose app can be opened by one today. Docs, |
| +// Sheets, Calendar and Memoria answer only …://signin until their apps take |
| +// the kit's …://open, so they open on the web until then. |
| +var oficinaSchemes = map[string]string{"calls": "oficina-calls", "equipo": "works.oficina.equipo"} |
| + |
| +// Scheme is the URL scheme that opens the app's native app, or "" when it |
| +// opens on the web. |
| +func (o OficinaApp) Scheme() string { return oficinaSchemes[o.ID] } |
| + |
| // OficinaIDs is every app id BASE_OFICINA_APPS accepts. |
| func OficinaIDs() []string { |
| ids := make([]string, len(oficinaApps)) |
diff --git a/internal/web/api.go b/internal/web/api.go| new file mode 100644 |
| index 0000000..ffbe10a |
| --- /dev/null |
| +++ b/internal/web/api.go |
| @@ -0,0 +1,148 @@ |
| +package web |
| + |
| +import ( |
| + "net/http" |
| + "strings" |
| + |
| + "amadan.net/carlos/base/internal/look" |
| +) |
| + |
| +// Base's small JSON API for its native app (docs/api/base-native-v1.md): |
| +// reads only, behind the member gate, with the session the native exchange |
| +// minted. Each answer is what the web page of the same name shows, from the |
| +// same builders. |
| + |
| +type apiMember struct { |
| + ID string `json:"id"` |
| + Name string `json:"name"` |
| + Email string `json:"email"` |
| + Initials string `json:"initials"` |
| + Owner bool `json:"owner"` |
| +} |
| + |
| +type apiBase struct { |
| + Name string `json:"name"` |
| + Slug string `json:"slug"` |
| + Origin string `json:"origin"` |
| + Timezone string `json:"timezone"` |
| +} |
| + |
| +type apiMe struct { |
| + Member apiMember `json:"member"` |
| + Base apiBase `json:"base"` |
| + // Appearance is "system", "light" or "dark". |
| + Appearance string `json:"appearance"` |
| + // EquipoOrigin is the Equipo instance Ask Base relays to, null with |
| + // Ask off. The app asks Oficina ID for an assertion addressed to it. |
| + EquipoOrigin *string `json:"equipo_origin"` |
| +} |
| + |
| +// apiMeRead is GET /api/v1/me. |
| +func (a *app) apiMeRead(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + name := displayName(me) |
| + out := apiMe{ |
| + Member: apiMember{ID: me.ID, Name: name, Email: me.Email, Initials: initials(name), Owner: me.Role == "owner"}, |
| + Base: apiBase{Name: a.cfg.Name, Slug: a.cfg.Slug, Origin: a.cfg.Origin, Timezone: "UTC"}, |
| + Appearance: "system", |
| + } |
| + if a.cfg.Timezone != nil { |
| + out.Base.Timezone = a.cfg.Timezone.String() |
| + } |
| + if me.Theme != "" { |
| + out.Appearance = me.Theme |
| + } |
| + if a.ask != nil { |
| + origin := a.cfg.EquipoOrigin |
| + out.EquipoOrigin = &origin |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
| + |
| +type apiStep struct { |
| + Label string `json:"label"` |
| + Done bool `json:"done"` |
| +} |
| + |
| +// apiApp is one app on Home. An Oficina app has its icon at IconURL, a |
| +// path on Base's origin, and its native bundle ID (and, when its native app |
| +// opens by one, a URL scheme); an installed app or one of Base's own pages |
| +// has line art (IconSVG, drawn in currentColor) on a tint, one of the |
| +// catalogue's tint names. |
| +type apiApp struct { |
| + ID string `json:"id"` |
| + Kind string `json:"kind"` |
| + Name string `json:"name"` |
| + URL string `json:"url"` |
| + IconURL string `json:"icon_url,omitempty"` |
| + Tint string `json:"tint,omitempty"` |
| + IconSVG string `json:"icon_svg,omitempty"` |
| + BundleID string `json:"bundle_id,omitempty"` |
| + Scheme string `json:"scheme,omitempty"` |
| +} |
| + |
| +type apiHome struct { |
| + Greeting string `json:"greeting"` |
| + Lede string `json:"lede"` |
| + Steps []apiStep `json:"steps"` |
| + Apps []apiApp `json:"apps"` |
| +} |
| + |
| +// apiHomeRead is GET /api/v1/home: Home's steps and apps, in Home's order |
| +// (the team's Oficina apps, the installed apps, then Base's own pages). |
| +func (a *app) apiHomeRead(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + c, err := a.homeContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("api home", "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + out := apiHome{Greeting: c.Greeting, Lede: c.Lede, Steps: []apiStep{}, Apps: []apiApp{}} |
| + for _, s := range c.Steps { |
| + out.Steps = append(out.Steps, apiStep(s)) |
| + } |
| + bundles := map[string]struct{ bundle, scheme string }{} |
| + for _, o := range a.cfg.OficinaApps { |
| + bundles[o.ID] = struct{ bundle, scheme string }{o.BundleID(), o.Scheme()} |
| + } |
| + for _, t := range append(append([]tile{}, c.Apps...), c.Dock...) { |
| + app := apiApp{ID: t.ID, Kind: t.Kind, Name: t.Name, URL: t.Href} |
| + switch t.Kind { |
| + case "oficina": |
| + app.IconURL = look.Assets.Path(t.Image) |
| + app.BundleID, app.Scheme = bundles[t.ID].bundle, bundles[t.ID].scheme |
| + case "own": |
| + // Base's own pages open on the web. |
| + app.URL = a.cfg.Origin + t.Href |
| + fallthrough |
| + default: |
| + app.Tint, app.IconSVG = t.Tint, string(t.Icon) |
| + } |
| + out.Apps = append(out.Apps, app) |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
| + |
| +// apiError is every JSON refusal's body. |
| +type apiError struct { |
| + Code string `json:"code"` |
| +} |
| + |
| +// apiRequest reports whether a request is the native app's or a script's, |
| +// which hear a refusal as JSON, never as a redirect to /signin: everything |
| +// under /api/, and anything asking for JSON or an event stream. |
| +func apiRequest(r *http.Request) bool { |
| + if strings.HasPrefix(r.URL.Path, "/api/") { |
| + return true |
| + } |
| + accept := r.Header.Get("Accept") |
| + return strings.Contains(accept, "application/json") || strings.Contains(accept, "text/event-stream") |
| +} |
| + |
| +// unauthenticated is the JSON refusal for a request with no session, or one |
| +// that names nobody who is a member now. The native app hears 401 and signs |
| +// in again. |
| +func unauthenticated(w http.ResponseWriter) { |
| + writeJSON(w, http.StatusUnauthorized, apiError{Code: "unauthenticated"}) |
| +} |
diff --git a/internal/web/app.go b/internal/web/app.go| index e621f39..945d507 100644 |
| --- a/internal/web/app.go |
| +++ b/internal/web/app.go |
| @@ -206,6 +206,8 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger |
| r.Post("/store/{app}/uninstall", a.storeUninstall) |
| r.Get("/settings", a.settings) |
| r.Post("/settings/appearance", a.settingsAppearance) |
| + r.Get("/api/v1/me", a.apiMeRead) |
| + r.Get("/api/v1/home", a.apiHomeRead) |
| r.With(ownSignInOnly).Post(registerBeginPath, a.pk.RegisterBegin) |
| r.With(ownSignInOnly).Post(registerFinishPath, a.pk.RegisterFinish) |
| r.Method(http.MethodGet, "/authorize", authorize) |
| @@ -259,11 +261,14 @@ func CurrentMember(r *http.Request) (store.Member, bool) { |
| return m, ok |
| } |
| -// requireMember lets through only a browser session that belongs to a |
| -// current member, and puts that member on the request. A session from Base's |
| -// own sign-in names the member's address; one from Oficina ID names an |
| -// Oficina account, which counts only through a stored link to a member who |
| -// still exists. A signed-out page request goes to /signin. |
| +// requireMember lets through only a session that belongs to a current |
| +// member, and puts that member on the request. A session from Base's own |
| +// sign-in names the member's address; one from Oficina ID (a browser's or |
| +// the native app's) names an Oficina account, which counts only through a |
| +// stored link to a member who still exists. A signed-out page request goes |
| +// to /signin; the native app and scripts (apiRequest) hear |
| +// 401 {"code":"unauthenticated"} instead, for no session or a session that |
| +// names nobody. |
| func (a *app) requireMember(next http.Handler) http.Handler { |
| gate := a.auth.RequireSession |
| if a.oficina != nil { |
| @@ -271,7 +276,7 @@ func (a *app) requireMember(next http.Handler) http.Handler { |
| // /signin/local: a signed-out visitor is offered Oficina first. |
| gate = a.sess.Require |
| } |
| - return gate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + member := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| s, ok := sessions.Current(r) |
| if !ok { |
| @@ -283,12 +288,27 @@ func (a *app) requireMember(next http.Handler) http.Handler { |
| case err != nil: |
| a.logger.Error("member gate", "err", err) |
| http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| + case !found && apiRequest(r): |
| + unauthenticated(w) |
| case !found: |
| http.Error(w, "forbidden", http.StatusForbidden) |
| default: |
| next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, m))) |
| } |
| - })) |
| + }) |
| + paged := gate(member) |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if !apiRequest(r) { |
| + paged.ServeHTTP(w, r) |
| + return |
| + } |
| + s, ok := a.sess.From(r) |
| + if !ok { |
| + unauthenticated(w) |
| + return |
| + } |
| + member.ServeHTTP(w, sessions.WithSession(r, s)) |
| + }) |
| } |
| // memberFor is the member behind session s. found is false for a session |
diff --git a/internal/web/home.go b/internal/web/home.go| index bb793d4..f3b7e5d 100644 |
| --- a/internal/web/home.go |
| +++ b/internal/web/home.go |
| @@ -1,6 +1,8 @@ |
| package web |
| import ( |
| + "context" |
| + "fmt" |
| "html/template" |
| "net/http" |
| "strings" |
| @@ -19,13 +21,17 @@ type step struct { |
| // pages. Its icon is an image (Image, a path in the static tree for |
| // {{asset}}: an Oficina app's) or line art on a tint (Icon and Tint). |
| type tile struct { |
| - Name string |
| - Href string |
| - Tint string |
| - Icon template.HTML |
| - Image string |
| - NewTab bool // an Oficina app, which opens in a new tab |
| - Own bool // one of Base's own pages, which start a row of their own |
| + // ID names the app: an Oficina app's id, a catalogue app's, or the |
| + // page's ("store", "people", "settings"). Kind is "oficina", |
| + // "installed" or "own". |
| + ID, Kind string |
| + Name string |
| + Href string |
| + Tint string |
| + Icon template.HTML |
| + Image string |
| + NewTab bool // an Oficina app, which opens in a new tab |
| + Own bool // one of Base's own pages, which start a row of their own |
| } |
| type homePage struct { |
| @@ -98,29 +104,33 @@ func greeting(t time.Time, loc *time.Location, name string) string { |
| // chat's conversation before it draws the chat without it. |
| const homeSnapshotWait = 1500 * time.Millisecond |
| -func (a *app) home(w http.ResponseWriter, r *http.Request) { |
| - me, _ := CurrentMember(r) |
| - ms, err := store.Members(r.Context(), a.db) |
| +// homeContent is what Home shows a member, apart from the chat: the |
| +// greeting, the steps and every app in Home's order. Home and GET |
| +// /api/v1/home both draw from it, so they cannot disagree. |
| +type homeContent struct { |
| + Greeting, Initials, Lede string |
| + Steps []step |
| + Apps, Dock []tile |
| +} |
| + |
| +func (a *app) homeContent(ctx context.Context, me store.Member) (homeContent, error) { |
| + ms, err := store.Members(ctx, a.db) |
| if err != nil { |
| - a.logger.Error("home: members", "err", err) |
| - http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| - return |
| + return homeContent{}, fmt.Errorf("members: %w", err) |
| } |
| - installs, err := store.Installs(r.Context(), a.db) |
| + installs, err := store.Installs(ctx, a.db) |
| if err != nil { |
| - a.logger.Error("home: installs", "err", err) |
| - http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| - return |
| + return homeContent{}, fmt.Errorf("installs: %w", err) |
| } |
| name := displayName(me) |
| - page := homePage{Name: a.cfg.Name, Greeting: greeting(time.Now(), a.cfg.Timezone, name), Initials: initials(name)} |
| - page.Dock = []tile{ |
| - {Name: "Store", Href: "/store", Tint: "teal", Icon: iconStore, Own: true}, |
| - {Name: "People", Href: "/people", Tint: "violet", Icon: iconPeople, Own: true}, |
| - {Name: "Settings", Href: "/settings", Tint: "mist", Icon: iconSettings, Own: true}, |
| + c := homeContent{Greeting: greeting(time.Now(), a.cfg.Timezone, name), Initials: initials(name)} |
| + c.Dock = []tile{ |
| + {ID: "store", Kind: "own", Name: "Store", Href: "/store", Tint: "teal", Icon: iconStore, Own: true}, |
| + {ID: "people", Kind: "own", Name: "People", Href: "/people", Tint: "violet", Icon: iconPeople, Own: true}, |
| + {ID: "settings", Kind: "own", Name: "Settings", Href: "/settings", Tint: "mist", Icon: iconSettings, Own: true}, |
| } |
| for _, o := range a.cfg.OficinaApps { |
| - page.Apps = append(page.Apps, tile{Name: o.Name, Href: o.Origin + "/", Image: "static/oficina/" + o.ID + ".svg", NewTab: true}) |
| + c.Apps = append(c.Apps, tile{ID: o.ID, Kind: "oficina", Name: o.Name, Href: o.Origin + "/", Image: "static/oficina/" + o.ID + ".svg", NewTab: true}) |
| } |
| installedOwn := false |
| for _, in := range installs { |
| @@ -129,30 +139,42 @@ func (a *app) home(w http.ResponseWriter, r *http.Request) { |
| continue |
| } |
| // The host the app was installed at: config may name another now. |
| - page.Apps = append(page.Apps, tile{Name: e.Name, Href: "https://" + in.Host + "/", Tint: e.Tint, Icon: template.HTML(e.Icon)}) |
| + c.Apps = append(c.Apps, tile{ID: in.App, Kind: "installed", Name: e.Name, Href: "https://" + in.Host + "/", Tint: e.Tint, Icon: template.HTML(e.Icon)}) |
| if !e.Default { |
| installedOwn = true |
| } |
| } |
| - page.Steps = []step{ |
| + c.Steps = []step{ |
| {"Signed in", true}, |
| {"Invite your team", len(ms) > 1}, |
| {"Install your first app", installedOwn}, |
| } |
| left := 0 |
| - for _, s := range page.Steps { |
| + for _, s := range c.Steps { |
| if !s.Done { |
| left++ |
| } |
| } |
| switch left { |
| case 0: |
| - page.Lede = a.cfg.Name + "'s Base is ready." |
| + c.Lede = a.cfg.Name + "'s Base is ready." |
| case 1: |
| - page.Lede = "One step until " + a.cfg.Name + "'s Base is ready." |
| + c.Lede = "One step until " + a.cfg.Name + "'s Base is ready." |
| default: |
| - page.Lede = "Two steps until " + a.cfg.Name + "'s Base is ready." |
| + c.Lede = "Two steps until " + a.cfg.Name + "'s Base is ready." |
| + } |
| + return c, nil |
| +} |
| + |
| +func (a *app) home(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + c, err := a.homeContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("home", "err", err) |
| + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| + return |
| } |
| + page := homePage{Name: a.cfg.Name, Greeting: c.Greeting, Initials: c.Initials, Lede: c.Lede, Steps: c.Steps, Apps: c.Apps, Dock: c.Dock} |
| if a.ask != nil { |
| l, sec, state, err := a.askLink(r.Context(), me) |
| if err != nil { |
diff --git a/internal/webtest/api_test.go b/internal/webtest/api_test.go| new file mode 100644 |
| index 0000000..2bd9ea9 |
| --- /dev/null |
| +++ b/internal/webtest/api_test.go |
| @@ -0,0 +1,190 @@ |
| +package webtest |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| + "reflect" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/store" |
| +) |
| + |
| +// GET /api/v1/me and GET /api/v1/home: Base's reads for its native app |
| +// (docs/api/base-native-v1.md), with the session the native exchange mints. |
| + |
| +func decode[T any](t *testing.T, r Resp) T { |
| + t.Helper() |
| + var v T |
| + if err := json.Unmarshal([]byte(r.Body), &v); err != nil { |
| + t.Fatalf("%d %q: %v", r.Code, r.Body, err) |
| + } |
| + return v |
| +} |
| + |
| +func TestAPIMe(t *testing.T) { |
| + dublin, _ := time.LoadLocation("Europe/Dublin") |
| + a := newHomeAppWith(t, func(c *config.Config) { c.Timezone = dublin }) |
| + a.link(ownerAddress, "subject-owner") |
| + app := a.nativeSignIn("subject-owner") |
| + r := app.nativeGet("/api/v1/me") |
| + if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" || r.Header.Get("Content-Type") != "application/json" { |
| + t.Fatalf("me: %d %q %q", r.Code, r.Header.Get("Cache-Control"), r.Header.Get("Content-Type")) |
| + } |
| + got := decode[map[string]any](t, r) |
| + want := map[string]any{ |
| + "member": map[string]any{"id": a.ownerID(), "name": "Owner", "email": ownerAddress, "initials": "O", "owner": true}, |
| + "base": map[string]any{"name": "Acme", "slug": "acme", "origin": homeOrigin, "timezone": "Europe/Dublin"}, |
| + "appearance": "system", |
| + "equipo_origin": nil, |
| + } |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("me:\n got %v\nwant %v", got, want) |
| + } |
| + |
| + // The member's Appearance, a member who is not the owner, and Ask on. |
| + b := newHomeAppWith(t, func(c *config.Config) { c.EquipoOrigin = "https://equipo.acme.test" }) |
| + ana, _, err := store.Invite(t.Context(), b.DB, "ana.ruiz@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := store.SetTheme(t.Context(), b.DB, ana.ID, "dark"); err != nil { |
| + t.Fatal(err) |
| + } |
| + b.link("ana.ruiz@acme.test", "subject-ana") |
| + me := decode[apiMeShape](t, b.nativeSignIn("subject-ana").nativeGet("/api/v1/me")) |
| + if me.Member.Owner || me.Member.Email != "ana.ruiz@acme.test" || me.Member.Name != "Ana.ruiz" || me.Appearance != "dark" || |
| + me.EquipoOrigin == nil || *me.EquipoOrigin != "https://equipo.acme.test" || me.Base.Timezone != "UTC" { |
| + t.Fatalf("ana: %+v", me) |
| + } |
| +} |
| + |
| +type apiMeShape struct { |
| + Member struct { |
| + ID, Name, Email, Initials string |
| + Owner bool |
| + } |
| + Base struct{ Name, Slug, Origin, Timezone string } |
| + Appearance string |
| + EquipoOrigin *string `json:"equipo_origin"` |
| +} |
| + |
| +type apiAppShape struct { |
| + ID string `json:"id"` |
| + Kind string `json:"kind"` |
| + Name string `json:"name"` |
| + URL string `json:"url"` |
| + IconURL string `json:"icon_url"` |
| + Tint string `json:"tint"` |
| + IconSVG string `json:"icon_svg"` |
| + BundleID string `json:"bundle_id"` |
| + Scheme string `json:"scheme"` |
| +} |
| + |
| +type apiHomeShape struct { |
| + Greeting string `json:"greeting"` |
| + Lede string `json:"lede"` |
| + Steps []struct { |
| + Label string `json:"label"` |
| + Done bool `json:"done"` |
| + } `json:"steps"` |
| + Apps []apiAppShape `json:"apps"` |
| +} |
| + |
| +func TestAPIHome(t *testing.T) { |
| + a := newHomeAppWith(t, func(c *config.Config) { |
| + c.OficinaApps = []config.OficinaApp{ |
| + {ID: "docs", Name: "Docs", Origin: "https://docs.oficina.works"}, |
| + {ID: "calls", Name: "Calls", Origin: "https://calls.oficina.works"}, |
| + } |
| + }) |
| + a.link(ownerAddress, "subject-owner") |
| + a.setInstall("scratchpad", "installed", "") |
| + app := a.nativeSignIn("subject-owner") |
| + r := app.nativeGet("/api/v1/home") |
| + if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" { |
| + t.Fatalf("home: %d %q", r.Code, r.Header.Get("Cache-Control")) |
| + } |
| + var raw map[string]json.RawMessage |
| + if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 4 { |
| + t.Fatalf("home's keys: %v %s", err, r.Body) |
| + } |
| + h := decode[apiHomeShape](t, r) |
| + if !regexp.MustCompile(`^(Hello|Good (morning|afternoon|evening)), Owner\.$`).MatchString(h.Greeting) { |
| + t.Errorf("greeting %q", h.Greeting) |
| + } |
| + if h.Lede != "One step until Acme's Base is ready." { |
| + t.Errorf("lede %q", h.Lede) |
| + } |
| + steps := []string{} |
| + for _, s := range h.Steps { |
| + steps = append(steps, s.Label+"="+map[bool]string{true: "done", false: "open"}[s.Done]) |
| + } |
| + if got := strings.Join(steps, ", "); got != "Signed in=done, Invite your team=open, Install your first app=done" { |
| + t.Errorf("steps: %s", got) |
| + } |
| + var order []string |
| + for _, x := range h.Apps { |
| + order = append(order, x.Kind+":"+x.ID) |
| + } |
| + if got := strings.Join(order, " "); got != "oficina:docs oficina:calls installed:scratchpad own:store own:people own:settings" { |
| + t.Fatalf("apps in order: %s", got) |
| + } |
| + icon := regexp.MustCompile(`^/static/oficina/docs\.[0-9a-f]+\.svg$`) |
| + docs, calls, scratch, store := h.Apps[0], h.Apps[1], h.Apps[2], h.Apps[3] |
| + if docs.Name != "Docs" || docs.URL != "https://docs.oficina.works/" || !icon.MatchString(docs.IconURL) || docs.BundleID != "works.oficina.docs" || |
| + docs.Scheme != "" || docs.Tint != "" || docs.IconSVG != "" { |
| + t.Errorf("docs: %+v", docs) |
| + } |
| + if calls.BundleID != "works.oficina.calls" || calls.Scheme != "oficina-calls" { |
| + t.Errorf("calls: %+v", calls) |
| + } |
| + if scratch.Name != "Scratchpad" || scratch.URL != "https://acme-scratchpad.bab.oncarlos.com/" || scratch.Tint != "rose" || |
| + !strings.HasPrefix(scratch.IconSVG, "<svg") || scratch.IconURL != "" || scratch.BundleID != "" { |
| + t.Errorf("scratchpad: %+v", scratch) |
| + } |
| + if store.Name != "Store" || store.URL != homeOrigin+"/store" || store.Tint != "teal" || !strings.HasPrefix(store.IconSVG, "<svg") { |
| + t.Errorf("store: %+v", store) |
| + } |
| + // The icon is served where it says. |
| + if r := app.get(docs.IconURL); r.Code != 200 || !strings.Contains(r.Body, "<svg") { |
| + t.Errorf("GET %s: %d", docs.IconURL, r.Code) |
| + } |
| +} |
| + |
| +// The native app and scripts hear a refusal as JSON, never as a redirect. |
| +func TestAPIRefusesWithoutSession(t *testing.T) { |
| + a := newHomeAppWith(t, func(c *config.Config) { c.EquipoOrigin = "https://equipo.acme.test" }) |
| + a.link(ownerAddress, "subject-owner") |
| + refused := func(where string, r Resp) { |
| + t.Helper() |
| + if r.Code != http.StatusUnauthorized || strings.TrimSpace(r.Body) != `{"code":"unauthenticated"}` || |
| + r.Header.Get("Cache-Control") != "no-store" || r.Location() != "" { |
| + t.Errorf("%s: %d %q %q %q", where, r.Code, r.Body, r.Header.Get("Cache-Control"), r.Location()) |
| + } |
| + } |
| + none := a.newBrowser() |
| + refused("no session, /api/v1/me", none.get("/api/v1/me")) |
| + refused("no session, /api/v1/home", none.nativeGet("/api/v1/home")) |
| + refused("no session, /ask/state as JSON", none.nativeGet("/ask/state")) |
| + refused("no session, POST /ask/messages as JSON", none.nativePost("/ask/messages", "")) |
| + // A session that names nobody: unlinked, or a native one past seven days. |
| + refused("unlinked", a.storedSession("subject-stranger", "home-assertion-native", time.Now()).nativeGet("/api/v1/me")) |
| + refused("expired", a.storedSession("subject-owner", "home-assertion-native", time.Now().Add(-8*24*time.Hour)).nativeGet("/api/v1/me")) |
| + // A signed-out page still goes to /signin. |
| + if r := none.get("/"); r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Location(), "/signin") { |
| + t.Errorf("signed-out page: %d %q", r.Code, r.Location()) |
| + } |
| + // Without Oficina ID, the same. |
| + b := newApp(t) |
| + if r := b.get("/api/v1/me"); r.Code != http.StatusUnauthorized || strings.TrimSpace(r.Body) != `{"code":"unauthenticated"}` { |
| + t.Errorf("Oficina off, /api/v1/me: %d %q", r.Code, r.Body) |
| + } |
| + b.signedInOwner() |
| + if r := b.get("/api/v1/me"); r.Code != 200 { |
| + t.Errorf("Oficina off, signed in: %d", r.Code) |
| + } |
| +} |
diff --git a/internal/webtest/native_test.go b/internal/webtest/native_test.go| index cb3d474..1641167 100644 |
| --- a/internal/webtest/native_test.go |
| +++ b/internal/webtest/native_test.go |
| @@ -50,6 +50,16 @@ func (a *testApp) withSession(token string) *testApp { |
| return b |
| } |
| +// nativeGet is a GET as the native app makes it: the cookie, Origin and |
| +// Accept: application/json, and no Sec-Fetch-Site. |
| +func (a *testApp) nativeGet(target string) Resp { |
| + a.t.Helper() |
| + req, _ := http.NewRequest(http.MethodGet, a.base+target, nil) |
| + req.Header.Set("Origin", homeOrigin) |
| + req.Header.Set("Accept", "application/json") |
| + return a.do(req) |
| +} |
| + |
| // nativePost is a JSON POST as the native app makes it. |
| func (a *testApp) nativePost(target, body string) Resp { |
| a.t.Helper() |
| @@ -194,6 +204,9 @@ func TestNativeExchangeMintsASession(t *testing.T) { |
| if home := a.withSession(answer.Value).get("/"); home.Code != 200 { |
| t.Fatalf("the minted session, GET /: %d %q", home.Code, home.Location()) |
| } |
| + if me := a.withSession(answer.Value).nativeGet("/api/v1/me"); me.Code != 200 || !strings.Contains(me.Body, ownerAddress) { |
| + t.Fatalf("the minted session, GET /api/v1/me: %d %s", me.Code, me.Body) |
| + } |
| } |
| func TestNativeExchangeUnknownPerson(t *testing.T) { |
diff --git a/internal/webtest/oficina_harness_test.go b/internal/webtest/oficina_harness_test.go| index e4767f6..738d629 100644 |
| --- a/internal/webtest/oficina_harness_test.go |
| +++ b/internal/webtest/oficina_harness_test.go |
| @@ -53,7 +53,10 @@ type oficina struct { |
| // newHomeApp builds Base exactly as main.go does with every BASE_HOME_* |
| // setting present, with an assertion key so it can hand off to apps too. |
| -func newHomeApp(t *testing.T) *testApp { |
| +func newHomeApp(t *testing.T) *testApp { return newHomeAppWith(t, nil) } |
| + |
| +// newHomeAppWith is newHomeApp with a last say over the configuration. |
| +func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp { |
| t.Helper() |
| logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| d, err := db.Open(homeSchema.Path(t), logger) |
| @@ -83,6 +86,9 @@ func newHomeApp(t *testing.T) *testApp { |
| } |
| cfg := config.Config{Origin: homeOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true, |
| Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: time.UTC, AssertionKey: signing, Home: home} |
| + if tweak != nil { |
| + tweak(&cfg) |
| + } |
| mailer := &capturingMailer{} |
| h, err := web.App(d, cfg, mailer, noInstaller{}, logger) |
| if err != nil { |