Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

Add Open Facts barcode sources (#1426)

Robin46ac41dfcc95
diff --git a/backend/app/api/handlers/v1/v1_ctrl_product_search.go b/backend/app/api/handlers/v1/v1_ctrl_product_search.go
index 9a33bece..861e0815 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_product_search.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_product_search.go
@@ -19,7 +19,10 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/web/adapters"
)
-const barcodeHTTPTimeoutSec = 10
+const (
+ barcodeHTTPTimeoutSec = 10
+ schemeHTTPS = "https"
+)
type UPCITEMDBResponse struct {
Code string `json:"code"`
@@ -58,17 +61,33 @@ type UPCITEMDBResponse struct {
} `json:"items"`
}
-type OpenFoodFactsResponse struct {
- Code string `json:"code"`
- Status int `json:"status"`
- Product struct {
- ProductName string `json:"product_name"`
- Brands string `json:"brands"`
- Categories string `json:"categories"`
- ImageFrontURL string `json:"image_front_url"`
- Quantity string `json:"quantity"`
- GenericName string `json:"generic_name"`
- } `json:"product"`
+type OpenFactsResponse struct {
+ Code string `json:"code"`
+ Status int `json:"status"`
+ Product openFactsProduct `json:"product"`
+}
+
+// Open Food Facts, Open Beauty Facts, and Open Products Facts share the same
+// product response shape and API path, so one mapper can safely serve all three.
+type openFactsProduct struct {
+ ProductName string `json:"product_name"`
+ Brands string `json:"brands"`
+ Categories string `json:"categories"`
+ ImageFrontURL string `json:"image_front_url"`
+ ImageURL string `json:"image_url"`
+ Quantity string `json:"quantity"`
+ GenericName string `json:"generic_name"`
+}
+
+type openFactsSource struct {
+ Name string
+ BaseURL string
+}
+
+var openFactsSources = []openFactsSource{
+ {Name: "openfoodfacts.org", BaseURL: "https://world.openfoodfacts.org"},
+ {Name: "openbeautyfacts.org", BaseURL: "https://world.openbeautyfacts.org"},
+ {Name: "openproductsfacts.org", BaseURL: "https://world.openproductsfacts.org"},
}
type BARCODESPIDER_COMResponse struct {
@@ -217,10 +236,89 @@ func sanitizeHeader(s string) string {
}, s)
}
-func lookupOpenFoodFacts(contact string, iEan string) ([]repo.BarcodeProduct, error) {
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ value = strings.TrimSpace(value)
+ if value != "" {
+ return value
+ }
+ }
+ return ""
+}
+
+func isAllowedOpenFactsImageHost(host string) bool {
+ host = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
+ allowedDomains := []string{
+ "openfoodfacts.org",
+ "openbeautyfacts.org",
+ "openproductsfacts.org",
+ }
+
+ for _, domain := range allowedDomains {
+ if host == domain || strings.HasSuffix(host, "."+domain) {
+ return true
+ }
+ }
+
+ return false
+}
+
+func normalizeOpenFactsImageURL(imageURL string) string {
+ imageURL = strings.TrimSpace(imageURL)
+ if imageURL == "" {
+ return ""
+ }
+
+ u, err := url.Parse(imageURL)
+ if err != nil || u.Hostname() == "" || u.User != nil {
+ return ""
+ }
+
+ switch u.Scheme {
+ case "http":
+ u.Scheme = schemeHTTPS
+ case schemeHTTPS:
+ default:
+ return ""
+ }
+
+ if !isAllowedOpenFactsImageHost(u.Hostname()) {
+ return ""
+ }
+
+ return u.String()
+}
+
+func buildOpenFactsBarcodeProduct(sourceName string, iEan string, product openFactsProduct) (repo.BarcodeProduct, bool) {
+ name := firstNonEmpty(product.ProductName, product.GenericName, product.Brands)
+ if name == "" {
+ return repo.BarcodeProduct{}, false
+ }
+
+ var p repo.BarcodeProduct
+ p.Barcode = iEan
+ p.SearchEngineName = sourceName
+ p.Item.Name = name
+ p.Manufacturer = product.Brands
+
+ var descriptionParts []string
+ for _, value := range []string{product.GenericName, product.Categories, product.Quantity} {
+ value = strings.TrimSpace(value)
+ if value != "" && value != name {
+ descriptionParts = append(descriptionParts, value)
+ }
+ }
+ p.Item.Description = strings.Join(descriptionParts, " | ")
+
+ p.ImageURL = normalizeOpenFactsImageURL(firstNonEmpty(product.ImageFrontURL, product.ImageURL))
+
+ return p, true
+}
+
+func lookupOpenFacts(contact string, source openFactsSource, iEan string) ([]repo.BarcodeProduct, error) {
client := &http.Client{Timeout: barcodeHTTPTimeoutSec * time.Second}
req, err := http.NewRequest(
- "GET", "https://world.openfoodfacts.org/api/v2/product/"+url.PathEscape(iEan)+".json", nil)
+ "GET", strings.TrimRight(source.BaseURL, "/")+"/api/v2/product/"+url.PathEscape(iEan)+".json", nil)
if err != nil {
return nil, err
}
@@ -240,8 +338,11 @@ func lookupOpenFoodFacts(contact string, iEan string) ([]repo.BarcodeProduct, er
err = errors.Join(err, resp.Body.Close())
}()
+ if resp.StatusCode == http.StatusNotFound {
+ return nil, nil
+ }
if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("OpenFoodFacts API returned status code: %d", resp.StatusCode)
+ return nil, fmt.Errorf("%s API returned status code: %d", source.Name, resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
@@ -249,9 +350,9 @@ func lookupOpenFoodFacts(contact string, iEan string) ([]repo.BarcodeProduct, er
return nil, err
}
- var result OpenFoodFactsResponse
+ var result OpenFactsResponse
if err := json.Unmarshal(body, &result); err != nil {
- log.Error().Msg("Can not unmarshal OpenFoodFacts JSON")
+ log.Error().Msg("Can not unmarshal " + source.Name + " JSON")
return nil, err
}
@@ -259,29 +360,9 @@ func lookupOpenFoodFacts(contact string, iEan string) ([]repo.BarcodeProduct, er
return nil, nil
}
- var p repo.BarcodeProduct
- p.Barcode = iEan
- p.SearchEngineName = "openfoodfacts.org"
- p.Item.Name = result.Product.ProductName
- p.Manufacturer = result.Product.Brands
-
- description := result.Product.GenericName
- if len(result.Product.Categories) > 0 {
- if len(description) > 0 {
- description += " | "
- }
- description += result.Product.Categories
- }
- if len(result.Product.Quantity) > 0 {
- if len(description) > 0 {
- description += " | "
- }
- description += result.Product.Quantity
- }
- p.Item.Description = description
-
- if len(result.Product.ImageFrontURL) > 0 {
- p.ImageURL = result.Product.ImageFrontURL
+ p, ok := buildOpenFactsBarcodeProduct(source.Name, iEan, result.Product)
+ if !ok {
+ return nil, nil
}
return []repo.BarcodeProduct{p}, nil
@@ -360,22 +441,24 @@ func (ctrl *V1Controller) HandleProductSearchFromBarcode(conf config.BarcodeAPIC
if err != nil {
log.Error().Msg("Can not retrieve product from upcitemdb.com: " + err.Error())
}
+ products = append(products, ps...)
- ps2, err := lookupBarcodespider(conf.TokenBarcodespider, q.EAN)
- if err != nil {
- log.Error().Msg("Can not retrieve product from barcodespider.com: " + err.Error())
+ if conf.TokenBarcodespider != "" {
+ ps2, err := lookupBarcodespider(conf.TokenBarcodespider, q.EAN)
+ if err != nil {
+ log.Error().Msg("Can not retrieve product from barcodespider.com: " + err.Error())
+ }
+ products = append(products, ps2...)
}
- ps3, err := lookupOpenFoodFacts(conf.OpenFoodFactsContact, q.EAN)
- if err != nil {
- log.Error().Msg("Can not retrieve product from openfoodfacts.org: " + err.Error())
+ for _, source := range openFactsSources {
+ ps3, err := lookupOpenFacts(conf.OpenFoodFactsContact, source, q.EAN)
+ if err != nil {
+ log.Error().Msg("Can not retrieve product from " + source.Name + ": " + err.Error())
+ }
+ products = append(products, ps3...)
}
- // Merge everything.
- products = append(products, ps...)
- products = append(products, ps2...)
- products = append(products, ps3...)
-
// Retrieve images if possible
for i := range products {
p := &products[i]
@@ -386,7 +469,7 @@ func (ctrl *V1Controller) HandleProductSearchFromBarcode(conf config.BarcodeAPIC
// Validate URL is HTTPS
u, err := url.Parse(p.ImageURL)
- if err != nil || u.Scheme != "https" {
+ if err != nil || u.Scheme != schemeHTTPS {
log.Warn().Msg("Skipping non-HTTPS image URL: " + p.ImageURL)
continue
}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_product_search_test.go b/backend/app/api/handlers/v1/v1_ctrl_product_search_test.go
new file mode 100644
index 00000000..f383a9de
--- /dev/null
+++ b/backend/app/api/handlers/v1/v1_ctrl_product_search_test.go
@@ -0,0 +1,95 @@
+package v1
+
+import "testing"
+
+func TestBuildOpenFactsBarcodeProduct(t *testing.T) {
+ product, ok := buildOpenFactsBarcodeProduct("openbeautyfacts.org", "3600522058124", openFactsProduct{
+ ProductName: "Shower Gel",
+ Brands: "Example Brand",
+ GenericName: "Body wash",
+ Categories: "Hygiene, Shower",
+ Quantity: "250 ml",
+ ImageFrontURL: "http://images.openbeautyfacts.org/images/products/360/052/205/8124/front_en.1.400.jpg",
+ })
+
+ if !ok {
+ t.Fatal("expected product to be built")
+ }
+ if product.Barcode != "3600522058124" {
+ t.Fatalf("unexpected barcode: %s", product.Barcode)
+ }
+ if product.SearchEngineName != "openbeautyfacts.org" {
+ t.Fatalf("unexpected source name: %s", product.SearchEngineName)
+ }
+ if product.Item.Name != "Shower Gel" {
+ t.Fatalf("unexpected product name: %s", product.Item.Name)
+ }
+ if product.Manufacturer != "Example Brand" {
+ t.Fatalf("unexpected manufacturer: %s", product.Manufacturer)
+ }
+ if product.Item.Description != "Body wash | Hygiene, Shower | 250 ml" {
+ t.Fatalf("unexpected description: %s", product.Item.Description)
+ }
+ if product.ImageURL != "https://images.openbeautyfacts.org/images/products/360/052/205/8124/front_en.1.400.jpg" {
+ t.Fatalf("unexpected image URL: %s", product.ImageURL)
+ }
+}
+
+func TestBuildOpenFactsBarcodeProductFallsBackToGenericName(t *testing.T) {
+ product, ok := buildOpenFactsBarcodeProduct("openproductsfacts.org", "1234567890123", openFactsProduct{
+ GenericName: "Replacement filter",
+ Categories: "Appliance parts",
+ })
+
+ if !ok {
+ t.Fatal("expected product to be built")
+ }
+ if product.Item.Name != "Replacement filter" {
+ t.Fatalf("unexpected product name: %s", product.Item.Name)
+ }
+ if product.Item.Description != "Appliance parts" {
+ t.Fatalf("unexpected description: %s", product.Item.Description)
+ }
+}
+
+func TestBuildOpenFactsBarcodeProductRequiresName(t *testing.T) {
+ _, ok := buildOpenFactsBarcodeProduct("openfoodfacts.org", "1234567890123", openFactsProduct{})
+ if ok {
+ t.Fatal("expected empty product to be ignored")
+ }
+}
+
+func TestBuildOpenFactsBarcodeProductRejectsUntrustedImageHost(t *testing.T) {
+ product, ok := buildOpenFactsBarcodeProduct("openfoodfacts.org", "1234567890123", openFactsProduct{
+ ProductName: "Example Product",
+ ImageURL: "https://example.com/image.jpg",
+ })
+
+ if !ok {
+ t.Fatal("expected product to be built")
+ }
+ if product.ImageURL != "" {
+ t.Fatalf("expected untrusted image URL to be cleared, got %q", product.ImageURL)
+ }
+}
+
+func TestBuildOpenFactsBarcodeProductRejectsUnsupportedImageScheme(t *testing.T) {
+ product, ok := buildOpenFactsBarcodeProduct("openfoodfacts.org", "1234567890123", openFactsProduct{
+ ProductName: "Example Product",
+ ImageURL: "ftp://images.openfoodfacts.org/image.jpg",
+ })
+
+ if !ok {
+ t.Fatal("expected product to be built")
+ }
+ if product.ImageURL != "" {
+ t.Fatalf("expected unsupported image URL to be cleared, got %q", product.ImageURL)
+ }
+}
+
+func TestSanitizeHeaderRemovesControlCharacters(t *testing.T) {
+ got := sanitizeHeader("[email protected]\r\nInjected: value\t")
+ if got != "[email protected]: value" {
+ t.Fatalf("unexpected sanitized header: %q", got)
+ }
+}
diff --git a/docs/src/content/docs/en/quick-start/configure/index.mdx b/docs/src/content/docs/en/quick-start/configure/index.mdx
index c0e78f35..0478edd9 100644
--- a/docs/src/content/docs/en/quick-start/configure/index.mdx
+++ b/docs/src/content/docs/en/quick-start/configure/index.mdx
@@ -83,7 +83,8 @@ import {Tabs, TabItem} from "@astrojs/starlight/components";
| HBOX_THUMBNAIL_ENABLED | true | enable thumbnail generation for images, supports PNG, JPEG, AVIF, WEBP, GIF file types |
| HBOX_THUMBNAIL_WIDTH | 500 | width for generated thumbnails in pixels |
| HBOX_THUMBNAIL_HEIGHT | 500 | height for generated thumbnails in pixels |
-| HBOX_BARCODE_TOKEN_BARCODESPIDER | | API token for BarcodeSpider.com service used for barcode product lookups. If not set, barcode product lookups will not be performed. |
+| HBOX_BARCODE_TOKEN_BARCODESPIDER | | API token for BarcodeSpider.com service used for barcode product lookups. If not set, BarcodeSpider lookups will not be performed. |
+| HBOX_BARCODE_OPENFOODFACTS_CONTACT | | Optional contact value included in the User-Agent for Open Food Facts, Open Beauty Facts, and Open Products Facts barcode lookups. This is sent to third-party APIs, so avoid secrets or personal PII and prefer a role/contact alias. |
| HBOX_NOTIFIER_ALLOW_NETS | | comma-separated list of CIDR networks to allow for generic notifiers (e.g., `192.168.1.0/24,10.0.0.0/8`). If set, only these networks will be allowed and all block rules are bypassed. |
| HBOX_NOTIFIER_BLOCK_NETS | | comma-separated list of CIDR networks to block for generic notifiers (e.g., `192.168.1.0/24,10.0.0.0/8`). Provides fine-grained blocking without enabling blanket rules. |
| HBOX_NOTIFIER_BLOCK_LOCALHOST | false | block generic notifiers from sending to localhost/loopback addresses (127.0.0.1, ::1) |
@@ -102,6 +103,7 @@ OPTIONS
--auth-rate-limit-max-attempts <int> (default: 5)
--auth-rate-limit-max-backoff <duration> (default: 5m)
--auth-rate-limit-window <duration> (default: 1m)
+ --barcode-openfoodfacts-contact <string>
--barcode-token-barcodespider <string>
--database-database <string>
--database-driver <string> (default: sqlite3)
@@ -263,4 +265,4 @@ Usage:
```bash
systemctl start homebox.socket
-```
\ No newline at end of file
+```