repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

226 lines · 24.7 KB · download this file

#!/usr/bin/env python3
"""Markdown: what every text written in Markdown can do (quotes, titles,
strikethrough, tick-box lists, bare links, aligned tables, heading anchors,
footnotes, line breaks, fenced code) and that none of it opens a way around
the escaping. Texts go through a page's Text panel, previewed as the editor
does and saved, as visitors see them. Runs on a new site's catalogue (never
the site's own); never touches live data, credentials or media."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets,hashlib
import html as H
script=str(pathlib.Path(sys.argv[1]).resolve())
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from sample_content import ensure_samples, start_catalog
import signin  # signs requests in (REMOTE_USER → session cookie)
checks=[]
def check(v,msg):
 assert v,msg
 checks.append(msg);print('PASS',msg,flush=True)
with tempfile.TemporaryDirectory(prefix='blowfish-markdown-test-') as tmp:
 root=pathlib.Path(tmp);data=root/'var/db/blowfishcms';(data/'admin/tmp').mkdir(parents=True)
 (data/'admin/csrf.key').write_text(secrets.token_hex(32))
 for kind in ['photography','music','artwork','blog']:(root/'media/blowfishcms'/kind).mkdir(parents=True)
 start_catalog(data/'catalog.sqlite')
 with signin.connect(data/'catalog.sqlite') as copy:
  for table in ['pages','page_blocks','site_settings']:copy.execute('drop table if exists '+table)
  ensure_samples(copy)
 env={**os.environ,'BLOWFISH_ROOT':str(root),'BLOWFISH_PAGES_SEED':str(pathlib.Path(__file__).resolve().parent/'fixtures/sample-pages-seed.json')}
 def run(path,fields=None,cookie='',user='',fetch=False,page_route=False):
  url=urllib.parse.urlsplit(path);body=urllib.parse.urlencode(fields or {},doseq=True).encode() if fields is not None else b''
  e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'POST' if fields is not None else 'GET','SCRIPT_NAME':'/_page' if page_route else url.path,'DOCUMENT_URI':url.path,
     'QUERY_STRING':url.query,'CONTENT_TYPE':'application/x-www-form-urlencoded','CONTENT_LENGTH':str(len(body)),'HTTP_COOKIE':cookie,'REMOTE_USER':user,
     'HTTP_ORIGIN':'https://example.net','REMOTE_ADDR':'192.0.2.1'}
  if fetch:e['HTTP_X_REQUESTED_WITH']='fetch'
  p=subprocess.run(['perl',script],input=body,env=signin.sign(e),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  assert p.returncode==0,(p.stderr.decode(),p.stdout[:300])
  head,html=p.stdout.decode().split('\r\n\r\n',1);hdr={}
  for line in head.split('\r\n'):k,v=line.split(': ',1);hdr[k]=v
  return int(hdr['Status']),html,hdr
 subprocess.run(['perl',script,'--migrate'],env=env,check=True,stdout=subprocess.PIPE)
 con=sqlite3.connect(data/'catalog.sqlite');con.row_factory=sqlite3.Row
 status,html,hdr=run('/admin/',user='admin');csrf=re.match(r'bf_csrf=([^;]+)',hdr['Set-Cookie']).group(1);admin='bf_csrf='+csrf
 def post(fields,fetch=False):return run('/admin/',{'csrf':csrf,**fields},cookie=admin,user='admin',fetch=fetch)
 # A page with one Text panel to write in.
 post({'kind':'pages','action':'page_create','label':'Notes','slug':'notes'})
 post({'kind':'pages','action':'nav_toggle','page':'notes'})
 post({'kind':'page','page':'notes','action':'block_add','type':'text','width':'full'})
 block=con.execute("select id from page_blocks where page='notes' and type='text'").fetchone()[0]
 def form():
  html=run('/admin/?kind=page&page=notes',user='admin',cookie=admin)[1]
  p=dict(con.execute("select * from pages where slug='notes'").fetchone())
  f={'kind':'page','page':'notes','action':'page_save','title':p['title'],'description':p['description'],'nav_label':p['nav_label'],'slug':'notes'}
  for tag in re.findall(r'<input [^>]*>',html):
   name=re.search(r'name="(b\.[^"]+)"',tag);value=re.search(r'value="([^"]*)"',tag)
   if name and 'type="checkbox"' not in tag:f.setdefault(name.group(1),H.unescape(value.group(1)) if value else '')
  for name,opts in re.findall(r'<select name="(b\.[^"]+)"[^>]*>(.*?)</select>',html,re.S):
   sel=re.search(r'<option value="([^"]*)" selected',opts) or re.search(r'<option value="([^"]*)"',opts);f[name]=sel.group(1)
  return f
 base=form()
 def md(text):
  # The panel's contents as the editor's preview draws them (nothing saved).
  status,body,_=post({**base,'action':'page_preview',f'b.{block}.body':text},fetch=True)
  assert status==200,body
  page=json.loads(body)['html']
  m=re.search(r'<div class="page-copy">(.*?)</div></div></section>',page,re.S)
  return m.group(1) if m else page
 key=lambda text:hashlib.sha256(text.encode()).hexdigest()[:8]

 # ---- What was there, now working -------------------------------------
 out=md('> Quoted words\n> > and a quote inside')
 check(out.count('<blockquote>')==2 and 'Quoted words' in out and '&gt;' not in out,'a > quote is a quotation, and > > nests one')
 out=md('[a link](https://example.org/ "On hover") and [another](/contact/ \'Single\')')
 check('<a href="https://example.org/" title="On hover">a link</a>' in out and '<a href="/contact/" title="Single">another</a>' in out,'a link’s title in quotes works, double or single')
 pic='/media/pictures/0123456789abcdef0123456789abcdef.jpg'
 check(f'<img src="{pic}" alt="Harbour" title="At dawn"' in md(f'![Harbour]({pic} "At dawn")'),'a picture’s title works too')
 check('<a href="https://example.org/" title="Kept">a reference</a>' in md('[a reference][r]\n\n[r]: https://example.org/ "Kept"'),'and a reference link’s')
 out=md('~~gone~~, `~~kept~~`, ~~ not this ~~')
 check('<del>gone</del>' in out and '<code>~~kept~~</code>' in out and '~~ not this ~~' in out,'~~strikethrough~~, but not in code or with spaces inside')
 out=md('```\nfirst = 1\n```\n\nThen text.')
 check(out.startswith('<pre><code>first = 1') and '<p>Then text.</p>' in out,'a text may start with fenced code')

 # ---- New --------------------------------------------------------------
 out=md('- [ ] to do\n- [x] done\n- [X] also done\n- [a link](/x/)')
 check(out.count('<li class="task"><input type="checkbox" disabled')==3 and out.count(' checked')==2 and '<li><a href="/x/">a link</a></li>' in out,'- [ ] and - [x] are tick boxes (disabled), a link in a list stays a link')
 out=md('Go to https://example.org/a?b=1&c=2. Or (https://example.org/x_(y)), see [https://example.org/](https://example.org/), and `https://example.org/code`.')
 check('<a href="https://example.org/a?b=1&amp;c=2">https://example.org/a?b=1&amp;c=2</a>.' in out,'a bare address is a link, the full stop after it left out')
 check('(<a href="https://example.org/x_(y)">https://example.org/x_(y)</a>)' in out,'a bracket it opened stays in, one it didn’t stays out')
 check(out.count('<a href="https://example.org/">')==1 and '<a href="https://example.org/"><a' not in out and '<code>https://example.org/code</code>' in out,'no link inside a link, none in code')
 out=md('| Plan | Price | Note |\n|:-----|:-----:|------:|\n| Basic | 10 | a |\n| Full | 20 | b |')
 check('<th class="align-left">Plan</th><th class="align-center">Price</th><th class="align-right">Note</th>' in out and '<td class="align-center">20</td>' in out,'a table’s columns are aligned by its separator line')
 check('<th>A</th><th>B</th>' in md('| A | B |\n|---|---|\n| 1 | 2 |'),'and left as they are without colons')
 out=md('## Pricing {#pricing}\n\n### Taken {#main}\n\nNot a heading {#x}')
 check('<h2 id="pricing">Pricing</h2>' in out,'a heading ending in {#name} gets that anchor')
 check('<h3>Taken {#main}</h3>' in out and 'Not a heading {#x}' in out,'a name the page uses itself isn’t taken (the mark stays); {#…} outside a heading is text')
 text='A claim[^src], another[^2] and the first again[^src]. A missing one[^none].\n\n[^src]: The **source**, at https://example.org/.\n[^2]: A second note,\n    on two lines.\n[^unused]: Never mentioned.'
 out=md(text);k=key(text)
 check(f'<sup class="fn-ref"><a href="#fn-{k}-src" id="fnref-{k}-src">1</a></sup>' in out and f'<sup class="fn-ref"><a href="#fn-{k}-2" id="fnref-{k}-2">2</a></sup>' in out,'footnote marks are numbered in order, each linking to its note')
 check(out.count(f'href="#fn-{k}-src"')==2 and out.count(f'id="fnref-{k}-src"')==1,'a note marked twice keeps its number; only the first mark is linked back to')
 check(f'<li id="fn-{k}-src">The <strong>source</strong>, at <a href="https://example.org/">https://example.org/</a>. <a href="#fnref-{k}-src" class="fn-back" title="Back to the text">↩</a></li>' in out,'notes are listed at the end, in Markdown, with a link back')
 check('A second note, on two lines.' in re.sub(r'\s+',' ',out) and 'Never mentioned' not in out and '[^none]' in out and '[^src]:' not in out,'lines indented under a note are part of it; unused notes are left out, unknown marks stay as written')
 check(key('Other text[^src]\n\n[^src]: x') != k,'two texts never share a footnote’s ids')
 out=md('First line\\\nsecond line\n\n    code ends with \\')
 check('First line <br />' in out.replace('\n',' ') and 'code ends with \\' in out,'a backslash at a line’s end is a line break, except in code')

 # ---- The page tools ------------------------------------------------------
 out=md('> [!NOTE]\n> Heads up.\n\n> [!warning] Mind the step\n>\n> Second paragraph.\n\n> [!BOGUS]\n> A plain quote.')
 check('<blockquote class="callout callout--note">' in out and '<p class="callout__title">Note</p><p>Heads up.</p>' in out,'> [!NOTE] is a callout box titled Note')
 check('<blockquote class="callout callout--warning">' in out and '<p class="callout__title">Mind the step</p>' in out and out.count('<blockquote')==3,'a title after the type names it; each callout is a box of its own, even straight after another')
 check('[!BOGUS] A plain quote.' in re.sub(r'\s+',' ',out),'an unknown type stays a plain quotation')
 out=md('::: center lead\nBig **words**\n:::\n\n::: box soft\n## Inside {#inside}\n\n- a\n:::')
 check('<div class="md-center md-lead"><p>Big <strong>words</strong></p>' in out and '<div class="md-box md-soft"><h2 id="inside">Inside</h2>' in out,'::: containers take their names as styles and hold any Markdown')
 check('<p>::: nope stays text :::</p>' in re.sub(r'\s+',' ',md('::: nope\nstays text\n:::')) and '::: center never closed' in re.sub(r'\s+',' ',md('::: center\nnever closed')),'unknown names, and a container that never closes, stay as text')
 text='::: columns\nLeft[^1]\n|||\nRight\n|||\nThird\n:::\n\n[^1]: A note.';out=md(text)
 check('<div class="md-columns md-columns--3"><div class="md-col"><p>Left<sup class="fn-ref">' in out and out.count('<div class="md-col">')==3 and f'id="fn-{key(text)}-1"' in out,'columns split at |||, each Markdown, footnotes and all')
 out=md('+++ What does it **cost**?\nAbout ~~ten~~ twelve.\n+++\n\n+++ breaking news +++\nand more')
 check('<details class="md-fold"><summary>What does it <strong>cost</strong>?</summary><div class="md-fold__body"><p>About <del>ten</del> twelve.</p>' in out,'+++ makes a fold-out: its title shows, the rest opens from it')
 check('+++ breaking news +++' in out,'a +++ line with no closing line is text')
 check('<div class="md-box"><details class="md-fold"><summary>In a box</summary><div class="md-fold__body"><div class="md-center"><p>deep</p>' in md('::: box\n+++ In a box\n::: center\ndeep\n:::\n+++\n:::').replace('\n',''),'containers and fold-outs nest')
 out=md('Hosting\n: Your site, kept *running*.\n: Backups too.\n\nRepairs\n: Laptops.')
 check('<dl class="md-dl"><dt>Hosting</dt><dd>Your site, kept <em>running</em>.</dd><dd>Backups too.</dd><dt>Repairs</dt><dd>Laptops.</dd></dl>' in out,'a term with : lines under it is a definition list')
 out=md('[Book](/contact/){.button .outline .large} [Go](/x/){.button .theme .full} [plain](/y/){.nothing}')
 check('<a class="cta cta--outline cta--large" href="/contact/">Book</a>' in out and '<a class="cta cta--theme form-submit cta--full" href="/x/">Go</a>' in out and '<a href="/y/">plain</a>{.nothing}' in out,'{.button} makes a link a button, drawn as the Button block’s; without .button the marks stay')
 out=md(f'![Shop]({pic} "Our shop"){{.small .right .round .bogus}}\n\nInline ![x]({pic}) here')
 check(f'<figure class="md-figure md-figure--small md-figure--right md-figure--round"><img src="{pic}" alt="Shop" title="Our shop" /><figcaption>Our shop</figcaption></figure>' in out,'a picture on its own line is a figure, its title the caption, sized and placed by its marks')
 check(f'<p>Inline <img src="{pic}" alt="x" /> here</p>' in out,'a picture inside a sentence stays where it is')
 out=md('==marked== H~2~O x^2^ [[Ctrl]]+[[C]] but a == b, 2^10 and ~1 day; `==code==`')
 check('<mark>marked</mark> H<sub>2</sub>O x<sup>2</sup> <kbd>Ctrl</kbd>+<kbd>C</kbd> but a == b, 2^10 and ~1 day' in out and '<code>==code==</code>' in out,'highlight, sub- and superscript and keys, but not loose marks or code')
 out=md('::: box onclick\nx\n:::\n\n[x](/a/){.button .x" onclick="y}\n\n> [!NOTE" onclick="x]\n> y\n\n+++ <b>t</b>\nz\n+++')
 check(not re.search(r'<[^>]*onclick',out) and '<b>' not in out and '<div class="md-box">' in out,'the page tools take only their own names: nothing else reaches an attribute')

 # ---- Code and the library's items -----------------------------------------
 out=md('```perl\nmy $x = "a <b> & \'c\'"; # note\n```\n\n```\nplain <b> & x\n```\n\n```nosuchlang\nx < y\n```')
 check('<pre><code class="lang-perl"><span class="tok-k">my</span> <span class="tok-v">$x</span> = <span class="tok-s">&quot;a &lt;b&gt; &amp; &#39;c&#39;&quot;</span>; <span class="tok-c"># note</span>' in out,'```perl is coloured: keywords, variables, strings, comments, all escaped')
 check('<pre><code>plain &lt;b&gt; &amp; x\n</code></pre>' in out and '<pre><code>x &lt; y\n</code></pre>' in out,'a fence without a language, or with one not known, is plain code')
 check('<span class="tok-t">&lt;p</span> <span class="tok-a">class</span>=' in md('```html\n<p class="x">hi</p>\n```') and 'class="lang-js"' in md('```javascript\nlet a = 1;\n```'),'other languages too, by their names')
 ids={k:secrets.token_hex(16) for k in ('video','file','late')}
 track=con.execute("select id from uploads where kind='music' limit 1").fetchone()[0]
 def libraries(path):
  # The editor's #md-library data block: what its "library" button offers.
  m=re.search(r'<script type="application/json" id="md-library">(.*?)</script>',run(path,user='admin',cookie=admin)[1],re.S)
  return json.loads(m.group(1)) if m else []
 check([l['ref'] for l in libraries('/admin/?kind=page&page=notes')]==['picture','track'],'the library button offers Pictures, and only the libraries with something in them (no videos or files yet)')
 for kind,i,title,name in [('video',ids['video'],'Shop tour','tour.mp4'),('file',ids['file'],'Price list','prices.pdf')]:
  con.execute('insert into uploads (id,kind,title,collection,filename,thumbnail,mime,bytes,created_at) values (?,?,?,?,?,?,?,?,?)',(i,kind,title,'',name,'','application/octet-stream',1000,'2026-01-01T00:00:00Z'))
 con.commit()
 out=md(f'![Our jingle](/track/{track}/)\n\n![A walk round the shop](/video/{ids["video"]}/)\n\n![](/file/{ids["file"]}/)')
 check('<figure class="md-embed md-embed--track"><audio controls preload="none"' in out and '<figcaption>Our jingle</figcaption>' in out,'a library track on its own line is its player, captioned')
 check('<figure class="md-embed md-embed--video"><div class="video-list">' in out and '<figcaption>A walk round the shop</figcaption>' in out,'a video is its player')
 check('<figure class="md-embed md-embed--file"><div class="file-list">' in out and 'Price list' in out,'a file is its download card')
 out=md(f'![Gone](/video/{"0"*32}/)\n\nWatch ![this](/video/{ids["video"]}/) now.')
 check('md-embed' not in out and 'Gone' not in out and 'video-list' not in out,'an item that isn’t there shows nothing; one inside a sentence isn’t embedded')
 text=f'![Late](/file/{ids["late"]}/)'
 check('md-embed' not in md(text),'(before the file is in the library)')
 con.execute('insert into uploads (id,kind,title,collection,filename,thumbnail,mime,bytes,created_at) values (?,?,?,?,?,?,?,?,?)',(ids['late'],'file','Late file','','late.txt','','text/plain',10,'2026-01-01T00:00:00Z'));con.commit()
 check('md-embed--file' in md(text),'a text embedding an item isn’t kept between requests, so a new item shows at once')
 check('' not in md('a 0 b 1 c') and 'a 0 b 1 c' in md('a 0 b 1 c'),'the placeholders’ marks can’t be typed in')

 # ---- Nothing new gets around the escaping ------------------------------
 out=md('<script>alert(1)</script> <b onclick="x">b</b>')
 check('<script' not in out and '<b' not in out and '&lt;script&gt;' in out,'HTML typed in a text is shown as text')
 out=md('[a](javascript:alert(1)) [b](/x/ "t\\" onclick=\\"alert(1)") ![c](https://example.org/x.png "t")')
 check('javascript:' not in out and not re.search(r'<[^>]*onclick',out) and 'example.org/x.png' not in out and 'title="t"' in out,'unsafe links, attributes slipped into titles and outside pictures stay out')
 out=md('https://example.org/"onmouseover="alert(1) and https://example.org/<x>')
 check('onmouseover="' not in out and 'href="https://example.org/"' in out,'a bare address ends where an escaped quote or bracket starts')
 out=md('## X {#x" onmouseover="a}\n\n[^a"b]: no\n\n- [x]" onclick="y\n\n| a |\n|:---|\n| <i>b</i> |')
 check('onmouseover="' not in out and 'onclick="' not in out and '<i>' not in out,'heading anchors, footnote names, tick boxes and table cells take only their own shapes')
 # Ids and classes on what's left are checked by the scrubber, whoever made them.
 out=md('&lt;h2 id="main"&gt;x &lt;input type="text"&gt;')
 check('<h2' not in out and '<input' not in out,'escaped tags stay escaped')

 # ---- As visitors see it ------------------------------------------------
 f=form();body='## Our prices {#prices}\n\n| Plan | Price |\n|:--|--:|\n| x | 1 |\n\nNote[^1]\n\n[^1]: Taxes included.'
 f[f'b.{block}.body']=body
 status,resp,_=post(f,fetch=True);check(status==200 and json.loads(resp)['ok'],'a text with the new Markdown saves')
 html=run('/notes/',page_route=True)[1]
 check('<h2 id="prices">Our prices</h2>' in html and f'id="fn-{key(body)}-1"' in html and '<section class="footnotes">' in html and '/css/site.css?v=18' in html,'the page shows it, with the stylesheet that draws it')
 # ---- Writing it: the editor's boxes and help ------------------------------
 ed=run('/admin/?kind=page&page=notes',user='admin',cookie=admin)[1]
 check(f'name="b.{block}.body"' in ed and re.search(rf'<textarea name="b\.{block}\.body"[^>]*data-markdown="pictures"',ed),'a block’s Markdown box is marked for the toolbar, with its picture button')
 check(not re.search(r'<input [^>]*data-markdown',ed),'plain text fields are not')
 # (To the help's closing note: its examples hold fold-outs, <details> of their own.)
 helpbox=re.search(r'<details class="pe-fold md-help" id="md-help">(.*?)<p class="optional">Leave a blank line',ed,re.S)
 check(helpbox and ed.count('id="md-help"')==1 and ed.count('data-tab-panel=')==3,'the page editor’s bar has the Markdown help, once, apart from the page’s settings')
 rows=re.findall(r'<tr><td><pre>(.*?)</pre>.*?</td><td class="md-help__out">(.*?)</td></tr>',helpbox.group(1),re.S) if helpbox else []
 out={H.unescape(w):o for w,o in rows}
 check(len(out)>=10 and '<del>struck</del>' in out.get('**bold**, *italic*, ~~struck~~','') and '<h3 id="prices">A heading</h3>' in out.get('### A heading {#prices}','')
  and 'class="align-right"' in out.get('| Plan | Price |\n|:-----|------:|\n| Basic | 10 |','') and 'class="footnotes"' in out.get('A claim[^1]\n\n[^1]: The source.',''),'each example in the help is shown as the site draws it')
 js=(pathlib.Path(__file__).resolve().parent.parent/'public/js/admin.js').read_text()
 check("textarea[data-markdown]" in js and "'insertText'" in js and '/js/admin.js?v=41' in ed and '/css/admin.css?v=55' in ed,'admin.js gives those boxes the toolbar (with undo), at its new version')
 css=(pathlib.Path(__file__).resolve().parent.parent/'public/css/site.css').read_text()
 check(all(s in css for s in ['li.task{','.align-right{','.footnotes{']),'site.css styles tick boxes, aligned columns and footnotes')
 check(all(s in css for s in ['blockquote.callout{','.md-columns--3{','.md-fold>summary{','.md-figure--round img{','.md-dl dt{','kbd{']+[f'.md-{n}' for n in ['center','right','lead','small','muted','box','soft','accent','dark','light']]),'and every page tool, each container style included')
 check('<details class="md-fold">' in out.get('+++ What does it cost?\nTen a month.\n+++','') and 'callout--note' in out.get('> [!NOTE]\n> Something worth knowing.',''),'the help shows the page tools too')
 check("'Two columns'" in js and 'md-tools__more' in js,'the toolbar’s “more…” menu puts them in')
 libs={l['ref']:l for l in libraries('/admin/?kind=page&page=notes')}
 check(list(libs)==['picture','track','video','file'] and [l['label'] for l in libs.values()]==['Pictures','Music','Videos','Files'] and libs['picture']['items']==[],'the editor lists every library, in the libraries’ order, for its library button (Pictures open the picture chooser)')
 check(any(i['id']==track for i in libs['track']['items']) and {'id':ids['video'],'title':'Shop tour','note':''} in libs['video']['items'] and 'fromLibrary' in js and "['library', 'library'" in js,'with each library’s items, by title and collection')
 con.execute("update uploads set title=? where id=?",('</script><b>x',ids['file']));con.commit()
 ed=run('/admin/?kind=page&page=notes',user='admin',cookie=admin)[1]
 check('</script><b>' not in ed and '\\u003c/script\\u003e\\u003cb\\u003ex' in ed,'a title can’t end the list early: its < and > are written as \\u003c and \\u003e')

 # ---- Articles: anything from the libraries ---------------------------------
 con.execute("update uploads set title='Harbour song',artwork='harbour.webp' where id=?",(track,))
 con.execute("update uploads set title='Price list',filename=?,bytes=2500000 where id=?",(ids['file']+'/prices.pdf',ids['file']))
 con.execute("update uploads set thumbnail='poster.webp' where id=?",(ids['video'],));con.commit()
 ed=run('/admin/?kind=blog&new=1',user='admin',cookie=admin)[1]
 check(re.search(r'<textarea name="body"[^>]*data-markdown="pictures" data-picture-folder="articles"',ed) and 'data-insert-picture' not in ed,'the article editor has the toolbar’s picture and library buttons, its pictures chosen from the Articles folder')
 check([l['ref'] for l in libraries('/admin/?kind=blog&new=1')]==['picture','track','video','file'],'its library button offers every library')
 body=(f'Before the things.\n\n![Our jingle](/track/{track}/)\n\n![A walk round the shop](/video/{ids["video"]}/)\n\n'
  f'::: columns\n![The prices](/file/{ids["file"]}/)\n|||\n![Harbour]({pic} "At dawn")\n:::')
 status,resp,_=post({'kind':'blog','action':'autosave','id':'','title':'Library things','body':body},fetch=True);pid=json.loads(resp)['id']
 status,resp,_=post({'kind':'blog','action':'publish','id':pid,'title':'Library things','body':body},fetch=True)
 check(status==200,'an article holding a track, a video, a file and a picture publishes')
 status,page,_=run(f'/blog/?post={pid}',page_route=True)
 post_html=page[page.index('Before the things.'):]
 check(status==200 and '<figure class="md-embed md-embed--track">' in post_html and '<audio controls preload="none"' in post_html
  and '<figcaption>Our jingle</figcaption>' in post_html,'on the article, a track plays, with the caption under it')
 track_fig=re.search(r'<figure class="md-embed md-embed--track">(.*?)</figure>',post_html,re.S).group(1)
 check(track_fig.startswith('<audio ') and 'aria-label="Listen to Harbour song"' in track_fig and not any(s in track_fig for s in ['album-art','Harbour song<','download','badge','music-card']),'and shows its player alone: no title, artwork, badge or download')
 check('<figure class="md-embed md-embed--video">' in post_html and '<video controls playsinline' in post_html and 'poster="/media/video/poster.webp"' in post_html,'a video plays, its poster first')
 check(f'<div class="md-col"><figure class="md-embed md-embed--file">' in post_html and f'href="/download/{ids["file"]}/" download="prices.pdf"' in post_html and 'PDF · 2.4 MB' in post_html,'a file, here in a column, is its download, with its name and size')
 check(f'<figure class="md-figure"><img src="{pic}" alt="Harbour" title="At dawn" /><figcaption>At dawn</figcaption></figure>' in post_html,'a picture is a captioned figure beside it')
 check(' style=' not in page and all(re.search(r'\ssrc="/|type="application/ld\+json"',t) for t in re.findall(r'<script[^>]*>',page)),'none of it needs an inline script or style (the security policy allows neither)')
 status,feed,_=run('/blog/feed.xml')
 check(status==200 and re.search(r'poster="https://[^"/]+/media/video/poster\.webp"',feed) and re.search(rf'href="https://[^"/]+/download/{ids["file"]}/"',feed) and re.search(r'src="https://[^"/]+/media/music/',feed),'in the RSS feed, its players, posters and downloads have whole addresses')
 lead=re.search(r'<meta name="description" content="([^"]*)"',page)
 check(lead and lead.group(1)=='Before the things.','the article’s opening lines leave the embeds out')
print(json.dumps({'checks':len(checks)}))