@@ -38,26 +38,58 @@ export function hexEncode(str: string): string {
3838
3939 return returnStr ;
4040}
41- export const pouchDBincludeCredentialsConfig : PouchDB . Configuration . RemoteDatabaseConfiguration = {
41+ const pouchDBincludeCredentialsConfig : PouchDB . Configuration . RemoteDatabaseConfiguration = {
4242 fetch ( url : string | Request , opts : RequestInit ) : Promise < Response > {
4343 opts . credentials = 'include' ;
4444
4545 return ( pouch as any ) . fetch ( url , opts ) ;
4646 } ,
4747} as PouchDB . Configuration . RemoteDatabaseConfiguration ;
4848
49+ /**
50+ * Creates PouchDB configuration with appropriate authentication method
51+ * - Uses HTTP Basic Auth when credentials are available (Node.js/MCP)
52+ * - Falls back to cookie auth for browser environments
53+ */
54+ export function createPouchDBConfig ( ) : PouchDB . Configuration . RemoteDatabaseConfiguration {
55+ // Check if running in Node.js with explicit credentials
56+ const hasExplicitCredentials = ENV . COUCHDB_USERNAME && ENV . COUCHDB_PASSWORD ;
57+ const isNodeEnvironment = typeof window === 'undefined' ;
58+
59+ if ( hasExplicitCredentials && isNodeEnvironment ) {
60+ // Use HTTP Basic Auth for Node.js environments (MCP server)
61+ return {
62+ fetch ( url : string | Request , opts : RequestInit = { } ) : Promise < Response > {
63+ const basicAuth = btoa ( `${ ENV . COUCHDB_USERNAME } :${ ENV . COUCHDB_PASSWORD } ` ) ;
64+ const headers = new Headers ( opts . headers || { } ) ;
65+ headers . set ( 'Authorization' , `Basic ${ basicAuth } ` ) ;
66+
67+ const newOpts = {
68+ ...opts ,
69+ headers : headers
70+ } ;
71+
72+ return ( pouch as any ) . fetch ( url , newOpts ) ;
73+ }
74+ } as PouchDB . Configuration . RemoteDatabaseConfiguration ;
75+ }
76+
77+ // Use cookie-based auth for browser environments or when no explicit credentials
78+ return pouchDBincludeCredentialsConfig ;
79+ }
80+
4981function getCouchDB ( dbName : string ) : PouchDB . Database {
5082 return new pouch (
5183 ENV . COUCHDB_SERVER_PROTOCOL + '://' + ENV . COUCHDB_SERVER_URL + dbName ,
52- pouchDBincludeCredentialsConfig
84+ createPouchDBConfig ( )
5385 ) ;
5486}
5587
5688export function getCourseDB ( courseID : string ) : PouchDB . Database {
5789 // todo: keep a cache of opened courseDBs? need to benchmark this somehow
5890 return new pouch (
5991 ENV . COUCHDB_SERVER_PROTOCOL + '://' + ENV . COUCHDB_SERVER_URL + 'coursedb-' + courseID ,
60- pouchDBincludeCredentialsConfig
92+ createPouchDBConfig ( )
6193 ) ;
6294}
6395
@@ -188,7 +220,7 @@ export function getCouchUserDB(username: string): PouchDB.Database {
188220 // see: https://github.com/pouchdb-community/pouchdb-authentication/issues/239
189221 const ret = new pouch (
190222 ENV . COUCHDB_SERVER_PROTOCOL + '://' + ENV . COUCHDB_SERVER_URL + dbName ,
191- pouchDBincludeCredentialsConfig
223+ createPouchDBConfig ( )
192224 ) ;
193225 if ( guestAccount ) {
194226 updateGuestAccountExpirationDate ( ret ) ;
0 commit comments