ident
All repositories: gitoria
7.4 KB
// lib/api-helpers.hl — the plumbing of the function routes (lib/api.hl): JSON answers, redirects, the component error// page, the STRICT JSON body, the app's key + secret check of a call, the selector's CORS answers. Statics only.//// STRICT: a body must be a JSON object; an unknown field, a missing field and a field of// the wrong type are each a 400 whose `error` names the field. hl:json's JSON.parse// aborts the request (500) on invalid input and the language has no catch (hybriel #12),// so the body's syntax is checked first by jsoncheck.hl (copied from tickets).import { Response } from 'hl:http1'import ErrorPage from '../components/error.hl'import { jsonErrorAt } from './jsoncheck.hl'import { appByKey, appOfSecret } from './apps.hl'import { originAllowed } from './apps-helpers.hl'import { publicUrl } from './invites.hl'// SECURITY HEADERS of every answer these routes make (mission SI): no sniffing, no referrer, no framing, and a JSON / redirect answer may// load nothing at all. (A component page's headers are hl:web's, not ours: reports/SI-sec.md.)static noSniff = 'nosniff'static dataPolicy = "default-src 'none'; frame-ancestors 'none'"static pagePolicy = "default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self'; manifest-src 'self'; form-action 'none'; base-uri 'none'; frame-ancestors 'none'"static jsonHeaders = { 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' 'X-Content-Type-Options' = noSniff 'Referrer-Policy' = 'no-referrer' 'X-Frame-Options' = 'DENY' 'Content-Security-Policy' = dataPolicy }static htmlHeaders = { 'Content-Type' = 'text/html; charset=utf-8' 'Cache-Control' = 'no-store' 'X-Content-Type-Options' = noSniff 'Referrer-Policy' = 'no-referrer' 'X-Frame-Options' = 'DENY' 'Content-Security-Policy' = pagePolicy }// the headers a framework-rendered page (srv.page: the code page, the 404 page) gets from usstatic hardenPage = (res) => {res.headers['X-Content-Type-Options'] = noSniffres.headers['Referrer-Policy'] = 'same-origin'res.headers['X-Frame-Options'] = 'DENY'res.headers['Content-Security-Policy'] = "frame-ancestors 'none'"return res}// a page that MAY be framed — by the origins given (an app's registered origins) and nobody else (no X-Frame-Options: it cannot name// more than one origin, and browsers that read frame-ancestors ignore it anyway)static framedBy = (res, origins) => {res.headers['X-Content-Type-Options'] = noSniffres.headers['Referrer-Policy'] = 'same-origin'res.headers['Cache-Control'] = 'no-store'res.headers['Content-Security-Policy'] = 'frame-ancestors ' + origins.join(' ')return res}static reply = (status, value) => { return new Response(JSON.stringify(value), { status = status headers = jsonHeaders }) }static fail = (status, message) => { return reply(status, { error = message }) }static redirect = (url) => { return new Response('', { status = 302 headers = { 'Location' = url 'Cache-Control' = 'no-store' 'X-Content-Type-Options' = noSniff 'Referrer-Policy' = 'no-referrer' 'X-Frame-Options' = 'DENY' } }) }// THE STRICT BODY: `spec` maps each allowed field to { type ('String' | 'Number' |// 'Boolean' | 'List'), required }. Answers { error } or { body }.static strictBody = (req, spec) => {raw = req.bodyif (raw == null || raw.trim() == '') { return { error = 'a JSON object body is required' } }at = jsonErrorAt(raw)if (at >= 0) { return { error = 'the body is not valid JSON (at character ' + at + ')' } }t = raw.trim()if (t[0] != '{') { return { error = 'the body must be a JSON object' } }b = JSON.parse(raw)for (k of b.keys()) {if (spec[k] == null) { return { error = 'unknown field: ' + k } }}for (k of spec.keys()) {let f = spec[k]let v = b[k]if (v == null) {if (f.required) { return { error = 'missing field: ' + k } }} else if (f.type == 'List') {if (hlTypeName(v) != 'Hybrid' || v.length == null) { return { error = 'field ' + k + ' must be a list' } }} else if (hlTypeName(v) != f.type) {return { error = 'field ' + k + ' must be a ' + f.type.toLowerCase() }}}return { body = b }}// ---- the HTML error page of the login button (never a redirect) ------------------------static errorPage = (route, req, &srv, status, title, message) => {m = { route = { pattern = route.route.pattern component = ErrorPage } kind = 'component' params = { title = title message = message } path = req.path }res = srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers))res.status = statusfor (k of htmlHeaders.keys()) { res.headers[k] = htmlHeaders[k] }return res}// the answer of a call that asked for profile fields (ident#11): the identity's short id, then one key per asked fieldstatic withProfile = (identity, profile) => {out = { identity = identity }for (k of profile.keys()) { out[k] = profile[k] }return out}// ---- THE APP'S CALLS (key + secret, strict JSON body) ------------------------------------------static field = (n, t) => { return { type = t required = n } }// POST only, the strict body `spec`, then the app of its key + secret: answers { res } (the refusal) or { app, body }static inviteCaller = (req, spec) => {if (req.method != 'POST') { return { res = fail(405, 'POST only') } }b = strictBody(req, spec)if (b.error != null) { return { res = fail(400, b.error) } }a = appOfSecret(b.body.key, b.body.secret)if (a == null) { return { res = fail(401, 'unknown API key or wrong secret') } }return { app = a body = b.body }}// where an invite link points: IDENT_PUBLIC_URL, else the request's own hoststatic baseOf = (req) => {if (publicUrl != null) { return publicUrl }proto = req.headers['x-forwarded-proto'] != null ? req.headers['x-forwarded-proto'] : 'http'return proto + '://' + req.headers['host']}// a login request id is 32 hex (lib/apps.hl openRequest)static hexId = (v) => {if (v.length != 32) { return false }let i = 0while (i < v.length) {if (!'0123456789abcdef'.includes(v[i])) { return false }i = i + 1}return true}// ---- THE SELECTOR's CORS answers (lib/selector.hl) ----------------------------------------------static jsonType = 'application/json; charset=utf-8'// the refusal: no CORS headers → the browser gives the page nothingstatic refuse = (status, message) => {return new Response(JSON.stringify({ error = message }), { status = status headers = { 'Content-Type' = jsonType 'Cache-Control' = 'no-store' 'Vary' = 'Origin' 'X-Content-Type-Options' = noSniff 'Referrer-Policy' = 'no-referrer' } })}static corsHeaders = (origin) => {return { 'Content-Type' = jsonType 'Cache-Control' = 'no-store' 'Vary' = 'Origin' 'X-Content-Type-Options' = noSniff 'Referrer-Policy' = 'no-referrer' 'Access-Control-Allow-Origin' = origin 'Access-Control-Allow-Credentials' = 'true' }}static answer = (origin, status, value) => {return new Response(JSON.stringify(value), { status = status headers = corsHeaders(origin) })}// WHO ASKS: answers { app (record), origin } or { status, error }static caller = (req) => {let origin = req.headers['origin']if (origin == null || origin == '') { return { status = 403 error = 'the selector answers browsers only (no Origin header)' } }q = req.query != null ? req.query : {}a = appByKey(q.key)if (a == null) { return { status = 403 error = 'no app has this API key' } }if (!originAllowed(a, origin)) { return { status = 403 error = 'this origin is not registered for the app' } }return { app = a origin = origin }}
Branches
Latest commits
- e0f0ddaaident#34: inbox: the Mark read/unread button is styled as the button of its note-foot, the icon is found as the row's img (no toggle/icon classes)mre
- 16b49756ident#34: unused row classes (choice, usedrow, kind, shortid) droppedmre
- f9d6fb38ident#34: apps and identity rows: the Edit/New secret/Delete buttons carry name=..., the API key is found by its element; unused row classes (app, identity, shortid) droppedmre
- b323265aMerge branch 'f5-styles' into mainIdent
- 9ced53c3|||PR ident#33 ident#35 every component's styles live in its own Style block; styles.hl keeps the page-wide rest; the account bar is phone first (min-width: 60rem block); the avatar preview is hidden with the hidden attribute (ident#34 in part)mre
- f28333e4ident#33 ident#35: styles.hl keeps only the accent, the page column and the shared patterns; the account bar is written phone first (base rule + one min-width: 60rem block) instead of a max-width overridemre
- 5b4541fcident#33: the selector sign-in frame's rules move into embed.hl's Stylemre
- 00235f21ident#33: the per-app notification switches move into appsettings.hl's Stylemre
- 2249945cident#33: the inbox and connection list rules move into inbox.hl's Stylemre
- f2d9f79fident#33: the apps list and the secret box move into apps.hl's Stylemre
- 8370b748ident#33: the app request box moves into home.hl's Stylemre
- 40bf3b97ident#33: the 404 page's home link rule moves into notfound.hlmre
- 40627a89ident#33: the time zone section's spacing moves into timezone.hlmre
- d389db08ident#33: the identity page's rules and the Notif. chip move into identity.hl's Stylemre
- ddda0b5bident#33: the identity row's parts move into identitylist.hl's Stylemre
- 47e516afident#33 ident#34: the identity form's avatar rules move into identityform.hl; the preview and Remove button are hidden with the hidden attribute instead of built class strings (avatarPreviewClass, avatarRemoveClass gone)mre
- 5cb5cf0eident#33: the code field's look moves into codestep.hl's Stylemre
- f421cd60ident#33: the shell's own rules (user menu address, offline note, network probe) move into main.hl's Stylemre
- c512fb96Merge branch 'f4-homesplit' into mainIdent
- 07d1717c|||PR ident#40 home.hl is split into components, one per area: email step, identity form, identity list, app identity choice, time zone; each moves its faces with it, the email step is shared with embed.hl (#40.3, rest of #40.2)mre