gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitcd442066cd442066gitoria#43: app-auth unit test reads the apps table from its new filemrecd442066/lib/users.hl

7.2 KB

  1. // lib/users.hl — WHO MAY CREATE (ticket gitoria#6; CONCEPT.md "login via ident"). Reading is public;
  2. // creating a repo needs a login through ident. Login is ident's LOGIN BUTTON flow (ident README
  3. // "How apps use ident", way 2): <ident>/login?key=&return=<public url>/login/callback → ?ident_code=
  4. // → the server exchanges it (key + secret) for the per-app identity id. Way 3, the IDENTITY SELECTOR
  5. // (gitoria#14, ident README "The identity selector"), sits beside the button; ident checks its caller's origin
  6. // against the app's registered origins, and a repo address (<slug>.<domain>) is not one — so the selector shows
  7. // on the main address only (login.js) and the button works from every address (it returns through the main one).
  8. //
  9. // usersTable pk @id index !identity { identity, name, created } storage/mpackdb/users.db
  10. // identity = what ident's exchange answers: the identity's public SHORT id since ident#23 (`a68sz`; old 32-hex per-app
  11. // ids are rewritten once by tools/migrate-short-ids.hl) — stays SERVER SIDE, never sent to a page.
  12. // name = the display name asked once at the first login ('' until chosen); it is what
  13. // a repo shows as its owner.
  14. // The session (hl:web) carries `user = { id = <users @id> }` only.
  15. //
  16. // Config (environment, or `.env` beside project.hl — never read or printed by workers):
  17. // IDENT_URL, IDENT_EXCHANGE_URL, IDENT_API_KEY, IDENT_API_SECRET as in tickets
  18. // (GITORIA_PUBLIC_URL and GITORIA_STORAGE: lib/util.hl)
  19. import { MPackDB } from 'hl:mpackdb'
  20. import { now } from 'hl:time'
  21. import { fetch } from 'hl:fetch'
  22. import { envOr, storageDir, publicUrl, scheme, hostPort, firstOf, plainError, isHex } from './util.hl'
  23. static identUrl = envOr('IDENT_URL', 'https://ident.worldapi.org')
  24. static identExchangeUrl = envOr('IDENT_EXCHANGE_URL', identUrl)
  25. static identKey = envOr('IDENT_API_KEY', '')
  26. static identSecret = envOr('IDENT_API_SECRET', '')
  27. static usersTable = new MPackDB(file = storageDir + '/users.db', primaryKey = '@id', indexes = ['!identity'])
  28. static selectorScript = identUrl + '/selector.js'
  29. static callbackUrl = publicUrl.replaceAll('/', '') == '' ? '' : scheme + '://' + hostPort + '/login/callback'
  30. static loginHref = identUrl + '/login?key=' + identKey + '&return=' + encodeURIComponent(callbackUrl)
  31. // an identity id as ident answers it: its public SHORT ID since ident#23 (5 characters like `a68sz`: 2-9 and a-z),
  32. // before that the old per-app id (32 hex) — lower case letters and digits, at most 64 (mission 039; isHex refused `a68sz`)
  33. static isIdentId = (s) => {
  34. if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > 64) { return false }
  35. let i = 0
  36. while (i < s.length) {
  37. c = s.charCodeAt(i)
  38. if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 122))) { return false }
  39. i = i + 1
  40. }
  41. return true
  42. }
  43. // THE EXCHANGE: POST <ident>/api/exchange { key, secret, code } → { identity } | { error }
  44. // (a failed fetch is an `Error` event, absorbed by project.hl's `on Error`; the fetch then yields null)
  45. static exchangeCode = (code) => {
  46. if (identKey == '' || identSecret == '') { return { error = 'login is not set up on this server (IDENT_API_KEY / IDENT_API_SECRET missing)' } }
  47. if (!isHex(code, 200)) { return { error = 'that is not an ident login code' } }
  48. r = fetch(identExchangeUrl + '/api/exchange', { method = 'POST' json = { key = identKey secret = identSecret code = code } headers = { 'user-agent' = 'gitoria.worldapi.org (ident exchange)' } timeoutMs = 10000 })
  49. if (r == null || r.status == null || r.status == 0) { return { error = 'ident did not answer' } }
  50. j = r.status == 200 ? r.json() : null
  51. if (j == null || j.identity == null || !isIdentId(j.identity)) {
  52. let why = ''
  53. if (r.status != 200) {
  54. e = r.json()
  55. why = e != null && e.error != null ? ': ' + e.error : ''
  56. }
  57. return { error = 'ident refused the login (' + r.status + why + ')' }
  58. }
  59. return { identity = j.identity }
  60. }
  61. // ---- users --------------------------------------------------------------------------------
  62. // a face's trailing `session` is always the server's since hybriel #16 (a peer's extra argument is refused)
  63. static userRecord = (userId) => {
  64. if (userId == null || hlTypeName(userId) != 'String' || userId == '') { return null }
  65. return usersTable.fetch(userId)
  66. }
  67. // the user of an identity id, made at its first login (name '' = not chosen yet)
  68. static ensureUser = (identity) => {
  69. u = firstOf(usersTable.find('identity', identity))
  70. if (u != null) { return u }
  71. id = usersTable.put({ identity = identity name = '' created = now() })
  72. if (id == null) { return null }
  73. return usersTable.fetch(id)
  74. }
  75. // what a page may know about a user: NEVER the identity id
  76. static userInfo = (u) => { return { name = u.name named = u.name != '' } }
  77. static userOfSession = (session) => {
  78. if (session == null || session.user == null) { return null }
  79. return userRecord(session.user.id)
  80. }
  81. // the users @id of a session's user, or null — for a page that must NOT carry the whole record (it holds the ident identity, which
  82. // never goes to a page: a page's values are sent to the browser, mission SG)
  83. static userIdOfSession = (session) => {
  84. u = userOfSession(session)
  85. return u == null ? null : u.id
  86. }
  87. static infoOfSession = (session) => {
  88. u = userOfSession(session)
  89. return u == null ? null : userInfo(u)
  90. }
  91. // the display name of an owner, 'someone' for a user without one
  92. static nameOfUser = (userId) => {
  93. u = userRecord(userId)
  94. if (u == null || u.name == '') { return 'someone' }
  95. return u.name
  96. }
  97. // the display name: 1–60 characters, one line, asked ONCE
  98. static setUserName = (userId, name) => {
  99. u = userRecord(userId)
  100. if (u == null) { return { error = 'not logged in' } }
  101. if (u.name != '') { return { error = 'your display name is already set' } }
  102. bad = plainError(name, 60, 'the display name')
  103. if (bad != null) { return { error = bad } }
  104. n = name.trim()
  105. if (n == '') { return { error = 'the display name must not be empty' } }
  106. usersTable.update(u.id, { id = u.id identity = u.identity name = n created = u.created })
  107. after = usersTable.fetch(u.id)
  108. if (after == null || after.name != n) { return { error = 'could not store the name: ' + usersTable.lastError() } }
  109. return { user = after }
  110. }
  111. // A LOGIN (the login button's return, lib/api.hl loginCallback, and the selector's face gitoriaLogin, components/main.hl):
  112. // ident's one-time code → { user } (made at the first login) or { error }. The caller puts the user into the session.
  113. static userOfLoginCode = (code) => {
  114. x = exchangeCode(code)
  115. if (x.error != null) { return { error = x.error } }
  116. u = ensureUser(x.identity)
  117. if (u == null) { return { error = 'could not store the user' } }
  118. return { user = u }
  119. }
  120. // the random tag of a session's login (session.data.tag, set at login): `gitoriaSignedIn` / `gitoriaSignedOut` reach the
  121. // tabs of the session that carries it (project.hl audience)
  122. static tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }
  123. // the users @ids with exactly this display name (member lists add people by name)
  124. static usersByName = (name) => {
  125. out = []
  126. if (name == null || name == '') { return out }
  127. all = usersTable.find(null, null)
  128. if (all == null || all.length == null) { return out }
  129. for (u of all) { if (u.name == name) { out.push(u.id) } }
  130. return out
  131. }

Branches

Latest commits

  • cd442066gitoria#43: app-auth unit test reads the apps table from its new filemre
  • 5dccbe38gitoria#43: in-flight rows are left alone by the other process; gate in deploy.sh; READMEmre
  • 8c8805f3merge main (gitoria#42), delivery log and redelivery routes, sweep fixmre
  • 5a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre
  • afdb0cbfgitoria#43: rename the moved helper (name clash in the browser build)mre
  • 15e01e94gitoria#43: tests/events.mjs and its probemre
  • 77829b73gitoria#43: signed events to connected apps (deliveries table, sender timer, pull_request events, ping)mre
  • b5d696fegitoria#42: app tokens (gat_, one hour), appOfRequest, app token as the git read passwordmre
  • 1997e77dgitoria#40: stable PR numbers, refs/pull/N/head, ssh pushes reach the app (merge w40-pr-number)mre
  • 9364fb16gitoria#40: ssh pushes call /__git/pushed before and after (ensurePulls, notifyPush, syncPulls); gate over the sshd imagemre
  • fdb9ed28gitoria#41: repo owners can connect an app (merge w41-apps-connect)mre
  • 2ef23df0gitoria#40: the browser gate reads the title without the #Nmre
  • 9af07ecegitoria#41: connect an app to a repo (apps table, connect flow, manual add, allow-list, settings)mre
  • b9137ff0gitoria#40: pull requests are stored with a number, refs/pull/N/head, syncPulls and pullObject; /pulls shows #Nmre
  • 06d622daown image tag gitoria-runtime:debian12 for gitoria and standby (shared tag lost git)mre
  • 20caa33agitoria#37: media queries in the language's @media block (minWidth = '60rem') in list, codebrowser and repomre
  • c4175e6dgitoria: a startup error prints its message before exit 1 (hybriel#247)mre
  • c50d17efKeep function-route not-found style in shared stylesheetmre
  • e42d78d3Preserve ticket state CSS and document function-route style gapmre
  • c6b7154eWIP gitoria#26: move styles into nested component blocksmre