gitoria

gitoria

All repositories: gitoria

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

8.9 KB

  1. // lib/apps.hl — APPS CONNECTED TO A REPO (gitoria#41, part of the push API gitoria#38; contract docs/apps-api.md §0 and §1).
  2. // An app is an outside program the repo's OWNER connected to ONE repo; it acts under its own name, never as a person. Two tables:
  3. // appsTable pk @id index !keyHash, repo storage/mpackdb/apps.db
  4. // { repo (repos @id, NOT the slug: a moved repo keeps its apps), name, hookUrl, keyHash (sha256 of `gak_` + 40 hex),
  5. // secret (64 hex, signs the events — SERVER ONLY, never sent to a page or a log), createdBy (users @id), created,
  6. // lastDelivery, lastStatus (gitoria#43 fills them: lib/events.hl) } one row per (repo, app name): a re-connect replaces key and secret
  7. // codesTable pk @id index !hash storage/mpackdb/appcodes.db { hash (sha256 of the code), repo, name, hookUrl, createdBy, created }
  8. // the one-time code of connect flow A: works once, for 5 minutes; only its sha256 is stored
  9. // The key and the secret are shown ONCE (at connect / add / rotate); only the key's sha256 is kept. The URL allow-list, the shapes: lib/apps-helpers.hl.
  10. // The routes are thin wrappers in lib/api.hl (connect, confirm, exchange); the settings page (components/settings.hl) lists, adds, removes, rotates.
  11. import { MPackDB } from 'hl:mpackdb'
  12. import { now } from 'hl:time'
  13. import { randomBytes, sha256 } from 'hl:crypto'
  14. import { storageDir, countOfList, firstOf, plainError, isHex, localStamp, newestFirst } from './util.hl'
  15. import { repoBySlug, ownsRepo } from './repos.hl'
  16. import { urlAllowed, hostOfUrl, keyShaped, apiOf } from './apps-helpers.hl'
  17. import { appsTable, appsOfRepo, appWith } from './apps-table.hl'
  18. import { raisePing, pingApp } from './events.hl'
  19. import { dropTokensOfApp } from './app-tokens.hl'
  20. static codesTable = new MPackDB(file = storageDir + '/appcodes.db', primaryKey = '@id', indexes = ['!hash'])
  21. static codeLifeMs = 300000
  22. static maxApps = 20
  23. // ---- the owner's list (never the key, never the secret) -----------------------------------------------------
  24. static statusText = (a) => {
  25. if (a.lastStatus == null || a.lastStatus == '') { return 'no delivery yet' }
  26. return '' + a.lastStatus + (a.lastDelivery != null && a.lastDelivery > 0 ? ' · ' + localStamp(a.lastDelivery) : '')
  27. }
  28. static rowOfApp = (a) => {
  29. return { id = a.id name = a.name host = hostOfUrl(a.hookUrl) created = localStamp(a.created) createdMs = a.created status = statusText(a) }
  30. }
  31. // the apps of a repo for its owner's page, newest first
  32. static appRows = (repoId) => {
  33. out = []
  34. for (a of appsOfRepo(repoId)) { out.push(rowOfApp(a)) }
  35. return newestFirst(out)
  36. }
  37. static appOfName = (repoId, name) => {
  38. want = ('' + name).toLowerCase()
  39. for (a of appsOfRepo(repoId)) { if (a.name.toLowerCase() == want) { return a } }
  40. return null
  41. }
  42. // the app a key belongs to (like tokens.hl userOfToken): the record or null; anything not shaped like a key is null without a lookup
  43. static appOfKey = (key) => {
  44. if (!keyShaped(key)) { return null }
  45. return firstOf(appsTable.find('keyHash', sha256(key)))
  46. }
  47. // ---- checks shared by the connect flow and the manual way ------------------------------------------------------
  48. // the app's name: one line, at most 60 characters → null or the complaint
  49. static nameError = (name) => {
  50. n = name == null ? '' : ('' + name).trim()
  51. if (n == '') { return 'give the app a name' }
  52. return plainError(n, 60, 'the app name')
  53. }
  54. // ---- THE HOOK POINT OF gitoria#43 -------------------------------------------------------------------------------
  55. // GITORIA#43: called once after an app was connected (connect flow A at the exchange, the manual way at Add): raises the `ping` event for that app
  56. // (lib/events.hl; the sender thread delivers it, docs/apps-api.md §4). It only writes a delivery row.
  57. static pingAfterConnect = (app, repo) => {
  58. raisePing(repo, app, app.createdBy)
  59. return null
  60. }
  61. // ---- storing an app: a new key and secret, shown once -----------------------------------------------------------
  62. // (re)connect: the one row of (repo, name) gets a new key and secret (a new row when there is none) → { app, key, secret } or { error }
  63. static storeApp = (repo, name, hookUrl, userId) => {
  64. n = ('' + name).trim()
  65. key = 'gak_' + randomBytes(20, 'hex')
  66. secret = randomBytes(32, 'hex')
  67. old = appOfName(repo.id, n)
  68. let id = null
  69. if (old != null) {
  70. appsTable.update(old.id, appWith(old, { hookUrl = hookUrl keyHash = sha256(key) secret = secret createdBy = userId }))
  71. id = old.id
  72. dropTokensOfApp(old.id)
  73. } else {
  74. if (appsOfRepo(repo.id).length >= maxApps) { return { error = 'this repository has ' + maxApps + ' apps already — remove one first' } }
  75. id = appsTable.put({ repo = repo.id name = n hookUrl = hookUrl keyHash = sha256(key) secret = secret createdBy = userId created = now() lastDelivery = 0 lastStatus = '' })
  76. }
  77. if (id == null) { return { error = 'could not store the app: ' + appsTable.lastError() } }
  78. a = appsTable.fetch(id)
  79. pingAfterConnect(a, repo)
  80. return { app = a key = key secret = secret }
  81. }
  82. // the manual way B (Settings → Apps → Add) for the owner → { rows, key, secret, name } or { error }
  83. static addApp = (userId, session, slug, name, hook) => {
  84. repo = repoBySlug(slug)
  85. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can add an app' } }
  86. bad = nameError(name)
  87. if (bad != null) { return { error = bad } }
  88. if (hook == null || !urlAllowed(('' + hook).trim())) { return { error = 'that receiver address is not allowed (https://, host worldapi.org or one of its subdomains, or a configured HyperConductor address)' } }
  89. r = storeApp(repo, name, ('' + hook).trim(), userId)
  90. if (r.error != null) { return r }
  91. return { rows = appRows(repo.id) name = r.app.name key = r.key secret = r.secret }
  92. }
  93. // the owner removes an app: the row is gone, so its key is dead at once → { rows } or { error }
  94. static removeApp = (userId, session, slug, appId) => {
  95. repo = repoBySlug(slug)
  96. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can remove an app' } }
  97. a = appId == null || hlTypeName(appId) != 'String' ? null : appsTable.fetch(appId)
  98. if (a == null || a.repo != repo.id) { return { error = 'no such app' } }
  99. appsTable.delete(a.id)
  100. dropTokensOfApp(a.id)
  101. return { rows = appRows(repo.id) }
  102. }
  103. // the owner rotates an app's secret: a new one, shown once → { rows, name, secret } or { error }
  104. static rotateSecret = (userId, session, slug, appId) => {
  105. repo = repoBySlug(slug)
  106. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can rotate a secret' } }
  107. a = appId == null || hlTypeName(appId) != 'String' ? null : appsTable.fetch(appId)
  108. if (a == null || a.repo != repo.id) { return { error = 'no such app' } }
  109. secret = randomBytes(32, 'hex')
  110. appsTable.update(a.id, appWith(a, { secret = secret }))
  111. return { rows = appRows(repo.id) name = a.name secret = secret }
  112. }
  113. // the owner clicks "Send ping" on an app: a `ping` event row for that app (the sender delivers it) → { name } or { error }
  114. static sendPing = (userId, session, slug, appId) => {
  115. repo = repoBySlug(slug)
  116. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can send a ping' } }
  117. a = appId == null || hlTypeName(appId) != 'String' ? null : appsTable.fetch(appId)
  118. if (a == null || a.repo != repo.id) { return { error = 'no such app' } }
  119. pingApp(repo, a, userId)
  120. return { name = a.name }
  121. }
  122. // ---- connect flow A ----------------------------------------------------------------------------------------------
  123. // the owner said Yes on the confirm page: a one-time code for (repo, name, hook) → the code (shown to nobody, it goes in the redirect)
  124. static makeCode = (repo, name, hookUrl, userId) => {
  125. code = randomBytes(24, 'hex')
  126. id = codesTable.put({ hash = sha256(code) repo = repo.id name = ('' + name).trim() hookUrl = hookUrl createdBy = userId created = now() })
  127. return id == null ? null : code
  128. }
  129. // the app's server trades the code for the key, secret and API address (POST /api/apps/exchange). `repo` = the repo the request's address names.
  130. // A code works once (it is deleted before anything else) and for 5 minutes, and only on the address of ITS repo → { body } (the contract's JSON) or { notFound }
  131. static exchangeCode = (repo, code) => {
  132. if (code == null || hlTypeName(code) != 'String' || !isHex(code, 48)) { return { notFound = true } }
  133. row = firstOf(codesTable.find('hash', sha256(code)))
  134. if (row == null) { return { notFound = true } }
  135. codesTable.delete(row.id)
  136. if (now() - row.created > codeLifeMs || repo == null || row.repo != repo.id) { return { notFound = true } }
  137. r = storeApp(repo, row.name, row.hookUrl, row.createdBy)
  138. if (r.error != null) { return { notFound = true } }
  139. return { body = { key = r.key secret = r.secret api = apiOf(repo.slug) repo = { id = repo.id full = repo.slug } app = { id = r.app.id name = r.app.name } } }
  140. }

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