@acpantenna/relay-protocol 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +54 -2
- package/dist/bip39-english.d.ts +28 -0
- package/dist/bip39-english.d.ts.map +1 -0
- package/dist/bip39-english.js +28 -0
- package/dist/bip39-english.js.map +1 -0
- package/dist/bytes.d.ts +21 -0
- package/dist/bytes.d.ts.map +1 -0
- package/dist/bytes.js +114 -0
- package/dist/bytes.js.map +1 -0
- package/dist/frames.d.ts +90 -0
- package/dist/frames.d.ts.map +1 -0
- package/dist/frames.js +234 -0
- package/dist/frames.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/link.d.ts +44 -0
- package/dist/link.d.ts.map +1 -0
- package/dist/link.js +120 -0
- package/dist/link.js.map +1 -0
- package/dist/noise.d.ts +181 -0
- package/dist/noise.d.ts.map +1 -0
- package/dist/noise.js +490 -0
- package/dist/noise.js.map +1 -0
- package/dist/relay.d.ts +37 -0
- package/dist/relay.d.ts.map +1 -0
- package/dist/relay.js +70 -0
- package/dist/relay.js.map +1 -0
- package/dist/sas.d.ts +11 -0
- package/dist/sas.d.ts.map +1 -0
- package/dist/sas.js +26 -0
- package/dist/sas.js.map +1 -0
- package/dist/session.d.ts +298 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +608 -0
- package/dist/session.js.map +1 -0
- package/package.json +56 -5
- package/src/bip39-english.ts +30 -0
- package/src/bytes.ts +125 -0
- package/src/frames.ts +278 -0
- package/src/index.ts +14 -0
- package/src/link.ts +160 -0
- package/src/noise.ts +655 -0
- package/src/relay.ts +106 -0
- package/src/sas.ts +28 -0
- package/src/session.ts +848 -0
- package/test-vectors/frames.json +353 -0
- package/test-vectors/noise-kk.json +43 -0
- package/test-vectors/noise-nkpsk0.json +47 -0
- package/test-vectors/sas.json +21 -0
- package/test-vectors/session.json +58 -0
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@acpantenna/relay-protocol",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "acpantenna's relay protocol: Noise NKpsk0 to pair and KK to reconnect, frames, the pairing link and the SAS words. Runs in browsers and Bun.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"bun": "./src/index.ts",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"default": "./dist/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./package.json": "./package.json"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"src",
|
|
21
|
+
"!src/**/*.test.ts",
|
|
22
|
+
"test-vectors",
|
|
23
|
+
"README.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "git+https://github.com/fboldo/acpantenna.git",
|
|
29
|
+
"directory": "packages/relay-protocol"
|
|
30
|
+
},
|
|
31
|
+
"homepage": "https://github.com/fboldo/acpantenna/blob/main/docs/relay-protocol.md",
|
|
32
|
+
"bugs": "https://github.com/fboldo/acpantenna/issues",
|
|
33
|
+
"keywords": [
|
|
34
|
+
"acp",
|
|
35
|
+
"agent-client-protocol",
|
|
36
|
+
"noise",
|
|
37
|
+
"noise-protocol",
|
|
38
|
+
"end-to-end-encryption",
|
|
39
|
+
"relay",
|
|
40
|
+
"websocket"
|
|
41
|
+
],
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && cp ../../LICENSE LICENSE",
|
|
47
|
+
"prepack": "bun run build",
|
|
48
|
+
"check": "bun run typecheck",
|
|
49
|
+
"test": "bun test src",
|
|
50
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@noble/ciphers": "2.4.0",
|
|
54
|
+
"@noble/curves": "2.4.0",
|
|
55
|
+
"@noble/hashes": "2.4.0"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The BIP-39 English wordlist: 2,048 words, used for the short authentication
|
|
3
|
+
* string. From https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt
|
|
4
|
+
* (SHA-256 2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda).
|
|
5
|
+
*
|
|
6
|
+
* BIP-39 is by Marek Palatinus, Pavol Rusnak, Aaron Voisine and Sean Bowe,
|
|
7
|
+
* and is licensed under the MIT License:
|
|
8
|
+
*
|
|
9
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
* of this software and associated documentation files (the "Software"), to
|
|
11
|
+
* deal in the Software without restriction, including without limitation the
|
|
12
|
+
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
|
13
|
+
* sell copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
* furnished to do so, subject to the following conditions:
|
|
15
|
+
*
|
|
16
|
+
* The above copyright notice and this permission notice shall be included in
|
|
17
|
+
* all copies or substantial portions of the Software.
|
|
18
|
+
*
|
|
19
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
24
|
+
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
|
25
|
+
* IN THE SOFTWARE.
|
|
26
|
+
*/
|
|
27
|
+
export const BIP39_ENGLISH: readonly string[] =
|
|
28
|
+
"abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo".split(
|
|
29
|
+
" ",
|
|
30
|
+
);
|
package/src/bytes.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Byte helpers on plain `Uint8Array`s, so the package runs in a browser as
|
|
3
|
+
* well as in Bun.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const encoder = new TextEncoder();
|
|
7
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
8
|
+
|
|
9
|
+
export function concatBytes(...parts: Uint8Array[]): Uint8Array {
|
|
10
|
+
let length = 0;
|
|
11
|
+
for (const part of parts) {
|
|
12
|
+
length += part.length;
|
|
13
|
+
}
|
|
14
|
+
const out = new Uint8Array(length);
|
|
15
|
+
let offset = 0;
|
|
16
|
+
for (const part of parts) {
|
|
17
|
+
out.set(part, offset);
|
|
18
|
+
offset += part.length;
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Compares two byte strings without stopping at the first difference. */
|
|
24
|
+
export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
|
|
25
|
+
if (a.length !== b.length) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
let diff = 0;
|
|
29
|
+
for (let index = 0; index < a.length; index++) {
|
|
30
|
+
diff |= (a[index] ?? 0) ^ (b[index] ?? 0);
|
|
31
|
+
}
|
|
32
|
+
return diff === 0;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function utf8Encode(text: string): Uint8Array {
|
|
36
|
+
return encoder.encode(text);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Decodes UTF-8, throwing on invalid sequences rather than replacing them. */
|
|
40
|
+
export function utf8Decode(bytes: Uint8Array): string {
|
|
41
|
+
return decoder.decode(bytes);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function hexToBytes(hex: string): Uint8Array {
|
|
45
|
+
if (hex.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(hex)) {
|
|
46
|
+
throw new Error("Invalid hex string");
|
|
47
|
+
}
|
|
48
|
+
const out = new Uint8Array(hex.length / 2);
|
|
49
|
+
for (let index = 0; index < out.length; index++) {
|
|
50
|
+
out[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function bytesToHex(bytes: Uint8Array): string {
|
|
56
|
+
let hex = "";
|
|
57
|
+
for (const byte of bytes) {
|
|
58
|
+
hex += byte.toString(16).padStart(2, "0");
|
|
59
|
+
}
|
|
60
|
+
return hex;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const BASE64URL =
|
|
64
|
+
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
65
|
+
|
|
66
|
+
/** Base64url without padding (RFC 4648 §5). */
|
|
67
|
+
export function base64urlEncode(bytes: Uint8Array): string {
|
|
68
|
+
let out = "";
|
|
69
|
+
let index = 0;
|
|
70
|
+
for (; index + 2 < bytes.length; index += 3) {
|
|
71
|
+
const n =
|
|
72
|
+
((bytes[index] ?? 0) << 16) |
|
|
73
|
+
((bytes[index + 1] ?? 0) << 8) |
|
|
74
|
+
(bytes[index + 2] ?? 0);
|
|
75
|
+
out +=
|
|
76
|
+
BASE64URL.charAt((n >> 18) & 63) +
|
|
77
|
+
BASE64URL.charAt((n >> 12) & 63) +
|
|
78
|
+
BASE64URL.charAt((n >> 6) & 63) +
|
|
79
|
+
BASE64URL.charAt(n & 63);
|
|
80
|
+
}
|
|
81
|
+
const rest = bytes.length - index;
|
|
82
|
+
if (rest === 1) {
|
|
83
|
+
const n = (bytes[index] ?? 0) << 16;
|
|
84
|
+
out += BASE64URL.charAt((n >> 18) & 63) + BASE64URL.charAt((n >> 12) & 63);
|
|
85
|
+
} else if (rest === 2) {
|
|
86
|
+
const n = ((bytes[index] ?? 0) << 16) | ((bytes[index + 1] ?? 0) << 8);
|
|
87
|
+
out +=
|
|
88
|
+
BASE64URL.charAt((n >> 18) & 63) +
|
|
89
|
+
BASE64URL.charAt((n >> 12) & 63) +
|
|
90
|
+
BASE64URL.charAt((n >> 6) & 63);
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Decodes base64url without padding. Only the canonical encoding is accepted
|
|
97
|
+
* (unused trailing bits must be zero), so one value has one spelling.
|
|
98
|
+
*/
|
|
99
|
+
export function base64urlDecode(text: string): Uint8Array {
|
|
100
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) {
|
|
101
|
+
throw new Error("Invalid base64url");
|
|
102
|
+
}
|
|
103
|
+
const out = new Uint8Array(Math.floor((text.length * 3) / 4));
|
|
104
|
+
let buffer = 0;
|
|
105
|
+
let bits = 0;
|
|
106
|
+
let offset = 0;
|
|
107
|
+
for (const char of text) {
|
|
108
|
+
buffer = (buffer << 6) | BASE64URL.indexOf(char);
|
|
109
|
+
bits += 6;
|
|
110
|
+
if (bits >= 8) {
|
|
111
|
+
bits -= 8;
|
|
112
|
+
out[offset++] = (buffer >> bits) & 0xff;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if ((buffer & ((1 << bits) - 1)) !== 0) {
|
|
116
|
+
throw new Error("Invalid base64url");
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function randomBytes(length: number): Uint8Array {
|
|
122
|
+
const out = new Uint8Array(length);
|
|
123
|
+
crypto.getRandomValues(out);
|
|
124
|
+
return out;
|
|
125
|
+
}
|
package/src/frames.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plaintext of each transport message: a 14-byte header, the payload,
|
|
3
|
+
* and zero padding up to a size bucket.
|
|
4
|
+
*
|
|
5
|
+
* offset size field
|
|
6
|
+
* 0 1 type 1 ACP, 2 CLOSE, 3 PING, 4 PONG, 5 CONFIRMED, 6 REMEMBER
|
|
7
|
+
* 1 4 stream u32 BE
|
|
8
|
+
* 5 4 seq u32 BE
|
|
9
|
+
* 9 1 flags bit0 FINAL
|
|
10
|
+
* 10 4 length u32 BE
|
|
11
|
+
* 14 n payload
|
|
12
|
+
* 14+n pad zero bytes up to the bucket
|
|
13
|
+
*
|
|
14
|
+
* One ACP message is one stream, cut into chunks if it does not fit in one
|
|
15
|
+
* frame. Control frames (CLOSE, PING, PONG, CONFIRMED, REMEMBER) are single frames
|
|
16
|
+
* with stream 0, seq 0 and FINAL set; ACP streams count from 1.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { concatBytes } from "./bytes.ts";
|
|
20
|
+
import { MAX_MESSAGE_LENGTH, TAGLEN } from "./noise.ts";
|
|
21
|
+
|
|
22
|
+
export const FrameType = {
|
|
23
|
+
ACP: 1,
|
|
24
|
+
CLOSE: 2,
|
|
25
|
+
PING: 3,
|
|
26
|
+
PONG: 4,
|
|
27
|
+
/** Agent side to browser: the user has confirmed the SAS words, or a reconnect is confirmed. */
|
|
28
|
+
CONFIRMED: 5,
|
|
29
|
+
/** Browser to agent side, once, right after pairing: its static key for reconnecting. */
|
|
30
|
+
REMEMBER: 6,
|
|
31
|
+
} as const;
|
|
32
|
+
export type FrameType = (typeof FrameType)[keyof typeof FrameType];
|
|
33
|
+
|
|
34
|
+
export const FLAG_FINAL = 0x01;
|
|
35
|
+
export const HEADER_LENGTH = 14;
|
|
36
|
+
/** The largest plaintext: one Noise message less its tag. */
|
|
37
|
+
export const MAX_PLAINTEXT_LENGTH = MAX_MESSAGE_LENGTH - TAGLEN;
|
|
38
|
+
/** The most payload one frame carries. */
|
|
39
|
+
export const MAX_CHUNK_PAYLOAD = MAX_PLAINTEXT_LENGTH - HEADER_LENGTH;
|
|
40
|
+
export const MIN_BUCKET = 256;
|
|
41
|
+
/** The largest ACP message a reassembler accepts by default: 32 MiB. */
|
|
42
|
+
export const DEFAULT_MAX_MESSAGE_BYTES = 32 * 1024 * 1024;
|
|
43
|
+
/** A 32-byte key in base64url without padding. */
|
|
44
|
+
export const REMEMBER_PAYLOAD_LENGTH = 43;
|
|
45
|
+
|
|
46
|
+
export interface Frame {
|
|
47
|
+
type: FrameType;
|
|
48
|
+
stream: number;
|
|
49
|
+
seq: number;
|
|
50
|
+
final: boolean;
|
|
51
|
+
payload: Uint8Array;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A broken rule of the framing. The session must end: there is no resync. */
|
|
55
|
+
export class FrameError extends Error {
|
|
56
|
+
constructor(message: string) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = "FrameError";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The padded size of a plaintext of `length` bytes: 256, else the next power
|
|
64
|
+
* of two, capped at {@link MAX_PLAINTEXT_LENGTH}.
|
|
65
|
+
*/
|
|
66
|
+
export function bucketLength(length: number): number {
|
|
67
|
+
if (length > MAX_PLAINTEXT_LENGTH) {
|
|
68
|
+
throw new FrameError("Frame too long");
|
|
69
|
+
}
|
|
70
|
+
let bucket = MIN_BUCKET;
|
|
71
|
+
while (bucket < length) {
|
|
72
|
+
bucket *= 2;
|
|
73
|
+
}
|
|
74
|
+
return Math.min(bucket, MAX_PLAINTEXT_LENGTH);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const KNOWN_TYPES = new Set<number>(Object.values(FrameType));
|
|
78
|
+
|
|
79
|
+
/** Encodes a frame as a padded plaintext. */
|
|
80
|
+
export function encodeFrame(frame: Frame): Uint8Array {
|
|
81
|
+
checkFrameShape(frame);
|
|
82
|
+
const out = new Uint8Array(
|
|
83
|
+
bucketLength(HEADER_LENGTH + frame.payload.length),
|
|
84
|
+
);
|
|
85
|
+
const view = new DataView(out.buffer);
|
|
86
|
+
view.setUint8(0, frame.type);
|
|
87
|
+
view.setUint32(1, frame.stream);
|
|
88
|
+
view.setUint32(5, frame.seq);
|
|
89
|
+
view.setUint8(9, frame.final ? FLAG_FINAL : 0);
|
|
90
|
+
view.setUint32(10, frame.payload.length);
|
|
91
|
+
out.set(frame.payload, HEADER_LENGTH);
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Decodes a padded plaintext. Anything off — an unknown type or flag, a
|
|
97
|
+
* length past the end, a size that is not the right bucket, non-zero
|
|
98
|
+
* padding — throws a {@link FrameError}.
|
|
99
|
+
*/
|
|
100
|
+
export function decodeFrame(plaintext: Uint8Array): Frame {
|
|
101
|
+
if (plaintext.length < HEADER_LENGTH) {
|
|
102
|
+
throw new FrameError("Frame shorter than its header");
|
|
103
|
+
}
|
|
104
|
+
const view = new DataView(
|
|
105
|
+
plaintext.buffer,
|
|
106
|
+
plaintext.byteOffset,
|
|
107
|
+
plaintext.byteLength,
|
|
108
|
+
);
|
|
109
|
+
const type = view.getUint8(0);
|
|
110
|
+
const stream = view.getUint32(1);
|
|
111
|
+
const seq = view.getUint32(5);
|
|
112
|
+
const flags = view.getUint8(9);
|
|
113
|
+
const length = view.getUint32(10);
|
|
114
|
+
if (!KNOWN_TYPES.has(type)) {
|
|
115
|
+
throw new FrameError(`Unknown frame type ${type}`);
|
|
116
|
+
}
|
|
117
|
+
if ((flags & ~FLAG_FINAL) !== 0) {
|
|
118
|
+
throw new FrameError("Unknown frame flags");
|
|
119
|
+
}
|
|
120
|
+
if (HEADER_LENGTH + length > plaintext.length) {
|
|
121
|
+
throw new FrameError("Frame length past the end");
|
|
122
|
+
}
|
|
123
|
+
if (plaintext.length !== bucketLength(HEADER_LENGTH + length)) {
|
|
124
|
+
throw new FrameError("Frame not padded to its bucket");
|
|
125
|
+
}
|
|
126
|
+
for (let index = HEADER_LENGTH + length; index < plaintext.length; index++) {
|
|
127
|
+
if (plaintext[index] !== 0) {
|
|
128
|
+
throw new FrameError("Non-zero padding");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const frame: Frame = {
|
|
132
|
+
type: type as FrameType,
|
|
133
|
+
stream,
|
|
134
|
+
seq,
|
|
135
|
+
final: (flags & FLAG_FINAL) !== 0,
|
|
136
|
+
payload: plaintext.slice(HEADER_LENGTH, HEADER_LENGTH + length),
|
|
137
|
+
};
|
|
138
|
+
checkFrameShape(frame);
|
|
139
|
+
return frame;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function checkFrameShape(frame: Frame): void {
|
|
143
|
+
if (!KNOWN_TYPES.has(frame.type)) {
|
|
144
|
+
throw new FrameError(`Unknown frame type ${frame.type}`);
|
|
145
|
+
}
|
|
146
|
+
if (frame.payload.length > MAX_CHUNK_PAYLOAD) {
|
|
147
|
+
throw new FrameError("Frame payload too long");
|
|
148
|
+
}
|
|
149
|
+
if (!isUint32(frame.stream) || !isUint32(frame.seq)) {
|
|
150
|
+
throw new FrameError("Stream and seq are 32-bit unsigned integers");
|
|
151
|
+
}
|
|
152
|
+
if (frame.type === FrameType.ACP) {
|
|
153
|
+
if (frame.stream === 0) {
|
|
154
|
+
throw new FrameError("ACP streams count from 1");
|
|
155
|
+
}
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (frame.stream !== 0 || frame.seq !== 0 || !frame.final) {
|
|
159
|
+
throw new FrameError("A control frame has stream 0, seq 0 and FINAL set");
|
|
160
|
+
}
|
|
161
|
+
if (
|
|
162
|
+
frame.type === FrameType.CONFIRMED &&
|
|
163
|
+
frame.payload.length !== 0 &&
|
|
164
|
+
frame.payload.length !== 4
|
|
165
|
+
) {
|
|
166
|
+
throw new FrameError("CONFIRMED is empty, or a u32 when resuming");
|
|
167
|
+
}
|
|
168
|
+
if (
|
|
169
|
+
frame.type === FrameType.REMEMBER &&
|
|
170
|
+
frame.payload.length !== REMEMBER_PAYLOAD_LENGTH
|
|
171
|
+
) {
|
|
172
|
+
throw new FrameError("REMEMBER carries a 32-byte key in base64url");
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function isUint32(value: number): boolean {
|
|
177
|
+
return Number.isInteger(value) && value >= 0 && value <= 0xffffffff;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** A control frame: stream 0, seq 0, FINAL. */
|
|
181
|
+
export function controlFrame(
|
|
182
|
+
type: Exclude<FrameType, typeof FrameType.ACP>,
|
|
183
|
+
payload: Uint8Array = new Uint8Array(0),
|
|
184
|
+
): Frame {
|
|
185
|
+
return { type, stream: 0, seq: 0, final: true, payload };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Cuts one ACP message into the frames of stream `stream`. An empty message
|
|
190
|
+
* is one empty FINAL frame.
|
|
191
|
+
*/
|
|
192
|
+
export function chunkMessage(
|
|
193
|
+
stream: number,
|
|
194
|
+
message: Uint8Array,
|
|
195
|
+
maxChunk = MAX_CHUNK_PAYLOAD,
|
|
196
|
+
): Frame[] {
|
|
197
|
+
if (maxChunk < 1 || maxChunk > MAX_CHUNK_PAYLOAD) {
|
|
198
|
+
throw new FrameError("Chunk size out of range");
|
|
199
|
+
}
|
|
200
|
+
const frames: Frame[] = [];
|
|
201
|
+
let offset = 0;
|
|
202
|
+
do {
|
|
203
|
+
const end = Math.min(offset + maxChunk, message.length);
|
|
204
|
+
frames.push({
|
|
205
|
+
type: FrameType.ACP,
|
|
206
|
+
stream,
|
|
207
|
+
seq: frames.length,
|
|
208
|
+
final: end === message.length,
|
|
209
|
+
payload: message.slice(offset, end),
|
|
210
|
+
});
|
|
211
|
+
offset = end;
|
|
212
|
+
} while (offset < message.length);
|
|
213
|
+
return frames;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Puts the ACP streams of one direction back together, enforcing the rules:
|
|
218
|
+
* stream ids go up by one from 1, seq goes up by one from 0, nothing is
|
|
219
|
+
* interleaved, and a message stays under a size cap. Any breach throws a
|
|
220
|
+
* {@link FrameError}.
|
|
221
|
+
*/
|
|
222
|
+
export class Reassembler {
|
|
223
|
+
private current:
|
|
224
|
+
| { stream: number; nextSeq: number; chunks: Uint8Array[]; size: number }
|
|
225
|
+
| undefined;
|
|
226
|
+
|
|
227
|
+
/** `lastStream` is the stream received before, when a connection resumes. */
|
|
228
|
+
constructor(
|
|
229
|
+
private readonly maxMessageBytes = DEFAULT_MAX_MESSAGE_BYTES,
|
|
230
|
+
private lastStream = 0,
|
|
231
|
+
) {}
|
|
232
|
+
|
|
233
|
+
/** Whether a stream has started and not yet ended. */
|
|
234
|
+
get inStream(): boolean {
|
|
235
|
+
return this.current !== undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Takes one ACP frame; returns the whole message once its FINAL chunk arrives. */
|
|
239
|
+
push(frame: Frame): Uint8Array | undefined {
|
|
240
|
+
if (frame.type !== FrameType.ACP) {
|
|
241
|
+
throw new FrameError("Only ACP frames are reassembled");
|
|
242
|
+
}
|
|
243
|
+
if (!this.current) {
|
|
244
|
+
if (frame.stream !== this.lastStream + 1) {
|
|
245
|
+
throw new FrameError(
|
|
246
|
+
`Expected stream ${this.lastStream + 1}, got ${frame.stream}`,
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
this.current = { stream: frame.stream, nextSeq: 0, chunks: [], size: 0 };
|
|
250
|
+
}
|
|
251
|
+
const current = this.current;
|
|
252
|
+
if (frame.stream !== current.stream) {
|
|
253
|
+
throw new FrameError("Streams interleaved");
|
|
254
|
+
}
|
|
255
|
+
if (frame.seq !== current.nextSeq) {
|
|
256
|
+
throw new FrameError(`Expected seq ${current.nextSeq}, got ${frame.seq}`);
|
|
257
|
+
}
|
|
258
|
+
current.size += frame.payload.length;
|
|
259
|
+
if (current.size > this.maxMessageBytes) {
|
|
260
|
+
throw new FrameError("Message too large");
|
|
261
|
+
}
|
|
262
|
+
current.chunks.push(frame.payload);
|
|
263
|
+
current.nextSeq++;
|
|
264
|
+
if (!frame.final) {
|
|
265
|
+
return undefined;
|
|
266
|
+
}
|
|
267
|
+
this.lastStream = current.stream;
|
|
268
|
+
this.current = undefined;
|
|
269
|
+
return concatBytes(...current.chunks);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Called on CLOSE: a stream still open then means the relay truncated it. */
|
|
273
|
+
end(): void {
|
|
274
|
+
if (this.current) {
|
|
275
|
+
throw new FrameError("Stream left without FINAL");
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The wire protocol between acpantenna and a web client over a relay:
|
|
3
|
+
* Noise NKpsk0, the frame codec, the pairing link, the SAS words, and a
|
|
4
|
+
* session object both ends use. Plain `Uint8Array`s and Web APIs only, so it
|
|
5
|
+
* runs in a browser as well as in Bun. The spec is `docs/relay-protocol.md`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export * from "./bytes.ts";
|
|
9
|
+
export * from "./frames.ts";
|
|
10
|
+
export * from "./link.ts";
|
|
11
|
+
export * from "./noise.ts";
|
|
12
|
+
export * from "./relay.ts";
|
|
13
|
+
export * from "./sas.ts";
|
|
14
|
+
export * from "./session.ts";
|
package/src/link.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pairing link: `<web origin>/#v1.<room>.<s_pub>.<psk>.<expiry>`.
|
|
3
|
+
*
|
|
4
|
+
* `room` (16 bytes), `s_pub` (32) and `psk` (32) are base64url without
|
|
5
|
+
* padding; `expiry` is unix seconds in decimal. Everything secret is in the
|
|
6
|
+
* fragment, which browsers never send to a server.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
base64urlDecode,
|
|
11
|
+
base64urlEncode,
|
|
12
|
+
concatBytes,
|
|
13
|
+
utf8Encode,
|
|
14
|
+
} from "./bytes.ts";
|
|
15
|
+
|
|
16
|
+
export const LINK_VERSION = "v1";
|
|
17
|
+
export const ROOM_LENGTH = 16;
|
|
18
|
+
export const KEY_LENGTH = 32;
|
|
19
|
+
/** How long a link is valid by default: 10 minutes. */
|
|
20
|
+
export const DEFAULT_LINK_TTL_SECONDS = 10 * 60;
|
|
21
|
+
/** The label at the start of the prologue. */
|
|
22
|
+
export const PROLOGUE_LABEL = "acpantenna-relay/1";
|
|
23
|
+
|
|
24
|
+
export interface PairingLink {
|
|
25
|
+
/** The web client's origin, e.g. `https://app.example`. */
|
|
26
|
+
webOrigin: string;
|
|
27
|
+
room: Uint8Array;
|
|
28
|
+
/** The agent side's static X25519 public key. */
|
|
29
|
+
staticPublicKey: Uint8Array;
|
|
30
|
+
psk: Uint8Array;
|
|
31
|
+
/** Unix seconds. */
|
|
32
|
+
expiry: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class LinkError extends Error {
|
|
36
|
+
constructor(message: string) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "LinkError";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Checks that `origin` is an origin and nothing more — a scheme, a host and
|
|
44
|
+
* maybe a port — and returns it in the form `URL.origin` gives.
|
|
45
|
+
*/
|
|
46
|
+
export function normalizeWebOrigin(origin: string): string {
|
|
47
|
+
let url: URL;
|
|
48
|
+
try {
|
|
49
|
+
url = new URL(origin);
|
|
50
|
+
} catch {
|
|
51
|
+
throw new LinkError(`Not a URL: ${origin}`);
|
|
52
|
+
}
|
|
53
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
54
|
+
throw new LinkError("The web origin is http or https");
|
|
55
|
+
}
|
|
56
|
+
if (
|
|
57
|
+
url.origin !== origin.replace(/\/$/, "") ||
|
|
58
|
+
url.username ||
|
|
59
|
+
url.password
|
|
60
|
+
) {
|
|
61
|
+
throw new LinkError(
|
|
62
|
+
`The web origin is a scheme and host only, like https://app.example: ${origin}`,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
return url.origin;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function encodeLink(link: PairingLink): string {
|
|
69
|
+
checkFields(link);
|
|
70
|
+
const fragment = [
|
|
71
|
+
LINK_VERSION,
|
|
72
|
+
base64urlEncode(link.room),
|
|
73
|
+
base64urlEncode(link.staticPublicKey),
|
|
74
|
+
base64urlEncode(link.psk),
|
|
75
|
+
String(link.expiry),
|
|
76
|
+
].join(".");
|
|
77
|
+
return `${normalizeWebOrigin(link.webOrigin)}/#${fragment}`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Parses a link. It does not check expiry: see {@link isLinkExpired}. */
|
|
81
|
+
export function parseLink(text: string): PairingLink {
|
|
82
|
+
const hashIndex = text.indexOf("#");
|
|
83
|
+
if (hashIndex < 0) {
|
|
84
|
+
throw new LinkError("The link has no fragment");
|
|
85
|
+
}
|
|
86
|
+
const base = text.slice(0, hashIndex).replace(/\/$/, "");
|
|
87
|
+
const webOrigin = normalizeWebOrigin(base);
|
|
88
|
+
const parts = text.slice(hashIndex + 1).split(".");
|
|
89
|
+
if (parts.length !== 5 || parts[0] !== LINK_VERSION) {
|
|
90
|
+
throw new LinkError("Not a v1 link");
|
|
91
|
+
}
|
|
92
|
+
const [, room, staticPublicKey, psk, expiry] = parts as [
|
|
93
|
+
string,
|
|
94
|
+
string,
|
|
95
|
+
string,
|
|
96
|
+
string,
|
|
97
|
+
string,
|
|
98
|
+
];
|
|
99
|
+
if (!/^[1-9][0-9]{0,15}$/.test(expiry)) {
|
|
100
|
+
throw new LinkError("Invalid expiry");
|
|
101
|
+
}
|
|
102
|
+
const link: PairingLink = {
|
|
103
|
+
webOrigin,
|
|
104
|
+
room: decodeField(room, "room"),
|
|
105
|
+
staticPublicKey: decodeField(staticPublicKey, "static key"),
|
|
106
|
+
psk: decodeField(psk, "psk"),
|
|
107
|
+
expiry: Number(expiry),
|
|
108
|
+
};
|
|
109
|
+
checkFields(link);
|
|
110
|
+
return link;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function isLinkExpired(link: PairingLink, nowMs = Date.now()): boolean {
|
|
114
|
+
return nowMs >= link.expiry * 1000;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The room id as it appears in the relay URL: base64url, 22 characters. */
|
|
118
|
+
export function roomId(room: Uint8Array): string {
|
|
119
|
+
return base64urlEncode(room);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The Noise prologue: `"acpantenna-relay/1" ‖ 0x00 ‖ room ‖ 0x00 ‖ web
|
|
124
|
+
* origin`, binding the handshake to this room and this web client.
|
|
125
|
+
*/
|
|
126
|
+
export function prologue(room: Uint8Array, webOrigin: string): Uint8Array {
|
|
127
|
+
if (room.length !== ROOM_LENGTH) {
|
|
128
|
+
throw new LinkError("A room is 16 bytes");
|
|
129
|
+
}
|
|
130
|
+
return concatBytes(
|
|
131
|
+
utf8Encode(PROLOGUE_LABEL),
|
|
132
|
+
Uint8Array.of(0),
|
|
133
|
+
room,
|
|
134
|
+
Uint8Array.of(0),
|
|
135
|
+
utf8Encode(normalizeWebOrigin(webOrigin)),
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function decodeField(text: string, name: string): Uint8Array {
|
|
140
|
+
try {
|
|
141
|
+
return base64urlDecode(text);
|
|
142
|
+
} catch {
|
|
143
|
+
throw new LinkError(`Invalid ${name}`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function checkFields(link: PairingLink): void {
|
|
148
|
+
if (link.room.length !== ROOM_LENGTH) {
|
|
149
|
+
throw new LinkError("A room is 16 bytes");
|
|
150
|
+
}
|
|
151
|
+
if (link.staticPublicKey.length !== KEY_LENGTH) {
|
|
152
|
+
throw new LinkError("A static key is 32 bytes");
|
|
153
|
+
}
|
|
154
|
+
if (link.psk.length !== KEY_LENGTH) {
|
|
155
|
+
throw new LinkError("A psk is 32 bytes");
|
|
156
|
+
}
|
|
157
|
+
if (!Number.isSafeInteger(link.expiry) || link.expiry <= 0) {
|
|
158
|
+
throw new LinkError("Invalid expiry");
|
|
159
|
+
}
|
|
160
|
+
}
|