11// @effect -diagnostics nodeBuiltinImport:off globalFetchInEffect:off - Local mock OAuth server validates the browser callback boundary.
2+ import * as NodeNet from "node:net" ;
3+ import * as Context from "effect/Context" ;
4+ import * as Scope from "effect/Scope" ;
5+ import * as ServerConfig from "../config.ts" ;
6+ import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts" ;
27import * as NodeHttp from "node:http" ;
38import * as NodeCrypto from "node:crypto" ;
49import * as NodeServices from "@effect/platform-node/NodeServices" ;
@@ -11,7 +16,7 @@ import * as Stream from "effect/Stream";
1116import * as Fiber from "effect/Fiber" ;
1217import * as Deferred from "effect/Deferred" ;
1318import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts" ;
14- import { FetchHttpClient } from "effect/http" ;
19+ import { FetchHttpClient , HttpClient , HttpClientResponse } from "effect/http" ;
1520import { exportJWK , generateKeyPair , SignJWT } from "jose" ;
1621import * as ServerSecretStore from "../auth/ServerSecretStore.ts" ;
1722import * as ServerEnvironment from "../environment/ServerEnvironment.ts" ;
@@ -320,6 +325,16 @@ const makeHarnessFor = Effect.fnUntraced(function* (
320325 ) ;
321326 return { auth : destination , bytes : destinationBytes } ;
322327 } ) ,
328+ bindProfile : ( expectedProfileKey : string ) =>
329+ makeCodexChatGptAuth ( {
330+ instanceId,
331+ expectedProfileKey,
332+ discoveryUrl : `${ origin } /discovery` ,
333+ resource : `${ origin } /v1` ,
334+ } ) . pipe (
335+ Effect . provideService ( ServerSecretStore . ServerSecretStore , secrets ) ,
336+ Effect . provideService ( ServerEnvironment . ServerEnvironmentIdentity , environment ) ,
337+ ) ,
323338 recreateAuth : makeCodexChatGptAuth ( {
324339 instanceId,
325340 discoveryUrl : `${ origin } /discovery` ,
@@ -1604,3 +1619,205 @@ it.effect("telemetry failures do not fail a verified ChatGPT sign-in", () =>
16041619 } ) ,
16051620 ) ,
16061621) ;
1622+ it . effect ( "a running session renews its bound profile but refuses a replacement sign-in" , ( ) =>
1623+ provision (
1624+ Effect . gen ( function * ( ) {
1625+ const h = yield * makeHarness ;
1626+ yield * h . signIn ;
1627+ yield * h . phase ( "succeeded" ) ;
1628+ const profileKey = yield * h . auth . profileKey ( Option . getOrThrow ( yield * h . auth . read ) ) ;
1629+ const first = yield * h . bindProfile ( profileKey ) ;
1630+ const second = yield * h . bindProfile ( profileKey ) ;
1631+ yield * h . seedExpired ;
1632+ const renewed = yield * Effect . all ( [ first . access , second . access ] , {
1633+ concurrency : "unbounded" ,
1634+ } ) ;
1635+ assert . equal ( h . refreshes ( ) , 1 ) ;
1636+ assert . equal ( renewed [ 0 ] . accessToken , "access-1" ) ;
1637+ assert . deepEqual ( renewed [ 0 ] , renewed [ 1 ] ) ;
1638+ assert . equal ( yield * h . auth . profileKey ( renewed [ 0 ] ) , profileKey ) ;
1639+
1640+ // Reconnecting the same account replaces its sign-in identity, too.
1641+ yield * h . reconnectProfile ( "oaiapp_test" ) ;
1642+ yield * h . phase ( "succeeded" ) ;
1643+ const replacement = Option . getOrThrow ( yield * h . auth . read ) ;
1644+ assert . equal ( replacement . clientId , renewed [ 0 ] . clientId ) ;
1645+ assert . equal ( replacement . subject , renewed [ 0 ] . subject ) ;
1646+ yield * h . seedExpired ;
1647+ assert . equal ( ( yield * first . access . pipe ( Effect . flip ) ) . operation , "access" ) ;
1648+ assert . equal ( h . refreshes ( ) , 1 ) ;
1649+ yield * h . auth . revoke ;
1650+ assert . equal ( ( yield * second . access . pipe ( Effect . flip ) ) . operation , "access" ) ;
1651+ assert . isTrue ( Option . isNone ( yield * h . auth . read ) ) ;
1652+ } ) ,
1653+ ) ,
1654+ ) ;
1655+
1656+ const makeRenewalBroker = Effect . gen ( function * ( ) {
1657+ const oauthEntered = yield * Deferred . make < void > ( ) ;
1658+ const oauthRelease = yield * Deferred . make < void > ( ) ;
1659+ let pauseOAuth = false ;
1660+ const refreshTokens : string [ ] = [ ] ;
1661+ const credentials = {
1662+ clientId : "oaiapp_broker" ,
1663+ subject : "broker-user" ,
1664+ idToken : "broker-sign-in" ,
1665+ email : null ,
1666+ accessToken : "expired-access" ,
1667+ refreshToken : "single-use-refresh" ,
1668+ expiresAt : 0 ,
1669+ earliestRefreshAt : null ,
1670+ scopes : [ "chatgpt.tokens.use.direct" ] ,
1671+ } ;
1672+ const environmentId = EnvironmentId . make ( "00000000-0000-4000-8000-000000000001" ) ;
1673+ const http = HttpClient . make ( ( request ) =>
1674+ Effect . gen ( function * ( ) {
1675+ if ( request . url . endsWith ( "openid-configuration" ) ) {
1676+ return HttpClientResponse . fromWeb (
1677+ request ,
1678+ Response . json ( {
1679+ issuer : "https://auth.openai.com" ,
1680+ authorization_endpoint : "https://auth.openai.com/authorize" ,
1681+ token_endpoint : "https://auth.openai.com/token" ,
1682+ jwks_uri : "https://auth.openai.com/jwks" ,
1683+ } ) ,
1684+ ) ;
1685+ }
1686+ assert . equal ( request . url , "https://auth.openai.com/token" ) ;
1687+ assert . equal ( request . body . _tag , "Uint8Array" ) ;
1688+ if ( request . body . _tag !== "Uint8Array" ) return yield * Effect . die ( "Missing refresh body" ) ;
1689+ const body = new URLSearchParams ( new TextDecoder ( ) . decode ( request . body . body ) ) ;
1690+ refreshTokens . push ( body . get ( "refresh_token" ) ! ) ;
1691+ yield * Deferred . succeed ( oauthEntered , undefined ) ;
1692+ if ( pauseOAuth ) yield * Deferred . await ( oauthRelease ) ;
1693+ return HttpClientResponse . fromWeb (
1694+ request ,
1695+ Response . json ( {
1696+ access_token : "renewed-access" ,
1697+ refresh_token : "rotated-refresh" ,
1698+ expires_in : 3600 ,
1699+ token_type : "Bearer" ,
1700+ scope : "chatgpt.tokens.use.direct" ,
1701+ } ) ,
1702+ ) ;
1703+ } ) ,
1704+ ) ;
1705+ return yield * Effect . gen ( function * ( ) {
1706+ const store = yield * ProviderCredentialStore . make ( "codex-chatgpt" , instanceId ) ;
1707+ yield * store . set ( new TextEncoder ( ) . encode ( JSON . stringify ( credentials ) ) ) ;
1708+ const auth = yield * makeCodexChatGptAuth ( { instanceId } ) ;
1709+ const profileKey = yield * auth . profileKey ( credentials ) ;
1710+ const scope = yield * Scope . make ( ) ;
1711+ yield * Effect . addFinalizer ( ( exit ) => Scope . close ( scope , exit ) ) ;
1712+ const context = yield * Layer . buildWithScope ( CodexManagedTokenBroker . layer , scope ) ;
1713+ const broker = Context . get ( context , CodexManagedTokenBroker . CodexManagedTokenBroker ) ;
1714+ const endpoint = yield * broker . endpoint ;
1715+ yield * Effect . addFinalizer ( ( ) => Deferred . succeed ( oauthRelease , undefined ) ) ;
1716+ return {
1717+ auth,
1718+ store,
1719+ broker,
1720+ endpoint,
1721+ refreshTokens,
1722+ request : { version : 1 , instanceId, environmentId, profileKey } ,
1723+ oauthEntered,
1724+ oauthRelease,
1725+ pause : ( ) => {
1726+ pauseOAuth = true ;
1727+ } ,
1728+ } ;
1729+ } ) . pipe (
1730+ Effect . provide ( ServerSecretStore . layer ) ,
1731+ Effect . provideService ( HttpClient . HttpClient , http ) ,
1732+ Effect . provideService ( ServerEnvironment . ServerEnvironmentIdentity , {
1733+ getEnvironmentId : Effect . succeed ( environmentId ) ,
1734+ } ) ,
1735+ ) ;
1736+ } ) ;
1737+
1738+ const brokerClient = ( endpoint : string , request : unknown ) =>
1739+ Effect . acquireRelease (
1740+ Effect . callback < { socket : NodeNet . Socket ; response : Promise < string > } , Error > ( ( resume ) => {
1741+ const socket = NodeNet . createConnection ( endpoint ) ;
1742+ let text = "" ;
1743+ socket . setEncoding ( "utf8" ) ;
1744+ socket . on ( "data" , ( chunk ) => {
1745+ text += chunk ;
1746+ } ) ;
1747+ const response = new Promise < string > ( ( resolve ) => socket . once ( "close" , ( ) => resolve ( text ) ) ) ;
1748+ socket . on ( "error" , ( ) => { } ) ;
1749+ socket . once ( "error" , ( error ) => resume ( Effect . fail ( error ) ) ) ;
1750+ socket . once ( "connect" , ( ) => {
1751+ socket . write ( JSON . stringify ( request ) + "\n" ) ;
1752+ resume ( Effect . succeed ( { socket, response } ) ) ;
1753+ } ) ;
1754+ return Effect . sync ( ( ) => {
1755+ if ( socket . connecting ) socket . destroy ( ) ;
1756+ } ) ;
1757+ } ) ,
1758+ ( { socket } ) => Effect . sync ( ( ) => socket . destroy ( ) ) ,
1759+ ) ;
1760+ const provideBroker = < A , E , R > ( effect : Effect . Effect < A , E , R > ) =>
1761+ effect . pipe (
1762+ Effect . scoped ,
1763+ Effect . provide (
1764+ ServerConfig . layerTest ( process . cwd ( ) , { prefix : "t3-renewal-test-" } ) . pipe (
1765+ Layer . provideMerge ( NodeServices . layer ) ,
1766+ ) ,
1767+ ) ,
1768+ ) ;
1769+
1770+ // regression: #16132 a renewal must outlive the Codex helper that asked for it, because the
1771+ // refresh token it spends is single-use.
1772+ it . effect ( "server-owned renewal persists rotated credentials after the helper disconnects" , ( ) =>
1773+ provideBroker (
1774+ Effect . gen ( function * ( ) {
1775+ const h = yield * makeRenewalBroker ;
1776+ h . pause ( ) ;
1777+ const client = yield * brokerClient ( h . endpoint , h . request ) ;
1778+ yield * Deferred . await ( h . oauthEntered ) ;
1779+ client . socket . destroy ( ) ;
1780+ yield * Effect . promise ( ( ) => client . response ) ;
1781+ assert . equal ( Option . getOrThrow ( yield * h . auth . read ) . refreshToken , "single-use-refresh" ) ;
1782+ yield * Deferred . succeed ( h . oauthRelease , undefined ) ;
1783+ yield * h . broker . awaitIdle ;
1784+ const persisted = Option . getOrThrow ( yield * h . auth . read ) ;
1785+ assert . equal ( persisted . refreshToken , "rotated-refresh" ) ;
1786+ assert . equal ( ( yield * h . auth . access ) . accessToken , "renewed-access" ) ;
1787+ assert . deepEqual ( h . refreshTokens , [ "single-use-refresh" ] ) ;
1788+ } ) ,
1789+ ) ,
1790+ ) ;
1791+
1792+ it . live ( "the private broker refuses another environment, instance, or sign-in profile" , ( ) =>
1793+ provideBroker (
1794+ Effect . gen ( function * ( ) {
1795+ const h = yield * makeRenewalBroker ;
1796+ yield * Effect . forEach (
1797+ [
1798+ {
1799+ ...h . request ,
1800+ environmentId : EnvironmentId . make ( "00000000-0000-4000-8000-000000000002" ) ,
1801+ } ,
1802+ { ...h . request , instanceId : ProviderInstanceId . make ( "another-instance" ) } ,
1803+ { ...h . request , profileKey : "0" . repeat ( 64 ) } ,
1804+ ] ,
1805+ ( request ) =>
1806+ Effect . scoped (
1807+ Effect . gen ( function * ( ) {
1808+ const client = yield * brokerClient ( h . endpoint , request ) ;
1809+ assert . equal ( yield * Effect . promise ( ( ) => client . response ) , "" ) ;
1810+ } ) ,
1811+ ) ,
1812+ ) ;
1813+ yield * h . broker . awaitIdle ;
1814+ assert . deepEqual ( h . refreshTokens , [ ] ) ;
1815+ const client = yield * brokerClient ( h . endpoint , h . request ) ;
1816+ assert . deepEqual ( JSON . parse ( yield * Effect . promise ( ( ) => client . response ) ) , {
1817+ token : "renewed-access" ,
1818+ } ) ;
1819+ yield * h . broker . awaitIdle ;
1820+ assert . deepEqual ( h . refreshTokens , [ "single-use-refresh" ] ) ;
1821+ } ) ,
1822+ ) ,
1823+ ) ;
0 commit comments