gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit716860b0716860b0ident#28: gates follow Hybriel ac1ed9da (lazy sessions, meta attribute order, JSON key order, default X-Frame-Options switched off for the embed page)mre716860b0/lib/apps.hl

15.4 KB

  1. // lib/apps.hl — APPS AND THE LOGIN BUTTON (piece 2 of 6, ticket #25; CONCEPT.md "Apps",
  2. // "One id per app", "Flow 1: login button"; the invite's login flow, ident#22). Statics only, the server realm.
  3. // Every write to the apps, connections, requests and grants tables is here. The checks (app form, origins,
  4. // return URL), keys and the row a page shows: lib/apps-helpers.hl.
  5. //
  6. // appsTable pk @id index @owner, !apiKey
  7. // { owner (account @id), name, origins ('a b c': the origins it runs
  8. // on, space separated), apiKey, secretHash = sha256(secret), created, updated }
  9. // connectionsTable pk @id index !pair, @app
  10. // { pair = '<app @id>:<identity @id>', app, identity, created } — `created` is
  11. // when the identity registered in that app (the per-app page).
  12. // What an app holds is the identity's ONE SHORT ID (ident#23, lib/identities.hl
  13. // `shortId`), the same in every app. Rows made before ident#23 still carry
  14. // `appIdentity` (the old per-app id, 32 hex) until the app has migrated:
  15. // POST /api/migrate-ids answers old → short and, with finish, drops them.
  16. // requestsTable pk @id index !rid a login button press waiting for the choice:
  17. // { rid, app (app @id), returnUrl, expires, invite (invite @id, ident#22; absent for a plain login) }
  18. // grantsTable pk @id index !hash a one-time code on its way back to the app:
  19. // { hash = sha256(code), app, identity, expires }
  20. //
  21. // Any signed-in account registers apps. An app has a PUBLIC API key (`pk_…`, it may sit
  22. // in a page) and a SECRET (`sk_…`, the app's server only). The secret is shown ONCE, when
  23. // it is made (register / new secret); only its sha256 is stored.
  24. // Public app ids are the records' mpackdb UUIDs (`@id`), as for accounts and identities;
  25. // the files live in storage/mpackdb/ (lib/util.hl `dir`).
  26. import { MPackDB } from 'hl:mpackdb'
  27. import { now } from 'hl:time'
  28. import { randomBytes, sha256 } from 'hl:crypto'
  29. import { dir, envNumber, countOf, first, merged, isId, oldestFirst } from './util.hl'
  30. import { checkAppInput, newKey, newSecret, appRowOf, checkReturn } from './apps-helpers.hl'
  31. import { ownIdentity, identitiesTable, identityByShortId } from './identities.hl'
  32. import { checkProfileFields, profileValues } from './identities-helpers.hl'
  33. import { dropInvitesOf, openableInvite, inviteById, acceptInvite } from './invites.hl'
  34. static appsTable = new MPackDB(file = dir + '/apps.db', primaryKey = '@id', indexes = ['@owner' '!apiKey'])
  35. static connectionsTable = new MPackDB(file = dir + '/connections.db', primaryKey = '@id', indexes = ['!pair' '@app'])
  36. static requestsTable = new MPackDB(file = dir + '/requests.db', primaryKey = '@id', indexes = ['!rid'])
  37. static grantsTable = new MPackDB(file = dir + '/grants.db', primaryKey = '@id', indexes = ['!hash'])
  38. static grantTtl = envNumber('IDENT_GRANT_TTL_MS', 60000) // a one-time code: 60 s
  39. static requestTtl = 1800000 // a login button press: 30 min
  40. // an account's apps (mission SI): each app may mail invitations (lib/invites.hl mailLimit) and any address can make an account, so the
  41. // number of apps bounds what one account can make ident mail. The gate sets a lower one.
  42. static maxApps = envNumber('IDENT_MAX_APPS', 20)
  43. // ---- apps -----------------------------------------------------------------------------
  44. // the account's apps, oldest first (stored `created`, never key order)
  45. static appRows = (accountId) => {
  46. out = []
  47. if (!isId(accountId)) { return out }
  48. for (r of oldestFirst(appsTable.find('owner', accountId))) { out.push(appRowOf(r)) }
  49. return out
  50. }
  51. // the app record `id` (public) if the account owns it, else null
  52. static ownApp = (accountId, id) => {
  53. if (!isId(id)) { return null }
  54. r = appsTable.fetch(id)
  55. if (r == null || r.owner != accountId) { return null }
  56. return r
  57. }
  58. static appByKey = (key) => {
  59. if (key == null || hlTypeName(key) != 'String' || key == '') { return null }
  60. return first(appsTable.find('apiKey', key))
  61. }
  62. // THE APP'S SERVER, key + secret: answers the app record or null (unknown key or wrong secret: one answer, 401)
  63. static appOfSecret = (key, secret) => {
  64. a = appByKey(key)
  65. if (a == null || hlTypeName(secret) != 'String' || sha256(secret) != a.secretHash) { return null }
  66. return a
  67. }
  68. // answers { error, field } or { app (row), secret } — the secret leaves ident only here
  69. static createApp = (accountId, input) => {
  70. c = checkAppInput(input)
  71. if (c.error != null) { return c }
  72. if (countOf(appsTable.find('owner', accountId)) >= maxApps) { return { error = 'an account can have at most ' + maxApps + ' apps' field = '' } }
  73. let secret = newSecret()
  74. id = appsTable.put({ owner = accountId name = c.name origins = c.origins.join(' ') apiKey = newKey() secretHash = sha256(secret) created = now() updated = now() })
  75. return { app = appRowOf(appsTable.fetch(id)) secret = secret }
  76. }
  77. static updateApp = (accountId, id, input) => {
  78. r = ownApp(accountId, id)
  79. if (r == null) { return { error = 'no such app' field = 'id' } }
  80. c = checkAppInput(input)
  81. if (c.error != null) { return c }
  82. appsTable.update(r.id, merged(r, { name = c.name origins = c.origins.join(' ') updated = now() }))
  83. return { app = appRowOf(appsTable.fetch(r.id)) }
  84. }
  85. // a NEW SECRET: the old one stops working at once; the API key stays
  86. static regenerateSecret = (accountId, id) => {
  87. r = ownApp(accountId, id)
  88. if (r == null) { return { error = 'no such app' } }
  89. let secret = newSecret()
  90. appsTable.update(r.id, merged(r, { secretHash = sha256(secret) updated = now() }))
  91. return { app = appRowOf(appsTable.fetch(r.id)) secret = secret }
  92. }
  93. // DELETING AN APP removes its connections (the per-app ids) and its invites with it; a pending login
  94. // request or code for it dies because its app is gone
  95. static deleteApp = (accountId, id) => {
  96. r = ownApp(accountId, id)
  97. if (r == null) { return { error = 'no such app' } }
  98. conns = connectionsTable.find('app', id)
  99. if (countOf(conns) > 0) { for (c of conns) { connectionsTable.delete(c.id) } }
  100. dropInvitesOf(id)
  101. appsTable.delete(r.id)
  102. return { deleted = id }
  103. }
  104. // ---- the login button ---------------------------------------------------------------
  105. // the login button's GET /login?key=&return= : answers { error } or { rid }
  106. static openRequest = (key, returnUrl) => {
  107. a = appByKey(key)
  108. if (a == null) { return { error = key == null || key == '' ? 'the key parameter (the app’s API key) is missing' : 'no app has this API key' } }
  109. r = checkReturn(returnUrl, a)
  110. if (r.error != null) { return r }
  111. let rid = randomBytes(16)
  112. requestsTable.put({ rid = rid app = a.id returnUrl = returnUrl expires = now() + requestTtl })
  113. return { rid = rid }
  114. }
  115. // { rid, app (row), origin, returnUrl } or null (unknown, expired, or its app is gone)
  116. static requestOf = (rid) => {
  117. if (rid == null || hlTypeName(rid) != 'String' || rid == '') { return null }
  118. r = first(requestsTable.find('rid', rid))
  119. if (r == null) { return null }
  120. if (r.expires < now()) {
  121. requestsTable.delete(r.id)
  122. return null
  123. }
  124. a = isId(r.app) ? appsTable.fetch(r.app) : null
  125. if (a == null) { return null }
  126. c = checkReturn(r.returnUrl, a)
  127. if (c.error != null) { return null } // the origin was removed from the app since
  128. return { rid = r.rid app = appRowOf(a) origin = c.origin returnUrl = r.returnUrl invite = r.invite == null ? '' : r.invite }
  129. }
  130. // The identity's connection to the app, made on the first login
  131. static connectionOf = (appId, identityId) => {
  132. let pair = appId + ':' + identityId
  133. c = first(connectionsTable.find('pair', pair))
  134. if (c != null) { return c }
  135. id = connectionsTable.put({ pair = pair app = appId identity = identityId created = now() })
  136. return connectionsTable.fetch(id)
  137. }
  138. // "SIGN OUT" OF AN APP (ticket #2): forgets this identity's connection to it (its
  139. // notification settings for the app). The identity's short id does not change: a later
  140. // login makes a fresh connection and the app gets the same id. Notifications already sent
  141. // through the old connection stay (as for a deleted app).
  142. static disconnectConnection = (accountId, id) => {
  143. if (!isId(id)) { return { error = 'no such app connection' } }
  144. c = connectionsTable.fetch(id)
  145. if (c == null) { return { error = 'no such app connection' } }
  146. ident = ownIdentity(accountId, c.identity)
  147. if (ident == null) { return { error = 'no such app connection' } }
  148. connectionsTable.delete(c.id)
  149. return { disconnected = id }
  150. }
  151. // A ONE-TIME CODE for app `appId` and identity `identityId` (public ids): 48 hex, single
  152. // use, grantTtl (60 s), this app only. The login button AND the selector (lib/selector.hl)
  153. // hand out these codes; the app's server trades one with `exchange` below.
  154. static issueCode = (appId, identityId) => {
  155. connectionOf(appId, identityId)
  156. code = randomBytes(24)
  157. grantsTable.put({ hash = sha256(code) app = appId identity = identityId expires = now() + grantTtl })
  158. return code
  159. }
  160. // THE CHOICE: the account picks one of its identities for the request. Answers { error }
  161. // or { url } — the app's return URL with a fresh one-time `ident_code`.
  162. static grantLogin = (accountId, rid, identityId) => {
  163. rq = requestOf(rid)
  164. if (rq == null) { return { error = 'this login request is unknown or expired — go back to the app and start again' } }
  165. ident = ownIdentity(accountId, identityId)
  166. if (ident == null) { return { error = 'no such identity' } }
  167. code = issueCode(rq.app.id, identityId)
  168. r = first(requestsTable.find('rid', rid))
  169. if (r != null) { requestsTable.delete(r.id) }
  170. sep = rq.returnUrl.includes('?') ? '&' : '?'
  171. return { url = rq.returnUrl + sep + 'ident_code=' + code }
  172. }
  173. // THE EXCHANGE (the app's server): answers { status, error } or { identity }. The app
  174. // authenticates with key + secret (401); a code works once, for its own app, for 60 s (400).
  175. // A code shown to the wrong app is spent: it has leaked.
  176. // ident#11: with `fields` (a list of profile field names the app wants) the answer also carries `profile`, one key per field
  177. // (null when the person has not filled it in); a bad field name is a 400 and the code is NOT spent. Without `fields` nothing changes.
  178. static exchange = (key, secret, code, fields) => {
  179. a = appByKey(key)
  180. if (a == null || sha256(secret) != a.secretHash) { return { status = 401 error = 'unknown API key or wrong secret' } }
  181. let asked = []
  182. if (fields != null) {
  183. pf = checkProfileFields(fields)
  184. if (pf.error != null) { return { status = 400 error = pf.error } }
  185. asked = pf.fields
  186. }
  187. g = first(grantsTable.find('hash', sha256(code)))
  188. if (g == null) { return { status = 400 error = 'unknown or already used code' } }
  189. grantsTable.delete(g.id)
  190. if (g.app != a.id) { return { status = 400 error = 'this code was not issued to this app' } }
  191. if (g.expires < now()) { return { status = 400 error = 'the code expired' } }
  192. c = first(connectionsTable.find('pair', a.id + ':' + g.identity))
  193. ident = isId(g.identity) ? identitiesTable.fetch(g.identity) : null
  194. if (c == null || ident == null) { return { status = 400 error = 'the identity is no longer connected to this app' } }
  195. // ident#26: the "Used in" list's last use — one write per login, none per request
  196. connectionsTable.update(c.id, merged(c, { lastLogin = now() }))
  197. if (fields != null) { return { identity = ident.shortId profile = profileValues(ident, asked) } }
  198. return { identity = ident.shortId }
  199. }
  200. // THE PROFILE, asked later (ident#11): the app's server (key + secret, checked by the route) asks again for an identity (short id)
  201. // that signed in to this app before. Answers { status, error } or { identity, profile }. An identity that does not exist and one that
  202. // never signed in to this app get the same answer, so an app cannot probe for identities.
  203. static profileOf = (a, given, fields) => {
  204. pf = checkProfileFields(fields)
  205. if (pf.error != null) { return { status = 400 error = pf.error } }
  206. ident = identityByShortId(given)
  207. c = ident == null ? null : first(connectionsTable.find('pair', a.id + ':' + ident.id))
  208. if (c == null) { return { status = 404 error = 'no such identity in this app' } }
  209. return { identity = ident.shortId profile = profileValues(ident, pf.fields) }
  210. }
  211. // ---- AN INVITE'S LOGIN (ident#22; the invite records: lib/invites.hl) -------------------------------
  212. // GET /invite/<token>: answers { status, title, error } (an error page) or { rid } — a login
  213. // request of the app that carries the invite, so the login flow does the rest.
  214. static openInvite = (token) => {
  215. o = openableInvite(token)
  216. if (o.error != null) { return o }
  217. rec = o.invite
  218. let rid = randomBytes(16)
  219. requestsTable.put({ rid = rid app = rec.app returnUrl = rec.returnUrl invite = rec.id expires = now() + requestTtl })
  220. return { rid = rid }
  221. }
  222. // THE CHOICE for an invite's request: the identity accepts it. Answers { error } or { url }
  223. // (the app's return URL with ident_code and invite). An identity that already accepted this
  224. // invite may pass again without taking another use.
  225. static grantInvite = (accountId, rid, identityId) => {
  226. rq = requestOf(rid)
  227. if (rq == null) { return { error = 'this login request is unknown or expired — open the invitation link again' } }
  228. rec = inviteById(rq.invite)
  229. if (rec == null || rec.app != rq.app.id) { return { error = 'this invitation no longer exists' } }
  230. if (ownIdentity(accountId, identityId) == null) { return { error = 'no such identity' } }
  231. conn = connectionOf(rq.app.id, identityId)
  232. a = acceptInvite(rec, identityId, conn)
  233. if (a.error != null) { return a }
  234. code = issueCode(rq.app.id, identityId)
  235. r = first(requestsTable.find('rid', rid))
  236. if (r != null) { requestsTable.delete(r.id) }
  237. sep = rq.returnUrl.includes('?') ? '&' : '?'
  238. return { url = rq.returnUrl + sep + 'ident_code=' + code + '&invite=' + rec.id }
  239. }
  240. // the face chooseIdentity (components/home.hl): a request that carries an invite accepts the invite, any
  241. // other is a plain login. Answers { error } or { url }.
  242. static grantRequest = (accountId, rid, identityId) => {
  243. rq = requestOf(rid)
  244. if (rq != null && rq.invite != '') { return grantInvite(accountId, rid, identityId) }
  245. return grantLogin(accountId, rid, identityId)
  246. }
  247. // ---- THE SHORT IDS (ident#23) ---------------------------------------------------------------------
  248. // WHAT THE APP MEANT BY AN ID: a notification or a lookup may name an identity by
  249. // its short id, or — until the app has migrated — by its old per-app id. Answers the
  250. // connection (of app `appId`) or null.
  251. static connectionByAnyId = (appId, given) => {
  252. ident = identityByShortId(given)
  253. if (ident != null) { return first(connectionsTable.find('pair', appId + ':' + ident.id)) }
  254. if (given == null || hlTypeName(given) != 'String') { return null }
  255. rows = connectionsTable.find('app', appId)
  256. if (countOf(rows) > 0) {
  257. for (c of rows) { if (c.appIdentity != null && c.appIdentity == given) { return c } }
  258. }
  259. return null
  260. }
  261. // THE MIGRATION, for the app's server: answers { ids } — every old per-app id
  262. // → the identity's short id (an identity that was deleted has none and is left out).
  263. // With `finish` the old ids are dropped afterwards: the app has stored the short ids.
  264. static migrateIds = (a, finish) => {
  265. let ids = {}
  266. let n = 0
  267. rows = connectionsTable.find('app', a.id)
  268. if (countOf(rows) > 0) {
  269. for (c of rows) {
  270. if (c.appIdentity == null) { continue }
  271. let ident = isId(c.identity) ? identitiesTable.fetch(c.identity) : null
  272. if (ident != null) { ids[c.appIdentity] = ident.shortId n = n + 1 }
  273. if (finish) {
  274. let rec = {}
  275. for (k of c.keys()) { if (k != 'appIdentity') { rec[k] = c[k] } }
  276. connectionsTable.update(c.id, rec)
  277. }
  278. }
  279. }
  280. return { ids = ids count = n finished = finish }
  281. }

Branches

Latest commits

  • 716860b0ident#28: gates follow Hybriel ac1ed9da (lazy sessions, meta attribute order, JSON key order, default X-Frame-Options switched off for the embed page)mre
  • 889e00fbident#28: Hybriel master ac1ed9da (sessions reload a newer file, a replayed reconnect carries the server session); a startup fault exits 1 (on Error)mre
  • f5a55f8aident#11: apps can ask for nickname, firstname and lastname (fields list on /api/exchange, new POST /api/profile); empty fields come back null; gate checks, READMEmre
  • d8be66ebident: report and log line for the widget cache and frame height changemre
  • 2068f61aident#31: browsers revalidate the widget scripts on every load; the sign-in frame is exactly as tall as the current step (the frame page reports its height, selector.js accepts it from ident only)mre
  • a22d2daaident#31: the sign-in frame is no taller than the tallest step needs (plain CSS height per width), gate check for itmre
  • a77d1b22ident#31: the welcome form keeps editId a plain value (browser gate), README, wider rows in the framemre
  • 5c481bfdident#31: sign in to ident inside the selector's panel (email, code, identity in an iframe; a new address goes to ident in the same tab and comes back)mre
  • 061abfe2ident: the apps gate waits until the test app's login button stops moving before it clicks (the page grows after load and the click missed about every second run)mre
  • 45f7e4daident: the user menu's Sign out waits for the server before it reloads (the apps gate failed because the session could still be signed in)mre
  • f07658c7ident: home page shows the account once (account bar removed, the user menu carries email, Sign out, Sign out everywhere); wildcard origins https://*.domain for apps on many subdomains; gates follow (WIP: gates not re-run after the last edits)mre
  • f2c43bbbtheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 6d4f996esessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • 029eb5e5deploy: security gate (tests/security.mjs)mre
  • d3c065a8security audit (SI): uploadMax 0, Secure __Host- cookie behind https, headers on function routes/files, page CSP+referrer meta, app/identity caps, tests/security.mjs, reportmre
  • 5561a0cbreport I4-mobilemre
  • 4ca2ed20404 page in the shell (viewport, status 404, way home); phone: account actions live in the user menu so the open menu covers nothing; mobile gate; signoutall waits for a cold startmre
  • 9baad745tests: browser gate waits for the reloaded document (offline reload race under CPU throttle); HL_CPU_THROTTLE knobmre
  • b96796bdtests: wait for hydration before real clicks after a navigation (H2)mre
  • 9722964fre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre