gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita77d1b22a77d1b22ident#31: the welcome form keeps editId a plain value (browser gate), README, wider rows in the framemrea77d1b22/lib/apps.hl

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

Branches

Latest commits

  • 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
  • c9b196c9tests/iplimit: wait for the welcome form itself after B's first login (identities list renders before it); mission 017 reportmre
  • 72e0f587ident#26: identity page with "Used in" (app, since, last use, Notif. chip, empty state); lastLogin recorded at exchange; gates + lisbeth E2E; mission 016 reportmre
  • 94576fbcident#26 WIP: identity page /identity/:iid with "Used in" (app, since, last use, Notif. chip), lastLogin recorded at exchange, "Used in…" link on the identities list; apps gate 4b, e2e-usedin.mjsmre
  • 349cb502tests/invites: wait for hydration on the code page before entering the code (native GET submit raced the welcome form); mission 015 reportmre
  • d1bf4720tests: no hard-coded ports — every gate's ports and fixture origins come from <GATE>_PORT / _CHROME env (defaults unchanged; Bob/fixture origins follow, selector cookie name too)mre
  • 6280c92fre-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre