@johnhenry/wsh 0.48.0 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +122 -30
- package/package.json +17 -3
- package/spec/capabilities.md +174 -0
- package/spec/capabilities.vectors.json +200 -0
- package/spec/key-options.vectors.json +248 -0
- package/spec/message-matrix.md +259 -0
- package/spec/wsh-v1.md +1607 -0
- package/spec/wsh-v1.yaml +2775 -0
- package/src/auth.mjs +3 -34
- package/src/capabilities.d.ts +53 -0
- package/src/capabilities.mjs +69 -0
- package/src/gateway-errors.mjs +45 -0
- package/src/identity.d.ts +61 -0
- package/src/identity.mjs +194 -0
- package/src/index.d.ts +11 -0
- package/src/index.mjs +1 -0
- package/src/key-names.mjs +115 -0
- package/src/key-options.mjs +2 -0
- package/src/mcp-duplex.mjs +184 -0
- package/src/memory-host.d.ts +5 -0
- package/src/memory-host.mjs +3 -2
- package/src/objects-core.mjs +31 -8
- package/src/objects.d.ts +18 -5
- package/src/objects.mjs +4 -1
- package/src/page-host.d.ts +46 -2
- package/src/page-host.mjs +10 -2
- package/src/server/connection.mjs +4 -1
- package/src/server/gateway-core.mjs +4 -4
- package/src/testing-doubles.mjs +115 -0
- package/src/testing.d.ts +44 -0
- package/src/testing.mjs +3 -0
- package/src/transport.mjs +1 -1
- package/src/webmcp.mjs +8 -4
package/src/auth.mjs
CHANGED
|
@@ -465,31 +465,9 @@ export async function podId(publicKeyRaw) {
|
|
|
465
465
|
return base64urlEncode(new Uint8Array(hash));
|
|
466
466
|
}
|
|
467
467
|
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
* @returns {string} base64url pod ID
|
|
472
|
-
*/
|
|
473
|
-
export function fingerprintToPodId(hexFingerprint) {
|
|
474
|
-
if (typeof hexFingerprint !== 'string' || !/^(?:[0-9a-fA-F]{2})+$/.test(hexFingerprint)) {
|
|
475
|
-
throw new TypeError('fingerprintToPodId: expected a hex fingerprint');
|
|
476
|
-
}
|
|
477
|
-
const bytes = new Uint8Array(hexFingerprint.length / 2);
|
|
478
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
479
|
-
bytes[i] = parseInt(hexFingerprint.slice(i * 2, i * 2 + 2), 16);
|
|
480
|
-
}
|
|
481
|
-
return base64urlEncode(bytes);
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
/**
|
|
485
|
-
* Convert a base64url pod ID to a hex fingerprint.
|
|
486
|
-
* @param {string} podIdStr - base64url pod ID
|
|
487
|
-
* @returns {string} hex fingerprint
|
|
488
|
-
*/
|
|
489
|
-
export function podIdToFingerprint(podIdStr) {
|
|
490
|
-
const bytes = base64urlDecode(podIdStr);
|
|
491
|
-
return hexEncode(bytes);
|
|
492
|
-
}
|
|
468
|
+
// The two conversions between a fingerprint and a pod id live in `key-names.mjs` (pure, no crypto), so that the object and MCP layers
|
|
469
|
+
// can use them without this file; they are the same functions, and strict: exactly a 32-byte hash, in its canonical spelling.
|
|
470
|
+
export { fingerprintToPodId, podIdToFingerprint } from './key-names.mjs';
|
|
493
471
|
|
|
494
472
|
/**
|
|
495
473
|
* Get the shortest unique prefix of a fingerprint within a set.
|
|
@@ -529,15 +507,6 @@ function base64urlEncode(bytes) {
|
|
|
529
507
|
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
530
508
|
}
|
|
531
509
|
|
|
532
|
-
function base64urlDecode(str) {
|
|
533
|
-
let b64 = str.replace(/-/g, '+').replace(/_/g, '/');
|
|
534
|
-
while (b64.length % 4) b64 += '=';
|
|
535
|
-
const binary = atob(b64);
|
|
536
|
-
const bytes = new Uint8Array(binary.length);
|
|
537
|
-
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
538
|
-
return bytes;
|
|
539
|
-
}
|
|
540
|
-
|
|
541
510
|
function base64Encode(bytes) {
|
|
542
511
|
let binary = '';
|
|
543
512
|
for (const b of bytes) binary += String.fromCharCode(b);
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/capabilities`: the notation of key capabilities as a pure function. The notation is written in
|
|
3
|
+
* `spec/capabilities.md` and its vectors in `spec/capabilities.vectors.json` (both in the package, under `@johnhenry/wsh/spec/`).
|
|
4
|
+
* Browser-safe (no Node import); a stable entry point.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** A request a capability list is asked about; the kinds, and what each needs, are in `spec/capabilities.md`. */
|
|
8
|
+
export type CapabilityRequest =
|
|
9
|
+
| { kind: 'login' }
|
|
10
|
+
| { kind: 'open'; channel: 'pty' | 'exec'; target?: string }
|
|
11
|
+
| { kind: 'open'; channel: 'file'; direction: 'upload' | 'download'; target?: string }
|
|
12
|
+
| { kind: 'open'; channel: 'rpc'; protocol: string; scoped?: boolean; target?: string }
|
|
13
|
+
| { kind: 'file-op'; op: string; target?: string }
|
|
14
|
+
| { kind: 'mcp' }
|
|
15
|
+
| { kind: 'mcp-call' | 'mcp-tool'; tool: string }
|
|
16
|
+
| { kind: 'objects'; root: string; op: 'get' | 'call' | 'set' | 'on' | 'walk' }
|
|
17
|
+
| { kind: 'relay' }
|
|
18
|
+
| { kind: 'key-admin' }
|
|
19
|
+
| { kind: 'tcp' | 'udp'; host: string; port: number }
|
|
20
|
+
| { kind: 'dns'; name: string }
|
|
21
|
+
| { kind: 'listen-tcp'; port: number }
|
|
22
|
+
| { kind: 'unix' | 'listen-unix'; path: string }
|
|
23
|
+
| { kind: 'endpoint'; name: string; target?: string }
|
|
24
|
+
| { kind: 'target'; name: string };
|
|
25
|
+
|
|
26
|
+
export interface CapabilityRefusal {
|
|
27
|
+
/** `capability-missing` (see `capability`), `key-expired`, `key-admin-not-permitted`, or `unknown-capability` / `bad-capability` for a list with an entry that is not understood (the whole list is refused). */
|
|
28
|
+
code: string;
|
|
29
|
+
reason: string;
|
|
30
|
+
/** The capability that was needed, for `capability-missing`. */
|
|
31
|
+
capability?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CapabilityOptions {
|
|
35
|
+
/** An RFC 3339 string, a `Date` or epoch milliseconds: the instant from which the list is refused. */
|
|
36
|
+
expires?: string | Date | number;
|
|
37
|
+
/** A `Date` or epoch milliseconds (default: the present). */
|
|
38
|
+
now?: Date | number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The revision of the notation implemented here: the `version` of `spec/capabilities.vectors.json`. */
|
|
42
|
+
export const CAPABILITIES_NOTATION_VERSION: 1;
|
|
43
|
+
|
|
44
|
+
/** Parse a capability list; `{ ok: false, code, reason }` for an entry that is unknown or malformed. */
|
|
45
|
+
export function parseCapabilityList(list: string | string[]):
|
|
46
|
+
| { ok: true; capabilities: string[]; parsed: object[] }
|
|
47
|
+
| { ok: false; code: string; reason: string };
|
|
48
|
+
|
|
49
|
+
/** `null` when a holder of `capabilities` may make `request`, else why not. Fails closed. */
|
|
50
|
+
export function checkCapabilities(capabilities: string[] | string, request: CapabilityRequest, options?: CapabilityOptions): CapabilityRefusal | null;
|
|
51
|
+
|
|
52
|
+
/** Whether a holder of `capabilities` may make `request`. A list with an entry that is not understood, no list, or an unknown request kind permits nothing. */
|
|
53
|
+
export function permits(capabilities: string[] | string, request: CapabilityRequest, options?: CapabilityOptions): boolean;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/capabilities` -- the notation of key capabilities, as a pure function (browser-safe, no Node import).
|
|
3
|
+
*
|
|
4
|
+
* import { permits } from '@johnhenry/wsh/capabilities';
|
|
5
|
+
* permits(['exec', 'gateway:tcp:*.example.com:443', 'objects:window:get'], { kind: 'tcp', host: 'api.example.com', port: 443 }); // true
|
|
6
|
+
*
|
|
7
|
+
* What a list means (the grammar, what each wildcard matches, the request kinds and what each needs, and what an
|
|
8
|
+
* implementation does with something it does not understand) is written in `spec/capabilities.md`, and
|
|
9
|
+
* `spec/capabilities.vectors.json` holds the vectors that the JS evaluation and the Rust `wsh-server` both run. Both files are
|
|
10
|
+
* published in the package (`@johnhenry/wsh/spec/capabilities.md`, `@johnhenry/wsh/spec/capabilities.vectors.json`), so another
|
|
11
|
+
* implementation can run the same vectors.
|
|
12
|
+
*
|
|
13
|
+
* This is the same evaluation `@johnhenry/wsh/server`, the memory host and the page host run for a key's `capabilities="..."`;
|
|
14
|
+
* it is exported so a registry of grants in another system (a mesh peer's) can use it instead of keeping a second reading
|
|
15
|
+
* of the notation.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { grantPermissions, checkKeyRequest, parseCapabilityList } from './key-options.mjs';
|
|
19
|
+
|
|
20
|
+
/** The revision of the notation these functions implement: the `version` of `spec/capabilities.vectors.json`. */
|
|
21
|
+
export const CAPABILITIES_NOTATION_VERSION = 1;
|
|
22
|
+
|
|
23
|
+
export { parseCapabilityList };
|
|
24
|
+
|
|
25
|
+
/** `Date | epoch milliseconds | RFC 3339 string | undefined` as epoch seconds, or `undefined`. */
|
|
26
|
+
function toSeconds(now) {
|
|
27
|
+
if (now === undefined || now === null) return undefined;
|
|
28
|
+
const ms = now instanceof Date ? now.getTime() : now;
|
|
29
|
+
if (typeof ms !== 'number' || !Number.isFinite(ms)) throw new TypeError('now must be a Date or epoch milliseconds');
|
|
30
|
+
return Math.floor(ms / 1000);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Whether a holder of `capabilities` may make `request`, with the reason when not: `null` when permitted, else `{ code, reason,
|
|
35
|
+
* capability? }`. `code` is `capability-missing` (`capability` names what was needed) or `key-expired`; a list that has an entry
|
|
36
|
+
* this implementation does not understand is refused whole, with its `unknown-capability` or `bad-capability` code (the list
|
|
37
|
+
* permits nothing). `capabilities` that is not an array of strings (including `null` and `undefined`: no list is no grant) is refused
|
|
38
|
+
* as `bad-capability`.
|
|
39
|
+
*
|
|
40
|
+
* @param {string[] | string} capabilities a list of capability strings (a comma separated string is read the same way as `capabilities="..."`)
|
|
41
|
+
* @param {{ kind: string, [field: string]: unknown }} request what is asked; the kinds are in `spec/capabilities.md`
|
|
42
|
+
* @param {{ expires?: string | Date | number, now?: Date | number }} [options] `expires`: an RFC 3339 string, a `Date` or epoch
|
|
43
|
+
* milliseconds, the instant from which the list is refused; `now`: a `Date` or epoch milliseconds (default: the present)
|
|
44
|
+
* @returns {null | { code: string, reason: string, capability?: string }}
|
|
45
|
+
*/
|
|
46
|
+
export function checkCapabilities(capabilities, request, { expires, now } = {}) {
|
|
47
|
+
if (!(Array.isArray(capabilities) || typeof capabilities === 'string')) {
|
|
48
|
+
return { code: 'bad-capability', reason: 'a capability list is an array of strings' };
|
|
49
|
+
}
|
|
50
|
+
if (request === null || typeof request !== 'object' || typeof request.kind !== 'string') {
|
|
51
|
+
return { code: 'capability-missing', reason: 'a request is an object with a kind' };
|
|
52
|
+
}
|
|
53
|
+
const granted = grantPermissions({ capabilities, ...(expires !== undefined ? { expires } : {}) });
|
|
54
|
+
if (!granted.ok) return { code: granted.code, reason: granted.reason };
|
|
55
|
+
return checkKeyRequest(granted.permissions, request, { now: toSeconds(now) });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Whether a holder of `capabilities` may make `request`. Fails closed: a list with an entry this implementation does not
|
|
60
|
+
* understand, a missing list, or a request of a kind it does not know permits nothing. See `checkCapabilities` for the reason.
|
|
61
|
+
*
|
|
62
|
+
* @param {string[] | string} capabilities
|
|
63
|
+
* @param {{ kind: string, [field: string]: unknown }} request
|
|
64
|
+
* @param {{ expires?: string | Date | number, now?: Date | number }} [options]
|
|
65
|
+
* @returns {boolean}
|
|
66
|
+
*/
|
|
67
|
+
export function permits(capabilities, request, options) {
|
|
68
|
+
return checkCapabilities(capabilities, request, options) === null;
|
|
69
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The codes of `GatewayFail` as data, in one place (browser-safe, no Node import). A host puts one of these numbers in `GatewayFail.code`
|
|
3
|
+
* when a gateway request (`OpenTcp`, `OpenUdp`, `ResolveDns`, `OpenEndpoint`, `OpenUnix`) fails; a client reads it back as
|
|
4
|
+
* `GatewayError.code`. The Node gateway, the page host and the memory host send them from this table, and `@johnhenry/browsermesh-netway`
|
|
5
|
+
* decodes them (it keeps a copy by hand: it can import this one instead, the names and numbers are the same).
|
|
6
|
+
*
|
|
7
|
+
* The table is a contract: a code is never reused for something else and a number is never renumbered. A new code is added at the end.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Wire codes of `GatewayFail`, by name. */
|
|
11
|
+
export const GATEWAY_FAIL = Object.freeze({
|
|
12
|
+
CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, TIMEOUT: 5, CLOSED: 6, QUEUE_FULL: 7,
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The same codes with their meaning. `alsoSentAs` lists a second name a different implementation gives the same number: the Rust
|
|
17
|
+
* `wsh-server` sends `5` for "gateway disabled" (and `spec/wsh-v1.yaml` lists `5=GATEWAY_DISABLED`), where the Node gateway sends it for a
|
|
18
|
+
* timeout. A client that reads `5` therefore should say "timed out or disabled" rather than only one of the two.
|
|
19
|
+
*/
|
|
20
|
+
export const GATEWAY_FAIL_TABLE = Object.freeze([
|
|
21
|
+
Object.freeze({ name: 'CONNECTION_REFUSED', code: 1, meaning: 'The destination actively refused the connection (nothing listens there).' }),
|
|
22
|
+
Object.freeze({ name: 'HOST_UNREACHABLE', code: 2, meaning: 'The destination could not be reached on the network (no route, connect failed, socket error).' }),
|
|
23
|
+
Object.freeze({ name: 'DNS_FAILED', code: 3, meaning: 'The name did not resolve, or is not a valid name.' }),
|
|
24
|
+
Object.freeze({ name: 'POLICY_DENIED', code: 4, meaning: 'The host refused by policy: the key lacks the capability, the address is not allowed, the endpoint or target does not exist or is not for this caller, or the request was malformed or reused an id.' }),
|
|
25
|
+
Object.freeze({ name: 'TIMEOUT', code: 5, alsoSentAs: Object.freeze(['GATEWAY_DISABLED']), meaning: 'The host did not finish in time. The Rust wsh-server sends this number when its gateway is disabled.' }),
|
|
26
|
+
Object.freeze({ name: 'CLOSED', code: 6, meaning: 'The gateway connection was closed before the operation finished.' }),
|
|
27
|
+
Object.freeze({ name: 'QUEUE_FULL', code: 7, meaning: 'The host holds too many gateway connections or too much unsent data, and takes no more for now.' }),
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Codes a client gives its own `GatewayError` when it never asked the host: they are not on the wire, and a host never sends them.
|
|
32
|
+
* `UNSUPPORTED`: the host did not advertise the feature the call needs.
|
|
33
|
+
*/
|
|
34
|
+
export const GATEWAY_FAIL_LOCAL = Object.freeze({ UNSUPPORTED: 0 });
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The name of a code (wire or client-local), or `null` for a number that is not in the table.
|
|
38
|
+
* @param {number} code
|
|
39
|
+
* @returns {string | null}
|
|
40
|
+
*/
|
|
41
|
+
export function gatewayFailName(code) {
|
|
42
|
+
for (const row of GATEWAY_FAIL_TABLE) if (row.code === code) return row.name;
|
|
43
|
+
for (const [name, value] of Object.entries(GATEWAY_FAIL_LOCAL)) if (value === code) return name;
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/identity`: a key's identity in its spellings (raw 32-byte key, OpenSSH `ssh-ed25519` line, hex fingerprint, base64url
|
|
3
|
+
* pod id), and a builder of `authorized_keys` lines that refuses unsafe input. Browser-safe (no Node import); a stable entry point.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Who a call is from, whatever carried it: a login name and a key (over wsh), or a pod id (over a mesh). The key's two names are one hash. */
|
|
7
|
+
export interface WshIdentity {
|
|
8
|
+
username: string | null;
|
|
9
|
+
/** 64 lower-case hex digits: the SHA-256 of the caller's raw public key. `null` for a caller with no key. */
|
|
10
|
+
fingerprint: string | null;
|
|
11
|
+
/** 43 base64url characters: the same hash. Derived from `fingerprint` when only that is known, and the other way round. */
|
|
12
|
+
podId: string | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** SHA-256 of a raw Ed25519 public key, as 64 lower-case hex digits. */
|
|
16
|
+
export function fingerprint(publicKeyRaw: Uint8Array): Promise<string>;
|
|
17
|
+
/** SHA-256 of a raw Ed25519 public key, as 43 base64url characters (BrowserMesh's pod id). */
|
|
18
|
+
export function podId(publicKeyRaw: Uint8Array): Promise<string>;
|
|
19
|
+
/** Convert a fingerprint (exactly 64 hex digits, either case) to a pod id. Throws a `TypeError` for anything else. */
|
|
20
|
+
export function fingerprintToPodId(hexFingerprint: string): string;
|
|
21
|
+
/** Convert a pod id (exactly 43 base64url characters, canonical spelling) to a fingerprint. Throws a `TypeError` for anything else. */
|
|
22
|
+
export function podIdToFingerprint(podIdStr: string): string;
|
|
23
|
+
|
|
24
|
+
/** The OpenSSH `ssh-ed25519` line of a raw 32-byte public key (`comment`: no control character or line break). */
|
|
25
|
+
export function rawKeyToOpenSsh(raw: Uint8Array, comment?: string): string;
|
|
26
|
+
/** The OpenSSH `ssh-ed25519` line of a public `CryptoKey`. */
|
|
27
|
+
export function publicKeyToOpenSsh(publicKey: CryptoKey, comment?: string): Promise<string>;
|
|
28
|
+
/** Read a plain `ssh-ed25519 <base64> [comment]` line. Refuses options in front, other key types, trailing bytes, more than one line. */
|
|
29
|
+
export function parseOpenSshKey(line: string): { raw: Uint8Array; comment: string };
|
|
30
|
+
/** The raw 32-byte public key of an OpenSSH `ssh-ed25519` line. */
|
|
31
|
+
export function openSshToRawKey(line: string): Uint8Array;
|
|
32
|
+
|
|
33
|
+
/** One key in every spelling. */
|
|
34
|
+
export function identityOf(key: Uint8Array | string | CryptoKey): Promise<{ raw: Uint8Array; fingerprint: string; podId: string; openssh: string }>;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* An identity as `{ username, fingerprint, podId }`: whichever of `fingerprint` and `podId` is given, the other is derived. Throws a
|
|
38
|
+
* `TypeError` for an identity that names two keys or is malformed (`strict: false` keeps a `fingerprint` that is not a key hash).
|
|
39
|
+
*/
|
|
40
|
+
export function normalizeIdentity(
|
|
41
|
+
who: { username?: string | null; fingerprint?: string | null; podId?: string | null } | null | undefined,
|
|
42
|
+
options?: { strict?: boolean },
|
|
43
|
+
): WshIdentity;
|
|
44
|
+
|
|
45
|
+
export interface AuthorizedKeyLineOptions {
|
|
46
|
+
/** The capabilities the key holds (`spec/capabilities.md`); `[]` for a key that may do nothing. Required unless `allowFullAccess`. */
|
|
47
|
+
capabilities?: string[] | string;
|
|
48
|
+
/** When the key stops working: an RFC 3339 string, a `Date` or epoch milliseconds. Written in UTC. */
|
|
49
|
+
expires?: string | Date | number;
|
|
50
|
+
/** Written after the key; no control character or line break. */
|
|
51
|
+
comment?: string;
|
|
52
|
+
/** Say it out loud: a line with no capability list is a key that may do everything. Contradicts `capabilities`. */
|
|
53
|
+
allowFullAccess?: boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A line for an `authorized_keys` file, read back through the host's own parser before it is returned. Throws a `TypeError` for a
|
|
58
|
+
* capability that is not in the notation, a malformed expiry, a comment that could start another line, a key that is not a plain
|
|
59
|
+
* Ed25519 key, or an option it does not write.
|
|
60
|
+
*/
|
|
61
|
+
export function authorizedKeyLine(key: Uint8Array | string, options: AuthorizedKeyLineOptions): string;
|
package/src/identity.mjs
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/identity` -- a key's identity in its spellings, in one stable, browser-safe module (no Node import).
|
|
3
|
+
*
|
|
4
|
+
* One Ed25519 public key has these names:
|
|
5
|
+
*
|
|
6
|
+
* raw key the 32 bytes (`Uint8Array`), what WebCrypto exports as `'raw'`
|
|
7
|
+
* OpenSSH line `ssh-ed25519 AAAAC3Nza... comment`: what `authorized_keys` and `ssh-keygen` write
|
|
8
|
+
* fingerprint the SHA-256 of the raw key, 64 lower-case hex digits: what wsh logs, pins and passes to `authorize()`
|
|
9
|
+
* pod id the same 32 bytes of SHA-256, as 43 characters of base64url: what BrowserMesh calls a pod
|
|
10
|
+
*
|
|
11
|
+
* The fingerprint and the pod id are two spellings of one hash (so they convert in both directions without the key), and both are
|
|
12
|
+
* derived from the raw key (so they cannot be turned back into it). The OpenSSH line and the raw key are one value in two spellings.
|
|
13
|
+
*
|
|
14
|
+
* ```js
|
|
15
|
+
* import { identityOf, authorizedKeyLine } from '@johnhenry/wsh/identity';
|
|
16
|
+
* const { fingerprint, podId } = await identityOf('ssh-ed25519 AAAAC3Nza...');
|
|
17
|
+
* const line = authorizedKeyLine(rawKey, { capabilities: ['objects:window:get'], expires: '2030-01-01T00:00:00Z', comment: 'mesh peer' });
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* Everything here refuses what is not exactly what it names (a key that is not 32 bytes, a fingerprint that is not a SHA-256, a line
|
|
21
|
+
* that carries options or a second line) rather than convert it into something else.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { fingerprint, podId, exportPublicKeyRaw, base64Decode } from './auth.mjs';
|
|
25
|
+
import { fingerprintToPodId, podIdToFingerprint, normalizeIdentity } from './key-names.mjs';
|
|
26
|
+
import { grantPermissions, parseAuthorizedKeyLine, parseRfc3339 } from './key-options.mjs';
|
|
27
|
+
|
|
28
|
+
export { fingerprint, podId, fingerprintToPodId, podIdToFingerprint, normalizeIdentity };
|
|
29
|
+
|
|
30
|
+
const KEY_TYPE = 'ssh-ed25519';
|
|
31
|
+
const TYPE_BYTES = new TextEncoder().encode(KEY_TYPE);
|
|
32
|
+
const WIRE_LENGTH = 4 + TYPE_BYTES.length + 4 + 32;
|
|
33
|
+
// Anything that could end a line or start another: C0 and C1 controls, DEL, and the Unicode line and paragraph separators
|
|
34
|
+
// (written with their code points, so that no separator character sits in the source of a regular expression).
|
|
35
|
+
const LINE_BREAKING = new RegExp(`[\\u0000-\\u001f\\u007f-\\u009f${String.fromCharCode(0x2028)}${String.fromCharCode(0x2029)}]`);
|
|
36
|
+
|
|
37
|
+
const isRawKey = (raw) => raw instanceof Uint8Array && raw.byteLength === 32;
|
|
38
|
+
|
|
39
|
+
function base64(bytes) {
|
|
40
|
+
let binary = '';
|
|
41
|
+
for (const b of bytes) binary += String.fromCharCode(b);
|
|
42
|
+
return btoa(binary);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function checkComment(comment, who) {
|
|
46
|
+
if (comment === undefined || comment === '') return '';
|
|
47
|
+
if (typeof comment !== 'string') throw new TypeError(`${who}: the comment must be a string`);
|
|
48
|
+
if (LINE_BREAKING.test(comment)) throw new TypeError(`${who}: the comment may not contain a control character or a line break (it could start another line)`);
|
|
49
|
+
return comment;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The OpenSSH `ssh-ed25519` line of a raw public key.
|
|
54
|
+
* @param {Uint8Array} raw exactly 32 bytes
|
|
55
|
+
* @param {string} [comment] appended after the key; no control character or line break
|
|
56
|
+
* @returns {string}
|
|
57
|
+
*/
|
|
58
|
+
export function rawKeyToOpenSsh(raw, comment) {
|
|
59
|
+
if (!isRawKey(raw)) throw new TypeError('rawKeyToOpenSsh: expected a Uint8Array of exactly 32 bytes (an Ed25519 public key)');
|
|
60
|
+
const note = checkComment(comment, 'rawKeyToOpenSsh');
|
|
61
|
+
const wire = new Uint8Array(WIRE_LENGTH);
|
|
62
|
+
const view = new DataView(wire.buffer);
|
|
63
|
+
view.setUint32(0, TYPE_BYTES.length);
|
|
64
|
+
wire.set(TYPE_BYTES, 4);
|
|
65
|
+
view.setUint32(4 + TYPE_BYTES.length, 32);
|
|
66
|
+
wire.set(raw, 8 + TYPE_BYTES.length);
|
|
67
|
+
return `${KEY_TYPE} ${base64(wire)}${note ? ` ${note}` : ''}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The OpenSSH line of a public `CryptoKey`.
|
|
72
|
+
* @param {CryptoKey} publicKey an extractable Ed25519 public key
|
|
73
|
+
* @param {string} [comment]
|
|
74
|
+
* @returns {Promise<string>}
|
|
75
|
+
*/
|
|
76
|
+
export async function publicKeyToOpenSsh(publicKey, comment) {
|
|
77
|
+
return rawKeyToOpenSsh(await exportPublicKeyRaw(publicKey), comment);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Read an OpenSSH `ssh-ed25519` public key line: the raw key and the comment. Only a plain key is read: no options in front (those are
|
|
82
|
+
* `authorized_keys` syntax, see `parseAuthorizedKeyLine`), no other key type, nothing after the 32 bytes of the key inside, one line.
|
|
83
|
+
* @param {string} line `ssh-ed25519 <base64> [comment]`
|
|
84
|
+
* @returns {{ raw: Uint8Array, comment: string }}
|
|
85
|
+
*/
|
|
86
|
+
export function parseOpenSshKey(line) {
|
|
87
|
+
if (typeof line !== 'string') throw new TypeError('parseOpenSshKey: expected an ssh-ed25519 line');
|
|
88
|
+
const text = line.endsWith('\n') ? line.slice(0, -1) : line;
|
|
89
|
+
if (LINE_BREAKING.test(text)) throw new TypeError('parseOpenSshKey: expected one line with no control character');
|
|
90
|
+
const m = /^ssh-ed25519 ([A-Za-z0-9+/]+={0,2})(?: (.*))?$/.exec(text);
|
|
91
|
+
if (!m) throw new TypeError('parseOpenSshKey: expected "ssh-ed25519 <base64> [comment]" (a key with options in front is an authorized_keys line, not a key)');
|
|
92
|
+
let wire;
|
|
93
|
+
try { wire = base64Decode(m[1]); } catch { throw new TypeError('parseOpenSshKey: the key is not base64'); }
|
|
94
|
+
if (base64(wire) !== m[1]) throw new TypeError('parseOpenSshKey: the key is not in the canonical base64 spelling');
|
|
95
|
+
if (wire.byteLength !== WIRE_LENGTH) throw new TypeError('parseOpenSshKey: not an Ed25519 key (the wire form of one is exactly 51 bytes)');
|
|
96
|
+
const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
|
|
97
|
+
const typeLength = view.getUint32(0);
|
|
98
|
+
const typeOk = typeLength === TYPE_BYTES.length && TYPE_BYTES.every((b, i) => wire[4 + i] === b);
|
|
99
|
+
if (!typeOk || view.getUint32(4 + TYPE_BYTES.length) !== 32) throw new TypeError('parseOpenSshKey: the key inside the line is not an ssh-ed25519 key');
|
|
100
|
+
return { raw: wire.slice(8 + TYPE_BYTES.length), comment: m[2] ?? '' };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The raw 32-byte public key of an OpenSSH `ssh-ed25519` line (what `parseOpenSshKey` reads; the comment is dropped).
|
|
105
|
+
* @param {string} line
|
|
106
|
+
* @returns {Uint8Array}
|
|
107
|
+
*/
|
|
108
|
+
export function openSshToRawKey(line) {
|
|
109
|
+
return parseOpenSshKey(line).raw;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* One key in every spelling: `{ raw, fingerprint, podId, openssh }`.
|
|
114
|
+
* @param {Uint8Array | string | CryptoKey} key a raw 32-byte key, an OpenSSH `ssh-ed25519` line, or a public `CryptoKey`
|
|
115
|
+
* @returns {Promise<{ raw: Uint8Array, fingerprint: string, podId: string, openssh: string }>}
|
|
116
|
+
*/
|
|
117
|
+
export async function identityOf(key) {
|
|
118
|
+
let raw;
|
|
119
|
+
if (typeof key === 'string') raw = openSshToRawKey(key);
|
|
120
|
+
else if (isRawKey(key)) raw = key.slice();
|
|
121
|
+
else if (typeof CryptoKey !== 'undefined' && key instanceof CryptoKey) raw = await exportPublicKeyRaw(key);
|
|
122
|
+
else throw new TypeError('identityOf: expected a raw 32-byte key, an ssh-ed25519 line or a public CryptoKey');
|
|
123
|
+
const fp = await fingerprint(raw);
|
|
124
|
+
return { raw, fingerprint: fp, podId: fingerprintToPodId(fp), openssh: rawKeyToOpenSsh(raw) };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const LINE_OPTIONS = new Set(['capabilities', 'expires', 'comment', 'allowFullAccess']);
|
|
128
|
+
|
|
129
|
+
/** `Date | epoch milliseconds | RFC 3339 string` as the canonical `YYYY-MM-DDTHH:MM:SSZ`, or a TypeError. */
|
|
130
|
+
function canonicalExpiry(expires) {
|
|
131
|
+
let seconds = null;
|
|
132
|
+
if (typeof expires === 'string') seconds = parseRfc3339(expires);
|
|
133
|
+
else if (expires instanceof Date) seconds = Number.isFinite(expires.getTime()) ? Math.floor(expires.getTime() / 1000) : null;
|
|
134
|
+
else if (typeof expires === 'number') seconds = Number.isFinite(expires) ? Math.floor(expires / 1000) : null;
|
|
135
|
+
// The grammar starts in 1970, and the text of a timestamp holds four digits of year
|
|
136
|
+
if (seconds === null || seconds < 0 || seconds > 253402300799) {
|
|
137
|
+
throw new TypeError('authorizedKeyLine: expires must be an RFC 3339 timestamp such as 2030-01-01T00:00:00Z, a Date, or epoch milliseconds, between 1970 and 9999');
|
|
138
|
+
}
|
|
139
|
+
return new Date(seconds * 1000).toISOString().replace('.000Z', 'Z');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* A line for an `authorized_keys` file: `capabilities="..."[,expires="..."] ssh-ed25519 <key> [comment]`. Only what it is asked for
|
|
144
|
+
* is written, and it refuses what could grant more:
|
|
145
|
+
*
|
|
146
|
+
* - `capabilities` is required: a line with no limits at all is a key that may do everything, so that is `allowFullAccess: true`
|
|
147
|
+
* said out loud (and then `capabilities` must not be given). `[]` is a key that may do nothing.
|
|
148
|
+
* - every capability must be one this package's notation knows (`spec/capabilities.md`): an entry it does not understand, or one that
|
|
149
|
+
* carries a quote, a comma or whitespace, is refused, naming it, instead of being written for a host to refuse or misread;
|
|
150
|
+
* - `expires` must be a timestamp and is written in UTC, `Z`;
|
|
151
|
+
* - the key must be a plain Ed25519 key (raw bytes or a plain OpenSSH line; the options and the comment of an input line are not
|
|
152
|
+
* carried over); the comment may not hold a control character or line break;
|
|
153
|
+
* - what it wrote is read back through the same parser a host uses, and must give the same capabilities, the same expiry and no other
|
|
154
|
+
* option; if not, it throws.
|
|
155
|
+
*
|
|
156
|
+
* @param {Uint8Array | string} key a raw 32-byte public key, or an OpenSSH `ssh-ed25519` line (use `publicKeyToOpenSsh` for a `CryptoKey`)
|
|
157
|
+
* @param {{ capabilities?: string[] | string, expires?: string | Date | number, comment?: string, allowFullAccess?: boolean }} options
|
|
158
|
+
* @returns {string} one line, no trailing newline
|
|
159
|
+
*/
|
|
160
|
+
export function authorizedKeyLine(key, options) {
|
|
161
|
+
if (options === null || typeof options !== 'object') throw new TypeError('authorizedKeyLine: options { capabilities, expires, comment } are required');
|
|
162
|
+
for (const name of Object.keys(options)) {
|
|
163
|
+
if (!LINE_OPTIONS.has(name)) throw new TypeError(`authorizedKeyLine: unknown option ${JSON.stringify(name)} (this builder writes capabilities, expires and a comment)`);
|
|
164
|
+
}
|
|
165
|
+
const { capabilities, expires, comment, allowFullAccess = false } = options;
|
|
166
|
+
if (allowFullAccess !== true && allowFullAccess !== false) throw new TypeError('authorizedKeyLine: allowFullAccess must be true or false');
|
|
167
|
+
if (capabilities === undefined && !allowFullAccess) {
|
|
168
|
+
throw new TypeError('authorizedKeyLine: capabilities are required (a key line with none may do everything): pass the list, [] for a key that may do nothing, or allowFullAccess: true');
|
|
169
|
+
}
|
|
170
|
+
if (capabilities !== undefined && allowFullAccess) throw new TypeError('authorizedKeyLine: allowFullAccess: true and a capabilities list contradict each other');
|
|
171
|
+
const raw = isRawKey(key) ? key : (typeof key === 'string' ? parseOpenSshKey(key).raw : null);
|
|
172
|
+
if (raw === null) throw new TypeError('authorizedKeyLine: key must be a raw 32-byte Ed25519 key or an ssh-ed25519 line');
|
|
173
|
+
const note = checkComment(comment, 'authorizedKeyLine');
|
|
174
|
+
const written = [];
|
|
175
|
+
let list = null;
|
|
176
|
+
if (capabilities !== undefined) {
|
|
177
|
+
const granted = grantPermissions({ capabilities });
|
|
178
|
+
if (!granted.ok) throw new TypeError(`authorizedKeyLine: ${granted.reason}`);
|
|
179
|
+
list = granted.permissions.capabilities;
|
|
180
|
+
written.push(`capabilities="${list.join(',')}"`);
|
|
181
|
+
}
|
|
182
|
+
const until = expires === undefined ? null : canonicalExpiry(expires);
|
|
183
|
+
if (until !== null) written.push(`expires="${until}"`);
|
|
184
|
+
const line = `${written.length ? `${written.join(',')} ` : ''}${rawKeyToOpenSsh(raw, note)}`;
|
|
185
|
+
// Read it back as a host would.
|
|
186
|
+
const back = parseAuthorizedKeyLine(line);
|
|
187
|
+
const ok = back.permissions
|
|
188
|
+
&& back.key.byteLength === 32 && back.key.every((b, i) => b === raw[i])
|
|
189
|
+
&& JSON.stringify(back.permissions.capabilities) === JSON.stringify(list)
|
|
190
|
+
&& back.permissions.expires === (until === null ? null : parseRfc3339(until))
|
|
191
|
+
&& back.permissions.forcedCommand === null && back.permissions.maxSessions === null;
|
|
192
|
+
if (!ok) throw new TypeError('authorizedKeyLine: the line it built does not read back as the grant that was asked for; refusing to write it');
|
|
193
|
+
return line;
|
|
194
|
+
}
|
package/src/index.d.ts
CHANGED
|
@@ -2251,6 +2251,17 @@ export const GATEWAY_DATAGRAM_FEATURE: 'gateway-datagram';
|
|
|
2251
2251
|
/** A GatewayFail / ListenFail as an Error: `code` 4 = refused by the host's policy, 7 = too many connections, 1 = refused by the target. */
|
|
2252
2252
|
export class GatewayError extends Error { code: number }
|
|
2253
2253
|
|
|
2254
|
+
/** The codes of `GatewayFail` by name (the one table the Node gateway, the page host and netway share). Frozen; a number is never reused. */
|
|
2255
|
+
export const GATEWAY_FAIL: Readonly<{
|
|
2256
|
+
CONNECTION_REFUSED: 1; HOST_UNREACHABLE: 2; DNS_FAILED: 3; POLICY_DENIED: 4; TIMEOUT: 5; CLOSED: 6; QUEUE_FULL: 7;
|
|
2257
|
+
}>;
|
|
2258
|
+
/** The same codes with their meaning; `alsoSentAs` is a second name another implementation gives the number (the Rust server sends `5` for a disabled gateway). */
|
|
2259
|
+
export const GATEWAY_FAIL_TABLE: ReadonlyArray<Readonly<{ name: keyof typeof GATEWAY_FAIL; code: number; meaning: string; alsoSentAs?: readonly string[] }>>;
|
|
2260
|
+
/** Codes a client gives its own `GatewayError` when it never asked the host (not on the wire): `UNSUPPORTED` is `0`, a feature the host did not advertise. */
|
|
2261
|
+
export const GATEWAY_FAIL_LOCAL: Readonly<{ UNSUPPORTED: 0 }>;
|
|
2262
|
+
/** The name of a wire or client-local code, or `null`. */
|
|
2263
|
+
export function gatewayFailName(code: number): string | null;
|
|
2264
|
+
|
|
2254
2265
|
/** The feature a client lists in `Hello.features` and a host in `ServerHello.features` to meter gateway data with `GatewayCredit`. */
|
|
2255
2266
|
export const GATEWAY_CREDIT_FEATURE: 'gateway-credit';
|
|
2256
2267
|
/** Credit, in bytes, each direction of a gateway connection starts with. */
|
package/src/index.mjs
CHANGED
|
@@ -79,6 +79,7 @@ export { WshVirtualSessionBackend, normalizeSessionData } from './virtual-sessio
|
|
|
79
79
|
export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, TARGETS_FEATURE } from './client.mjs';
|
|
80
80
|
// Gateway forwarding (unix sockets, named endpoints, flow control) -- wsh #120, #123
|
|
81
81
|
export { GatewayError } from './gateway-client.mjs';
|
|
82
|
+
export { GATEWAY_FAIL, GATEWAY_FAIL_TABLE, GATEWAY_FAIL_LOCAL, gatewayFailName } from './gateway-errors.mjs';
|
|
82
83
|
export { GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from './gateway-channel.mjs';
|
|
83
84
|
export { GATEWAY_DATAGRAM_FEATURE } from './gateway-datagram.mjs';
|
|
84
85
|
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two names of a key's hash, and the caller identity built from them. Pure functions of strings: no crypto, no Node import, so the
|
|
3
|
+
* object layer, the MCP layer and `@johnhenry/wsh/identity` can all use them without pulling in the key code.
|
|
4
|
+
*
|
|
5
|
+
* A key is named by the SHA-256 of its raw 32-byte Ed25519 public key. wsh writes the 32 bytes as 64 lower-case hex digits (the
|
|
6
|
+
* "fingerprint"); BrowserMesh writes the same 32 bytes as 43 characters of base64url (the "pod id"). They are one name in two
|
|
7
|
+
* spellings, and these functions convert between them and refuse anything that is not exactly such a hash.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const HEX_RE = /^[0-9a-fA-F]{64}$/;
|
|
11
|
+
const B64URL_RE = /^[A-Za-z0-9_-]{43}$/;
|
|
12
|
+
const B64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
13
|
+
|
|
14
|
+
/** @param {string} hex 64 hex digits @returns {string} the 43-character base64url spelling of the same 32 bytes */
|
|
15
|
+
function hexToBase64url(hex) {
|
|
16
|
+
let out = '';
|
|
17
|
+
let acc = 0;
|
|
18
|
+
let bits = 0;
|
|
19
|
+
for (let i = 0; i < hex.length; i += 2) {
|
|
20
|
+
acc = (acc << 8) | parseInt(hex.slice(i, i + 2), 16);
|
|
21
|
+
bits += 8;
|
|
22
|
+
while (bits >= 6) { bits -= 6; out += B64URL_ALPHABET[(acc >> bits) & 63]; }
|
|
23
|
+
acc &= (1 << bits) - 1;
|
|
24
|
+
}
|
|
25
|
+
if (bits > 0) out += B64URL_ALPHABET[(acc << (6 - bits)) & 63];
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {string} id 43 base64url characters @returns {string | null} 64 lower-case hex digits, or null when the last character has bits a 32-byte value cannot have */
|
|
30
|
+
function base64urlToHex(id) {
|
|
31
|
+
let hex = '';
|
|
32
|
+
let acc = 0;
|
|
33
|
+
let bits = 0;
|
|
34
|
+
for (const ch of id) {
|
|
35
|
+
acc = (acc << 6) | B64URL_ALPHABET.indexOf(ch);
|
|
36
|
+
bits += 6;
|
|
37
|
+
if (bits >= 8) { bits -= 8; hex += ((acc >> bits) & 255).toString(16).padStart(2, '0'); acc &= (1 << bits) - 1; }
|
|
38
|
+
}
|
|
39
|
+
// 43 characters are 258 bits: the last two must be zero, or two different ids would name the same key
|
|
40
|
+
return acc === 0 ? hex : null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Convert a hex fingerprint to a base64url pod id.
|
|
45
|
+
* @param {string} hexFingerprint exactly 64 hex digits (either case): the SHA-256 of a raw public key
|
|
46
|
+
* @returns {string} the 43-character base64url pod id
|
|
47
|
+
*/
|
|
48
|
+
export function fingerprintToPodId(hexFingerprint) {
|
|
49
|
+
if (typeof hexFingerprint !== 'string' || !HEX_RE.test(hexFingerprint)) {
|
|
50
|
+
throw new TypeError('fingerprintToPodId: expected a fingerprint of exactly 64 hex digits (the SHA-256 of a public key)');
|
|
51
|
+
}
|
|
52
|
+
return hexToBase64url(hexFingerprint.toLowerCase());
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Convert a base64url pod id to a hex fingerprint.
|
|
57
|
+
* @param {string} podIdStr exactly 43 base64url characters (no padding), in the canonical spelling
|
|
58
|
+
* @returns {string} 64 lower-case hex digits
|
|
59
|
+
*/
|
|
60
|
+
export function podIdToFingerprint(podIdStr) {
|
|
61
|
+
const hex = typeof podIdStr === 'string' && B64URL_RE.test(podIdStr) ? base64urlToHex(podIdStr) : null;
|
|
62
|
+
if (hex === null) throw new TypeError('podIdToFingerprint: expected a pod id of exactly 43 base64url characters (the SHA-256 of a public key)');
|
|
63
|
+
return hex;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Who a call is from, in the one shape every layer of the package uses: `{ username, fingerprint, podId }`. A caller that arrives over
|
|
68
|
+
* wsh has a login name and a key (the hex `fingerprint`); one that arrives over a mesh has a pod id. Both are the hash of the same
|
|
69
|
+
* kind of key, so whichever is given, the other is derived: an `authorize(who, op)` callback written for one world reads the other's
|
|
70
|
+
* callers the same way, and nobody has to put a pod id in a field named `fingerprint`.
|
|
71
|
+
*
|
|
72
|
+
* An identity that names two different keys, or whose `podId` is not a pod id, is refused. A caller with no key (a password login)
|
|
73
|
+
* has `fingerprint: null` and `podId: null`.
|
|
74
|
+
*
|
|
75
|
+
* @param {{ username?: string | null, fingerprint?: string | null, podId?: string | null } | null | undefined} who
|
|
76
|
+
* @param {{ strict?: boolean, derivePodId?: boolean }} [options] `strict: false` keeps a `fingerprint` that is not a key hash as it was
|
|
77
|
+
* given (a host may name its callers some other way) and derives no pod id from it; the default refuses it. `derivePodId: false`
|
|
78
|
+
* derives no pod id from a fingerprint (a `podId` that was given is kept, and always gives the fingerprint): what the object and MCP
|
|
79
|
+
* layers use, so a caller that came in over wsh keeps the `{ username, fingerprint }` it always had.
|
|
80
|
+
* @returns {{ username: string | null, fingerprint: string | null, podId: string | null }}
|
|
81
|
+
*/
|
|
82
|
+
export function normalizeIdentity(who, { strict = true, derivePodId = true } = {}) {
|
|
83
|
+
if (who === null || who === undefined) return { username: null, fingerprint: null, podId: null };
|
|
84
|
+
if (typeof who !== 'object' || Array.isArray(who)) throw new TypeError('an identity is an object { username, fingerprint, podId }');
|
|
85
|
+
const { username = null, fingerprint = null, podId = null } = who;
|
|
86
|
+
if (username !== null && typeof username !== 'string') throw new TypeError('identity.username must be a string or null');
|
|
87
|
+
if (fingerprint !== null && typeof fingerprint !== 'string') throw new TypeError('identity.fingerprint must be a string or null');
|
|
88
|
+
if (podId !== null && typeof podId !== 'string') throw new TypeError('identity.podId must be a string or null');
|
|
89
|
+
let fp = fingerprint === null ? null : (HEX_RE.test(fingerprint) ? fingerprint.toLowerCase() : fingerprint);
|
|
90
|
+
if (fp !== null && !HEX_RE.test(fp) && strict) throw new TypeError('identity.fingerprint must be 64 hex digits (the SHA-256 of a public key)');
|
|
91
|
+
let id = podId;
|
|
92
|
+
if (id !== null) {
|
|
93
|
+
const fromId = podIdToFingerprint(id); // throws for something that is not a pod id
|
|
94
|
+
if (fp !== null && HEX_RE.test(fp) && fp !== fromId) throw new TypeError('identity.fingerprint and identity.podId name different keys');
|
|
95
|
+
if (fp !== null && !HEX_RE.test(fp)) throw new TypeError('identity.fingerprint and identity.podId name different keys');
|
|
96
|
+
fp = fromId;
|
|
97
|
+
} else if (derivePodId && fp !== null && HEX_RE.test(fp)) {
|
|
98
|
+
id = fingerprintToPodId(fp);
|
|
99
|
+
}
|
|
100
|
+
return { username, fingerprint: fp, podId: id };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The identity a layer hands to `authorize(who, op)`, a prompt or an `onCall` callback: what it was given, with `fingerprint` and (when
|
|
105
|
+
* the transport knows it) `podId` agreeing. A caller that arrived over wsh keeps its old shape `{ username, fingerprint }`; one that
|
|
106
|
+
* arrived with only a `podId` (a mesh adapter) also gets the hex `fingerprint`. Extra fields the transport put on it are kept.
|
|
107
|
+
* `undefined` stays `undefined` (no identity given).
|
|
108
|
+
* @param {object | undefined} who
|
|
109
|
+
* @returns {{ username: string | null, fingerprint: string | null, podId?: string } | undefined}
|
|
110
|
+
*/
|
|
111
|
+
export function callerIdentity(who) {
|
|
112
|
+
if (who === undefined) return undefined;
|
|
113
|
+
const n = normalizeIdentity(who, { strict: false, derivePodId: false });
|
|
114
|
+
return { ...who, username: n.username, fingerprint: n.fingerprint, ...(n.podId !== null ? { podId: n.podId } : {}) };
|
|
115
|
+
}
|
package/src/key-options.mjs
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* `authorized_keys` options (wsh #122): what a key's leading options mean, parsed the same way by the Node host (this file) and
|
|
3
3
|
* the Rust `wsh-server` (`crates/wsh-server/src/auth/permissions.rs`). `spec/key-options.vectors.json` holds the shared test
|
|
4
4
|
* vectors both suites run, so the two cannot drift. Browser-safe (no Node imports): the in-memory host uses it too.
|
|
5
|
+
* The notation of capabilities is written in `spec/capabilities.md`, with `spec/capabilities.vectors.json` run by both hosts, and the
|
|
6
|
+
* pure function over it is `permits()` of `@johnhenry/wsh/capabilities`.
|
|
5
7
|
*
|
|
6
8
|
* A line is `[options] ssh-ed25519 <base64> [comment]`. `options` is one token (no whitespace outside double quotes) of
|
|
7
9
|
* comma-separated items, each `name` or `name=value`, where a value is `"..."` (a `\"` is a quote, any other backslash is
|