Files
pansy/internal/service/service.go
T
steveandClaude Opus 4.8 f3b0ca572d
Build image / build-and-push (push) Successful in 8s
Gadfly review (reusable) / review (pull_request) Successful in 10m11s
Adversarial Review (Gadfly) / review (pull_request) Successful in 10m11s
Public read-only share link (#41)
A per-garden public link anyone can open read-only, with no login and no OIDC.

Backend:
- Migration 0004 adds gardens.public_token (nullable, unique over non-NULL).
- Owner-only management: GET/POST/DELETE /gardens/:id/share-link (state /
  enable-or-rotate / disable). The token is stored raw (it must be shown back
  to the owner) and never selected into the normal garden payload.
- Unauthenticated GET /api/v1/public/gardens/:token returns the read-only /full
  payload — the token is the capability, so no requireAuth and no redirect. The
  public view drops MyRole and OwnerID to minimize what an anonymous viewer
  learns. Unknown/rotated/disabled tokens are masked as 404.
- assembleFull is extracted from GardenFull so both reads return one shape.

Frontend:
- /g/$token route with NO auth guard (SPA fallback already serves it), rendering
  GardenCanvas read-only via usePublicGarden.
- Share dialog gains a Public link section: create, copy, regenerate, turn off.

Tests: service lifecycle + ACL (owner-only, non-owner masked, rotate/disable
invalidation) and the HTTP surface incl. the cookieless public read.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
2026-07-19 02:04:11 -04:00

87 lines
3.3 KiB
Go

// Package service is pansy's business-logic seam: all permission checks and
// invariants live here rather than in the HTTP handlers. Resource operations
// take (ctx, actor, args) so every rule is enforced regardless of caller; the
// auth operations here are the exception — they establish the actor, so they
// take credentials rather than one. REST handlers (internal/api) and, later,
// agent tools (internal/agent) are thin adapters over these methods, so both
// inherit the same rules. This file holds the shared plumbing; feature methods
// live alongside it (auth.go, and gardens/objects/… in later issues).
package service
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"time"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/config"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/store"
)
// timeLayout is the ISO-8601 UTC format used for every full timestamp pansy
// stores (created_at/updated_at/expires_at). It matches the schema's
// strftime('%Y-%m-%dT%H:%M:%SZ') so string comparison (e.g. session expiry) is
// equivalent to time comparison. Date-only fields (planting planted_at/
// removed_at) use dateLayout instead.
const timeLayout = "2006-01-02T15:04:05Z"
// sessionTTL is how long a session lives from its last use (sliding expiry).
const sessionTTL = 30 * 24 * time.Hour
// Service holds the dependencies shared by every operation.
type Service struct {
store *store.DB
cfg *config.Config
// now is the clock, injectable so tests can advance time (session expiry).
now func() time.Time
// dummyHash is a valid argon2id hash Login verifies against when an email is
// unknown, so response time doesn't reveal whether an account exists. It is
// produced by timingHash (fixed salt, no RNG) so it is always present — an
// empty one would silently re-open account enumeration.
dummyHash string
}
// New constructs a Service.
func New(st *store.DB, cfg *config.Config) *Service {
return &Service{
store: st,
cfg: cfg,
now: time.Now,
dummyHash: timingHash(),
}
}
// formatTime renders a time as pansy's canonical UTC string.
func formatTime(t time.Time) string { return t.UTC().Format(timeLayout) }
// parseTime parses a canonical pansy timestamp.
func parseTime(s string) (time.Time, error) { return time.Parse(timeLayout, s) }
// randToken returns nBytes of cryptographic randomness as a URL-safe string.
func randToken(nBytes int) (string, error) {
b := make([]byte, nBytes)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("service: generate token: %w", err)
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// newSessionToken returns a fresh URL-safe random bearer token (32 bytes of
// entropy). The raw token goes in the cookie; only its hash is persisted.
func newSessionToken() (string, error) { return randToken(32) }
// newPublicToken returns a fresh unguessable token for a garden's public share
// link (18 bytes → 144 bits; a 24-char URL segment). Unlike a session token it's
// stored raw (it must be shown back to the owner to copy) and grants only
// read-only access to one garden.
func newPublicToken() (string, error) { return randToken(18) }
// hashToken maps a raw bearer token to the hex sha256 stored as the session's
// primary key.
func hashToken(raw string) string {
sum := sha256.Sum256([]byte(raw))
return hex.EncodeToString(sum[:])
}