2
0

api.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 id = c.env.SYNC_SERVER.idFromName("oVF8Rsiv")
  121. const stub = c.env.SYNC_SERVER.get(id)
  122. await stub.clear()
  123. return c.json({})
  124. })
  125. .post("/share_sync", async (c) => {
  126. const body = await c.req.json<{
  127. sessionID: string
  128. secret: string
  129. key: string
  130. content: any
  131. }>()
  132. const name = SyncServer.shortName(body.sessionID)
  133. const id = c.env.SYNC_SERVER.idFromName(name)
  134. const stub = c.env.SYNC_SERVER.get(id)
  135. await stub.assertSecret(body.secret)
  136. await stub.publish(body.key, body.content)
  137. return c.json({})
  138. })
  139. .get("/share_poll", async (c) => {
  140. const upgradeHeader = c.req.header("Upgrade")
  141. if (!upgradeHeader || upgradeHeader !== "websocket") {
  142. return c.text("Error: Upgrade header is required", { status: 426 })
  143. }
  144. const id = c.req.query("id")
  145. console.log("share_poll", id)
  146. if (!id) return c.text("Error: Share ID is required", { status: 400 })
  147. const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
  148. return stub.fetch(c.req.raw)
  149. })
  150. .get("/share_data", async (c) => {
  151. const id = c.req.query("id")
  152. console.log("share_data", id)
  153. if (!id) return c.text("Error: Share ID is required", { status: 400 })
  154. const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
  155. const data = await stub.getData()
  156. let info
  157. const messages: Record<string, any> = {}
  158. data.forEach((d) => {
  159. const [root, type, ...splits] = d.key.split("/")
  160. if (root !== "session") return
  161. if (type === "info") {
  162. info = d.content
  163. return
  164. }
  165. if (type === "message") {
  166. messages[d.content.id] = {
  167. parts: [],
  168. ...d.content,
  169. }
  170. }
  171. if (type === "part") {
  172. messages[d.content.messageID].parts.push(d.content)
  173. }
  174. })
  175. return c.json({ info, messages })
  176. })
  177. /**
  178. * Used by the GitHub action to get GitHub installation access token given the OIDC token
  179. */
  180. .post("/exchange_github_app_token", async (c) => {
  181. const EXPECTED_AUDIENCE = "opencode-github-action"
  182. const GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
  183. const JWKS_URL = `${GITHUB_ISSUER}/.well-known/jwks`
  184. // get Authorization header
  185. const token = c.req.header("Authorization")?.replace(/^Bearer /, "")
  186. if (!token) return c.json({ error: "Authorization header is required" }, { status: 401 })
  187. // verify token
  188. const JWKS = createRemoteJWKSet(new URL(JWKS_URL))
  189. let owner, repo
  190. try {
  191. const { payload } = await jwtVerify(token, JWKS, {
  192. issuer: GITHUB_ISSUER,
  193. audience: EXPECTED_AUDIENCE,
  194. })
  195. const sub = payload.sub // e.g. 'repo:my-org/my-repo:ref:refs/heads/main'
  196. const parts = sub.split(":")[1].split("/")
  197. owner = parts[0]
  198. repo = parts[1]
  199. } catch (err) {
  200. console.error("Token verification failed:", err)
  201. return c.json({ error: "Invalid or expired token" }, { status: 403 })
  202. }
  203. // Create app JWT token
  204. const auth = createAppAuth({
  205. appId: Resource.GITHUB_APP_ID.value,
  206. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  207. })
  208. const appAuth = await auth({ type: "app" })
  209. // Lookup installation
  210. const octokit = new Octokit({ auth: appAuth.token })
  211. const { data: installation } = await octokit.apps.getRepoInstallation({ owner, repo })
  212. // Get installation token
  213. const installationAuth = await auth({ type: "installation", installationId: installation.id })
  214. return c.json({ token: installationAuth.token })
  215. })
  216. /**
  217. * Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally)
  218. */
  219. .post("/exchange_github_app_token_with_pat", async (c) => {
  220. const body = await c.req.json<{ owner: string; repo: string }>()
  221. const owner = body.owner
  222. const repo = body.repo
  223. try {
  224. // get Authorization header
  225. const authHeader = c.req.header("Authorization")
  226. const token = authHeader?.replace(/^Bearer /, "")
  227. if (!token) throw new Error("Authorization header is required")
  228. // Verify permissions
  229. const userClient = new Octokit({ auth: token })
  230. const { data: repoData } = await userClient.repos.get({ owner, repo })
  231. if (!repoData.permissions.admin && !repoData.permissions.push && !repoData.permissions.maintain)
  232. throw new Error("User does not have write permissions")
  233. // Get installation token
  234. const auth = createAppAuth({
  235. appId: Resource.GITHUB_APP_ID.value,
  236. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  237. })
  238. const appAuth = await auth({ type: "app" })
  239. // Lookup installation
  240. const appClient = new Octokit({ auth: appAuth.token })
  241. const { data: installation } = await appClient.apps.getRepoInstallation({ owner, repo })
  242. // Get installation token
  243. const installationAuth = await auth({ type: "installation", installationId: installation.id })
  244. return c.json({ token: installationAuth.token })
  245. } catch (e: any) {
  246. let error = e
  247. if (e instanceof Error) {
  248. error = e.message
  249. }
  250. return c.json({ error }, { status: 401 })
  251. }
  252. })
  253. /**
  254. * Used by the opencode CLI to check if the GitHub app is installed
  255. */
  256. .get("/get_github_app_installation", async (c) => {
  257. const owner = c.req.query("owner")
  258. const repo = c.req.query("repo")
  259. const auth = createAppAuth({
  260. appId: Resource.GITHUB_APP_ID.value,
  261. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  262. })
  263. const appAuth = await auth({ type: "app" })
  264. // Lookup installation
  265. const octokit = new Octokit({ auth: appAuth.token })
  266. let installation
  267. try {
  268. const ret = await octokit.apps.getRepoInstallation({ owner, repo })
  269. installation = ret.data
  270. } catch (err) {
  271. if (err instanceof Error && err.message.includes("Not Found")) {
  272. // not installed
  273. } else {
  274. throw err
  275. }
  276. }
  277. return c.json({ installation })
  278. })
  279. .all("*", (c) => c.text("Not Found"))