oficina / fichas Public

Clone
git clone https://amadan.net/oficina/fichas

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3import (
4 "amadan.net/oficina/estilo.git/chrome"
5 "amadan.net/rastrillo/rastrillo/ui"
6 "crypto/ed25519"
7 "crypto/sha256"
8 "encoding/base64"
9 "errors"
10 "net/http"
11 "net/url"
12 "strconv"
13 "strings"
14 "time"
15
16 json "github.com/go-json-experiment/json"
17 "github.com/google/uuid"
18 "gorm.io/gorm"
19)
20
21// ContractReleaseConfig pairs one importer and one destination in an explicit
22// trusted team binding. It does not grant suite identity or general S3 access.
23type ContractReleaseConfig struct {
24 Destination, Importer, Team string
25 Key ed25519.PrivateKey
26}
27type releaseField struct {
28 Key string `json:"key"`
29 Label string `json:"label"`
30 Kind string `json:"kind"`
31 Value string `json:"value"`
32}
33type releaseEnvelope struct {
34 Version int `json:"version"`
35 Source string `json:"source"`
36 Destination string `json:"destination"`
37 Team string `json:"team"`
38 Purpose string `json:"purpose"`
39 Importer string `json:"importer"`
40 Actor string `json:"actor"`
41 Flow string `json:"flow"`
42 ID string `json:"id"`
43 Card int64 `json:"card"`
44 Revision int64 `json:"revision"`
45 Issued int64 `json:"issued"`
46 Expires int64 `json:"expires"`
47 Fields []releaseField `json:"fields"`
48}
49
50const releasePurpose = "oficina.contract.self-sign.v1"
51
52var errRelease = errors.New("fichas: contract release refused")
53
54func releaseOrigin(s string) bool {
55 u, e := url.Parse(s)
56 return e == nil && u.Scheme == "https" && u.Host != "" && u.User == nil && u.Path == "" && u.RawQuery == "" && u.Fragment == "" && !u.ForceQuery
57}
58func loadContractRelease(getenv func(string) string, source string) (*ContractReleaseConfig, error) {
59 dest, key, importer, team := getenv("FICHAS_CONTRACT_DESTINATION"), getenv("FICHAS_CONTRACT_SEED"), getenv("FICHAS_CONTRACT_IMPORTER"), getenv("FICHAS_CONTRACT_TEAM")
60 if dest == "" && key == "" && importer == "" && team == "" {
61 return nil, nil
62 }
63 seed, e := base64.StdEncoding.DecodeString(key)
64 if e != nil || len(seed) != ed25519.SeedSize || !releaseOrigin(source) || !releaseOrigin(dest) || source == dest || !releaseTeam(source, team) || !releaseTeam(dest, team) || importer == "" || importer != normaliseAddress(importer) || !strings.Contains(importer, "@") || team == "" || len(team) > 64 {
65 return nil, errRelease
66 }
67 return &ContractReleaseConfig{Destination: dest, Importer: importer, Team: team, Key: ed25519.NewKeyFromSeed(seed)}, nil
68}
69
70type contractReleasePage struct {
71 Nav []NavItem
72 Account *chrome.Account
73 // The frame every shell page draws (level-up §3).
74 Bar chrome.Bar
75 L *ui.Localizer
76 Rail, Here, Search string
77
78 Theme, Flow, Phase, Payload, Signature, Destination, Importer, Error string
79 Cards []CardView
80 Card *CardView
81 Release *releaseEnvelope
82}
83
84func (a *app) contractPage(w http.ResponseWriter, r *http.Request, p contractReleasePage) {
85 w.Header().Set("Cache-Control", "no-store")
86 w.Header().Set("Referrer-Policy", "no-referrer")
87 p.Theme = themeAttr(r)
88 p.Nav, _ = a.nav(r, "")
89 address, _ := a.identity(r)
90 p.Account = a.account(r, address)
91 frame := map[string]any{}
92 if err := a.buildFrame(r, "contract_prepare", frame, p.Nav); err != nil {
93 a.fail(w, r, err)
94 return
95 }
96 p.Bar, _ = frame["Bar"].(chrome.Bar)
97 p.Rail, _ = frame["Rail"].(string)
98 p.Here, _ = frame["Here"].(string)
99 p.Search, _ = frame["Search"].(string)
100 p.L = a.readerL(r)
101 p.Destination = a.cfg.ContractRelease.Destination
102 p.Importer = a.cfg.ContractRelease.Importer
103 if p.Phase == "send" {
104 // A no-referrer policy makes a cross-origin POST carry Origin: null.
105 // Docs requires our exact origin; disclose only the origin, never the path.
106 w.Header().Set("Referrer-Policy", "strict-origin")
107 // Scope the exact destination to this single outbound form page.
108 policy := w.Header().Get("Content-Security-Policy")
109 if strings.Contains(policy, "form-action 'self'") {
110 policy = strings.Replace(policy, "form-action 'self'", "form-action 'self' "+p.Destination, 1)
111 } else {
112 policy = "default-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self' " + p.Destination
113 }
114 w.Header().Set("Content-Security-Policy", policy)
115 }
116 render(w, "contract_prepare", p)
117}
118func (a *app) contractPrepare(w http.ResponseWriter, r *http.Request) {
119 flow := r.URL.Query().Get("flow")
120 if _, e := uuid.Parse(flow); e != nil {
121 notFound(w, r)
122 return
123 }
124 p := contractReleasePage{Flow: flow, Phase: "choose"}
125 if id, e := strconv.ParseInt(r.URL.Query().Get("card"), 10, 64); e == nil && id > 0 {
126 c, e := LoadCard(r.Context(), a.db.G, a.sealer, id)
127 if e != nil {
128 notFound(w, r)
129 return
130 }
131 p.Card = &c
132 p.Phase = "fields"
133 } else {
134 cards, e := ListCards(r.Context(), a.db.G, a.sealer, TypeCustomer)
135 if e != nil {
136 http.Error(w, "Customers are unavailable.", 503)
137 return
138 }
139 p.Cards = cards
140 }
141 a.contractPage(w, r, p)
142}
143func releaseFields(c CardView, keys []string) ([]releaseField, error) {
144 if len(keys) == 0 || len(keys) > 32 {
145 return nil, errRelease
146 }
147 out := []releaseField{}
148 seen := map[string]bool{}
149 for _, key := range keys {
150 if seen[key] {
151 return nil, errRelease
152 }
153 seen[key] = true
154 f := c.Field(key)
155 kind, ok := releaseKind(f.Def.Kind)
156 if f.Def.Key == "" || !ok || len(f.Value) > 8192 || len(f.Label) > 256 {
157 return nil, errRelease
158 }
159 out = append(out, releaseField{key, f.Label, kind, f.Value})
160 }
161 return out, nil
162}
163func (a *app) contractReview(w http.ResponseWriter, r *http.Request) {
164 r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
165 if r.ParseForm() != nil {
166 http.Error(w, "Invalid selection.", 400)
167 return
168 }
169 flow := r.PostForm.Get("flow")
170 if _, e := uuid.Parse(flow); e != nil {
171 notFound(w, r)
172 return
173 }
174 id, _ := strconv.ParseInt(r.PostForm.Get("card"), 10, 64)
175 rev, _ := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64)
176 actor, ok := a.identity(r)
177 if !ok || !a.Admit(actor) {
178 notFound(w, r)
179 return
180 }
181 var rel releaseEnvelope
182 e := a.db.G.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
183 c, e := LoadCard(r.Context(), tx, a.sealer, id)
184 if e != nil {
185 return e
186 }
187 if c.Card.Revision != rev {
188 return errRelease
189 }
190 fields, e := releaseFields(c, r.PostForm["field"])
191 if e != nil {
192 return e
193 }
194 now := time.Now().Unix()
195 cfg := a.cfg.ContractRelease
196 rel = releaseEnvelope{Version: 1, Source: a.cfg.Origin, Destination: cfg.Destination, Team: cfg.Team, Purpose: "confirm:" + releasePurpose, Importer: cfg.Importer, Actor: actor, Flow: flow, ID: uuid.NewString(), Card: id, Revision: rev, Issued: now, Expires: now + 600, Fields: fields}
197 return nil
198 })
199 if e != nil {
200 http.Error(w, "The card changed or the selected fields cannot be used. Return to the customer and try again.", 409)
201 return
202 }
203 raw, e := json.Marshal(rel)
204 if e != nil || len(raw) > 64<<10 {
205 http.Error(w, "The selection is too large.", 400)
206 return
207 }
208 a.contractPage(w, r, contractReleasePage{Flow: flow, Phase: "review", Release: &rel, Payload: base64.RawURLEncoding.EncodeToString(raw), Signature: base64.RawURLEncoding.EncodeToString(ed25519.Sign(a.cfg.ContractRelease.Key, raw))})
209}
210func (a *app) contractApprove(w http.ResponseWriter, r *http.Request) {
211 r.Body = http.MaxBytesReader(w, r.Body, 128<<10)
212 if r.ParseForm() != nil {
213 http.Error(w, "Invalid approval.", 400)
214 return
215 }
216 raw, e := base64.RawURLEncoding.DecodeString(r.PostForm.Get("payload"))
217 sig, se := base64.RawURLEncoding.DecodeString(r.PostForm.Get("signature"))
218 cfg := a.cfg.ContractRelease
219 if e != nil || se != nil || len(raw) > 64<<10 || !ed25519.Verify(cfg.Key.Public().(ed25519.PublicKey), raw, sig) {
220 http.Error(w, "Invalid approval.", 400)
221 return
222 }
223 var rel releaseEnvelope
224 if json.Unmarshal(raw, &rel, json.RejectUnknownMembers(true)) != nil {
225 http.Error(w, "Invalid approval.", 400)
226 return
227 }
228 actor, ok := a.identity(r)
229 now := time.Now().Unix()
230 if !ok || !a.Admit(actor) || rel.Actor != actor || rel.Purpose != "confirm:"+releasePurpose || rel.Expires <= now || rel.Issued > now+60 || rel.Expires-rel.Issued > 600 || rel.Source != a.cfg.Origin || rel.Destination != cfg.Destination || rel.Importer != cfg.Importer || rel.Team != cfg.Team {
231 http.Error(w, "This approval has expired or changed. Start again from Docs.", 409)
232 return
233 }
234 e = a.db.G.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
235 c, e := LoadCard(r.Context(), tx, a.sealer, rel.Card)
236 if e != nil {
237 return e
238 }
239 if c.Card.Revision != rel.Revision {
240 return errRelease
241 }
242 keys := []string{}
243 for _, f := range rel.Fields {
244 keys = append(keys, f.Key)
245 }
246 current, e := releaseFields(c, keys)
247 if e != nil {
248 return e
249 }
250 before, _ := json.Marshal(rel.Fields)
251 after, _ := json.Marshal(current)
252 if sha256.Sum256(before) != sha256.Sum256(after) {
253 return errRelease
254 }
255 return nil
256 })
257 if e != nil {
258 http.Error(w, "The displayed customer details changed. Start again from Docs.", 409)
259 return
260 }
261 rel.Purpose = releasePurpose
262 rel.Issued = time.Now().Unix()
263 rel.Expires = rel.Issued + 1800
264 raw, e = json.Marshal(rel)
265 if e != nil {
266 http.Error(w, "Approval unavailable.", 503)
267 return
268 }
269 a.contractPage(w, r, contractReleasePage{Flow: rel.Flow, Phase: "send", Release: &rel, Payload: base64.RawURLEncoding.EncodeToString(raw), Signature: base64.RawURLEncoding.EncodeToString(ed25519.Sign(cfg.Key, raw))})
270}
271
272func validContractFlow(s string) bool { _, e := uuid.Parse(s); return e == nil }
273
274// Save only an opaque flow identifier through sign-in, never a return URL.
275func (a *app) contractPrepareReturning(w http.ResponseWriter, r *http.Request) {
276 flow := r.URL.Query().Get("flow")
277 if !validContractFlow(flow) {
278 notFound(w, r)
279 return
280 }
281 http.SetCookie(w, &http.Cookie{Name: "fichas_contract_return", Value: flow, Path: "/", MaxAge: 1800, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
282 a.requireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
283 http.SetCookie(w, &http.Cookie{Name: "fichas_contract_return", Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
284 a.contractPrepare(w, r)
285 })).ServeHTTP(w, r)
286}
287
288func releaseTeam(origin, team string) bool {
289 u, e := url.Parse(origin)
290 if e != nil {
291 return false
292 }
293 host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".")
294 parts := strings.Split(host, ".")
295 if strings.HasSuffix(host, ".oficina.works") && len(parts) >= 4 {
296 return len(parts) == 4 && parts[0] == team
297 }
298 return true
299}
300
301// releaseKind is the kind a field travels to Docs as. Docs knows text and
302// date; Email and Phone were Text until 2026-11-12 and still travel as
303// text, so the upgrade took nothing away from a contract.
304func releaseKind(kind string) (string, bool) {
305 switch kind {
306 case KindText, KindEmail, KindPhone:
307 return KindText, true
308 case KindDate:
309 return KindDate, true
310 }
311 return "", false
312}
313