gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitd6da2d02d6da2d02tests: delivery and migration gate ports from env (DELIVERY_GATE_PORT, DELIVERY_GATE_CHROME, MIGRATION_GATE_CHROME) — hard-coded 8700-8719 collided with a worker during deploymred6da2d02/lib/api.hl

12.8 KB

  1. // lib/api.hl — THE FUNCTION ROUTES (project.hl `routes`): the login button's GET /login, the app's server calls
  2. // (exchange, migrate-ids, kinds, notify, invites), the selector's two CORS calls, the code request, the invite
  3. // link, the code page, the offline probe. THIN WRAPPERS: check the method, the body (lib/api-helpers.hl strictBody)
  4. // and the app's key + secret, call the topic function, answer. Shapes: README "How apps use ident",
  5. // "How apps send notifications", "Invites". Statics only.
  6. import { Response } from 'hl:http1'
  7. import { reply, fail, redirect, strictBody, errorPage, field, inviteCaller, baseOf, hexId, refuse, corsHeaders, answer, caller } from './api-helpers.hl'
  8. import { openRequest, exchange, migrateIds, appOfSecret, openInvite } from './apps.hl'
  9. import { selectorList, codeOfPick } from './selector.hl'
  10. import { createInvite, listInvites, revokeInvite, ownInvite, inviteRow } from './invites.hl'
  11. import { registerKinds, sendNotification } from './notify.hl'
  12. import { startLogin, pendingOf } from './login.hl'
  13. import { accountOfSession } from './accounts.hl'
  14. import { sendCode, sendInvite } from './mail.hl'
  15. import { deliverUrgent } from './delivery.hl'
  16. // ---- THE LOGIN BUTTON: GET /login?key=<api key>&return=<url> ---------------------------
  17. // An unknown key or a return URL outside the app's origins → an error page, NEVER a
  18. // redirect. Otherwise the request is parked under a random id (a page component cannot
  19. // read the query, hybriel #18) and the browser goes to /signin/<rid>.
  20. static appLogin = (route, req) => {
  21. if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }
  22. q = req.query != null ? req.query : {}
  23. r = openRequest(q.key, q['return'])
  24. if (r.error != null) { return errorPage(400, 'Bad login request', r.error) }
  25. return redirect('/signin/' + r.rid)
  26. }
  27. // ---- POST /api/migrate-ids { key, secret, finish? } → { ids: { <old per-app id>: <short id> } } (ident#23)
  28. // the APP'S SERVER moves its stored users to the identities' short ids in one step; with
  29. // `finish: true` the old per-app ids are dropped afterwards (they are gone for good).
  30. static apiMigrateIds = (route, req) => {
  31. if (req.method != 'POST') { return fail(405, 'POST only') }
  32. b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } finish = { type = 'Boolean' required = false } })
  33. if (b.error != null) { return fail(400, b.error) }
  34. a = appOfSecret(b.body.key.trim(), b.body.secret.trim())
  35. if (a == null) { return fail(401, 'unknown API key or wrong secret') }
  36. return reply(200, migrateIds(a, b.body.finish == true))
  37. }
  38. // ---- POST /api/exchange { key, secret, code } → { identity } ---------------------------
  39. // the APP'S SERVER trades the ident_code from its return URL for the app-specific
  40. // identity's short id. Nothing else is handed out (CONCEPT.md "More fields").
  41. static apiExchange = (route, req) => {
  42. if (req.method != 'POST') { return fail(405, 'POST only') }
  43. b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } code = { type = 'String' required = true } })
  44. if (b.error != null) { return fail(400, b.error) }
  45. for (k of ['key' 'secret' 'code']) {
  46. if (b.body[k].trim() == '') { return fail(400, 'missing field: ' + k) }
  47. }
  48. r = exchange(b.body.key.trim(), b.body.secret.trim(), b.body.code.trim())
  49. if (r.error != null) { return fail(r.status, r.error) }
  50. return reply(200, { identity = r.identity })
  51. }
  52. // ---- THE SELECTOR's two calls (lib/selector.hl): the ident user is the cookie's ---------
  53. // (hl:web hands a function route the cookie's session as req.session, hybriel#11)
  54. static apiSelectorIdentities = (route, req) => { return selectorIdentities(req, req.session) }
  55. static apiSelectorChoose = (route, req) => { return selectorChoose(req, req.session) }
  56. // GET /api/selector/identities?key=
  57. static selectorIdentities = (req, &session) => {
  58. c = caller(req)
  59. if (c.error != null) { return refuse(c.status, c.error) }
  60. if (req.method != 'GET') { return answer(c.origin, 405, { error = 'GET only' }) }
  61. me = accountOfSession(session)
  62. if (me == null) { return answer(c.origin, 200, { signedIn = false identities = [] }) }
  63. return answer(c.origin, 200, { signedIn = true identities = selectorList(c.app, me.id) })
  64. }
  65. // POST /api/selector/choose?key= { identity } (+ its OPTIONS preflight)
  66. static selectorChoose = (req, &session) => {
  67. c = caller(req)
  68. if (c.error != null) { return refuse(c.status, c.error) }
  69. if (req.method == 'OPTIONS') {
  70. h = corsHeaders(c.origin)
  71. h['Access-Control-Allow-Methods'] = 'POST'
  72. h['Access-Control-Allow-Headers'] = 'Content-Type'
  73. h['Access-Control-Max-Age'] = '600'
  74. return new Response('', { status = 204 headers = h })
  75. }
  76. if (req.method != 'POST') { return answer(c.origin, 405, { error = 'POST only' }) }
  77. b = strictBody(req, { identity = { type = 'String' required = true } })
  78. if (b.error != null) { return answer(c.origin, 400, { error = b.error }) }
  79. me = accountOfSession(session)
  80. if (me == null) { return answer(c.origin, 401, { error = 'you are not signed in to ident' }) }
  81. let code = codeOfPick(c.app, me.id, b.body.identity)
  82. if (code != null) { return answer(c.origin, 200, { code = code }) }
  83. return answer(c.origin, 400, { error = 'no such identity' })
  84. }
  85. // ---- POST /api/code { email } → { email }: THE ONE WAY TO GET A LOGIN CODE MAILED --------
  86. // (the sign-in form of `/` and `/signin/<rid>` fetches it). Limits: per address (3 / 10 min)
  87. // and per client IP (lib/login-helpers.hl ipBucket: 10 / 10 min, 30 / 24 h) → 429 with the reason.
  88. // THE CLIENT IP is the X-Client-IP header and nothing else: nginx on Byrodin sets it and
  89. // overwrites any the client sent (/CONTAINERS/web/nginx/conf.d/cloudflare-client-ip.conf).
  90. // CF-Connecting-IP / X-Forwarded-For / X-Real-IP are NEVER read (a client could forge them).
  91. // Without the header (dev, no nginx) every request shares ONE bucket ('direct'):
  92. // (hl:web's req.remoteAddress, hybriel#25, would be nginx's address behind the proxy.)
  93. // A function route, not a face: a face gets no request (no headers), and the per-IP limit needs the IP.
  94. static apiCode = (route, req) => {
  95. if (req.method != 'POST') { return fail(405, 'POST only') }
  96. b = strictBody(req, { email = { type = 'String' required = true } })
  97. if (b.error != null) { return fail(400, b.error) }
  98. r = startLogin(b.body.email, req.headers['x-client-ip'])
  99. if (r.error != null) { return fail(r.limited == true ? 429 : 400, r.error) }
  100. sendCode(r.email, r.code)
  101. return reply(200, { email = r.email })
  102. }
  103. // ---- NOTIFICATIONS (piece 4, lib/notify.hl; README "How apps send notifications") -------
  104. // The APP'S SERVER, with its key + secret. Strict JSON bodies. ident stores the notification and its channels, the
  105. // user reads it in the inbox (/inbox); delivery (the daily mail, urgent at once): lib/delivery.hl (piece 5, ident#7).
  106. // POST /api/kinds { key, secret, kinds: [{ name, push, email }] } → { kinds }
  107. // POST /api/notify { key, secret, identity, name, text, icon?, link?, urgent? } → { id }
  108. static apiKinds = (route, req) => {
  109. if (req.method != 'POST') { return fail(405, 'POST only') }
  110. b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } kinds = { type = 'List' required = true } })
  111. if (b.error != null) { return fail(400, b.error) }
  112. a = appOfSecret(b.body.key, b.body.secret)
  113. if (a == null) { return fail(401, 'unknown API key or wrong secret') }
  114. r = registerKinds(a, b.body.kinds)
  115. if (r.error != null) { return fail(r.status, r.error) }
  116. return reply(200, { kinds = r.kinds })
  117. }
  118. static apiNotify = (route, req) => {
  119. if (req.method != 'POST') { return fail(405, 'POST only') }
  120. b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } identity = { type = 'String' required = true } name = { type = 'String' required = true } text = { type = 'String' required = true } icon = { type = 'String' required = false } link = { type = 'String' required = false } urgent = { type = 'Boolean' required = false } })
  121. if (b.error != null) { return fail(400, b.error) }
  122. r = sendNotification(b.body)
  123. if (r.error != null) { return fail(r.status, r.error) }
  124. // an URGENT one goes out at once (lib/delivery.hl); a normal one waits for the daily mail
  125. deliverUrgent(r.id)
  126. return reply(200, { id = r.id })
  127. }
  128. // ---- INVITES (ident#22, lib/invites.hl; README "Invites") ----------------------------------------
  129. // The APP'S SERVER, key + secret, strict JSON bodies:
  130. // POST /api/invites { key, secret, project, role, return, uses?, days?, email? } → { id, url, state, … }
  131. // POST /api/invites/list { key, secret, project? } → { invites: [...] }
  132. // POST /api/invites/get { key, secret, id } → { invite }
  133. // POST /api/invites/revoke { key, secret, id } → { invite }
  134. // and the PERSON: GET /invite/<token> → the login flow (or an error page: used, expired, withdrawn).
  135. static apiInvites = (route, req) => {
  136. c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') project = field(true, 'String') role = field(true, 'String') 'return' = field(true, 'String') uses = field(false, 'Number') days = field(false, 'Number') email = field(false, 'String') })
  137. if (c.res != null) { return c.res }
  138. r = createInvite(c.app, c.body, baseOf(req))
  139. if (r.error != null) { return fail(r.status, r.error) }
  140. let mailed = false
  141. if (r.mail != null) {
  142. sendInvite(r.mail.to, r.url, c.app.name, r.invite.project, r.invite.role, r.mail.days)
  143. mailed = true
  144. }
  145. return reply(200, { id = r.invite.id url = r.url state = r.invite.state project = r.invite.project role = r.invite.role uses = r.invite.uses expires = r.invite.expires mailed = mailed })
  146. }
  147. static apiInvitesList = (route, req) => {
  148. c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') project = field(false, 'String') })
  149. if (c.res != null) { return c.res }
  150. return reply(200, { invites = listInvites(c.app, c.body.project) })
  151. }
  152. static apiInvitesGet = (route, req) => {
  153. c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') id = field(true, 'String') })
  154. if (c.res != null) { return c.res }
  155. r = ownInvite(c.app, c.body.id)
  156. if (r == null) { return fail(404, 'no such invite') }
  157. return reply(200, { invite = inviteRow(r) })
  158. }
  159. static apiInvitesRevoke = (route, req) => {
  160. c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') id = field(true, 'String') })
  161. if (c.res != null) { return c.res }
  162. r = revokeInvite(c.app, c.body.id)
  163. if (r.error != null) { return fail(r.status, r.error) }
  164. return reply(200, { invite = r.invite })
  165. }
  166. static inviteLink = (route, req) => {
  167. if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }
  168. r = openInvite(route.params.token)
  169. if (r.error != null) { return errorPage(r.status, r.title, r.error) }
  170. return redirect('/signin/' + r.rid)
  171. }
  172. // ---- THE CODE PAGE: GET /code and /signin/<rid>/code (ident#20, mission 008 (old 032)) ------------
  173. // Creator: "just make a /code where it checks a pending code". The page asks the SESSION
  174. // (lib/login.hl pendingOf) whether a code it asked for is still waiting — unused, unexpired,
  175. // not killed by wrong tries. Yes → Home renders its code step with that address (a reload
  176. // shows it again). No, or already signed in → 302 back to the email form (`/` or
  177. // `/signin/<rid>`), so a stale /code is never a dead end.
  178. // A FUNCTION route because a component route cannot answer a redirect: it takes the
  179. // cookie's session (req.session, hybriel#11) and renders `pageComponent` (Home) through the framework's own page
  180. // render (`srv.page`, the same call a component route makes) with `step = 'code'`; project.hl hands in
  181. // its server (by reference) and Home.
  182. // Its signature since hybriel #105 (mission 048): page(match, session, host, headers) — the
  183. // old page(match, req, session) still compiles but renders with req as the session (empty page).
  184. static codePage = (route, req, &srv, pageComponent) => {
  185. let rid = route.params.rid
  186. // a rid is 32 hex (lib/apps.hl); anything else goes to `/` (it lands in a Location header)
  187. if (rid != null && !hexId(rid)) { return redirect('/') }
  188. home = rid != null ? '/signin/' + rid : '/'
  189. if (req.method != 'GET') { return redirect(home) }
  190. s = req.session
  191. if (s == null || accountOfSession(s) != null || pendingOf(s) == null) { return redirect(home) }
  192. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { rid = rid step = 'code' pending = pendingOf(s) } path = route.path }
  193. return srv.page(m, s, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers))
  194. }
  195. static notFoundApi = (route, req) => { return fail(404, 'no such endpoint') }
  196. // GET /api/online → 204: the shell's network probe (components/main.hl). Never cached, carries nothing.
  197. static apiOnline = (route, req) => { return new Response('', { status = 204 headers = { 'Cache-Control' = 'no-store' } }) }

Branches

Latest commits

  • d6da2d02tests: delivery and migration gate ports from env (DELIVERY_GATE_PORT, DELIVERY_GATE_CHROME, MIGRATION_GATE_CHROME) — hard-coded 8700-8719 collided with a worker during deploymre
  • 7276a008ident mission 013: re-vendor Hybriel master f9614007 (#200, #202 mpackdb copy fix); gates and e2e rerunmre
  • e13e30c3ident mission 013: report, mission, repro, LOGmre
  • eff734f3ident mission 013: in-place sign-out also closes the code step (no leftover code form); checksmre
  • b7a61546ident mission 013: e2e — in-place main-menu mark kept as a known gapmre
  • 59b43d81ident mission 013: sign out everywhere keeps this browser's own (signed-out) session so the page goes on in placemre
  • 716e14ffident mission 013: browser gate — Bob signs out everywhere (no second code request)mre
  • 5885f1c9ident mission 013 step 2: stopgap reload removed (in-place sign-in/out reach the shell via emit, notices back, route-marked main menu), gates updatedmre
  • 734ac0a9ident mission 013 step 1: re-vendor Hybriel ce6f2e0a (plugins whole; bin/ is git-ignored)mre
  • b37875ccident mission 012 part 3: real-Chrome fixes (brand 44 px, identity form width), e2e walk, report, logmre
  • f989c2ebident mission 012: stopgap reload after in-place sign-in/sign-out (until hybriel#193), gates wait for cold start, welcome end reloadsmre
  • 443291d4ident mission 012: /start on its own shell (no account), browser gate 152/0, reportmre
  • 021dd0fcident mission 012: browser gate waits cold start (IDENT_COLD_MS), header selectors, e2e checks; shell events from a page do not reach it (probe), current not marked, account-bar link 44 pxmre
  • 97f77b07ident mission 012 (WIP): onto the layouts theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ContentFirst, styles cut, check-theme gatemre
  • 8e4f435bpaths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • fa288f63ident mission 011: report wording (Intl zone names)mre
  • 961fae01ident mission 011: report, LOG, STATUSmre
  • 65348039ident#7: delivery gate — console check split at the gate's own server restart (49 checks)mre
  • dfa7b783ident#7: README (Delivery, env, gate, files, data), deploy.sh runs tests/delivery.mjsmre
  • ab6331f4ident#7: tests/delivery.mjs — fake clock gate: Vienna/New York/Tokyo/UTC 17:00, urgent, mail off, restart, DST days, zone changemre