oficina / estilo Public

typeface: inspect TTF, OTF, WOFF and WOFF2 font files

A new package for apps that keep uploaded fonts. Inspect reads the
table directory and the head, name, OS/2 and fvar tables, bounds-checks
every offset, and returns the family and style names, weight, italic,
variable weight range, outline kind, fsType and a SHA-256 ref. Errors
wrap ErrNotAFont, ErrTooBig or ErrMalformed.

WOFF tables are inflated one by one; a WOFF2 brotli stream is unpacked
whole and must hold exactly its tables, capped at 4x MaxBytes. Pictures
says whether an app's own engines may use a face (static TrueType sfnt
whose fsType allows embedding); Headers sets the serving headers.

Adds github.com/andybalholm/brotli v1.2.7. The test font is Liberation
Sans Regular (SIL OFL 1.1, licence beside it).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 2aae8e89307a70598d548dd4fbeb84f542aeed5f parent b635bc4
7 files changed, +1,408 −0
  • go.mod +1 −0
  • go.sum +4 −0
  • typeface/testdata/LICENSE-OFL-1.1.txt +91 −0
  • typeface/testdata/LiberationSans-Regular.ttf binary
  • typeface/typeface.go +469 −0
  • typeface/typeface_test.go +608 −0
  • typeface/woff.go +235 −0
diff --git a/go.mod b/go.mod
index 9af7908..cb195d4 100644
--- a/go.mod
+++ b/go.mod
@@ -3,6 +3,7 @@ module amadan.net/oficina/estilo.git
go 1.25.0
require (
+ github.com/andybalholm/brotli v1.2.7
github.com/carlosframework/rastrillo v0.23.0
golang.org/x/text v0.20.0
)
diff --git a/go.sum b/go.sum
index be1533c..02e6bbf 100644
--- a/go.sum
+++ b/go.sum
@@ -1,3 +1,5 @@
+github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
+github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/carlosframework/rastrillo v0.23.0 h1:tKAAlwPt4Pg/rkqk7o6jvV12bbZ0r34oEVpuOlKfX7w=
github.com/carlosframework/rastrillo v0.23.0/go.mod h1:pZlrE5F5OhspvZFzef0DrfjHAjA8FXycb9J5/8vc8Tw=
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 h1:UQ4AU+BGti3Sy/aLU8KVseYKNALcX9UXY6DfpwQ6J8E=
@@ -38,6 +40,8 @@ github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOF
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
+github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
diff --git a/typeface/testdata/LICENSE-OFL-1.1.txt b/typeface/testdata/LICENSE-OFL-1.1.txt
new file mode 100644
index 0000000..84619fc
--- /dev/null
+++ b/typeface/testdata/LICENSE-OFL-1.1.txt
@@ -0,0 +1,91 @@
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+
+PREAMBLE The goals of the Open Font License (OFL) are to stimulate
+worldwide development of collaborative font projects, to support the font
+creation efforts of academic and linguistic communities, and to provide
+a free and open framework in which fonts may be shared and improved in
+partnership with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves.
+The fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply to
+any document created using the fonts or their derivatives.
+
+
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such.
+This may include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components
+as distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting ? in part or in whole ?
+any of the components of the Original Version, by changing formats or
+by porting the Font Software to a new environment.
+
+"Author" refers to any designer, engineer, programmer, technical writer
+or other person who contributed to the Font Software.
+
+
+PERMISSION & CONDITIONS
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,in
+ Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+ redistributed and/or sold with any software, provided that each copy
+ contains the above copyright notice and this license. These can be
+ included either as stand-alone text files, human-readable headers or
+ in the appropriate machine-readable metadata fields within text or
+ binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+ Name(s) unless explicit written permission is granted by the
+ corresponding Copyright Holder. This restriction only applies to the
+ primary font name as presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+ Software shall not be used to promote, endorse or advertise any
+ Modified Version, except to acknowledge the contribution(s) of the
+ Copyright Holder(s) and the Author(s) or with their explicit written
+ permission.
+
+5) The Font Software, modified or unmodified, in part or in whole, must
+ be distributed entirely under this license, and must not be distributed
+ under any other license. The requirement for fonts to remain under
+ this license does not apply to any document created using the Font
+ Software.
+
+
+
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+
+
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
+DEALINGS IN THE FONT SOFTWARE.
+
diff --git a/typeface/testdata/LiberationSans-Regular.ttf b/typeface/testdata/LiberationSans-Regular.ttf
new file mode 100644
index 0000000..f524339
Binary files /dev/null and b/typeface/testdata/LiberationSans-Regular.ttf differ
diff --git a/typeface/typeface.go b/typeface/typeface.go
new file mode 100644
index 0000000..70f56b1
--- /dev/null
+++ b/typeface/typeface.go
@@ -0,0 +1,469 @@
+// Package typeface reads what an app needs to know about an uploaded font
+// file before it keeps it: the family and style names, weight, italic,
+// whether it is variable, its outline kind, its embedding flags and a
+// SHA-256 ref. It also says whether the app's own layout and PDF engines
+// may use the face (Pictures) and sets the headers for serving it.
+//
+// It takes TTF, OTF, WOFF and WOFF2 and nothing else. It reads only the
+// table directory and the head, name, OS/2 and fvar tables, bounds-checks
+// every offset against the bytes it has, and believes no length it has not
+// checked. It has no storage and no routes: the app gives it bytes.
+package typeface
+
+import (
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+ "unicode"
+ "unicode/utf16"
+
+ "golang.org/x/text/encoding/charmap"
+)
+
+// Limits on what a person may keep. Inspect enforces MaxBytes; the other
+// two are for the app that keeps the faces.
+const (
+ MaxBytes = 10 << 20
+ MaxFacesPerFamily = 16
+ MaxFamilies = 32
+)
+
+// maxUnpacked caps how much a WOFF or WOFF2 may unpack to, so a small file
+// that expands enormously is refused rather than unpacked.
+const maxUnpacked = 4 * MaxBytes
+
+// maxNameRunes caps a family or style name. Real ones are a few words.
+const maxNameRunes = 256
+
+// Format is the file's container.
+type Format string
+
+const (
+ TTF Format = "ttf"
+ OTF Format = "otf"
+ WOFF Format = "woff"
+ WOFF2 Format = "woff2"
+)
+
+// Outline is the kind of glyph outlines the face carries.
+type Outline string
+
+const (
+ TrueType Outline = "truetype"
+ CFF Outline = "cff"
+)
+
+// Face is what Inspect learned about one font file.
+type Face struct {
+ Ref string // lowercase hex SHA-256 of the file as given
+ Format Format // the container
+ Outline Outline // TrueType (glyf) or CFF outlines
+ Family string // name ID 16, else 1
+ Style string // name ID 17, else 2
+ Weight int // OS/2 usWeightClass, 1..1000
+ WeightMin int // = Weight unless variable
+ WeightMax int // = Weight unless variable
+ Italic bool // OS/2 fsSelection bit 0 or head macStyle bit 1
+ Variable bool // fvar present with a 'wght' axis
+ FSType uint16 // OS/2 fsType, the embedding flags
+}
+
+// The errors Inspect returns wrap one of these, so a caller can tell a
+// file that is not a font it takes from one that is too big from one that
+// is broken.
+var (
+ ErrNotAFont = errors.New("typeface: not a TTF, OTF, WOFF or WOFF2 file")
+ ErrTooBig = errors.New("typeface: font file too big")
+ ErrMalformed = errors.New("typeface: malformed font file")
+)
+
+func malformed(format string, args ...any) error {
+ return fmt.Errorf("%w: "+format, append([]any{ErrMalformed}, args...)...)
+}
+
+// Signatures: the first four bytes of the file, and an sfnt's version.
+const (
+ sigTrueType = 0x00010000
+ sigTrue = 0x74727565 // 'true', Apple's TrueType
+ sigOTTO = 0x4F54544F // 'OTTO', CFF outlines
+ sigTTCF = 0x74746366 // 'ttcf', a collection
+ sigWOFF = 0x774F4646 // 'wOFF'
+ sigWOFF2 = 0x774F4632 // 'wOF2'
+)
+
+// fontTables is an sfnt after unwrapping: its version, the tags it has,
+// and the bytes of the tables Inspect reads.
+type fontTables struct {
+ version uint32
+ has map[string]bool
+ data map[string][]byte
+}
+
+// wanted are the only tables whose bytes Inspect reads.
+func wanted(tag string) bool {
+ switch tag {
+ case "head", "name", "OS/2", "fvar":
+ return true
+ }
+ return false
+}
+
+// Inspect reads a font file. It refuses anything over MaxBytes
+// (ErrTooBig), anything that is not TTF, OTF, WOFF or WOFF2 (ErrNotAFont)
+// and anything it cannot read in full (ErrMalformed).
+func Inspect(data []byte) (Face, error) {
+ if len(data) > MaxBytes {
+ return Face{}, fmt.Errorf("%w: %d bytes, the limit is %d", ErrTooBig, len(data), MaxBytes)
+ }
+ if len(data) < 4 {
+ return Face{}, ErrNotAFont
+ }
+ var (
+ format Format
+ ft fontTables
+ err error
+ )
+ switch binary.BigEndian.Uint32(data) {
+ case sigTrueType, sigTrue:
+ format = TTF
+ ft, err = readSFNT(data)
+ case sigOTTO:
+ format = OTF
+ ft, err = readSFNT(data)
+ case sigWOFF:
+ format = WOFF
+ ft, err = readWOFF(data)
+ case sigWOFF2:
+ format = WOFF2
+ ft, err = readWOFF2(data)
+ case sigTTCF:
+ return Face{}, fmt.Errorf("%w: font collections are not taken", ErrNotAFont)
+ default:
+ return Face{}, ErrNotAFont
+ }
+ if err != nil {
+ return Face{}, err
+ }
+ f, err := describe(ft)
+ if err != nil {
+ return Face{}, err
+ }
+ sum := sha256.Sum256(data)
+ f.Ref = hex.EncodeToString(sum[:])
+ f.Format = format
+ return f, nil
+}
+
+// checkFlavor refuses a WOFF or WOFF2 wrapping something other than a
+// single TrueType or CFF sfnt.
+func checkFlavor(flavor uint32) error {
+ switch flavor {
+ case sigTrueType, sigTrue, sigOTTO:
+ return nil
+ case sigTTCF:
+ return fmt.Errorf("%w: font collections are not taken", ErrNotAFont)
+ }
+ return malformed("unknown flavor %#08x", flavor)
+}
+
+// readSFNT reads a bare sfnt's table directory. Every table, read or not,
+// must lie inside the file, and no tag may appear twice.
+func readSFNT(data []byte) (fontTables, error) {
+ if len(data) < 12 {
+ return fontTables{}, malformed("sfnt header cut short")
+ }
+ n := int(binary.BigEndian.Uint16(data[4:]))
+ if n == 0 {
+ return fontTables{}, malformed("no tables")
+ }
+ if 12+16*n > len(data) {
+ return fontTables{}, malformed("table directory cut short: %d tables", n)
+ }
+ ft := fontTables{version: binary.BigEndian.Uint32(data), has: map[string]bool{}, data: map[string][]byte{}}
+ for i := 0; i < n; i++ {
+ rec := data[12+16*i:]
+ tag := string(rec[:4])
+ off := uint64(binary.BigEndian.Uint32(rec[8:]))
+ length := uint64(binary.BigEndian.Uint32(rec[12:]))
+ if off+length > uint64(len(data)) {
+ return fontTables{}, malformed("table %q runs past the end of the file", tag)
+ }
+ if ft.has[tag] {
+ return fontTables{}, malformed("table %q appears twice", tag)
+ }
+ ft.has[tag] = true
+ if wanted(tag) {
+ ft.data[tag] = data[off : off+length]
+ }
+ }
+ return ft, nil
+}
+
+// describe turns the tables into a Face (all but Ref and Format).
+func describe(ft fontTables) (Face, error) {
+ var f Face
+ switch {
+ case ft.version == sigOTTO || ft.has["CFF "] || ft.has["CFF2"]:
+ f.Outline = CFF
+ case ft.has["glyf"]:
+ f.Outline = TrueType
+ default:
+ return Face{}, malformed("no glyf or CFF outlines")
+ }
+
+ head, ok := ft.data["head"]
+ if !ok {
+ return Face{}, malformed("no head table")
+ }
+ if len(head) < 54 || binary.BigEndian.Uint32(head[12:]) != 0x5F0F3CF5 {
+ return Face{}, malformed("head table is not one")
+ }
+ macStyle := binary.BigEndian.Uint16(head[44:])
+
+ os2, ok := ft.data["OS/2"]
+ if !ok {
+ return Face{}, malformed("no OS/2 table")
+ }
+ if len(os2) < 64 {
+ return Face{}, malformed("OS/2 table cut short")
+ }
+ f.Weight = clampWeight(int(binary.BigEndian.Uint16(os2[4:])))
+ if f.Weight == 0 {
+ f.Weight = 400 // unset: the weight a browser assumes
+ }
+ f.FSType = binary.BigEndian.Uint16(os2[8:])
+ fsSelection := binary.BigEndian.Uint16(os2[62:])
+ f.Italic = fsSelection&0x0001 != 0 || macStyle&0x0002 != 0
+ f.WeightMin, f.WeightMax = f.Weight, f.Weight
+
+ name, ok := ft.data["name"]
+ if !ok {
+ return Face{}, malformed("no name table")
+ }
+ names, err := readNames(name)
+ if err != nil {
+ return Face{}, err
+ }
+ f.Family = firstOf(names, 16, 1)
+ f.Style = firstOf(names, 17, 2)
+ if f.Family == "" {
+ return Face{}, malformed("no family name")
+ }
+
+ if fv, ok := ft.data["fvar"]; ok {
+ lo, hi, isVar, err := weightAxis(fv)
+ if err != nil {
+ return Face{}, err
+ }
+ if isVar {
+ f.Variable = true
+ f.WeightMin, f.WeightMax = lo, hi
+ }
+ }
+ return f, nil
+}
+
+// clampWeight keeps a weight within CSS's 1..1000, leaving 0 for unset.
+func clampWeight(w int) int {
+ return min(max(w, 0), 1000)
+}
+
+// weightAxis reads fvar and returns the 'wght' axis's range, if it has one.
+func weightAxis(fv []byte) (lo, hi int, ok bool, err error) {
+ if len(fv) < 16 {
+ return 0, 0, false, malformed("fvar header cut short")
+ }
+ axesAt := int(binary.BigEndian.Uint16(fv[4:]))
+ count := int(binary.BigEndian.Uint16(fv[8:]))
+ size := int(binary.BigEndian.Uint16(fv[10:]))
+ if size < 20 {
+ return 0, 0, false, malformed("fvar axis records of %d bytes", size)
+ }
+ if axesAt+count*size > len(fv) {
+ return 0, 0, false, malformed("fvar axes run past the table")
+ }
+ for i := 0; i < count; i++ {
+ a := fv[axesAt+i*size:]
+ if string(a[:4]) != "wght" {
+ continue
+ }
+ minV := fixed(binary.BigEndian.Uint32(a[4:]))
+ maxV := fixed(binary.BigEndian.Uint32(a[12:]))
+ lo, hi = max(clampWeight(minV), 1), max(clampWeight(maxV), 1)
+ if lo > hi {
+ return 0, 0, false, malformed("wght axis runs from %d down to %d", lo, hi)
+ }
+ return lo, hi, true, nil
+ }
+ return 0, 0, false, nil
+}
+
+// fixed rounds a 16.16 fixed-point number to the nearest integer.
+func fixed(v uint32) int {
+ return int((int64(int32(v)) + 0x8000) >> 16)
+}
+
+// nameKey is a name record's identity: which name, on which platform,
+// encoding and language.
+type nameKey struct{ platform, encoding, language, id uint16 }
+
+// readNames decodes the name records Inspect can use: platform 3
+// (Windows) and platform 0 (Unicode) in UTF-16BE, platform 1 (Mac) in
+// Mac Roman. Other records are skipped; every record must still lie
+// inside the table.
+func readNames(t []byte) (map[nameKey]string, error) {
+ if len(t) < 6 {
+ return nil, malformed("name table cut short")
+ }
+ count := int(binary.BigEndian.Uint16(t[2:]))
+ storage := int(binary.BigEndian.Uint16(t[4:]))
+ if 6+12*count > len(t) {
+ return nil, malformed("name records run past the table")
+ }
+ out := map[nameKey]string{}
+ for i := 0; i < count; i++ {
+ r := t[6+12*i:]
+ k := nameKey{
+ platform: binary.BigEndian.Uint16(r[0:]),
+ encoding: binary.BigEndian.Uint16(r[2:]),
+ language: binary.BigEndian.Uint16(r[4:]),
+ id: binary.BigEndian.Uint16(r[6:]),
+ }
+ length := int(binary.BigEndian.Uint16(r[8:]))
+ off := storage + int(binary.BigEndian.Uint16(r[10:]))
+ if off+length > len(t) {
+ return nil, malformed("name record %d runs past the table", i)
+ }
+ if k.id != 1 && k.id != 2 && k.id != 16 && k.id != 17 {
+ continue
+ }
+ raw := t[off : off+length]
+ var s string
+ switch {
+ case k.platform == 3 && (k.encoding == 0 || k.encoding == 1 || k.encoding == 10),
+ k.platform == 0:
+ s = utf16BE(raw)
+ case k.platform == 1 && k.encoding == 0:
+ b, err := charmap.Macintosh.NewDecoder().Bytes(raw)
+ if err != nil {
+ continue
+ }
+ s = string(b)
+ default:
+ continue
+ }
+ s = clean(s)
+ if len([]rune(s)) > maxNameRunes {
+ return nil, malformed("name %d is longer than %d characters", k.id, maxNameRunes)
+ }
+ out[k] = s
+ }
+ return out, nil
+}
+
+func utf16BE(b []byte) string {
+ u := make([]uint16, len(b)/2)
+ for i := range u {
+ u[i] = binary.BigEndian.Uint16(b[2*i:])
+ }
+ return string(utf16.Decode(u))
+}
+
+// clean drops control characters and surrounding space.
+func clean(s string) string {
+ s = strings.Map(func(r rune) rune {
+ if unicode.IsControl(r) {
+ return -1
+ }
+ return r
+ }, s)
+ return strings.TrimSpace(s)
+}
+
+// firstOf returns the best non-empty name among ids, tried in order. For
+// one id the platforms go Windows, then Mac, then Unicode; English (US
+// on Windows, language 0 on Mac) before any other language.
+func firstOf(names map[nameKey]string, ids ...uint16) string {
+ for _, id := range ids {
+ best, rank := "", 0
+ for k, s := range names {
+ if k.id != id || s == "" {
+ continue
+ }
+ r := nameRank(k)
+ // Ties between other languages go to the lowest key, so the
+ // answer does not depend on map order.
+ if r > rank || (r == rank && rank > 0 && s < best) {
+ best, rank = s, r
+ }
+ }
+ if best != "" {
+ return best
+ }
+ }
+ return ""
+}
+
+func nameRank(k nameKey) int {
+ switch {
+ case k.platform == 3 && k.language == 0x0409:
+ return 6
+ case k.platform == 3:
+ return 5
+ case k.platform == 1 && k.language == 0:
+ return 4
+ case k.platform == 1:
+ return 3
+ case k.platform == 0:
+ return 2
+ }
+ return 1
+}
+
+// Pictures reports whether the app's own layout and PDF engines may use
+// the face: a static, TrueType-outline, bare sfnt (not WOFF or WOFF2)
+// whose fsType allows embedding it. fsType 0 (installable),
+// 0x0004 (preview and print) and 0x0008 (editable) allow it; the
+// restricted-licence bit (0x0002) and bitmap-only (0x0200) do not, even
+// alongside a less restrictive bit.
+func (f Face) Pictures() bool {
+ return !f.Variable &&
+ f.Outline == TrueType &&
+ (f.Format == TTF || f.Format == OTF) &&
+ f.FSType&0x0002 == 0 &&
+ f.FSType&0x0200 == 0
+}
+
+// ContentType is the face's media type.
+func (f Face) ContentType() string {
+ return contentType(f.Format)
+}
+
+func contentType(f Format) string {
+ switch f {
+ case TTF:
+ return "font/ttf"
+ case OTF:
+ return "font/otf"
+ case WOFF:
+ return "font/woff"
+ case WOFF2:
+ return "font/woff2"
+ }
+ return "application/octet-stream"
+}
+
+// Headers sets the headers for serving a font file by its ref: its media
+// type, no sniffing, a year's immutable caching (the ref is the file's
+// hash, so its bytes never change) and a policy that lets it load nothing.
+func Headers(w http.ResponseWriter, f Format) {
+ h := w.Header()
+ h.Set("Content-Type", contentType(f))
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("Cache-Control", "public, max-age=31536000, immutable")
+ h.Set("Content-Security-Policy", "default-src 'none'")
+}
diff --git a/typeface/typeface_test.go b/typeface/typeface_test.go
new file mode 100644
index 0000000..7006c0b
--- /dev/null
+++ b/typeface/typeface_test.go
@@ -0,0 +1,608 @@
+package typeface
+
+import (
+ "bytes"
+ "compress/zlib"
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/hex"
+ "errors"
+ "net/http/httptest"
+ "os"
+ "sort"
+ "testing"
+
+ "github.com/andybalholm/brotli"
+)
+
+// The test font is Liberation Sans Regular (SIL OFL 1.1; the licence is
+// beside it in testdata). Every other file these tests read is built from
+// it here: WOFF and WOFF2 copies, and synthetic sfnts with one table
+// swapped or patched.
+
+type table struct {
+ tag string
+ data []byte
+}
+
+func liberation(t *testing.T) []byte {
+ t.Helper()
+ b, err := os.ReadFile("testdata/LiberationSans-Regular.ttf")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// tablesOf reads an sfnt's version and tables, in directory order.
+func tablesOf(t *testing.T, sfnt []byte) (uint32, []table) {
+ t.Helper()
+ n := int(binary.BigEndian.Uint16(sfnt[4:]))
+ var ts []table
+ for i := 0; i < n; i++ {
+ rec := sfnt[12+16*i:]
+ off := binary.BigEndian.Uint32(rec[8:])
+ length := binary.BigEndian.Uint32(rec[12:])
+ ts = append(ts, table{string(rec[:4]), bytes.Clone(sfnt[off : off+length])})
+ }
+ return binary.BigEndian.Uint32(sfnt), ts
+}
+
+// buildSFNT writes an sfnt with the tables sorted by tag, each padded to
+// four bytes. Checksums are left zero: Inspect does not read them.
+func buildSFNT(version uint32, ts []table) []byte {
+ ts = append([]table(nil), ts...)
+ sort.Slice(ts, func(i, j int) bool { return ts[i].tag < ts[j].tag })
+ var b []byte
+ b = binary.BigEndian.AppendUint32(b, version)
+ b = binary.BigEndian.AppendUint16(b, uint16(len(ts)))
+ b = append(b, 0, 0, 0, 0, 0, 0) // searchRange and friends: unread
+ off := 12 + 16*len(ts)
+ for _, tb := range ts {
+ b = append(b, tb.tag...)
+ b = binary.BigEndian.AppendUint32(b, 0)
+ b = binary.BigEndian.AppendUint32(b, uint32(off))
+ b = binary.BigEndian.AppendUint32(b, uint32(len(tb.data)))
+ off += (len(tb.data) + 3) &^ 3
+ }
+ for _, tb := range ts {
+ b = append(b, tb.data...)
+ for len(b)%4 != 0 {
+ b = append(b, 0)
+ }
+ }
+ return b
+}
+
+func withTable(ts []table, tag string, data []byte) []table {
+ out := withoutTable(ts, tag)
+ return append(out, table{tag, data})
+}
+
+func withoutTable(ts []table, tags ...string) []table {
+ var out []table
+ for _, tb := range ts {
+ drop := false
+ for _, tag := range tags {
+ drop = drop || tb.tag == tag
+ }
+ if !drop {
+ out = append(out, tb)
+ }
+ }
+ return out
+}
+
+func tableData(ts []table, tag string) []byte {
+ for _, tb := range ts {
+ if tb.tag == tag {
+ return tb.data
+ }
+ }
+ return nil
+}
+
+// patched is Liberation with its OS/2 fsType and fsSelection set.
+func patched(t *testing.T, fsType, fsSelection uint16) []byte {
+ t.Helper()
+ v, ts := tablesOf(t, liberation(t))
+ os2 := bytes.Clone(tableData(ts, "OS/2"))
+ binary.BigEndian.PutUint16(os2[8:], fsType)
+ binary.BigEndian.PutUint16(os2[62:], fsSelection)
+ return buildSFNT(v, withTable(ts, "OS/2", os2))
+}
+
+// cff is Liberation's metadata tables in an OTTO with a stub CFF table
+// where its glyf and loca were.
+func cff(t *testing.T) []byte {
+ t.Helper()
+ _, ts := tablesOf(t, liberation(t))
+ ts = withoutTable(ts, "glyf", "loca")
+ ts = append(ts, table{"CFF ", []byte{1, 0, 4, 1}})
+ return buildSFNT(0x4F54544F, ts)
+}
+
+type axis struct {
+ tag string
+ min, def, max float64
+}
+
+func fvar(axes ...axis) []byte {
+ var b []byte
+ b = binary.BigEndian.AppendUint16(b, 1) // majorVersion
+ b = binary.BigEndian.AppendUint16(b, 0) // minorVersion
+ b = binary.BigEndian.AppendUint16(b, 16) // axesArrayOffset
+ b = binary.BigEndian.AppendUint16(b, 2) // reserved
+ b = binary.BigEndian.AppendUint16(b, uint16(len(axes)))
+ b = binary.BigEndian.AppendUint16(b, 20) // axisSize
+ b = binary.BigEndian.AppendUint16(b, 0) // instanceCount
+ b = binary.BigEndian.AppendUint16(b, uint16(4+4*len(axes)))
+ for _, a := range axes {
+ b = append(b, a.tag...)
+ for _, v := range []float64{a.min, a.def, a.max} {
+ b = binary.BigEndian.AppendUint32(b, uint32(int32(v*65536)))
+ }
+ b = binary.BigEndian.AppendUint16(b, 0) // flags
+ b = binary.BigEndian.AppendUint16(b, 256) // axisNameID
+ }
+ return b
+}
+
+func variable(t *testing.T, axes ...axis) []byte {
+ t.Helper()
+ v, ts := tablesOf(t, liberation(t))
+ return buildSFNT(v, withTable(ts, "fvar", fvar(axes...)))
+}
+
+type nameRec struct {
+ platform, encoding, language, id uint16
+ value string
+}
+
+// nameTable builds a format 0 name table: platform 1 strings in Mac
+// Roman (ASCII here, plus é as 0x8E), everything else UTF-16BE.
+func nameTable(recs ...nameRec) []byte {
+ var storage []byte
+ var b []byte
+ b = binary.BigEndian.AppendUint16(b, 0)
+ b = binary.BigEndian.AppendUint16(b, uint16(len(recs)))
+ b = binary.BigEndian.AppendUint16(b, uint16(6+12*len(recs)))
+ for _, r := range recs {
+ var s []byte
+ if r.platform == 1 {
+ for _, c := range r.value {
+ if c == 'é' {
+ s = append(s, 0x8E)
+ } else {
+ s = append(s, byte(c))
+ }
+ }
+ } else {
+ for _, c := range r.value {
+ s = binary.BigEndian.AppendUint16(s, uint16(c))
+ }
+ }
+ for _, v := range []uint16{r.platform, r.encoding, r.language, r.id, uint16(len(s)), uint16(len(storage))} {
+ b = binary.BigEndian.AppendUint16(b, v)
+ }
+ storage = append(storage, s...)
+ }
+ return append(b, storage...)
+}
+
+func named(t *testing.T, recs ...nameRec) []byte {
+ t.Helper()
+ v, ts := tablesOf(t, liberation(t))
+ return buildSFNT(v, withTable(ts, "name", nameTable(recs...)))
+}
+
+// buildWOFF wraps an sfnt in WOFF 1.0, each table zlib-compressed (or
+// stored when that is no smaller, as the format requires).
+func buildWOFF(t *testing.T, sfnt []byte) []byte {
+ t.Helper()
+ flavor, ts := tablesOf(t, sfnt)
+ sort.Slice(ts, func(i, j int) bool { return ts[i].tag < ts[j].tag })
+ type entry struct {
+ tag string
+ comp []byte
+ origLength int
+ offset int
+ storedLength int
+ }
+ var es []entry
+ off := 44 + 20*len(ts)
+ for _, tb := range ts {
+ var z bytes.Buffer
+ w := zlib.NewWriter(&z)
+ w.Write(tb.data)
+ w.Close()
+ comp := z.Bytes()
+ if len(comp) >= len(tb.data) {
+ comp = tb.data
+ }
+ es = append(es, entry{tb.tag, comp, len(tb.data), off, len(comp)})
+ off += (len(comp) + 3) &^ 3
+ }
+ var b []byte
+ b = append(b, "wOFF"...)
+ b = binary.BigEndian.AppendUint32(b, flavor)
+ b = binary.BigEndian.AppendUint32(b, uint32(off)) // length
+ b = binary.BigEndian.AppendUint16(b, uint16(len(ts)))
+ b = binary.BigEndian.AppendUint16(b, 0)
+ b = binary.BigEndian.AppendUint32(b, uint32(len(sfnt)))
+ b = append(b, make([]byte, 4+20)...) // version, metadata, private
+ for _, e := range es {
+ b = append(b, e.tag...)
+ b = binary.BigEndian.AppendUint32(b, uint32(e.offset))
+ b = binary.BigEndian.AppendUint32(b, uint32(e.storedLength))
+ b = binary.BigEndian.AppendUint32(b, uint32(e.origLength))
+ b = binary.BigEndian.AppendUint32(b, 0)
+ }
+ for _, e := range es {
+ b = append(b, e.comp...)
+ for len(b)%4 != 0 {
+ b = append(b, 0)
+ }
+ }
+ return b
+}
+
+var testWOFF2Tags = []string{"cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS", "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc", "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop", "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill"}
+
+func encodeBase128(n uint32) []byte {
+ var out []byte
+ for {
+ out = append([]byte{byte(n & 0x7F)}, out...)
+ n >>= 7
+ if n == 0 {
+ break
+ }
+ }
+ for i := 0; i < len(out)-1; i++ {
+ out[i] |= 0x80
+ }
+ return out
+}
+
+// woff2Entry is a WOFF2 directory entry as written: lengths may lie,
+// which is the point of some refusals.
+type woff2Entry struct {
+ tag string
+ version byte // transform version, the flags' top two bits
+ origLength uint32
+ transform uint32 // written only when the entry is transformed
+}
+
+func woff2Transformed(e woff2Entry) bool {
+ switch e.tag {
+ case "glyf", "loca":
+ return e.version != 3
+ default:
+ return e.version != 0
+ }
+}
+
+func assembleWOFF2(flavor uint32, es []woff2Entry, compressed []byte) []byte {
+ var dir []byte
+ for _, e := range es {
+ idx := 63
+ for i, tag := range testWOFF2Tags {
+ if tag == e.tag {
+ idx = i
+ }
+ }
+ dir = append(dir, e.version<<6|byte(idx))
+ if idx == 63 {
+ dir = append(dir, e.tag...)
+ }
+ dir = append(dir, encodeBase128(e.origLength)...)
+ if woff2Transformed(e) {
+ dir = append(dir, encodeBase128(e.transform)...)
+ }
+ }
+ total := 48 + len(dir) + len(compressed)
+ padded := (total + 3) &^ 3
+ var b []byte
+ b = append(b, "wOF2"...)
+ b = binary.BigEndian.AppendUint32(b, flavor)
+ b = binary.BigEndian.AppendUint32(b, uint32(padded))
+ b = binary.BigEndian.AppendUint16(b, uint16(len(es)))
+ b = binary.BigEndian.AppendUint16(b, 0)
+ b = binary.BigEndian.AppendUint32(b, 0) // totalSfntSize: unread
+ b = binary.BigEndian.AppendUint32(b, uint32(len(compressed)))
+ b = append(b, make([]byte, 4+20)...) // version, metadata, private
+ b = append(b, dir...)
+ b = append(b, compressed...)
+ return append(b, make([]byte, padded-total)...)
+}
+
+func brotliOf(data []byte) []byte {
+ var z bytes.Buffer
+ w := brotli.NewWriterLevel(&z, 5)
+ w.Write(data)
+ w.Close()
+ return z.Bytes()
+}
+
+// woff2Parts is an sfnt's tables as WOFF2 entries, glyf and loca with
+// the null transform, and their concatenation (the uncompressed stream).
+func woff2Parts(t *testing.T, sfnt []byte) (uint32, []woff2Entry, []byte) {
+ t.Helper()
+ flavor, ts := tablesOf(t, sfnt)
+ var es []woff2Entry
+ var stream []byte
+ for _, tb := range ts {
+ e := woff2Entry{tag: tb.tag, origLength: uint32(len(tb.data))}
+ if tb.tag == "glyf" || tb.tag == "loca" {
+ e.version = 3
+ }
+ es = append(es, e)
+ stream = append(stream, tb.data...)
+ }
+ return flavor, es, stream
+}
+
+func buildWOFF2(t *testing.T, sfnt []byte) []byte {
+ t.Helper()
+ flavor, es, stream := woff2Parts(t, sfnt)
+ return assembleWOFF2(flavor, es, brotliOf(stream))
+}
+
+func mustInspect(t *testing.T, data []byte) Face {
+ t.Helper()
+ f, err := Inspect(data)
+ if err != nil {
+ t.Fatalf("Inspect: %v", err)
+ }
+ return f
+}
+
+func TestInspectReadsTheNamesAndStyle(t *testing.T) {
+ data := liberation(t)
+ f := mustInspect(t, data)
+ sum := sha256.Sum256(data)
+ want := Face{
+ Ref: hex.EncodeToString(sum[:]),
+ Format: "ttf",
+ Outline: "truetype",
+ Family: "Liberation Sans",
+ Style: "Regular",
+ Weight: 400,
+ WeightMin: 400,
+ WeightMax: 400,
+ }
+ if f != want {
+ t.Fatalf("Inspect(Liberation Sans)\n got %+v\nwant %+v", f, want)
+ }
+ if f.ContentType() != "font/ttf" {
+ t.Errorf("ContentType = %q", f.ContentType())
+ }
+
+ t.Run("italic from fsSelection", func(t *testing.T) {
+ if f := mustInspect(t, patched(t, 0, 0x0001)); !f.Italic {
+ t.Errorf("fsSelection bit 0 set, Italic = false")
+ }
+ })
+ t.Run("italic from macStyle", func(t *testing.T) {
+ v, ts := tablesOf(t, liberation(t))
+ head := bytes.Clone(tableData(ts, "head"))
+ binary.BigEndian.PutUint16(head[44:], 0x0002)
+ if f := mustInspect(t, buildSFNT(v, withTable(ts, "head", head))); !f.Italic {
+ t.Errorf("macStyle bit 1 set, Italic = false")
+ }
+ })
+ t.Run("typographic names win, Windows before Mac", func(t *testing.T) {
+ f := mustInspect(t, named(t,
+ nameRec{1, 0, 0, 1, "Mac Family"},
+ nameRec{1, 0, 0, 2, "Mac Style"},
+ nameRec{1, 0, 0, 16, "Mac Typo"},
+ nameRec{3, 1, 0x0409, 1, "Win Family"},
+ nameRec{3, 1, 0x0409, 2, "Bold"},
+ nameRec{3, 1, 0x0409, 16, "Café Sans"},
+ nameRec{3, 1, 0x0409, 17, "Semibold"},
+ ))
+ if f.Family != "Café Sans" || f.Style != "Semibold" {
+ t.Errorf("Family, Style = %q, %q; want Café Sans, Semibold", f.Family, f.Style)
+ }
+ })
+ t.Run("legacy names, Mac Roman when there is nothing else", func(t *testing.T) {
+ f := mustInspect(t, named(t,
+ nameRec{1, 0, 0, 1, "Café Mac"},
+ nameRec{1, 0, 0, 2, "Italic"},
+ ))
+ if f.Family != "Café Mac" || f.Style != "Italic" {
+ t.Errorf("Family, Style = %q, %q; want Café Mac, Italic", f.Family, f.Style)
+ }
+ })
+}
+
+func TestInspectReadsWOFFAndWOFF2(t *testing.T) {
+ ttf := mustInspect(t, liberation(t))
+ for _, c := range []struct {
+ format Format
+ data []byte
+ ctype string
+ }{
+ {"woff", buildWOFF(t, liberation(t)), "font/woff"},
+ {"woff2", buildWOFF2(t, liberation(t)), "font/woff2"},
+ } {
+ t.Run(string(c.format), func(t *testing.T) {
+ f := mustInspect(t, c.data)
+ sum := sha256.Sum256(c.data)
+ want := ttf
+ want.Ref = hex.EncodeToString(sum[:])
+ want.Format = c.format
+ if f != want {
+ t.Fatalf("\n got %+v\nwant %+v", f, want)
+ }
+ if f.ContentType() != c.ctype {
+ t.Errorf("ContentType = %q, want %q", f.ContentType(), c.ctype)
+ }
+ })
+ }
+ t.Run("woff2 of a cff", func(t *testing.T) {
+ f := mustInspect(t, buildWOFF2(t, cff(t)))
+ if f.Format != "woff2" || f.Outline != "cff" {
+ t.Errorf("Format, Outline = %q, %q", f.Format, f.Outline)
+ }
+ })
+}
+
+func TestInspectReadsCFFAndVariable(t *testing.T) {
+ f := mustInspect(t, cff(t))
+ if f.Format != "otf" || f.Outline != "cff" || f.Family != "Liberation Sans" || f.ContentType() != "font/otf" {
+ t.Errorf("CFF: %+v (content type %q)", f, f.ContentType())
+ }
+
+ v := mustInspect(t, variable(t, axis{"wdth", 75, 100, 100}, axis{"wght", 100, 400, 900}))
+ if !v.Variable || v.Weight != 400 || v.WeightMin != 100 || v.WeightMax != 900 {
+ t.Errorf("variable: Variable %v, Weight %d, range %d..%d; want true, 400, 100..900",
+ v.Variable, v.Weight, v.WeightMin, v.WeightMax)
+ }
+
+ w := mustInspect(t, buildWOFF2(t, variable(t, axis{"wght", 100, 400, 900})))
+ if !w.Variable || w.WeightMin != 100 || w.WeightMax != 900 {
+ t.Errorf("variable woff2: %+v", w)
+ }
+
+ s := mustInspect(t, variable(t, axis{"wdth", 75, 100, 100}))
+ if s.Variable || s.WeightMin != 400 || s.WeightMax != 400 {
+ t.Errorf("fvar with no wght axis: %+v; want static at 400", s)
+ }
+}
+
+func TestPicturesOnlyForStaticTrueTypeThatMayEmbed(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ data []byte
+ want bool
+ }{
+ {"ttf, installable", liberation(t), true},
+ {"preview and print", patched(t, 0x0004, 0), true},
+ {"editable", patched(t, 0x0008, 0), true},
+ {"editable, no subsetting", patched(t, 0x0108, 0), true},
+ {"restricted licence", patched(t, 0x0002, 0), false},
+ {"restricted with preview and print", patched(t, 0x0006, 0), false},
+ {"bitmap embedding only", patched(t, 0x0200, 0), false},
+ {"cff", cff(t), false},
+ {"variable", variable(t, axis{"wght", 100, 400, 900}), false},
+ {"woff", buildWOFF(t, liberation(t)), false},
+ {"woff2", buildWOFF2(t, liberation(t)), false},
+ } {
+ f := mustInspect(t, c.data)
+ if got := f.Pictures(); got != c.want {
+ t.Errorf("%s: Pictures() = %v, want %v (%+v)", c.name, got, c.want, f)
+ }
+ }
+ if f := mustInspect(t, patched(t, 0x0002, 0)); f.FSType != 0x0002 {
+ t.Errorf("FSType = %#x, want 0x2", f.FSType)
+ }
+}
+
+func TestHeaders(t *testing.T) {
+ for format, ctype := range map[Format]string{"ttf": "font/ttf", "otf": "font/otf", "woff": "font/woff", "woff2": "font/woff2"} {
+ w := httptest.NewRecorder()
+ Headers(w, format)
+ h := w.Header()
+ for k, v := range map[string]string{
+ "Content-Type": ctype,
+ "X-Content-Type-Options": "nosniff",
+ "Cache-Control": "public, max-age=31536000, immutable",
+ "Content-Security-Policy": "default-src 'none'",
+ } {
+ if h.Get(k) != v {
+ t.Errorf("Headers(%s): %s = %q, want %q", format, k, h.Get(k), v)
+ }
+ }
+ }
+}
+
+func TestInspectRefuses(t *testing.T) {
+ ttf := liberation(t)
+
+ truncatedDir := ttf[:12+16*3]
+
+ pastEnd := bytes.Clone(ttf)
+ binary.BigEndian.PutUint32(pastEnd[12+16*4+12:], uint32(len(ttf))) // the fifth table's length
+
+ tooBig := make([]byte, MaxBytes+1)
+ copy(tooBig, ttf)
+
+ flavor, es, stream := woff2Parts(t, ttf)
+ good := brotliOf(stream)
+ badStream := bytes.Clone(good)
+ for i := 8; i < len(badStream) && i < 64; i++ {
+ badStream[i] ^= 0xA5
+ }
+ shortStream := assembleWOFF2(flavor, es, good[:len(good)/2])
+ longer := append([]woff2Entry(nil), es...)
+ longer[0].origLength += 4096 // claims more than the stream holds
+ extra := append([]woff2Entry(nil), es...)
+ extra[0].origLength -= 4 // the stream holds more than the tables claim
+ bomb := append([]woff2Entry(nil), es...)
+ bomb[0].origLength = 4*MaxBytes + 1
+ transformedName := append([]woff2Entry(nil), es...)
+ for i := range transformedName {
+ if transformedName[i].tag == "name" {
+ transformedName[i].version = 1
+ transformedName[i].transform = transformedName[i].origLength
+ }
+ }
+
+ woff := buildWOFF(t, ttf)
+ badZlib := bytes.Clone(woff)
+ {
+ // Corrupt the name table's compressed bytes.
+ n := int(binary.BigEndian.Uint16(woff[12:]))
+ for i := 0; i < n; i++ {
+ rec := woff[44+20*i:]
+ if string(rec[:4]) == "name" {
+ off := binary.BigEndian.Uint32(rec[4:])
+ for j := off + 2; j < off+40; j++ {
+ badZlib[j] ^= 0xA5
+ }
+ }
+ }
+ }
+
+ v, ts := tablesOf(t, ttf)
+ shortFvar := fvar(axis{"wght", 100, 400, 900})
+ binary.BigEndian.PutUint16(shortFvar[8:], 40) // 40 axes, room for one
+
+ pngHeader := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00")
+
+ for _, c := range []struct {
+ name string
+ data []byte
+ want error
+ }{
+ {"empty", nil, ErrNotAFont},
+ {"a PNG", pngHeader, ErrNotAFont},
+ {"a font collection", append([]byte("ttcf"), ttf[4:]...), ErrNotAFont},
+ {"a truncated table directory", truncatedDir, ErrMalformed},
+ {"a table past the end", pastEnd, ErrMalformed},
+ {"no tables", append(bytes.Clone(ttf[:4]), make([]byte, 8)...), ErrMalformed},
+ {"over MaxBytes", tooBig, ErrTooBig},
+ {"no OS/2", buildSFNT(v, withoutTable(ts, "OS/2")), ErrMalformed},
+ {"no name", buildSFNT(v, withoutTable(ts, "name")), ErrMalformed},
+ {"no family name", named(t, nameRec{3, 1, 0x409, 2, "Regular"}), ErrMalformed},
+ {"no outlines", buildSFNT(v, withoutTable(ts, "glyf", "loca")), ErrMalformed},
+ {"an fvar shorter than its axes", buildSFNT(v, withTable(ts, "fvar", shortFvar)), ErrMalformed},
+ {"a truncated WOFF", woff[:len(woff)/2], ErrMalformed},
+ {"a WOFF whose zlib is bad", badZlib, ErrMalformed},
+ {"a WOFF2 whose brotli stream is bad", assembleWOFF2(flavor, es, badStream), ErrMalformed},
+ {"a WOFF2 whose brotli stream is cut short", shortStream, ErrMalformed},
+ {"a WOFF2 table past the stream", assembleWOFF2(flavor, longer, good), ErrMalformed},
+ {"a WOFF2 stream longer than its tables", assembleWOFF2(flavor, extra, good), ErrMalformed},
+ {"a WOFF2 that unpacks too big", assembleWOFF2(flavor, bomb, good), ErrTooBig},
+ {"a WOFF2 with a transformed name table", assembleWOFF2(flavor, transformedName, good), ErrMalformed},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f, err := Inspect(c.data)
+ if !errors.Is(err, c.want) {
+ t.Fatalf("Inspect = %+v, %v; want %v", f, err, c.want)
+ }
+ t.Log(err)
+ })
+ }
+}
diff --git a/typeface/woff.go b/typeface/woff.go
new file mode 100644
index 0000000..f5c1c09
--- /dev/null
+++ b/typeface/woff.go
@@ -0,0 +1,235 @@
+package typeface
+
+import (
+ "bytes"
+ "compress/zlib"
+ "encoding/binary"
+ "fmt"
+ "io"
+
+ "github.com/andybalholm/brotli"
+)
+
+// WOFF and WOFF2 unwrapping, as far as Inspect needs it: the table
+// directory, and the bytes of the tables it reads. Neither rebuilds the
+// sfnt.
+
+// readWOFF reads a WOFF 1.0 file (zlib per table). Every table must lie
+// inside the file; the tables Inspect reads are inflated, each to exactly
+// the length the directory gives it.
+func readWOFF(data []byte) (fontTables, error) {
+ const headerLen, entryLen = 44, 20
+ if len(data) < headerLen {
+ return fontTables{}, malformed("WOFF header cut short")
+ }
+ flavor := binary.BigEndian.Uint32(data[4:])
+ if err := checkFlavor(flavor); err != nil {
+ return fontTables{}, err
+ }
+ if int64(binary.BigEndian.Uint32(data[8:])) != int64(len(data)) {
+ return fontTables{}, malformed("WOFF length is not the file's")
+ }
+ n := int(binary.BigEndian.Uint16(data[12:]))
+ if n == 0 {
+ return fontTables{}, malformed("no tables")
+ }
+ if headerLen+entryLen*n > len(data) {
+ return fontTables{}, malformed("WOFF table directory cut short: %d tables", n)
+ }
+ ft := fontTables{version: flavor, has: map[string]bool{}, data: map[string][]byte{}}
+ var unpacked uint64
+ for i := 0; i < n; i++ {
+ e := data[headerLen+entryLen*i:]
+ tag := string(e[:4])
+ off := uint64(binary.BigEndian.Uint32(e[4:]))
+ compLen := uint64(binary.BigEndian.Uint32(e[8:]))
+ origLen := uint64(binary.BigEndian.Uint32(e[12:]))
+ if off+compLen > uint64(len(data)) {
+ return fontTables{}, malformed("table %q runs past the end of the file", tag)
+ }
+ if compLen > origLen {
+ return fontTables{}, malformed("table %q is bigger packed than unpacked", tag)
+ }
+ if unpacked += origLen; unpacked > maxUnpacked {
+ return fontTables{}, fmt.Errorf("%w: unpacks to over %d bytes", ErrTooBig, maxUnpacked)
+ }
+ if ft.has[tag] {
+ return fontTables{}, malformed("table %q appears twice", tag)
+ }
+ ft.has[tag] = true
+ if !wanted(tag) {
+ continue
+ }
+ packed := data[off : off+compLen]
+ if compLen == origLen {
+ ft.data[tag] = packed // stored, not compressed
+ continue
+ }
+ b, err := inflate(packed, int(origLen))
+ if err != nil {
+ return fontTables{}, malformed("table %q: %v", tag, err)
+ }
+ ft.data[tag] = b
+ }
+ return ft, nil
+}
+
+// inflate unpacks a zlib stream that must hold exactly n bytes.
+func inflate(packed []byte, n int) ([]byte, error) {
+ r, err := zlib.NewReader(bytes.NewReader(packed))
+ if err != nil {
+ return nil, err
+ }
+ defer r.Close()
+ return readExactly(r, n)
+}
+
+// readExactly reads n bytes from r and checks that r then ends cleanly.
+// It reads no more than n+1 bytes whatever r holds.
+func readExactly(r io.Reader, n int) ([]byte, error) {
+ b, err := io.ReadAll(io.LimitReader(r, int64(n)+1))
+ if err != nil {
+ return nil, err
+ }
+ if len(b) > n {
+ return nil, fmt.Errorf("unpacks to more than the %d bytes its tables hold", n)
+ }
+ if len(b) < n {
+ return nil, fmt.Errorf("unpacks to %d bytes, not %d", len(b), n)
+ }
+ return b, nil
+}
+
+// woff2Tags is WOFF2's known-tag table: a directory entry's flags name a
+// tag by its index here, or 63 for a tag written out in full.
+var woff2Tags = [63]string{
+ "cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post",
+ "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", "VORG", "EBDT",
+ "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea",
+ "vmtx", "BASE", "GDEF", "GPOS", "GSUB", "EBSC", "JSTF", "MATH",
+ "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar",
+ "bdat", "bloc", "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar",
+ "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop",
+ "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill",
+}
+
+// readWOFF2 reads a WOFF2 file: the table directory, then the one brotli
+// stream holding every table end to end. The stream must unpack to
+// exactly the tables' total length, and that total may not pass
+// maxUnpacked. The tables Inspect reads are never transformed by a valid
+// encoder; one that says it is transformed is refused, since its bytes
+// are not the table. glyf, loca and hmtx may be transformed: their bytes
+// are only skipped.
+func readWOFF2(data []byte) (fontTables, error) {
+ const headerLen = 48
+ if len(data) < headerLen {
+ return fontTables{}, malformed("WOFF2 header cut short")
+ }
+ flavor := binary.BigEndian.Uint32(data[4:])
+ if err := checkFlavor(flavor); err != nil {
+ return fontTables{}, err
+ }
+ if int64(binary.BigEndian.Uint32(data[8:])) != int64(len(data)) {
+ return fontTables{}, malformed("WOFF2 length is not the file's")
+ }
+ n := int(binary.BigEndian.Uint16(data[12:]))
+ if n == 0 {
+ return fontTables{}, malformed("no tables")
+ }
+ compressedLen := uint64(binary.BigEndian.Uint32(data[20:]))
+
+ type entry struct {
+ tag string
+ off, size uint64 // in the unpacked stream
+ }
+ entries := make([]entry, 0, n)
+ has := map[string]bool{}
+ p := data[headerLen:]
+ var total uint64
+ for i := 0; i < n; i++ {
+ if len(p) < 1 {
+ return fontTables{}, malformed("WOFF2 table directory cut short")
+ }
+ flags := p[0]
+ p = p[1:]
+ var tag string
+ if idx := flags & 0x3F; idx == 63 {
+ if len(p) < 4 {
+ return fontTables{}, malformed("WOFF2 table directory cut short")
+ }
+ tag, p = string(p[:4]), p[4:]
+ } else {
+ tag = woff2Tags[idx]
+ }
+ origLen, rest, err := base128(p)
+ if err != nil {
+ return fontTables{}, err
+ }
+ p = rest
+ size := uint64(origLen)
+ version := flags >> 6
+ transformed := version != 0
+ if tag == "glyf" || tag == "loca" {
+ transformed = version != 3
+ }
+ if transformed {
+ transformLen, rest, err := base128(p)
+ if err != nil {
+ return fontTables{}, err
+ }
+ p, size = rest, uint64(transformLen)
+ if wanted(tag) {
+ return fontTables{}, malformed("table %q is transformed", tag)
+ }
+ }
+ if uint64(origLen) > maxUnpacked {
+ return fontTables{}, fmt.Errorf("%w: table %q unpacks to %d bytes", ErrTooBig, tag, origLen)
+ }
+ if has[tag] {
+ return fontTables{}, malformed("table %q appears twice", tag)
+ }
+ has[tag] = true
+ entries = append(entries, entry{tag, total, size})
+ if total += size; total > maxUnpacked {
+ return fontTables{}, fmt.Errorf("%w: unpacks to over %d bytes", ErrTooBig, maxUnpacked)
+ }
+ }
+ start := uint64(len(data) - len(p))
+ if start+compressedLen > uint64(len(data)) {
+ return fontTables{}, malformed("WOFF2 stream runs past the end of the file")
+ }
+ stream, err := readExactly(brotli.NewReader(bytes.NewReader(data[start:start+compressedLen])), int(total))
+ if err != nil {
+ return fontTables{}, malformed("WOFF2 stream: %v", err)
+ }
+ ft := fontTables{version: flavor, has: has, data: map[string][]byte{}}
+ for _, e := range entries {
+ if wanted(e.tag) {
+ ft.data[e.tag] = stream[e.off : e.off+e.size]
+ }
+ }
+ return ft, nil
+}
+
+// base128 reads WOFF2's UIntBase128: at most five bytes, no leading zero
+// byte, and a value that fits 32 bits.
+func base128(p []byte) (uint32, []byte, error) {
+ var v uint32
+ for i := 0; i < 5; i++ {
+ if i >= len(p) {
+ return 0, nil, malformed("WOFF2 table directory cut short")
+ }
+ b := p[i]
+ if i == 0 && b == 0x80 {
+ return 0, nil, malformed("UIntBase128 with a leading zero")
+ }
+ if v&0xFE000000 != 0 {
+ return 0, nil, malformed("UIntBase128 past 32 bits")
+ }
+ v = v<<7 | uint32(b&0x7F)
+ if b&0x80 == 0 {
+ return v, p[i+1:], nil
+ }
+ }
+ return 0, nil, malformed("UIntBase128 longer than five bytes")
+}