mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 13:34:09 +01:00
- invites: Einladungsmails nutzen ausschließlich die eingestellte Adresse des Spiels (kein Host-/Origin-Header); fehlt sie, wird der Versand mit klarer Meldung abgelehnt und im Admin-Bereich angezeigt. Anzeige-Link im eigenen Client nur aus Origin, wenn er erlaubt ist bzw. zum Host passt. - llmmodels/newsanalysis: Antworten des Sprachmodell-Servers begrenzt gelesen (1 MB), Zeitlimit gilt auch fürs Lesen. - merger: Bilanzhistorie des Käufers pro forma zusammengeführt (pf-Markierung) plus Stichtag „Fusion“; Anzeige „pro forma“. - game: eveImp und Market-Maker-Stand werden gespeichert (Abendkurs springt nach Neustart nicht zurück). - derivatives: laufende Schutzfristen gegen Selbst-Manipulation kompakt gespeichert. - Client: Scroll-Hinweis (Randverlauf) und gehaltene Scrollposition der Kennzahlen am Handy, Kopfbilder und Mehr-Kacheln nur drei Runden animiert, Admin-Tagesangaben und Börsentagebuch-Titel als Datum (Turbo: „Tag N“). - Tests: review-rest.test.js Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
403 lines
22 KiB
JavaScript
403 lines
22 KiB
JavaScript
// Freunde einladen: persönlicher Einladungscode je Spieler (Link /e/CODE, QR-Code), Einladung per E-Mail mit Grenzen,
|
||
// Admin-Codes für „Registrierung nur mit Einladung“, automatische Freundschaft und Belohnung beim ersten Handel.
|
||
//
|
||
// Datenschutz: Fremde E-Mail-Adressen werden nie im Klartext gespeichert – nur als HMAC-SHA256 mit einem Server-Geheimnis
|
||
// (für Wochensperre und Abmeldung) und als stark gekürzter Hinweis („a***@g***.de“) für die Liste des Einladenden.
|
||
// Ob eine Adresse schon registriert ist oder sich abgemeldet hat, verrät die Antwort nicht.
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import { createHmac, randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
|
||
import { settings } from './settings.js';
|
||
import { sendMailChecked, mailEnabled, explainMailError } from './mailer.js';
|
||
import { cleanText } from './util.js';
|
||
|
||
const DAY = 86_400_000;
|
||
const WEEK = 7 * DAY;
|
||
/** ohne verwechselbare Zeichen (0/O, 1/I/L) */
|
||
export const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
|
||
export const PLAYER_CODE_LEN = 8;
|
||
export const ADMIN_CODE_LEN = 10;
|
||
export const MESSAGE_MAX = 300;
|
||
export const XP_INVITER = 150;
|
||
export const XP_INVITEE = 75;
|
||
const NETWORKER = [[1, 'networker'], [3, 'networker_3'], [10, 'networker_10']];
|
||
const MAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
|
||
|
||
export function newCode(len = PLAYER_CODE_LEN) {
|
||
let s = '';
|
||
for (let i = 0; i < len; i++) s += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
|
||
return s;
|
||
}
|
||
/** Eingabe vereinheitlichen: Großbuchstaben, ohne Leer- und Bindestriche */
|
||
export const normCode = (s) => String(s ?? '').toUpperCase().replace(/[\s-]/g, '').slice(0, 40);
|
||
export const normMail = (s) => String(s ?? '').trim().toLowerCase();
|
||
|
||
/** „anna@gmail.com“ → „a***@g***.com“ – erkennbar für den Einladenden, aber kein Klartext */
|
||
export function maskMail(addr) {
|
||
const [local, domain = ''] = normMail(addr).split('@');
|
||
const dot = domain.lastIndexOf('.');
|
||
const host = dot > 0 ? domain.slice(0, dot) : domain;
|
||
const tld = dot > 0 ? domain.slice(dot) : '';
|
||
return `${local.slice(0, 1)}***@${host.slice(0, 1)}***${tld}`;
|
||
}
|
||
|
||
/** Geheimnis für HMAC: INVITE_SECRET oder DATA_DIR/invite.key (wird beim ersten Start erzeugt, nur für den Besitzer lesbar) */
|
||
export function loadSecret(dir) {
|
||
if (process.env.INVITE_SECRET && process.env.INVITE_SECRET.length >= 16) return Buffer.from(process.env.INVITE_SECRET);
|
||
const file = path.join(dir, 'invite.key');
|
||
try {
|
||
const s = fs.readFileSync(file, 'utf8').trim();
|
||
if (s.length >= 32) return Buffer.from(s, 'hex');
|
||
} catch { /* noch nicht vorhanden */ }
|
||
const key = randomBytes(32).toString('hex');
|
||
fs.mkdirSync(dir, { recursive: true });
|
||
fs.writeFileSync(file, `${key}\n`, { mode: 0o600 });
|
||
return Buffer.from(key, 'hex');
|
||
}
|
||
|
||
const SCHEMA = `
|
||
CREATE TABLE IF NOT EXISTS invites (id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, inviter TEXT NOT NULL,
|
||
channel TEXT NOT NULL, addr TEXT, hint TEXT, sent INTEGER NOT NULL DEFAULT 0, invitee TEXT, reg_ts INTEGER, active_ts INTEGER);
|
||
CREATE INDEX IF NOT EXISTS invites_inviter ON invites(inviter, ts);
|
||
CREATE INDEX IF NOT EXISTS invites_addr ON invites(addr, ts);
|
||
CREATE INDEX IF NOT EXISTS invites_invitee ON invites(invitee);
|
||
CREATE TABLE IF NOT EXISTS invite_optout (addr TEXT PRIMARY KEY, ts INTEGER NOT NULL);
|
||
CREATE TABLE IF NOT EXISTS invite_codes (code TEXT PRIMARY KEY, data TEXT NOT NULL);
|
||
`;
|
||
|
||
export class Invites {
|
||
/** @param {any} g Spiel */
|
||
constructor(g, { secret } = {}) {
|
||
this.g = g;
|
||
this.db = g.store.db;
|
||
this.db.exec(SCHEMA);
|
||
this.secret = secret ?? loadSecret(g.store.dir);
|
||
this.byCode = new Map(); // Spielercode → Spieler-ID
|
||
for (const p of g.players.values()) if (p.inviteCode) this.byCode.set(p.inviteCode, p.id);
|
||
this.q = {
|
||
insert: this.db.prepare('INSERT INTO invites (ts, inviter, channel, addr, hint, sent, invitee, reg_ts) VALUES (?,?,?,?,?,?,?,?)'),
|
||
del: this.db.prepare('DELETE FROM invites WHERE id = ?'),
|
||
setSent: this.db.prepare('UPDATE invites SET sent = 1 WHERE id = ?'),
|
||
countMailSince: this.db.prepare("SELECT COUNT(*) AS n FROM invites WHERE inviter = ? AND channel = 'mail' AND ts > ?"),
|
||
addrSince: this.db.prepare('SELECT inviter FROM invites WHERE addr = ? AND ts > ?'),
|
||
openMail: this.db.prepare("SELECT id FROM invites WHERE inviter = ? AND channel = 'mail' AND addr = ? AND invitee IS NULL ORDER BY id DESC LIMIT 1"),
|
||
linkInvitee: this.db.prepare('UPDATE invites SET invitee = ?, reg_ts = ? WHERE id = ?'),
|
||
active: this.db.prepare('UPDATE invites SET active_ts = ? WHERE invitee = ? AND active_ts IS NULL'),
|
||
mine: this.db.prepare('SELECT id, ts, channel, hint, invitee, reg_ts, active_ts FROM invites WHERE inviter = ? ORDER BY id DESC LIMIT ?'),
|
||
optout: this.db.prepare('INSERT OR IGNORE INTO invite_optout (addr, ts) VALUES (?, ?)'),
|
||
isOptout: this.db.prepare('SELECT 1 AS x FROM invite_optout WHERE addr = ?'),
|
||
codeGet: this.db.prepare('SELECT data FROM invite_codes WHERE code = ?'),
|
||
codeSet: this.db.prepare('INSERT OR REPLACE INTO invite_codes (code, data) VALUES (?, ?)'),
|
||
codes: this.db.prepare('SELECT data FROM invite_codes'),
|
||
};
|
||
}
|
||
|
||
get cfg() { return settings.game; }
|
||
|
||
// ================================================================ Codes
|
||
hash(addr) { return createHmac('sha256', this.secret).update(`mail|${normMail(addr)}`).digest('hex'); }
|
||
#sign(s) { return createHmac('sha256', this.secret).update(`optout|${s}`).digest('base64url').slice(0, 32); }
|
||
|
||
#taken(code) { return this.byCode.has(code) || !!this.q.codeGet.get(code); }
|
||
|
||
/** Stabiler persönlicher Code (wird beim ersten Bedarf vergeben) */
|
||
codeOf(p) {
|
||
if (!p.inviteCode) {
|
||
let c;
|
||
do c = newCode(PLAYER_CODE_LEN); while (this.#taken(c));
|
||
p.inviteCode = c;
|
||
this.byCode.set(c, p.id);
|
||
this.g.markDirty(p);
|
||
}
|
||
return p.inviteCode;
|
||
}
|
||
|
||
/** Basisadresse für Links in der eigenen Ansicht: Einstellung „Adresse des Spiels“, sonst der (geprüfte) Origin der Anfrage */
|
||
base(origin) { return String(settings.smtp.baseUrl || origin || '').replace(/\/+$/, ''); }
|
||
linkFor(p, origin) { return `${this.base(origin)}/e/${this.codeOf(p)}`; }
|
||
/**
|
||
* Basisadresse für Links in E-Mails: NUR die eingestellte Adresse des Spiels – nie der Host-/Origin-Header der Anfrage,
|
||
* sonst könnte ein manipulierter Host-Header fremde Links in echte Einladungsmails schleusen. Leer → null.
|
||
*/
|
||
mailBase() {
|
||
const b = String(settings.smtp.baseUrl ?? '').trim().replace(/\/+$/, '');
|
||
return /^https?:\/\/[^\s/]+/i.test(b) ? b : null;
|
||
}
|
||
|
||
/**
|
||
* Prüft einen eingegebenen Code. Liefert {ok, kind:'player'|'admin'|'setup', inviter?, entry?, code} oder {ok:false, error}.
|
||
* Der Einrichtungscode für das erste Admin-Konto gilt immer (auch bei „nur mit Einladung“).
|
||
*/
|
||
check(input) {
|
||
const raw = String(input ?? '').trim();
|
||
if (!raw) return { ok: false, empty: true, error: 'Kein Einladungscode angegeben' };
|
||
const setup = this.g.setupCode;
|
||
if (setup) {
|
||
const a = Buffer.from(raw), b = Buffer.from(setup);
|
||
if (a.length === b.length && timingSafeEqual(a, b)) return { ok: true, kind: 'setup', code: raw };
|
||
}
|
||
const code = normCode(raw);
|
||
const pid = this.byCode.get(code);
|
||
if (pid) {
|
||
const p = this.g.players.get(pid);
|
||
if (!p || p.banned || p.rival) return { ok: false, error: 'Diese Einladung ist nicht mehr gültig' };
|
||
if (!this.cfg.invitesEnabled) return { ok: false, error: 'Einladungen sind derzeit abgeschaltet' };
|
||
return { ok: true, kind: 'player', inviter: p, code };
|
||
}
|
||
const row = this.q.codeGet.get(code);
|
||
if (row) {
|
||
const e = JSON.parse(row.data);
|
||
if (e.revoked) return { ok: false, error: 'Dieser Einladungscode wurde widerrufen' };
|
||
if (e.uses >= e.max) return { ok: false, error: 'Dieser Einladungscode ist bereits aufgebraucht' };
|
||
return { ok: true, kind: 'admin', entry: e, code };
|
||
}
|
||
return { ok: false, error: 'Einladungscode unbekannt – bitte noch einmal prüfen' };
|
||
}
|
||
|
||
/** Öffentliche Prüfung für die Willkommenskarte (nur Name des Einladenden) */
|
||
publicCheck(input) {
|
||
const r = this.check(input);
|
||
const base = { inviteOnly: !!this.cfg.inviteOnly, registrationOpen: !!this.cfg.registrationOpen };
|
||
if (!r.ok) return { ...base, ok: false, error: r.error };
|
||
return { ...base, ok: true, kind: r.kind === 'player' ? 'player' : 'code', inviter: r.kind === 'player' ? r.inviter.name : null };
|
||
}
|
||
|
||
/** Vor dem Anlegen eines Kontos: Code auswerten; bei „nur mit Einladung“ ohne gültigen Code ablehnen */
|
||
beforeRegister(input) {
|
||
const r = this.check(input);
|
||
if (!r.ok && this.cfg.inviteOnly) {
|
||
throw new Error(r.empty ? 'Registrierung derzeit nur mit Einladung – bitte deinen Einladungscode eingeben'
|
||
: `${r.error}. Registrierung ist derzeit nur mit gültiger Einladung möglich`);
|
||
}
|
||
return r;
|
||
}
|
||
|
||
/** Nach dem Anlegen: Freundschaft, Benachrichtigungen, Codeverbrauch, Eintrag in „Meine Einladungen“ */
|
||
afterRegister(p, r) {
|
||
const g = this.g;
|
||
this.codeOf(p);
|
||
if (!r?.ok) return r?.empty ? null : { ok: false, error: `${r.error} – du bist trotzdem registriert.` };
|
||
if (r.kind === 'setup') { g.claimAdmin(p, r.code); return { ok: true, kind: 'setup', admin: true }; }
|
||
if (r.kind === 'admin') {
|
||
const e = JSON.parse(this.q.codeGet.get(r.code).data);
|
||
e.uses += 1;
|
||
e.players = [...(e.players ?? []), p.id].slice(-200);
|
||
this.q.codeSet.run(e.code, JSON.stringify(e));
|
||
p.invitedBy = `code:${e.code}`;
|
||
this.q.insert.run(Date.now(), `code:${e.code}`, 'code', null, null, 0, p.id, Date.now());
|
||
g.store.audit(p.name, 'inviteCode', { code: e.code, uses: e.uses, max: e.max });
|
||
g.markDirty(p);
|
||
return { ok: true, kind: 'code' };
|
||
}
|
||
const inv = r.inviter;
|
||
p.invitedBy = inv.id;
|
||
// gleiche IP bei Registrierung und Einladendem → Freundschaft ja, Belohnung nein
|
||
p.inviteSameIp = !!p.ips?.[0] && (inv.ips ?? []).includes(p.ips[0]);
|
||
// kam eine Einladungsmail an genau diese Adresse? Dann wird dieser Eintrag fortgeschrieben
|
||
const mail = p.email ? this.q.openMail.get(inv.id, this.hash(p.email)) : null;
|
||
if (mail) this.q.linkInvitee.run(p.id, Date.now(), mail.id);
|
||
else this.q.insert.run(Date.now(), inv.id, 'link', null, null, 0, p.id, Date.now());
|
||
// automatisch befreundet (beide folgen einander)
|
||
for (const [a, b] of [[p, inv], [inv, p]]) {
|
||
a.follows ??= [];
|
||
if (!a.follows.includes(b.id)) { a.follows.push(b.id); if (a.follows.length > 100) a.follows.shift(); }
|
||
g.markDirty(a);
|
||
}
|
||
g.social.notify(inv.id, { kind: 'social', title: `${p.name} ist deiner Einladung gefolgt`, text: 'Ihr seid jetzt befreundet. Sobald der erste Handel klappt, bekommt ihr beide XP.', action: { profile: p.name } });
|
||
g.social.notify(p.id, { kind: 'social', title: `Fordere ${inv.name} zu einem ersten Battle heraus`, text: `${inv.name} hat dich eingeladen – ihr seid jetzt befreundet.`, action: { challenge: inv.name } });
|
||
g.log('player', `${p.name} wurde von ${inv.name} eingeladen`);
|
||
return { ok: true, kind: 'player', inviter: inv.name };
|
||
}
|
||
|
||
// ================================================================ Belohnung
|
||
/** Erster Handel eines eingeladenen Spielers (aus der Börse); Belohnung nur einmal je neuem Konto */
|
||
onTrade(p) {
|
||
if (!p?.invitedBy || p.inviteActiveAt) return;
|
||
const g = this.g;
|
||
p.inviteActiveAt = Date.now();
|
||
this.q.active.run(p.inviteActiveAt, p.id);
|
||
g.markDirty(p);
|
||
const inv = g.players.get(p.invitedBy);
|
||
if (!inv || p.inviteRewarded) return;
|
||
if (p.inviteSameIp || g.sharedIp(p.id, inv.id) || p.banned || inv.banned) {
|
||
p.inviteRewarded = 'gesperrt';
|
||
g.store.audit('Einladungen', 'inviteNoReward', { player: p.name, inviter: inv.name, reason: p.banned || inv.banned ? 'gesperrt' : 'gleiche IP' });
|
||
g.social.notify(inv.id, { kind: 'social', title: `${p.name} hat zum ersten Mal gehandelt`, text: 'Für Einladungen vom selben Anschluss gibt es keine XP – die Freundschaft bleibt.' });
|
||
return;
|
||
}
|
||
p.inviteRewarded = true;
|
||
inv.recruits = (inv.recruits ?? 0) + 1;
|
||
g.prog.addXp(p, XP_INVITEE);
|
||
g.prog.addXp(inv, XP_INVITER);
|
||
g.markDirty(inv);
|
||
g.social.notify(inv.id, { kind: 'social', title: `${p.name} handelt jetzt mit – +${XP_INVITER} XP`, text: 'Danke fürs Einladen! Dein Netzwerk wächst.', action: { profile: p.name } });
|
||
g.social.notify(p.id, { kind: 'social', title: `Erster Handel – +${XP_INVITEE} XP`, text: `Bonus für den Einstieg über die Einladung von ${inv.name}.` });
|
||
for (const [n, id] of NETWORKER) if (inv.recruits >= n) g.unlock(inv, id);
|
||
}
|
||
|
||
// ================================================================ Ansicht für den Spieler
|
||
#status(r) { return r.active_ts ? 'aktiv' : r.invitee ? 'registriert' : 'verschickt'; }
|
||
|
||
mine(p, origin) {
|
||
const rows = this.q.mine.all(p.id, 200);
|
||
const list = rows.map((r) => ({
|
||
id: r.id, ts: r.ts, channel: r.channel, hint: r.hint ?? null, status: this.#status(r),
|
||
name: r.invitee ? this.g.players.get(r.invitee)?.name ?? null : null, regTs: r.reg_ts ?? null, activeTs: r.active_ts ?? null,
|
||
}));
|
||
const used = this.q.countMailSince.get(p.id, Date.now() - DAY).n;
|
||
const limit = this.cfg.inviteDailyLimit;
|
||
return {
|
||
enabled: !!this.cfg.invitesEnabled, code: this.codeOf(p), link: this.linkFor(p, origin),
|
||
mail: { enabled: !!this.cfg.invitesEnabled && mailEnabled() && !!this.mailBase() && limit > 0, limit, left: Math.max(0, limit - used) },
|
||
counts: {
|
||
sent: list.filter((x) => x.channel === 'mail').length,
|
||
registered: list.filter((x) => x.status !== 'verschickt').length,
|
||
active: list.filter((x) => x.status === 'aktiv').length,
|
||
},
|
||
xp: { inviter: XP_INVITER, invitee: XP_INVITEE },
|
||
list,
|
||
};
|
||
}
|
||
|
||
// ================================================================ Einladung per E-Mail
|
||
optoutToken(h) { return `${h}.${this.#sign(h)}`; }
|
||
verifyOptout(t) {
|
||
const [h, sig] = String(t ?? '').split('.');
|
||
if (!/^[0-9a-f]{64}$/.test(h ?? '') || !sig) return null;
|
||
const a = Buffer.from(sig), b = Buffer.from(this.#sign(h));
|
||
return a.length === b.length && timingSafeEqual(a, b) ? h : null;
|
||
}
|
||
optout(t) {
|
||
const h = this.verifyOptout(t);
|
||
if (!h) return false;
|
||
this.q.optout.run(h, Date.now());
|
||
return true;
|
||
}
|
||
isOptedOut(h) { return !!this.q.isOptout.get(h); }
|
||
|
||
/** Ist die Adresse (als Hash) schon einem Spielerkonto zugeordnet? */
|
||
#registered(h) {
|
||
for (const q of this.g.players.values()) if (q.email && this.hash(q.email) === h) return true;
|
||
return false;
|
||
}
|
||
|
||
/** Inhalt der Einladungsmail (auch für Vorschau und Tests) */
|
||
mailContent(p, { link, message, optoutUrl }) {
|
||
const code = this.codeOf(p);
|
||
return {
|
||
kicker: 'Einladung', title: `${p.name} lädt dich zu WiBoSim ein`,
|
||
preheader: 'Börsenspiel mit Spielgeld: fiktive Börse, Politik und Battles unter Freunden.',
|
||
greeting: 'Hallo,',
|
||
blocks: [
|
||
{ type: 'text', text: `${p.name} spielt WiBoSim und möchte dich dabeihaben.` },
|
||
message ? { type: 'note', title: `Persönliche Nachricht von ${p.name}`, text: `„${message}“` } : null,
|
||
{ type: 'list', title: 'Was ist WiBoSim?', items: [
|
||
{ icon: '●', dot: '#6ea8ff', text: `Eine fiktive Börse mit erfundenen Unternehmen – du handelst mit Spielgeld (${this.cfg.startCash.toLocaleString('de-DE')} € Startkapital), echtes Geld ist nie im Spiel.` },
|
||
{ icon: '●', dot: '#d6ad4c', text: 'Politik: Ein Parlament stimmt über Gesetze ab, die die Kurse bewegen – und du stimmst mit.' },
|
||
{ icon: '●', dot: '#ff5d5d', text: 'Battles: Fordere Freunde zum Depot-Duell heraus und steig in den Ligen auf.' },
|
||
] },
|
||
{ type: 'text', text: `Dein Einladungscode: ${code} – er ist im Link schon eingetragen. Ihr seid nach der Registrierung automatisch befreundet.` },
|
||
],
|
||
cta: { label: 'Jetzt mitspielen', url: link },
|
||
footer: 'Du bekommst diese Mail, weil dich jemand aus dem Spiel eingeladen hat. Deine Adresse wird dabei nicht im Klartext gespeichert.',
|
||
footerLink: optoutUrl ? { label: 'Keine Einladungen mehr an diese Adresse', url: optoutUrl } : undefined,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Einladung per E-Mail. Antwortet für bereits registrierte, abgemeldete oder diese Woche schon (von anderen)
|
||
* eingeladene Adressen genauso wie bei einem echten Versand – so lassen sich keine Adressen ausspähen.
|
||
*/
|
||
async sendInvite(p, { to, message } = {}, origin = '') {
|
||
if (!this.cfg.invitesEnabled) throw new Error('Einladungen sind derzeit abgeschaltet');
|
||
if (!mailEnabled()) throw new Error('Mailversand ist auf diesem Server nicht eingerichtet – teile stattdessen deinen Link oder QR-Code');
|
||
if (!this.mailBase()) {
|
||
console.warn('[invite] Einladungsmail abgelehnt: „Adresse des Spiels (für Links)“ in den E-Mail-Einstellungen ist leer');
|
||
throw new Error('Einladungsmails sind gerade nicht möglich (die Spielleitung muss die Adresse des Spiels eintragen) – teile stattdessen deinen Link oder QR-Code');
|
||
}
|
||
if (p.rival) throw new Error('Nicht möglich');
|
||
if (p.mutedUntil && p.mutedUntil > Date.now()) throw new Error('Während einer Stummschaltung kannst du keine Einladungen verschicken');
|
||
const addr = normMail(to);
|
||
if (!MAIL_RE.test(addr) || addr.length > 200) throw new Error('Ungültige E-Mail-Adresse');
|
||
const raw = String(message ?? '');
|
||
if (raw.length > MESSAGE_MAX) throw new Error(`Persönliche Nachricht: höchstens ${MESSAGE_MAX} Zeichen`);
|
||
const msg = cleanText(raw.replace(/\s+/g, ' '), MESSAGE_MAX);
|
||
const limit = this.cfg.inviteDailyLimit;
|
||
const now = Date.now();
|
||
if (this.q.countMailSince.get(p.id, now - DAY).n >= limit) throw new Error(`Tageslimit erreicht – höchstens ${limit} Einladungsmails je Tag`);
|
||
const h = this.hash(addr);
|
||
if (p.email && this.hash(p.email) === h) throw new Error('Das ist deine eigene Adresse');
|
||
const recent = this.q.addrSince.all(h, now - WEEK);
|
||
if (recent.some((r) => r.inviter === p.id)) throw new Error('Diese Adresse hast du in den letzten 7 Tagen schon eingeladen');
|
||
const suppressed = recent.length > 0 || this.isOptedOut(h) || this.#registered(h);
|
||
// erst eintragen (zählt fürs Limit, auch bei parallelen Anfragen), bei Versandfehler wieder löschen
|
||
const id = Number(this.q.insert.run(now, p.id, 'mail', h, maskMail(addr), 0, null, null).lastInsertRowid);
|
||
if (suppressed) {
|
||
await new Promise((r) => setTimeout(r, 150 + randomInt(450))); // ähnliche Antwortzeit wie ein echter Versand
|
||
} else {
|
||
const base = this.mailBase();
|
||
const optoutUrl = `${base}/einladung/abmelden?t=${this.optoutToken(h)}`;
|
||
const content = this.mailContent(p, { link: `${base}/e/${this.codeOf(p)}`, message: msg, optoutUrl });
|
||
try {
|
||
await sendMailChecked(addr, `${p.name} lädt dich zu WiBoSim ein`, '', {
|
||
mail: content, headers: { 'List-Unsubscribe': `<${optoutUrl}>`, 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click' },
|
||
});
|
||
this.q.setSent.run(id);
|
||
} catch (e) {
|
||
this.q.del.run(id);
|
||
const x = explainMailError(e);
|
||
console.warn(`[invite] Einladungsmail von ${p.name} fehlgeschlagen: ${x.hint}`);
|
||
throw new Error(`Einladung nicht verschickt: ${x.hint}`);
|
||
}
|
||
}
|
||
this.g.store.audit(p.name, 'inviteMail', { hint: maskMail(addr) });
|
||
return { ok: true, text: `Einladung an ${maskMail(addr)} verschickt.`, invites: this.mine(p, origin) };
|
||
}
|
||
|
||
// ================================================================ Admin
|
||
codes() {
|
||
return this.q.codes.all().map((r) => JSON.parse(r.data)).sort((a, b) => b.created - a.created).map((e) => ({
|
||
...e, players: (e.players ?? []).map((id) => this.g.players.get(id)?.name).filter(Boolean),
|
||
state: e.revoked ? 'widerrufen' : e.uses >= e.max ? 'aufgebraucht' : 'aktiv',
|
||
}));
|
||
}
|
||
|
||
createCode(actor, { uses = 1, note = '' } = {}) {
|
||
const max = Math.round(Number(uses));
|
||
if (!Number.isFinite(max) || max < 1 || max > 1000) throw new Error('Anzahl: 1 bis 1000 Registrierungen');
|
||
let code;
|
||
do code = newCode(ADMIN_CODE_LEN); while (this.#taken(code));
|
||
const e = { code, max, uses: 0, note: cleanText(note, 80), created: Date.now(), by: actor.name, revoked: false, players: [] };
|
||
this.q.codeSet.run(code, JSON.stringify(e));
|
||
this.g.store.audit(actor.name, 'inviteCodeCreate', { code, max });
|
||
return e;
|
||
}
|
||
|
||
revokeCode(actor, code) {
|
||
const row = this.q.codeGet.get(normCode(code));
|
||
if (!row) throw new Error('Code nicht gefunden');
|
||
const e = JSON.parse(row.data);
|
||
e.revoked = true;
|
||
this.q.codeSet.run(e.code, JSON.stringify(e));
|
||
this.g.store.audit(actor.name, 'inviteCodeRevoke', { code: e.code });
|
||
return e;
|
||
}
|
||
|
||
stats() {
|
||
const one = (sql) => this.db.prepare(sql).get().n;
|
||
const players = [...this.g.players.values()].filter((p) => !p.rival);
|
||
return {
|
||
mails: one("SELECT COUNT(*) AS n FROM invites WHERE channel = 'mail' AND sent = 1"),
|
||
mailRequests: one("SELECT COUNT(*) AS n FROM invites WHERE channel = 'mail'"),
|
||
registered: players.filter((p) => p.invitedBy).length,
|
||
viaPlayers: players.filter((p) => p.invitedBy && !String(p.invitedBy).startsWith('code:')).length,
|
||
viaCodes: players.filter((p) => String(p.invitedBy ?? '').startsWith('code:')).length,
|
||
active: players.filter((p) => p.invitedBy && p.inviteActiveAt).length,
|
||
rewarded: players.filter((p) => p.inviteRewarded === true).length,
|
||
optouts: one('SELECT COUNT(*) AS n FROM invite_optout'),
|
||
enabled: !!this.cfg.invitesEnabled, inviteOnly: !!this.cfg.inviteOnly, dailyLimit: this.cfg.inviteDailyLimit,
|
||
mailLinkMissing: !!this.cfg.invitesEnabled && mailEnabled() && !this.mailBase(),
|
||
};
|
||
}
|
||
}
|