or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

asn1.mdasymmetric-cryptography.mdindex.mdlogging.mdmessage-digests.mdnetwork-http.mdpkcs.mdpki.mdrandom.mdsymmetric-encryption.mdtls.mdutilities.mdweb-forms.md

network-http.mddocs/

0

# Network and HTTP Client

1

2

HTTP client implementation with TLS support, cookie management, and XMLHttpRequest interface. This module provides secure HTTP communications using forge's TLS implementation and flash-based socket pooling for cross-browser compatibility.

3

4

**Note:** This module is primarily designed for browser environments and requires Flash plugin support for full functionality.

5

6

## Capabilities

7

8

### XMLHttpRequest Interface

9

10

Standards-compliant XMLHttpRequest implementation using TLS and forge networking.

11

12

```javascript { .api }

13

/**

14

* Initialize the XHR system with configuration options

15

* @param options - Configuration object for XHR initialization

16

*/

17

forge.xhr.init(options: {

18

url?: string; // Default base URL for relative requests

19

flashId: string; // DOM ID of the flash SocketPool element

20

policyPort?: number; // Port for flash policy server (default: 0)

21

policyUrl?: string; // Policy file URL instead of policy port

22

msie?: boolean; // True if browser is Internet Explorer

23

connections?: number; // Maximum concurrent connections (default: 10)

24

caCerts?: string[]; // Array of PEM-formatted CA certificates

25

cipherSuites?: object[]; // TLS cipher suites to use

26

verify?: function; // TLS certificate verification callback

27

getCertificate?: function; // Client certificate callback

28

getPrivateKey?: function; // Client private key callback

29

getSignature?: function; // Client signature callback

30

persistCookies?: boolean; // Use persistent cookies via flash storage

31

primeTlsSockets?: boolean; // Pre-connect TLS sockets for session caching

32

}): void;

33

34

/**

35

* Create a new XMLHttpRequest instance

36

* @param options - Optional configuration for this specific XHR

37

* @returns XMLHttpRequest-compatible object

38

*/

39

forge.xhr.create(options?: {

40

logWarningOnError?: boolean; // Log warnings on HTTP errors

41

verbose?: boolean; // Verbose logging output

42

logError?: function; // Custom error logging function

43

logWarning?: function; // Custom warning logging function

44

logDebug?: function; // Custom debug logging function

45

logVerbose?: function; // Custom verbose logging function

46

url?: string; // Base URL for this XHR (creates new client)

47

policyPort?: number; // Policy port for new client

48

policyUrl?: string; // Policy URL for new client

49

connections?: number; // Max connections for new client

50

caCerts?: string[]; // CA certificates for new client

51

cipherSuites?: object[]; // Cipher suites for new client

52

verify?: function; // Certificate verification for new client

53

getCertificate?: function; // Client certificate for new client

54

getPrivateKey?: function; // Client private key for new client

55

getSignature?: function; // Client signature for new client

56

persistCookies?: boolean; // Cookie persistence for new client

57

primeTlsSockets?: boolean; // Socket priming for new client

58

}): XMLHttpRequest;

59

60

/**

61

* Clean up clients and socket pools

62

*/

63

forge.xhr.cleanup(): void;

64

65

interface XMLHttpRequest {

66

// Standard XMLHttpRequest properties

67

onreadystatechange: (() => void) | null;

68

readyState: number; // UNSENT=0, OPENED=1, HEADERS_RECEIVED=2, LOADING=3, DONE=4

69

responseText: string;

70

responseXML: Document | null;

71

status: number;

72

statusText: string;

73

cookies?: object; // Available cookies (forge extension)

74

75

// Standard XMLHttpRequest methods

76

open(method: string, url: string, async?: boolean, user?: string, password?: string): void;

77

setRequestHeader(header: string, value: string): void;

78

send(data?: string | Document): void;

79

abort(): void;

80

getAllResponseHeaders(): string;

81

getResponseHeader(header: string): string | null;

82

}

83

```

84

85

### HTTP Client

86

87

Lower-level HTTP client with TLS support and connection pooling.

88

89

```javascript { .api }

90

/**

91

* Create an HTTP client with TLS support

92

* @param options - Client configuration options

93

* @returns HTTP client instance

94

*/

95

forge.http.createClient(options: {

96

url: string; // Base URL for the client

97

socketPool: object; // Socket pool instance

98

policyPort?: number; // Flash policy port

99

policyUrl?: string; // Flash policy URL

100

connections?: number; // Maximum concurrent connections

101

caCerts?: string[]; // PEM-formatted CA certificates

102

cipherSuites?: object[]; // TLS cipher suites

103

persistCookies?: boolean; // Enable persistent cookies

104

primeTlsSockets?: boolean; // Prime TLS sockets for performance

105

verify?: function; // Certificate verification callback

106

getCertificate?: function; // Client certificate callback

107

getPrivateKey?: function; // Client private key callback

108

getSignature?: function; // Client signature callback

109

}): HTTPClient;

110

111

interface HTTPClient {

112

url: URL; // Client base URL

113

secure: boolean; // Whether client uses HTTPS

114

115

send(options: {

116

request: HTTPRequest;

117

headerReady?: (event: object) => void;

118

bodyReady?: (event: object) => void;

119

error?: (event: object) => void;

120

}): void;

121

122

setCookie(cookie: Cookie): void;

123

getCookie(name: string, path?: string): Cookie | null;

124

removeCookie(name: string, path?: string): boolean;

125

destroy(): void;

126

}

127

```

128

129

### Cookie Management

130

131

Global cookie management functions for cross-domain scenarios.

132

133

```javascript { .api }

134

/**

135

* Set a cookie that applies to appropriate client domains

136

* @param cookie - Cookie object with properties

137

*/

138

forge.xhr.setCookie(cookie: {

139

name: string; // Cookie name

140

value: string; // Cookie value

141

comment?: string; // Optional comment

142

maxAge?: number; // Age in seconds (-1 for session cookie)

143

secure?: boolean; // Require secure connection

144

httpOnly?: boolean; // Restrict to HTTP (ineffective in JavaScript)

145

path?: string; // Cookie path

146

domain?: string; // Cookie domain (must start with dot)

147

version?: string; // Cookie version

148

created?: number; // Creation time in UTC seconds

149

}): void;

150

151

/**

152

* Get a cookie by name, path, and domain

153

* @param name - Cookie name

154

* @param path - Optional cookie path

155

* @param domain - Optional cookie domain

156

* @returns Cookie object, array of cookies, or null

157

*/

158

forge.xhr.getCookie(name: string, path?: string, domain?: string): Cookie | Cookie[] | null;

159

160

/**

161

* Remove a cookie by name, path, and domain

162

* @param name - Cookie name

163

* @param path - Optional cookie path

164

* @param domain - Optional cookie domain

165

* @returns true if cookie was removed

166

*/

167

forge.xhr.removeCookie(name: string, path?: string, domain?: string): boolean;

168

169

interface Cookie {

170

name: string;

171

value: string;

172

comment?: string;

173

maxAge: number;

174

secure: boolean;

175

httpOnly: boolean;

176

path: string;

177

domain?: string;

178

version?: string;

179

created: number;

180

}

181

```

182

183

## Usage Examples

184

185

### Basic XMLHttpRequest Usage

186

187

```javascript

188

// Initialize the XHR system

189

forge.xhr.init({

190

url: 'https://api.example.com',

191

flashId: 'socketPool',

192

caCerts: [/* PEM certificates */],

193

connections: 5

194

});

195

196

// Create and use an XMLHttpRequest

197

const xhr = forge.xhr.create();

198

xhr.onreadystatechange = function() {

199

if (xhr.readyState === 4) {

200

if (xhr.status === 200) {

201

console.log('Response:', xhr.responseText);

202

} else {

203

console.error('Error:', xhr.status, xhr.statusText);

204

}

205

}

206

};

207

208

xhr.open('GET', '/api/data');

209

xhr.setRequestHeader('Accept', 'application/json');

210

xhr.send();

211

```

212

213

### Advanced Configuration

214

215

```javascript

216

// Initialize with custom TLS settings

217

forge.xhr.init({

218

url: 'https://secure.example.com',

219

flashId: 'secureSocketPool',

220

caCerts: [

221

'-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----'

222

],

223

cipherSuites: [

224

forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA,

225

forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA

226

],

227

verify: function(connection, verified, depth, certs) {

228

// Custom certificate verification

229

return verified;

230

},

231

persistCookies: true,

232

primeTlsSockets: true

233

});

234

235

// Create XHR with custom logging

236

const xhr = forge.xhr.create({

237

verbose: true,

238

logWarningOnError: true,

239

logDebug: function(category, message) {

240

console.log(`[${category}] ${message}`);

241

}

242

});

243

```

244

245

### Cookie Management

246

247

```javascript

248

// Set a cookie for all applicable domains

249

forge.xhr.setCookie({

250

name: 'sessionId',

251

value: 'abc123',

252

maxAge: 3600, // 1 hour

253

secure: true,

254

path: '/',

255

domain: '.example.com'

256

});

257

258

// Get a specific cookie

259

const sessionCookie = forge.xhr.getCookie('sessionId', '/', '.example.com');

260

if (sessionCookie) {

261

console.log('Session ID:', sessionCookie.value);

262

}

263

264

// Remove a cookie

265

const removed = forge.xhr.removeCookie('sessionId', '/', '.example.com');

266

console.log('Cookie removed:', removed);

267

```

268

269

### Cross-Domain Requests

270

271

```javascript

272

// Create XHR for a different domain

273

const crossDomainXhr = forge.xhr.create({

274

url: 'https://api.partner.com',

275

caCerts: [/* Partner's CA certificates */],

276

verify: function(connection, verified, depth, certs) {

277

// Verify partner's certificates

278

return verifyPartnerCert(certs[0]);

279

}

280

});

281

282

crossDomainXhr.open('POST', '/api/partner-data');

283

crossDomainXhr.setRequestHeader('Content-Type', 'application/json');

284

crossDomainXhr.send(JSON.stringify({ data: 'value' }));

285

```

286

287

## Security Considerations

288

289

1. **Certificate Validation**: Always implement proper certificate verification callbacks

290

2. **Flash Dependency**: Requires Flash plugin for socket operations

291

3. **Cookie Security**: Use secure flags and appropriate domains for sensitive cookies

292

4. **TLS Configuration**: Choose strong cipher suites and avoid deprecated protocols

293

5. **Cross-Domain**: Validate policy files and implement proper CORS handling

294

295

## Browser Support

296

297

- **Flash Plugin**: Required for socket pool functionality

298

- **TLS Support**: Uses forge's JavaScript TLS implementation

299

- **Cookie Storage**: Supports both JavaScript and Flash local storage

300

- **CORS**: Handles cross-domain requests through flash policy files