HANIVVRA SUPPORT

CMS API reference

The CMS exposes three machine-facing endpoints. They are served over HTTPS on the site's own domain (https://<domain>) and authenticated with a short-lived, self-signed JWT.

Endpoint Purpose
/cms/api/cms Manage CMS objects: pages, headers, footers, CSS, JS, forms, error pages, redirects and links. Each request runs a single action (§3).
/cms/api/content Read and write the stored content of an existing object: the HTML of a page, header, footer or error page, or the source of a CSS or JS file (§4).
/cms/api/form Read and write a form's field schema (§5). The schema format is documented in Form schema.

All three endpoints use the same credentials (§1) and the same JWT authentication (§2). A complete, working client is in §7.


1. Credentials

When an API key is created (or regenerated) in the admin UI, under API › Manage (see the admin quick start), you are shown a one-time JSON object, with a button to download it as credentials.json. Save it; it is never shown again. It is conventionally stored as credentials.json:

{
  "domain": "example.com",
  "user":   "mykeyname",
  "key":    "-----BEGIN PRIVATE KEY-----\n…Ed25519 PKCS#8…\n-----END PRIVATE KEY-----\n"
}
Field Use in the JWT / request
domain The request host, and the value of the aud claim. Must match exactly.
user The value of the sub claim.
key Your Ed25519 private key (PEM, PKCS#8). Sign the JWT with it. Keep it secret: never print it, log it, or commit it.

1.1 Key format caveat

The key is an Ed25519 key in PKCS#8 version 2 form (RFC 5958 OneAsymmetricKey, 83 bytes of DER, which embeds the public key). Some OpenSSL builds, and the libraries layered on them (older Python cryptography, Node.js 18 crypto.createPrivateKey), reject this form with errors such as DECODER routines::unsupported or asn1 encoding routines::wrong tag.

The portable fix is to extract the 32-byte private seed yourself. In the DER bytes, the seed is the 32 bytes immediately after the byte sequence 04 22 04 20. Every code example in §7 does this, so it works whatever form the key is in. The jwtsign tool (§7.1) reads either form directly.


2. Authentication (JWT)

The token is a compact JWS that you build and sign yourself. There is no login call and no session: mint a fresh token for every request.

  • Algorithm: EdDSA only (Ed25519). No other alg is accepted.
  • Header: {"alg":"EdDSA","typ":"JWT"}
  • Encoding: standard JWT, base64url without padding: base64url(header) . base64url(claims) . base64url(signature). The signature covers the ASCII string base64url(header) + "." + base64url(claims).
  • Clock skew: the server tolerates ±300 seconds on time-based claims.

2.1 Claims

Claim Required Value
aud yes Must equal domain, the request host. Mismatch → 401.
exp yes Expiry, Unix seconds. Keep it short: 60 seconds is typical.
iat yes Issued-at, Unix seconds.
nbf optional Not-before, Unix seconds (honored within the ±300 s skew if present).
sub yes The key's user name.
action /cms/api/cms only The command to run (§3.3, §3.4).
query see below All request parameters, as a URL-encoded query string.

/cms/api/cms requires action; some actions also take a query. /cms/api/content and /cms/api/form have no action and require query.

2.2 The query claim carries all request parameters

The HTTP request itself only ever carries one parameter: token. Every parameter for the request lives inside the JWT's query claim, as a URL-encoded query string (what PHP's http_build_query, Python's urllib.parse.urlencode or JavaScript's URLSearchParams produce).

To reference object id 3:

query = "id=3"

For a request with several fields:

query = "name=about&title=About+Us&description=Company+info&keywords=&header=2&footer=1&generate_toc=1&generate_footnotes=0&css=4,5&js="

Content writes put the whole HTML, CSS or JS source in the query claim too, so a token can be large (up to about 1 MB of content). Send such tokens in a POST body, never in a URL.

2.3 Authentication failures

A missing or invalid token, a bad signature, a wrong aud, an expired or not-yet-valid token, or an unknown or disabled key are all rejected with 401 (plain-text message). An unexpected server error returns 500.


3. Endpoint: /cms/api/cms

Runs a single command named by the required action claim. Parameters go in the query claim.

3.1 Making requests

Method Where token goes Which actions run
GET URL query string: /cms/api/cms?token=… Read actions (§3.3)
POST Form body (application/x-www-form-urlencoded): token=… Write actions (§3.4)

The HTTP method selects the dispatcher: a read action sent via POST, or a write action sent via GET, is not found and returns 404. Use GET for reads and POST for writes.

Example: list pages (GET)

GET https://example.com/cms/api/cms?token=<jwt>

where <jwt> has the claims aud=example.com, sub=mykeyname, exp=<now+60>, iat=<now>, action=pages, and no query, since listing takes no parameters.

Example: create a header (POST)

POST https://example.com/cms/api/cms
Content-Type: application/x-www-form-urlencoded

token=<jwt>

where <jwt> has action=header_new and query=name=Main+Header.

3.2 Responses

Code Meaning Body
200 Success (reads, and create/save writes) application/json; see §3.5
204 Success, no content (deletes, enable/disable) empty
400 Invalid or missing action parameters plain-text message
401 JWT rejected (see §2.3) plain-text message
404 Unknown action, or the wrong HTTP method for it plain text Unrecognized action: …
409 Conflict: delete blocked by references, or a duplicate name plain-text message
422 A rejected value, such as a reserved page-name prefix plain-text message, e.g. Page name is not allowed to begin with "cms/"
500 Server error plain-text message

Useful response headers

  • Content-Type: application/json on every 200.
  • X-ID: <n>: the numeric id of the newly created row. Set by the *_new and page_duplicate actions. Read it from the header; the body is the refreshed list, not the new object.

All timestamps in responses (time_modified, etc.) are Unix seconds. Sizes (size) are bytes and may be null. Booleans (generate_toc, is_enabled, …) are JSON true/false.

3.3 Read actions (use GET)

Pass the name as the action claim. "Params" are the keys you put in the query claim.

action Params (query) Returns
pages (optional) id Array of page objects. With id, just that page.
pages-link-back id Array of partial page objects that link to page id.
headers (optional) id Array of header objects.
footers (optional) id Array of footer objects.
css (optional) id Array of CSS objects.
js (optional) id Array of JS objects.
forms (optional) id Array of form objects. With id, just that form.
error-pages (optional) id Array of error-page objects (id = HTTP status code).
redirects (optional) id* Array of redirect objects. Omit id to list all.
pages-brief none { "pages": [ {value,text}, … ] }: id/name pairs, handy for pickers.
headers_footers_css_js none { headers:[…], footers:[…], css:[…], js:[…] } of {value,text} pairs.
form-options none { spam_levels:[…], anti_robots:[…] } of {value,text,description}.
links_broken none { pages:{…}, headers:{…}, footers:{…}, form_response_pages:{…}, error_pages:{…} } (see §3.5).
page-history id (page id) Array of history entries.
header-history id Array of history entries.
footer-history id Array of history entries.
css-history id Array of history entries.
js-history id Array of history entries.
form-schema-history id (form id) Array of history entries for the field schema.
form-response-history id (form id) Array of history entries for the response page.
error-page-history id (status code) Array of history entries.

* The redirects id is only honored as an integer (the base-10 encoding of the source string). In practice, omit id and list all, then match the source you want client-side.

An id for a read must be all digits; a non-numeric id is ignored and treated as "list all".

3.4 Write actions (use POST)

Unless noted, on success these return 200 with the refreshed list for that entity type (the same shape as the matching read action).

Where a table says "all keys must be present", send every listed key, even when its value is empty (keywords=, css=). To change one property of a page, read the page first and send back all of its current values with your change applied.

Pages

action Params (all keys must be present) Notes and limits
page_new name, title, description, keywords, header, footer, generate_toc, generate_footnotes, css, js name 1–64 characters matching ^[a-z0-9-_~]+(/[a-z0-9-_~]+)*$; reserved prefixes rejected (422); title 1–255; description 1–65535; keywords ≤65535; header/footer = an id or "" for none; generate_* = 0/1; css/js = comma-separated ids or "". Returns X-ID.
page_duplicate id, name, title, description, keywords Copies the page at id (its header/footer, TOC/footnote flags, CSS/JS links and latest content) under a new name/title/description/keywords. Same field rules as page_new. Returns X-ID.
page_save id, name, title, description, keywords, header, footer, generate_toc, generate_footnotes, css, js Same rules as page_new. Changing name moves the page to a new URL, and the CMS adds a redirect from the old path to the page automatically; a redirect_new for that path then returns 409.
page_delete id Returns 204.

Page names and URLs. A page's name determines its public path:

name Published at
index /
about /about.html
animal/index /animal/
animal/cow /animal/cow.html

Link to pages with root-relative URLs in exactly that form: /about.html, /animal/.

Reserved prefixes. Names (and redirect sources) beginning with a reserved prefix such as admin/, cms/, css/, forum/ or js/ are rejected with 422. Avoid any name that could collide with the CMS's own paths, or with the asset folders images/, docs/, audio/ and video/.

Headers and footers

action Params Notes
header_new name name ≤64. Returns X-ID.
header_save id, name name ≤64.
header_delete id Returns 204; 409 if pages still use it.
footer_new name name ≤64. Returns X-ID.
footer_save id, name name ≤64.
footer_delete id Returns 204; 409 if pages still use it.

A header or footer name is a label only (it may contain spaces). Its HTML is written through /cms/api/content (§4).

CSS and JS

action Params Notes
css_new name, media name 1–64 characters matching ^[a-z0-9-_~]+(/[a-z0-9-_~]+)*$; media ≤65535 (a media query list such as screen or print; empty for all media). Returns X-ID.
css_save id, name, media Same rules.
css_delete id Returns 204; 409 if in use.
js_new name name 1–64 characters, same pattern. Returns X-ID.
js_save id, name Same rules.
js_delete id Returns 204; 409 if in use.

The source of a CSS or JS object is written through /cms/api/content (§4). When a page links several JS files, they are loaded in alphabetical order of name.

Forms

This covers the metadata only. The field schema goes through /cms/api/form (§5), and the response page through /cms/api/content with type=form-response (§4).

action Params Notes
form_new name, response_title, closed_message, notify_address, notify_immediate, digest_hour, spam_level, anti_robot, retention_days, header, footer, css, js name 1–64 characters matching ^[a-z0-9-_~]+$; response_title 1–255; closed_message ≤65535; notify_address ≤254 or ""; notify_immediate = 0/1; digest_hour = 0–23, or "" for no digest; spam_level/anti_robot = a value from form-options; retention_days = 1–65535, or "" to keep forever. Returns X-ID.
form_save id plus the same keys Same rules.
form_enable id Returns 204.
form_disable id Returns 204. A disabled form serves its closed_message instead of its fields, and refuses submissions regardless of what a stale page shows.
form_delete id Returns 204; 409 naming the published pages that still carry the form. Deleting a form discards its schema versions, response page, key ledger and every stored submission.

A form is placed on a page with <cms-form id="<form id>"></cms-form>. See Styling forms.

The response page, which a visitor sees after sending the form, can show details of their submission. Put these placeholders where the details should appear, and the CMS fills them in for each submission:

  • <cms-field name="reference"></cms-field>: the submission's reference, such as 4-17, which the visitor can quote if they get in touch.
  • <cms-field name="date"></cms-field>: the date it was sent, as a <time class="cms-time"> element that the page's script restates in the visitor's own timezone and conventions.
  • <cms-field name="form"></cms-field>: the form's name in the CMS.

Write each tag exactly as shown, with name as its only attribute. A name the CMS doesn't know is replaced by nothing.

Error pages

There is no create or delete: the set is fixed at 401, 403, 404 and 500.

action Params Notes
error-page_save id, title, header, footer, generate_toc, generate_footnotes, css, js id = status code; title 1–255; other rules as for pages.

Redirects

action Params Notes
redirect_new source, destination source ≤128 characters matching ^[a-z0-9-_~]((\.|/)?[a-z0-9-_~])*/?$ (a path without the leading slash, e.g. old-page.html or old/); reserved prefixes rejected (422); destination = a page id (digits). Ignored if a page already occupies that path. Returns X-ID.
redirect_save id, source, destination id = the existing source string; other rules as above.
redirect_delete source Returns 204.
action Params Notes
links_add label, url, mode Turns occurrences of the text label into links to url across the site's content. label 1–4096; url 1–4096; mode = 0 (first appearance), 1 (first per section), 2 (every appearance). Returns an array of per-entity results (see §3.5).

3.5 Response data shapes

Page (pages)

id, name, title, description, keywords, id_header, header, id_footer, footer,
generate_toc (bool), generate_footnotes (bool),
css (comma-separated ids | null), js (comma-separated ids | null),
author_last, time_modified (unix), size (bytes | null)

header and footer are names; id_header and id_footer are the ids to send back in page_save (use "" when they are null).

Form (forms)

id, name, is_enabled (bool), response_title, closed_message, notify_address (| null),
notify_immediate (bool), digest_hour (0-23 | null), spam_level, anti_robot,
retention_days (| null), id_header, header, id_footer, footer,
css (comma-separated ids | null), js (comma-separated ids | null),
author_last, time_modified (unix), size (response page bytes | null),
schema_size (field schema bytes | null), schema_id (| null),
schema_modified (unix | null), schema_published (unix | null)

closed_message is plain text, not HTML. size is the response page; the schema columns describe the form's latest field schema. schema_size measures that schema document as stored, the same bytes /cms/api/form returns. schema_id null means the form has no fields yet; schema_published null means its latest schema has never been published.

Header / Footer (headers, footers)

id, name, author_last, time_modified, size

CSS (css): id, name, media, author_last, time_modified, size

JS (js): id, name, author_last, time_modified, size

Error page (error-pages)

id (status code), title, id_header, header, id_footer, footer,
generate_toc, generate_footnotes, css, js, author_last, time_modified, size

Redirect (redirects): source, page (destination page id), destination (page name)

History entry (*-history): id (version id), num (1-based version #), author_last, time_modified, size. Pass id as version to /cms/api/content (§4.2) to read that version.

Select list (pages-brief, headers_footers_css_js): objects of { value, text }.

Broken links (links_broken)

{
  "pages":               { "<page name>":   ["<broken href>", "…"] },
  "headers":             { "<header name>": ["…"] },
  "footers":             { "<footer name>": ["…"] },
  "form_response_pages": { "<form name>":   ["…"] },
  "error_pages":         { "<status code>": ["…"] }
}

A group with no broken links comes back as an empty array ([]) rather than an empty object, so test for emptiness rather than type. Only links to pages are recognized: a link to a non-page file such as /js/fonts.json is reported as broken even when the file exists.

Links added (links_add): an array of

{ "type", "id", "name", "v1", "v2" }        // success (v1/v2 are the before/after version ids)
{ "type", "name", "error" }                 // per-entity failure

4. Endpoint: /cms/api/content

Reads and writes the stored content of a single existing object:

  • page: the children of <main>
  • header: the children of <header>
  • footer: the children of <footer>
  • error-page: the children of <main> on that error page
  • form-response: the page shown after a form is submitted
  • css, js: the source file

It does not create or delete objects; use /cms/api/cms for that.

Content is the inside of the wrapping element. Never include the <header>, <footer> or <main> tags themselves, nor <html>, <head> or <body>: the CMS builds the document around your content.

This endpoint has no action claim; it is driven entirely by the query claim, which is required (a request without it returns 400). The HTTP method selects the operation:

Method Operation token location
GET Read the current content of an object URL query string: /cms/api/content?token=…
POST Write new content to an object Form body (application/x-www-form-urlencoded): token=…

4.1 Parameters (in the query claim)

Param GET POST Value
type ✓ ✓ Object kind: page, header, footer, css, js, form-response or error-page.
file ✓ ✓ The object's numeric id, or for error-page its HTTP status code.
version ✓ (optional) A revision id from the object's history (the id of a *-history entry, §3). Omit for the latest.
contentId ✓ The revision id from your most recent read (the id field of the GET response). Use 0 if the object has no content yet.
content ✓ The new content. Up to 1,048,576 characters.

4.2 Read content (GET)

On success, 200 with a JSON object:

{ "id": 1234, "content": "…current content…", "name": "about" }
  • id: the current revision id. Pass it back as contentId when you write. 0 means the object exists but has no content yet.
  • content: the stored content (an empty string if none).
  • name: the object's name (for error-page, its status code).

With version, the response is that earlier revision instead of the latest, and id is its revision id. A revision that belongs to a different object returns 404.

To restore an earlier revision, read it with version, read the object again without version to get the latest id, and write the old content with that latest id as contentId. A write that sends the old revision's id as contentId is rejected with 409, like any other outdated id.

4.3 Write content (POST)

On success, 204 with an X-ID header carrying the resulting revision id. Use that value as contentId on your next write to the same object. The server may create a new revision or amend the most recent one in place; either way the response is 204 and X-ID is the current revision id.

Typical flow: read the object, make your change to the content you read, and send that read's id as contentId together with the new content. Then carry the response's X-ID into your next write. The id must come from the read your change is based on: reading the object again just before writing, only to get a fresh id, silently overwrites anything saved since your first read.

Your contentId must be the object's current latest revision. If someone else has saved since you read it, the write is rejected with 409. Reload the object (its new id and content) and re-apply your change before saving again.

A write can also get 409 when another user saved the same object at the same moment. The message then says another save occurred simultaneously: wait a moment, reload, and save again.

Writes go to staging. A human reviews staged changes in the admin UI and publishes them; until then the public site is unchanged and you cannot view the rendered result there.

4.4 Responses

Code Meaning Body
200 (GET) content returned application/json; see §4.2
204 (POST) content saved; X-ID = resulting revision id empty
400 Missing query, a missing required parameter, an unknown type (POST), or a version that is not a whole number (GET) plain-text message
401 JWT rejected (see §2.3) plain-text message
404 (GET) unknown type, or the requested object, content or version does not exist for that object plain-text message
409 (POST) contentId is not the latest revision, or another save occurred at the same moment; reload and retry plain-text message
413 (POST) content exceeds 1,048,576 characters plain-text message
500 Server error plain-text message

4.5 HTML normalization

page, header, footer, error-page and form-response content is HTML and is normalized when saved, so a later read may return a reformatted version of what you sent. css and js are stored byte-for-byte.

Observed behavior of the normalizer:

  • Markup is re-indented and attributes are re-serialized; <pre> content and its whitespace are preserved exactly.
  • Classes, ids and all data-* attributes are kept.
  • Void elements are written in XHTML form (<hr />).
  • Element and attribute names are lowercased, including inside inline SVG (viewBox is stored as viewbox). This is harmless: pages are served as text/html, and the browser's HTML parser restores the correct case for SVG names.
  • Executable <script> and <style> elements and inline style/event attributes are not allowed; the site's Content Security Policy blocks inline code in any case. Use CSS and JS objects. The one exception is structured data: <script type="application/ld+json"> blocks are kept and published as valid JSON.

Content may later be edited by people in the admin UI's CKEditor 5, which can rewrap loose inline content in <p> elements and drop elements that are empty. Put &nbsp; in any element that must exist but has no content.

When a person edits content in that editor, it also strips these attributes (which copy-and-paste from other editors and chat tools often leaves behind): data-end, data-index-in-node, data-list-item-id, data-number, data-path-to-node, data-pm-slice, data-start and data-tight. API writes keep them, but avoid those names for your own data so a later human edit cannot break the page.


5. Endpoint: /cms/api/form

Reads and writes the field schema of an existing form. It does not create or delete forms; use /cms/api/cms (§3.4) for that.

The schema document's format (element types, constraints, conditional visibility, limits) is documented in Form schema. This section covers only the transport.

Like /cms/api/content, this endpoint has no action claim; it is driven entirely by the query claim, which is required. The HTTP method selects the operation:

Method Operation token location
GET Read a schema version URL query string: /cms/api/form?token=…
POST Write a new schema version Form body (application/x-www-form-urlencoded): token=…

5.1 Parameters (in the query claim)

Param GET POST Value
id ✓ ✓ The form's numeric id.
version ✓ (optional) A specific schema version id (the id of a form-schema-history entry). Omit for the latest.
schemaId ✓ The version id from your most recent read. Use 0 if the form has no schema yet.
schema ✓ The new schema document, as a JSON string. Up to 65,535 bytes.
remove ✓ (optional) Comma-separated element keys whose removal you are confirming. See §5.4.

5.2 Read a schema (GET)

On success, 200 with a JSON object:

{ "id": 41, "schema": "{\"format\":1,\"fields\":[…]}", "name": "contact", "time_published": 1786000000 }
  • id: the version id. Pass it back as schemaId when you write. 0 means the form exists but has no schema yet.
  • schema: the stored document as a JSON string, normalized (every default filled in). An empty string if none.
  • name: the form's name.
  • time_published: when a publish emitted this version, or null if it never has.

Because every submission records the version it was made against, version lets you fetch a historical schema to render or interpret older submissions correctly.

5.3 Write a schema (POST)

On success, 204 with an X-ID header carrying the resulting version id.

A write normally creates a new version, but the server may amend the most recent one in place instead when that version is unpublished, was saved by you, and is less than two minutes old. A write whose schema is byte-identical to the current version creates nothing. In every case the response is 204 and X-ID is the version to send as your next schemaId.

A published version is never amended, so the schema a live page was generated against cannot change underneath it. Versions are never deleted.

Typical flow: read the form, make your change to the schema you read, and send that read's id as schemaId with the new schema. Then carry the response's X-ID into your next write. The id must come from the read your change is based on: reading the form again just before writing, only to get a fresh id, silently overwrites anything saved since your first read.

Your schemaId must be the form's current latest version. If someone else has saved since you read it, the write is rejected with 409.

5.4 Element keys are frozen

Element keys are the join between the schema, stored submissions, exports and notification templates, so once a key exists it keeps its meaning permanently.

  • Send back the key of every element you are keeping. An element without a key is treated as new and gets one derived from its label.
  • Dropping a key is a removal, and must be confirmed by naming it in remove. Otherwise the write is rejected with 422 naming the field you were about to strand. This catches the common mistake of relabeling an element and forgetting to send its key.
  • A key's type may only change within a compatible pair: text ↔ textarea, select ↔ radio. Anything else must be a confirmed removal plus a new element.
  • A retired key may be reused only for the same kind of field it was before. Keys are remembered for the life of the form, so a key derived for a new element never collides with a retired one either.

5.5 Responses

Code Meaning Body
200 (GET) schema returned application/json; see §5.2
204 (POST) schema saved; X-ID = new version id empty
400 Missing query or a required parameter, a version that is not a whole number (GET), or the document is not a schema at all (not JSON, not a JSON object, unknown format, fields not a list) plain-text message
401 JWT rejected (see §2.3) plain-text message
404 (GET) no such form, or no such version plain-text message
409 (POST) schemaId is not the latest version; reload and retry plain-text message
413 (POST) schema exceeds 65,535 bytes plain-text message
422 (POST) the document is a schema but breaks one or more rules application/json; see below
500 Server error plain-text message

A 422 body lists every failure at once, each with a JSON path into the document you sent:

{"errors":[
  {"path":"fields[3].visible_when.field","message":"No field named \"topic\" appears earlier in the form"},
  {"path":"fields[5].max","message":"Required"}
]}

6. Notes and caveats

  • Only token is read from the HTTP request. Put every request parameter in the JWT query claim, never in the URL or body directly.
  • exp should be short and freshly minted per request; the ±300 s skew is the only leeway.
  • Reserved page-name prefixes (admin/, cms/, css/, forum/, js/, …) are rejected on page_new, page_save and redirect sources with 422 and a plain-text message.
  • sub follows the key name. Renaming an API key changes its user name, and therefore the sub you must send. Update your clients after a rename.
  • On /cms/api/cms, every write returns the full refreshed entity list (or 204), so a client can keep its local view in sync from a single call.
  • Create dependencies first. Create headers, footers, CSS and JS (and write their content) before pages, so each page can be created with its final properties in one page_new.
  • Nothing goes live by itself. Every change lands in staging and must be reviewed and published by a person in the admin UI (how). Use links_broken after uploading to check internal links.
  • Assets are uploaded by people, not the API. Images (/images/…), documents (/docs/…), downloads (/downloads/…), audio (/audio/…) and video (/video/…) are uploaded through the admin UI's File Management (how). File names are case-sensitive. Uploaded files go live at once, without publishing.

7. Working clients

7.1 jwtsign (command line)

jwtsign is a command-line tool that signs a token directly, with no code to write. It reads every key form, including PKCS#8 v2. Run jwtsign --help for every option.

System Download Notes
Windows /downloads/jwtsign.zip jwtsign.exe, 32-bit; runs on 32-bit and 64-bit Windows.
Linux (x86-64) /downloads/jwtsign.tar.gz jwtsign, for 64-bit Intel and AMD processors. Needs glibc 2.25 or later (below).
macOS None Sign tokens in code instead (§7.2 to §7.4).

On Linux, unpack it with tar -xzf jwtsign.tar.gz. Check your glibc version with ldd --version. These releases have glibc 2.25 or later:

  • Ubuntu 18.04 and later, and distributions based on it, such as Linux Mint 19 and later
  • Debian 10 (buster) and later
  • Fedora 26 and later
  • Red Hat Enterprise Linux, Rocky Linux, AlmaLinux and CentOS Stream 8 and later
  • openSUSE Leap 15 and SUSE Linux Enterprise 15 and later
  • Amazon Linux 2 and Amazon Linux 2023
  • Rolling releases such as Arch Linux, Manjaro and openSUSE Tumbleweed

Older releases, such as Ubuntu 16.04, Debian 9 and CentOS 7, are too old. Alpine Linux uses musl instead of glibc, and ARM computers, such as a Raspberry Pi, need a different build; neither can run it. On Windows, it also runs under WSL with a current Ubuntu.

Give it credentials.json as it is, and it takes the key, the audience (domain) and the subject (user) from that file:

Option Use
--credentials <path> The credentials file. Supplies the key, aud and sub.
--claim <name>=<value> Any other claim; repeat as needed. Use it for action. The value is everything after the first =, used exactly as given.
--query <name>=<value> One parameter of the query claim; repeat as needed. Names and values are URL-encoded for you and joined with &. A name given twice keeps its last value.
--exp <seconds> Lifetime in seconds (default 120). iat is added automatically.
--out <path> Write the token to a file instead of standard output.
--aud, --sub Override the values from the credentials file. Rarely needed.
--key-file <path> Instead of --credentials: a PEM key file. Then --aud and --sub are required.

On any error, including a missing key, jwtsign prints a message and exits with a non-zero status.

# Read (GET): list pages
TOKEN=$(jwtsign --credentials credentials.json --exp 60 --claim action=pages)
curl -G https://example.com/cms/api/cms --data-urlencode "token=$TOKEN"

# Write (POST): create a header; the new id is in the X-ID response header
TOKEN=$(jwtsign --credentials credentials.json --exp 60 --claim action=header_new --query "name=Main Header")
curl -i https://example.com/cms/api/cms --data-urlencode "token=$TOKEN"

# Content (GET): no action claim, only a query
TOKEN=$(jwtsign --credentials credentials.json --exp 60 --query type=header --query file=1)
curl -G https://example.com/cms/api/content --data-urlencode "token=$TOKEN"

Mint a new token for every request. With --claim query=… instead of --query, the value is used exactly as given, so you must URL-encode it yourself. For content writes, whose query contains a whole page, a client library (below) is usually easier than passing the page on a command line.

Each code example below signs a token with the key from credentials.json and lists the site's error pages. All three handle both PKCS#8 key forms (§1.1).

7.2 Python

Requires cryptography and requests.

import base64, json, time, urllib.parse
import requests
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

creds = json.load(open('credentials.json'))
der = base64.b64decode(''.join(creds['key'].strip().split('\n')[1:-1]))
at = der.index(bytes.fromhex('04220420'))
key = Ed25519PrivateKey.from_private_bytes(der[at + 4:at + 36])

def b64(data):
  return base64.urlsafe_b64encode(data).rstrip(b'=').decode()

def token(action=None, query=None):
  now = int(time.time())
  claims = {'aud': creds['domain'], 'sub': creds['user'], 'iat': now, 'exp': now + 60}
  if action is not None:
    claims['action'] = action
  if query is not None:
    claims['query'] = urllib.parse.urlencode(query)
  signing_input = b64(json.dumps({'alg': 'EdDSA', 'typ': 'JWT'}).encode()) + '.' + b64(json.dumps(claims).encode())
  return signing_input + '.' + b64(key.sign(signing_input.encode()))

base = 'https://' + creds['domain']

# Read: GET with the token in the URL
r = requests.get(base + '/cms/api/cms', params={'token': token('error-pages')})
print(r.status_code, r.json())

# Write: POST with the token in the form body; the new id is in X-ID
# r = requests.post(base + '/cms/api/cms', data={'token': token('header_new', {'name': 'Main'})})
# header_id = r.headers['X-ID']

# Content: read the revision id, then write with it
# cur = requests.get(base + '/cms/api/content', params={'token': token(query={'type': 'header', 'file': header_id})}).json()
# r = requests.post(base + '/cms/api/content', data={'token': token(query={'type': 'header', 'file': header_id, 'contentId': cur['id'], 'content': '<a href="/">Home</a>'})})
# next_content_id = r.headers['X-ID']

7.3 Node.js (18+)

No dependencies.

import { createPrivateKey, sign } from 'node:crypto';
import { readFileSync } from 'node:fs';

const creds = JSON.parse(readFileSync('credentials.json', 'utf8'));
// Rebuild a PKCS#8 v1 wrapper around the 32-byte seed; works for v1 and v2 keys.
const der = Buffer.from(creds.key.replace(/-----[^-]+-----|\s/g, ''), 'base64');
const at = der.indexOf(Buffer.from('04220420', 'hex'));
const seed = der.subarray(at + 4, at + 36);
const key = createPrivateKey(
{
  key: Buffer.concat([Buffer.from('302e020100300506032b657004220420', 'hex'), seed]),
  format: 'der',
  type: 'pkcs8'
});

const b64 = (data) => Buffer.from(data).toString('base64url');

function token(claims)
{
  const now = Math.floor(Date.now() / 1000);
  const head = b64(JSON.stringify({ alg: 'EdDSA', typ: 'JWT' }));
  const body = b64(JSON.stringify({ aud: creds.domain, sub: creds.user, iat: now, exp: now + 60, ...claims }));
  return head + '.' + body + '.' + b64(sign(null, Buffer.from(head + '.' + body), key));
}

const base = 'https://' + creds.domain;
const res = await fetch(base + '/cms/api/cms?token=' + token({ action: 'error-pages' }));
console.log(res.status, await res.json());

// Write example:
// await fetch(base + '/cms/api/cms', { method: 'POST', body: new URLSearchParams({ token: token({ action: 'header_new', query: new URLSearchParams({ name: 'Main' }).toString() }) }) });

7.4 PHP (7.2+, with sodium)

<?php
$creds = json_decode(file_get_contents('credentials.json'), true);
$der = base64_decode(preg_replace('/-----[^-]+-----|\s/', '', $creds['key']));
$seed = substr($der, strpos($der, "\x04\x22\x04\x20") + 4, 32);
$secret = sodium_crypto_sign_secretkey(sodium_crypto_sign_seed_keypair($seed));

function b64($s) { return rtrim(strtr(base64_encode($s), '+/', '-_'), '='); }

function token($secret, $creds, $action = null, $query = null)
{
  $now = time();
  $claims = ['aud' => $creds['domain'], 'sub' => $creds['user'], 'iat' => $now, 'exp' => $now + 60];
  if ($action !== null) { $claims['action'] = $action; }
  if ($query !== null) { $claims['query'] = http_build_query($query); }
  $input = b64(json_encode(['alg' => 'EdDSA', 'typ' => 'JWT'])) . '.' . b64(json_encode($claims));
  return $input . '.' . b64(sodium_crypto_sign_detached($input, $secret));
}

$base = 'https://' . $creds['domain'];
echo file_get_contents($base . '/cms/api/cms?token=' . urlencode(token($secret, $creds, 'error-pages')));

7.5 End-to-end: publishing a page

The order that avoids revisiting objects:

  1. header_new and footer_new (POST /cms/api/cms); note each X-ID.
  2. Write each header and footer's HTML with POST /cms/api/content, type=header / type=footer, contentId=0.
  3. css_new / js_new for each stylesheet and script, then write their source with type=css / type=js.
  4. page_new with the header, footer, CSS and JS ids; note its X-ID.
  5. Write the page's <main> content with type=page, contentId=0.
  6. Optionally error-page_save for 401, 403, 404, 500, then write their content with type=error-page, file=<status code>. These already have content, so read first to get the current contentId.
  7. GET links_broken and fix anything it reports.
  8. Ask a person to review the staged changes and publish them.