39 lines
1016 B
JavaScript
39 lines
1016 B
JavaScript
/**
|
|
* @file The gate: hands a capability to whoever presents its key.
|
|
* A server listens with a gate, not the capability itself, so a connection gets nothing
|
|
* until it shows the key: open(key) returns the capability, and pipelines, so a client
|
|
* can open and call in one round trip.
|
|
*/
|
|
import { RpcTarget } from 'capnweb';
|
|
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
|
|
const digest = (s) => createHash('sha256').update(String(s)).digest();
|
|
|
|
/**
|
|
* @template T
|
|
*/
|
|
export class Gate extends RpcTarget {
|
|
#want;
|
|
#cap;
|
|
|
|
/**
|
|
* @param {string} key unguessable, from a credential file
|
|
* @param {T} cap what open(key) hands out
|
|
*/
|
|
constructor(key, cap) {
|
|
super();
|
|
this.#want = digest(key);
|
|
this.#cap = cap;
|
|
}
|
|
|
|
/**
|
|
* @param {string} k
|
|
* @returns {T}
|
|
*/
|
|
open(k) {
|
|
// Digests are the same length whatever k is, so the comparison takes the same time.
|
|
if (!timingSafeEqual(digest(k), this.#want)) throw new Error('no such key');
|
|
return this.#cap;
|
|
}
|
|
}
|