gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5a996ea85a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre5a996ea8/lib/apps.hl

8.8 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) } 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 { dropTokensOfApp } from './app-tokens.hl'
  18. static appsTable = new MPackDB(file = storageDir + '/apps.db', primaryKey = '@id', indexes = ['!keyHash', 'repo'])
  19. static codesTable = new MPackDB(file = storageDir + '/appcodes.db', primaryKey = '@id', indexes = ['!hash'])
  20. static codeLifeMs = 300000
  21. static maxApps = 20
  22. // a whole app record with some fields changed (update() replaces the record: every field must be given again)
  23. static withChange = (a, change) => {
  24. o = { id = a.id repo = a.repo name = a.name hookUrl = a.hookUrl keyHash = a.keyHash secret = a.secret createdBy = a.createdBy created = a.created lastDelivery = a.lastDelivery lastStatus = a.lastStatus }
  25. for (k of change.keys()) { o[k] = change[k] }
  26. return o
  27. }
  28. // ---- the owner's list (never the key, never the secret) -----------------------------------------------------
  29. static statusText = (a) => {
  30. if (a.lastStatus == null || a.lastStatus == '') { return 'no delivery yet' }
  31. return '' + a.lastStatus + (a.lastDelivery != null && a.lastDelivery > 0 ? ' · ' + localStamp(a.lastDelivery) : '')
  32. }
  33. static rowOfApp = (a) => {
  34. return { id = a.id name = a.name host = hostOfUrl(a.hookUrl) created = localStamp(a.created) createdMs = a.created status = statusText(a) }
  35. }
  36. static appsOfRepo = (repoId) => {
  37. all = appsTable.find('repo', repoId)
  38. return countOfList(all) == 0 ? [] : all
  39. }
  40. // the apps of a repo for its owner's page, newest first
  41. static appRows = (repoId) => {
  42. out = []
  43. for (a of appsOfRepo(repoId)) { out.push(rowOfApp(a)) }
  44. return newestFirst(out)
  45. }
  46. static appOfName = (repoId, name) => {
  47. want = ('' + name).toLowerCase()
  48. for (a of appsOfRepo(repoId)) { if (a.name.toLowerCase() == want) { return a } }
  49. return null
  50. }
  51. // 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
  52. static appOfKey = (key) => {
  53. if (!keyShaped(key)) { return null }
  54. return firstOf(appsTable.find('keyHash', sha256(key)))
  55. }
  56. // ---- checks shared by the connect flow and the manual way ------------------------------------------------------
  57. // the app's name: one line, at most 60 characters → null or the complaint
  58. static nameError = (name) => {
  59. n = name == null ? '' : ('' + name).trim()
  60. if (n == '') { return 'give the app a name' }
  61. return plainError(n, 60, 'the app name')
  62. }
  63. // ---- THE HOOK POINT OF gitoria#43 -------------------------------------------------------------------------------
  64. // GITORIA#43 HOOK: called once after an app was connected (connect flow A at the exchange, the manual way at Add). #43 sends the `ping` event
  65. // to app.hookUrl from here (docs/apps-api.md §4). Today it sends nothing.
  66. static pingAfterConnect = (app, repo) => {
  67. return null
  68. }
  69. // ---- storing an app: a new key and secret, shown once -----------------------------------------------------------
  70. // (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 }
  71. static storeApp = (repo, name, hookUrl, userId) => {
  72. n = ('' + name).trim()
  73. key = 'gak_' + randomBytes(20, 'hex')
  74. secret = randomBytes(32, 'hex')
  75. old = appOfName(repo.id, n)
  76. let id = null
  77. if (old != null) {
  78. appsTable.update(old.id, withChange(old, { hookUrl = hookUrl keyHash = sha256(key) secret = secret createdBy = userId }))
  79. id = old.id
  80. dropTokensOfApp(old.id)
  81. } else {
  82. if (appsOfRepo(repo.id).length >= maxApps) { return { error = 'this repository has ' + maxApps + ' apps already — remove one first' } }
  83. id = appsTable.put({ repo = repo.id name = n hookUrl = hookUrl keyHash = sha256(key) secret = secret createdBy = userId created = now() lastDelivery = 0 lastStatus = '' })
  84. }
  85. if (id == null) { return { error = 'could not store the app: ' + appsTable.lastError() } }
  86. a = appsTable.fetch(id)
  87. pingAfterConnect(a, repo)
  88. return { app = a key = key secret = secret }
  89. }
  90. // the manual way B (Settings → Apps → Add) for the owner → { rows, key, secret, name } or { error }
  91. static addApp = (userId, session, slug, name, hook) => {
  92. repo = repoBySlug(slug)
  93. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can add an app' } }
  94. bad = nameError(name)
  95. if (bad != null) { return { error = bad } }
  96. 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)' } }
  97. r = storeApp(repo, name, ('' + hook).trim(), userId)
  98. if (r.error != null) { return r }
  99. return { rows = appRows(repo.id) name = r.app.name key = r.key secret = r.secret }
  100. }
  101. // the owner removes an app: the row is gone, so its key is dead at once → { rows } or { error }
  102. static removeApp = (userId, session, slug, appId) => {
  103. repo = repoBySlug(slug)
  104. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can remove an app' } }
  105. a = appId == null || hlTypeName(appId) != 'String' ? null : appsTable.fetch(appId)
  106. if (a == null || a.repo != repo.id) { return { error = 'no such app' } }
  107. appsTable.delete(a.id)
  108. dropTokensOfApp(a.id)
  109. return { rows = appRows(repo.id) }
  110. }
  111. // the owner rotates an app's secret: a new one, shown once → { rows, name, secret } or { error }
  112. static rotateSecret = (userId, session, slug, appId) => {
  113. repo = repoBySlug(slug)
  114. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can rotate a secret' } }
  115. a = appId == null || hlTypeName(appId) != 'String' ? null : appsTable.fetch(appId)
  116. if (a == null || a.repo != repo.id) { return { error = 'no such app' } }
  117. secret = randomBytes(32, 'hex')
  118. appsTable.update(a.id, withChange(a, { secret = secret }))
  119. return { rows = appRows(repo.id) name = a.name secret = secret }
  120. }
  121. // ---- connect flow A ----------------------------------------------------------------------------------------------
  122. // 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)
  123. static makeCode = (repo, name, hookUrl, userId) => {
  124. code = randomBytes(24, 'hex')
  125. id = codesTable.put({ hash = sha256(code) repo = repo.id name = ('' + name).trim() hookUrl = hookUrl createdBy = userId created = now() })
  126. return id == null ? null : code
  127. }
  128. // 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.
  129. // 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 }
  130. static exchangeCode = (repo, code) => {
  131. if (code == null || hlTypeName(code) != 'String' || !isHex(code, 48)) { return { notFound = true } }
  132. row = firstOf(codesTable.find('hash', sha256(code)))
  133. if (row == null) { return { notFound = true } }
  134. codesTable.delete(row.id)
  135. if (now() - row.created > codeLifeMs || repo == null || row.repo != repo.id) { return { notFound = true } }
  136. r = storeApp(repo, row.name, row.hookUrl, row.createdBy)
  137. if (r.error != null) { return { notFound = true } }
  138. 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 } } }
  139. }

Branches

Latest commits

  • 5a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)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
  • 77a2c31cgitoria#31: plain declarations instead of needless let in lib/ and tools/ (103 let removed, 137 kept because reassigned); no other changemre
  • 4b98ab62gitoria: an ident access key (idt_) works as the git password; read key clones only, bad key 401, ident down 503 (ident#27); gate tests/ident-access-gitoria.mjs in deploy.shmre
  • 1185f686gitoria#36: a failed return from tickets shows a note on the settings page and leaves one log line per outcome; no code is exchangedmre
  • 5d2c385agitoria: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 71+5 failing → 76 passed; deploy.sh runs tests/private.mjs toomre
  • 241ef3f9deploy.sh: rebuild the sshd image before up -d (GO34c)mre
  • 821cdbb1gitoria#34b: styles, create-repo tool, docs, push/ssh gates sign in through the selector, shots scriptmre