api.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import { Hono } from "hono"
  2. import { DurableObject } from "cloudflare:workers"
  3. import { randomUUID } from "node:crypto"
  4. import { jwtVerify, createRemoteJWKSet } from "jose"
  5. import { createAppAuth } from "@octokit/auth-app"
  6. import { Octokit } from "@octokit/rest"
  7. import { Resource } from "sst"
  8. type Env = {
  9. SYNC_SERVER: DurableObjectNamespace<SyncServer>
  10. Bucket: R2Bucket
  11. WEB_DOMAIN: string
  12. }
  13. export class SyncServer extends DurableObject<Env> {
  14. constructor(ctx: DurableObjectState, env: Env) {
  15. super(ctx, env)
  16. }
  17. async fetch() {
  18. console.log("SyncServer subscribe")
  19. const webSocketPair = new WebSocketPair()
  20. const [client, server] = Object.values(webSocketPair)
  21. this.ctx.acceptWebSocket(server)
  22. const data = await this.ctx.storage.list()
  23. Array.from(data.entries())
  24. .filter(([key, _]) => key.startsWith("session/"))
  25. .map(([key, content]) => server.send(JSON.stringify({ key, content })))
  26. return new Response(null, {
  27. status: 101,
  28. webSocket: client,
  29. })
  30. }
  31. async webSocketMessage(ws, message) {}
  32. async webSocketClose(ws, code, reason, wasClean) {
  33. ws.close(code, "Durable Object is closing WebSocket")
  34. }
  35. async publish(key: string, content: any) {
  36. const sessionID = await this.getSessionID()
  37. if (
  38. !key.startsWith(`session/info/${sessionID}`) &&
  39. !key.startsWith(`session/message/${sessionID}/`) &&
  40. !key.startsWith(`session/part/${sessionID}/`)
  41. )
  42. return new Response("Error: Invalid key", { status: 400 })
  43. // store message
  44. await this.env.Bucket.put(`share/${key}.json`, JSON.stringify(content), {
  45. httpMetadata: {
  46. contentType: "application/json",
  47. },
  48. })
  49. await this.ctx.storage.put(key, content)
  50. const clients = this.ctx.getWebSockets()
  51. console.log("SyncServer publish", key, "to", clients.length, "subscribers")
  52. for (const client of clients) {
  53. client.send(JSON.stringify({ key, content }))
  54. }
  55. }
  56. public async share(sessionID: string) {
  57. let secret = await this.getSecret()
  58. if (secret) return secret
  59. secret = randomUUID()
  60. await this.ctx.storage.put("secret", secret)
  61. await this.ctx.storage.put("sessionID", sessionID)
  62. return secret
  63. }
  64. public async getData() {
  65. const data = (await this.ctx.storage.list()) as Map<string, any>
  66. return Array.from(data.entries())
  67. .filter(([key, _]) => key.startsWith("session/"))
  68. .map(([key, content]) => ({ key, content }))
  69. }
  70. public async assertSecret(secret: string) {
  71. if (secret !== (await this.getSecret())) throw new Error("Invalid secret")
  72. }
  73. private async getSecret() {
  74. return this.ctx.storage.get<string>("secret")
  75. }
  76. private async getSessionID() {
  77. return this.ctx.storage.get<string>("sessionID")
  78. }
  79. async clear() {
  80. const sessionID = await this.getSessionID()
  81. const list = await this.env.Bucket.list({
  82. prefix: `session/message/${sessionID}/`,
  83. limit: 1000,
  84. })
  85. for (const item of list.objects) {
  86. await this.env.Bucket.delete(item.key)
  87. }
  88. await this.env.Bucket.delete(`session/info/${sessionID}`)
  89. await this.ctx.storage.deleteAll()
  90. }
  91. static shortName(id: string) {
  92. return id.substring(id.length - 8)
  93. }
  94. }
  95. export default new Hono<{ Bindings: Env }>()
  96. .get("/", (c) => c.text("Hello, world!"))
  97. .post("/share_create", async (c) => {
  98. const body = await c.req.json<{ sessionID: string }>()
  99. const sessionID = body.sessionID
  100. const short = SyncServer.shortName(sessionID)
  101. const id = c.env.SYNC_SERVER.idFromName(short)
  102. const stub = c.env.SYNC_SERVER.get(id)
  103. const secret = await stub.share(sessionID)
  104. return c.json({
  105. secret,
  106. url: `https://${c.env.WEB_DOMAIN}/s/${short}`,
  107. })
  108. })
  109. .post("/share_delete", async (c) => {
  110. const body = await c.req.json<{ sessionID: string; secret: string }>()
  111. const sessionID = body.sessionID
  112. const secret = body.secret
  113. const id = c.env.SYNC_SERVER.idFromName(SyncServer.shortName(sessionID))
  114. const stub = c.env.SYNC_SERVER.get(id)
  115. await stub.assertSecret(secret)
  116. await stub.clear()
  117. return c.json({})
  118. })
  119. .post("/share_delete_admin", async (c) => {
  120. const body = await c.req.json<{ sessionShortName: string; adminSecret: string }>()
  121. const sessionShortName = body.sessionShortName
  122. const adminSecret = body.adminSecret
  123. if (adminSecret !== Resource.ADMIN_SECRET.value) throw new Error("Invalid admin secret")
  124. const id = c.env.SYNC_SERVER.idFromName(sessionShortName)
  125. const stub = c.env.SYNC_SERVER.get(id)
  126. await stub.clear()
  127. return c.json({})
  128. })
  129. .post("/share_sync", async (c) => {
  130. const body = await c.req.json<{
  131. sessionID: string
  132. secret: string
  133. key: string
  134. content: any
  135. }>()
  136. const name = SyncServer.shortName(body.sessionID)
  137. const id = c.env.SYNC_SERVER.idFromName(name)
  138. const stub = c.env.SYNC_SERVER.get(id)
  139. await stub.assertSecret(body.secret)
  140. await stub.publish(body.key, body.content)
  141. return c.json({})
  142. })
  143. .get("/share_poll", async (c) => {
  144. const upgradeHeader = c.req.header("Upgrade")
  145. if (!upgradeHeader || upgradeHeader !== "websocket") {
  146. return c.text("Error: Upgrade header is required", { status: 426 })
  147. }
  148. const id = c.req.query("id")
  149. console.log("share_poll", id)
  150. if (!id) return c.text("Error: Share ID is required", { status: 400 })
  151. const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
  152. return stub.fetch(c.req.raw)
  153. })
  154. .get("/share_data", async (c) => {
  155. const id = c.req.query("id")
  156. console.log("share_data", id)
  157. if (!id) return c.text("Error: Share ID is required", { status: 400 })
  158. const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
  159. const data = await stub.getData()
  160. let info
  161. const messages: Record<string, any> = {}
  162. data.forEach((d) => {
  163. const [root, type, ...splits] = d.key.split("/")
  164. if (root !== "session") return
  165. if (type === "info") {
  166. info = d.content
  167. return
  168. }
  169. if (type === "message") {
  170. messages[d.content.id] = {
  171. parts: [],
  172. ...d.content,
  173. }
  174. }
  175. if (type === "part") {
  176. messages[d.content.messageID].parts.push(d.content)
  177. }
  178. })
  179. return c.json({ info, messages })
  180. })
  181. /**
  182. * Used by the GitHub action to get GitHub installation access token given the OIDC token
  183. */
  184. .post("/exchange_github_app_token", async (c) => {
  185. const EXPECTED_AUDIENCE = "opencode-github-action"
  186. const GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
  187. const JWKS_URL = `${GITHUB_ISSUER}/.well-known/jwks`
  188. // get Authorization header
  189. const token = c.req.header("Authorization")?.replace(/^Bearer /, "")
  190. if (!token) return c.json({ error: "Authorization header is required" }, { status: 401 })
  191. // verify token
  192. const JWKS = createRemoteJWKSet(new URL(JWKS_URL))
  193. let owner, repo
  194. try {
  195. const { payload } = await jwtVerify(token, JWKS, {
  196. issuer: GITHUB_ISSUER,
  197. audience: EXPECTED_AUDIENCE,
  198. })
  199. const sub = payload.sub // e.g. 'repo:my-org/my-repo:ref:refs/heads/main'
  200. const parts = sub.split(":")[1].split("/")
  201. owner = parts[0]
  202. repo = parts[1]
  203. } catch (err) {
  204. console.error("Token verification failed:", err)
  205. return c.json({ error: "Invalid or expired token" }, { status: 403 })
  206. }
  207. // Create app JWT token
  208. const auth = createAppAuth({
  209. appId: Resource.GITHUB_APP_ID.value,
  210. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  211. })
  212. const appAuth = await auth({ type: "app" })
  213. // Lookup installation
  214. const octokit = new Octokit({ auth: appAuth.token })
  215. const { data: installation } = await octokit.apps.getRepoInstallation({
  216. owner,
  217. repo,
  218. })
  219. // Get installation token
  220. const installationAuth = await auth({
  221. type: "installation",
  222. installationId: installation.id,
  223. })
  224. return c.json({ token: installationAuth.token })
  225. })
  226. /**
  227. * Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally)
  228. */
  229. .post("/exchange_github_app_token_with_pat", async (c) => {
  230. const body = await c.req.json<{ owner: string; repo: string }>()
  231. const owner = body.owner
  232. const repo = body.repo
  233. try {
  234. // get Authorization header
  235. const authHeader = c.req.header("Authorization")
  236. const token = authHeader?.replace(/^Bearer /, "")
  237. if (!token) throw new Error("Authorization header is required")
  238. // Verify permissions
  239. const userClient = new Octokit({ auth: token })
  240. const { data: repoData } = await userClient.repos.get({ owner, repo })
  241. if (!repoData.permissions.admin && !repoData.permissions.push && !repoData.permissions.maintain)
  242. throw new Error("User does not have write permissions")
  243. // Get installation token
  244. const auth = createAppAuth({
  245. appId: Resource.GITHUB_APP_ID.value,
  246. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  247. })
  248. const appAuth = await auth({ type: "app" })
  249. // Lookup installation
  250. const appClient = new Octokit({ auth: appAuth.token })
  251. const { data: installation } = await appClient.apps.getRepoInstallation({
  252. owner,
  253. repo,
  254. })
  255. // Get installation token
  256. const installationAuth = await auth({
  257. type: "installation",
  258. installationId: installation.id,
  259. })
  260. return c.json({ token: installationAuth.token })
  261. } catch (e: any) {
  262. let error = e
  263. if (e instanceof Error) {
  264. error = e.message
  265. }
  266. return c.json({ error }, { status: 401 })
  267. }
  268. })
  269. /**
  270. * Used by the opencode CLI to check if the GitHub app is installed
  271. */
  272. .get("/get_github_app_installation", async (c) => {
  273. const owner = c.req.query("owner")
  274. const repo = c.req.query("repo")
  275. const auth = createAppAuth({
  276. appId: Resource.GITHUB_APP_ID.value,
  277. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  278. })
  279. const appAuth = await auth({ type: "app" })
  280. // Lookup installation
  281. const octokit = new Octokit({ auth: appAuth.token })
  282. let installation
  283. try {
  284. const ret = await octokit.apps.getRepoInstallation({ owner, repo })
  285. installation = ret.data
  286. } catch (err) {
  287. if (err instanceof Error && err.message.includes("Not Found")) {
  288. // not installed
  289. } else {
  290. throw err
  291. }
  292. }
  293. return c.json({ installation })
  294. })
  295. .all("*", (c) => c.text("Not Found"))