api.ts 9.0 KB

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