@certrev/cert-block 1.2.0-canary.6 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +120 -35
  2. package/README.md +116 -21
  3. package/dist/builder/card-reader-css.d.ts +14 -0
  4. package/dist/builder/card-reader-css.d.ts.map +1 -0
  5. package/dist/builder/card-reader-css.js +17 -0
  6. package/dist/builder/card-reader-css.js.map +1 -0
  7. package/dist/builder/cert-review-card.d.ts +8 -0
  8. package/dist/builder/cert-review-card.d.ts.map +1 -1
  9. package/dist/builder/cert-review-card.js +234 -41
  10. package/dist/builder/cert-review-card.js.map +1 -1
  11. package/dist/builder/delivery-runtime.d.ts +15 -1
  12. package/dist/builder/delivery-runtime.d.ts.map +1 -1
  13. package/dist/builder/delivery-runtime.js +31 -3
  14. package/dist/builder/delivery-runtime.js.map +1 -1
  15. package/dist/builder/ssr-seed.d.ts +155 -0
  16. package/dist/builder/ssr-seed.d.ts.map +1 -0
  17. package/dist/builder/ssr-seed.js +278 -0
  18. package/dist/builder/ssr-seed.js.map +1 -0
  19. package/dist/reader/face.d.ts +6 -2
  20. package/dist/reader/face.d.ts.map +1 -1
  21. package/dist/reader/face.js +53 -5
  22. package/dist/reader/face.js.map +1 -1
  23. package/dist/reader/render.d.ts.map +1 -1
  24. package/dist/reader/render.js +10 -10
  25. package/dist/reader/render.js.map +1 -1
  26. package/dist/verify/cache.d.ts +39 -2
  27. package/dist/verify/cache.d.ts.map +1 -1
  28. package/dist/verify/cache.js +61 -12
  29. package/dist/verify/cache.js.map +1 -1
  30. package/dist/verify/get-verified-delivery.d.ts +28 -3
  31. package/dist/verify/get-verified-delivery.d.ts.map +1 -1
  32. package/dist/verify/get-verified-delivery.js +46 -9
  33. package/dist/verify/get-verified-delivery.js.map +1 -1
  34. package/package.json +112 -112
  35. package/src/builder/card-reader-css.ts +19 -0
  36. package/src/builder/cert-review-card.tsx +308 -56
  37. package/src/builder/delivery-runtime.ts +33 -3
  38. package/src/builder/ssr-seed.ts +343 -0
  39. package/src/reader/face.ts +59 -6
  40. package/src/reader/render.ts +12 -12
  41. package/src/verify/cache.ts +87 -11
  42. package/src/verify/get-verified-delivery.ts +77 -11
@@ -0,0 +1,343 @@
1
+ /**
2
+ * The server render's envelope seed (1.2.0): what lets a hydrated delivery card paint with NO browser read.
3
+ *
4
+ * Through 1.1.1 the browser re-read the Delivery API for every card it hydrated, because nothing handed the server's
5
+ * read to it. A storefront whose Content-Security-Policy `connect-src` does not name the CertREV origin (e.l.f.'s
6
+ * Hydrogen store is one) blocked that read, the read settled as a suppress, and the card the server had painted
7
+ * vanished. So the painted face now carries the envelope it was painted from, as one attribute on its wrapper:
8
+ * `data-certrev-envelope` = `{ v: 1, baseUrl, externalId, design?, payload, signature?, renderDef }`. `payload` is the
9
+ * signed envelope's payload as the Delivery API served it, less the fields the def hides (below); `renderDef` is the
10
+ * def the face was painted with; `design` is the design pin the read was made with (the canary replica's `?design=N`),
11
+ * present only on a pinned read. React escapes the attribute like any other, so no `<script>` and no CSP `script-src`
12
+ * are involved.
13
+ *
14
+ * HIDDEN FIELDS ARE ABSENT FROM THE PAGE, NOT JUST FROM THE FACE. A def's `hidden` set (`reviewerPhoto`, `memo`) is the
15
+ * brand's statement that the page does not show those fields; a seed that carried them would put the reviewer's photo
16
+ * URL or the memo text in the page source all the same. So `withoutHiddenContent` removes them from the payload
17
+ * BEFORE the card paints and before it serializes, and both the server's face and the browser's are painted from the
18
+ * stripped payload (so they are identical, and a hidden memo is not on the page in either place):
19
+ * - `reviewerPhoto` hides `content.expert.photoUrl` and the author's `content.author.photoUrl` (the reader face paints
20
+ * the author's photo under the same switch);
21
+ * - `memo` hides `content.memo`.
22
+ * `display.showExpertPhoto: false` is the payload's own switch for the same photos and is stripped the same way (the
23
+ * portal never writes the URL for it either): both photo URLs go, as for `reviewerPhoto`, whatever the def hides.
24
+ * `content.expert.compensationCue` is NEVER touched: the cue is a locked disclosure no def can hide, and the face
25
+ * paints "Compensated expert" from it in the banner, the memo and the sidebar (the floating pill's own markup has
26
+ * no disclosure line, as in the portal's snippets; its modal paints the cue from the same field).
27
+ *
28
+ * THE SIGNATURE IS LEFT OUT WHENEVER ANYTHING WAS STRIPPED. The signature signs the full payload, so a payload with a
29
+ * field removed no longer verifies against it, and a seed that carried both would hand a verifier a pair that fails.
30
+ * Leaving it out costs nothing: the browser never re-checks a seed's signature (next paragraph), it re-runs only
31
+ * `renderVerdict` (lifecycle and subject) at its own clock, and neither reads a field the strip removes. A seed whose
32
+ * payload was not stripped keeps the signature, so a verifier can still check the page's HTML against the issuer key.
33
+ *
34
+ * The browser trusts a seed as far as it trusts the server HTML the seed sits in: whoever can write that HTML can
35
+ * already write any card they like, so the signature is NOT re-verified here (which would make hydration async, and
36
+ * Ed25519 in WebCrypto is not in every browser). The client still re-runs the lifecycle and subject policy
37
+ * (`renderVerdict`) at its own clock once hydration is done; `cert-review-card.tsx` does that.
38
+ *
39
+ * A PINNED CARD TAKES ONLY A SEED WITH THE SAME PIN (and an unpinned card only an unpinned one): the pin is part of
40
+ * the seed's key, as it is part of the read's, so the canary replica's `?design=7` card never paints the design the
41
+ * page carried for another version.
42
+ *
43
+ * WHEN THE SERVER HAD NO ENVELOPE TO PAINT (1.2.0) the same attribute carries a fallback record instead of a seed:
44
+ * `{ v: 1, baseUrl, externalId, design?, face }`, where `face` is `'options'` (CertREV could not be reached, so the
45
+ * server painted the block's own options face) or `'none'` (the server painted nothing: revoked, expired, unverifiable,
46
+ * for another entry). A browser that renders the card again (hydration, or React's client re-render after a hydration
47
+ * error elsewhere on the page) paints what the record says, so it neither reads the Delivery API nor shows a card the
48
+ * server withheld. A record holds no payload, so `parseSeed` never takes one for a seed. A `'none'` record sits on a
49
+ * `hidden` element with nothing in it.
50
+ *
51
+ * React-free and browser-only in effect: with no `document` (a server) `pageSeedFor` finds nothing, so a server never
52
+ * reads or keeps a seed and a multi-tenant render process holds nothing per page.
53
+ */
54
+
55
+ import { HIDEABLE_FIELDS } from '../components/render-def.js'
56
+ import type { CertContent, CertPayload, CertSignature } from '../contract/kernel.js'
57
+ import { type DesignPin, parseDesignPin, parseRenderDef } from '../verify/get-verified-delivery.js'
58
+ import type { CertChromeRenderDef } from './cert-chrome-data.js'
59
+
60
+ export const SEED_ATTRIBUTE = 'data-certrev-envelope'
61
+
62
+ export interface DeliverySeed {
63
+ readonly baseUrl: string
64
+ readonly externalId: string
65
+ /** The design pin the read was made with; absent on an unpinned read (every production brand). */
66
+ readonly design?: DesignPin
67
+ /** The payload as painted: with every field the def hides removed (`withoutHiddenContent`). */
68
+ readonly payload: CertPayload
69
+ /**
70
+ * The envelope's signature as served; absent when the payload was stripped (it no longer verifies), and when a
71
+ * cache was filled by hand (a test, a custom cache).
72
+ */
73
+ readonly signature?: CertSignature
74
+ readonly renderDef: CertChromeRenderDef | null
75
+ }
76
+
77
+ /** A seed as read from the page: the parsed seed and the attribute's exact text (re-rendered verbatim on hydration). */
78
+ export interface PageSeed {
79
+ readonly seed: DeliverySeed
80
+ readonly raw: string
81
+ }
82
+
83
+ /** What the server painted with no verified envelope: the block's options face, or nothing. */
84
+ export type FallbackFace = 'options' | 'none'
85
+
86
+ /** The record a server writes where it had no envelope to paint (the file header). */
87
+ export interface DeliveryFallback {
88
+ readonly baseUrl: string
89
+ readonly externalId: string
90
+ readonly design?: DesignPin
91
+ readonly face: FallbackFace
92
+ }
93
+
94
+ /** A fallback record as read from the page, with the attribute's exact text. */
95
+ export interface PageFallback {
96
+ readonly fallback: DeliveryFallback
97
+ readonly raw: string
98
+ }
99
+
100
+ /** Whatever the server wrote for one placement: a seed or a fallback record. */
101
+ export type PageRecord = PageSeed | PageFallback
102
+
103
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
104
+
105
+ /** A value worth hiding: anything but nothing (absent, null, the empty string). */
106
+ const hasValue = (v: unknown): boolean => v !== undefined && v !== null && v !== ''
107
+
108
+ /**
109
+ * The payload with the named people's photo URLs removed (`null`); the same object when neither had one. The card uses
110
+ * it for a photo the browser could not load (a brand's CSP `img-src`, a 404), so the face repaints with the initials.
111
+ */
112
+ export function withoutPhotos(payload: CertPayload, people: readonly ('expert' | 'author')[]): CertPayload {
113
+ let content: Record<string, unknown> = { ...payload.content }
114
+ let stripped = false
115
+ for (const person of people) {
116
+ const fields = content[person]
117
+ if (isRecord(fields) && hasValue(fields.photoUrl)) {
118
+ content = { ...content, [person]: { ...fields, photoUrl: null } }
119
+ stripped = true
120
+ }
121
+ }
122
+ return stripped ? { ...payload, content: content as unknown as CertContent } : payload
123
+ }
124
+
125
+ /**
126
+ * The payload with every content field the def's `hidden` set controls removed, and whether anything was; the two
127
+ * photo URLs go as well when the payload's own `display.showExpertPhoto` is `false` (exactly `false`, as the reader
128
+ * face reads it: absent or `null` shows the photo).
129
+ *
130
+ * Only the ids in `HIDEABLE_FIELDS` count (a def may list others; the faces ignore them, so they hide nothing). A
131
+ * removed text field becomes `null`, so the content keeps the shape the contract types give it and every face reads it
132
+ * as absent. Nothing but those fields changes: the subject and lifecycle (what `renderVerdict` reads), the cue, the
133
+ * dates, the links and the names are the payload's own. Never throws on a hostile shape: a payload whose `expert` or
134
+ * `author` is not an object has no photo to strip.
135
+ */
136
+ export function withoutHiddenContent(
137
+ payload: CertPayload,
138
+ renderDef: CertChromeRenderDef | null,
139
+ ): { readonly payload: CertPayload; readonly stripped: boolean } {
140
+ const hidden = (renderDef?.hidden ?? []).filter((id) => (HIDEABLE_FIELDS as readonly string[]).includes(id))
141
+ const display: unknown = (payload.content as unknown as Record<string, unknown> | undefined)?.display
142
+ const photoOff = isRecord(display) && display.showExpertPhoto === false
143
+ if (hidden.length === 0 && !photoOff) return { payload, stripped: false }
144
+ let next = photoOff || hidden.includes('reviewerPhoto') ? withoutPhotos(payload, ['expert', 'author']) : payload
145
+ if (hidden.includes('memo') && hasValue(next.content.memo)) {
146
+ next = { ...next, content: { ...next.content, memo: null } as unknown as CertContent }
147
+ }
148
+ return { payload: next, stripped: next !== payload }
149
+ }
150
+
151
+ /**
152
+ * The seed for a verified read: the payload stripped of what the def hides, and the signature only when nothing was
153
+ * stripped. The card paints from this seed's payload, on the server and in the browser alike.
154
+ */
155
+ export function seedFor(read: {
156
+ readonly baseUrl: string
157
+ readonly externalId: string
158
+ readonly design?: DesignPin
159
+ readonly payload: CertPayload
160
+ readonly signature?: CertSignature
161
+ readonly renderDef: CertChromeRenderDef | null
162
+ }): DeliverySeed {
163
+ const { payload, stripped } = withoutHiddenContent(read.payload, read.renderDef)
164
+ return {
165
+ baseUrl: read.baseUrl,
166
+ externalId: read.externalId,
167
+ ...(read.design ? { design: read.design } : {}),
168
+ payload,
169
+ ...(read.signature && !stripped ? { signature: read.signature } : {}),
170
+ renderDef: read.renderDef,
171
+ }
172
+ }
173
+
174
+ const serializedPin = (design: DesignPin | undefined) =>
175
+ design ? { design: { version: design.version, ...(design.brand === undefined ? {} : { brand: design.brand }) } } : {}
176
+
177
+ export function serializeSeed(seed: DeliverySeed): string {
178
+ return JSON.stringify({
179
+ v: 1,
180
+ baseUrl: seed.baseUrl,
181
+ externalId: seed.externalId,
182
+ ...serializedPin(seed.design),
183
+ payload: seed.payload,
184
+ ...(seed.signature ? { signature: seed.signature } : {}),
185
+ renderDef: seed.renderDef,
186
+ })
187
+ }
188
+
189
+ export function serializeFallback(fallback: DeliveryFallback): string {
190
+ return JSON.stringify({
191
+ v: 1,
192
+ baseUrl: fallback.baseUrl,
193
+ externalId: fallback.externalId,
194
+ ...serializedPin(fallback.design),
195
+ face: fallback.face,
196
+ })
197
+ }
198
+
199
+ /** A pin a record names, judged by the same grammar the card's own pin is: undefined when absent, null when bad. */
200
+ function parsedPin(design: unknown): DesignPin | undefined | null {
201
+ if (design === undefined) return undefined
202
+ const judged = isRecord(design)
203
+ ? parseDesignPin({ design: design.version, ...(design.brand === undefined ? {} : { designBrand: design.brand }) })
204
+ : 'invalid'
205
+ return judged === 'invalid' || judged === undefined ? null : judged
206
+ }
207
+
208
+ /** The seed in one attribute value, or null for anything that is not one (never throws). */
209
+ export function parseSeed(raw: string): DeliverySeed | null {
210
+ let value: unknown
211
+ try {
212
+ value = JSON.parse(raw)
213
+ } catch {
214
+ return null
215
+ }
216
+ if (!isRecord(value) || value.v !== 1) return null
217
+ const { baseUrl, externalId, design, payload, signature, renderDef } = value
218
+ if (typeof baseUrl !== 'string' || typeof externalId !== 'string') return null
219
+ if (!isRecord(payload) || !isRecord(payload.subject) || !isRecord(payload.lifecycle) || !isRecord(payload.content)) {
220
+ return null
221
+ }
222
+ // A pin the seed names is judged by the same grammar the card's own pin is; one that fails it is not a seed.
223
+ const pin = parsedPin(design)
224
+ if (pin === null) return null
225
+ return {
226
+ baseUrl,
227
+ externalId,
228
+ ...(pin ? { design: pin } : {}),
229
+ payload: payload as unknown as CertPayload,
230
+ ...(isRecord(signature) ? { signature: signature as unknown as CertSignature } : {}),
231
+ renderDef: parseRenderDef(renderDef),
232
+ }
233
+ }
234
+
235
+ /** A fallback record in one attribute value, or null for anything that is not one (a seed included; never throws). */
236
+ export function parseFallback(raw: string): DeliveryFallback | null {
237
+ let value: unknown
238
+ try {
239
+ value = JSON.parse(raw)
240
+ } catch {
241
+ return null
242
+ }
243
+ if (!isRecord(value) || value.v !== 1 || 'payload' in value) return null
244
+ const { baseUrl, externalId, design, face } = value
245
+ if (typeof baseUrl !== 'string' || typeof externalId !== 'string') return null
246
+ if (face !== 'options' && face !== 'none') return null
247
+ const pin = parsedPin(design)
248
+ if (pin === null) return null
249
+ return { baseUrl, externalId, ...(pin ? { design: pin } : {}), face }
250
+ }
251
+
252
+ /** One placement's key: the origin, the entry and the pin (the read's own key, so a pin never shares a seed). */
253
+ function seedKey(baseUrl: string, externalId: string, design: DesignPin | undefined): string {
254
+ return design ? `${baseUrl}|${externalId}|design=${design.version}|${design.brand ?? ''}` : `${baseUrl}|${externalId}`
255
+ }
256
+
257
+ /**
258
+ * The seeds (and fallback records) this page's server HTML carried, by placement, for the page's lifetime: a card
259
+ * mounted later by a client-side render (an in-app navigation back to a server-rendered article, or React's client
260
+ * re-render after a hydration error) paints what the server painted, as the hydrated card it replaces would have.
261
+ */
262
+ const pageSeeds = new Map<string, PageRecord>()
263
+
264
+ const recordKey = (record: PageRecord): string => {
265
+ const r = 'seed' in record ? record.seed : record.fallback
266
+ return seedKey(r.baseUrl, r.externalId, r.design)
267
+ }
268
+
269
+ /** Every seed and fallback record the live document carries, in document order. */
270
+ function scanDocument(): PageRecord[] {
271
+ const found: PageRecord[] = []
272
+ for (const el of Array.from(document.querySelectorAll(`[${SEED_ATTRIBUTE}]`))) {
273
+ const raw = el.getAttribute(SEED_ATTRIBUTE)
274
+ if (!raw) continue
275
+ const seed = parseSeed(raw)
276
+ const fallback = seed ? null : parseFallback(raw)
277
+ if (seed) found.push({ seed, raw })
278
+ else if (fallback) found.push({ fallback, raw })
279
+ }
280
+ return found
281
+ }
282
+
283
+ /**
284
+ * The record the server wrote for this placement and pin: its seed, or its fallback record. By default: from the map,
285
+ * else from one scan of the document (which also records every other one on the page). With `live`, the map is not
286
+ * consulted: the document is scanned and decides, so what a hydrating card learns is what the server HTML in front of
287
+ * it carries, not what an earlier page in this process left behind. `undefined` when the page carries none, and always
288
+ * on a server.
289
+ */
290
+ export function pageRecordFor(
291
+ baseUrl: string,
292
+ externalId: string,
293
+ design?: DesignPin,
294
+ options: { readonly live?: boolean } = {},
295
+ ): PageRecord | undefined {
296
+ const key = seedKey(baseUrl, externalId, design)
297
+ if (typeof document === 'undefined') return undefined
298
+ const known = options.live ? undefined : pageSeeds.get(key)
299
+ if (known) return known
300
+ let inDocument = false
301
+ for (const found of scanDocument()) {
302
+ const k = recordKey(found)
303
+ if (k === key) inDocument = true
304
+ if (options.live || !pageSeeds.has(k)) pageSeeds.set(k, found)
305
+ }
306
+ // A live read answers for the document alone: a record an earlier page left in the map is not one this page carries.
307
+ return options.live && !inDocument ? undefined : pageSeeds.get(key)
308
+ }
309
+
310
+ /** `pageRecordFor`, seeds only: the seed the server painted for this placement and pin. */
311
+ export function pageSeedFor(
312
+ baseUrl: string,
313
+ externalId: string,
314
+ design?: DesignPin,
315
+ options: { readonly live?: boolean } = {},
316
+ ): PageSeed | undefined {
317
+ const record = pageRecordFor(baseUrl, externalId, design, options)
318
+ return record && 'seed' in record ? record : undefined
319
+ }
320
+
321
+ /** A Suspense boundary's comment marker as React's server render writes it: `$` (done), `$?` (pending), `$!`, `$~`. */
322
+ const BOUNDARY_MARKER = /^\$[?!~]?$/
323
+
324
+ /**
325
+ * Whether the live document holds server-rendered React HTML: any Suspense boundary marker. The delivery card sits in
326
+ * a `<Suspense>` of its own, so a server render of one always leaves a marker, a card the server painted nothing for
327
+ * (revoked, expired, unreachable) included, and a client render never does. This is how a card that is hydrating tells
328
+ * a browser hydrating server HTML (the document holds it) from a server render that merely runs where a `document`
329
+ * exists (a test's jsdom, a shim): there the document does not hold the HTML being produced.
330
+ */
331
+ export function pageHoldsServerHtml(): boolean {
332
+ if (typeof document === 'undefined' || !document.documentElement) return false
333
+ const walker = document.createTreeWalker(document.documentElement, 128 /* NodeFilter.SHOW_COMMENT */)
334
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
335
+ if (BOUNDARY_MARKER.test((node as Comment).data)) return true
336
+ }
337
+ return false
338
+ }
339
+
340
+ /** Test seam: forget every seed (a new page). */
341
+ export function forgetPageSeedsForTests(): void {
342
+ pageSeeds.clear()
343
+ }
@@ -1,8 +1,23 @@
1
1
  /**
2
- * `certrev-reader-face`: the round avatar on a reader byline: the person's photo when there is one to show, the
3
- * silhouette when there is not. The span carries a size class (`sm` for the author, none for the banner reviewer,
4
- * `lg` for the memo and sidebar reviewer); the image is requested at `width` square through the asset resizer.
2
+ * `certrev-reader-face`: the round avatar on a reader byline: the person's photo when there is one to paint, else their
3
+ * initials, else (a person with no name to take them from) the silhouette. The span carries a size class (`sm` for the
4
+ * author, none for the banner reviewer, `lg` for the memo and sidebar reviewer); the image is requested at `width`
5
+ * square through the asset resizer.
6
+ *
7
+ * THE INITIALS ARE A BYTE SPEC the portal's Liquid snippets and the WordPress renderer repeat, so all three print the
8
+ * same bytes: trim the name and split it on single spaces (`' '`) SKIPPING empty parts (two spaces in a row are one
9
+ * gap: "Jane Doe" gives "JD"); drop the FIRST part when, lowercased, it is one of the honorifics dr, mr, mrs, ms,
10
+ * prof, mx (each with or without its trailing dot); take the first character, by code point, of each of the first two
11
+ * parts left; uppercase them. Non-empty initials paint exactly
12
+ * `<svg viewBox="0 0 40 40" aria-hidden="true" focusable="false"><text x="20" y="20" text-anchor="middle"
13
+ * dominant-baseline="central" font-size="15" font-weight="700">JD</text></svg>` (one line, the initials escaped);
14
+ * empty ones paint the silhouette as before.
15
+ *
16
+ * "A photo to paint" is `show` with a URL that passes `safeUrl`. A def that hides `reviewerPhoto`, or
17
+ * `display.showExpertPhoto: false`, passes `show: false`: the URL is never read, so it never reaches the page, and the
18
+ * avatar is the initials (a hidden photo used to remove the avatar altogether; it removes the photo now).
5
19
  */
20
+ import { asText } from '../components/escape.js'
6
21
  import { avatarUrl, cleaned, esc, safeUrl } from './helpers.js'
7
22
 
8
23
  export type ReaderFaceSize = '' | 'sm' | 'lg'
@@ -10,8 +25,10 @@ export type ReaderFaceSize = '' | 'sm' | 'lg'
10
25
  export interface ReaderFaceInput {
11
26
  /** The photo URL on the envelope. */
12
27
  readonly photo: unknown
13
- /** Whether to ATTEMPT the photo: false never reads the URL (the silhouette shows). */
28
+ /** Whether to ATTEMPT the photo: false never reads the URL (the initials show). */
14
29
  readonly show: boolean
30
+ /** The person's display name, the initials' source; a hostile type reads as no name. */
31
+ readonly name: unknown
15
32
  readonly size: ReaderFaceSize
16
33
  /** The pixel width the resizer is asked for. */
17
34
  readonly width: number
@@ -20,16 +37,52 @@ export interface ReaderFaceInput {
20
37
  const SILHOUETTE =
21
38
  '<svg viewBox="0 0 40 40" aria-hidden="true" focusable="false"><circle cx="20" cy="14.8" r="7"/><path d="M20 23.4c-6.9 0-12.6 4.8-13.8 11.2a20 20 0 0 0 27.6 0C32.6 28.2 26.9 23.4 20 23.4Z"/></svg>'
22
39
 
40
+ const HONORIFICS: ReadonlySet<string> = new Set([
41
+ 'dr',
42
+ 'dr.',
43
+ 'mr',
44
+ 'mr.',
45
+ 'mrs',
46
+ 'mrs.',
47
+ 'ms',
48
+ 'ms.',
49
+ 'prof',
50
+ 'prof.',
51
+ 'mx',
52
+ 'mx.',
53
+ ])
54
+
55
+ /** The initials of a display name by the spec above: '' when the name leaves no first character to take. */
56
+ export function initialsOf(name: unknown): string {
57
+ const parts = asText(name)
58
+ .trim()
59
+ .split(' ')
60
+ .filter((part) => part !== '')
61
+ if (HONORIFICS.has((parts[0] ?? '').toLowerCase())) parts.shift()
62
+ return parts
63
+ .slice(0, 2)
64
+ .map((part) => Array.from(part)[0] ?? '')
65
+ .join('')
66
+ .toUpperCase()
67
+ }
68
+
69
+ const initialsSvg = (initials: string): string =>
70
+ '<svg viewBox="0 0 40 40" aria-hidden="true" focusable="false"><text x="20" y="20" text-anchor="middle" ' +
71
+ `dominant-baseline="central" font-size="15" font-weight="700">${esc(initials)}</text></svg>`
72
+
23
73
  const DIMENSION: Readonly<Record<ReaderFaceSize, number>> = { '': 42, sm: 36, lg: 46 }
24
74
 
25
- export function readerFace({ photo, show, size, width }: ReaderFaceInput): string {
75
+ export function readerFace({ photo, show, name, size, width }: ReaderFaceInput): string {
26
76
  const safe = show ? cleaned(safeUrl(photo)) : ''
27
77
  const src = cleaned(avatarUrl(safe, width))
28
78
  const dim = DIMENSION[size]
29
79
  const cls = size === '' ? 'certrev-r-face' : `certrev-r-face ${esc(size)}`
80
+ const initials = src !== '' ? '' : initialsOf(name)
30
81
  const inner =
31
82
  src !== ''
32
83
  ? `<img src="${esc(src)}" alt="" width="${dim}" height="${dim}" loading="lazy" decoding="async">`
33
- : SILHOUETTE
84
+ : initials !== ''
85
+ ? initialsSvg(initials)
86
+ : SILHOUETTE
34
87
  return `<span class="${cls}">${inner}</span>`
35
88
  }
@@ -27,8 +27,10 @@
27
27
  * sentence is direct text of the scope element, which carries `data-ftc-line` itself (after the cue's " · " there
28
28
  * is a `<!-- -->`, so the cue separator and the sentence are two text nodes). The `<!-- -->` marks between
29
29
  * adjacent leaves are React's, kept so the bytes equal the Liquid snippets' and the portal's goldens;
30
- * - the def's `hidden` set removes the avatars (`reviewerPhoto`), `display.showExpertPhoto === false` keeps the
31
- * silhouette and never requests the photo, `display.showAuthor === false` drops the author column.
30
+ * - the avatars: a photo when there is one to paint, else the person's initials (`face.ts` is the byte spec), else the
31
+ * silhouette for a name with none. The def's `hidden` set holding `reviewerPhoto`, and `display.showExpertPhoto ===
32
+ * false`, keep the photo URL out of the page entirely (the avatar is the initials); neither removes the avatar.
33
+ * `display.showAuthor === false` drops the author column.
32
34
  *
33
35
  * Every interpolated field is escaped and every URL passes `safeUrl`. A hostile type (a number, an object) renders as
34
36
  * nothing, never as a throw: see `helpers.ts`.
@@ -90,7 +92,7 @@ interface Facts {
90
92
  readonly def: unknown
91
93
  readonly certId: string
92
94
  readonly ename: string
93
- readonly hideAvatar: boolean
95
+ /** Whether a photo may be painted: neither `reviewerPhoto` hidden nor `showExpertPhoto: false`. */
94
96
  readonly showPhoto: boolean
95
97
  /** The joined credential labels, '' when there are none. */
96
98
  readonly creds: string
@@ -110,8 +112,7 @@ function readFacts(input: ReaderFaceInput): Facts {
110
112
  const def = input.def
111
113
  const rd = rec(def)
112
114
 
113
- const hideAvatar = contains(rd.hidden, 'reviewerPhoto')
114
- const showPhoto = disp.showExpertPhoto !== false && !hideAvatar
115
+ const showPhoto = disp.showExpertPhoto !== false && !contains(rd.hidden, 'reviewerPhoto')
115
116
 
116
117
  // POR-9738: each credential's cardLabel over its bare abbreviation, joined with ', ' (labels are not trimmed).
117
118
  const labels: string[] = []
@@ -132,7 +133,6 @@ function readFacts(input: ReaderFaceInput): Facts {
132
133
  def,
133
134
  certId: asText(input.certId),
134
135
  ename: textOr(expert.displayName),
135
- hideAvatar,
136
136
  showPhoto,
137
137
  creds: labels.join(', '),
138
138
  hasCue,
@@ -216,15 +216,15 @@ function bannerCard(f: Facts): string {
216
216
  const authorName = textOr(author.name)
217
217
  const authorTitle = textOr(author.title)
218
218
  const hasAuthor = f.disp.showAuthor !== false && authorName !== '' && authorName !== f.ename
219
- const avatar = (photo: unknown, size: 'sm' | ''): string =>
220
- f.hideAvatar ? '' : readerFace({ photo, show: f.showPhoto, size, width: 84 })
219
+ const avatar = (photo: unknown, name: string, size: 'sm' | ''): string =>
220
+ readerFace({ photo, show: f.showPhoto, name, size, width: 84 })
221
221
 
222
222
  const authorBy = hasAuthor
223
- ? `<div class="certrev-r-by">${avatar(author.photoUrl, 'sm')}<div>\n <b>${esc(authorName)}</b>` +
223
+ ? `<div class="certrev-r-by">${avatar(author.photoUrl, authorName, 'sm')}<div>\n <b>${esc(authorName)}</b>` +
224
224
  `${authorTitle !== '' ? `<em>${esc(authorTitle)}</em>` : ''}<span class="certrev-r-role">Written by</span>\n </div>\n </div>`
225
225
  : ''
226
226
  const expertBy =
227
- `<div class="certrev-r-by">${avatar(f.expert.photoUrl, '')}<div>\n <b>${esc(f.ename)}</b>` +
227
+ `<div class="certrev-r-by">${avatar(f.expert.photoUrl, f.ename, '')}<div>\n <b>${esc(f.ename)}</b>` +
228
228
  `${verifiedLine(f, true)}<span class="certrev-r-role on">Reviewed by</span>\n </div>\n </div>`
229
229
 
230
230
  const certifiedAt = f.content.certifiedAt
@@ -279,7 +279,7 @@ function bannerMemo(f: Facts): string {
279
279
  (f.vurl !== '' ? anchor(f.vurl, '', 'View certificate') : '') +
280
280
  '</div>'
281
281
  : ''
282
- const avatar = f.hideAvatar ? '' : readerFace({ photo: f.expert.photoUrl, show: f.showPhoto, size: 'lg', width: 112 })
282
+ const avatar = readerFace({ photo: f.expert.photoUrl, show: f.showPhoto, name: f.ename, size: 'lg', width: 112 })
283
283
  return (
284
284
  `${sectionOpen(f, false, `Expert memo by ${f.ename}`)}\n <div class="certrev-r-card pad">\n` +
285
285
  ' <div class="certrev-r-kick">Expert memo</div>\n' +
@@ -299,7 +299,7 @@ function bannerMemo(f: Facts): string {
299
299
  function sidebar(f: Facts): string {
300
300
  if (f.ename === '') return ''
301
301
  const bio = f.disp.showBio !== false && !isBlank(f.expert.bio) ? asText(f.expert.bio) : ''
302
- const avatar = f.hideAvatar ? '' : readerFace({ photo: f.expert.photoUrl, show: f.showPhoto, size: 'lg', width: 112 })
302
+ const avatar = readerFace({ photo: f.expert.photoUrl, show: f.showPhoto, name: f.ename, size: 'lg', width: 112 })
303
303
  const both = f.purl !== '' && f.vurl !== ''
304
304
  const links =
305
305
  f.purl !== '' || f.vurl !== ''