browser-credentials.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import type { Context } from '@deepseek-ai/cordis'
  2. const browserCookies = new WeakMap<Context, string>()
  3. /** Provide an in-memory credential-record owner for a mounted Connection plugin. */
  4. export function provideBrowserCredentials(ctx: Context): void {
  5. const records = new Map<unknown, unknown>()
  6. ctx.provide('credentials', {
  7. async modifyRecord(
  8. key: unknown,
  9. mutate: (current: unknown) => Promise<unknown>,
  10. ): Promise<unknown> {
  11. const current = records.get(key)
  12. const next = await mutate(current)
  13. if (next !== undefined) records.set(key, next)
  14. return next ?? current
  15. },
  16. } as never)
  17. }
  18. /**
  19. * Exchange a test Host's process token for its WebSocket/HTTP Cookie header.
  20. * @param ctx - Host root with the Web server and Connection mounted.
  21. * @returns the `cookie` header value, cached per root.
  22. */
  23. export function browserCookie(ctx: Context): string {
  24. const existing = browserCookies.get(ctx)
  25. if (existing !== undefined) return existing
  26. const origin = `http://127.0.0.1:${String(ctx.webServer.port)}`
  27. const target = new URL(ctx.connection.authenticatedUrl(origin))
  28. let setCookie: string | undefined
  29. ctx.connection.authorizeIndex({
  30. method: 'GET',
  31. url: `${target.pathname}${target.search}`,
  32. headers: { host: target.host },
  33. }, {
  34. writeHead(_status, headers) { setCookie = headers?.['set-cookie'] },
  35. end() {},
  36. })
  37. if (setCookie === undefined) throw new Error('gateway fixture did not receive a browser cookie')
  38. const cookie = setCookie.split(';', 1)[0]!
  39. browserCookies.set(ctx, cookie)
  40. return cookie
  41. }