AtlatestRepositorysigil-nat
1
// One owned UDP mapping. Every state transition can be durably journaled before2
// the next request; a lost creation/renewal reply blocks fallback until deletion.3
import { randomBytes } from 'node:crypto';4
import { pcpMap, decodePcp, natPmpMap, decodeNatPmp } from './codecs.mjs';5
import { udpQuery } from './discovery.mjs';7
export class MappingRejected extends Error {}8
export class MappingUncertain extends Error {}10
export function udpMappingCandidates(route, discovery, internalPort, query = udpQuery) {11
const candidates = [];12
if (discovery.pcp?.result === 0) {13
const fields = { clientAddress: route.localAddress, nonce: randomBytes(12), protocol: 17, internalPort };14
candidates.push({15
protocol: 'pcp', identity: { ...fields, nonce: fields.nonce.toString('hex') },16
async exchange(lifetime, previous) {17
const response = await query({ ...route, request: pcpMap({ ...fields, lifetime,18
externalPort: previous?.externalPort ?? 0, externalAddress: previous?.externalAddress ?? '0.0.0.0' }),19
decode: bytes => decodePcp(bytes, 1, fields), delays: [3000, 6000] });20
if (response.result !== 0) throw new MappingRejected(`PCP result ${response.result}`);21
return response;22
},23
});24
}25
if (discovery.natPmp?.result === 0) {26
candidates.push({27
protocol: 'nat-pmp', identity: { protocol: 17, internalPort, clientAddress: route.localAddress },28
async exchange(lifetime, previous) {29
const response = await query({ ...route, request: natPmpMap({ protocol: 17, internalPort, lifetime,30
externalPort: lifetime === 0 ? 0 : previous?.externalPort ?? 0 }),31
decode: bytes => decodeNatPmp(bytes, 1, internalPort), delays: [250, 500, 1000] });32
if (response.result !== 0) throw new MappingRejected(`NAT-PMP result ${response.result}`);33
return { ...response, externalAddress: discovery.natPmp.externalAddress };34
},35
});36
}37
return candidates;38
}40
export class SingleUdpLease {41
constructor({ candidates, deadline, leaseSeconds = 120, journal = () => {}, now = Date.now,42
schedule = setTimeout, cancel = clearTimeout }) {43
if (!Array.isArray(candidates) || candidates.length > 4 ||44
!Number.isInteger(leaseSeconds) || leaseSeconds < 1 || leaseSeconds > 1800 ||45
!Number.isFinite(deadline) || deadline <= now() || deadline - now() > 1800000)46
throw new Error('One UDP lease requires a future deadline and a 1..1800 second cap');47
this.candidates = candidates;48
this.deadline = deadline;49
this.leaseSeconds = leaseSeconds;50
this.journal = journal;51
this.now = now;52
this.schedule = schedule;53
this.cancel = cancel;54
this.state = { phase: 'idle' };55
this.tail = Promise.resolve();56
this.stopping = false;57
}58
serial(action) {59
const result = this.tail.then(action);60
this.tail = result.catch(() => {});61
return result;62
}63
async record(phase, extra = {}) {64
this.state = { ...this.state, ...extra, phase, at: new Date(this.now()).toISOString() };65
await this.journal(structuredClone(this.state));66
}67
requestedLifetime() {68
const seconds = Math.min(this.leaseSeconds, Math.floor((this.deadline - this.now()) / 1000));69
if (seconds < 1 || this.stopping) throw new Error('Mapping run deadline reached or stopping');70
return seconds;71
}72
async accept(response, requestedLifetime) {73
// A success reply may describe an unacceptable lease. Preserve that state74
// for deletion rather than treating it as a clean rejection/fallback.75
await this.record('uncertain', { mapping: response });76
if (!Number.isInteger(response.lifetime) || response.lifetime < 1 || response.lifetime > requestedLifetime ||77
response.lifetime * 1000 > this.deadline - this.now() ||78
!Number.isInteger(response.externalPort) || response.externalPort < 1 || response.externalPort > 65535 ||79
typeof response.externalAddress !== 'string')80
throw new MappingUncertain('Router granted an invalid or over-cap mapping');81
await this.record('active', { expiresAt: this.now() + response.lifetime * 1000 });82
return structuredClone(this.state);83
}84
async removeOwned() {85
if (!this.current) return;86
// A full disk must not prevent the network cleanup of an owned mapping.87
try { await this.record('deleting'); }88
catch { /* State was retained in memory; still attempt deletion. */ }89
try {90
const response = await this.current.exchange(0, this.state.mapping);91
if (response.lifetime !== 0) throw new Error('Deletion did not acknowledge zero lifetime');92
await this.record('deleted', { deletion: response });93
} catch (error) {94
await this.record('uncertain', { error: `Deletion unconfirmed: ${error.message}` });95
throw new MappingUncertain(this.state.error);96
}97
}98
create() {99
return this.serial(async () => {100
if (this.state.phase !== 'idle') throw new Error('This lease already attempted creation');101
for (const candidate of this.candidates) {102
const lifetime = this.requestedLifetime();103
this.current = candidate;104
await this.record('creating', { protocol: candidate.protocol, identity: candidate.identity, mapping: null });105
let response;106
try {107
response = await candidate.exchange(lifetime);108
} catch (error) {109
if (error instanceof MappingRejected) {110
await this.record('rejected', { error: error.message });111
continue;112
}113
await this.record('uncertain', { error: `Creation unconfirmed: ${error.message}` });114
await this.removeOwned();115
// Only an acknowledged delete permits the next protocol.116
continue;117
}118
try {119
const active = await this.accept(response, lifetime);120
if (this.stopping) {121
await this.removeOwned();122
throw new Error('Lease stopped during creation');123
}124
return active;125
} catch (error) {126
if (this.state.phase !== 'deleted') await this.removeOwned();127
throw error;128
}129
}130
this.current = undefined;131
await this.record('unavailable');132
throw new Error('No responding mapping protocol succeeded');133
});134
}135
renew() {136
return this.serial(async () => {137
if (this.state.phase !== 'active') throw new Error('Only an active owned lease can renew');138
try {139
const lifetime = this.requestedLifetime();140
await this.record('renewing');141
return await this.accept(await this.current.exchange(lifetime, this.state.mapping), lifetime);142
} catch (error) {143
await this.record('uncertain', { error: `Renewal failed: ${error.message}` });144
await this.removeOwned();145
throw error;146
}147
});148
}149
maintain(onError = () => {}) {150
if (this.state.phase !== 'active' || this.maintaining || this.stopping)151
throw new Error('Maintain requires an active, running lease');152
this.maintaining = true;153
const failed = error => { try { onError(error); } catch { /* Cleanup is already attempted. */ } };154
this.deadlineTimer = this.schedule(() => { void this.close().catch(failed); },155
Math.max(0, this.deadline - this.now()));156
const next = () => {157
if (this.stopping || this.state.phase !== 'active') return;158
const delay = Math.max(1, Math.floor(this.state.mapping.lifetime * 500));159
if (this.now() + delay >= this.deadline) return;160
this.renewTimer = this.schedule(() => {161
void this.renew().then(next, async error => {162
try { await this.close(); } catch (closeError) { failed(closeError); }163
failed(error);164
});165
}, delay);166
};167
next();168
}169
close() {170
this.stopping = true;171
this.cancel(this.renewTimer);172
this.cancel(this.deadlineTimer);173
return this.serial(async () => {174
if (this.current && ['creating', 'active', 'renewing', 'uncertain', 'deleting'].includes(this.state.phase))175
await this.removeOwned();176
return structuredClone(this.state);177
});178
}179
}