Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ const server = createServer({key, cert}, () => {
});
```

On the client side, a mechanism is provided to override some of the TLS
internals of node so that fetch will work correctly.

Example:

```js
import {whileCAtrusted} from '@cto.af/ca/client';

const fetchResult = await whileCAtrusted(
{}, // CA options, or a PEM-encoded string with the CA cert.
() => fetch('https://localhost:8001')
);
```

### CLI

A rudimentary CLI is provided.
Expand Down
18 changes: 12 additions & 6 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,17 @@ let currentSym: symbol | undefined = undefined;
* @throws On invalid state.
*/
export async function overrideCreateSecureContext(
options: CertOptions
options: CertOptions | string
): Promise<symbol> {
const CA = new CertificateAuthority(options);
const {ca} = await CA.init();
assert(ca, 'Will always be filled in if no exception thrown');
let cert: string | undefined = undefined;
if (typeof options === 'string') {
cert = options;
} else {
const CA = new CertificateAuthority(options);
const {ca} = await CA.init();
assert(ca, 'Will always be filled in if no exception thrown');
({cert} = ca);
}

assert.equal(
origCsC.name,
Expand All @@ -37,7 +43,7 @@ export async function overrideCreateSecureContext(
tls.createSecureContext =
(opts: tls.SecureContextOptions | undefined): tls.SecureContext => {
const res = origCsC(opts);
res.context.addCACert(ca.cert);
res.context.addCACert(cert);
return res;
};
return currentSym;
Expand Down Expand Up @@ -75,7 +81,7 @@ export function resetCreateSecureContext(sym: symbol): void {
* @returns The result of during.
*/
export async function whileCAtrusted<T>(
options: CertOptions,
options: CertOptions | string,
during: () => T
): Promise<Awaited<T>> {
const sym = await overrideCreateSecureContext(options);
Expand Down
3 changes: 3 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@ test('whileCAtrusted', async () => {
const whileRet = await whileCAtrusted(opts, () => tls.createSecureContext());
assert(whileRet.context);

const certRet = await whileCAtrusted(kc.ca.cert, () => 4);
assert.equal(certRet, 4);

await assert.rejects(async () => {
await whileCAtrusted(opts, () => whileCAtrusted(opts, () => 5));
}, /createSecureContext already hooked/);
Expand Down