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
- e24b59a6ident#40.3: the time zone is one component (components/timezone.hl); its face changeTimeZone moves with itmre
- 8cbc5717ident#40.3: the email step is one component (components/emailstep.hl) placed by home.hl and embed.hlmre
- 6fad3bd2Merge branch 'f3-codestep' into mainIdent
- 51e387f2|||PR ident#40 the code step is one component (components/codestep.hl) placed by home.hl and embed.hl; its verify face, setCode, browserZone and verify call exist once (#40.2)mre
- c28bddeeMerge branch 'f2-shell' into mainIdent
- c3a40ff6|||PR ident#40 one shell for the app and /start (account part off on /start, #40.1); startshell.hl removed; unused signOut faces gone (#40.4)mre
- 060f3870ident#40.4: use the shell sign-out faces in regression gatesmre
- 9b94aa6aMerge branch 'f1b-cleanup' into mainIdent
- edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
- 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
- c7eef14aMerge branch 'nv1-navigate' into mainIdent
- 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
- 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre
- 23971fb7ident#49: media queries in the language's @media formmre
- 73f4f97dident: re-vendor to hybriel day38b (mpackdb store-open fix)mre
- aa056c03ident: a startup error prints its message before exit 1 (hybriel#247)mre
- ee37a861ident#G48: gitoria's registration gets the wildcard origin of its repo addresses at load (gate tests/gitoria-origin.mjs)mre
- dc6d486fident#27: the docs gate expects the new Access entry in the main menumre
- d277633cident#27: README: identity access and the introspect endpointmre
- e999b0d3ident#27: the Access tab — one key per identity for all its apps: give access in three steps, the overview matrix, a cell's sheet (since, last use, level, rotate, revoke), the app's check POST /api/introspect, agent identities hidden from the login picker, an inbox icon in the header's icon style (gate: tests/access.mjs)mre