-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpairing.ts
More file actions
More file actions
Latest commit
526 lines (484 loc) · 17.3 KB
/
Copy pathpairing.ts
File metadata and controls
526 lines (484 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
import { createHash, randomBytes, randomInt } from 'crypto';
import { EventEmitter } from 'events';
import sodium from 'libsodium-wrappers';
import WebSocket from 'ws';
import { fetchJsonWithTimeout, isRetryableHttpStatus } from './http';
import { parseJuneTokenResponse } from './protocol';
import {
JUNE_API_URL,
JUNE_APP_VERSION,
JUNE_CLIENT_ID,
JUNE_CLIENT_SECRET,
JUNE_PLATFORM_VERSION,
JUNE_USER_AGENT,
JUNE_WS_URL,
SRP_G,
SRP_N_HEX,
} from './settings';
const SRP_N = BigInt(`0x${SRP_N_HEX}`);
const ASSOCIATION_MAX_DELAY_MS = 30_000;
const PAIRING_SESSION_TIMEOUT_MS = 5 * 60_000;
export function calculateAssociationDelay(attempt: number, random = Math.random): number {
const exponential = Math.min(ASSOCIATION_MAX_DELAY_MS, 3_000 * 2 ** Math.max(0, attempt));
return Math.min(ASSOCIATION_MAX_DELAY_MS, Math.round(exponential * (0.75 + random() * 0.5)));
}
const PAD_LEN = (SRP_N.toString(2).length + 7) >> 3;
const DAMM = [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
];
export type PairingState = 'starting' | 'waiting-for-oven' | 'posting-companion' | 'waiting-for-associated' | 'paired' | 'failed';
export interface PairingStatus {
id: string;
state: PairingState;
shownCode?: string;
error?: string;
oven?: PairedOvenIdentity;
}
export interface PairedOvenIdentity {
name: string;
preheatSwitchName: string;
readySensor: boolean;
doneSensor: boolean;
defaultMode: string;
defaultTempF: number;
tempUnit: 'F' | 'C';
ovenId: string;
deviceId: string;
deviceName: string;
password: string;
ed25519SeedHex: string;
accessToken: string;
refreshToken: string;
clientId: string;
clientSecret: string;
}
export function damm(input: string): number {
let state = 0;
for (const char of input) {
state = DAMM[state][Number(char)];
}
return state;
}
export function buildShownCode(serverCode: string, twoDigits = randomInt(0, 100)): string {
const base = `${serverCode}${twoDigits.toString().padStart(2, '0')}`;
return `${base}${damm(base)}`;
}
export function modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {
let result = 1n;
let b = base % modulus;
let e = exponent;
while (e > 0n) {
if (e & 1n) {
result = (result * b) % modulus;
}
e >>= 1n;
b = (b * b) % modulus;
}
return result;
}
function sha1(...chunks: Buffer[]): Buffer {
const hash = createHash('sha1');
chunks.forEach(chunk => hash.update(chunk));
return hash.digest();
}
function pad(value: bigint): Buffer {
return bigintToBuffer(value, PAD_LEN);
}
function bigintToBuffer(value: bigint, minLength = 0): Buffer {
if (value === 0n) {
return Buffer.alloc(Math.max(1, minLength));
}
let hex = value.toString(16);
if (hex.length % 2) {
hex = `0${hex}`;
}
const raw = Buffer.from(hex, 'hex');
if (raw.length >= minLength) {
return raw;
}
return Buffer.concat([Buffer.alloc(minLength - raw.length), raw]);
}
export class SrpServer {
public readonly salt: Buffer;
public readonly B: bigint;
private readonly verifier: bigint;
private readonly multiplier: bigint;
private readonly secretB: bigint;
constructor(password: string, salt = randomBytes(16), secretB = BigInt(`0x${randomBytes(32).toString('hex')}`) % SRP_N) {
this.salt = salt;
const identityHash = sha1(Buffer.from(`user:${password}`, 'utf8'));
const x = BigInt(`0x${sha1(this.salt, identityHash).toString('hex')}`);
this.verifier = modPow(SRP_G, x, SRP_N);
this.multiplier = BigInt(`0x${sha1(pad(SRP_N), pad(SRP_G)).toString('hex')}`);
this.secretB = secretB;
this.B = (this.multiplier * this.verifier + modPow(SRP_G, this.secretB, SRP_N)) % SRP_N;
}
public secret(A: bigint): Buffer {
const u = BigInt(`0x${sha1(pad(A), pad(this.B)).toString('hex')}`);
const S = modPow((A * modPow(this.verifier, u, SRP_N)) % SRP_N, this.secretB, SRP_N);
return bigintToBuffer(S);
}
public saltBase64(): string {
const session = this.sessionFactory(id, deviceName);
this.sessions.set(id, session);
const statusListener = (status: PairingStatus) => {
if (this.sessions.get(id) !== session) {
return;
}
if (isTerminal(status.state)) {
this.scheduleEviction(id, session);
}
};
this.statusListeners.set(id, statusListener);
session.on('status', statusListener);
try {
const status = await session.begin();
if (isTerminal(status.state)) {
this.scheduleEviction(id, session);
}
return status;
} catch (error) {
this.remove(id, session);
throw error;
}
}
public status(id: string): PairingStatus {
const session = this.sessions.get(id);
if (!session) {
return { id, state: 'failed', error: 'Pairing session not found.' };
}
return session.currentStatus();
}
public cancel(id: string): void {
const session = this.sessions.get(id);
if (session) {
this.remove(id, session);
}
}
private scheduleEviction(id: string, session: JunePairingSession): void {
if (this.evictionTimers.has(id)) {
return;
}
const timer = setTimeout(() => this.remove(id, session), this.terminalTtlMs);
timer.unref?.();
this.evictionTimers.set(id, timer);
}
private remove(id: string, session: JunePairingSession): void {
const timer = this.evictionTimers.get(id);
if (timer) {
clearTimeout(timer);
this.evictionTimers.delete(id);
}
if (this.sessions.get(id) !== session) {
return;
}
const listener = this.statusListeners.get(id);
if (listener) {
session.removeListener('status', listener);
this.statusListeners.delete(id);
}
this.sessions.delete(id);
session.destroy();
}
}
function isTerminal(state: PairingState): boolean {
return state === 'paired' || state === 'failed';
}
function findLongBase64(input: string): string | undefined {
return input.match(/"([A-Za-z0-9+/=]{300,})"/)?.[1];
}