| 1 | // assets.go is how a picture gets into a deck and back out of it |
| 2 | // (spec §2.7). |
| 3 | // |
| 4 | // Three endpoints and one rule. The rule is that bytes go in the object |
| 5 | // store and nowhere else — never a column, never this instance's disk, |
| 6 | // which is ephemeral and hibernates (rastrillo §2) — and that they |
| 7 | // travel browser-to-bucket rather than through this process: |
| 8 | // |
| 9 | // POST /d/{sqid}/uploads sign a PUT the browser makes itself |
| 10 | // POST /d/{sqid}/assets verify what landed, hand back the record |
| 11 | // GET /d/{sqid}/assets/{ref} the bytes, by the deck's own capability |
| 12 | // |
| 13 | // A scene's bundle goes in through the same sign, PUT and register, as |
| 14 | // an asset of kind scene signed as text/html, and comes back only |
| 15 | // through scenes.go's sealed routes, never this GET. |
| 16 | // |
| 17 | // STAGE, THEN PROMOTE (codex 1, codex 2). The browser never names the |
| 18 | // address its bytes will live at. The first endpoint mints a staging |
| 19 | // key of this app's own — models.go's AssetUpload says how it is built |
| 20 | // and why — writes the receipt for it, and signs a PUT for that key and |
| 21 | // nothing else. The second endpoint will only look at bytes a receipt |
| 22 | // says THIS principal staged for THIS deck; it reads them, hashes what |
| 23 | // it actually read, and puts them back as a final object keyed by that |
| 24 | // hash. So no browser is ever handed a PUT for an address anything is |
| 25 | // already served from, and knowing a ref is never a way to get one |
| 26 | // registered. Both of those were true the other way round until the |
| 27 | // codex review, and both were reachable by any member of the team. |
| 28 | // |
| 29 | // The middle one is the shape worth reading twice. It does NOT write |
| 30 | // the document. It answers with a validated record and the browser then |
| 31 | // applies `register_asset` with it, so an asset arrives in the deck |
| 32 | // through the same op path, the same update log and the same undo stack |
| 33 | // as every other change. A server that wrote the Y.Doc behind the |
| 34 | // editor's back would be a second writer with no seq, no actor and |
| 35 | // nothing for undo to take back. What it DOES write is one row saying |
| 36 | // the ref was verified for this deck (models.go's DeckAsset), because |
| 37 | // the op is one any member can apply with any ref, and the GET requires |
| 38 | // that row as well as the deck's map. |
| 39 | // |
| 40 | // The GET is keyed by the deck rather than global, and it is three |
| 41 | // routes rather than one, because a slide is rendered on surfaces |
| 42 | // authenticated four different ways: a session, a share token, a |
| 43 | // presentation session. Each renders its images under its own |
| 44 | // capability (render.Options.AssetBase) and each checks the ref against |
| 45 | // THAT deck's `assets` map before serving a byte — so a share link to |
| 46 | // one deck is not a way to read another deck's pictures. |
| 47 | // |
| 48 | // With no object store bound — which is this deployment today — the |
| 49 | // sign endpoint answers 503 and the inspector says so in words. That is |
| 50 | // the whole "no store" story: nothing half-works, and nothing falls |
| 51 | // back to a place the bytes would be lost from. |
| 52 | package slides |
| 53 | |
| 54 | import ( |
| 55 | "bytes" |
| 56 | "context" |
| 57 | "crypto/rand" |
| 58 | "crypto/sha256" |
| 59 | "encoding/hex" |
| 60 | "encoding/json" |
| 61 | "errors" |
| 62 | "fmt" |
| 63 | "io" |
| 64 | "net/http" |
| 65 | "regexp" |
| 66 | "slices" |
| 67 | "strings" |
| 68 | "time" |
| 69 | "unicode/utf8" |
| 70 | |
| 71 | "github.com/go-chi/chi/v5" |
| 72 | "gorm.io/gorm" |
| 73 | "gorm.io/gorm/clause" |
| 74 | |
| 75 | "amadan.net/rastrillo/rastrillo" |
| 76 | "amadan.net/rastrillo/rastrillo/blobs" |
| 77 | ) |
| 78 | |
| 79 | // maxAssetBytes is spec §2.7's 20 MiB, enforced in three places that |
| 80 | // each have to hold on their own: the sign endpoint refuses a size |
| 81 | // bigger than this before minting a URL, the development PUT caps the |
| 82 | // body it will read, and registration refuses an object that turns out |
| 83 | // bigger than it was told. The first is a courtesy, the second and |
| 84 | // third are the actual limits — a presigned PUT goes straight to the |
| 85 | // bucket and this process never sees it. |
| 86 | const maxAssetBytes = 20 << 20 |
| 87 | |
| 88 | // assetTypes is §2.7's four, mapped to the extension a person's file |
| 89 | // picker will have offered. Values are unused today and the map is the |
| 90 | // allowlist; spelled as a map so adding a fifth is one line. |
| 91 | var assetTypes = map[string]string{ |
| 92 | "image/png": ".png", |
| 93 | "image/jpeg": ".jpg", |
| 94 | "image/webp": ".webp", |
| 95 | "image/svg+xml": ".svg", |
| 96 | } |
| 97 | |
| 98 | // acceptTypes is assetTypes as a file input's accept attribute, sorted |
| 99 | // so the markup is the same on every render. The picker offers exactly |
| 100 | // what signUpload will admit, from the one map. |
| 101 | func acceptTypes() string { |
| 102 | out := make([]string, 0, len(assetTypes)) |
| 103 | for kind := range assetTypes { |
| 104 | out = append(out, kind) |
| 105 | } |
| 106 | slices.Sort(out) |
| 107 | return strings.Join(out, ",") |
| 108 | } |
| 109 | |
| 110 | // maxAssetName bounds the filename a client sends. It is only ever |
| 111 | // shown back to the person who uploaded it, but it is held in memory |
| 112 | // and written into the document, so it is bounded like every other |
| 113 | // string that arrives from outside. |
| 114 | const maxAssetName = 200 |
| 115 | |
| 116 | // maxAssetAlt bounds the alternative text. Long enough for the sentence |
| 117 | // or two a description actually is; short enough that the field is not |
| 118 | // a way to put a novel in the CRDT. |
| 119 | const maxAssetAlt = 2000 |
| 120 | |
| 121 | // maxAssetDimension bounds the width and height a client reports. They |
| 122 | // come from the browser's own decode of the image, so they are |
| 123 | // advisory — the renderer writes them onto the <img> so the layout does |
| 124 | // not jump — and a number outside this is dropped rather than refused. |
| 125 | const maxAssetDimension = 30000 |
| 126 | |
| 127 | // assetRefPattern is what may be a ref in this app: one URL path |
| 128 | // segment of unreserved characters. The object store mints a hex |
| 129 | // SHA-256 (rastrillo/blobs is content-addressed), which passes. Kept in |
| 130 | // step with render.safeRef's own pattern — the renderer writes these |
| 131 | // into a src and this file reads them out of a path, and a value only |
| 132 | // one of the two accepts is a broken image either way. |
| 133 | var assetRefPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,128}$`) |
| 134 | |
| 135 | // presigner is the part of an object store that can hand a browser a |
| 136 | // URL of its own. blobs.Store does not require it — blobs.Dir has |
| 137 | // nothing to presign, being files in a directory — so this is a type |
| 138 | // assertion at the point of use rather than a wider interface. |
| 139 | // |
| 140 | // Declared here rather than imported because rastrillo/blobs exports |
| 141 | // the methods on *blobs.S3 concretely; naming the shape keeps this file |
| 142 | // testable against a fake and keeps a second backend from needing a |
| 143 | // change here. |
| 144 | type presigner interface { |
| 145 | PresignPut(hash string, ttl time.Duration) (string, error) |
| 146 | PresignGet(hash string, ttl time.Duration) (string, error) |
| 147 | } |
| 148 | |
| 149 | // ThroughApp is a bound object store with its presigning hidden, so |
| 150 | // every byte goes through this app: an upload is PUT to |
| 151 | // /d/{sqid}/uploads/{key} (putUpload), a picture is streamed from |
| 152 | // serveAsset, and an export from serveExport — the paths development's |
| 153 | // blobs.Dir always took. |
| 154 | // |
| 155 | // Production binds the platform's bucket through it (cmd/slides). The |
| 156 | // presigned design (spec §2.7) has the browser PUT to the bucket and |
| 157 | // load pictures from it, and neither can work as deployed: the page's |
| 158 | // CSP is default-src 'self' and img-src 'self' data: (serving.go), so |
| 159 | // the browser refuses both, and the platform's bucket answers no CORS |
| 160 | // for this origin. Found when the store was first bound, 2026-11-11 — |
| 161 | // the path had never run. Going direct again needs the bucket's origin |
| 162 | // in connect-src and img-src and a CORS rule on the bucket; until then |
| 163 | // this is the path that works. The cost is the bytes passing through |
| 164 | // one instance. On the way out a picture is streamed (serveAsset). On |
| 165 | // the way in rastrillo's blobs.S3.Put holds the body in memory (twice, |
| 166 | // as of v0.27), and registration reads it again to sniff and promote, |
| 167 | // so one 20 MiB upload can take ~60 MiB for a moment — fine for one |
| 168 | // team, and a rastrillo streaming Put is the fix when it is not. |
| 169 | func ThroughApp(s blobs.Store) blobs.Store { |
| 170 | if s == nil { |
| 171 | return nil |
| 172 | } |
| 173 | return throughApp{s} |
| 174 | } |
| 175 | |
| 176 | // throughApp embeds only the blobs.Store interface, so a type assertion |
| 177 | // to presigner fails on it whatever the store underneath can do. |
| 178 | type throughApp struct{ blobs.Store } |
| 179 | |
| 180 | // presignTTL is how long a minted URL lives. An hour for a GET, because |
| 181 | // that is the life of one person reading a deck; the same for a PUT, |
| 182 | // because a 20 MiB file on a bad connection is not a five-minute job. |
| 183 | const presignTTL = time.Hour |
| 184 | |
| 185 | // --- the staging key --- |
| 186 | |
| 187 | // stagingLife is how long a receipt is registrable for. Twice the |
| 188 | // presigned PUT's own hour, because the PUT may be minted at the start |
| 189 | // of that hour and land at the end of it, and registration happens |
| 190 | // after the bytes are up. Long enough that a 20 MiB file on hotel wifi |
| 191 | // still registers; short enough that a staged object nobody registered |
| 192 | // stops being a thing this app will read. |
| 193 | const stagingLife = 2 * presignTTL |
| 194 | |
| 195 | // newStagingKey mints the address one upload may be written to. |
| 196 | // |
| 197 | // It is a SHA-256 because that is the only shape rastrillo/blobs will |
| 198 | // take as a key (blobs.checkHash), and it is a hash of the deck, the |
| 199 | // actor and 32 fresh random bytes so the address is literally a |
| 200 | // function of the principal and the deck it was signed for — codex 1's |
| 201 | // "never a caller-chosen final address". The randomness is what makes |
| 202 | // it unguessable; the domain prefix is what keeps it from ever |
| 203 | // colliding with a content address, which is a hash of bytes and not of |
| 204 | // this string. |
| 205 | func newStagingKey(deckID int64, actor string) (string, error) { |
| 206 | nonce := make([]byte, 32) |
| 207 | if _, err := rand.Read(nonce); err != nil { |
| 208 | return "", fmt.Errorf("slides: generate a staging key: %w", err) |
| 209 | } |
| 210 | sum := sha256.Sum256([]byte(fmt.Sprintf("slides/asset-staging\x00%d\x00%s\x00%x", deckID, actor, nonce))) |
| 211 | return hex.EncodeToString(sum[:]), nil |
| 212 | } |
| 213 | |
| 214 | // stagedUpload resolves one receipt: this staging key, staged by this |
| 215 | // actor for this deck, not yet registered and not yet stale. |
| 216 | // |
| 217 | // All four conditions are the codex 2 fix in one query. The key alone |
| 218 | // is not enough (that was the hole: a ref was), the deck alone is not |
| 219 | // enough, and a receipt cannot be replayed into a second registration. |
| 220 | func (a *app) stagedUpload(ctx context.Context, d Deck, actor, key string) (AssetUpload, bool, error) { |
| 221 | var up AssetUpload |
| 222 | err := a.db.G.WithContext(ctx). |
| 223 | Where("staging_key = ? AND deck_id = ? AND actor = ? AND consumed_at IS NULL AND created_at > ?", |
| 224 | key, d.ID, actor, time.Now().UTC().Add(-stagingLife)). |
| 225 | Take(&up).Error |
| 226 | switch { |
| 227 | case err == nil: |
| 228 | return up, true, nil |
| 229 | case errors.Is(err, gorm.ErrRecordNotFound): |
| 230 | return AssetUpload{}, false, nil |
| 231 | default: |
| 232 | return AssetUpload{}, false, err |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // --- POST /d/{sqid}/uploads --- |
| 237 | |
| 238 | // signUpload answers "where do I put these bytes". |
| 239 | // |
| 240 | // The answer is a staging key of this app's own and never the hash the |
| 241 | // client sent (codex 1). The hash is still read, because the browser |
| 242 | // computes it anyway and the development PUT can cheaply check what |
| 243 | // landed against it, but nothing is addressed by it: registration |
| 244 | // hashes the bytes it actually reads and that hash is what the deck |
| 245 | // ends up referring to. |
| 246 | // |
| 247 | // Why it matters that the client cannot choose: rastrillo's store signs |
| 248 | // an unconditional PUT (blobs/s3.go's PresignPut), so an address a |
| 249 | // browser can name is an address a browser can overwrite. Naming a ref |
| 250 | // another deck's picture is already served from would have changed that |
| 251 | // picture, in that deck, with no document update anywhere. |
| 252 | func (a *app) signUpload(w http.ResponseWriter, r *http.Request) { |
| 253 | u, ok := a.viewer(w, r) |
| 254 | if !ok { |
| 255 | return |
| 256 | } |
| 257 | d, ok := a.deckFor(w, r, u) |
| 258 | if !ok { |
| 259 | return |
| 260 | } |
| 261 | store := a.cfg.Blobs |
| 262 | if store == nil { |
| 263 | assetFail(w, r, http.StatusServiceUnavailable, "no_store", "nostore") |
| 264 | return |
| 265 | } |
| 266 | |
| 267 | r.Body = http.MaxBytesReader(w, r.Body, 4<<10) |
| 268 | var body struct { |
| 269 | Name string `json:"name"` |
| 270 | Size int64 `json:"size"` |
| 271 | Type string `json:"type"` |
| 272 | Hash string `json:"hash"` |
| 273 | } |
| 274 | if err := json.NewDecoder(r.Body).Decode(&body); err != nil { |
| 275 | assetFail(w, r, http.StatusUnprocessableEntity, "invalid", "invalid") |
| 276 | return |
| 277 | } |
| 278 | // A picture, a scene's bundle (scenes.go) or a clip's video |
| 279 | // (clips.go), the last two held to their own sizes and refused in |
| 280 | // codes rather than the pictures' words. |
| 281 | kind := strings.ToLower(strings.TrimSpace(body.Type)) |
| 282 | limit, refuse := uploadLimit(kind), assetRefusal(w, r, kind) |
| 283 | if _, allowed := assetTypes[kind]; !allowed && kind != sceneType && !isVideo(kind) { |
| 284 | assetFail(w, r, http.StatusUnprocessableEntity, "unsupported_type", "type") |
| 285 | return |
| 286 | } |
| 287 | if body.Size <= 0 || body.Size > limit { |
| 288 | refuse(http.StatusRequestEntityTooLarge, "too_large", "toolarge") |
| 289 | return |
| 290 | } |
| 291 | // The declared hash is still held to the shape a ref has, because a |
| 292 | // malformed one is a client bug worth reporting rather than a |
| 293 | // number to record. It addresses nothing either way. |
| 294 | if !assetRefPattern.MatchString(body.Hash) { |
| 295 | assetFail(w, r, http.StatusUnprocessableEntity, "invalid", "invalid") |
| 296 | return |
| 297 | } |
| 298 | |
| 299 | key, err := newStagingKey(d.ID, actorFor(u)) |
| 300 | if err != nil { |
| 301 | a.fail(w, r, "mint a staging key", err) |
| 302 | return |
| 303 | } |
| 304 | // Belt to the staging key's braces. A fresh random key cannot be an |
| 305 | // address this deck already serves from, so this can only fire if |
| 306 | // somebody reintroduces a caller-chosen key — which is the mistake |
| 307 | // codex 1 found, and this is the line that would catch it coming |
| 308 | // back. Checked across every deck, not just this one: an address |
| 309 | // verified anywhere is an address in use, a scene's bundle included. |
| 310 | var verified int64 |
| 311 | for _, model := range []any{&DeckAsset{}, &SceneBundle{}} { |
| 312 | var n int64 |
| 313 | if err := a.db.G.WithContext(r.Context()).Model(model). |
| 314 | Where("ref = ?", key).Count(&n).Error; err != nil { |
| 315 | a.fail(w, r, "check whether an upload address is already verified", err) |
| 316 | return |
| 317 | } |
| 318 | verified += n |
| 319 | } |
| 320 | if verified > 0 { |
| 321 | a.logger.Error("slides: refused to sign a PUT for a verified address", |
| 322 | "deck", d.Sqid, "ref", key) |
| 323 | refuse(http.StatusConflict, "already_verified", "failed") |
| 324 | return |
| 325 | } |
| 326 | |
| 327 | // The receipt goes in BEFORE the URL goes out. A receipt with no |
| 328 | // upload against it is a row that expires unread; a URL with no |
| 329 | // receipt is bytes nothing will ever register, which is worse |
| 330 | // because somebody waits for it. |
| 331 | up := AssetUpload{ |
| 332 | DeckID: d.ID, |
| 333 | Actor: actorFor(u), |
| 334 | StagingKey: key, |
| 335 | DeclaredHash: body.Hash, |
| 336 | ContentType: kind, |
| 337 | Size: body.Size, |
| 338 | CreatedAt: time.Now().UTC(), |
| 339 | } |
| 340 | out := map[string]any{ |
| 341 | "ref": key, |
| 342 | "headers": map[string]string{"Content-Type": body.Type}, |
| 343 | } |
| 344 | if p, canPresign := store.(presigner); canPresign { |
| 345 | // The browser writes the staging key itself, so that is where |
| 346 | // the bytes will be. |
| 347 | up.ObjectKey = key |
| 348 | url, err := p.PresignPut(key, presignTTL) |
| 349 | if err != nil { |
| 350 | a.logger.Error("slides: presign an upload", "deck", d.Sqid, "err", err) |
| 351 | refuse(http.StatusInternalServerError, "internal", "failed") |
| 352 | return |
| 353 | } |
| 354 | out["url"] = url |
| 355 | } else { |
| 356 | // A store that does not presign — blobs.Dir in development, and |
| 357 | // production's bucket behind ThroughApp — takes the bytes |
| 358 | // through this app. ObjectKey stays empty: a content-addressed |
| 359 | // store picks the key itself, and putUpload records which one. |
| 360 | out["url"] = "/d/" + d.Sqid + "/uploads/" + key |
| 361 | } |
| 362 | if err := a.guarded(r.Context(), a.deckGuard(r.Context(), u, d), func(db *gorm.DB) error { return db.Create(&up).Error }); err != nil { |
| 363 | if a.guardRefused(w, r, err) { |
| 364 | return |
| 365 | } |
| 366 | a.fail(w, r, "record a staged upload", err) |
| 367 | return |
| 368 | } |
| 369 | writeAssetJSON(w, http.StatusOK, out) |
| 370 | } |
| 371 | |
| 372 | // --- PUT /d/{sqid}/uploads/{ref} --- |
| 373 | |
| 374 | // putUpload is the receiving end of the URL signUpload hands back when |
| 375 | // the bound store does not presign — blobs.Dir in development, and the |
| 376 | // platform's bucket behind ThroughApp in production. |
| 377 | // |
| 378 | // It refuses outright on a store that DOES presign: that store's uploads |
| 379 | // go to the bucket, and an endpoint that also accepted them here would |
| 380 | // be a second path nobody chose. |
| 381 | // |
| 382 | // It takes a staging key, not a ref, and resolves the receipt for it |
| 383 | // before it reads a byte (codex 1). Without that this endpoint was its |
| 384 | // own copy of the same hole: any member could write any address in the |
| 385 | // store, presigning or not. |
| 386 | func (a *app) putUpload(w http.ResponseWriter, r *http.Request) { |
| 387 | u, ok := a.viewer(w, r) |
| 388 | if !ok { |
| 389 | return |
| 390 | } |
| 391 | d, ok := a.deckFor(w, r, u) |
| 392 | if !ok { |
| 393 | return |
| 394 | } |
| 395 | store := a.cfg.Blobs |
| 396 | if store == nil { |
| 397 | assetFail(w, r, http.StatusServiceUnavailable, "no_store", "nostore") |
| 398 | return |
| 399 | } |
| 400 | if _, canPresign := store.(presigner); canPresign { |
| 401 | assetFail(w, r, http.StatusNotFound, "not_found", "invalid") |
| 402 | return |
| 403 | } |
| 404 | key := chi.URLParam(r, "ref") |
| 405 | if !assetRefPattern.MatchString(key) { |
| 406 | assetFail(w, r, http.StatusUnprocessableEntity, "invalid", "invalid") |
| 407 | return |
| 408 | } |
| 409 | up, staged, err := a.stagedUpload(r.Context(), d, actorFor(u), key) |
| 410 | if err != nil { |
| 411 | a.fail(w, r, "resolve a staged upload", err) |
| 412 | return |
| 413 | } |
| 414 | if !staged { |
| 415 | // The same 404 an address nobody signed gets. A member learns |
| 416 | // nothing about what other people have staged. |
| 417 | assetFail(w, r, http.StatusNotFound, "not_found", "invalid") |
| 418 | return |
| 419 | } |
| 420 | |
| 421 | limit, refuse := uploadLimit(up.ContentType), assetRefusal(w, r, up.ContentType) |
| 422 | r.Body = http.MaxBytesReader(w, r.Body, limit) |
| 423 | stored, err := store.Put(r.Context(), r.Body, r.Header.Get("Content-Type")) |
| 424 | if err != nil { |
| 425 | var tooBig *http.MaxBytesError |
| 426 | if errors.As(err, &tooBig) { |
| 427 | refuse(http.StatusRequestEntityTooLarge, "too_large", "toolarge") |
| 428 | return |
| 429 | } |
| 430 | a.logger.Error("slides: store an upload", "err", err) |
| 431 | refuse(http.StatusInternalServerError, "internal", "failed") |
| 432 | return |
| 433 | } |
| 434 | // The store hashed what it read, and the client said what it was |
| 435 | // sending. A disagreement is a client bug and is reported as one — |
| 436 | // it is no longer a security question, because what registration |
| 437 | // promotes is addressed by the bytes this app read either way. |
| 438 | if up.DeclaredHash != "" && stored.Hash != up.DeclaredHash { |
| 439 | refuse(http.StatusUnprocessableEntity, "hash_mismatch", "invalid") |
| 440 | return |
| 441 | } |
| 442 | // Where the bytes actually landed. blobs.Dir is content-addressed |
| 443 | // and has no way to write a key of somebody else's choosing, so the |
| 444 | // receipt records the key it chose rather than pretending the |
| 445 | // staging key holds anything. |
| 446 | if err := a.guarded(r.Context(), a.deckGuard(r.Context(), u, d), func(db *gorm.DB) error { |
| 447 | return db.Model(&AssetUpload{}). |
| 448 | Where("id = ?", up.ID). |
| 449 | Updates(map[string]any{"object_key": stored.Hash, "size": stored.Size}).Error |
| 450 | }); err != nil { |
| 451 | if a.guardRefused(w, r, err) { |
| 452 | return |
| 453 | } |
| 454 | a.fail(w, r, "record where an upload landed", err) |
| 455 | return |
| 456 | } |
| 457 | w.WriteHeader(http.StatusNoContent) |
| 458 | } |
| 459 | |
| 460 | // --- POST /d/{sqid}/assets --- |
| 461 | |
| 462 | // registerAsset verifies what actually landed in the store and hands |
| 463 | // back the record the client should register. |
| 464 | // |
| 465 | // Verifying means reading the bytes, not asking the store what it was |
| 466 | // told: the content type on an object is whatever the browser put in a |
| 467 | // header, and this is the one place between an upload and a deck full |
| 468 | // of readers where somebody can check that a file called a PNG is one. |
| 469 | // |
| 470 | // What it will look at is a STAGED upload and nothing else: the `ref` |
| 471 | // in the body is the staging key POST /d/{sqid}/uploads answered with, |
| 472 | // and a receipt has to say this principal staged it for this deck |
| 473 | // (codex 2). A ref on its own is never enough — that was the hole, and |
| 474 | // it turned knowing another deck's content address into permission to |
| 475 | // read it, because the row this writes plus a `register_asset` op are |
| 476 | // exactly what serveAsset asks for. |
| 477 | // |
| 478 | // It then does what this comment used to claim and did not do (codex |
| 479 | // 1): it hashes the bytes it read and PUTS THEM BACK, so the address |
| 480 | // the deck ends up referring to is derived from bytes this app has |
| 481 | // seen. That costs one upload of at most 20 MiB per registration, on |
| 482 | // top of the download registration already did. Known, and the price |
| 483 | // of a final object no browser was ever handed a PUT for. |
| 484 | // |
| 485 | // An SVG goes through svg.go on the way, and comes back different — a |
| 486 | // stripped document has different bytes and therefore, in a |
| 487 | // content-addressed store, a different address. So the ref this answers |
| 488 | // with is never the ref it was asked about, and the client registers |
| 489 | // what came back rather than what it uploaded. |
| 490 | func (a *app) registerAsset(w http.ResponseWriter, r *http.Request) { |
| 491 | u, ok := a.viewer(w, r) |
| 492 | if !ok { |
| 493 | return |
| 494 | } |
| 495 | d, ok := a.deckFor(w, r, u) |
| 496 | if !ok { |
| 497 | return |
| 498 | } |
| 499 | store := a.cfg.Blobs |
| 500 | if store == nil { |
| 501 | assetFail(w, r, http.StatusServiceUnavailable, "no_store", "nostore") |
| 502 | return |
| 503 | } |
| 504 | |
| 505 | r.Body = http.MaxBytesReader(w, r.Body, 8<<10) |
| 506 | var body struct { |
| 507 | Ref string `json:"ref"` |
| 508 | Name string `json:"name"` |
| 509 | Width int `json:"width"` |
| 510 | Height int `json:"height"` |
| 511 | Alt string `json:"alt"` |
| 512 | Decorative bool `json:"decorative"` |
| 513 | // A clip's video: its poster's ref and its length in whole |
| 514 | // milliseconds (clips.go). |
| 515 | Poster string `json:"poster"` |
| 516 | Duration int64 `json:"duration"` |
| 517 | } |
| 518 | if err := json.NewDecoder(r.Body).Decode(&body); err != nil { |
| 519 | assetFail(w, r, http.StatusUnprocessableEntity, "invalid", "invalid") |
| 520 | return |
| 521 | } |
| 522 | if !assetRefPattern.MatchString(body.Ref) { |
| 523 | assetFail(w, r, http.StatusUnprocessableEntity, "invalid", "invalid") |
| 524 | return |
| 525 | } |
| 526 | |
| 527 | // The receipt. Everything after this point is about bytes THIS |
| 528 | // principal staged for THIS deck; a `ref` that names anything else |
| 529 | // gets the same 404 an address holding nothing gets. |
| 530 | up, staged, err := a.stagedUpload(r.Context(), d, actorFor(u), body.Ref) |
| 531 | if err != nil { |
| 532 | a.fail(w, r, "resolve a staged upload", err) |
| 533 | return |
| 534 | } |
| 535 | if !staged { |
| 536 | assetFail(w, r, http.StatusNotFound, "not_found", "missing") |
| 537 | return |
| 538 | } |
| 539 | // A receipt signed as text/html is a scene's bundle, judged as one |
| 540 | // and recorded apart from the pictures (scenes.go). |
| 541 | if up.ContentType == sceneType { |
| 542 | a.registerScene(w, r, u, d, store, up) |
| 543 | return |
| 544 | } |
| 545 | // One signed as a video is a clip's, registered with its poster. |
| 546 | if isVideo(up.ContentType) { |
| 547 | a.registerVideo(w, r, u, d, store, up, body.Name, strings.TrimSpace(body.Alt), strings.TrimSpace(body.Poster), body.Width, body.Height, body.Duration) |
| 548 | return |
| 549 | } |
| 550 | // §2.4 makes alt required unless the block is marked decorative. |
| 551 | // Checked here as well as in the inspector, because the inspector |
| 552 | // is a courtesy and this is the gate. A refusal spends nothing: the |
| 553 | // receipt is there for the registration that gets it right. |
| 554 | alt := strings.TrimSpace(body.Alt) |
| 555 | if alt == "" && !body.Decorative { |
| 556 | assetFail(w, r, http.StatusUnprocessableEntity, "alt_required", "altrequired") |
| 557 | return |
| 558 | } |
| 559 | // Where the bytes are: the staging key on a presigning store, where |
| 560 | // the browser wrote them itself, or whatever key blobs.Dir chose |
| 561 | // when the PUT came through this app. Empty means the PUT never |
| 562 | // landed, which reads the same as an empty address. |
| 563 | object := up.ObjectKey |
| 564 | if object == "" { |
| 565 | assetFail(w, r, http.StatusNotFound, "not_found", "missing") |
| 566 | return |
| 567 | } |
| 568 | |
| 569 | raw, err := a.readAsset(r.Context(), store, object) |
| 570 | if err != nil { |
| 571 | if errors.Is(err, blobs.ErrNotFound) { |
| 572 | assetFail(w, r, http.StatusNotFound, "not_found", "missing") |
| 573 | return |
| 574 | } |
| 575 | if errors.Is(err, errAssetTooLarge) { |
| 576 | assetFail(w, r, http.StatusRequestEntityTooLarge, "too_large", "toolarge") |
| 577 | return |
| 578 | } |
| 579 | a.logger.Error("slides: read an uploaded asset", "deck", d.Sqid, "err", err) |
| 580 | assetFail(w, r, http.StatusInternalServerError, "internal", "failed") |
| 581 | return |
| 582 | } |
| 583 | |
| 584 | // An HTML document is never a picture, even one with an <svg> in its |
| 585 | // head, which sniffImage alone would take for one. |
| 586 | kind := sniffImage(raw) |
| 587 | if kind == "" || sniffScene(raw) { |
| 588 | assetFail(w, r, http.StatusUnprocessableEntity, "not_an_image", "notimage") |
| 589 | return |
| 590 | } |
| 591 | final := raw |
| 592 | if kind == "image/svg+xml" { |
| 593 | clean, err := sanitiseSVG(raw) |
| 594 | if err != nil { |
| 595 | a.logger.Info("slides: refused an SVG", "deck", d.Sqid, "err", err) |
| 596 | assetFail(w, r, http.StatusUnprocessableEntity, "unsafe_svg", "svg") |
| 597 | return |
| 598 | } |
| 599 | final = clean |
| 600 | } |
| 601 | |
| 602 | // The promotion: what was read, put back. The store is |
| 603 | // content-addressed, so the key this answers with IS the SHA-256 of |
| 604 | // the bytes above — the rehash this endpoint's comment promised |
| 605 | // before codex 1 pointed out that nothing did it — and no browser |
| 606 | // has ever been handed a PUT for that address, so it holds these |
| 607 | // bytes for as long as it exists. Idempotent by construction: |
| 608 | // registering the same picture twice is one stored object. |
| 609 | stored, err := store.Put(r.Context(), bytes.NewReader(final), kind) |
| 610 | if err != nil { |
| 611 | a.logger.Error("slides: promote a staged upload", "deck", d.Sqid, "err", err) |
| 612 | assetFail(w, r, http.StatusInternalServerError, "internal", "failed") |
| 613 | return |
| 614 | } |
| 615 | ref := stored.Hash |
| 616 | |
| 617 | // The verification, written down (models.go's DeckAsset). The |
| 618 | // record this answers with is what the client will name in a |
| 619 | // `register_asset` op, and that op is one any member can apply |
| 620 | // with ANY ref — so the deck's own map cannot be the whole gate, |
| 621 | // and serveAsset requires this row as well. Written before the |
| 622 | // answer, and a failure to write it fails the request: a record |
| 623 | // the browser registers without this row is a picture that will |
| 624 | // never be served. |
| 625 | if err := a.guarded(r.Context(), a.deckGuard(r.Context(), u, d), func(db *gorm.DB) error { |
| 626 | return db.Clauses(clause.OnConflict{DoNothing: true}). |
| 627 | Create(&DeckAsset{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error |
| 628 | }); err != nil { |
| 629 | if a.guardRefused(w, r, err) { |
| 630 | return |
| 631 | } |
| 632 | a.fail(w, r, "record a verified asset", err) |
| 633 | return |
| 634 | } |
| 635 | |
| 636 | a.spendUpload(r, d, up, object, ref) |
| 637 | |
| 638 | id, err := newID() |
| 639 | if err != nil { |
| 640 | a.fail(w, r, "mint an asset id", err) |
| 641 | return |
| 642 | } |
| 643 | writeAssetJSON(w, http.StatusOK, map[string]any{ |
| 644 | "id": id, |
| 645 | "ref": ref, |
| 646 | "name": trimTo(body.Name, maxAssetName), |
| 647 | "width": boundDimension(body.Width), |
| 648 | "height": boundDimension(body.Height), |
| 649 | "alt": trimTo(alt, maxAssetAlt), |
| 650 | }) |
| 651 | } |
| 652 | |
| 653 | // spendUpload spends a registered upload's receipt and discards its |
| 654 | // staged copy, the last step of registering a picture or a scene's |
| 655 | // bundle. Both after the verification row, so a failure here costs a |
| 656 | // stale row and a staged object rather than an asset that can never be |
| 657 | // served. |
| 658 | // |
| 659 | // The delete is skipped when the staged key IS the final one, which is |
| 660 | // the ordinary development case: blobs.Dir stored the bytes under their |
| 661 | // own hash, sanitising changed nothing, and the object the browser |
| 662 | // uploaded is the promoted object. Deleting it there would delete the |
| 663 | // asset. |
| 664 | func (a *app) spendUpload(r *http.Request, d Deck, up AssetUpload, object, ref string) { |
| 665 | if err := a.db.G.WithContext(r.Context()).Model(&AssetUpload{}). |
| 666 | Where("id = ? AND consumed_at IS NULL", up.ID). |
| 667 | Update("consumed_at", time.Now().UTC()).Error; err != nil { |
| 668 | a.logger.Error("slides: spend an upload receipt", "deck", d.Sqid, "upload", up.ID, "err", err) |
| 669 | } |
| 670 | if object != ref { |
| 671 | if err := a.cfg.Blobs.Delete(r.Context(), object); err != nil { |
| 672 | a.logger.Error("slides: discard a staged upload", "deck", d.Sqid, "ref", object, "err", err) |
| 673 | } |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | // assetRefusal is how an upload of kind is refused: in the pictures' |
| 678 | // words (assetFail), or for a scene's bundle or a clip's video in a |
| 679 | // code alone (sceneFail, videoFail). |
| 680 | func assetRefusal(w http.ResponseWriter, r *http.Request, kind string) func(status int, code, messageKey string) { |
| 681 | if kind == sceneType { |
| 682 | return func(status int, code, _ string) { sceneFail(w, status, code) } |
| 683 | } |
| 684 | if isVideo(kind) { |
| 685 | return func(status int, code, _ string) { videoFail(w, status, code) } |
| 686 | } |
| 687 | return func(status int, code, messageKey string) { assetFail(w, r, status, code, messageKey) } |
| 688 | } |
| 689 | |
| 690 | // uploadLimit is the most an upload signed as kind may be: a picture's |
| 691 | // 20 MiB, a scene bundle's 2 MiB, a clip's 50 MiB. |
| 692 | func uploadLimit(kind string) int64 { |
| 693 | switch { |
| 694 | case kind == sceneType: |
| 695 | return maxSceneBytes |
| 696 | case isVideo(kind): |
| 697 | return maxVideoBytes |
| 698 | } |
| 699 | return maxAssetBytes |
| 700 | } |
| 701 | |
| 702 | // errAssetTooLarge is an object in the store that is bigger than §2.7 |
| 703 | // allows. Reachable even though signUpload refuses the size: a |
| 704 | // presigned PUT goes straight to the bucket, so what actually landed is |
| 705 | // only ever known here. |
| 706 | var errAssetTooLarge = errors.New("slides: this object is larger than an asset may be") |
| 707 | |
| 708 | // readAsset reads one object out of the store, refusing at the limit |
| 709 | // rather than reading whatever is there. The +1 is what tells "exactly |
| 710 | // at the limit" from "over it". |
| 711 | // |
| 712 | // A context rather than the request it usually comes from: the export |
| 713 | // job reads assets too (exports.go), and a job outlives the request |
| 714 | // that started it by definition. |
| 715 | func (a *app) readAsset(ctx context.Context, store blobs.Store, ref string) ([]byte, error) { |
| 716 | return a.readObject(ctx, store, ref, maxAssetBytes) |
| 717 | } |
| 718 | |
| 719 | // readObject is readAsset with the limit given: a scene's bundle is held |
| 720 | // to its own 2 MiB (scenes.go). |
| 721 | func (a *app) readObject(ctx context.Context, store blobs.Store, ref string, limit int64) ([]byte, error) { |
| 722 | rc, err := store.Get(ctx, ref) |
| 723 | if err != nil { |
| 724 | return nil, err |
| 725 | } |
| 726 | defer rc.Close() |
| 727 | raw, err := io.ReadAll(io.LimitReader(rc, limit+1)) |
| 728 | if err != nil { |
| 729 | return nil, err |
| 730 | } |
| 731 | if int64(len(raw)) > limit { |
| 732 | return nil, errAssetTooLarge |
| 733 | } |
| 734 | return raw, nil |
| 735 | } |
| 736 | |
| 737 | // sniffImage reads the bytes themselves rather than any header, and |
| 738 | // returns one of §2.7's four types or the empty string. |
| 739 | // |
| 740 | // http.DetectContentType is not used: it answers "image/svg+xml" for |
| 741 | // nothing at all, and its window is 512 bytes, which is enough for the |
| 742 | // three raster magics and awkward for an XML declaration followed by a |
| 743 | // long comment. The magics are short and there are three of them. |
| 744 | func sniffImage(raw []byte) string { |
| 745 | switch { |
| 746 | case bytes.HasPrefix(raw, []byte("\x89PNG\r\n\x1a\n")): |
| 747 | return "image/png" |
| 748 | case bytes.HasPrefix(raw, []byte{0xff, 0xd8, 0xff}): |
| 749 | return "image/jpeg" |
| 750 | case len(raw) >= 12 && bytes.HasPrefix(raw, []byte("RIFF")) && bytes.Equal(raw[8:12], []byte("WEBP")): |
| 751 | return "image/webp" |
| 752 | } |
| 753 | // An SVG is text, and may open with a byte-order mark, an XML |
| 754 | // declaration, a comment or whitespace before the element. Looking |
| 755 | // for "<svg" in the head of the file is what a browser does too; |
| 756 | // svg.go then refuses anything that is not really one. |
| 757 | head := raw |
| 758 | if len(head) > 1024 { |
| 759 | head = head[:1024] |
| 760 | } |
| 761 | head = bytes.TrimPrefix(head, []byte("\xef\xbb\xbf")) |
| 762 | if bytes.Contains(bytes.ToLower(head), []byte("<svg")) { |
| 763 | return "image/svg+xml" |
| 764 | } |
| 765 | return "" |
| 766 | } |
| 767 | |
| 768 | // --- GET {surface}/assets/{ref} --- |
| 769 | |
| 770 | // deckAsset serves an asset to a signed-in reader of the deck. |
| 771 | func (a *app) deckAsset(w http.ResponseWriter, r *http.Request) { |
| 772 | u, ok := a.viewer(w, r) |
| 773 | if !ok { |
| 774 | return |
| 775 | } |
| 776 | d, ok := a.deckFor(w, r, u) |
| 777 | if !ok { |
| 778 | return |
| 779 | } |
| 780 | a.serveAsset(w, r, d) |
| 781 | } |
| 782 | |
| 783 | // sharedAsset serves an asset to somebody holding a share link. The |
| 784 | // token is the whole capability, exactly as it is for the page the |
| 785 | // image is on (share.go). |
| 786 | func (a *app) sharedAsset(w http.ResponseWriter, r *http.Request) { |
| 787 | d, _, ok := a.deckForShareLink(w, r, chi.URLParam(r, "token")) |
| 788 | if !ok { |
| 789 | return |
| 790 | } |
| 791 | a.serveAsset(w, r, d) |
| 792 | } |
| 793 | |
| 794 | // presentAsset serves an asset to a projector, a presenter's phone or |
| 795 | // an audience following along — none of which has a session |
| 796 | // (presentation.go). The session sqid is the capability. |
| 797 | func (a *app) presentAsset(w http.ResponseWriter, r *http.Request) { |
| 798 | p, ok := a.presentationFor(w, r) |
| 799 | if !ok { |
| 800 | return |
| 801 | } |
| 802 | d, ok := a.deckOf(w, r, p) |
| 803 | if !ok { |
| 804 | return |
| 805 | } |
| 806 | a.serveAsset(w, r, d) |
| 807 | } |
| 808 | |
| 809 | // serveAsset is the one body behind all three: check that this ref was |
| 810 | // verified for this deck AND that the deck really refers to it, then |
| 811 | // hand over the bytes. |
| 812 | // |
| 813 | // Both checks are the security property, and they answer different |
| 814 | // questions. The deck's `assets` map says the deck refers to the ref — |
| 815 | // without that, any capability for any deck would fetch any object in |
| 816 | // the bucket, because a ref is a content address and knowing one is |
| 817 | // knowing the sha256 of somebody's file. The deck_assets row says |
| 818 | // registerAsset READ the bytes and passed them — without that, a |
| 819 | // member could presign a PUT for an unsanitised SVG, name its ref in a |
| 820 | // `register_asset` op (which nothing checks), and have this app serve |
| 821 | // a script under its own origin. The row is checked first because it |
| 822 | // is one indexed read and the map costs an openDeck per image. |
| 823 | func (a *app) serveAsset(w http.ResponseWriter, r *http.Request, d Deck) { |
| 824 | ref := chi.URLParam(r, "ref") |
| 825 | if !assetRefPattern.MatchString(ref) { |
| 826 | a.notFound(w, r) |
| 827 | return |
| 828 | } |
| 829 | store := a.cfg.Blobs |
| 830 | if store == nil { |
| 831 | a.notFound(w, r) |
| 832 | return |
| 833 | } |
| 834 | |
| 835 | var verified int64 |
| 836 | if err := a.db.G.WithContext(r.Context()).Model(&DeckAsset{}). |
| 837 | Where("deck_id = ? AND ref = ?", d.ID, ref).Count(&verified).Error; err != nil { |
| 838 | a.fail(w, r, "look up a verified asset", err) |
| 839 | return |
| 840 | } |
| 841 | if verified == 0 { |
| 842 | a.notFound(w, r) |
| 843 | return |
| 844 | } |
| 845 | |
| 846 | h, view, err := a.openDeck(r.Context(), d) |
| 847 | if err != nil { |
| 848 | a.fail(w, r, "open a deck to serve an asset", err) |
| 849 | return |
| 850 | } |
| 851 | defer h.Close(r.Context()) |
| 852 | registered, video := false, false |
| 853 | for _, asset := range view.Assets { |
| 854 | if asset.Ref == ref { |
| 855 | registered = true |
| 856 | video = video || asset.Video() |
| 857 | } |
| 858 | } |
| 859 | if !registered { |
| 860 | // The same answer as a ref that is not in the store at all: a |
| 861 | // reader of this deck learns nothing about what other decks |
| 862 | // hold. |
| 863 | a.notFound(w, r) |
| 864 | return |
| 865 | } |
| 866 | |
| 867 | if p, canPresign := store.(presigner); canPresign { |
| 868 | url, err := p.PresignGet(ref, presignTTL) |
| 869 | if err != nil { |
| 870 | a.fail(w, r, "presign an asset", err) |
| 871 | return |
| 872 | } |
| 873 | // private, and shorter-lived than the URL it points at: the |
| 874 | // redirect is per-reader and the URL inside it expires. |
| 875 | w.Header().Set("Cache-Control", "private, max-age=300") |
| 876 | http.Redirect(w, r, url, http.StatusFound) |
| 877 | return |
| 878 | } |
| 879 | |
| 880 | // A clip's video (clips.go) is served in ranges from the clip cache |
| 881 | // (clipcache.go), which reads the store once for it, whoever asks |
| 882 | // and however many at once. |
| 883 | cache := a.clipCacheFor() |
| 884 | if video { |
| 885 | assetCaching(w, ref) |
| 886 | if notModified(w, r, ref) { |
| 887 | return |
| 888 | } |
| 889 | a.serveCachedVideo(w, r, cache, ref, videoLoad(r.Context(), store, ref)) |
| 890 | return |
| 891 | } |
| 892 | |
| 893 | rc, err := store.Get(r.Context(), ref) |
| 894 | if err != nil { |
| 895 | if errors.Is(err, blobs.ErrNotFound) { |
| 896 | a.notFound(w, r) |
| 897 | return |
| 898 | } |
| 899 | a.fail(w, r, "read an asset", err) |
| 900 | return |
| 901 | } |
| 902 | defer rc.Close() |
| 903 | // Streamed, not read whole: the bucket is served through this app |
| 904 | // (ThroughApp), and a deck of large photos opened by a few readers |
| 905 | // at once would otherwise hold 20 MiB per picture per request. The |
| 906 | // sniff needs only the head (sniffImage reads 1 KiB), which is read |
| 907 | // first and sent ahead of the rest. |
| 908 | head := make([]byte, 1024) |
| 909 | n, err := io.ReadFull(rc, head) |
| 910 | if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) { |
| 911 | a.fail(w, r, "read an asset", err) |
| 912 | return |
| 913 | } |
| 914 | head = head[:n] |
| 915 | // Bytes that open as a video, under an asset with no poster (an op |
| 916 | // written by hand), are still a video: no picture opens as one does. |
| 917 | kind := sniffVideo(head) |
| 918 | video = kind != "" |
| 919 | if !video { |
| 920 | kind = sniffImage(head) |
| 921 | } |
| 922 | if kind == "" { |
| 923 | a.notFound(w, r) |
| 924 | return |
| 925 | } |
| 926 | assetCaching(w, ref) |
| 927 | if notModified(w, r, ref) { |
| 928 | return |
| 929 | } |
| 930 | if video { |
| 931 | a.serveCachedVideo(w, r, cache, ref, func() (string, io.Reader, func(), error) { |
| 932 | if rs, ok := rc.(io.ReadSeeker); ok { |
| 933 | return kind, rs, func() {}, nil |
| 934 | } |
| 935 | return kind, io.MultiReader(bytes.NewReader(head), rc), func() {}, nil |
| 936 | }) |
| 937 | return |
| 938 | } |
| 939 | assetHeaders(w, kind) |
| 940 | w.Write(head) |
| 941 | io.Copy(w, io.LimitReader(rc, maxAssetBytes-int64(len(head)))) |
| 942 | } |
| 943 | |
| 944 | // assetCaching is how long a served asset may be kept, and its |
| 945 | // validator. Content-addressed: these bytes are these bytes forever, so |
| 946 | // a year is honest. Private rather than public — the address is the |
| 947 | // deck's capability, not the object's. The ref is the content hash, so |
| 948 | // it is an honest strong validator. |
| 949 | func assetCaching(w http.ResponseWriter, ref string) { |
| 950 | w.Header().Set("Cache-Control", "private, max-age=31536000, immutable") |
| 951 | w.Header().Set("ETag", `"`+ref+`"`) |
| 952 | } |
| 953 | |
| 954 | // notModified answers 304 when the reader already has ref. |
| 955 | func notModified(w http.ResponseWriter, r *http.Request, ref string) bool { |
| 956 | if match := r.Header.Get("If-None-Match"); match != "" && strings.Contains(match, `"`+ref+`"`) { |
| 957 | w.WriteHeader(http.StatusNotModified) |
| 958 | return true |
| 959 | } |
| 960 | return false |
| 961 | } |
| 962 | |
| 963 | // assetHeaders is the header set every served asset carries. |
| 964 | // |
| 965 | // The Content-Security-Policy is the belt to svg.go's braces. An SVG |
| 966 | // comes back from this app's OWN origin, so a script inside one would |
| 967 | // run with every cookie this app has; svg.go strips them, and this says |
| 968 | // that even a document that somehow got past it can load nothing, |
| 969 | // script nothing and reach nowhere. Costless for a PNG and decisive for |
| 970 | // the one format where it matters. |
| 971 | func assetHeaders(w http.ResponseWriter, kind string) { |
| 972 | w.Header().Set("Content-Type", kind) |
| 973 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 974 | w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox") |
| 975 | // An asset is a picture on a page, never a page. Said out loud so a |
| 976 | // reader who does navigate straight to one gets a download rather |
| 977 | // than a document rendered on this origin. |
| 978 | w.Header().Set("Content-Disposition", "inline") |
| 979 | } |
| 980 | |
| 981 | // --- answering --- |
| 982 | |
| 983 | // writeAssetJSON is the shape every answer on these endpoints takes, |
| 984 | // buffered before the status line the way every other JSON answer in |
| 985 | // this app is (api.go's writeJSON). |
| 986 | func writeAssetJSON(w http.ResponseWriter, status int, body any) { |
| 987 | b, err := json.Marshal(body) |
| 988 | if err != nil { |
| 989 | http.Error(w, "something went wrong", http.StatusInternalServerError) |
| 990 | return |
| 991 | } |
| 992 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 993 | w.Header().Set("Cache-Control", "no-store") |
| 994 | w.WriteHeader(status) |
| 995 | _, _ = w.Write(b) |
| 996 | } |
| 997 | |
| 998 | // assetFail is one refusal: a fixed identifier the bundle branches on, |
| 999 | // and a message from the catalog for it to show. Two fields rather than |
| 1000 | // one for the reason api.go gives — a program reads the same word |
| 1001 | // whatever Accept-Language it sent, and a person reads their own. |
| 1002 | func assetFail(w http.ResponseWriter, r *http.Request, status int, code, messageKey string) { |
| 1003 | writeAssetJSON(w, status, map[string]string{ |
| 1004 | "error": code, |
| 1005 | "message": rastrillo.T(r, "slides.assets.error."+messageKey), |
| 1006 | }) |
| 1007 | } |
| 1008 | |
| 1009 | // trimTo trims a string and cuts it to at most n bytes, never through |
| 1010 | // the middle of a rune. |
| 1011 | func trimTo(v string, n int) string { |
| 1012 | v = strings.TrimSpace(v) |
| 1013 | if len(v) <= n { |
| 1014 | return v |
| 1015 | } |
| 1016 | cut := v[:n] |
| 1017 | for len(cut) > 0 && !utf8.ValidString(cut) { |
| 1018 | cut = cut[:len(cut)-1] |
| 1019 | } |
| 1020 | return cut |
| 1021 | } |
| 1022 | |
| 1023 | // boundDimension keeps a client-reported pixel size inside something a |
| 1024 | // picture could be. Out of range becomes 0, which the renderer reads as |
| 1025 | // "no intrinsic size" and simply omits from the <img>. |
| 1026 | func boundDimension(v int) int { |
| 1027 | if v <= 0 || v > maxAssetDimension { |
| 1028 | return 0 |
| 1029 | } |
| 1030 | return v |
| 1031 | } |
| 1032 | |
| 1033 | // assetBaseFor is the path a surface's images are served from — what |
| 1034 | // render.Options.AssetBase wants. One function so the three surfaces |
| 1035 | // cannot each spell it slightly differently from the routes app.go |
| 1036 | // registers. |
| 1037 | func assetBaseFor(base string) string { return strings.TrimSuffix(base, "/") + "/assets" } |
| 1038 | |