SHC vNext QR proof of concept

Design notes

Rendered from DESIGN.md in the repository.

Proof of concept for the QR form of SMART Health Cards vNext. Experimental and unsigned. All sample data is synthetic.

The idea

A QR code carries a compact, purpose-built encoding of a dataset. A small WebAssembly module, the codec, turns those bytes into an ordinary FHIR Bundle on the receiving device. The person showing the code needs very little screen; whoever scans it gets FHIR. No server holds the data.

https://joshuamandel.com/shc2-poc/#shc2:/0059945165226113...     text in the QR
        │  digits → bytes (17 digits per 7 bytes)
        ▼
[ codec reference ][ codec input ][ check ]                       1 + 288 + 2 bytes
        │  look the codec up; run it in a sandbox
        ▼
FHIR Bundle                                                       695 entries, 248 KB of JSON

The example is a tracking history (365 days) for one synthetic person.

Layer 1: bytes in the QR are decimal digits

QR numeric mode stores three digits in ten bits, which wastes 0.3% of the symbol. A digit string is also plain text that every scanner, camera app and link handler passes through unchanged. Raw binary is not: the web scanning API and camera apps never return bytes, and scanning libraries guess a character set.

Each 7 bytes become one 17-digit number (10^17 is just above 2^56). This needs only 64-bit arithmetic and keeps leading zero bytes.

Way of writing bytes into a QRPayload at Version 22-LAt Version 22-M
SMART Health Cards 1.x: base64url, two digits per character895 bytes693
base45, alphanumeric mode (EU COVID certificate)965748
7 bytes → 17 digits (this design)983762
one big decimal integer (India's Aadhaar QR)991768
raw bytes in byte mode997773

A QR symbol can switch modes partway through, so the text starts with a short prefix in byte mode and continues with the digits in numeric mode. SMART Health Cards 1.x does the same.

Two forms of the text:

  • shc2:/ followed by the digits, for a receiver with its own scanner.
  • https://joshuamandel.com/shc2-poc/#shc2:/ followed by the digits. Any phone camera opens this as a web page, which decodes the card on the device. The part after # is never sent to a server. A receiver that knows the format ignores everything before shc2:/.

A third form is for links that are pasted or sent, not scanned: shc2:/b/ followed by the card in base64url. Digits are the densest thing a QR can hold but a poor way to write bytes as text, at 2.43 characters per byte; base64url takes 1.33. A 291-byte card is 748 characters as a digit link and 430 as a base64url link. What follows shc2:/ starts with a digit in the QR form and with b/ in the link form, so a receiver tells them apart by the first character. A QR code always uses digits.

A link that is emailed or messaged stays wherever it is stored and cannot be taken back.

Layer 2: the card is a codec reference, the codec's input, and a 2-byte check

Nothing else: no version byte, no length field.

  • A registered codec is named by its id, written as a variable-length integer. Ids 1 to 127 take one byte, ids up to 16,383 take two, and so on without limit.
  • An unregistered codec is named by a zero byte and the 32-byte SHA-256 of its module. Anyone can do this without asking.
  • The check is the first 2 bytes of the SHA-256 of everything before it. A reader verifies it before running any codec.

The check exists because a codec's input is not self-checking. The cycle-log input is one arithmetic-coded stream with no length field, and a card with its last byte missing can be the complete, valid input for a slightly different record. A scanner returns the whole text of a QR symbol or nothing, but a pasted or forwarded link can lose its tail. With the check, a cut or altered card is refused, except for 1 in 65,536 that slips through.

Layer 3: the codec turns bytes into FHIR

A codec is a WebAssembly module with no imports. It cannot reach the network, the clock, storage or the host; it can only compute. The interface is in CODEC-ABI.md.

The registry holds only constrained codecs. Each publishes three things:

  1. An input model: a small, closed description of exactly the facts it can carry. Developers write against this and never construct FHIR.
  2. A wire format: the bytes, with exactly one encoding per dataset.
  3. An output mapping: the FHIR Bundle the decoder emits for each model.

An encoder refuses anything its model cannot represent exactly. It never drops or approximates. Data that no codec fits goes in a SMART Health Link.

Built-in tables and scales make expected content cheap; they are not the limit of what can be said. Any code from any system can be used where a concept goes, and a card can declare its own per-day series.

The cycle-log codec

Codec 1 (cycle-log) carries menstrual-cycle and health tracking spanning up to 10,000 days (~27 years), bounded naturally by QR capacity. Built-in slots use readable string keywords (SymptomKind, MedicationKind, ConditionKind, Mucus, Sex, Mood, Energy, ProcedureKind, IntervalKind, ExcludeReason, etc.) expanding on decode to canonical SNOMED CT / LOINC / cycle-log codings. Every daily series is a uniform flat array of { date, ... } entries using standard FHIR DateTime (YYYY-MM-DD or full date with time and UTC offset, accepting Z and :00), genuine FHIR R4 CodeableConcept escapes ({ coding: [{ system, code, display? }], text? } or text-only { text } without synthetic app URIs), and natural JSON decimals (no date-string map keys, no start/days/DayIndex, no root labels, no scale field, and no synthetic tracking-window Observation):

  • bleeding and flow, with "explicitly none" kept distinct from "not recorded";
  • pain score, symptoms (SymptomKind + CodeableConcept escapes), basal body temperature (with optional disturbance/exclusion flags and reasons);
  • cervical mucus, ovulation, progesterone (PdG) and pregnancy tests;
  • sexual activity, mood, energy, sleep;
  • pill log, medications taken or missed (MedicationKind + CodeableConcept escapes, with optional exact doses);
  • contraception, pregnancy and breastfeeding intervals; IUD, implant and emergency-contraception procedures;
  • measured menstrual fluid volume, and skin temperature from a wearable (absolute or as a deviation from baseline, with optional exclusion flags);
  • reported conditions (ConditionKind + CodeableConcept escapes), and unified procedures ({ date: FhirDateTime, code: ProcedureKind | CodeableConcept }) with dates as precise as the person knows them (YYYY, YYYY-MM, YYYY-MM-DD, or full timestamp);
  • answers to seven screening questions ({ date: DateTime, question, value }), dated when answered and kept apart from anything computed from the log;
  • optional export timestamp (exportedAt FhirInstant, mapped to FHIR Bundle.timestamp);
  • the app or device the data came from;
  • custom series declared by the card via valueType ("boolean" → valueBoolean, "coded" → valueCodeableConcept, "quantity" → valueQuantity, "components" → component[]), including multi-component readings ({ date, components: [{ code, value }] }) and vital signs (heart rate, weight, blood pressure, fever);
  • a flag saying the card was reduced to fit a size (Bundle.meta.tag SUBSETTED);
  • an optional name and birth date.

The input model is defined by TypeScript types (codecs/cycle-log/model.d.ts); a JSON Schema is derived from them. Both are published on the site with example models. Every field on CycleLog is optional ({} is valid).

It is written in Rust with no dependencies, zero floats, and link-time zero-panic. An adaptive range coder with 2-level KT probability chains, dominant grids, circular midnight-safe time coding, and LZ77 UTF-8 text compression learns the person's pattern as it goes. Encoder and decoder ship in one module. A decoder accepts a card only if encoding its result again reproduces the same bytes.

Every card emits a Patient as the first entry, and every fact refers to it. Without a name or birth date, the Patient is the smallest valid one.

Sizes

Sample recordFHIR BundleDEFLATE of the BundleCardQR version at level L
near-empty3 KB503 bytes18 bytes2
bleeding only19 KB786343
calendar export with logging statements26 KB1,192494
combined pill with pill log213 KB6,45623610
irregular, PCOS-like163 KB5,68028011
copper IUD, named patient248 KB7,36929111
heavy bleeding with measured volume278 KB8,24130811
after endometrial ablation261 KB7,58045815
wearable: sleep and skin temperature282 KB8,06367618
hypertension follow-up: blood pressure, heart rate, weight484 KB14,29470118
perimenopause488 KB14,54769318
power tracker, everything daily1.15 MB31,6051,15425
app with its own vocabulary838 KB25,7441,57329
wellness diary, mostly custom series763 KB27,5061,86232

Card sizes include the one-byte codec reference and the 2-byte check. QR versions are for the bare shc2:/ form; with the site's link in front, a code is about one version larger. DEFLATE is the browser's default level. bun demo.ts reproduces the card sizes end to end: encode, draw, scan with zbarimg, decode, compare. The site's home page shows the same records with the link in front.

  • The codec's constants were tuned on three sample records. Three were tuned on and the rest held out (20 sample records total, including text-only tags and offline displays on standard escape codes). Held-out cards came to 84% of an independent per-category entropy estimate, tuned ones to 91%. One held-out sample record is 2% over its estimate.
  • Removing the cycle-phase modelling costs about 7%. Most of a heavy tracker's bytes are day-to-day variation in numeric series, which no model removes.
  • Leaving the built-in vocabulary costs text. The own-vocabulary sample record spends about 300 bytes declaring codes and labels.
  • A card is never larger than a plain fixed-width coding of the same model.

Fitting an existing Bundle

codecs/cycle-log/lift/ is a prototype of the other direction. A lifter reads a FHIR Bundle however it is shaped into the model and reports every resource as carried exactly, carried with a named change, or left out with a reason; elements that change meaning (a modifier extension, entered-in-error) are refused unless the caller allows them. A planner then fits the model to a target size by named steps. Leaving things out comes first: times of day, display text, extra entries on a day, whole series, the oldest days. Steps that change a recorded value are offered only where the project owner has approved that kind for that measure; none is approved yet. The default takes the mildest omissions first, and a caller can protect series, forbid steps, reorder priorities or supply a plan.

A card reduced this way carries one flag, emitted as the Bundle tag SUBSETTED. The steps stay with the sender: a receiver learns that things that were recorded may be absent, not which. The fit/ page on the site runs all of this in the browser. lift/LIFT.md has the rules and the judgment calls.

How large a QR is practical

SMART Health Cards 1.x stops at Version 22. On a phone screen there is room for more:

VersionPayload at level LModule size on a 65 mm screen
22983 bytes0.58 mm
251,2500.52 mm
301,7030.45 mm
321,9210.42 mm
402,9100.35 mm

What has been observed, on an Android emulator with a Google Play image:

  • The system scanner read a Version 22 code of 2,395 characters and a Version 30 code of 4,144 characters live, and delivered each intact to the registered app.
  • ML Kit and ZXing inside an app returned exact text at every size up to Version 40.
  • Google Lens does not hand custom-scheme codes to the registered app: it rewrites the scheme into a web address. An https:// prefix avoids this.
  • shc:/ codes are claimed by Google Wallet. A new prefix is not.

The emulator's camera shows a clean image, so this is not evidence about focus, hand shake or screen moiré.

A simulation study (research/scan-density.md) rendered 15,261 synthetic camera frames with blur, noise, tilt, moiré and glare and ran them through ML Kit, ZXing and zbar:

  • With mild blur, ML Kit decoded Version 20 to 22 in at least 95% of frames at the resolution the Android system scanner uses (1280×960), held about 10 cm from the screen.
  • Version 27 to 30 needed 1920×1080 frames, the code filling most of the frame, and sharp focus.
  • Above Version 32, no setting reached 95% of frames with mild blur.
  • At equal payload, level M never needed fewer camera pixels than level L.
  • No decoder ever returned a wrong text.

These are per-frame rates from a model of the camera, not measurements on phones. A scanner sees many frames a second, so time to a successful scan is better than the per-frame rate suggests. The scan test on the site collects real results; research/ also has the scanner survey and prior art.

Working lines for the lab: up to Version 25 comfortable, up to Version 30 a stretch. The simulation suggests the comfortable line belongs nearer Version 22; the lines will be set from phone tests.

Linking a card to remote data

Not built. A card may later carry one SMART Health Link, in a block between the codec reference and the codec input, read by the host and not by the codec. Carrying an arbitrary link takes a flags byte, an optional 4-byte expiry, the URL at about 0.8 bytes per character, and the 32-byte key: about 100 bytes for a typical link, which is under half of the same link as shlink:/ text. The card would be a snapshot that the link supersedes when it resolves.

Signatures

Out of scope. The experiment is unsigned, which fits patient-reported data. No approved post-quantum signature is small enough for a QR code, and binding a new format to an algorithm that is being retired was judged not worth it. When a small-signature algorithm is standardized, signing can follow whatever SMART Health Cards vNext adopts for it.

Where things are published

Path under https://joshuamandel.com/shc2-poc/What is there
/The site. Opened with #shc2:/…, it sends the browser to the viewer, which decodes and shows the record.
view/, lab/, explain/, scan-test/The viewer, the squeeze lab, the bit-level explainer, the scanning test
import/Make a card from a calendar export
fit/Lift a FHIR Bundle into the model and reduce it to a target QR size
developers/, reference/How to make and read a code; the documents, rendered
codecs/cycle-log/input-model/The cycle-log input model: types, schema, example models
registry.jsonThe codec registry
codecs/<id>.wasm, codecs/sha256/<hex>.wasmModules by id and by hash
CodeSystem/cycle-logThe proposed concepts the cycle-log codec uses where no standard code exists

Open questions

  1. Scan limits on real phones. Which QR versions are reliable from a phone screen, and at which error-correction level.
  2. Finding an unregistered codec. A hash names a module but does not say where to get it.
  3. Registry admission. Who reviews a codec, and what is checked: determinism, one encoding per dataset, and the quality of the FHIR it emits.
  4. Clinical review of the cycle-log model and of the viewer's derived summaries.
  5. Real data. Every measurement here is on synthetic sample records.
  6. Proposed codes. About 25 concepts have no standard code and live in an experimental code system.