function legacyPeer(comment: string): string { return comment.match(/(?:network|gateway)\s*=\s*([0-9.]+\/\d+)/)?.[1] ?? "" } /** Keep app-only peer information on RouterOS without changing routes. */ export function readGreComment(raw = ""): { comment: string; remoteInnerIp: string } { const match = raw.match(/(?:\n)?\[mmapp-gre-peer:v1:([A-Za-z0-9_-]+)\]$/) if (match) { try { const value: unknown = JSON.parse(Buffer.from(match[1], "base64url").toString("utf8")) if (value && typeof value === "object" && "remoteInnerIp" in value && typeof value.remoteInnerIp === "string") { return { comment: raw.slice(0, match.index), remoteInnerIp: value.remoteInnerIp } } } catch { /* Preserve unrecognized user comments verbatim. */ } } return { comment: raw, remoteInnerIp: legacyPeer(raw) } } export function writeGreComment(raw: string, remoteInnerIp: string): string { const { comment } = readGreComment(raw) const peer = remoteInnerIp.trim() if (!peer && !legacyPeer(comment)) return comment const payload = Buffer.from(JSON.stringify({ remoteInnerIp: peer }), "utf8").toString("base64url") return `${comment}${comment ? "\n" : ""}[mmapp-gre-peer:v1:${payload}]` }